// 游戏常量
const GRID_SIZE = 20;
const CELL_SIZE = 20;
const GAME_SPEED = 100; // 毫秒
// 游戏状态
let snake = [];
let food = {};
let direction = 'right';
let nextDirection = 'right';
let score = 0;
let gameInterval;
let isGameRunning = false;
// DOM元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const startBtn = document.getElementById('startBtn');
// 初始化游戏
function initGame() {
// 初始化蛇
snake = [
{x: 10, y: 10},
{x: 9, y: 10},
{x: 8, y: 10}
];
// 初始化食物
generateFood();
// 重置方向和分数
direction = 'right';
nextDirection = 'right';
score = 0;
scoreElement.textContent = score;
}
// 生成食物
function generateFood() {
food = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
// 确保食物不会生成在蛇身上
for (let segment of snake) {
if (segment.x === food.x && segment.y === food.y) {
return generateFood();
}
}
}
// 游戏循环
function gameLoop() {
update();
draw();
}
// 更新游戏状态
function update() {
// 更新蛇的方向
direction = nextDirection;
// 计算蛇头新位置
const head = {...snake[0]};
switch (direction) {
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
}
// 检查碰撞
if (
head.x < 0 || head.x >= GRID_SIZE ||
head.y < 0 || head.y >= GRID_SIZE ||
snake.some(segment => segment.x === head.x && segment.y === head.y)
) {
gameOver();
return;
}
// 添加新头部
snake.unshift(head);
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
score++;
scoreElement.textContent = score;
generateFood();
} else {
// 如果没有吃到食物,移除尾部
snake.pop();
}
}
// 绘制游戏
function draw() {
// 清空画布
ctx.fillStyle = '#ecf0f1';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制蛇
ctx.fillStyle = '#2ecc71';
for (let segment of snake) {
ctx.fillRect(
segment.x * CELL_SIZE,
segment.y * CELL_SIZE,
CELL_SIZE - 1,
CELL_SIZE - 1
);
}
// 绘制蛇头(不同颜色)
ctx.fillStyle = '#27ae60';
ctx.fillRect(
snake[0].x * CELL_SIZE,
snake[0].y * CELL_SIZE,
CELL_SIZE - 1,
CELL_SIZE - 1
);
// 绘制食物
ctx.fillStyle = '#e74c3c';
ctx.beginPath();
ctx.arc(
food.x * CELL_SIZE + CELL_SIZE / 2,
food.y * CELL_SIZE + CELL_SIZE / 2,
CELL_SIZE / 2 - 1,
0,
Math.PI * 2
);
ctx.fill();
}
// 游戏结束
function gameOver() {
clearInterval(gameInterval);
isGameRunning = false;
alert(`游戏结束!你的得分是: ${score}`);
}
// 键盘控制
document.addEventListener('keydown', e => {
if (!isGameRunning) return;
switch (e.key) {
case 'ArrowUp':
if (direction !== 'down') nextDirection = 'up';
break;
case 'ArrowDown':
if (direction !== 'up') nextDirection = 'down';
break;
case 'ArrowLeft':
if (direction !== 'right') nextDirection = 'left';
break;
case 'ArrowRight':
if (direction !== 'left') nextDirection = 'right';
break;
}
});
// 开始游戏按钮
startBtn.addEventListener('click', () => {
if (isGameRunning) return;
initGame();
isGameRunning = true;
gameInterval = setInterval(gameLoop, GAME_SPEED);
});
// 初始化游戏(但不自动开始)
initGame();
评论