科学教育

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

二胎太325

[复制链接]

8

主题

13

帖子

51

积分

注册会员

Rank: 2

积分
51
跳转到指定楼层
楼主
发表于 2026-1-6 09:45:58 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>飞机大战小游戏</title>
<style>
  body {
    margin: 0;
    overflow: hidden;
    background: black;
    color: white;
    font-family: "微软雅黑", sans-serif;
  }
  #gameCanvas {
    background: #111;
    display: block;
    margin: auto;
    border: 2px solid white;
  }
  #scoreboard {
    text-align:center;
    margin-top: 10px;
  }
</style>
</head>
<body>

<canvas id="gameCanvas" width="400" height="600"></canvas>
<div id="scoreboard">
  血量:<span id="hp">3</span> &nbsp;&nbsp; 分数:<span id="score">0</span>
</div>

<script>
  const canvas = document.getElementById("gameCanvas");
  const ctx = canvas.getContext("2d");

  const planeWidth = 40;
  const planeHeight = 40;
  let planeX = (canvas.width - planeWidth) / 2;
  const planeY = canvas.height - planeHeight - 10;
  let hp = 3;
  let score = 0;

  // 敌机数组
  let enemies = [];

  // 子弹数组
  let bullets = [];

  // 控制左右移动
  let moveLeft = false;
  let moveRight = false;

  // 监听键盘按下
  window.addEventListener("keydown", function(e) {
    if (e.key === "a" || e.key === "A") moveLeft = true;
    if (e.key === "d" || e.key === "D") moveRight = true;
  });

  // 监听松开键盘
  window.addEventListener("keyup", function(e) {
    if (e.key === "a" || e.key === "A") moveLeft = false;
    if (e.key === "d" || e.key === "D") moveRight = false;
    if (e.key === " ") shoot();
  });

  // 画飞机
  function drawPlane() {
    ctx.fillStyle = "lightblue";
    ctx.beginPath();
    // 画三角形代表飞机
    ctx.moveTo(planeX + planeWidth/2, planeY);
    ctx.lineTo(planeX, planeY + planeHeight);
    ctx.lineTo(planeX + planeWidth, planeY + planeHeight);
    ctx.closePath();
    ctx.fill();
  }

  // 生成敌机
  function createEnemy() {
    let x = Math.random() * (canvas.width - 30);
    enemies.push({x: x, y: -30, width: 30, height: 30});
  }

  // 画敌机
  function drawEnemies() {
    ctx.fillStyle = "red";
    enemies.forEach(enemy => {
      ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
    });
  }

  // 移动敌机
  function moveEnemies() {
    enemies.forEach(enemy => {
      enemy.y += 2;  // 敌机向下移动速度
    });
    // 删除超出画面底部的敌机
    enemies = enemies.filter(enemy => enemy.y < canvas.height);
  }

  // 发射子弹
  function shoot() {
    bullets.push({x: planeX + planeWidth / 2 - 2.5, y: planeY, width:5, height:10});
  }

  // 画子弹
  function drawBullets() {
    ctx.fillStyle = "yellow";
    bullets.forEach(bullet => {
      ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
    });
  }

  // 移动子弹
  function moveBullets() {
    bullets.forEach(bullet => {
      bullet.y -= 5;  // 子弹向上飞
    });
    // 删除飞出画面的子弹
    bullets = bullets.filter(bullet => bullet.y + bullet.height > 0);
  }

  // 碰撞检测函数,检测两个矩形是否重叠
  function isColliding(rect1, rect2) {
    return !(
      rect1.x > rect2.x + rect2.width ||
      rect1.x + rect1.width < rect2.x ||
      rect1.y > rect2.y + rect2.height ||
      rect1.y + rect1.height < rect2.y
    );
  }

  // 检查子弹和敌机碰撞
  function checkBulletEnemyCollision() {
    for (let i = bullets.length -1; i>=0; i--) {
      let b = bullets[i];
      for (let j = enemies.length -1; j>=0; j--) {
        let e = enemies[j];
        if (isColliding(b, e)) {
          // 消灭敌机和子弹
          bullets.splice(i,1);
          enemies.splice(j,1);
          score++;
          updateScore();
          break;
        }
      }
    }
  }

  // 检查敌机和飞机碰撞
  function checkEnemyPlaneCollision() {
    for (let i = enemies.length -1; i>=0; i--) {
      let e = enemies[i];
      let planeRect = {x: planeX, y: planeY, width: planeWidth, height: planeHeight};
      if (isColliding(e, planeRect)) {
        enemies.splice(i,1);
        hp--;
        updateHP();
        if (hp <= 0) {
          alert("游戏结束!你的得分是:" + score);
          resetGame();
        }
      }
    }
  }

  // 更新血量显示
  function updateHP() {
    document.getElementById("hp").textContent = hp;
  }

  // 更新分数显示
  function updateScore() {
    document.getElementById("score").textContent = score;
  }

  // 重置游戏
  function resetGame() {
    hp = 3;
    score = 0;
    enemies = [];
    bullets = [];
    planeX = (canvas.width - planeWidth) / 2;
    updateHP();
    updateScore();
  }

  // 游戏主循环
  function gameLoop() {
    ctx.clearRect(0,0,canvas.width,canvas.height);

    // 移动飞机
    if (moveLeft && planeX > 0) planeX -= 5;
    if (moveRight && planeX < canvas.width - planeWidth) planeX += 5;

    drawPlane();

    // 敌机出现概率控制(差不多每30帧一个)
    if (Math.random() < 0.03) createEnemy();

    moveEnemies();
    drawEnemies();

    moveBullets();
    drawBullets();

    checkBulletEnemyCollision();
    checkEnemyPlaneCollision();

    requestAnimationFrame(gameLoop);
  }

  // 开始游戏
  updateHP();
  updateScore();
  gameLoop();
</script>

<p style="text-align:center; color:#ccc; margin-top:10px;">
  操作提示:<br />
  按A键向左移动,D键向右移动,空格键发射子弹。
</p>

</body>
</html>
帮我把乱码变成文字

回复

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
沙发
发表于 2026-1-6 09:46:18 | 只看该作者
你好!你提供的代码里有一些“乱码”其实是因为JavaScript中数组没有写完整,还有一些地方拼写和逻辑有点小问题。我帮你把这些地方改成正确的代码,并且用文字描述每个部分的意思,好让你更容易懂。

我先给你一个修正好的版本,然后再讲解关键点:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.   <meta charset="UTF-8" />
  5.   <title>飞机大战小游戏</title>
  6.   <style>
  7.     body {
  8.       margin: 0;
  9.       overflow: hidden;
  10.       background: black;
  11.       color: white;
  12.       font-family: "微软雅黑", sans-serif;
  13.     }
  14.     #gameCanvas {
  15.       background: #111;
  16.       display: block;
  17.       margin: auto;
  18.       border: 2px solid white;
  19.     }
  20.     #scoreboard {
  21.       text-align: center;
  22.       margin-top: 10px;
  23.     }
  24.   </style>
  25. </head>
  26. <body>
  27.   <canvas id="gameCanvas" width="400" height="600"></canvas>
  28.   <div id="scoreboard">
  29.     血量:<span id="hp">3</span> &nbsp;&nbsp; 分数:<span id="score">0</span>
  30.   </div>

  31.   <p style="text-align:center; color:#ccc;">
  32.     操作提示:按A键向左移动,D键向右移动,空格键发射子弹。
  33.   </p>

  34.   <script>
  35.     const canvas = document.getElementById("gameCanvas");
  36.     const ctx = canvas.getContext("2d");

  37.     const planeWidth = 40;
  38.     const planeHeight = 40;
  39.     let planeX = (canvas.width - planeWidth) / 2;
  40.     const planeY = canvas.height - planeHeight - 10;
  41.     let hp = 3;
  42.     let score = 0;

  43.     // 敌机数组,开始为空
  44.     let enemies = [];

  45.     // 子弹数组,开始为空
  46.     let bullets = [];

  47.     // 控制左右移动
  48.     let moveLeft = false;
  49.     let moveRight = false;

  50.     // 监听键盘按下
  51.     window.addEventListener("keydown", function(e) {
  52.       if (e.key === "a" || e.key === "A") moveLeft = true;
  53.       if (e.key === "d" || e.key === "D") moveRight = true;
  54.     });

  55.     // 监听键盘松开
  56.     window.addEventListener("keyup", function(e) {
  57.       if (e.key === "a" || e.key === "A") moveLeft = false;
  58.       if (e.key === "d" || e.key === "D") moveRight = false;
  59.       if (e.key === " ") shoot();
  60.     });

  61.     // 画飞机(用三角形表示)
  62.     function drawPlane() {
  63.       ctx.fillStyle = "lightblue";
  64.       ctx.beginPath();
  65.       ctx.moveTo(planeX + planeWidth / 2, planeY);
  66.       ctx.lineTo(planeX, planeY + planeHeight);
  67.       ctx.lineTo(planeX + planeWidth, planeY + planeHeight);
  68.       ctx.closePath();
  69.       ctx.fill();
  70.     }

  71.     // 生成敌机,随机x位置
  72.     function createEnemy() {
  73.       let x = Math.random() * (canvas.width - 30);
  74.       enemies.push({ x: x, y: -30, width: 30, height: 30 });
  75.     }

  76.     // 画敌机(红色矩形)
  77.     function drawEnemies() {
  78.       ctx.fillStyle = "red";
  79.       enemies.forEach(enemy => {
  80.         ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
  81.       });
  82.     }

  83.     // 移动敌机,向下移2像素
  84.     function moveEnemies() {
  85.       enemies.forEach(enemy => {
  86.         enemy.y += 2;
  87.       });
  88.       // 删除超出画面底部的敌机
  89.       enemies = enemies.filter(enemy => enemy.y < canvas.height);
  90.     }

  91.     // 发射子弹,子弹初始位置在飞机头部中间
  92.     function shoot() {
  93.       bullets.push({ x: planeX + planeWidth / 2 - 2.5, y: planeY, width: 5, height: 10 });
  94.     }

  95.     // 画子弹(黄色矩形)
  96.     function drawBullets() {
  97.       ctx.fillStyle = "yellow";
  98.       bullets.forEach(bullet => {
  99.         ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
  100.       });
  101.     }

  102.     // 移动子弹,向上移5像素
  103.     function moveBullets() {
  104.       bullets.forEach(bullet => {
  105.         bullet.y -= 5;
  106.       });
  107.       // 删除飞出画面的子弹
  108.       bullets = bullets.filter(bullet => bullet.y + bullet.height > 0);
  109.     }

  110.     // 碰撞检测两个矩形是否相交
  111.     function isColliding(rect1, rect2) {
  112.       return !(
  113.         rect1.x > rect2.x + rect2.width ||
  114.         rect1.x + rect1.width < rect2.x ||
  115.         rect1.y > rect2.y + rect2.height ||
  116.         rect1.y + rect1.height < rect2.y
  117.       );
  118.     }

  119.     // 检查子弹和敌机碰撞
  120.     function checkBulletEnemyCollision() {
  121.       for (let i = bullets.length - 1; i >= 0; i--) {
  122.         let b = bullets[i];
  123.         for (let j = enemies.length - 1; j >= 0; j--) {
  124.           let e = enemies[j];
  125.           if (isColliding(b, e)) {
  126.             // 子弹和敌机都消失
  127.             bullets.splice(i, 1);
  128.             enemies.splice(j, 1);
  129.             score++;
  130.             updateScore();
  131.             break; // 跳出内层循环,继续检查下一个子弹
  132.           }
  133.         }
  134.       }
  135.     }

  136.     // 检查敌机和飞机碰撞
  137.     function checkEnemyPlaneCollision() {
  138.       let planeRect = { x: planeX, y: planeY, width: planeWidth, height: planeHeight };
  139.       for (let i = enemies.length - 1; i >= 0; i--) {
  140.         let e = enemies[i];
  141.         if (isColliding(e, planeRect)) {
  142.           enemies.splice(i, 1); // 敌机消失
  143.           hp--;
  144.           updateHP();
  145.           if (hp <= 0) {
  146.             alert("游戏结束!你的得分是:" + score);
  147.             document.location.reload(); // 重新加载页面,重玩游戏
  148.           }
  149.         }
  150.       }
  151.     }

  152.     // 更新血量显示
  153.     function updateHP() {
  154.       document.getElementById("hp").textContent = hp;
  155.     }

  156.     // 更新分数显示
  157.     function updateScore() {
  158.       document.getElementById("score").textContent = score;
  159.     }

  160.     // 游戏主循环
  161.     function gameLoop() {
  162.       ctx.clearRect(0, 0, canvas.width, canvas.height);

  163.       // 根据按键移动飞机
  164.       if (moveLeft && planeX > 0) planeX -= 5;
  165.       if (moveRight && planeX < canvas.width - planeWidth) planeX += 5;

  166.       drawPlane();

  167.       // 控制敌机出现概率(大约每30帧一个)
  168.       if (Math.random() < 0.03) createEnemy();

  169.       moveEnemies();
  170.       drawEnemies();

  171.       moveBullets();
  172.       drawBullets();

  173.       checkBulletEnemyCollision();
  174.       checkEnemyPlaneCollision();

  175.       requestAnimationFrame(gameLoop);
  176.     }

  177.     // 初始化血量和分数
  178.     updateHP();
  179.     updateScore();
  180.     gameLoop();
  181.   </script>
  182. </body>
  183. </html>
复制代码


---

### 这个代码做了什么?

1. **画布和飞机**

   - 画布大小是400x600像素,背景是暗色的。
   - 飞机用一个蓝色的三角形表示,会在画布底部中间。
   - 用变量 `planeX` 和 `planeY` 控制位置。

2. **敌机**

   - 敌人是红色的30x30像素的方块,从屏幕顶端随机位置往下飞。
   - 敌机会慢慢往下移动,如果飞出画面就消失。

3. **子弹**

   - 按空格键可以发射子弹,黄色小长方形从飞机头部向上飞。
   - 子弹飞出画面会消失。

4. **移动控制**

   - 按“A”键飞机向左移动,按“D”键向右移动。
   - 用事件监听处理按键按下和松开。

5. **碰撞检测**

   - 判断敌机和子弹是否碰撞,碰撞时子弹和敌机都会消失,分数加一。
   - 判断敌机和飞机是否碰撞,碰撞时敌机消失,血量减少。血量变为0游戏结束。

6. **显示信息**

   - 屏幕上方显示血量和分数,会随时更新。

7. **游戏循环**

   - 利用 `requestAnimationFrame` 每帧刷新画面,移动角色,检测碰撞。

---

### 为什么之前的代码看起来像乱码?

- 数组写法要用方括号 [],你写成了 `let enemies = ;`,少了 []
- 遍历数组时,要用索引取元素,比如 `let b = bullets`
- 有些变量比较少写全,比如 `if (hp  0)` 应该写成 `if (hp <= 0)`
- 语法不完整电脑就不会运行,所以才会有错误

---

如果你想自己试一下,可以复制我上面这段代码,保存成 `.html` 文件,用浏览器打开,就能玩这个小游戏啦!如果还有哪里不明白,我可以再帮你解释哦~
回复 支持 反对

使用道具 举报

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

本版积分规则

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