目录

鸿蒙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结构体的闭合
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
别说我什么都不会3 小时前
【仓颉三方库】对象存储——OBS Cangjie SDK
harmonyos
星释4 小时前
鸿蒙Flutter仓库停止更新?
flutter·华为·harmonyos
云_杰5 小时前
鸿蒙开发干货——手把手教你玩转多媒体文件操作
harmonyos·交互设计
王老汉5 小时前
鸿蒙生态新利器:华为ArkUI-X混合开发框架深度解析
华为·harmonyos·arkui-x
NapleC6 小时前
HarmonyOS:网络HTTP数据请求
网络·http·harmonyos
模拟IC攻城狮7 小时前
(最新)华为 2026 届校招实习-硬件技术工程师-硬件通用/单板开发—机试题—(共14套)(每套四十题)
单片机·嵌入式硬件·华为·硬件架构·电源·模拟芯片
心随_风动9 小时前
华为openEuler操作系统全解析:起源、特性与生态对比
linux·华为·openeuler
新小梦10 小时前
OpenHarmony声明为系统应用和系统签名文件
harmonyos
别说我什么都不会11 小时前
【仓颉三方库】 数据解析——ini4cj
harmonyos
悬空八只脚11 小时前
React-Native开发鸿蒙NEXT-svg绘制睡眠质量图part1
harmonyos