<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>贪吃蛇游戏</title>
<style>
body {
align-items: center;
display: flex;
justify-content: center;
}
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<!-- <script src="snake.js"></script> -->
</body>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const gridSize = 10;
const gridNum = canvas.width / gridSize;
let snake = [
{ x: 0, y: 0 },
{ x: gridSize, y: 0 },
{ x: 2 * gridSize, y: 0 },
];
let food = { x: 0, y: 0 };
let direction = 'right';
let isGameOver = false;
function initGame() {
snake = [
{ x: 0, y: 0 },
{ x: gridSize, y: 0 },
{ x: 2 * gridSize, y: 0 },
];
generateFood();
direction = 'right';
isGameOver = false;
setInterval(gameLoop, 100);
}
function generateFood() {
const x = Math.floor(Math.random() * gridNum) * gridSize;
const y = Math.floor(Math.random() * gridNum) * gridSize;
for (let i = 0; i < snake.length; i++) {
if (x === snake[i].x && y === snake[i].y) {
return generateFood();
}
}
food.x = x;
food.y = y;
}
function moveSnake() {
for (let i = snake.length - 1; i > 0; i--) {
snake[i].x = snake[i - 1].x;
snake[i].y = snake[i - 1].y;
}
switch (direction) {
case 'up':
snake[0].y -= gridSize;
break;
case 'down':
snake[0].y += gridSize;
break;
case 'left':
snake[0].x -= gridSize;
break;
case 'right':
snake[0].x += gridSize;
break;
}
if (snake[0].x < 0 ||
snake[0].x >= canvas.width ||
snake[0].y < 0 ||
snake[0].y >= canvas.height) {
isGameOver = true;
}
for (let i = 1; i < snake.length; i++) {
if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
isGameOver = true;
break;
}
}
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveSnake();
ctx.fillStyle = 'green';
for (let i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x, snake[i].y, gridSize, gridSize);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, gridSize, gridSize);
if (snake[0].x === food.x && snake[0].y === food.y) {
generateFood();
snake.push({ x: 0, y: 0 });
}
if (isGameOver) {
clearInterval(gameInterval);
alert('游戏结束!');
}
}
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;
}
});
initGame();
</script>
</html>