vue 实现贪吃蛇
实现贪吃蛇的基本思路
使用 Vue 实现贪吃蛇游戏需要处理游戏逻辑、渲染蛇和食物、控制移动方向以及碰撞检测。Vue 的响应式特性适合管理游戏状态(如蛇的位置、食物位置、得分等),通过键盘事件监听控制蛇的移动方向。
核心代码结构
-
游戏状态初始化
在 Vue 的data中定义游戏所需的状态:data() { return { snake: [{ x: 10, y: 10 }], // 蛇的初始位置(数组存储每一节) food: { x: 5, y: 5 }, // 食物的位置 direction: 'right', // 移动方向 gameOver: false, // 游戏结束标志 score: 0, // 得分 gridSize: 20, // 网格大小(像素) cellCount: 20, // 网格行列数 }; } -
游戏循环与蛇的移动
使用setInterval驱动游戏循环,每隔一定时间更新蛇的位置:methods: { startGame() { this.gameInterval = setInterval(() => { if (this.gameOver) return; this.moveSnake(); }, 200); // 控制蛇的速度 }, moveSnake() { const head = { ...this.snake[0] }; switch (this.direction) { case 'up': head.y -= 1; break; case 'down': head.y += 1; break; case 'left': head.x -= 1; break; case 'right': head.x += 1; break; } this.checkCollision(head); this.snake.unshift(head); // 添加新头部 if (this.isEatingFood(head)) { this.generateFood(); this.score += 1; } else { this.snake.pop(); // 移除尾部(未吃到食物时) } } } -
碰撞检测
检测蛇是否撞墙或撞到自己:
checkCollision(head) { // 撞墙 if ( head.x < 0 || head.x >= this.cellCount || head.y < 0 || head.y >= this.cellCount ) { this.gameOver = true; } // 撞到自己 this.snake.forEach(segment => { if (segment.x === head.x && segment.y === head.y) { this.gameOver = true; } }); } -
生成食物
随机生成食物位置,确保不在蛇身上:generateFood() { const food = { x: Math.floor(Math.random() * this.cellCount), y: Math.floor(Math.random() * this.cellCount), }; // 检查食物是否与蛇重叠 const isOnSnake = this.snake.some(segment => segment.x === food.x && segment.y === food.y ); if (isOnSnake) this.generateFood(); else this.food = food; } -
键盘控制方向
监听键盘事件,限制反向移动(如不能从右直接转向左):mounted() { window.addEventListener('keydown', (e) => { const keyToDirection = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right', }; const newDirection = keyToDirection[e.key]; const oppositeDirections = { up: 'down', down: 'up', left: 'right', right: 'left', }; if (newDirection && oppositeDirections[this.direction] !== newDirection) { this.direction = newDirection; } }); this.startGame(); }
渲染游戏界面
在模板中通过 v-for 渲染蛇和食物:

<template>
<div class="game-container">
<div class="grid">
<!-- 渲染食物 -->
<div
class="food"
:style="{
left: `${food.x * gridSize}px`,
top: `${food.y * gridSize}px`,
width: `${gridSize}px`,
height: `${gridSize}px`,
}"
></div>
<!-- 渲染蛇 -->
<div
v-for="(segment, index) in snake"
:key="index"
class="snake-segment"
:style="{
left: `${segment.x * gridSize}px`,
top: `${segment.y * gridSize}px`,
width: `${gridSize}px`,
height: `${gridSize}px`,
}"
></div>
</div>
<div v-if="gameOver" class="game-over">Game Over! Score: {{ score }}</div>
</div>
</template>
样式设计
添加基础 CSS 样式:
.game-container {
position: relative;
width: 400px;
height: 400px;
margin: 0 auto;
border: 1px solid #000;
}
.grid {
position: relative;
width: 100%;
height: 100%;
}
.snake-segment {
position: absolute;
background-color: green;
border-radius: 2px;
}
.food {
position: absolute;
background-color: red;
border-radius: 50%;
}
.game-over {
text-align: center;
font-size: 24px;
margin-top: 20px;
}
完整示例与扩展建议
-
完整代码
将上述代码片段整合到 Vue 单文件组件(.vue)中即可运行。 -
扩展功能
- 添加开始/暂停按钮。
- 调整游戏难度(如速度随得分增加)。
- 实现本地存储高分记录。
- 添加音效或动画效果。






