制作一个网页版贪吃蛇游戏html
时间: 2023-07-04 18:16:29 浏览: 59
好的,以下是一个简单的贪吃蛇游戏的 HTML 代码,你可以在浏览器中打开并运行它:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贪吃蛇游戏</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
let canvas = document.getElementById('gameCanvas');
let ctx = canvas.getContext('2d');
let snake = [{x: 10, y: 10}];
let food = {x: 5, y: 5};
let direction = 'right';
function update() {
// 更新贪吃蛇的位置
let head = {x: snake[0].x, y: snake[0].y};
switch (direction) {
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
}
snake.unshift(head);
// 检测是否吃到食物
if (head.x === food.x && head.y === food.y) {
food.x = Math.floor(Math.random() * 20);
food.y = Math.floor(Math.random() * 20);
} else {
snake.pop();
}
// 检测游戏是否结束
if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20) {
gameOver();
}
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
}
}
}
function draw() {
// 绘制背景
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制贪吃蛇
ctx.fillStyle = 'green';
for (let i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x * 20, snake[i].y * 20, 20, 20);
}
// 绘制食物
ctx.fillStyle = 'red';
ctx.fillRect(food.x * 20, food.y * 20, 20, 20);
}
function gameOver() {
clearInterval(gameLoop);
alert('游戏结束!');
}
function gameLoop() {
update();
draw();
}
document.addEventListener('keydown', event => {
switch (event.keyCode) {
case 37: // left arrow
if (direction !== 'right') {
direction = 'left';
}
break;
case 38: // up arrow
if (direction !== 'down') {
direction = 'up';
}
break;
case 39: // right arrow
if (direction !== 'left') {
direction = 'right';
}
break;
case 40: // down arrow
if (direction !== 'up') {
direction = 'down';
}
break;
}
});
let gameLoop = setInterval(() => {
gameLoop();
}, 100);
</script>
</body>
</html>
```
这个代码创建了一个 400x400 的画布,用于绘制贪吃蛇游戏。它定义了一个 `canvas` 元素、一个 `gameLoop` 函数和一些变量,以及一些用于更新和绘制游戏状态的函数。它还通过 `setInterval` 函数每 100 毫秒调用一次 `gameLoop` 函数来运行游戏。
你可以将这个代码复制到一个文本编辑器中,并将文件保存为 `.html` 格式,然后在浏览器中打开它,就可以玩贪吃蛇游戏了。