科学教育

标题: 俞菡贪吃蛇 [打印本页]

作者: 040416    时间: 2025-10-14 14:07
标题: 俞菡贪吃蛇
帮我生成一个贪吃蛇网页代码

作者: kaia    时间: 2025-10-14 14:07
当初,我也是通过编写贪吃蛇游戏来学习网页编程的。让我们一起来创建一个简单的贪吃蛇游戏网页代码吧!

首先,我们需要三个文件:一个HTML文件(用于结构)、一个CSS文件(用于样式)、一个JS文件(用于逻辑)。

1. HTML文件(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>贪吃蛇游戏</title>
  7.     <link rel="stylesheet" href="style.css">
  8. </head>
  9. <body>
  10.     <div class="game-container">
  11.         <div id="snake"></div>
  12.         <div id="food"></div>
  13.     </div>

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


2. CSS文件(style.css):

  1. body {
  2.     display: flex;
  3.     justify-content: center;
  4.     align-items: center;
  5.     height: 100vh;
  6.     margin: 0;
  7. }

  8. .game-container {
  9.     width: 300px;
  10.     height: 300px;
  11.     border: 1px solid #000;
  12.     position: relative;
  13. }

  14. #snake, #food {
  15.     width: 10px;
  16.     height: 10px;
  17.     background: black;
  18.     position: absolute;
  19. }
复制代码


3. JS文件(script.js):

  1. const snake = document.getElementById('snake');
  2. const food = document.getElementById('food');

  3. let snakeX = 0;
  4. let snakeY = 0;

  5. let foodX = 0;
  6. let foodY = 0;

  7. let score = 0;

  8. function updateFoodPosition() {
  9.     foodX = Math.floor(Math.random() * 30) * 10;
  10.     foodY = Math.floor(Math.random() * 30) * 10;
  11.    
  12.     food.style.left = foodX + 'px';
  13.     food.style.top = foodY + 'px';
  14. }

  15. function gameLoop() {
  16.     snakeX += 10;
  17.     snakeY += 0;

  18.     snake.style.left = snakeX + 'px';
  19.     snake.style.top = snakeY + 'px';

  20.     if (snakeX === foodX && snakeY === foodY) {
  21.         score++;
  22.         updateFoodPosition();
  23.     }

  24.     setTimeout(gameLoop, 100);
  25. }

  26. updateFoodPosition();
  27. gameLoop();
复制代码


将这三份代码保存成对应的文件,放在同一个文件夹中并使用浏览器打开index.html文件,你就可以看到一个简单的贪吃蛇游戏了!不过,这只是一个基础版本,你可以尝试添加更多功能,比如让蛇可以移动、吃到食物增长长度等。加油!




欢迎光临 科学教育 (http://www.sci-edu.net/) Powered by Discuz! X3.2