下面是一个使用单个HTML文件实现的简单贪吃蛇游戏的示例。请将以下代码复制并粘贴到一个新的HTML文件中,然后用浏览器打开即可玩游戏。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20; // 每个方块的大小
let snake = [{ x: 9 * box, y: 9 * box }];
let direction = '';
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowUp' && direction !== 'down') direction = 'up';
else if (event.key === 'ArrowDown' && direction !== 'up') direction = 'down';
else if (event.key === 'ArrowLeft' && direction !== 'right') direction = 'left';
else if (event.key === 'ArrowRight' && direction !== 'left') direction = 'right';
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'lightgreen';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'white';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'darkgreen';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === 'up') snakeY -= box;
if (direction === 'down') snakeY += box;
if (direction === 'left') snakeX -= box;
if (direction === 'right') snakeX += box;
if (snakeX === food.x && snakeY === food.y) {
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
snake.pop();
}
const newHead = { x: snakeX, y: snakeY };
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collide(newHead, snake)) {
clearInterval(game);
alert('游戏结束!');
}
snake.unshift(newHead);
}
function collide(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
const game = setInterval(draw, 100);
</script>
</body>
</html>
效果图
将这段代码保存为 snake_game.html
,然后用浏览器打开,你就可以开始玩简单的贪吃蛇游戏了。使用方向键控制蛇的移动方向。祝你玩得开心!
标签:box,direction,ctx,canvas,HTML,snake,单个,贪吃蛇,Math From: https://blog.csdn.net/weixin_49939244/article/details/143304809