科学教育

搜索
查看: 386|回复: 2
打印 上一主题 下一主题

游戏飞机大战的代码

[复制链接]

1

主题

1

帖子

5

积分

新手上路

Rank: 1

积分
5
跳转到指定楼层
楼主
发表于 2025-12-2 14:58:53 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
帮我生成一个游戏飞机大战的代码
回复

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
沙发
发表于 2025-12-2 15:00:22 | 只看该作者
当然可以!我来帮你写一个简单的“飞机大战”小游戏代码,用网页上的代码来做,里面包括飞机、敌机、子弹等等。你可以直接把下面的代码复制到记事本里,保存成一个后缀名叫 `.html` 的文件,然后用浏览器打开就可以玩了!

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>飞机大战小游戏</title>
  6. <style>
  7.   body { margin:0; background: #000; overflow: hidden; }
  8.   canvas { display: block; margin: 0 auto; background: #111; }
  9. </style>
  10. </head>
  11. <body>
  12. <canvas id="game" width="400" height="600"></canvas>
  13. <script>
  14. // 画布和上下文
  15. const canvas = document.getElementById('game');
  16. const ctx = canvas.getContext('2d');

  17. const WIDTH = canvas.width;
  18. const HEIGHT = canvas.height;

  19. // 飞机
  20. const plane = {
  21.   x: WIDTH / 2 - 20,
  22.   y: HEIGHT - 80,
  23.   width: 40,
  24.   height: 60,
  25.   speed: 5
  26. };

  27. // 子弹数组
  28. let bullets = [];

  29. // 敌机数组
  30. let enemies = [];

  31. // 分数
  32. let score = 0;

  33. // 按键状态
  34. const keys = {};

  35. // 创建子弹函数
  36. function createBullet() {
  37.   bullets.push({
  38.     x: plane.x + plane.width / 2 - 3,
  39.     y: plane.y,
  40.     width: 6,
  41.     height: 12,
  42.     speed: 7
  43.   });
  44. }

  45. // 随机生成敌机
  46. function createEnemy() {
  47.   const size = 40;
  48.   enemies.push({
  49.     x: Math.random() * (WIDTH - size),
  50.     y: -size,
  51.     width: size,
  52.     height: size,
  53.     speed: 2 + Math.random() * 2
  54.   });
  55. }

  56. // 监听键盘按下
  57. window.addEventListener('keydown', function(e) {
  58.   keys[e.key] = true;

  59.   // 空格键发射子弹
  60.   if (e.code === 'Space') {
  61.     createBullet();
  62.   }
  63. });

  64. //监听键盘松开
  65. window.addEventListener('keyup', function(e) {
  66.   keys[e.key] = false;
  67. });

  68. // 碰撞检测函数
  69. function isColliding(a, b) {
  70.   return !(
  71.     a.x + a.width < b.x ||
  72.     a.x > b.x + b.width ||
  73.     a.y + a.height < b.y ||
  74.     a.y > b.y + b.height
  75.   );
  76. }

  77. // 游戏主循环
  78. function gameLoop() {
  79.   // 清空画布
  80.   ctx.clearRect(0, 0, WIDTH, HEIGHT);

  81.   // 移动飞机
  82.   if (keys['ArrowLeft'] && plane.x > 0) {
  83.     plane.x -= plane.speed;
  84.   }
  85.   if (keys['ArrowRight'] && plane.x + plane.width < WIDTH) {
  86.     plane.x += plane.speed;
  87.   }

  88.   // 画飞机(用三角形表示)
  89.   ctx.fillStyle = 'skyblue';
  90.   ctx.beginPath();
  91.   ctx.moveTo(plane.x + plane.width / 2, plane.y);
  92.   ctx.lineTo(plane.x, plane.y + plane.height);
  93.   ctx.lineTo(plane.x + plane.width, plane.y + plane.height);
  94.   ctx.closePath();
  95.   ctx.fill();

  96.   // 移动子弹,画子弹
  97.   for (let i = bullets.length - 1; i >= 0; i--) {
  98.     let b = bullets[i];
  99.     b.y -= b.speed;

  100.     if (b.y + b.height < 0) {
  101.       bullets.splice(i, 1);
  102.       continue;
  103.     }

  104.     ctx.fillStyle = 'yellow';
  105.     ctx.fillRect(b.x, b.y, b.width, b.height);
  106.   }

  107.   // 生成敌机(每隔一些帧数生成)
  108.   if (Math.random() < 0.02) {
  109.     createEnemy();
  110.   }

  111.   // 移动敌机,画敌机
  112.   for (let i = enemies.length - 1; i >= 0; i--) {
  113.     let e = enemies[i];
  114.     e.y += e.speed;

  115.     if (e.y > HEIGHT) {
  116.       enemies.splice(i, 1);
  117.       continue;
  118.     }

  119.     ctx.fillStyle = 'red';
  120.     ctx.fillRect(e.x, e.y, e.width, e.height);
  121.   }

  122.   // 检测子弹和敌机碰撞
  123.   for (let i = enemies.length - 1; i >= 0; i--) {
  124.     for (let j = bullets.length - 1; j >= 0; j--) {
  125.       if (isColliding(enemies[i], bullets[j])) {
  126.         enemies.splice(i, 1);
  127.         bullets.splice(j, 1);
  128.         score += 10;
  129.         break;
  130.       }
  131.     }
  132.   }

  133.   // 检测敌机和飞机碰撞
  134.   for (let e of enemies) {
  135.     if (isColliding(e, plane)) {
  136.       alert(`游戏结束!得分:${score}`);
  137.       document.location.reload();
  138.       return;
  139.     }
  140.   }

  141.   // 显示分数
  142.   ctx.fillStyle = 'white';
  143.   ctx.font = '20px Arial';
  144.   ctx.fillText('分数: ' + score, 10, 30);

  145.   // 请求下一帧动画
  146.   requestAnimationFrame(gameLoop);
  147. }

  148. // 开始游戏
  149. gameLoop();
  150. </script>
  151. </body>
  152. </html>
复制代码


### 怎么玩?
- 用键盘左右箭头键控制你的飞机左右移动。
- 按空格键发射子弹,射击从上方飞来的红色敌机。
- 打中一个敌机得10分。
- 如果敌机碰到你的飞机,游戏结束,会弹出得分。

这段代码很适合刚开始学网页编程的小伙伴,也可以做个基础项目练习。你可以试着改改速度、颜色或者增加更多功能哦~

如果有问题可以随时问我!祝你玩得开心!????✈️
回复 支持 反对

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
板凳
发表于 2025-12-2 15:02:17 | 只看该作者
好呀!我来帮你写一个简单的“飞机大战”小游戏代码,用的是网页编程中的HTML和JavaScript。你可以把它放到电脑上的一个文件里,保存为 `index.html`,然后用浏览器打开就能玩啦!

这是一个简单版的飞机大战游戏,内容包括:
- 你的飞机可以用左右方向键移动
- 按空格键发射子弹击打敌机
- 敌机会从上方不断出现并向下移动
- 撞到敌机或者敌机到底游戏结束

---

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>简易飞机大战</title>
  5.     <style>
  6.         body {
  7.             margin: 0;
  8.             overflow: hidden; /* 不显示滚动条 */
  9.             background: black;
  10.         }
  11.         #gameCanvas {
  12.             background: #111;
  13.             display: block;
  14.             margin: 0 auto;
  15.             border: 2px solid white;
  16.         }
  17.     </style>
  18. </head>
  19. <body>

  20. <canvas id="gameCanvas" width="400" height="600"></canvas>

  21. <script>
  22. // 获取画布和上下文
  23. const canvas = document.getElementById('gameCanvas');
  24. const ctx = canvas.getContext('2d');

  25. const planeWidth = 40;
  26. const planeHeight = 40;

  27. let score = 0;
  28. let gameOver = false;

  29. // 玩家飞机对象
  30. const player = {
  31.     x: canvas.width / 2 - planeWidth / 2,
  32.     y: canvas.height - planeHeight - 10,
  33.     width: planeWidth,
  34.     height: planeHeight,
  35.     speed: 5,
  36.     moveLeft: false,
  37.     moveRight: false,
  38. };

  39. // 子弹数组
  40. const bullets = [];

  41. // 敌机数组
  42. const enemies = [];

  43. // 生成敌机
  44. function createEnemy() {
  45.     const enemyWidth = 40;
  46.     const enemyHeight = 40;
  47.     const x = Math.random() * (canvas.width - enemyWidth);
  48.     const y = -enemyHeight;
  49.     const speed = 2 + Math.random() * 2;
  50.     enemies.push({x, y, width: enemyWidth, height: enemyHeight, speed});
  51. }

  52. // 绘制玩家飞机
  53. function drawPlayer() {
  54.     ctx.fillStyle = 'cyan';
  55.     // 用三角形画飞机
  56.     ctx.beginPath();
  57.     ctx.moveTo(player.x + player.width/2, player.y);
  58.     ctx.lineTo(player.x, player.y + player.height);
  59.     ctx.lineTo(player.x + player.width, player.y + player.height);
  60.     ctx.closePath();
  61.     ctx.fill();
  62. }

  63. // 绘制子弹
  64. function drawBullets() {
  65.     ctx.fillStyle = 'yellow';
  66.     bullets.forEach(b => {
  67.         ctx.fillRect(b.x, b.y, b.width, b.height);
  68.     });
  69. }

  70. // 绘制敌机
  71. function drawEnemies() {
  72.     ctx.fillStyle = 'red';
  73.     enemies.forEach(e => {
  74.         ctx.fillRect(e.x, e.y, e.width, e.height);
  75.     });
  76. }

  77. // 移动玩家飞机
  78. function movePlayer() {
  79.     if (player.moveLeft && player.x > 0) {
  80.         player.x -= player.speed;
  81.     }
  82.     if (player.moveRight && player.x + player.width < canvas.width) {
  83.         player.x += player.speed;
  84.     }
  85. }

  86. // 移动子弹
  87. function moveBullets() {
  88.     for(let i = bullets.length -1; i >= 0; i--) {
  89.         bullets[i].y -= bullets[i].speed;
  90.         if (bullets[i].y < 0) {
  91.             bullets.splice(i, 1); // 把超出画面顶部的子弹删掉
  92.         }
  93.     }
  94. }

  95. // 移动敌机
  96. function moveEnemies() {
  97.     for(let i = enemies.length -1; i >= 0; i--) {
  98.         enemies[i].y += enemies[i].speed;
  99.         if (enemies[i].y > canvas.height) {
  100.             // 敌机到底,算作游戏失败
  101.             gameOver = true;
  102.         }
  103.     }
  104. }

  105. // 碰撞检测函数
  106. function isColliding(a, b) {
  107.     return !(
  108.         a.x + a.width < b.x ||
  109.         a.x > b.x + b.width ||
  110.         a.y + a.height < b.y ||
  111.         a.y > b.y + b.height
  112.     );
  113. }

  114. // 检测子弹和敌机碰撞
  115. function checkBulletEnemyCollision() {
  116.     for(let i = enemies.length -1; i >= 0; i--) {
  117.         for(let j = bullets.length -1; j >= 0; j--) {
  118.             if(isColliding(enemies[i], bullets[j])) {
  119.                 // 击中了敌机
  120.                 enemies.splice(i,1);
  121.                 bullets.splice(j,1);
  122.                 score += 10;
  123.                 break; // 一个敌机被一个子弹击中后跳出内层循环
  124.             }
  125.         }
  126.     }
  127. }

  128. // 检测玩家和敌机碰撞
  129. function checkPlayerEnemyCollision() {
  130.     for(let i = 0; i < enemies.length; i++) {
  131.         if(isColliding(player, enemies[i])) {
  132.             gameOver = true;
  133.             break;
  134.         }
  135.     }
  136. }

  137. // 显示分数
  138. function drawScore() {
  139.     ctx.fillStyle = 'white';
  140.     ctx.font = '20px Arial';
  141.     ctx.fillText('得分: '+score, 10, 30);
  142. }

  143. // 显示游戏结束字样
  144. function drawGameOver() {
  145.     ctx.fillStyle = 'white';
  146.     ctx.font = '40px Arial';
  147.     ctx.textAlign = 'center';
  148.     ctx.fillText('游戏结束', canvas.width / 2, canvas.height / 2);
  149.     ctx.font = '20px Arial';
  150.     ctx.fillText('得分: '+score, canvas.width / 2, canvas.height / 2 + 40);
  151. }

  152. // 主循环
  153. function gameLoop() {
  154.     if (gameOver) {
  155.         drawGameOver();
  156.         return;
  157.     }

  158.     // 清空画布
  159.     ctx.clearRect(0, 0, canvas.width, canvas.height);

  160.     movePlayer();
  161.     moveBullets();
  162.     moveEnemies();
  163.    
  164.     checkBulletEnemyCollision();
  165.     checkPlayerEnemyCollision();

  166.     drawPlayer();
  167.     drawBullets();
  168.     drawEnemies();
  169.     drawScore();

  170.     requestAnimationFrame(gameLoop);
  171. }

  172. // 控制按键
  173. document.addEventListener('keydown', function(e) {
  174.     if(e.code === 'ArrowLeft') {
  175.         player.moveLeft = true;
  176.     } else if(e.code === 'ArrowRight') {
  177.         player.moveRight = true;
  178.     } else if(e.code === 'Space') {
  179.         // 发射子弹
  180.         bullets.push({
  181.             x: player.x + player.width/2 - 2,
  182.             y: player.y,
  183.             width:4,
  184.             height:10,
  185.             speed:7,
  186.         });
  187.     }
  188. });

  189. document.addEventListener('keyup', function(e) {
  190.     if(e.code === 'ArrowLeft') {
  191.         player.moveLeft = false;
  192.     } else if(e.code === 'ArrowRight') {
  193.         player.moveRight = false;
  194.     }
  195. });

  196. // 每秒生成一个敌机
  197. setInterval(() => {
  198.     if(!gameOver) {
  199.         createEnemy();
  200.     }
  201. }, 1000);

  202. // 开始游戏
  203. gameLoop();

  204. </script>

  205. </body>
  206. </html>
复制代码


---

###怎么玩?
1. 左右方向键控制飞机左右移动
2. 空格键发射子弹
3. 尽量用子弹打掉红色的敌机,不让敌机碰到你的飞机或者飞到底部
4. 游戏结束时会显示“游戏结束”和你的得分

---

有没有听明白呀?这个游戏其实就是用画布不停地画图,动画就是让东西的位置一帧一帧地改变,看起来像在动。飞机、子弹和敌机都是用简单的颜色和形状表示的,容易理解。

如果你想换飞机样子或增加新功能,可以再问我,我帮你改哦!祝你玩得开心!????✈️????
回复 支持 反对

使用道具 举报

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

本版积分规则

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