贪吃蛇js小游戏完整代码
时间: 2024-07-04 14:00:51 浏览: 120
20行js代码实现的贪吃蛇小游戏
编写一个完整的贪吃蛇JS小游戏涉及到多个部分,包括游戏循环、键盘控制、蛇的移动、食物生成、碰撞检测等。以下是一个简化的版本,你可以根据这个基础进行扩展:
```javascript
// 创建游戏元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let snake = [{ x: canvas.width / 2, y: canvas.height / 2 }, { x: canvas.width / 2 - 10, y: canvas.height / 2 }];
let food = { x: Math.floor(Math.random() * canvas.width), y: Math.floor(Math.random() * canvas.height) };
let direction = { x: 1, y: 0 }; // 初始方向为右
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制蛇和食物
snake.forEach(s => ctx.fillRect(s.x, s.y, 10, 10));
ctx.fillRect(food.x, food.y, 10, 10);
}
function move() {
let newHead = { x: snake.x + direction.x * 10, y: snake.y + direction.y * 10 };
// 检查边界和碰撞
if (newHead.x < 0 || newHead.x >= canvas.width || newHead.y < 0 || newHead.y >= canvas.height) {
gameOver();
} else {
if (newHead.x === food.x && newHead.y === food.y) {
// 吃到食物,增长蛇身
snake.push(newHead);
food = { x: Math.floor(Math.random() * canvas.width), y: Math.floor(Math.random() * canvas.height) };
} else {
// 移除蛇尾
snake.shift();
}
// 更新蛇头位置
snake.unshift(newHead);
}
}
function gameLoop() {
draw();
move();
requestAnimationFrame(gameLoop);
}
document.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowUp':
direction.y = -1;
break;
case 'ArrowDown':
direction.y = 1;
break;
case 'ArrowLeft':
direction.x = -1;
break;
case 'ArrowRight':
direction.x = 1;
break;
}
});
gameLoop();
```
阅读全文