|
|
你好!我看到你的代码中有几个地方存在问题,可能导致游戏无法正常运行。特别是 `snake` 变量没有正确初始化,还有一些其他的小问题。让我帮你修正这些问题。
### HTML 文件
首先,我们确保 HTML 文件是正确的:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>贪吃蛇游戏</title>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <h1>贪吃蛇游戏</h1>
- <div id="gameContainer">
- <canvas id="gameCanvas" width="400" height="400"></canvas>
- <button id="startButton" onclick="startGame()">开始游戏</button>
- <p id="gameOverText">游戏结束</p>
- </div>
- <div id="rulesButton">游戏规则</div>
- <div id="rulesContent" class="hidden">
- 游戏规则
- <ol>
- <li>使用方向键控制蛇的移动。</li>
- <li>吃到食物会得分并增长体长。</li>
- <li>撞到墙壁或自身会导致游戏结束。</li>
- </ol>
- </div>
- <select id="snakeColor">
- <option value="lightgreen">绿</option>
- <option value="lightblue">蓝</option>
- <option value="yellow">黄</option>
- <option value="red">红</option>
- </select>
- <script src="script.js"></script>
- </body>
- </html>
复制代码
### CSS 文件
CSS 文件看起来是没问题的,这里是你的 CSS 文件:
- body {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- height: 100vh;
- background-color: #e0e0e0;
- margin: 0;
- }
- h1 {
- margin-bottom: 20px;
- }
- #gameContainer {
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- #snakeColor {
- margin: 10px;
- padding: 5px;
- font-size: 16px;
- }
- canvas {
- border: 1px solid black;
- background-color: #f5f5f5;
- }
- #startButton {
- padding: 10px 20px;
- font-size: 20px;
- margin-top: 20px;
- cursor: pointer;
- background-color: #DB516F;
- color: white;
- border: none;
- border-radius: 5px;
- }
- #startButton:hover {
- background-color: #E6889C;
- }
- #gameOverText {
- font-size: 24px;
- color: red;
- text-align: center;
- margin-top: 20px;
- display: none; /* 默认隐藏 */
- }
- .hidden {
- display: none;
- }
- #rulesButton {
- position: absolute;
- right: 10px;
- top: 10px;
- padding: 10px;
- background-color: lightblue;
- border: none;
- cursor: pointer;
- font-size: 16px;
- }
- #rulesContent {
- position: absolute;
- right: 10px;
- top: 50px;
- padding: 10px;
- background-color: white;
- border: 1px solid #ccc;
- box-shadow: 0 0 10px rgba(0,0,0,0.1);
- }
复制代码
### JavaScript 文件
这是你修正后的 JavaScript 文件:
- const canvas = document.getElementById('gameCanvas');
- const ctx = canvas.getContext('2d');
- let snake = [{ x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }, { x: 120, y: 150 }, { x: 110, y: 150 }];
- let food = { x: 0, y: 0 };
- let dx = 10;
- let dy = 0;
- let score = 0;
- let gameOver = false;
- let snakeColor = 'lightgreen'; // 默认颜色
- // 创建音效对象
- const eatSound = new Audio('eat.mp3');
- // 创建背景音乐对象
- const backgroundMusic = new Audio('background.mp3');
- backgroundMusic.loop = true; // 设置循环播放
- document.addEventListener("keydown", changeDirection);
- document.getElementById('snakeColor').addEventListener('change', function(event) {
- snakeColor = event.target.value; // 更新贪吃蛇颜色
- });
- function randomFoodPosition() {
- const x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
- const y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
- return { x, y };
- }
- function clearCanvas() {
- ctx.fillStyle = "white";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- }
- function drawSnake() {
- snake.forEach(drawSnakePart);
- }
- function drawSnakePart(snakePart) {
- ctx.fillStyle = snakeColor; // 使用选择的颜色
- ctx.strokeStyle = 'darkgreen';
- ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
- ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
- }
- function drawFood() {
- ctx.fillStyle = 'lightpink';
- ctx.fillRect(food.x, food.y, 10, 10);
- }
- function moveSnake() {
- 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 || collision(head)) {
- gameOver = true;
- return;
- }
- snake.unshift(head);
- // 检查是否吃到食物
- if (head.x === food.x && head.y === food.y) {
- score++;
- food = randomFoodPosition();
- playEatSound(); // 播放音效
- } else {
- snake.pop();
- }
- }
- function collision(head) {
- for (let i = 1; i < snake.length; i++) {
- if (snake[i].x === head.x && snake[i].y === head.y) {
- return true;
- }
- }
- return false;
- }
- // 播放吃食物的音效
- function playEatSound() {
- eatSound.play();
- }
- // 播放背景音乐
- function playBackgroundMusic() {
- backgroundMusic.play();
- }
- // 停止背景音乐
- function stopBackgroundMusic() {
- backgroundMusic.pause();
- backgroundMusic.currentTime = 0; // 重置音乐到开头
- }
- function main() {
- if (gameOver) {
- displayGameOver();
- return;
- }
- setTimeout(function onTick() {
- clearCanvas();
- drawFood();
- moveSnake();
- drawSnake();
- main();
- }, 100);
- }
- function changeDirection(event) {
- const LEFT_KEY = 37;
- const RIGHT_KEY = 39;
- const UP_KEY = 38;
- const DOWN_KEY = 40;
- const keyPressed = event.keyCode;
- const goingUp = dy === -10;
- const goingDown = dy === 10;
- const goingRight = dx === 10;
- const goingLeft = dx === -10;
- if (keyPressed === LEFT_KEY && !goingRight) {
- dx = -10;
- dy = 0;
- }
- if (keyPressed === UP_KEY && !goingDown) {
- dx = 0;
- dy = -10;
- }
- if (keyPressed === RIGHT_KEY && !goingLeft) {
- dx = 10;
- dy = 0;
- }
- if (keyPressed === DOWN_KEY && !goingUp) {
- dx = 0;
- dy = 10;
- }
- }
- // 显示游戏结束
- function displayGameOver() {
- ctx.fillStyle = "pink";
- ctx.font = "30px Arial";
- // 绘制“游戏结束!”位于中心稍上方
- ctx.fillText("很遗憾,游戏结束!", canvas.width / 2 - 115, canvas.height / 2 - 20);
- // 绘制得分位于中心稍下方
- ctx.fillText("得分: " + score, canvas.width / 2 - 50, canvas.height / 2 + 20);
- document.getElementById("startButton").style.display = "block";
- stopBackgroundMusic(); // 停止背景音乐
- }
- function startGame() {
- snake = [{ x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }, { x: 120, y: 150 }, { x: 110, y: 150 }];
- score = 0;
- dx = 10;
- dy = 0;
- gameOver = false;
- food = randomFoodPosition();
- document.getElementById('startButton').style.display = 'none';
- playBackgroundMusic(); // 播放背景音乐
- main();
- }
- // 隐藏“游戏结束”提示
- document.getElementById('gameOverText').style.display = 'none';
- main();
- // 获取按钮和规则内容的DOM元素
- const rulesButton = document.getElementById('rulesButton');
- const rulesContent = document.getElementById('rulesContent');
- // 当鼠标移到按钮上时,显示规则
- rulesButton.addEventListener('mouseover', function () {
- rulesContent.style.display = 'block';
- });
- // 当鼠标离开按钮时,隐藏规则
- rulesButton.addEventListener('mouseout', function () {
- rulesContent.style.display = 'none';
- });
复制代码
### 改动说明
1. 修正了`snake`变量的初始化,让蛇从一开始就有五个部分。
2. 在 `moveSnake` 函数中修正访问蛇头的位置错误。
3. 确保游戏开始时隐藏“游戏结束”的提示,并将蛇重置为初始状态。
4. 补充了在 `startGame` 函数中初始化蛇的代码。
现在,你可以试着再次运行这个贪吃蛇游戏,看看是否能正常运行。如果还有任何问题,请随时告诉我! |
|