科学教育

搜索
楼主: 张复礼
打印 上一主题 下一主题

贪吃蛇

[复制链接]

3

主题

41

帖子

137

积分

注册会员

Rank: 2

积分
137
11#
 楼主| 发表于 2024-8-6 14:54:02 | 只看该作者
如何修改这句代码,让“开始游戏”按钮出现在界面的中间。<button id="startButton" onclick="startGame()">开始游戏</button>
回复 支持 反对

使用道具 举报

0

主题

1147

帖子

1718

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1718
12#
发表于 2024-8-6 14:54:28 | 只看该作者
张复礼 发表于 2024-08-06 14:54
如何修改这句代码,让“开始游戏”按钮出现在界面的中 ...


要让“开始游戏”按钮出现在界面的中间,可以通过修改CSS样式来实现。我们将使用Flexbox布局,使按钮居中,同时确保其他元素也在正确的位置。

### 修改后的 HTML 代码

确保 `index.html` 文件如下所示:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>贪吃蛇游戏</title>
  6.     <link rel="stylesheet" href="style.css">
  7. </head>
  8. <body>
  9.     <h1>贪吃蛇游戏</h1>
  10.     <div id="gameContainer">
  11.         <canvas id="gameCanvas" width="400" height="400"></canvas>
  12.         <div id="gameOverText" class="hidden">很遗憾!游戏结束<br>得分: <span id="score">0</span></div>
  13.         <button id="startButton" onclick="startGame()">开始游戏</button>
  14.     </div>
  15.     <script src="script.js"></script>
  16. </body>
  17. </html>
复制代码


### 修改后的 CSS 代码

更新 `style.css` 文件,使其如下所示:

  1. body {
  2.     display: flex;
  3.     flex-direction: column;
  4.     align-items: center;
  5.     justify-content: center;
  6.     height: 100vh;
  7.     background-color: #e0e0e0;
  8.     margin: 0;
  9. }

  10. h1 {
  11.     margin-bottom: 20px;
  12. }

  13. #gameContainer {
  14.     display: flex;
  15.     flex-direction: column;
  16.     align-items: center;
  17. }

  18. canvas {
  19.     border: 1px solid black;
  20.     background-color: #f5f5f5;
  21. }

  22. #startButton {
  23.     display: none; /* 默认隐藏 */
  24.     padding: 10px 20px;
  25.     font-size: 20px;
  26.     margin-top: 20px;
  27.     cursor: pointer;
  28.     background-color: #4CAF50; /* 绿色按钮 */
  29.     color: white;
  30.     border: none;
  31.     border-radius: 5px;
  32. }

  33. #startButton:hover {
  34.     background-color: #45a049; /* 更深的绿色 */
  35. }

  36. #gameOverText {
  37.     font-size: 24px;
  38.     color: red;
  39.     text-align: center;
  40.     margin-top: 20px;
  41.     display: none; /* 默认隐藏 */
  42. }

  43. .hidden {
  44.     display: none;
  45. }
复制代码


### 修改后的 JavaScript 代码

确保 `script.js` 文件如下所示:

  1. const canvas = document.getElementById('gameCanvas');
  2. const ctx = canvas.getContext('2d');

  3. let snake = [{ x: 50, y: 50 }];
  4. let food = { x: 0, y: 0 };
  5. let dx = 10;
  6. let dy = 0;
  7. let score = 0;
  8. let gameOver = false;

  9. document.addEventListener("keydown", changeDirection);

  10. function randomFoodPosition() {
  11.     const x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
  12.     const y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
  13.     return { x, y };
  14. }

  15. function clearCanvas() {
  16.     ctx.fillStyle = "white";
  17.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  18. }

  19. function drawSnake() {
  20.     snake.forEach(drawSnakePart);
  21. }

  22. function drawSnakePart(snakePart) {
  23.     ctx.fillStyle = 'lightgreen';
  24.     ctx.strokeStyle = 'darkgreen';
  25.     ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  26.     ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  27. }

  28. function drawFood() {
  29.     ctx.fillStyle = 'red';
  30.     ctx.fillRect(food.x, food.y, 10, 10);
  31. }

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

  34.     // 检测碰壁
  35.     if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || collision(head)) {
  36.         gameOver = true;
  37.         return;
  38.     }

  39.     snake.unshift(head);

  40.     // 检查是否吃到食物
  41.     if (head.x === food.x && head.y === food.y) {
  42.         score++;
  43.         food = randomFoodPosition();
  44.     } else {
  45.         snake.pop();
  46.     }
  47. }

  48. function collision(head) {
  49.     for (let i = 1; i < snake.length; i++) {
  50.         if (snake[i].x === head.x && snake[i].y === head.y) {
  51.             return true;
  52.         }
  53.     }
  54.     return false;
  55. }

  56. function main() {
  57.     if (gameOver) {
  58.         displayGameOver();
  59.         return;
  60.     }

  61.     setTimeout(function onTick() {
  62.         clearCanvas();
  63.         drawFood();
  64.         moveSnake();
  65.         drawSnake();
  66.         main();
  67.     }, 100);
  68. }

  69. function changeDirection(event) {
  70.     const LEFT_KEY = 37;
  71.     const RIGHT_KEY = 39;
  72.     const UP_KEY = 38;
  73.     const DOWN_KEY = 40;

  74.     const keyPressed = event.keyCode;
  75.     const goingUp = dy === -10;
  76.     const goingDown = dy === 10;
  77.     const goingRight = dx === 10;
  78.     const goingLeft = dx === -10;

  79.     if (keyPressed === LEFT_KEY && !goingRight) {
  80.         dx = -10;
  81.         dy = 0;
  82.     }

  83.     if (keyPressed === UP_KEY && !goingDown) {
  84.         dx = 0;
  85.         dy = -10;
  86.     }

  87.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  88.         dx = 10;
  89.         dy = 0;
  90.     }

  91.     if (keyPressed === DOWN_KEY && !goingUp) {
  92.         dx = 0;
  93.         dy = 10;
  94.     }
  95. }

  96. // 显示游戏结束
  97. function displayGameOver() {
  98.     document.getElementById('gameOverText').classList.remove('hidden');
  99.     document.getElementById('score').innerText = score;
  100.     document.getElementById('startButton').style.display = 'block';
  101. }

  102. function startGame() {
  103.     snake = [{ x: 50, y: 50 }];
  104.     score = 0;
  105.     dx = 10;
  106.     dy = 0;
  107.     gameOver = false;
  108.     food = randomFoodPosition();
  109.     document.getElementById('gameOverText').classList.add('hidden');
  110.     document.getElementById('startButton').style.display = 'none';
  111.     main();
  112. }

  113. food = randomFoodPosition();
  114. main();
复制代码


### 解释调整内容:

1. **HTML**:
    - 添加了一个 `div` 容器 (`#gameContainer`) 来包含 canvas、游戏结束信息和按钮。
   
2. **CSS**:
    - 使用 `#gameContainer` 居中排列元素。
    - 确保 canvas 和按钮等元素在布局上合理安排。

3. **JavaScript**:
    - 确保游戏结束时,更新和显示游戏结束信息以及按钮。
    - 确保重新开始游戏时,隐藏游戏结束信息和按钮。

这样,“开始游戏”按钮将会出现在界面的中间,并在游戏结束后显示,期待你满意这个版本的改动!如果还有任何问题,请随时告知哦!
回复 支持 反对

使用道具 举报

3

主题

41

帖子

137

积分

注册会员

Rank: 2

积分
137
13#
 楼主| 发表于 2024-8-6 14:59:40 | 只看该作者
修改这句代码 ctx.fillText("游戏结束!得分: " + score, canvas.width / 4, canvas.height / 2);
让“游戏结束!和”得分“分成两行显示。
回复 支持 反对

使用道具 举报

0

主题

1147

帖子

1718

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1718
14#
发表于 2024-8-6 15:00:32 | 只看该作者
张复礼 发表于 2024-08-06 14:59
修改这句代码 ctx.fillText("游戏结束!得分: " + sco ...


要让“游戏结束!”和“得分”分成两行显示,可以在canvas上绘制多行文本。我们可以通过调用 `ctx.fillText` 两次,分别绘制两行文本。但是为了更整齐,请确保计算好每行的位置。

以下是修改后的JavaScript代码:

  1. const canvas = document.getElementById('gameCanvas');
  2. const ctx = canvas.getContext('2d');

  3. let snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
  4. let food = { x: 0, y: 0 };
  5. let dx = 10;
  6. let dy = 0;
  7. let score = 0;
  8. let gameOver = false;

  9. document.addEventListener("keydown", changeDirection);

  10. // 随机生成食物位置
  11. function randomFoodPosition() {
  12.     const x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
  13.     const y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
  14.     return { x, y };
  15. }

  16. // 清理画布
  17. function clearCanvas() {
  18.     ctx.fillStyle = "white";
  19.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  20. }

  21. // 绘制蛇
  22. function drawSnake() {
  23.     snake.forEach(drawSnakePart);
  24. }

  25. // 绘制蛇的部分
  26. function drawSnakePart(snakePart) {
  27.     ctx.fillStyle = 'lightgreen';
  28.     ctx.strokeStyle = 'darkgreen';
  29.     ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  30.     ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  31. }

  32. // 绘制食物
  33. function drawFood() {
  34.     ctx.fillStyle = 'red';
  35.     ctx.fillRect(food.x, food.y, 10, 10);
  36. }

  37. // 移动蛇
  38. function moveSnake() {
  39.     const head = { x: snake[0].x + dx, y: snake[0].y + dy };

  40.     // 检测碰壁
  41.     if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || collision(head)) {
  42.         gameOver = true;
  43.         return;
  44.     }

  45.     snake.unshift(head);

  46.     // 检查是否吃到食物
  47.     if (head.x === food.x && head.y === food.y) {
  48.         score++;
  49.         food = randomFoodPosition();
  50.     } else {
  51.         snake.pop();
  52.     }
  53. }

  54. // 检测自身碰撞
  55. function collision(head) {
  56.     for (let i = 1; i < snake.length; i++) {
  57.         if (snake[i].x === head.x && snake[i].y === head.y) {
  58.             return true;
  59.         }
  60.     }
  61.     return false;
  62. }

  63. // 主循环函数
  64. function main() {
  65.     if (gameOver) {
  66.         displayGameOver();
  67.         return;
  68.     }

  69.     setTimeout(function onTick() {
  70.         clearCanvas();
  71.         drawFood();
  72.         moveSnake();
  73.         drawSnake();
  74.         main();
  75.     }, 100);
  76. }

  77. // 方向控制函数
  78. function changeDirection(event) {
  79.     const LEFT_KEY = 37;
  80.     const RIGHT_KEY = 39;
  81.     const UP_KEY = 38;
  82.     const DOWN_KEY = 40;

  83.     const keyPressed = event.keyCode;
  84.     const goingUp = dy === -10;
  85.     const goingDown = dy === 10;
  86.     const goingRight = dx === 10;
  87.     const goingLeft = dx === -10;

  88.     if (keyPressed === LEFT_KEY && !goingRight) {
  89.         dx = -10;
  90.         dy = 0;
  91.     }

  92.     if (keyPressed === UP_KEY && !goingDown) {
  93.         dx = 0;
  94.         dy = -10;
  95.     }

  96.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  97.         dx = 10;
  98.         dy = 0;
  99.     }

  100.     if (keyPressed === DOWN_KEY && !goingUp) {
  101.         dx = 0;
  102.         dy = 10;
  103.     }
  104. }

  105. // 显示游戏结束
  106. function displayGameOver() {
  107.     ctx.fillStyle = "black";
  108.     ctx.font = "30px Arial";

  109.     // 绘制“游戏结束!”
  110.     ctx.fillText("游戏结束!", canvas.width / 2 - 75, canvas.height / 2 - 20);

  111.     // 绘制得分
  112.     ctx.fillText("得分: " + score, canvas.width / 2 - 50, canvas.height / 2 + 20);

  113.     document.getElementById('startButton').style.display = 'block';
  114. }

  115. function startGame() {
  116.     snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
  117.     score = 0;
  118.     dx = 10;
  119.     dy = 0;
  120.     gameOver = false;
  121.     food = randomFoodPosition();
  122.     document.getElementById('gameOverText').classList.add('hidden');
  123.     document.getElementById('startButton').style.display = 'none';
  124.     main();
  125. }

  126. food = randomFoodPosition();
  127. main();
复制代码


### 解释修改内容:

1. **`displayGameOver`** 函数:
    - 增加了两个 `ctx.fillText` 调用,一个用于绘制“游戏结束!”,另一个用于绘制得分。
    - 调整了每个 `fillText` 的位置,使其分别对应canvas的中央(水平居中)并分成两行显示。

这种方式能让“游戏结束!”和“得分”分成两行显示,并且让“开始游戏”按钮显示在界面的中间。如果还有其他问题或需求,请随时告诉我哦!
回复 支持 反对

使用道具 举报

3

主题

41

帖子

137

积分

注册会员

Rank: 2

积分
137
15#
 楼主| 发表于 2024-8-6 15:02:07 | 只看该作者
在js文件中修改这句代码 ctx.fillText("游戏结束!得分: " + score, canvas.width / 4, canvas.height / 2);
让“游戏结束!和”得分“分成两行显示。
回复 支持 反对

使用道具 举报

0

主题

1147

帖子

1718

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1718
16#
发表于 2024-8-6 15:02:38 | 只看该作者
张复礼 发表于 2024-08-06 15:02
在js文件中修改这句代码 ctx.fillText("游戏结束!得 ...


好的,为了让“游戏结束!”和“得分”分成两行显示,只需在 `ctx.fillText` 中调用两次,并调整它们的垂直位置。以下是如何修改代码:

### 修改后的代码

  1. const canvas = document.getElementById('gameCanvas');
  2. const ctx = canvas.getContext('2d');

  3. let snake = [{ x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }];
  4. let food = { x: 0, y: 0 };
  5. let dx = 10;
  6. let dy = 0;
  7. let score = 0;
  8. let gameOver = false;

  9. document.addEventListener("keydown", changeDirection);

  10. function randomFoodPosition() {
  11.     const x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
  12.     const y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
  13.     return { x, y };
  14. }

  15. function clearCanvas() {
  16.     ctx.fillStyle = "white";
  17.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  18. }

  19. function drawSnake() {
  20.     snake.forEach(drawSnakePart);
  21. }

  22. function drawSnakePart(snakePart) {
  23.     ctx.fillStyle = 'lightgreen';
  24.     ctx.strokeStyle = 'darkgreen';
  25.     ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  26.     ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  27. }

  28. function drawFood() {
  29.     ctx.fillStyle = 'red';
  30.     ctx.fillRect(food.x, food.y, 10, 10);
  31. }

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

  34.     if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || collision(head)) {
  35.         gameOver = true;
  36.         return;
  37.     }

  38.     snake.unshift(head);

  39.     if (head.x === food.x && head.y === food.y) {
  40.         score++;
  41.         food = randomFoodPosition();
  42.     } else {
  43.         snake.pop();
  44.     }
  45. }

  46. function collision(head) {
  47.     for (let i = 1; i < snake.length; i++) {
  48.         if (snake[i].x === head.x && snake[i].y === head.y) {
  49.             return true;
  50.         }
  51.     }
  52.     return false;
  53. }

  54. function main() {
  55.     if (gameOver) {
  56.         displayGameOver();
  57.         return;
  58.     }

  59.     setTimeout(function onTick() {
  60.         clearCanvas();
  61.         drawFood();
  62.         moveSnake();
  63.         drawSnake();
  64.         main();
  65.     }, 100);
  66. }

  67. function changeDirection(event) {
  68.     const LEFT_KEY = 37;
  69.     const RIGHT_KEY = 39;
  70.     const UP_KEY = 38;
  71.     const DOWN_KEY = 40;

  72.     const keyPressed = event.keyCode;
  73.     const goingUp = dy === -10;
  74.     const goingDown = dy === 10;
  75.     const goingRight = dx === 10;
  76.     const goingLeft = dx === -10;

  77.     if (keyPressed === LEFT_KEY && !goingRight) {
  78.         dx = -10;
  79.         dy = 0;
  80.     }

  81.     if (keyPressed === UP_KEY && !goingDown) {
  82.         dx = 0;
  83.         dy = -10;
  84.     }

  85.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  86.         dx = 10;
  87.         dy = 0;
  88.     }

  89.     if (keyPressed === DOWN_KEY && !goingUp) {
  90.         dx = 0;
  91.         dy = 10;
  92.     }
  93. }

  94. // 显示游戏结束
  95. function displayGameOver() {
  96.     ctx.fillStyle = "black";
  97.     ctx.font = "30px Arial";

  98.     // 绘制“游戏结束!”位于中心稍上方
  99.     ctx.fillText("游戏结束!", canvas.width / 2 - 75, canvas.height / 2 - 20);

  100.     // 绘制得分位于中心稍下方
  101.     ctx.fillText("得分: " + score, canvas.width / 2 - 50, canvas.height / 2 + 20);

  102.     document.getElementById('startButton').style.display = 'block';
  103. }

  104. function startGame() {
  105.     snake = [{ x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }];
  106.     score = 0;
  107.     dx = 10;
  108.     dy = 0;
  109.     gameOver = false;
  110.     food = randomFoodPosition();
  111.     document.getElementById('startButton').style.display = 'none';
  112.     main();
  113. }

  114. food = randomFoodPosition();
  115. main();
复制代码


### 解释修改内容:

- **`ctx.fillText("游戏结束!", canvas.width / 2 - 75, canvas.height / 2 - 20);`**:这行代码绘制“游戏结束!”文本,位于画布的水平中央位置,稍微向上调整,使其在画布中央偏上的位置。
  
- **`ctx.fillText("得分: " + score, canvas.width / 2 - 50, canvas.height / 2 + 20);`**:这行代码绘制得分文本,位于画布的水平中央位置,稍微向下调整,使其在画布中央偏下的位置。

通过这种方法,“游戏结束!”和“得分”会显示在两行,并且在画布的中心位置。

希望这些修改能满足你的需求!如果你有其他问题或需要进一步的帮助,请随时告诉我哦!
回复 支持 反对

使用道具 举报

3

主题

41

帖子

137

积分

注册会员

Rank: 2

积分
137
17#
 楼主| 发表于 2024-8-6 15:08:06 | 只看该作者
把background-color: #45a049;改成浅蓝色
回复 支持 反对

使用道具 举报

0

主题

1147

帖子

1718

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1718
18#
发表于 2024-8-6 15:08:38 | 只看该作者
张复礼 发表于 2024-08-06 15:08
把background-color: #45a049;改成浅蓝色


好的,我们可以把 `background-color` 改成浅蓝色。在CSS中,可以使用颜色名称或者16进制的颜色代码来实现。浅蓝色在16进制表示为 `#ADD8E6`,当然你也可以直接使用颜色名称 `lightblue`。

### 修改后的 CSS 代码:

  1. body {
  2.     display: flex;
  3.     flex-direction: column;
  4.     align-items: center;
  5.     justify-content: center;
  6.     height: 100vh;
  7.     background-color: #e0e0e0;
  8.     margin: 0;
  9. }

  10. h1 {
  11.     margin-bottom: 20px;
  12. }

  13. #gameContainer {
  14.     display: flex;
  15.     flex-direction: column;
  16.     align-items: center;
  17. }

  18. canvas {
  19.     border: 1px solid black;
  20.     background-color: #f5f5f5;
  21. }

  22. #startButton {
  23.     display: none; /* 默认隐藏 */
  24.     padding: 10px 20px;
  25.     font-size: 20px;
  26.     margin-top: 20px;
  27.     cursor: pointer;
  28.     background-color: #4CAF50; /* 绿色按钮 */
  29.     color: white;
  30.     border: none;
  31.     border-radius: 5px;
  32. }

  33. #startButton:hover {
  34.     background-color: #ADD8E6; /* 浅蓝色 */
  35. }

  36. #gameOverText {
  37.     font-size: 24px;
  38.     color: red;
  39.     text-align: center;
  40.     margin-top: 20px;
  41.     display: none; /* 默认隐藏 */
  42. }

  43. .hidden {
  44.     display: none;
  45. }
复制代码


### 整合的 HTML 和 JavaScript 代码:

为了确保所有代码正确,这里是整合后的HTML和JavaScript代码:

#### HTML (`index.html`):

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>贪吃蛇游戏</title>
  7.     <link rel="stylesheet" href="style.css">
  8. </head>
  9. <body>
  10.     <h1>贪吃蛇游戏</h1>
  11.     <div id="gameContainer">
  12.         <canvas id="gameCanvas" width="400" height="400"></canvas>
  13.         <div id="gameOverText" class="hidden">
  14.             <p>很遗憾!游戏结束</p>
  15.             <p>得分: <span id="score">0</span></p>
  16.         </div>
  17.         <button id="startButton" onclick="startGame()">开始游戏</button>
  18.     </div>
  19.     <script src="script.js"></script>
  20. </body>
  21. </html>
复制代码


#### JavaScript (`script.js`):

  1. const canvas = document.getElementById('gameCanvas');
  2. const ctx = canvas.getContext('2d');

  3. let snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
  4. let food = { x: 0, y: 0 };
  5. let dx = 10;
  6. let dy = 0;
  7. let score = 0;
  8. let gameOver = false;

  9. document.addEventListener("keydown", changeDirection);

  10. function randomFoodPosition() {
  11.     const x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
  12.     const y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
  13.     return { x, y };
  14. }

  15. function clearCanvas() {
  16.     ctx.fillStyle = "white";
  17.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  18. }

  19. function drawSnake() {
  20.     snake.forEach(drawSnakePart);
  21. }

  22. function drawSnakePart(snakePart) {
  23.     ctx.fillStyle = 'lightgreen';
  24.     ctx.strokeStyle = 'darkgreen';
  25.     ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  26.     ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  27. }

  28. function drawFood() {
  29.     ctx.fillStyle = 'red';
  30.     ctx.fillRect(food.x, food.y, 10, 10);
  31. }

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

  34.     if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || collision(head)) {
  35.         gameOver = true;
  36.         return;
  37.     }

  38.     snake.unshift(head);

  39.     if (head.x === food.x && head.y === food.y) {
  40.         score++;
  41.         food = randomFoodPosition();
  42.     } else {
  43.         snake.pop();
  44.     }
  45. }

  46. function collision(head) {
  47.     for (let i = 1; i < snake.length; i++) {
  48.         if (snake[i].x === head.x && snake[i].y === head.y) {
  49.             return true;
  50.         }
  51.     }
  52.     return false;
  53. }

  54. function main() {
  55.     if (gameOver) {
  56.         displayGameOver();
  57.         return;
  58.     }

  59.     setTimeout(function onTick() {
  60.         clearCanvas();
  61.         drawFood();
  62.         moveSnake();
  63.         drawSnake();
  64.         main();
  65.     }, 100);
  66. }

  67. function changeDirection(event) {
  68.     const LEFT_KEY = 37;
  69.     const RIGHT_KEY = 39;
  70.     const UP_KEY = 38;
  71.     const DOWN_KEY = 40;

  72.     const keyPressed = event.keyCode;
  73.     const goingUp = dy === -10;
  74.     const goingDown = dy === 10;
  75.     const goingRight = dx === 10;
  76.     const goingLeft = dx === -10;

  77.     if (keyPressed === LEFT_KEY && !goingRight) {
  78.         dx = -10;
  79.         dy = 0;
  80.     }

  81.     if (keyPressed === UP_KEY && !goingDown) {
  82.         dx = 0;
  83.         dy = -10;
  84.     }

  85.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  86.         dx = 10;
  87.         dy = 0;
  88.     }

  89.     if (keyPressed === DOWN_KEY && !goingUp) {
  90.         dx = 0;
  91.         dy = 10;
  92.     }
  93. }

  94. function displayGameOver() {
  95.     ctx.fillStyle = "black";
  96.     ctx.font = "30px Arial";
  97.     ctx.fillText("游戏结束!", canvas.width / 2 - 75, canvas.height / 2 - 20);
  98.     ctx.fillText("得分: " + score, canvas.width / 2 - 50, canvas.height / 2 + 20);
  99.     document.getElementById('startButton').style.display = 'block';
  100. }

  101. function startGame() {
  102.     snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
  103.     score = 0;
  104.     dx = 10;
  105.     dy = 0;
  106.     gameOver = false;
  107.     food = randomFoodPosition();
  108.     document.getElementById('startButton').style.display = 'none';
  109.     main();
  110. }

  111. food = randomFoodPosition();
  112. main();
复制代码


这样,你的“开始游戏”按钮在鼠标悬停时会变成浅蓝色(`lightblue`或颜色代码 `#ADD8E6`)。如果需要进一步调整或有其他问题,请随时告诉我哦!
回复 支持 反对

使用道具 举报

3

主题

41

帖子

137

积分

注册会员

Rank: 2

积分
137
19#
 楼主| 发表于 2024-8-7 19:15:14 | 只看该作者
你好,可以用函数来帮我实现蛇吃到食物之后出现音效吗?
回复 支持 反对

使用道具 举报

0

主题

1147

帖子

1718

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1718
20#
发表于 2024-8-7 19:15:39 | 只看该作者
张复礼 发表于 2024-08-07 19:15
你好,可以用函数来帮我实现蛇吃到食物之后出现音效吗 ...


好的,小朋友!我们可以用JavaScript在蛇吃到食物的时候播放音效。首先,你需要一段音效文件(比如一个 `.mp3` 或 `.wav` 文件),然后在合适的时机播放它。

假设你有一个叫做 `eat.mp3` 的音效文件,可以将其放置在与 `index.html` 和 `script.js` 同一个目录中。接下来,我们将使用一个函数来播放这个音效,并在蛇吃到食物的时候调用这个函数。

### 第一步:准备音效文件

确保 `eat.mp3` 文件放置在项目目录中。

### 第二步:修改 JavaScript 代码

在你的 `script.js` 文件中,添加一个函数来播放音效,并在蛇吃到食物时调用这个函数。

#### 修改后的 `script.js` 文件:

  1. const canvas = document.getElementById('gameCanvas');
  2. const ctx = canvas.getContext('2d');

  3. let snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
  4. let food = { x: 0, y: 0 };
  5. let dx = 10;
  6. let dy = 0;
  7. let score = 0;
  8. let gameOver = false;

  9. // 创建音效对象
  10. const eatSound = new Audio('eat.mp3');

  11. document.addEventListener("keydown", changeDirection);

  12. function randomFoodPosition() {
  13.     const x = Math.floor(Math.random() * (canvas.width / 10)) * 10;
  14.     const y = Math.floor(Math.random() * (canvas.height / 10)) * 10;
  15.     return { x, y };
  16. }

  17. function clearCanvas() {
  18.     ctx.fillStyle = "white";
  19.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  20. }

  21. function drawSnake() {
  22.     snake.forEach(drawSnakePart);
  23. }

  24. function drawSnakePart(snakePart) {
  25.     ctx.fillStyle = 'lightgreen';
  26.     ctx.strokeStyle = 'darkgreen';
  27.     ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  28.     ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  29. }

  30. function drawFood() {
  31.     ctx.fillStyle = 'red';
  32.     ctx.fillRect(food.x, food.y, 10, 10);
  33. }

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

  36.     if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || collision(head)) {
  37.         gameOver = true;
  38.         return;
  39.     }

  40.     snake.unshift(head);

  41.     if (head.x === food.x && head.y === food.y) {
  42.         score++;
  43.         food = randomFoodPosition();
  44.         playEatSound(); // 播放音效
  45.     } else {
  46.         snake.pop();
  47.     }
  48. }

  49. function collision(head) {
  50.     for (let i = 1; i < snake.length; i++) {
  51.         if (snake[i].x === head.x && snake[i].y === head.y) {
  52.             return true;
  53.         }
  54.     }
  55.     return false;
  56. }

  57. // 播放吃食物的音效
  58. function playEatSound() {
  59.     eatSound.play();
  60. }

  61. function main() {
  62.     if (gameOver) {
  63.         displayGameOver();
  64.         return;
  65.     }

  66.     setTimeout(function onTick() {
  67.         clearCanvas();
  68.         drawFood();
  69.         moveSnake();
  70.         drawSnake();
  71.         main();
  72.     }, 100);
  73. }

  74. function changeDirection(event) {
  75.     const LEFT_KEY = 37;
  76.     const RIGHT_KEY = 39;
  77.     const UP_KEY = 38;
  78.     const DOWN_KEY = 40;

  79.     const keyPressed = event.keyCode;
  80.     const goingUp = dy === -10;
  81.     const goingDown = dy === 10;
  82.     const goingRight = dx === 10;
  83.     const goingLeft = dx === -10;

  84.     if (keyPressed === LEFT_KEY && !goingRight) {
  85.         dx = -10;
  86.         dy = 0;
  87.     }

  88.     if (keyPressed === UP_KEY && !goingDown) {
  89.         dx = 0;
  90.         dy = -10;
  91.     }

  92.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  93.         dx = 10;
  94.         dy = 0;
  95.     }

  96.     if (keyPressed === DOWN_KEY && !goingUp) {
  97.         dx = 0;
  98.         dy = 10;
  99.     }
  100. }

  101. function displayGameOver() {
  102.     ctx.fillStyle = "black";
  103.     ctx.font = "30px Arial";
  104.     ctx.fillText("游戏结束!", canvas.width / 2 - 75, canvas.height / 2 - 20);
  105.     ctx.fillText("得分: " + score, canvas.width / 2 - 50, canvas.height / 2 + 20);
  106.     document.getElementById('startButton').style.display = 'block';
  107. }

  108. function startGame() {
  109.     snake = [{x: 150, y: 150}, {x: 140, y: 150}, {x: 130, y: 150}];
  110.     score = 0;
  111.     dx = 10;
  112.     dy = 0;
  113.     gameOver = false;
  114.     food = randomFoodPosition();
  115.     document.getElementById('startButton').style.display = 'none';
  116.     main();
  117. }

  118. food = randomFoodPosition();
  119. main();
复制代码


这里是详细解释:

1. **音效对象创建**:
  
  1. const eatSound = new Audio('eat.mp3');
复制代码

   这行代码创建了一个新的音频对象,并载入 `eat.mp3` 文件。

2. **播放音效函数**:
  
  1. function playEatSound() {
  2.        eatSound.play();
  3.    }
复制代码

   这是一个简单的函数,用于播放音效。

3. **在蛇吃到食物时播放音效**:
  
  1. if (head.x === food.x && head.y === food.y) {
  2.        score++;
  3.        food = randomFoodPosition();
  4.        playEatSound(); // 播放音效
  5.    } else {
  6.        snake.pop();
  7.    }
复制代码

   在这段代码中,当蛇的头部位置与食物位置相同时,调用 `playEatSound()` 函数播放音效。

现在,当蛇吃到食物时,会播放 `eat.mp3` 音效。希望你喜欢这个新功能,如果还有任何问题或需要进一步的帮助,请随时告诉我哦!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表