你是否还记得前端初学时做过的H5小游戏,2048当之无愧是初学时遇到的最大困难,现在有ai辅助,你还能不能轻松实现并理解其中的原理。
下面就让Trae帮我们实现这一款经典的游戏吧,看看ai能不能无bug的实现~

首先先来看看实现的效果,可以通过键盘上的上下左右方向键来操控游戏,这也是初学时的js基础

实现的界面非常的好看,上面还有提示词,提示我们应该怎么玩这个经典的2048游戏、
可以看到页面的样式有间隙,让Trae自己把bug修复吧

引入眼帘,是非常经典的class类,

下面让Trae帮我们将各大方法的逻辑理清楚
1、初始化方法,是初始化游戏,包括初始化棋盘、分数、历史记录、以及绑定事件
js
init() {
this.board = Array(this.size).fill().map(() => Array(this.size).fill(0));
this.score = 0;
this.history = [];
this.addRandomTile();
this.addRandomTile();
this.updateDisplay();
}
2、然后是随机数,在棋盘上随机添加一个数字,数字为2或4,概率为9:1
ini
addRandomTile() {
const emptyCells = [];
for (let i = 0; i < this.size; i++) {
for (let j = 0; j < this.size; j++) {
if (this.board[i][j] === 0) {
emptyCells.push({ x: i, y: j });
}
}
}
if (emptyCells.length > 0) {
const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
this.board[randomCell.x][randomCell.y] = Math.random() < 0.9 ? 2 : 4;
}
}
3、再然后是保存当前游戏状态,包括棋盘和分数,最多保存10个历史记录
kotlin
saveState() {
this.history.push({
board: this.board.map(row => [...row]),
score: this.score
});
if (this.history.length > 10) {
this.history.shift();
}
}
4、更新显示的方法,包括更新棋盘和追加分数
javascript
updateDisplay() {
this.updateBoardDisplay();
this.updateScoreDisplay();
}
5、撤销按钮的逻辑,撤销上一步操作,包括恢复棋盘和减掉刚刚上一步加上的分数
kotlin
undo() {
if (this.history.length > 0) {
const lastState = this.history.pop();
this.board = lastState.board;
this.score = lastState.score;
this.updateDisplay();
}
}
6、移动棋子,遇到方向一致并且数字一致,就会合并相同数字的棋子,例如2和2,就会变成4,以此类推
如果数字到达2048,即为游戏胜利,这个时候就要提醒用户游戏胜利,如果所有的格子都满了,并且没有办法合并就要提示用户游戏失败,结束游戏,可以重新开始一局新的游戏
kotlin
move(direction) {
this.saveState();
const originalBoard = this.board.map(row => [...row]);
let moved = false;
switch (direction) {
case 'up':
moved = this.moveUp();
break;
case 'down':
moved = this.moveDown();
break;
case 'left':
moved = this.moveLeft();
break;
case 'right':
moved = this.moveRight();
break;
}
if (moved) {
this.addRandomTile();
this.updateDisplay();
if (this.checkWin()) {
this.showMessage('🎉 恭喜你达到2048,游戏胜利,太厉害了!');
} else if (this.checkGameOver()) {
this.showMessage('😅 游戏结束!');
}
} else {
this.history.pop();
}
}
7、压缩行,合并相同数字的棋子,使其空白格子
js
compress(row) {
let filtered = row.filter(val => val !== 0);
let compressed = [];
let scoreAdded = 0;
for (let i = 0; i < filtered.length; i++) {
if (i < filtered.length - 1 && filtered[i] === filtered[i + 1]) {
const merged = filtered[i] * 2;
compressed.push(merged);
this.score += merged;
i++;
} else {
compressed.push(filtered[i]);
}
}
while (compressed.length < this.size) {
compressed.push(0);
}
return compressed;
}
8、检查是否胜利的逻辑,胜利条件为棋盘上存在2048,有这个数字就是游戏胜利
js
checkWin() {
for (let i = 0; i < this.size; i++) {
for (let j = 0; j < this.size; j++) {
if (this.board[i][j] === 2048) {
return true;
}
}
}
return false;
}
总结:
ai编程很强大,要适当利用,但是不能完全依赖,可以借助一下ai的能力将我们的逻辑理清晰,帮助我们更好的成长