科学教育

搜索
楼主: 林奕锦
打印 上一主题 下一主题

林奕锦1

[复制链接]

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
11#
 楼主| 发表于 2024-7-17 10:14:21 | 只看该作者
禁用UTF-8编码的选项在哪里?
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
12#
发表于 2024-7-17 10:15:13 | 只看该作者
林奕锦 发表于 2024-07-17 10:14
禁用UTF-8编码的选项在哪里?


字节序列的问题,UTF-8是一种非常普遍的字符编码,几乎所有现代浏览器都默认支持它。因此,一般来说不需要在浏览器中进行额外设置。但是,如果你在页面中添加了meta标签并且确保文件是以UTF-8编码保存的之后,仍然无法显示中文字符,那么可能会有以下几个原因:

1. **文件未实际被保存为UTF-8**:有时候,尽管你设置了编码,但文件管理器或编辑器没有实际地用UTF-8保存文件。

2. **缓存问题**:浏览器可能缓存了之前的文件内容,导致未采取最新的修改。可以尝试清除浏览器缓存或者在隐身模式下打开页面。

3. **其他编码声明干扰**:确保没有其他的编码声明与UTF-8冲突。

### 确保文件以UTF-8保存
在你使用的文本编辑器中,有多种方式确保文件是以UTF-8保存的。下面是一些常用编辑器的具体操作方法:

#### VS Code
1. 打开文件。
2. 在右下角查看当前文件的编码格式。如果不是UTF-8,可以点击编码格式。
3. 选择“Save with Encoding...”,然后选择“UTF-8”。

#### Sublime Text
1. 打开文件。
2. 点击菜单栏中的 `File -> Save with Encoding -> UTF-8`。

#### Notepad++
1. 打开文件。
2. 点击菜单栏中的 `Encoding -> Convert to UTF-8 (without BOM)`。

### 清除浏览器缓存
为了确保浏览器加载的是最新版本的文件,可以清除浏览器缓存。以下是几种常见浏览器的操作步骤:

#### Google Chrome
1. 打开浏览器设置。
2. 找到“隐私和安全”选项。
3. 点击“清除浏览数据”。
4. 选择“缓存的图片和文件”,然后点击“清除数据”。

#### Firefox
1. 打开浏览器设置。
2. 找到“隐私与安全”选项。
3. 在“Cookies 和站点数据”部分,点击“清除数据”。
4. 勾选“缓存的 Web 内容”,然后点击“清除”。

### 更新后的完整代码示例
确保以下三个文件内容正确,并保存为UTF-8编码:

#### `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="styles.css">
  7. </head>
  8. <body>
  9.     <h1>贪吃蛇游戏</h1>
  10.     <button id="startButton">开始游戏</button>
  11.     <canvas id="gameCanvas" width="400" height="400"></canvas>
  12.     <div id="score">得分: 0</div>

  13.     <script src="snake_game.js"></script>
  14. </body>
  15. </html>
复制代码


#### `styles.css`
  1. /* 设置画布和页面的样式 */
  2. canvas {
  3.     background-color: #000; /* 黑色背景 */
  4.     display: block;        /* 画布作为块级元素 */
  5.     margin: 0 auto;        /* 居中对齐 */
  6. }

  7. /* 添加一些基本的页面样式 */
  8. body {
  9.     display: flex;
  10.     flex-direction: column;
  11.     align-items: center;
  12.     justify-content: center;
  13.     height: 100vh;
  14.     margin: 0;
  15. }

  16. h1 {
  17.     color: #333;
  18. }

  19. #startButton {
  20.     padding: 10px 20px;
  21.     font-size: 16px;
  22.     margin-bottom: 20px;
  23. }

  24. #score {
  25.     margin-top: 20px;
  26.     font-size: 20px;
  27.     color: #333;
  28. }
复制代码


#### `snake_game.js`
  1. // 获取画布并设置上下文
  2. const canvas = document.getElementById('gameCanvas');
  3. const ctx = canvas.getContext('2d');
  4. const startButton = document.getElementById('startButton');
  5. const scoreDisplay = document.getElementById('score');

  6. // 定义蛇的初始状态
  7. let snake = [{x: 200, y: 200}, {x: 190, y: 200}, {x: 180, y: 200}];
  8. let foodX;
  9. let foodY;
  10. let dx = 10;
  11. let dy = 0;
  12. let score = 0;
  13. let isGameRunning = false;

  14. // 创建游戏循环
  15. function main() {
  16.     if (isGameRunning) {
  17.         setTimeout(function onTick() {
  18.             clearCanvas();
  19.             moveSnake();
  20.             drawSnake();
  21.             drawFood();
  22.             checkGameOver();
  23.             main();
  24.         }, 100);
  25.     } else {
  26.         alert(`游戏结束!得分: ${score}`);
  27.     }
  28. }

  29. // 初始化游戏
  30. function startGame() {
  31.     snake = [{x: 200, y: 200}, {x: 190, y: 200}, {x: 180, y: 200}];
  32.     dx = 10;
  33.     dy = 0;
  34.     score = 0;
  35.     isGameRunning = true;
  36.     createFood();
  37.     scoreDisplay.innerText = `得分: ${score}`;
  38.     main();
  39. }

  40. // 清除画布
  41. function clearCanvas() {
  42.     ctx.fillStyle = "black";
  43.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  44. }

  45. // 绘制蛇
  46. function drawSnake() {
  47.     snake.forEach(snakePart => {
  48.         ctx.fillStyle = 'lightgreen';
  49.         ctx.strokestyle = 'darkgreen';
  50.         ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  51.         ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  52.     });
  53. }

  54. // 移动蛇
  55. function moveSnake() {
  56.     const head = { x: snake[0].x + dx, y: snake[0].y + dy };
  57.     snake.unshift(head);
  58.     const didEatFood = snake[0].x === foodX && snake[0].y === foodY;
  59.     if (didEatFood) {
  60.         score += 10;
  61.         scoreDisplay.innerText = `得分: ${score}`;
  62.         createFood();
  63.     } else {
  64.         snake.pop();
  65.     }
  66. }

  67. // 随机生成食物位置
  68. function createFood() {
  69.     foodX = Math.floor((Math.random() * canvas.width) / 10) * 10;
  70.     foodY = Math.floor((Math.random() * canvas.height) / 10) * 10;

  71.     // 确保食物不会生成在蛇身体上
  72.     snake.forEach(snakePart => {
  73.         if (snakePart.x === foodX && snakePart.y === foodY) {
  74.             createFood();
  75.         }
  76.     });
  77. }

  78. // 绘制食物
  79. function drawFood() {
  80.     ctx.fillStyle = 'red';
  81.     ctx.strokestyle = 'darkred';
  82.     ctx.fillRect(foodX, foodY, 10, 10);
  83.     ctx.strokeRect(foodX, foodY, 10, 10);
  84. }

  85. // 检查游戏是否结束
  86. function checkGameOver() {
  87.     for (let i = 4; i < snake.length; i++) {
  88.         if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
  89.             isGameRunning = false;
  90.         }
  91.     }

  92.     const hitLeftWall = snake[0].x < 0;
  93.     const hitRightWall = snake[0].x >= canvas.width;
  94.     const hitTopWall = snake[0].y < 0;
  95.     const hitBottomWall = snake[0].y >= canvas.height;

  96.     if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) {
  97.         isGameRunning = false;
  98.     }
  99. }

  100. // 更改方向
  101. document.addEventListener("keydown", changeDirection);

  102. function changeDirection(event) {
  103.     const LEFT_KEY = 37;
  104.     const RIGHT_KEY = 39;
  105.     const UP_KEY = 38;
  106.     const DOWN_KEY = 40;

  107.     const keyPressed = event.keyCode;
  108.     const goingUp = dy === -10;
  109.     const goingDown = dy === 10;
  110.     const goingRight = dx === 10;
  111.     const goingLeft = dx === -10;

  112.     if (keyPressed === LEFT_KEY && !goingRight) {
  113.         dx = -10;
  114.         dy = 0;
  115.     }

  116.     if (keyPressed === UP_KEY && !goingDown) {
  117.         dx = 0;
  118.         dy = -10;
  119.     }

  120.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  121.         dx = 10;
  122.         dy = 0;
  123.     }

  124.     if (keyPressed === DOWN_KEY && !goingUp) {
  125.         dx = 0;
  126.         dy = 10;
  127.     }
  128. }

  129. // 开始按钮点击事件
  130. startButton.addEventListener("click", startGame);
复制代码


将这三个文件放在同一文件夹中,然后在浏览器中打开`index.html`文件。如果你仍然遇到问题,可以尝试换一个浏览器或者清除浏览器缓存,再次测试。如果还有其他疑问,请继续告诉我!
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
13#
 楼主| 发表于 2024-7-17 10:34:28 | 只看该作者
请帮我把游戏画布改为蓝色,该怎么改?
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
14#
发表于 2024-7-17 10:35:10 | 只看该作者
林奕锦 发表于 2024-07-17 10:34
请帮我把游戏画布改为蓝色,该怎么改? ...


好的!我们可以通过修改CSS文件中的样式来更改游戏画布的颜色。当前的画布背景色设置在`styles.css`文件中,通过调整相关属性,我们可以把画布背景色改为蓝色。

### 更新后的完整代码

#### `index.html`

以下是更新后的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="styles.css">
  8. </head>
  9. <body>
  10.     <h1>贪吃蛇游戏</h1>
  11.     <button id="startButton">开始游戏</button>
  12.     <canvas id="gameCanvas" width="400" height="400"></canvas>
  13.     <div id="score">得分: 0</div>
  14.     <script src="snake_game.js"></script>
  15. </body>
  16. </html>
复制代码


#### `styles.css`

将画布的背景色改为蓝色,只需更新`styles.css`文件中的`canvas`样式:

  1. /* 设置画布和页面的样式 */
  2. canvas {
  3.     background-color: #0000FF; /* 蓝色背景 */
  4.     display: block;           /* 画布作为块级元素 */
  5.     margin: 0 auto;           /* 居中对齐 */
  6. }

  7. /* 添加一些基本的页面样式 */
  8. body {
  9.     display: flex;
  10.     flex-direction: column;
  11.     align-items: center;
  12.     justify-content: center;
  13.     height: 100vh;
  14.     margin: 0;
  15. }

  16. h1 {
  17.     color: #333;
  18. }

  19. #startButton {
  20.     padding: 10px 20px;
  21.     font-size: 16px;
  22.     margin-bottom: 20px;
  23. }

  24. #score {
  25.     margin-top: 20px;
  26.     font-size: 20px;
  27.     color: #333;
  28. }
复制代码


#### `snake_game.js`

JavaScript文件不需要修改,保持之前的内容即可。

  1. // 获取画布并设置上下文
  2. const canvas = document.getElementById('gameCanvas');
  3. const ctx = canvas.getContext('2d');
  4. const startButton = document.getElementById('startButton');
  5. const scoreDisplay = document.getElementById('score');

  6. // 定义蛇的初始状态
  7. let snake = [{ x: 50, y: 50 }];
  8. let foodX;
  9. let foodY;
  10. let dx = 10;
  11. let dy = 0;
  12. let score = 0;
  13. let isGameRunning = false;

  14. // 创建游戏循环
  15. function main() {
  16.     if (isGameRunning) {
  17.         setTimeout(function onTick() {
  18.             clearCanvas();
  19.             moveSnake();
  20.             drawSnake();
  21.             drawFood();
  22.             checkGameOver();
  23.             main();
  24.         }, 100);
  25.     } else {
  26.         alert(`游戏结束!得分: ${score}`);
  27.     }
  28. }

  29. // 初始化游戏
  30. function startGame() {
  31.     snake = [{ x: 50, y: 50 }];
  32.     dx = 10;
  33.     dy = 0;
  34.     score = 0;
  35.     isGameRunning = true;
  36.     createFood();
  37.     scoreDisplay.innerText = `得分: ${score}`;
  38.     main();
  39. }

  40. // 清除画布
  41. function clearCanvas() {
  42.     ctx.fillStyle = "black";
  43.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  44. }

  45. // 绘制蛇
  46. function drawSnake() {
  47.     snake.forEach(snakePart => {
  48.         ctx.fillStyle = 'lightgreen';
  49.         ctx.strokeStyle = 'darkgreen';
  50.         ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  51.         ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  52.     });
  53. }

  54. // 移动蛇
  55. function moveSnake() {
  56.     const head = { x: snake[0].x + dx, y: snake[0].y + dy };
  57.     snake.unshift(head);
  58.     const didEatFood = snake[0].x === foodX && snake[0].y === foodY;
  59.     if (didEatFood) {
  60.         score += 10;
  61.         scoreDisplay.innerText = `得分: ${score}`;
  62.         createFood();
  63.     } else {
  64.         snake.pop();
  65.     }
  66. }

  67. // 随机生成食物位置
  68. function createFood() {
  69.     foodX = Math.floor((Math.random() * canvas.width / 10)) * 10;
  70.     foodY = Math.floor((Math.random() * canvas.height / 10)) * 10;

  71.     // 确保食物不会生成在蛇身体上
  72.     snake.forEach(snakePart => {
  73.         if (snakePart.x === foodX && snakePart.y === foodY) {
  74.             createFood();
  75.         }
  76.     });
  77. }

  78. // 绘制食物
  79. function drawFood() {
  80.     ctx.fillStyle = 'red';
  81.     ctx.strokeStyle = 'darkred';
  82.     ctx.fillRect(foodX, foodY, 10, 10);
  83.     ctx.strokeRect(foodX, foodY, 10, 10);
  84. }

  85. // 检查游戏是否结束
  86. function checkGameOver() {
  87.     for (let i = 4; i < snake.length; i++) {
  88.         const hasCollided = snake[i].x === snake[0].x && snake[i].y === snake[0].y;
  89.         if (hasCollided) {
  90.             isGameRunning = false;
  91.         }
  92.     }

  93.     const hitLeftWall = snake[0].x < 0;
  94.     const hitRightWall = snake[0].x >= canvas.width;
  95.     const hitTopWall = snake[0].y < 0;
  96.     const hitBottomWall = snake[0].y >= canvas.height;

  97.     if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) {
  98.         isGameRunning = false;
  99.     }
  100. }

  101. // 更改方向
  102. document.addEventListener("keydown", changeDirection);

  103. function changeDirection(event) {
  104.     const LEFT_KEY = 37;
  105.     const RIGHT_KEY = 39;
  106.     const UP_KEY = 38;
  107.     const DOWN_KEY = 40;

  108.     const keyPressed = event.keyCode;
  109.     const goingUp = dy === -10;
  110.     const goingDown = dy === 10;
  111.     const goingRight = dx === 10;
  112.     const goingLeft = dx === -10;

  113.     if (keyPressed === LEFT_KEY && !goingRight) {
  114.         dx = -10;
  115.         dy = 0;
  116.     }

  117.     if (keyPressed === UP_KEY && !goingDown) {
  118.         dx = 0;
  119.         dy = -10;
  120.     }

  121.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  122.         dx = 10;
  123.         dy = 0;
  124.     }

  125.     if (keyPressed === DOWN_KEY && !goingUp) {
  126.         dx = 0;
  127.         dy = 10;
  128.     }
  129. }

  130. // 开始按钮点击事件
  131. startButton.addEventListener("click", startGame);
复制代码


将这三个文件放在同一文件夹中,然后在浏览器中打开`index.html`文件,你就会看到蓝色背景的贪吃蛇游戏了。如果还有其他问题,请继续告诉我!
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
15#
 楼主| 发表于 2024-7-17 10:38:10 | 只看该作者
如何将开始按钮调成蓝色
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
16#
发表于 2024-7-17 10:38:58 | 只看该作者
林奕锦 发表于 2024-07-17 10:38
如何将开始按钮调成蓝色


好的!我们可以通过修改CSS文件中的样式来更改“开始游戏”按钮的颜色。接下来,我会告诉你如何将按钮的背景色修改为蓝色,并根据需要提供其他样式的示例。

### 更新后的完整代码

#### `index.html`

以下是更新后的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="styles.css">
  8. </head>
  9. <body>
  10.     <h1>贪吃蛇游戏</h1>
  11.     <button id="startButton">开始游戏</button>
  12.     <div id="score">得分: 0</div>
  13.     <canvas id="gameCanvas" width="400" height="400"></canvas>
  14.     <script src="snake_game.js"></script>
  15. </body>
  16. </html>
复制代码


#### `styles.css`

将按钮的背景色改为蓝色,同时进行一些样式优化:

  1. /* 设置画布和页面的样式 */
  2. canvas {
  3.     background-color: #000; /* 黑色背景 */
  4.     display: block;        /* 画布作为块级元素 */
  5.     margin: 0 auto;        /* 居中对齐 */
  6. }

  7. /* 添加一些基本的页面样式 */
  8. body {
  9.     display: flex;
  10.     flex-direction: column;
  11.     align-items: center;
  12.     justify-content: center;
  13.     height: 100vh;
  14.     margin: 0;
  15. }

  16. h1 {
  17.     color: #333;
  18. }

  19. #startButton {
  20.     padding: 10px 20px;
  21.     font-size: 16px;
  22.     margin-bottom: 20px;
  23.     background-color: #0000FF; /* 蓝色背景 */
  24.     color: white;              /* 文字颜色设为白色 */
  25.     border: none;               /* 无边框 */
  26.     border-radius: 5px;         /* 圆角 */
  27.     cursor: pointer;            /* 鼠标悬停时变成手势 */
  28. }

  29. #startButton:hover {
  30.     background-color: #0000cc; /* 鼠标悬停时背景颜色稍微变深 */
  31. }

  32. #score {
  33.     margin-top: 20px;
  34.     font-size: 20px;
  35.     color: #333;
  36. }
复制代码


#### `snake_game.js`

JavaScript文件不需要修改,保持之前的内容即可。

  1. // 获取画布并设置上下文
  2. const canvas = document.getElementById('gameCanvas');
  3. const ctx = canvas.getContext('2d');
  4. const startButton = document.getElementById('startButton');
  5. const scoreDisplay = document.getElementById('score');

  6. // 定义蛇的初始状态
  7. let snake = [{ x: 150, y: 150 }];
  8. let foodX;
  9. let foodY;
  10. let dx = 10;
  11. let dy = 0;
  12. let score = 0;
  13. let isGameRunning = false;

  14. // 创建游戏循环
  15. function main() {
  16.     if (isGameRunning) {
  17.         setTimeout(function onTick() {
  18.             clearCanvas();
  19.             moveSnake();
  20.             drawSnake();
  21.             drawFood();
  22.             checkGameOver();
  23.             main();
  24.         }, 100);
  25.     } else {
  26.         alert(`游戏结束!得分: ${score}`);
  27.     }
  28. }

  29. // 初始化游戏
  30. function startGame() {
  31.     snake = [{ x: 150, y: 150 }];
  32.     dx = 10;
  33.     dy = 0;
  34.     score = 0;
  35.     isGameRunning = true;
  36.     createFood();
  37.     scoreDisplay.innerText = `得分: ${score}`;
  38.     main();
  39. }

  40. // 清除画布
  41. function clearCanvas() {
  42.     ctx.fillStyle = "black";
  43.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  44. }

  45. // 绘制蛇
  46. function drawSnake() {
  47.     snake.forEach(snakePart => {
  48.         ctx.fillStyle = 'lightgreen';
  49.         ctx.strokeStyle = 'darkgreen';
  50.         ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  51.         ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  52.     });
  53. }

  54. // 移动蛇
  55. function moveSnake() {
  56.     const head = { x: snake[0].x + dx, y: snake[0].y + dy };
  57.     snake.unshift(head);
  58.     const didEatFood = snake[0].x === foodX && snake[0].y === foodY;
  59.     if (didEatFood) {
  60.         score += 10;
  61.         scoreDisplay.innerText = `得分: ${score}`;
  62.         createFood();
  63.     } else {
  64.         snake.pop();
  65.     }
  66. }

  67. // 随机生成食物位置
  68. function createFood() {
  69.     foodX = Math.floor((Math.random() * canvas.width / 10)) * 10;
  70.     foodY = Math.floor((Math.random() * canvas.height / 10)) * 10;

  71.     // 确保食物不会生成在蛇身体上
  72.     snake.forEach(snakePart => {
  73.         if (snakePart.x === foodX && snakePart.y === foodY) {
  74.             createFood();
  75.         }
  76.     });
  77. }

  78. // 绘制食物
  79. function drawFood() {
  80.     ctx.fillStyle = 'red';
  81.     ctx.strokeStyle = 'darkred';
  82.     ctx.fillRect(foodX, foodY, 10, 10);
  83.     ctx.strokeRect(foodX, foodY, 10, 10);
  84. }

  85. // 检查游戏是否结束
  86. function checkGameOver() {
  87.     for (let i = 4; i < snake.length; i++) {
  88.         const hasCollided = snake[0].x === snake[i].x && snake[0].y === snake[i].y;
  89.         if (hasCollided) {
  90.             isGameRunning = false;
  91.         }
  92.     }

  93.     const hitLeftWall = snake[0].x < 0;
  94.     const hitRightWall = snake[0].x >= canvas.width;
  95.     const hitTopWall = snake[0].y < 0;
  96.     const hitBottomWall = snake[0].y >= canvas.height;

  97.     if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) {
  98.         isGameRunning = false;
  99.     }
  100. }

  101. // 更改方向
  102. document.addEventListener("keydown", changeDirection);

  103. function changeDirection(event) {
  104.     const LEFT_KEY = 37;
  105.     const RIGHT_KEY = 39;
  106.     const UP_KEY = 38;
  107.     const DOWN_KEY = 40;

  108.     const keyPressed = event.keyCode;
  109.     const goingUp = dy === -10;
  110.     const goingDown = dy === 10;
  111.     const goingRight = dx === 10;
  112.     const goingLeft = dx === -10;

  113.     if (keyPressed === LEFT_KEY && !goingRight) {
  114.         dx = -10;
  115.         dy = 0;
  116.     }

  117.     if (keyPressed === UP_KEY && !goingDown) {
  118.         dx = 0;
  119.         dy = -10;
  120.     }

  121.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  122.         dx = 10;
  123.         dy = 0;
  124.     }

  125.     if (keyPressed === DOWN_KEY && !goingUp) {
  126.         dx = 0;
  127.         dy = 10;
  128.     }
  129. }

  130. // 开始按钮点击事件
  131. startButton.addEventListener("click", startGame);
复制代码


将以上三个文件放在同一文件夹中,然后在浏览器中打开`index.html`文件,你就会看到蓝色背景的“开始游戏”按钮,以及正常运行的贪吃蛇游戏。如果还有其他问题,请继续告诉我!
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
17#
 楼主| 发表于 2024-7-17 10:42:18 | 只看该作者
为什么蛇的速度会越来越快?
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
18#
发表于 2024-7-17 10:43:31 | 只看该作者
林奕锦 发表于 2024-07-17 10:42
为什么蛇的速度会越来越快?


蛇的速度在某些情况下会越来越快,可能是由于我们在每个游戏循环中重复设置了`setTimeout`,没有正常清除之前的计时器。为了确保蛇的速度保持一致,我们需要对游戏循环的控制进行一些调整。

下面是修复速度递增问题的解决方案:

### 完整的代码示例

#### `index.html`

确保你的HTML文件结构正确无误:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>贪吃蛇游戏</title>
  6.     <link rel="stylesheet" href="styles.css">
  7. </head>
  8. <body>
  9.     <h1>贪吃蛇游戏</h1>
  10.     <button id="startButton">开始游戏</button>
  11.     <p id="score">得分: 0</p>
  12.     <canvas id="gameCanvas" width="400" height="400"></canvas>

  13.     <script src="snake_game.js"></script>
  14. </body>
  15. </html>
复制代码


#### `styles.css`

更新CSS样式:

  1. /* 设置画布和页面的样式 */
  2. canvas {
  3.     background-color: #0000FF; /* 蓝色背景 */
  4.     display: block;           /* 画布作为块级元素 */
  5.     margin: 0 auto;           /* 居中对齐 */
  6. }

  7. /* 添加一些基本的页面样式 */
  8. body {
  9.     display: flex;
  10.     flex-direction: column;
  11.     align-items: center;
  12.     justify-content: center;
  13.     height: 100vh;
  14.     margin: 0;
  15. }

  16. h1 {
  17.     color: #333;
  18. }

  19. #startButton {
  20.     padding: 10px 20px;
  21.     font-size: 16px;
  22.     margin-bottom: 20px;
  23.     background-color: #0000FF; /* 蓝色背景 */
  24.     color: white;              /* 文字颜色设为白色 */
  25.     border: none;              /* 无边框 */
  26.     border-radius: 5px;        /* 圆角 */
  27.     cursor: pointer;           /* 鼠标悬停时变成手势 */
  28. }

  29. #startButton:hover {
  30.     background-color: #0000cc; /* 鼠标悬停时背景颜色稍微变深 */
  31. }

  32. #score {
  33.     margin-top: 20px;
  34.     font-size: 20px;
  35.     color: #333;
  36. }
复制代码


#### `snake_game.js`

更新JavaScript文件,确保在每个游戏循环中只设置一个`setTimeout`:

  1. // 获取画布并设置上下文
  2. const canvas = document.getElementById('gameCanvas');
  3. const ctx = canvas.getContext('2d');
  4. const startButton = document.getElementById('startButton');
  5. const scoreDisplay = document.getElementById('score');

  6. // 定义初始状态
  7. let snake = [{x: 150, y: 150}]; // 初始蛇身
  8. let foodX;
  9. let foodY;
  10. let dx = 10;
  11. let dy = 0;
  12. let score = 0;
  13. let isGameRunning = false;
  14. let gameInterval;

  15. // 初始化游戏
  16. function startGame() {
  17.     snake = [{x: 150, y: 150}];
  18.     dx = 10;
  19.     dy = 0;
  20.     score = 0;
  21.     isGameRunning = true;
  22.     scoreDisplay.innerText = `得分: ${score}`;

  23.     createFood();
  24.     clearCanvas();
  25.     drawSnake();
  26.     drawFood();
  27.    
  28.     if (gameInterval) {
  29.         clearInterval(gameInterval);
  30.     }
  31.     gameInterval = setInterval(main, 100); // 使用 setInterval 代替 setTimeout
  32. }

  33. // 游戏主循环
  34. function main() {
  35.     if (isGameRunning) {
  36.         clearCanvas();
  37.         moveSnake();
  38.         drawSnake();
  39.         drawFood();
  40.         checkGameOver();
  41.     } else {
  42.         clearInterval(gameInterval);
  43.         alert(`游戏结束!得分: ${score}`);
  44.     }
  45. }

  46. // 清除画布
  47. function clearCanvas() {
  48.     ctx.fillStyle = "#0000FF"; // 即使画布已经是蓝色的,但为了以防万一,还是把背景颜色设置为蓝色
  49.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  50. }

  51. // 绘制蛇
  52. function drawSnake() {
  53.     snake.forEach(snakePart => {
  54.         ctx.fillStyle = 'lightgreen';
  55.         ctx.strokeStyle = 'darkgreen';
  56.         ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  57.         ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  58.     });
  59. }

  60. // 移动蛇
  61. function moveSnake() {
  62.     const head = { x: snake[0].x + dx, y: snake[0].y + dy };
  63.     snake.unshift(head);
  64.     const didEatFood = snake[0].x === foodX && snake[0].y === foodY;
  65.     if (didEatFood) {
  66.         score += 10;
  67.         scoreDisplay.innerText = `得分: ${score}`;
  68.         createFood();
  69.     } else {
  70.         snake.pop();
  71.     }
  72. }

  73. // 随机生成食物位置
  74. function createFood() {
  75.     foodX = Math.floor(Math.random() * canvas.width / 10) * 10;
  76.     foodY = Math.floor(Math.random() * canvas.height / 10) * 10;

  77.     // 确保食物不会生成在蛇身体上
  78.     snake.forEach(function isFoodOnSnake(part) {
  79.         const foodIsOnSnake = part.x === foodX && part.y === foodY;
  80.         if (foodIsOnSnake) createFood();
  81.     });
  82. }

  83. // 绘制食物
  84. function drawFood() {
  85.     ctx.fillStyle = 'red';
  86.     ctx.strokeStyle = 'darkred';
  87.     ctx.fillRect(foodX, foodY, 10, 10);
  88.     ctx.strokeRect(foodX, foodY, 10, 10);
  89. }

  90. // 检查游戏是否结束
  91. function checkGameOver() {
  92.     for (let i = 4; i < snake.length; i++) {
  93.         const hasCollided = snake[i].x === snake[0].x && snake[i].y === snake[0].y;
  94.         if (hasCollided) isGameRunning = false;
  95.     }

  96.     const hitLeftWall = snake[0].x < 0;
  97.     const hitRightWall = snake[0].x >= canvas.width;
  98.     const hitTopWall = snake[0].y < 0;
  99.     const hitBottomWall = snake[0].y >= canvas.height;

  100.     if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) isGameRunning = false;
  101. }

  102. // 更改方向
  103. document.addEventListener("keydown", changeDirection);

  104. function changeDirection(event) {
  105.     const LEFT_KEY = 37;
  106.     const RIGHT_KEY = 39;
  107.     const UP_KEY = 38;
  108.     const DOWN_KEY = 40;

  109.     const keyPressed = event.keyCode;
  110.     const goingUp = dy === -10;
  111.     const goingDown = dy === 10;
  112.     const goingRight = dx === 10;
  113.     const goingLeft = dx === -10;

  114.     if (keyPressed === LEFT_KEY && !goingRight) {
  115.         dx = -10;
  116.         dy = 0;
  117.     }
  118.     if (keyPressed === UP_KEY && !goingDown) {
  119.         dx = 0;
  120.         dy = -10;
  121.     }
  122.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  123.         dx = 10;
  124.         dy = 0;
  125.     }
  126.     if (keyPressed === DOWN_KEY && !goingUp) {
  127.         dx = 0;
  128.         dy = 10;
  129.     }
  130. }

  131. // 开始按钮点击事件
  132. startButton.addEventListener("click", startGame);
复制代码


通过使用 `setInterval` 替换 `setTimeout`,并确保在启动新的循环之前停止已经存在的循环,我们可以确保蛇的速度保持一致,不会不断增加。你可以将以上三个文件放在同一文件夹中,然后在浏览器中打开 `index.html` 来测试游戏。如果还有其他问题,请继续告诉我!
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
19#
 楼主| 发表于 2024-7-17 10:45:31 | 只看该作者
请帮我把代码中所有的中文改成英文
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
20#
发表于 2024-7-17 10:46:42 | 只看该作者
林奕锦 发表于 2024-07-17 10:45
请帮我把代码中所有的中文改成英文


好的!为了确保代码的可读性和一致性,我们可以将所有中文注释和文本替换为英文。以下是更新后的文件。

### 更新后的完整代码

#### `index.html`

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Snake Game</title>
  7.     <link rel="stylesheet" href="styles.css">
  8. </head>
  9. <body>
  10.     <h1>Snake Game</h1>
  11.     <button id="startButton">Start Game</button>
  12.     <canvas id="gameCanvas" width="400" height="400"></canvas>
  13.     <p id="score">Score: 0</p>
  14.     <script src="snake_game.js"></script>
  15. </body>
  16. </html>
复制代码


#### `styles.css`

  1. /* Set canvas and page styles */
  2. canvas {
  3.     background-color: #0000FF; /* Blue background */
  4.     display: block;           /* Display canvas as block element */
  5.     margin: 0 auto;           /* Center align */
  6. }

  7. /* Add some basic page styles */
  8. body {
  9.     display: flex;
  10.     flex-direction: column;
  11.     align-items: center;
  12.     justify-content: center;
  13.     height: 100vh;
  14.     margin: 0;
  15. }

  16. h1 {
  17.     color: #333;
  18. }

  19. #startButton {
  20.     padding: 10px 20px;
  21.     font-size: 16px;
  22.     margin-bottom: 20px;
  23.     background-color: #0000FF; /* Blue background */
  24.     color: white;              /* Text color white */
  25.     border: none;              /* No border */
  26.     border-radius: 5px;        /* Rounded corners */
  27.     cursor: pointer;           /* Pointer cursor on hover */
  28. }

  29. #startButton:hover {
  30.     background-color: #0000cc; /* Darker blue on hover */
  31. }

  32. #score {
  33.     margin-top: 20px;
  34.     font-size: 20px;
  35.     color: #333;
  36. }
复制代码


#### `snake_game.js`

  1. // Get the canvas and set its context
  2. const canvas = document.getElementById('gameCanvas');
  3. const ctx = canvas.getContext('2d');
  4. const startButton = document.getElementById('startButton');
  5. const scoreDisplay = document.getElementById('score');

  6. // Define initial state
  7. let snake = [{ x: 200, y: 200 }]; // Initial snake body
  8. let foodX;
  9. let foodY;
  10. let dx = 10;
  11. let dy = 0;
  12. let score = 0;
  13. let isGameRunning = false;
  14. let gameInterval;

  15. // Initialize the game
  16. function startGame() {
  17.     snake = [{ x: 200, y: 200 }];
  18.     dx = 10;
  19.     dy = 0;
  20.     score = 0;
  21.     isGameRunning = true;
  22.     scoreDisplay.innerText = `Score: ${score}`;

  23.     createFood();
  24.     clearCanvas();
  25.     drawSnake();
  26.     drawFood();

  27.     if (gameInterval) {
  28.         clearInterval(gameInterval);
  29.     }
  30.     gameInterval = setInterval(main, 100); // Use setInterval instead of setTimeout
  31. }

  32. // Main game loop
  33. function main() {
  34.     if (isGameRunning) {
  35.         clearCanvas();
  36.         moveSnake();
  37.         drawSnake();
  38.         drawFood();
  39.         checkGameOver();
  40.     } else {
  41.         clearInterval(gameInterval);
  42.         alert(`Game Over! Score: ${score}`);
  43.     }
  44. }

  45. // Clear the canvas
  46. function clearCanvas() {
  47.     ctx.fillStyle = "#0000FF"; // Ensure canvas background is blue
  48.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  49. }

  50. // Draw the snake
  51. function drawSnake() {
  52.     snake.forEach(snakePart => {
  53.         ctx.fillStyle = 'lightgreen';
  54.         ctx.strokeStyle = 'darkgreen';
  55.         ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  56.         ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  57.     });
  58. }

  59. // Move the snake
  60. function moveSnake() {
  61.     const head = { x: snake[0].x + dx, y: snake[0].y + dy };
  62.     snake.unshift(head);
  63.     const didEatFood = head.x === foodX && head.y === foodY;
  64.     if (didEatFood) {
  65.         score += 10;
  66.         scoreDisplay.innerText = `Score: ${score}`;
  67.         createFood();
  68.     } else {
  69.         snake.pop();
  70.     }
  71. }

  72. // Randomly generate food position
  73. function createFood() {
  74.     foodX = Math.floor(Math.random() * canvas.width / 10) * 10;
  75.     foodY = Math.floor(Math.random() * canvas.height / 10) * 10;

  76.     // Ensure food does not appear on the snake
  77.     snake.forEach(function isFoodOnSnake(part) {
  78.         const foodIsOnSnake = part.x === foodX && part.y === foodY;
  79.         if (foodIsOnSnake) createFood();
  80.     });
  81. }

  82. // Draw the food
  83. function drawFood() {
  84.     ctx.fillStyle = 'red';
  85.     ctx.strokeStyle = 'darkred';
  86.     ctx.fillRect(foodX, foodY, 10, 10);
  87.     ctx.strokeRect(foodX, foodY, 10, 10);
  88. }

  89. // Check if the game is over
  90. function checkGameOver() {
  91.     for (let i = 4; i < snake.length; i++) {
  92.         const hasCollided = snake[i].x === snake[0].x && snake[i].y === snake[0].y;
  93.         if (hasCollided) isGameRunning = false;
  94.     }

  95.     const hitLeftWall = snake[0].x < 0;
  96.     const hitRightWall = snake[0].x >= canvas.width;
  97.     const hitTopWall = snake[0].y < 0;
  98.     const hitBottomWall = snake[0].y >= canvas.height;

  99.     if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) isGameRunning = false;
  100. }

  101. // Change direction
  102. document.addEventListener('keydown', changeDirection);

  103. function changeDirection(event) {
  104.     const LEFT_KEY = 37;
  105.     const RIGHT_KEY = 39;
  106.     const UP_KEY = 38;
  107.     const DOWN_KEY = 40;

  108.     const keyPressed = event.keyCode;
  109.     const goingUp = dy === -10;
  110.     const goingDown = dy === 10;
  111.     const goingRight = dx === 10;
  112.     const goingLeft = dx === -10;

  113.     if (keyPressed === LEFT_KEY && !goingRight) {
  114.         dx = -10;
  115.         dy = 0;
  116.     }
  117.     if (keyPressed === UP_KEY && !goingDown) {
  118.         dx = 0;
  119.         dy = -10;
  120.     }
  121.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  122.         dx = 10;
  123.         dy = 0;
  124.     }
  125.     if (keyPressed === DOWN_KEY && !goingUp) {
  126.         dx = 0;
  127.         dy = 10;
  128.     }
  129. }

  130. // Start button click event
  131. startButton.addEventListener('click', startGame);
复制代码


将以上三个文件放在同一文件夹中,然后在浏览器中打开`index.html`文件,你就会看到英文版的贪吃蛇游戏。如果还有其他问题,请继续告诉我!
回复 支持 反对

使用道具 举报

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

本版积分规则

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