<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid #000;
position: relative;
}
.snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<h1>贪吃蛇游戏</h1>
<div id="game-board"></div>
<script>
// 获取游戏区域元素和设置相关变量
const gameBoard = document.getElementById("game-board");
const gridSize = 20;
const gameSize = 400;
const snakeSpeed = 150;
// 初始化蛇和食物的位置和初始移动方向
let snake = [{ x: 0, y: 0 }];
let food = { x: 0, y: 0 };
let dx = gridSize;
let dy = 0;
// 生成食物的随机位置
function generateFood() {
food.x = Math.floor(Math.random() * gridSize) * gridSize;
food.y = Math.floor(Math.random() * gridSize) * gridSize;
// 确保食物不会与蛇重叠
for (let i = 0; i < snake.length; i++) {
if (food.x === snake[i].x && food.y === snake[i].y) {
generateFood();
break;
}
}
}
// 更新蛇的位置和游戏状态
function update() {
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
snake.unshift(head);
// 检查是否吃到了食物
if (head.x === food.x && head.y === food.y) {
generateFood();
} else {
snake.pop();
}
// 检查是否碰到边界或自身
if (
head.x < 0 ||
head.x >= gameSize ||
head.y < 0 ||
head.y >= gameSize ||
checkCollision(head)
) {
clearInterval(gameInterval);
alert("游戏结束!");
return;
}
// 清空游戏区域
gameBoard.innerHTML = "";
// 绘制蛇
snake.forEach(segment => {
const snakeElement = document.createElement("div");
snakeElement.style.left = segment.x + "px";
snakeElement.style.top = segment.y + "px";
snakeElement.classList.add("snake");
gameBoard.appendChild(snakeElement);
});
// 绘制食物
const foodElement = document.createElement("div");
foodElement.style.left = food.x + "px";
foodElement.style.top = food.y + "px";
foodElement.classList.add("food");
gameBoard.appendChild(foodElement);
}
// 检查蛇头是否碰撞到蛇身
function checkCollision(head) {
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
return true;
}
}
return false;
}
// 处理按键事件,改变蛇的移动方向
function handleKeydown(event) {
if (event.key === "ArrowUp" && dy !== gridSize) {
dx = 0;
dy = -gridSize;
} else if (event.key === "ArrowDown" && dy !== -gridSize) {
dx = 0;
dy = gridSize;
} else if (event.key === "ArrowLeft" && dx !== gridSize) {
dx = -gridSize;
dy = 0;
} else if (event.key === "ArrowRight" && dx !== -gridSize) {
dx = gridSize;
dy = 0;
}
}
// 监听按键事件
document.addEventListener("keydown", handleKeydown);
// 生成初始食物
generateFood();
// 更新游戏状态的定时器
const gameInterval = setInterval(update, snakeSpeed);
</script>
</body>
</html>