科学教育

标题: 苏洛萱贪吃蛇 [打印本页]

作者: 苏洛萱    时间: 2025-11-4 09:38
标题: 苏洛萱贪吃蛇
帮我生成一个贪吃蛇代码

作者: kaia    时间: 2025-11-4 09:38
当然可以!贪吃蛇是一个经典的小游戏,让我们一起来编写一个简单的贪吃蛇代码吧!

首先,我们来定义一些基本的变量:
- `canvas`:画布,用来显示游戏
- `ctx`:画笔,用来在画布上绘制图形
- `snake`:贪吃蛇的身体,存储蛇身每一节的坐标
- `food`:食物的坐标
- `direction`:贪吃蛇的移动方向

接下来,我们编写一些基本的函数:
1. `drawSnake`:绘制贪吃蛇的身体
2. `drawFood`:绘制食物
3. `move`:移动贪吃蛇
4. `main`:主函数,用来初始化游戏并开始游戏循环

最后,让我们把这些代码组合起来:

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

  3. const snake = [
  4.   { x: 10, y: 10 },
  5.   { x: 10, y: 11 },
  6.   { x: 10, y: 12 }
  7. ];

  8. let food = { x: 15, y: 15 };
  9. let direction = "right";

  10. function drawSnake() {
  11.   ctx.fillStyle = "green";
  12.   snake.forEach(segment => {
  13.     ctx.fillRect(segment.x * 10, segment.y * 10, 10, 10);
  14.   });
  15. }

  16. function drawFood() {
  17.   ctx.fillStyle = "red";
  18.   ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
  19. }

  20. function move() {
  21.   const head = { x: snake[0].x, y: snake[0].y };

  22.   if (direction === "up") {
  23.     head.y--;
  24.   } else if (direction === "down") {
  25.     head.y++;
  26.   } else if (direction === "left") {
  27.     head.x--;
  28.   } else if (direction === "right") {
  29.     head.x++;
  30.   }

  31.   snake.unshift(head);

  32.   if (head.x === food.x && head.y === food.y) {
  33.     // 如果吃到食物,则生成新的食物
  34.     food = {
  35.       x: Math.floor(Math.random() * canvas.width / 10),
  36.       y: Math.floor(Math.random() * canvas.height / 10)
  37.     };
  38.   } else {
  39.     snake.pop();
  40.   }
  41. }

  42. function main() {
  43.   setInterval(() => {
  44.     ctx.clearRect(0, 0, canvas.width, canvas.height);

  45.     drawSnake();
  46.     drawFood();
  47.     move();
  48.   }, 100);
  49. }

  50. main();
复制代码


在这个代码中,我们定义了一个简单的贪吃蛇游戏,包括贪吃蛇的移动、吃食物等功能。你可以在网页上创建一个画布元素,并将其id设置为"gameCanvas",然后将以上代码粘贴到网页的<script>标签中就可以运行这个贪吃蛇游戏了。希望你玩得开心!如果有任何问题,都可以随时问我哦!
作者: 苏洛萱    时间: 2025-11-4 09:42
添加更多的CSS样式。
作者: kaia    时间: 2025-11-4 09:42
苏洛萱 发表于 2025-11-04 09:42
添加更多的CSS样式。


当你想要为贪吃蛇游戏添加更多的CSS样式时,你可以通过修改画布的样式、贪吃蛇身体的颜色、食物的颜色等来美化游戏界面。让我们来进行一些简单的CSS样式调整:

首先,我们可以设置画布的背景颜色和边框样式:

  1. #gameCanvas {
  2.   background-color: #f0f0f0;
  3.   border: 5px solid #333;
  4. }
复制代码


然后,我们可以设置贪吃蛇的身体颜色和食物的颜色:

  1. // 在drawSnake函数中设置贪吃蛇的身体颜色
  2. ctx.fillStyle = "darkgreen";

  3. // 在drawFood函数中设置食物的颜色
  4. ctx.fillStyle = "tomato";
复制代码


最后,如果你想要对游戏界面进行更多的样式调整,可以根据自己的喜好在CSS中添加更多样式规则,比如修改贪吃蛇身体的形状、食物的样式等。

希望这些简单的CSS样式调整能够使你的贪吃蛇游戏看起来更加炫酷!如果有任何其他想法或问题,随时告诉我哦!




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