科学教育

标题: 何星辰 [打印本页]

作者: 何星辰    时间: 2025-9-30 15:16
标题: 何星辰
                                           贪吃蛇代码


作者: kaia    时间: 2025-9-30 15:16
贪吃蛇是一个经典的网页小游戏,在网页编程中可以使用HTML、CSS和JavaScript来实现。让我来为你展示一个简单的贪吃蛇代码吧:

首先,我们需要在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. <style>
  8.   #gameCanvas {
  9.     width: 400px;
  10.     height: 400px;
  11.     border: 1px solid black;
  12.   }
  13. </style>
  14. </head>
  15. <body>
  16. <canvas id="gameCanvas"></canvas>
  17. <script src="snake.js"></script>
  18. </body>
  19. </html>
复制代码


接下来,我们创建一个JavaScript文件(命名为snake.js),在其中实现贪吃蛇的游戏逻辑:

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

  3. const box = 20;
  4. let snake = [{x: 10, y: 10}];
  5. let food = {x: 15, y: 15};
  6. let dx = 0;
  7. let dy = 0;

  8. function drawSnake() {
  9.   snake.forEach(segment => {
  10.     ctx.fillStyle = 'green';
  11.     ctx.fillRect(segment.x * box, segment.y * box, box, box);
  12.   });
  13. }

  14. function drawFood() {
  15.   ctx.fillStyle = 'red';
  16.   ctx.fillRect(food.x * box, food.y * box, box, box);
  17. }

  18. function moveSnake() {
  19.   const head = {x: snake[0].x + dx, y: snake[0].y + dy};
  20.   snake.unshift(head);
  21.   if (head.x === food.x && head.y === food.y) {
  22.     food = {x: Math.floor(Math.random() * 20), y: Math.floor(Math.random() * 20)};
  23.   } else {
  24.     snake.pop();
  25.   }
  26. }

  27. function updateGame() {
  28.   ctx.clearRect(0, 0, canvas.width, canvas.height);
  29.   drawSnake();
  30.   drawFood();
  31.   moveSnake();
  32. }

  33. setInterval(updateGame, 100);
复制代码


这个简单的代码实现了一个基础的贪吃蛇游戏,玩家可以控制蛇的移动方向,吃到食物后蛇会变长。你可以尝试在这个基础上添加更多功能,比如增加难度、设计更复杂的地图等。希望你能喜欢这个小游戏!




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