用html写一个贪吃蛇游戏代码
时间: 2023-09-30 19:05:37 浏览: 83
好的,以下是一个简单的贪吃蛇游戏的HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贪吃蛇游戏</title>
<style type="text/css">
body {
background-color: #EEE;
text-align: center;
}
canvas {
border: 1px solid #ccc;
background-color: #FFF;
margin: 20px auto;
}
</style>
</head>
<body>
<h1>贪吃蛇游戏</h1>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script type="text/javascript">
// 定义全局变量
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");
var snake = [{ x: 0, y: 0 }];
var direction = "right";
var food = { x: 0, y: 0 };
var score = 0;
var gameInterval;
// 初始化游戏
function initGame() {
snake = [{ x: 0, y: 0 }];
direction = "right";
score = 0;
generateFood();
gameInterval = setInterval(updateGame, 100);
}
// 生成食物
function generateFood() {
food.x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
food.y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
}
// 更新游戏
function updateGame() {
// 移动蛇头
var head = { x: snake[0].x, y: snake[0].y };
switch (direction) {
case "up": head.y -= 10; break;
case "down": head.y += 10; break;
case "left": head.x -= 10; break;
case "right": head.x += 10; break;
}
snake.unshift(head);
// 判断是否吃到食物
if (head.x == food.x && head.y == food.y) {
score++;
generateFood();
} else {
snake.pop();
}
// 判断游戏是否结束
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
clearInterval(gameInterval);
alert("游戏结束!得分: " + score);
initGame();
} else {
for (var i = 1; i < snake.length; i++) {
if (head.x == snake[i].x && head.y == snake[i].y) {
clearInterval(gameInterval);
alert("游戏结束!得分: " + score);
initGame();
}
}
}
// 绘制画面
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "#F00";
context.fillRect(food.x, food.y, 10, 10);
context.fillStyle = "#000";
for (var i = 0; i < snake.length; i++) {
context.fillRect(snake[i].x, snake[i].y, 10, 10);
}
context.fillText("得分:" + score, canvas.width - 70, 20)
}
// 监听键盘事件
document.addEventListener("keydown", function(event) {
switch (event.key) {
case "ArrowUp": direction = "up"; break;
case "ArrowDown": direction = "down"; break;
case "ArrowLeft": direction = "left"; break;
case "ArrowRight": direction = "right"; break;
}
});
// 初始化游戏
initGame();
</script>
</body>
</html>
```
阅读全文