科学教育

搜索
查看: 697|回复: 1
打印 上一主题 下一主题

陈宇硕贪吃蛇

[复制链接]

1

主题

1

帖子

9

积分

新手上路

Rank: 1

积分
9
跳转到指定楼层
楼主
发表于 2025-9-30 15:27:22 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
帮我生成一个贪吃蛇游戏
回复

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
沙发
发表于 2025-9-30 15:27:30 | 只看该作者
当我们创建一个贪吃蛇游戏时,需要用到HTML、CSS和JavaScript。在HTML中,我们会创建一个画布(<canvas>元素),在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.     canvas {
  9.       border: 1px solid #333;
  10.     }
  11.   </style>
  12. </head>
  13. <body>
  14.   <canvas id="gameCanvas" width="400" height="400"></canvas>
  15.   <script src="snake.js"></script>
  16. </body>
  17. </html>
复制代码


然后,在同一目录下创建一个名为`snake.js`的JavaScript文件,并添加以下代码:

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

  3. const box = 20;
  4. let snake = [{ x: 10 * box, y: 10 * box }];
  5. let food = { x: Math.floor(Math.random() * 19) * box, y: Math.floor(Math.random() * 19) * box };
  6. let direction = 'right';

  7. function draw() {
  8.   ctx.clearRect(0, 0, canvas.width, canvas.height);

  9.   // 绘制蛇身
  10.   ctx.fillStyle = 'green';
  11.   snake.forEach(p => ctx.fillRect(p.x, p.y, box, box));

  12.   // 绘制食物
  13.   ctx.fillStyle = 'red';
  14.   ctx.fillRect(food.x, food.y, box, box);

  15.   // 移动蛇头
  16.   let newX = snake[0].x;
  17.   let newY = snake[0].y;

  18.   if (direction === 'left') newX -= box;
  19.   if (direction === 'right') newX += box;
  20.   if (direction === 'up') newY -= box;
  21.   if (direction === 'down') newY += box;

  22.   // 判断是否吃到食物
  23.   if (newX === food.x && newY === food.y) {
  24.     snake.unshift({ x: newX, y: newY });
  25.     food = { x: Math.floor(Math.random() * 19) * box, y: Math.floor(Math.random() * 19) * box };
  26.   } else {
  27.     snake.pop();
  28.     snake.unshift({ x: newX, y: newY });
  29.   }
  30. }

  31. function changeDirection(event) {
  32.   const key = event.keyCode;
  33.   if (key === 37 && direction !== 'right') direction = 'left';
  34.   if (key === 38 && direction !== 'down') direction = 'up';
  35.   if (key === 39 && direction !== 'left') direction = 'right';
  36.   if (key === 40 && direction !== 'up') direction = 'down';
  37. }

  38. document.addEventListener('keydown', changeDirection);

  39. setInterval(draw, 100);
复制代码


这段代码实现了基本的贪吃蛇游戏功能,包括蛇的移动、吃食物等。你可以打开浏览器,加载HTML文件,就可以看到生成的贪吃蛇游戏了。尝试控制蛇的方向,让蛇吃到食物,看看能得多少分吧!
回复 支持 反对

使用道具 举报

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

本版积分规则

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