科学教育

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

林奕锦1

[复制链接]

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
21#
 楼主| 发表于 2024-7-17 11:02:58 | 只看该作者
请帮我将背景改为图片背景
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
22#
发表于 2024-7-17 11:03:37 | 只看该作者
林奕锦 发表于 2024-07-17 11:02
请帮我将背景改为图片背景


好的!我们可以将游戏画布和整个网页的背景修改为图片背景。我们将通过CSS来实现这一目标。假设我们有一张图片文件,名为`background.jpg`,我们将其设置为背景。

### 更新后的完整代码

#### `index.html`

确保你的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.     <div id="score">Score: 0</div>
  14.     <script src="snake_game.js"></script>
  15. </body>
  16. </html>
复制代码


#### `styles.css`

在CSS文件中,我们将设置背景图片,并对画布添加样式以确保其背景透明,能够显示出背景图片。

  1. /* Set canvas and page styles */
  2. body {
  3.     display: flex;
  4.     flex-direction: column;
  5.     align-items: center;
  6.     justify-content: center;
  7.     height: 100vh;
  8.     margin: 0;
  9.     background: url('background.jpg') no-repeat center center fixed; /* Background image */
  10.     background-size: cover; /* Ensure the background covers the entire page */
  11. }

  12. h1 {
  13.     color: #ffffff; /* White text color for better contrast */
  14. }

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

  25. #startButton:hover {
  26.     background-color: #0000cc; /* Darker blue on hover */
  27. }

  28. #gameCanvas {
  29.     background-color: transparent; /* Transparent background to show the image behind */
  30. }

  31. #score {
  32.     margin-top: 20px;
  33.     font-size: 20px;
  34.     color: #ffffff; /* White text color for better contrast */
  35. }
复制代码


#### `snake_game.js`

JavaScript代码无需修改,保持之前的内容即可。

  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.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas completely
  48. }

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

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

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

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

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

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

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

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

  100. // Change direction
  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. // Start button click event
  130. startButton.addEventListener('click', startGame);
复制代码


### 总结

将 `background.jpg` 图片放在与这三个文件相同的目录下,然后在浏览器中打开 `index.html` 文件,你就会看到带有图片背景的贪吃蛇游戏。如果你有任何其他问题或进一步需求,请继续告诉我!
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
23#
 楼主| 发表于 2024-7-17 11:22:05 | 只看该作者
请将画布改为透明背景
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
24#
发表于 2024-7-17 11:22:54 | 只看该作者
林奕锦 发表于 2024-07-17 11:22
请将画布改为透明背景


好的,将画布改为透明背景可以使其与背景图片更好地融合。我们只需要调整CSS和JavaScript代码中的一些内容,确保画布的背景是透明的。

### 更新后的完整代码

#### `index.html`

以下是更新后的HTML文件内容:



   
   
    Snake Game
   



    Snake Game
    Start Game
   
    Score: 0
   
   

   


#### `styles.css`

在CSS中,我们将设置画布的背景为透明,并对整个网页设置背景图片:

  1. /* Set canvas and page styles */
  2. body {
  3.     display: flex;
  4.     flex-direction: column;
  5.     align-items: center;
  6.     justify-content: center;
  7.     height: 100vh;
  8.     margin: 0;
  9.     background: url('background.jpg') no-repeat center center fixed; /* Background image */
  10.     background-size: cover; /* Ensure the background covers the entire page */
  11. }

  12. h1 {
  13.     color: #ffffff; /* White text color for better contrast */
  14. }

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

  25. #startButton:hover {
  26.     background-color: #0000cc; /* Darker blue on hover */
  27. }

  28. #gameCanvas {
  29.     background-color: transparent; /* Transparent background to show the image behind */
  30. }

  31. #score {
  32.     margin-top: 20px;
  33.     font-size: 20px;
  34.     color: #ffffff; /* White text color for better contrast */
  35. }
复制代码


#### `snake_game.js`

在JavaScript文件中,我们确保清除画布时不覆盖背景:

  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: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }, { x: 120, y: 150 }, { x: 110, 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. // Initialize the game
  16. function startGame() {
  17.     snake = [{ x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }, { x: 120, y: 150 }, { x: 110, y: 150 }];
  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.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas completely
  48. }

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

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

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

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

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

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

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

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

  100. // Change direction
  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. // Start button click event
  130. startButton.addEventListener('click', startGame);
复制代码


### 总结

将 `background.jpg` 图片放在与这三个文件相同的目录下,然后在浏览器中打开 `index.html` 文件,你就会看到带有图片背景的贪吃蛇游戏,画布背景将是透明的,使其与背景图片更好地融合。如果你有任何其他问题或进一步需求,请继续告诉我!
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
25#
 楼主| 发表于 2024-7-17 11:31:10 | 只看该作者
请帮我把背景图片改小一点
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
26#
 楼主| 发表于 2024-7-17 11:31:40 | 只看该作者
请帮我把游戏边界绘制出来
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
27#
 楼主| 发表于 2024-7-17 11:37:52 | 只看该作者
请帮我把游戏边界显示出来,并告诉我修改位置
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
28#
 楼主| 发表于 2024-7-17 11:48:29 | 只看该作者
请帮我把画布改为白色
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
29#
 楼主| 发表于 2024-7-18 12:43:50 | 只看该作者
在C++中显示 [错误] bits/stdc++.h: No such file or directory 是怎么回事?
回复 支持 反对

使用道具 举报

8

主题

62

帖子

184

积分

注册会员

Rank: 2

积分
184
30#
 楼主| 发表于 2024-7-19 13:07:21 | 只看该作者
kaia 发表于 2024-7-17 10:46
好的!为了确保代码的可读性和一致性,我们可以将所有中文注释和文本替换为英文。以下是更新后的文件。

...

请帮我将注释改为中文
回复 支持 反对

使用道具 举报

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

本版积分规则

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