科学教育

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

贪吃蛇代码

[复制链接]

5

主题

8

帖子

74

积分

注册会员

Rank: 2

积分
74
跳转到指定楼层
楼主
发表于 2024-7-17 11:20:57 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
请生成一个贪吃蛇游戏的代码
谁也不能阻止我发疯!
习惯一个人有时候会控制不住自己发癫
回复

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
沙发
发表于 2024-7-17 11:21:24 | 只看该作者
当然可以!贪吃蛇游戏是一个很有趣的项目,我们可以用HTML、CSS和JavaScript来实现。下面我会一步一步地给你讲解每一部分代码。

### 1. 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>贪吃蛇游戏</title>
  7.     <link rel="stylesheet" href="style.css">
  8. </head>
  9. <body>
  10.     <canvas id="gameCanvas" width="400" height="400"></canvas>
  11.     <script src="script.js"></script>
  12. </body>
  13. </html>
复制代码


### 2. CSS 部分
接下来,我们写一些简单的CSS来让画布看起来更好看一些。

  1. /* style.css */
  2. body {
  3.     display: flex;
  4.     justify-content: center;
  5.     align-items: center;
  6.     height: 100vh;
  7.     margin: 0;
  8.     background-color: #f0f0f0;
  9. }
  10. canvas {
  11.     border: 1px solid #000;
  12. }
复制代码


### 3. JavaScript 部分
最后,这是我们的主要部分,也就是贪吃蛇的逻辑部分。

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

  4. // 设置常量
  5. const unit = 20;
  6. let snake = [{ x: 80, y: 80 }];
  7. let food = { x: 160, y: 160 };
  8. let direction = 'RIGHT';
  9. let changingDirection = false;
  10. let score = 0;

  11. // 控制方向
  12. document.addEventListener('keydown', changeDirection);

  13. function main() {
  14.     if (checkGameOver()) return;

  15.     changingDirection = false;
  16.     setTimeout(() => {
  17.         clearCanvas();
  18.         drawFood();
  19.         moveSnake();
  20.         drawSnake();
  21.         main();
  22.     }, 100);
  23. }

  24. function clearCanvas() {
  25.     ctx.fillStyle = 'white';
  26.     ctx.fillRect(0, 0, canvas.width, canvas.height);
  27. }

  28. function drawSnake() {
  29.     ctx.fillStyle = 'lightgreen';
  30.     ctx.strokeStyle = 'darkgreen';

  31.     snake.forEach(segment => {
  32.         ctx.fillRect(segment.x, segment.y, unit, unit);
  33.         ctx.strokeRect(segment.x, segment.y, unit, unit);
  34.     });
  35. }

  36. function drawFood() {
  37.     ctx.fillStyle = 'red';
  38.     ctx.fillRect(food.x, food.y, unit, unit);
  39. }

  40. function moveSnake() {
  41.     const head = { x: snake[0].x, y: snake[0].y };

  42.     switch (direction) {
  43.         case 'UP':
  44.             head.y -= unit;
  45.             break;
  46.         case 'DOWN':
  47.             head.y += unit;
  48.             break;
  49.         case 'LEFT':
  50.             head.x -= unit;
  51.             break;
  52.         case 'RIGHT':
  53.             head.x += unit;
  54.             break;
  55.     }

  56.     snake.unshift(head);

  57.     if (head.x === food.x && head.y === food.y) {
  58.         score += 10;
  59.         generateFood();
  60.     } else {
  61.         snake.pop();
  62.     }
  63. }

  64. function changeDirection(event) {
  65.     if (changingDirection) return;
  66.     changingDirection = true;

  67.     const keyPressed = event.keyCode;
  68.     const UP_KEY = 38;
  69.     const DOWN_KEY = 40;
  70.     const LEFT_KEY = 37;
  71.     const RIGHT_KEY = 39;

  72.     const goingUp = direction === 'UP';
  73.     const goingDown = direction === 'DOWN';
  74.     const goingRight = direction === 'RIGHT';
  75.     const goingLeft = direction === 'LEFT';

  76.     if (keyPressed === UP_KEY && !goingDown) {
  77.         direction = 'UP';
  78.     }
  79.     if (keyPressed === DOWN_KEY && !goingUp) {
  80.         direction = 'DOWN';
  81.     }
  82.     if (keyPressed === LEFT_KEY && !goingRight) {
  83.         direction = 'LEFT';
  84.     }
  85.     if (keyPressed === RIGHT_KEY && !goingLeft) {
  86.         direction = 'RIGHT';
  87.     }
  88. }

  89. function checkGameOver() {
  90.     for (let i = 4; i < snake.length; i++) {
  91.         if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) return true;
  92.     }

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

  97.     return hitLeftWall || hitRightWall || hitToptWall || hitBottomWall;
  98. }

  99. function generateFood() {
  100.     food.x = Math.floor(Math.random() * canvas.width / unit) * unit;
  101.     food.y = Math.floor(Math.random() * canvas.height / unit) * unit;

  102.     snake.forEach(segment => {
  103.         if (segment.x === food.x && segment.y === food.y) {
  104.             generateFood();
  105.         }
  106.     });
  107. }

  108. main();
复制代码


### 总结
1. **HTML**定义了画布,用来显示游戏。
2. **CSS**简单地美化了画布。
3. **JavaScript**负责游戏的逻辑,包括蛇的移动、食物的生成、碰撞检测等。

你可以将这些代码分别保存到不同的文件中:`index.html`、`style.css`、`script.js`。打开`index.html`,就能在浏览器中玩这个简单的贪吃蛇游戏了!

希望你能喜欢这个游戏,祝你编程愉快!如果有任何问题,请随时问我哦!
回复 支持 反对

使用道具 举报

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

本版积分规则

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