酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>贪吃蛇游戏</title> <style> body { margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f0f0; } #game-container { position: relative; } #canvas { border: 2px solid #333; background: #fff; } #controls { position: absolute; bottom: 20px; width: 100%; disp

你提供的代码存在不完整的问题,`ctx.clearRect(0, 0, canvas.width, canvas.height)` 之后缺少相应的绘制操作,并且缺少游戏循环和事件监听的完整逻辑。以下是补全后的代码: ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>贪吃蛇游戏</title> <style> body { margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f0f0; } #game-container { position: relative; } #canvas { border: 2px solid #333; background: #fff; } #controls { position: absolute; bottom: 20px; width: 100%; display: flex; justify-content: center; gap: 20px; } .btn { width: 60px; height: 60px; border-radius: 50%; background: #4CAF50; color: white; display: flex; justify-content: center; align-items: center; font-size: 20px; cursor: pointer; } #score { position: absolute; top: 20px; left: 50%; transform: translateX(-50%); font-size: 24px; font-weight: bold; color: #333; } </style> </head> <body> <div id="game-container"> <canvas id="canvas" width="300" height="400"></canvas> <div id="score">分数: 0</div> <div id="controls"> <div class="btn" id="up">↑</div> <div class="btn" id="left">←</div> <div class="btn" id="down">↓</div> <div class="btn" id="right">→</div> </div> </div> <script> // 获取DOM元素 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const scoreEl = document.getElementById('score'); const upBtn = document.getElementById('up'); const downBtn = document.getElementById('down'); const leftBtn = document.getElementById('left'); const rightBtn = document.getElementById('right'); // 游戏参数 const gridSize = 20; // 网格大小 let snake = [{ x: 100, y: 100 }, { x: 80, y: 100 }, { x: 60, y: 100 }]; // 蛇身初始位置 let food = { x: 0, y: 0 }; // 食物位置 let direction = 'right'; // 初始方向 let score = 0; // 分数 let gameOver = false; // 游戏结束标志 let intervalId; // 定时器ID // 初始化食物位置 function initFood() { food.x = Math.floor(Math.random() * (canvas.width / gridSize - 2)) * gridSize + gridSize; food.y = Math.floor(Math.random() * (canvas.height / gridSize - 2)) * gridSize + gridSize; } // 绘制蛇 function drawSnake() { snake.forEach(segment => { ctx.fillStyle = '#4CAF50'; ctx.fillRect(segment.x, segment.y, gridSize, gridSize); ctx.strokeStyle = '#333'; ctx.strokeRect(segment.x, segment.y, gridSize, gridSize); }); } // 绘制食物 function drawFood() { ctx.fillStyle = '#F44336'; ctx.fillRect(food.x, food.y, gridSize, gridSize); ctx.strokeStyle = '#333'; ctx.strokeRect(food.x, food.y, gridSize, gridSize); } // 绘制分数 function drawScore() { scoreEl.textContent = `分数: ${score}`; } // 移动蛇 function moveSnake() { if (gameOver) return; // 获取蛇头位置 const head = { x: snake[0].x, y: snake[0].y }; // 根据方向移动蛇头 switch (direction) { case 'up': head.y -= gridSize; break; case 'down': head.y += gridSize; break; case 'left': head.x -= gridSize; break; case 'right': head.x += gridSize; break; } // 添加新蛇头 snake.unshift(head); // 检查是否吃到食物 if (head.x === food.x && head.y === food.y) { score += 10; initFood(); } else { // 没吃到食物则移除蛇尾 snake.pop(); } // 检查游戏是否结束 checkGameOver(); // 清屏并重新绘制 ctx.clearRect(0, 0, canvas.width, canvas.height); drawSnake(); drawFood(); drawScore(); } // 检查游戏是否结束 function checkGameOver() { const head = snake[0]; // 检查是否撞到墙壁 if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) { gameOver = true; } // 检查是否撞到自己 for (let i = 1; i < snake.length; i++) { if (head.x === snake[i].x && head.y === snake[i].y) { gameOver = true; } } if (gameOver) { clearInterval(intervalId); alert('游戏结束,你的分数是: ' + score); } } // 处理方向改变 function changeDirection(newDirection) { if ( (direction === 'up' && newDirection === 'down') || (direction === 'down' && newDirection === 'up') || (direction === 'left' && newDirection === 'right') || (direction === 'right' && newDirection === 'left') ) { return; } direction = newDirection; } // 键盘事件监听 document.addEventListener('keydown', function (e) { switch (e.key) { case 'ArrowUp': changeDirection('up'); break; case 'ArrowDown': changeDirection('down'); break; case 'ArrowLeft': changeDirection('left'); break; case 'ArrowRight': changeDirection('right'); break; } }); // 按钮事件监听 upBtn.addEventListener('click', function () { changeDirection('up'); }); downBtn.addEventListener('click', function () { changeDirection('down'); }); leftBtn.addEventListener('click', function () { changeDirection('left'); }); rightBtn.addEventListener('click', function () { changeDirection('right'); }); // 初始化游戏 function initGame() { initFood(); intervalId = setInterval(moveSnake, 200); } initGame(); </script> </body> </html> ``` 额外需要注意的逻辑点 1. 方向改变的限制:在改变蛇的方向时,要避免蛇直接反转方向,比如蛇向上移动时不能直接向下移动,这会导致蛇撞到自己。 2. 边界检查:在每次移动蛇后,要检查蛇头是否超出了画布的边界,如果超出则游戏结束。 3. 食物生成位置:食物的生成位置要保证不会出现在蛇的身体上,当前代码只是简单随机生成,可能会出现这种情况,后续可以进一步优化。 [2025-07-10 15:51:52 | AI写代码神器 | 2000点数解答]

相关提问