贪吃蛇

68 阅读1分钟

const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const GRID_SIZE = 20; const CELL_SIZE = canvas.width / GRID_SIZE;

let snake = [{x: 10, y: 10}]; let food = {x: 15, y: 15}; let dx = 1; let dy = 0; let score = 0; let gameLoop;

function drawGame() { // 清空画布 ctx.fillStyle = '#2c3e50'; ctx.fillRect(0, 0, canvas.width, canvas.height);

// 绘制食物 ctx.fillStyle = '#e74c3c'; ctx.fillRect(food.xCELL_SIZE, food.yCELL_SIZE, CELL_SIZE-2, CELL_SIZE-2);

// 绘制蛇 snake.forEach((segment, index) => { ctx.fillStyle = index === 0 ? '#2ecc71' : '#27ae60'; ctx.fillRect(segment.xCELL_SIZE, segment.yCELL_SIZE, CELL_SIZE-2, CELL_SIZE-2); }); }

function update() { const head = {x: snake[0].x + dx, y: snake[0].y + dy};

// 边界检测 if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) { gameOver(); return; }

// 自身碰撞检测 if (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 += 10; document.getElementById('score').textContent = score; generateFood(); } else { snake.pop(); } }

function generateFood() { do { food = { x: Math.floor(Math.random() * GRID_SIZE), y: Math.floor(Math.random() * GRID_SIZE) }; } while (snake.some(segment => segment.x === food.x && segment.y === food.y)); }

function gameOver() { clearInterval(gameLoop); document.getElementById('restart').style.display = 'block'; }

document.addEventListener('keydown', (e) => { switch(e.key) { case 'ArrowUp': if (dy !== 1) { dx = 0; dy = -1; } break; case 'ArrowDown': if (dy !== -1) { dx = 0; dy = 1; } break; case 'ArrowLeft': if (dx !== 1) { dx = -1; dy = 0; } break; case 'ArrowRight': if (dx !== -1) { dx = 1; dy = 0; } break; } });

document.getElementById('restart').addEventListener('click', () => { snake = [{x: 10, y: 10}]; dx = 1; dy = 0; score = 0; document.getElementById('score').textContent = '0'; document.getElementById('restart').style.display = 'none'; generateFood(); gameLoop = setInterval(() => { update(); drawGame(); }, 100); });

// 初始化游戏 generateFood(); gameLoop = setInterval(() => { update(); drawGame(); }, 100);