帮我实现一个H5的贪吃蛇游戏
时间: 2023-05-12 18:07:22 浏览: 65
好的,我可以为您提供一个基于HTML5的贪吃蛇游戏的代码示例。以下是一个简单的实现:
```html
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取画布和上下文
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 定义贪吃蛇和食物的初始位置
var snake = [{x: 10, y: 10}];
var food = {x: Math.floor(Math.random() * 40), y: Math.floor(Math.random() * 40)};
// 定义贪吃蛇的移动方向
var direction = "right";
// 定义游戏循环
var gameLoop = setInterval(function() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 移动贪吃蛇
var head = {x: snake[0].x, y: snake[0].y};
switch (direction) {
case "up":
head.y--;
break;
case "down":
head.y++;
break;
case "left":
head.x--;
break;
case "right":
head.x++;
break;
}
snake.unshift(head);
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
food = {x: Math.floor(Math.random() * 40), y: Math.floor(Math.random() * 40)};
} else {
snake.pop();
}
// 绘制食物
ctx.fillStyle = "red";
ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
// 绘制贪吃蛇
ctx.fillStyle = "green";
snake.forEach(function(segment) {
ctx.fillRect(segment.x * 10, segment.y * 10, 10, 10);
});
// 检查是否撞墙或撞到自己
if (head.x < 0 || head.x >= 40 || head.y < 0 || head.y >= 40) {
clearInterval(gameLoop);
alert("游戏结束!");
}
for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
clearInterval(gameLoop);
alert("游戏结束!");
}
}
}, 100);
// 监听键盘事件
document.addEventListener("keydown", function(event) {
switch (event.keyCode) {
case 38: // 上
if (direction !== "down") {
direction = "up";
}
break;
case 40: // 下
if (direction !== "up") {
direction = "down";
}
break;
case 37: // 左
if (direction !== "right") {
direction = "left";
}
break;
case 39: // 右
if (direction !== "left") {
direction = "right";
}
break;
}
});
</script>
</