<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贪吃蛇</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取画布和绘制上下文
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 定义常量和变量
const gridSize = 10;
const snake = [{ x: 0, y: 0 }];
let direction = 'right';
let food = generateFood();
let score = 0;
let gameOver = false;
// 监听键盘事件
document.addEventListener('keydown', (event) => {
switch (event.code) {
case 'ArrowUp':
if (direction !== 'down') direction = 'up';
break;
case 'ArrowDown':
if (direction !== 'up') direction = 'down';
break;
case 'ArrowLeft':
if (direction !== 'right') direction = 'left';
break;
case 'ArrowRight':
if (direction !== 'left') direction = 'right';
break;
}
});
// 游戏循环
setInterval(() => {
if (gameOver) return;
// 移动蛇
const head = { x: snake[0].x, y: snake[0].y };
switch (direction) {
case 'up':
head.y -= gridSize;
break;
case 'down':
head.y += gridSize;
break;
case 'left':
head.x -= gridSize;
break;
case 'right':
head.x += gridSize;
break;
}
snake.unshift(head);
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
food = generateFood();
score += 10;
} else {
snake.pop();
}
// 检查是否碰到墙壁或自己
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
gameOver = true;
} else {
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver = true;
break;
}
}
}
// 绘制画面
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, gridSize, gridSize);
ctx.fillStyle = 'green';
snake.forEach((segment) => {
ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
});
ctx.fillStyle = 'black';
ctx.fillText(`得分: ${score}`, 10, 20);
}, 100);
// 随机生成食物位置
function generateFood() {
const x = Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize;
const y = Math.floor(Math.random() * (canvas.height/gridSize)) * gridSize;
return { x, y };
}
</script>
</body>
</html>
这段代码创建了一个400×400像素的画布,每个格子大小为10像素,实现了一个简单的贪吃蛇游戏。游戏循环每隔100毫秒更新一次画面,根据玩家的输入移动蛇并检查游戏是否结束,绘制蛇和食物,显示得分等信息。你可以在浏览器中打开这个HTML文件来运行这个贪吃蛇游戏。如果你想要定制更多的游戏规则或添加更多的功能,可以在这个代码的基础上进行修改和扩展。