"D:\BaiduNetdiskDownload\test1\index.html"
贪吃蛇小游戏 body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f0f0f0; }#gameCanvas { border: 1px solid #000; background-color: #fff; } const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d');
const gridSize = 20; const tileCount = 20; canvas.width = gridSize * tileCount; canvas.height = gridSize * tileCount;
let snake = [ {x: 10, y: 10} ];
let direction = 'right'; let nextDirection = 'right';
let food = {x: 5, y: 5};
let score = 0;
function gameLoop() { clearCanvas(); changeDirection(); moveSnake(); checkCollision(); checkFoodCollision(); drawFood(); drawSnake(); drawScore(); setTimeout(gameLoop, 100); }
function clearCanvas() { ctx.fillStyle = '#f0f0f0'; ctx.fillRect(0, 0, canvas.width, canvas.height); }
function changeDirection() { direction = nextDirection; }
function moveSnake() { const head = {...snake[0]}; switch(direction) { case 'right': head.x++; break; case 'left': head.x--; break; case 'up': head.y--; break; case 'down': head.y++; break; } snake.unshift(head); snake.pop(); }
function checkCollision() { const head = snake[0]; if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) { restartGame(); } for (let i = 1; i < snake.length; i++) { if (head.x === snake[i].x && head.y === snake[i].y) { restartGame(); } } }
function checkFoodCollision() { const head = snake[0]; if (head.x === food.x && head.y === food.y) { score++; snake.push({}); generateFood(); } }
function generateFood() { food.x = Math.floor(Math.random() * tileCount); food.y = Math.floor(Math.random() * tileCount); }
function drawSnake() { ctx.fillStyle = '#00ff00'; snake.forEach(segment => { ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize); }); }
function drawFood() { ctx.fillStyle = '#ff0000'; ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize); }
function drawScore() {
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText(分数: ${score}, 10, 25);
}
function restartGame() { snake = [{x: 10, y: 10}]; direction = 'right'; nextDirection = 'right'; score = 0; generateFood(); }
document.addEventListener('keydown', function(event) { switch(event.key) { case 'ArrowRight': if (direction !== 'left') nextDirection = 'right'; break; case 'ArrowLeft': if (direction !== 'right') nextDirection = 'left'; break; case 'ArrowUp': if (direction !== 'down') nextDirection = 'up'; break; case 'ArrowDown': if (direction !== 'up') nextDirection = 'down'; break; } });
gameLoop();