vue实现2048
Vue 实现 2048 游戏
2048 是一款数字合并益智游戏,目标是通过滑动合并相同数字的方块,最终得到 2048。使用 Vue 实现可以充分利用其响应式特性和组件化优势。
初始化项目
使用 Vue CLI 创建项目:
vue create vue-2048
安装依赖后,在 src/components 下创建 Game2048.vue 文件。
核心逻辑实现
游戏逻辑包括初始化棋盘、随机生成数字、滑动合并和判断游戏状态。
// Game2048.vue
export default {
data() {
return {
grid: Array(4).fill().map(() => Array(4).fill(0)),
score: 0,
gameOver: false
}
},
methods: {
initGame() {
this.grid = Array(4).fill().map(() => Array(4).fill(0));
this.score = 0;
this.gameOver = false;
this.addRandomTile();
this.addRandomTile();
},
addRandomTile() {
const emptyCells = [];
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (this.grid[i][j] === 0) emptyCells.push({i, j});
}
}
if (emptyCells.length) {
const {i, j} = emptyCells[Math.floor(Math.random() * emptyCells.length)];
this.grid[i][j] = Math.random() < 0.9 ? 2 : 4;
}
},
move(direction) {
// 滑动合并逻辑
// ...
if (this.isGridChanged) this.addRandomTile();
if (this.isGameOver()) this.gameOver = true;
}
}
}
视图渲染
使用 Vue 模板渲染游戏界面:
<template>
<div class="game-container">
<div class="header">
<h1>2048</h1>
<div class="score">Score: {{ score }}</div>
</div>
<div class="grid">
<div v-for="(row, i) in grid" :key="i" class="row">
<div v-for="(cell, j) in row" :key="j" :class="['cell', `tile-${cell}`]">
{{ cell || '' }}
</div>
</div>
</div>
<button @click="initGame">New Game</button>
</div>
</template>
样式设计
添加 CSS 样式美化游戏界面:
.game-container {
width: 400px;
margin: 0 auto;
}
.grid {
background: #bbada0;
border-radius: 6px;
padding: 10px;
}
.row {
display: flex;
}
.cell {
width: 80px;
height: 80px;
margin: 10px;
background: rgba(238, 228, 218, 0.35);
border-radius: 3px;
display: flex;
justify-content: center;
align-items: center;
font-size: 35px;
font-weight: bold;
}
.tile-2 { background: #eee4da; }
.tile-4 { background: #ede0c8; }
/* 更多数字样式... */
键盘事件处理
监听键盘事件控制游戏:

mounted() {
window.addEventListener('keydown', this.handleKeyDown);
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeyDown);
},
methods: {
handleKeyDown(e) {
if (this.gameOver) return;
switch (e.key) {
case 'ArrowUp': this.move('up'); break;
case 'ArrowRight': this.move('right'); break;
case 'ArrowDown': this.move('down'); break;
case 'ArrowLeft': this.move('left'); break;
}
}
}
完整实现要点
- 使用二维数组表示游戏棋盘
- 每次移动后随机生成新数字
- 实现四个方向的合并逻辑
- 计算分数并判断游戏结束条件
- 响应式更新界面状态
- 添加动画效果增强用户体验
完整实现需要处理滑动时的合并逻辑和动画效果,这些可以通过 Vue 的过渡系统和 CSS 动画实现。






