用html写一个贪吃蛇游戏的完整页面
时间: 2023-09-27 19:07:28 浏览: 79
以下是一个简单的 HTML 页面,用于展示贪吃蛇游戏:
```html
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#canvas {
border: 1px solid black;
}
</style>
</head>
<body onload="init()">
<canvas id="canvas" width="400" height="400"></canvas>
<script>
var canvas;
var ctx;
var snake;
var food;
var score;
var direction;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
snake = {
x: 10,
y: 10,
dx: 10,
dy: 0,
cells: []
};
food = {
x: Math.floor(Math.random() * canvas.width / 10) * 10,
y: Math.floor(Math.random() * canvas.height / 10) * 10
};
score = 0;
direction = "right";
document.addEventListener("keydown", changeDirection);
setInterval(gameLoop, 100);
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.x += snake.dx;
snake.y += snake.dy;
if (snake.x < 0 || snake.x >= canvas.width || snake.y < 0 || snake.y >= canvas.height) {
gameOver();
}
snake.cells.unshift({x: snake.x, y: snake.y});
if (snake.x === food.x && snake.y === food.y) {
score++;
food.x = Math.floor(Math.random() * canvas.width / 10) * 10;
food.y = Math.floor(Math.random() * canvas.height / 10) * 10;
} else {
snake.cells.pop();
}
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, 10, 10);
ctx.fillStyle = "green";
snake.cells.forEach(function(cell, index) {
ctx.fillRect(cell.x, cell.y, 10, 10);
if (cell.x === snake.x && cell.y === snake.y && index > 4) {
gameOver();
}
});
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, canvas.height - 10);
}
function changeDirection(event) {
switch (event.keyCode) {
case 37:
if (direction !== "right") {
snake.dx = -10;
snake.dy = 0;
direction = "left";
}
break;
case 38:
if (direction !== "down") {
snake.dx = 0;
snake.dy = -10;
direction = "up";
}
break;
case 39:
if (direction !== "left") {
snake.dx = 10;
snake.dy = 0;
direction = "right";
}
break;
case 40:
if (direction !== "up") {
snake.dx = 0;
snake.dy = 10;
direction = "down";
}
break;
}
}
function gameOver() {
alert("Game over!");
window.location.reload();
}
</script>
</body>
</html>
```
这个页面包括了一个 canvas 元素,用于绘制贪吃蛇和食物,以及一些 JavaScript 代码,用于控制贪吃蛇的移动和游戏逻辑。在页面加载完毕后,init 函数会被调用,用于初始化游戏。在游戏循环中,会不断地更新贪吃蛇的位置、检测是否吃到了食物、绘制贪吃蛇和食物,以及显示分数。如果贪吃蛇撞墙或者撞到自己,就会触发 gameOver 函数,弹出一个提示框,并且重置游戏。
阅读全文