鸿蒙Arkts开发飞机大战小游戏,包含无敌模式,自动射弹,暂停和继续

飞机大战可以把飞机改成图片,目前包含无敌模式,自动射弹,暂停和继续的功能

代码如下:

ts 复制代码
// 定义位置类
class GamePosition {
  x: number
  y: number

  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
}

@Entry
@Component
struct PlaneGame {
  @State isPaused: boolean = false // 添加暂停状态
  @State playerX: number = 180
  @State playerY: number = 400  // 降低初始Y位置
  @State bullets: GamePosition[] = []
  @State enemies: GamePosition[] = []
  @State score: number = 0
  @State isGameOver: boolean = false
  @State isInvincible: boolean = false  // 添加无敌状态
  @State autoFire: boolean = false  // 添加自动发射状态
  // 修改移动速度从8提高到15
  private speed: number = 15      // 大幅提高移动速度
  private bulletSpeed: number = 15
  private enemySpeed: number = 3
  private enemySpawnRate: number = 45
  private fireInterval: number = 10  // 自动发射间隔(帧数)
  private frameCount: number = 0
  private planeSize: number = 40  // 减小尺寸
  private bulletSize: number = 8
  private enemySize: number = 40
  private isLeftPressed: boolean = false
  private isRightPressed: boolean = false
  private isFirePressed: boolean = false
  private gameInterval: number = 0 // 添加游戏循环引用

  // 添加togglePause方法
  togglePause() {
    this.isPaused = !this.isPaused
    // 强制状态更新
    this.score = this.score + 0
    console.log(`游戏已${this.isPaused ? '暂停' : '继续'}`)
  }

  aboutToAppear() {
    this.gameInterval = setInterval(() => {
      if (!this.isPaused && !this.isGameOver) {
        this.updateGame()
        this.handleContinuousInput()
      }
    }, 16)
  }

  handleContinuousInput() {
    if (this.isLeftPressed) {
      this.movePlayer('left')
    }
    if (this.isRightPressed) {
      this.movePlayer('right')
    }
    if (this.isFirePressed || (this.autoFire && this.frameCount % this.fireInterval === 0)) {
      this.fireBullet()
    }
  }

  updateGame() {
    if (this.isGameOver) {
      return;
    }
    
    this.frameCount++;
    
    // Update bullet positions
    this.bullets = this.bullets.map(bullet => 
      new GamePosition(bullet.x, bullet.y - this.bulletSpeed)
    ).filter(bullet => bullet.y > 0);
    
    // Update enemy positions
    this.enemies = this.enemies.map(enemy => 
      new GamePosition(enemy.x, enemy.y + this.enemySpeed)
    ).filter(enemy => enemy.y < 1000);
    
    // Spawn new enemies
    if (this.frameCount % this.enemySpawnRate === 0) {
      this.enemies.push(new GamePosition(
        Math.random() * (360 - this.enemySize),
        -this.enemySize
      ));
    }
    
    // Check collisions
    this.checkCollisions();
    
    // Check game over condition
    if (!this.isInvincible && this.enemies.some(enemy => 
        enemy.y + this.enemySize > this.playerY &&
        enemy.x + this.enemySize > this.playerX &&
        enemy.x < this.playerX + this.planeSize)) {
      this.isGameOver = true;
    }
  }

  checkCollisions() {
    this.bullets.forEach(bullet => {
      this.enemies.forEach((enemy, index) => {
        if (bullet.x + this.bulletSize > enemy.x &&
            bullet.x < enemy.x + this.enemySize &&
            bullet.y + this.bulletSize > enemy.y &&
            bullet.y < enemy.y + this.enemySize) {
          this.score += 10;
          this.enemies.splice(index, 1);
        }
      });
    });
  }

  fireBullet() {
    this.bullets.push(new GamePosition(
      this.playerX + this.planeSize / 2 - this.bulletSize / 2,
      this.playerY - this.bulletSize
    ));
  }

  movePlayer(direction: string) {
    if (direction === 'left' && this.playerX > 0) {
      this.playerX -= this.speed;
    } else if (direction === 'right' && this.playerX < 360 - this.planeSize) {
      this.playerX += this.speed;
    }
  }

  toggleInvincible() {
    this.isInvincible = !this.isInvincible;
  }

  toggleAutoFire() {
    this.autoFire = !this.autoFire;
  }

  restartGame() {
    this.playerX = 180;
    this.playerY = 350;  // 将初始Y坐标从400改为350
    this.bullets = [];
    this.enemies = [];
    this.score = 0;
    this.isGameOver = false;
    this.frameCount = 0;
    this.isPaused = false;
  }

  build() {
    Column() {
      // 游戏标题和状态栏
      Row() {
        Text('飞机大战')
          .fontSize(24)  // 缩小标题字号
          .fontColor(Color.White)
          .margin({ left: 10 })  // 减小左边距
        Blank()
        Text(`得分: ${this.score}`)
          .fontSize(20)  // 缩小得分显示字号
          .fontColor(Color.White)
          .margin(5)  // 减小边距
        Text(`无敌: ${this.isInvincible ? 'ON' : 'OFF'}`)
          .fontSize(20)  // 缩小无敌状态字号
          .fontColor(this.isInvincible ? Color.Green : Color.Gray)
          .margin(5)  // 减小边距
      }
      .width('100%')
      .height(40)  // 减小标题栏高度
      .backgroundColor('#333333')

      // 游戏主区域
      Stack() {
        // 游戏区域背景
        Rect()
          .width('100%')
          .height(450)  // 将高度从400增加到450
          .backgroundColor('#000033')
  
        // 玩家飞机
        Rect()
          .width(this.planeSize)
          .height(this.planeSize)
          .fill(Color.Blue)
          .position({ x: this.playerX, y: this.playerY })
  
        // 子弹
        ForEach(this.bullets, (bullet: GamePosition) => {
          Rect()
            .width(this.bulletSize)
            .height(this.bulletSize * 2)  // 加长子弹
            .fill(Color.Yellow)
            .position({ x: bullet.x, y: bullet.y })
        }, (bullet: GamePosition) => `${bullet.x},${bullet.y}`)
  
        // 敌机
        ForEach(this.enemies, (enemy: GamePosition) => {
          Rect()
            .width(this.enemySize)
            .height(this.enemySize)
            .fill(Color.Red)
            .position({ x: enemy.x, y: enemy.y })
        }, (enemy: GamePosition) => `${enemy.x},${enemy.y}`)
      }
      .width('100%')
      .height(450)  // 同步修改高度
      .margin({ top: 5, bottom: 5 })  // 调整上下边距
      .borderRadius(10)
      .border({ width: 2, color: '#555555' })

      // 游戏控制按钮区域
      Row() {
        Button(this.isInvincible ? '关闭无敌' : '开启无敌')
          .onClick(() => this.toggleInvincible())
          .width(100)
          .height(40)
          .fontSize(16)
          .backgroundColor('#4A4A4A')
          .fontColor(Color.White)
        Button(this.autoFire ? '关闭自动' : '开启自动')
          .onClick(() => this.toggleAutoFire())
          .width(100)
          .height(40)
          .fontSize(16)
          .backgroundColor(this.autoFire ? '#FFA500' : '#4A4A4A')
          .fontColor(Color.White)
        Button(this.isPaused ? '继续' : '暂停')
          .onClick(() => this.togglePause())
          .width(100)
          .height(40)
          .fontSize(16)
          .backgroundColor(this.isPaused ? '#00AA00' : '#AA0000')
          .fontColor(Color.White)
        // 添加重新开始按钮
        Button('重新开始')
          .onClick(() => this.restartGame())
          .width(100)
          .height(40)
          .fontSize(16)
          .backgroundColor('#4A4A4A')
          .fontColor(Color.White)
      }
      .width('95%')  // 减小宽度
      .justifyContent(FlexAlign.SpaceAround)
      .margin({ top: 5, bottom: 5 })  // 调整上下边距

      // 方向控制区域
      Column() {
        // 上方向按钮
        Button('↑')
          .onTouch((event: TouchEvent) => {
            if (event.type === TouchType.Down) {
              this.isFirePressed = true
            } else if (event.type === TouchType.Up) {
              this.isFirePressed = false
            }
          })
          .onClick(() => this.fireBullet())  // 上按钮用于发射子弹
          .width(60)
          .height(60)
          .fontSize(20)
          .margin(5)
        
        // 左右方向按钮
        Row() {
          Button('←')
            .onTouch((event: TouchEvent) => {
              if (event.type === TouchType.Down) {
                this.isLeftPressed = true
              } else if (event.type === TouchType.Up) {
                this.isLeftPressed = false
              }
            })
            .onClick(() => this.movePlayer('left'))
            .width(60)
            .height(60)
            .fontSize(20)
            .margin(5)
          Button('→')
            .onTouch((event: TouchEvent) => {
              if (event.type === TouchType.Down) {
                this.isRightPressed = true
              } else if (event.type === TouchType.Up) {
                this.isRightPressed = false
              }
            })
            .onClick(() => this.movePlayer('right'))
            .width(60)
            .height(60)
            .fontSize(20)
            .margin(5)
        }
        .justifyContent(FlexAlign.Center)
        
        // 下方向按钮(可留空或用作其他功能)
        // Button('↓')
        //   .width(60)
        //   .height(60)
        //   .fontSize(20)
        //   .margin(5)
        //   .opacity(0.5)  // 半透明表示不可用
      }
      .margin({ top: 20, bottom: 20 })
      .alignItems(HorizontalAlign.Center)
      .backgroundColor('#333333')
      .width('90%')
      .borderRadius(20)
      .padding(10)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#222222')
    .onClick(() => {
      console.log('游戏区域点击')
    })
    .onKeyEvent((event: KeyEvent) => {
      switch (event.keyCode) {
        case 2038: // 左箭头
        case 21: 
          this.isLeftPressed = (event.type === KeyType.Down)
          break
        case 2039: // 右箭头
        case 22: 
          this.isRightPressed = (event.type === KeyType.Down)
          break
        case 2040: // 空格
        case 23: 
        case 2037: // 上箭头
        case 19: 
          this.isFirePressed = (event.type === KeyType.Down)
          break
      }
    })
  }
} // 这是PlaneGame结构体的闭合
相关推荐
雪芽蓝域zzs23 分钟前
鸿蒙Next开发 获取APP缓存大小和清除缓存
缓存·华为·harmonyos
Robot2514 小时前
「华为」人形机器人赛道投资首秀!
大数据·人工智能·科技·microsoft·华为·机器人
鸿蒙布道师4 小时前
鸿蒙NEXT开发动画案例5
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
小诸葛的博客12 小时前
华为ensp实现跨vlan通信
网络·华为·智能路由器
康康这名还挺多14 小时前
鸿蒙HarmonyOS list优化一: list 结合 lazyforeach用法
数据结构·list·harmonyos·lazyforeach
晚秋大魔王17 小时前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——nettle库
linux·开源·harmonyos
python算法(魔法师版)21 小时前
.NET 在鸿蒙系统上的适配现状
华为od·华为·华为云·.net·wpf·harmonyos
bestadc1 天前
鸿蒙 UIAbility组件与UI的数据同步和窗口关闭
harmonyos
枫叶丹41 天前
【HarmonyOS Next之旅】DevEco Studio使用指南(二十二)
华为·harmonyos·deveco studio·harmonyos next
ax一号街阿楠1 天前
华为FAT AP配置 真机
网络·华为·智能路由器