科学教育

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

帮我生成飞机大战的网页代码

[复制链接]

1

主题

2

帖子

13

积分

新手上路

Rank: 1

积分
13
跳转到指定楼层
楼主
发表于 2025-12-2 13:57:36 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
帮我生成飞机大战的网页代码
回复

使用道具 举报

0

主题

1145

帖子

1715

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1715
沙发
发表于 2025-12-2 13:57:57 | 只看该作者
好呀!我帮你写一个简单的“飞机大战”网页游戏代码,里面有你的飞机,可以用键盘左右移动,还能发射子弹打敌机。这个代码用HTML和JavaScript做的,放到浏览器里就能玩。

下面是完整代码,你可以复制到一个叫`plane.html`的文件里,用浏览器打开就能开始玩啦!

```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>简单飞机大战</title>
<style>
  body {
    margin: 0;
    overflow: hidden;
    background: black;
  }
  #gameCanvas {
    background: #111;
    display: block;
    margin: 0 auto;
  }
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>

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

const planeWidth = 40;
const planeHeight = 60;

// 玩家飞机对象
const player = {
  x: canvas.width / 2 - planeWidth / 2,
  y: canvas.height - planeHeight - 10,
  width: planeWidth,
  height: planeHeight,
  speed: 5,
  bullets: [],
};

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

// 得分
let score = 0;

// 控制按键
const keys = {};

// 发射子弹类
class Bullet {
  constructor(x, y){
    this.x = x;
    this.y = y;
    this.width = 5;
    this.height = 10;
    this.speed = 7;
  }
  move(){
    this.y -= this.speed;
  }
  draw(){
    ctx.fillStyle = 'yellow';
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}

// 敌机类
class Enemy {
  constructor(x, y, speed){
    this.x = x;
    this.y = y;
    this.width = 40;
    this.height = 40;
    this.speed = speed;
  }
  move(){
    this.y += this.speed;
  }
  draw(){
    ctx.fillStyle = 'red';
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}

// 监听按键
window.addEventListener('keydown', function(e){
  keys[e.key] = true;
});

window.addEventListener('keyup', function(e){
  keys[e.key] = false;
});

// 发射子弹
function shoot(){
  // 子弹从飞机中间上方发射
  const bulletX = player.x + player.width/2 - 2.5;
  const bulletY = player.y;
  player.bullets.push(new Bullet(bulletX, bulletY));
}

// 生成敌机
function createEnemy(){
  // 敌机随机x坐标,速度随机
  const x = Math.random() * (canvas.width - 40);
  const speed = 2 + Math.random() *
回复 支持 反对

使用道具 举报

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

本版积分规则

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