项目结构 本项目包含三个文件: index.html:定义游戏页面结构。 style.css:设置游戏界面样式。 game.js:实现游戏逻辑和交互。 代码实现: const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const GRID_SIZE = 20; const GRID_COUNT = canvas.width / GRID_SIZE;
let snake = []; let food = {}; let dx = GRID_SIZE; let dy = 0; let score = 0; let gameLoop;
// 在startGame函数开头添加移动端适配
function startGame() {
canvas.style.touchAction = 'none';
canvas.addEventListener('touchmove', handleTouch, { passive: false });
snake = [{x: 100, y: 100}];
food = generateFood();
dx = GRID_SIZE;
dy = 0;
score = 0;
document.getElementById('score').textContent = 得分: ${score}
;
if (gameLoop) clearInterval(gameLoop); gameLoop = setInterval(update, 100); }
function update() { const head = {x: snake[0].x + dx, y: snake[0].y + dy};
// 碰撞检测
if (head.x < 0 || head.x >= canvas.width ||
head.y < 0 || head.y >= canvas.height ||
snake.some(segment => segment.x === head.x && segment.y === head.y)) {
clearInterval(gameLoop);
alert(游戏结束!得分: ${score}
);
return;
}
snake.unshift(head);
// 吃食物检测
if (head.x === food.x && head.y === food.y) {
score += 10;
document.getElementById('score').textContent = 得分: ${score}
;
food = generateFood();
} else {
snake.pop();
}
draw(); }
function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制蛇
snake.forEach((segment, index) => {
ctx.fillStyle = hsl(${index * 30}, 70%, 50%)
;
ctx.fillRect(segment.x, segment.y, GRID_SIZE-1, GRID_SIZE-1);
});
// 绘制食物 ctx.fillStyle = '#e74c3c'; ctx.beginPath(); ctx.arc(food.x + GRID_SIZE/2, food.y + GRID_SIZE/2, GRID_SIZE/2-1, 0, Math.PI*2); ctx.fill(); }
function generateFood() { while (true) { const newFood = { x: Math.floor(Math.random() * GRID_COUNT) * GRID_SIZE, y: Math.floor(Math.random() * GRID_COUNT) * GRID_SIZE };
if (!snake.some(segment =>
segment.x === newFood.x && segment.y === newFood.y)) {
return newFood;
}
} }
// 键盘控制 document.addEventListener('keydown', (e) => { switch(e.key) { case 'ArrowUp': if (dy === 0) { dx = 0; dy = -GRID_SIZE; } break; case 'ArrowDown': if (dy === 0) { dx = 0; dy = GRID_SIZE; } break; case 'ArrowLeft': if (dx === 0) { dx = -GRID_SIZE; dy = 0; } break; case 'ArrowRight': if (dx === 0) { dx = GRID_SIZE; dy = 0; } break; } });
// 添加触摸事件处理 function handleTouch(e) { const touch = e.touches[0]; const rect = canvas.getBoundingClientRect(); const touchX = touch.clientX - rect.left; const touchY = touch.clientY - rect.top; // 计算滑动方向... }