IN_game.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. import { _decorator, Component, Node, Label, ProgressBar, find } from 'cc';
  2. import EventBus, { GameEvents } from '../Core/EventBus';
  3. import { GameBlockSelection } from '../CombatSystem/BlockSelection/GameBlockSelection';
  4. import { Wall } from '../CombatSystem/Wall';
  5. import { GameStartMove } from '../Animations/GameStartMove';
  6. import { LevelSessionManager } from '../Core/LevelSessionManager';
  7. import { SaveDataManager } from './SaveDataManager';
  8. import { SkillManager } from '../CombatSystem/SkillSelection/SkillManager';
  9. import { StartGame } from './StartGame';
  10. import { BackgroundManager } from './BackgroundManager';
  11. import { GroundBurnAreaManager } from '../CombatSystem/BulletEffects/GroundBurnAreaManager';
  12. const { ccclass, property } = _decorator;
  13. /**
  14. * 游戏内状态枚举
  15. * 仅在 AppState.IN_GAME 时使用
  16. */
  17. export enum GameState {
  18. PLAYING = 'playing',
  19. SUCCESS = 'success',
  20. DEFEAT = 'defeat',
  21. PAUSED = 'paused',
  22. BLOCK_SELECTION = 'block_selection'
  23. }
  24. /**
  25. * 游戏内状态管理器
  26. * 负责管理游戏进行中的所有状态和逻辑
  27. */
  28. @ccclass('InGameManager')
  29. export class InGameManager extends Component {
  30. // === 游戏内UI节点引用 ===
  31. @property({
  32. type: Node,
  33. tooltip: '拖拽BallController节点到这里'
  34. })
  35. public ballController: Node = null;
  36. @property({
  37. type: Node,
  38. tooltip: '拖拽GameBlockSelection节点到这里'
  39. })
  40. public gameBlockSelection: Node = null;
  41. @property({
  42. type: Node,
  43. tooltip: '拖拽GameArea节点到这里'
  44. })
  45. public gameArea: Node = null;
  46. @property({
  47. type: Node,
  48. tooltip: '拖拽EnemyController节点到这里'
  49. })
  50. public enemyManager: Node = null;
  51. @property({
  52. type: Node,
  53. tooltip: '摄像机节点,用于获取GameStartMove组件'
  54. })
  55. public cameraNode: Node = null;
  56. @property({
  57. type: Node,
  58. tooltip: '墙体节点,用于获取Wall组件'
  59. })
  60. public wallNode: Node = null;
  61. @property({
  62. type: Node,
  63. tooltip: '上围栏墙体节点 (TopFence)'
  64. })
  65. public topFenceNode: Node = null;
  66. @property({
  67. type: Node,
  68. tooltip: '下围栏墙体节点 (BottomFence)'
  69. })
  70. public bottomFenceNode: Node = null;
  71. // === 游戏配置属性 ===
  72. @property({
  73. tooltip: '状态检查间隔(秒)'
  74. })
  75. public checkInterval: number = 1.0;
  76. // === 私有属性 ===
  77. private gameStarted: boolean = false;
  78. private currentState: GameState = GameState.PLAYING;
  79. private checkTimer: number = 0;
  80. // EnemyController现在通过事件系统通信,不再直接引用
  81. private enemySpawningStarted: boolean = false;
  82. private totalEnemiesSpawned: number = 0;
  83. private currentWave: number = 1;
  84. private currentWaveEnemyCount: number = 0;
  85. private currentWaveTotalEnemies: number = 0;
  86. public levelWaves: any[] = [];
  87. private levelTotalEnemies: number = 0;
  88. private enemiesKilled: number = 0;
  89. // === 背景管理器组件 ===
  90. private backgroundManager: BackgroundManager = null;
  91. // === 地面燃烧区域管理器 ===
  92. private groundBurnAreaManager: GroundBurnAreaManager = null;
  93. // 游戏计时器
  94. private gameStartTime: number = 0;
  95. private gameEndTime: number = 0;
  96. // 游戏区域的边界
  97. private gameBounds = {
  98. left: 0,
  99. right: 0,
  100. top: 0,
  101. bottom: 0
  102. };
  103. private preparingNextWave = false;
  104. // 能量系统
  105. private energyPoints: number = 0;
  106. private energyMax: number = 0; // 必须从关卡配置中读取
  107. private energyBar: ProgressBar = null;
  108. private selectSkillUI: Node = null;
  109. // 新增:能量条升级系统
  110. private energyUpgradeCount: number = 0; // 当前能量条升级次数
  111. private energyMaxUpgrades: number[] = []; // 每次升级后的最大值配置
  112. // 能量条UI节点
  113. @property({
  114. type: Node,
  115. tooltip: '拖拽能量条节点到这里 (Canvas/GameLevelUI/EnergyBar)'
  116. })
  117. public energyBarNode: Node = null;
  118. // 技能选择UI节点
  119. @property({
  120. type: Node,
  121. tooltip: '拖拽技能选择UI节点到这里 (Canvas/GameLevelUI/SelectSkillUI)'
  122. })
  123. public selectSkillUINode: Node = null;
  124. // === 背景管理器 ===
  125. @property({
  126. type: Node,
  127. tooltip: '拖拽BackgroundManager节点到这里'
  128. })
  129. public backgroundManagerNode: Node = null;
  130. @property({
  131. type: Node,
  132. tooltip: '拖拽GroundBurnAreaManager节点到这里'
  133. })
  134. public groundBurnAreaManagerNode: Node = null;
  135. // GameBlockSelection组件
  136. private blockSelectionComponent: GameBlockSelection = null;
  137. private pendingSkillSelection: boolean = false;
  138. private pendingBlockSelection: boolean = false;
  139. private shouldShowNextWavePrompt: boolean = false;
  140. // 墙体组件引用
  141. private wallComponent: Wall = null;
  142. private topFenceComponent: Wall = null;
  143. private bottomFenceComponent: Wall = null;
  144. // GameStartMove组件引用
  145. private gameStartMoveComponent: GameStartMove = null;
  146. start() {
  147. this.initializeGameState();
  148. this.setupEventListeners();
  149. this.initGameBlockSelection();
  150. this.initGameStartMove();
  151. this.initWallComponent();
  152. this.initUINodes();
  153. }
  154. update(deltaTime: number) {
  155. if (this.currentState !== GameState.PLAYING) {
  156. return;
  157. }
  158. this.checkTimer += deltaTime;
  159. if (this.checkTimer >= this.checkInterval) {
  160. this.checkTimer = 0;
  161. this.checkGameState();
  162. }
  163. }
  164. /**
  165. * 初始化游戏状态
  166. */
  167. private initializeGameState() {
  168. this.currentState = GameState.PLAYING;
  169. this.checkTimer = 0;
  170. this.enemySpawningStarted = false;
  171. this.totalEnemiesSpawned = 0;
  172. this.currentWave = 1;
  173. this.currentWaveEnemyCount = 0;
  174. this.currentWaveTotalEnemies = 0;
  175. this.energyPoints = 0;
  176. this.pendingSkillSelection = false;
  177. }
  178. /**
  179. * 设置事件监听器
  180. */
  181. private setupEventListeners() {
  182. const eventBus = EventBus.getInstance();
  183. eventBus.on(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  184. eventBus.on(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  185. eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  186. eventBus.on(GameEvents.GAME_RESUME_SKILL_SELECTION, this.onGameResumeEvent, this);
  187. eventBus.on(GameEvents.GAME_RESUME_BLOCK_SELECTION, this.onGameResumeEvent, this);
  188. eventBus.on('ENEMY_KILLED', this.onEnemyKilledEvent, this);
  189. eventBus.on(GameEvents.RESET_ENERGY_SYSTEM, this.resetEnergySystem, this);
  190. eventBus.on(GameEvents.WALL_DESTROYED, this.onWallDestroyedEvent, this);
  191. }
  192. /**
  193. * 初始化GameBlockSelection组件
  194. */
  195. private initGameBlockSelection() {
  196. if (this.gameBlockSelection) {
  197. this.blockSelectionComponent = this.gameBlockSelection.getComponent(GameBlockSelection);
  198. }
  199. }
  200. /**
  201. * 初始化GameStartMove组件
  202. */
  203. private initGameStartMove() {
  204. if (this.cameraNode) {
  205. this.gameStartMoveComponent = this.cameraNode.getComponent(GameStartMove);
  206. }
  207. }
  208. /**
  209. * EnemyController现在通过事件系统通信,不再需要直接初始化
  210. */
  211. /**
  212. * 初始化墙体组件
  213. */
  214. private initWallComponent() {
  215. // 初始化主墙体
  216. if (this.wallNode) {
  217. this.wallComponent = this.wallNode.getComponent(Wall);
  218. if (this.wallComponent) {
  219. console.log('[InGameManager] 主墙体组件初始化成功');
  220. } else {
  221. console.warn('[InGameManager] 未找到主墙体Wall组件');
  222. }
  223. } else {
  224. console.warn('[InGameManager] 主墙体节点未通过装饰器挂载');
  225. }
  226. // 初始化上围栏
  227. if (this.topFenceNode) {
  228. this.topFenceComponent = this.topFenceNode.getComponent(Wall);
  229. if (this.topFenceComponent) {
  230. console.log('[InGameManager] 上围栏墙体组件初始化成功');
  231. } else {
  232. console.warn('[InGameManager] 未找到上围栏Wall组件');
  233. }
  234. } else {
  235. console.warn('[InGameManager] 上围栏节点未通过装饰器挂载');
  236. }
  237. // 初始化下围栏
  238. if (this.bottomFenceNode) {
  239. this.bottomFenceComponent = this.bottomFenceNode.getComponent(Wall);
  240. if (this.bottomFenceComponent) {
  241. console.log('[InGameManager] 下围栏墙体组件初始化成功');
  242. } else {
  243. console.warn('[InGameManager] 未找到下围栏Wall组件');
  244. }
  245. } else {
  246. console.warn('[InGameManager] 下围栏节点未通过装饰器挂载');
  247. }
  248. }
  249. /**
  250. * 获取指定波次的敌人配置
  251. */
  252. private getWaveEnemyConfigs(wave: number): any[] {
  253. if (!this.levelWaves || wave < 1 || wave > this.levelWaves.length) {
  254. return [];
  255. }
  256. const waveConfig = this.levelWaves[wave - 1];
  257. return waveConfig?.enemies || [];
  258. }
  259. /**
  260. * 检查是否应该播放diban动画
  261. */
  262. public shouldPlayDibanAnimation(): boolean {
  263. return this.preparingNextWave && this.currentState === GameState.BLOCK_SELECTION;
  264. }
  265. /**
  266. * 技能选择完成后的处理
  267. */
  268. public onSkillSelectionComplete() {
  269. console.log('[InGameManager] 技能选择完成');
  270. // 关闭技能选择UI
  271. if (this.selectSkillUI) {
  272. this.selectSkillUI.active = false;
  273. console.log('[InGameManager] 技能选择UI已关闭');
  274. }
  275. // 恢复游戏
  276. this.resumeGame();
  277. // 发射技能选择结束恢复事件
  278. EventBus.getInstance().emit(GameEvents.GAME_RESUME_SKILL_SELECTION);
  279. // 如果有等待的diban动画,现在播放diban动画
  280. if (this.pendingBlockSelection) {
  281. console.log('[InGameManager] 技能选择完成,现在播放diban动画');
  282. this.playDibanAnimationAfterSkill();
  283. }
  284. }
  285. /**
  286. * 在技能选择后播放diban动画
  287. */
  288. public playDibanAnimationAfterSkill() {
  289. if (this.pendingBlockSelection) {
  290. console.log('[InGameManager] 技能选择完成,现在播放diban动画');
  291. this.pendingBlockSelection = false;
  292. if (this.currentWave < (this.levelWaves?.length || 1)) {
  293. this.playDibanAnimationForNextWave();
  294. } else {
  295. console.log('[InGameManager] 最后一波结束,触发游戏胜利');
  296. this.triggerGameSuccess();
  297. }
  298. } else if (this.shouldPlayDibanAnimation()) {
  299. this.playDibanAnimationForNextWave();
  300. }
  301. }
  302. /**
  303. * 播放下一波diban动画
  304. */
  305. private playDibanAnimationForNextWave() {
  306. // 如果游戏已经结束,不播放diban动画
  307. if (this.isGameOver()) {
  308. console.warn('[InGameManager] 游戏已经结束(胜利或失败),不播放下一波diban动画!');
  309. return;
  310. }
  311. console.log('[InGameManager] 播放diban动画');
  312. // 生成方块选择(不显示UI)
  313. if (this.blockSelectionComponent) {
  314. this.blockSelectionComponent.generateBlockSelection();
  315. }
  316. // 使用GameStartMove组件播放diban上滑动画和镜头下移动画
  317. if (this.gameStartMoveComponent) {
  318. console.log('[InGameManager] 调用GameStartMove组件播放diban上滑动画');
  319. this.gameStartMoveComponent.slideUpFromBottom(0.3);
  320. } else {
  321. console.warn('[InGameManager] GameStartMove组件未找到,无法播放diban动画');
  322. }
  323. // 使用底板选择专用暂停事件,小球继续运动
  324. EventBus.getInstance().emit(GameEvents.GAME_PAUSE_BLOCK_SELECTION);
  325. }
  326. /**
  327. * 处理游戏成功事件
  328. */
  329. private onGameSuccessEvent() {
  330. console.log('[InGameManager] 接收到游戏成功事件');
  331. this.currentState = GameState.SUCCESS;
  332. // 游戏结束时进入暂停状态,停止所有游戏对象的行为
  333. console.log('[InGameManager] 游戏成功,触发游戏暂停');
  334. const eventBus = EventBus.getInstance();
  335. eventBus.emit(GameEvents.GAME_PAUSE);
  336. }
  337. /**
  338. * 处理游戏失败事件
  339. */
  340. private onGameDefeatEvent() {
  341. console.log('[InGameManager] 接收到游戏失败事件');
  342. this.currentState = GameState.DEFEAT;
  343. // 游戏结束时进入暂停状态,停止所有游戏对象的行为
  344. console.log('[InGameManager] 游戏失败,触发游戏暂停');
  345. const eventBus = EventBus.getInstance();
  346. eventBus.emit(GameEvents.GAME_PAUSE);
  347. }
  348. /**
  349. * 处理游戏恢复事件
  350. */
  351. private onGameResumeEvent() {
  352. console.log('[InGameManager] 接收到游戏恢复事件');
  353. }
  354. /**
  355. * 墙体被摧毁事件处理
  356. * 墙体现在直接触发GAME_DEFEAT事件,与菜单退出处理流程一致
  357. */
  358. private onWallDestroyedEvent() {
  359. console.log('[InGameManager] 收到墙体被摧毁事件,墙体已直接触发GAME_DEFEAT事件');
  360. // 不再需要调用checkGameState,因为墙体已直接触发GAME_DEFEAT事件
  361. }
  362. /**
  363. * 处理敌人被击杀事件
  364. */
  365. private onEnemyKilledEvent() {
  366. // 游戏状态检查现在通过事件系统处理
  367. if (this.isGameOver()) {
  368. console.warn('[InGameManager] 游戏已结束状态下onEnemyKilledEvent被调用!');
  369. return;
  370. }
  371. // 如果游戏状态已经是成功或失败,不处理敌人击杀事件
  372. if (this.currentState === GameState.SUCCESS || this.currentState === GameState.DEFEAT) {
  373. console.warn(`[InGameManager] 游戏已结束(${this.currentState}),跳过敌人击杀事件处理`);
  374. return;
  375. }
  376. this.enemiesKilled++;
  377. this.currentWaveEnemyCount++;
  378. const remaining = this.currentWaveTotalEnemies - this.currentWaveEnemyCount;
  379. console.log(`[InGameManager] 敌人被消灭,当前波剩余敌人: ${remaining}/${this.currentWaveTotalEnemies}`);
  380. // 每死一个敌人就立即增加能量
  381. const energyBeforeIncrement = this.energyPoints;
  382. this.incrementEnergy();
  383. // 通过事件系统更新敌人计数标签
  384. EventBus.getInstance().emit(GameEvents.ENEMY_UPDATE_COUNT, this.currentWaveEnemyCount);
  385. // 检查能量是否已满,如果满了需要触发技能选择
  386. const energyWillBeFull = energyBeforeIncrement + 1 >= this.energyMax;
  387. // 基于UI显示的敌人数量判断波次是否结束(Canvas-001/TopArea/EnemyNode/EnemyNumber为0)
  388. const isWaveEnd = remaining <= 0;
  389. if (isWaveEnd) {
  390. console.log(`[InGameManager] 波次结束检测: remaining=${remaining}`);
  391. // 如果能量已满,设置等待方块选择状态
  392. if (energyWillBeFull) {
  393. this.pendingBlockSelection = true;
  394. this.preparingNextWave = true;
  395. this.currentState = GameState.BLOCK_SELECTION;
  396. } else {
  397. if (this.currentWave < (this.levelWaves?.length || 1)) {
  398. this.showNextWavePrompt();
  399. } else {
  400. this.triggerGameSuccess();
  401. }
  402. }
  403. } else if (energyWillBeFull) {
  404. // 如果波次未结束但能量已满,设置状态为方块选择
  405. // 注意:onEnergyFull()已在incrementEnergy()中调用,这里不需要重复调用
  406. console.log('[InGameManager] 能量已满但波次未结束,设置方块选择状态');
  407. this.currentState = GameState.BLOCK_SELECTION;
  408. }
  409. }
  410. /**
  411. * 增加能量值
  412. */
  413. private incrementEnergy() {
  414. // 获取技能等级
  415. const energyHunterLevel = SkillManager.getInstance() ? SkillManager.getInstance().getSkillLevel('energy_hunter') : 0;
  416. const baseEnergy = 1;
  417. const bonusEnergy = SkillManager.calculateEnergyBonus ? SkillManager.calculateEnergyBonus(baseEnergy, energyHunterLevel) : baseEnergy;
  418. this.energyPoints += bonusEnergy;
  419. console.log(`[InGameManager] 能量值增加: +${bonusEnergy}, 当前: ${this.energyPoints}/${this.energyMax}`);
  420. // 检查是否达到当前能量最大值
  421. if (this.energyPoints >= this.energyMax) {
  422. this.onEnergyFull();
  423. // 能量满后重置为0,开始下一轮积累
  424. this.energyPoints = 0;
  425. }
  426. this.updateEnergyBar();
  427. }
  428. /**
  429. * 显示下一波提示
  430. */
  431. private showNextWavePrompt() {
  432. // 设置准备下一波的状态
  433. this.preparingNextWave = true;
  434. this.pendingBlockSelection = true;
  435. this.currentState = GameState.BLOCK_SELECTION;
  436. console.log('[InGameManager] 设置准备下一波状态,准备播放diban动画');
  437. // 如果当前没有技能选择UI显示,立即播放diban动画
  438. if (!this.selectSkillUI || !this.selectSkillUI.active) {
  439. this.playDibanAnimationForNextWave();
  440. }
  441. // 如果技能选择UI正在显示,则等待技能选择完成后再播放diban动画
  442. // 这种情况下,pendingBlockSelection已经在onEnemyKilledEvent中设置为true
  443. }
  444. /**
  445. * 游戏状态检查
  446. * 现在只检查敌人击败状态,墙体摧毁直接触发GAME_DEFEAT事件
  447. */
  448. private checkGameState() {
  449. // 墙体摧毁检查已移除,因为墙体现在直接触发GAME_DEFEAT事件
  450. // 这样与菜单退出的失败处理流程保持一致
  451. if (this.checkAllEnemiesDefeated()) {
  452. this.triggerGameSuccess();
  453. return;
  454. }
  455. }
  456. /**
  457. * 检查所有敌人是否被击败
  458. */
  459. private checkAllEnemiesDefeated(): boolean {
  460. // 如果敌人生成还未开始,不进行胜利检查
  461. if (!this.enemySpawningStarted) {
  462. return false;
  463. }
  464. // 基于当前波次的敌人击杀数量判断是否胜利
  465. // 如果当前波次的剩余敌人数量为0,且是最后一波,则胜利
  466. const currentWaveRemaining = this.currentWaveTotalEnemies - this.currentWaveEnemyCount;
  467. const isLastWave = this.currentWave >= (this.levelWaves?.length || 1);
  468. return currentWaveRemaining <= 0 && isLastWave;
  469. }
  470. /**
  471. * 触发游戏失败
  472. * 只负责记录游戏结束时间和发送事件,状态切换由GameEnd.ts统一处理
  473. */
  474. private triggerGameDefeat() {
  475. // 记录游戏结束时间
  476. this.gameEndTime = Date.now();
  477. // 触发游戏结束状态事件
  478. EventBus.getInstance().emit(GameEvents.ENTER_GAME_END_STATE, { result: 'defeat' });
  479. console.log('[InGameManager] 游戏失败,发送GAME_DEFEAT事件,状态切换由GameEnd.ts处理');
  480. EventBus.getInstance().emit(GameEvents.GAME_DEFEAT);
  481. }
  482. /**
  483. * 触发游戏成功
  484. * 只负责记录游戏结束时间和发送事件,状态切换由GameEnd.ts统一处理
  485. */
  486. private triggerGameSuccess() {
  487. // 记录游戏结束时间
  488. this.gameEndTime = Date.now();
  489. // 触发游戏结束状态事件
  490. EventBus.getInstance().emit(GameEvents.ENTER_GAME_END_STATE, { result: 'success' });
  491. console.log('[InGameManager] 游戏成功,发送GAME_SUCCESS事件,状态切换由GameEnd.ts处理');
  492. EventBus.getInstance().emit(GameEvents.GAME_SUCCESS);
  493. }
  494. /**
  495. * 获取游戏持续时间
  496. */
  497. public getGameDuration(): number {
  498. const endTime = this.gameEndTime || Date.now();
  499. return Math.max(0, endTime - this.gameStartTime);
  500. }
  501. /**
  502. * 获取当前游戏状态
  503. */
  504. public getCurrentState(): GameState {
  505. return this.currentState;
  506. }
  507. /**
  508. * 设置游戏状态
  509. */
  510. public setCurrentState(state: GameState) {
  511. this.currentState = state;
  512. // 当游戏状态变为PLAYING时,更新能量条显示
  513. if (state === GameState.PLAYING) {
  514. this.updateEnergyBar();
  515. }
  516. }
  517. /**
  518. * 初始化UI节点
  519. */
  520. private initUINodes() {
  521. // 初始化能量条
  522. if (this.energyBarNode) {
  523. this.energyBar = this.energyBarNode.getComponent(ProgressBar);
  524. if (this.energyBar) {
  525. console.log('[InGameManager] 能量条组件初始化成功');
  526. // 不在初始化阶段更新能量条,等待游戏状态变为PLAYING后再更新
  527. } else {
  528. console.error('[InGameManager] 能量条节点存在但ProgressBar组件未找到');
  529. }
  530. } else {
  531. console.error('[InGameManager] 能量条节点未通过装饰器挂载,请在Inspector中拖拽EnergyBar节点');
  532. }
  533. // 初始化技能选择UI
  534. if (this.selectSkillUINode) {
  535. this.selectSkillUI = this.selectSkillUINode;
  536. console.log('[InGameManager] 技能选择UI节点初始化成功');
  537. } else {
  538. console.error('[InGameManager] 技能选择UI节点未通过装饰器挂载,请在Inspector中拖拽SelectSkillUI节点');
  539. }
  540. // 初始化背景管理器
  541. if (this.backgroundManagerNode) {
  542. this.backgroundManager = this.backgroundManagerNode.getComponent(BackgroundManager);
  543. if (this.backgroundManager) {
  544. console.log('[InGameManager] 背景管理器组件初始化成功');
  545. } else {
  546. console.error('[InGameManager] 背景管理器节点存在但BackgroundManager组件未找到');
  547. }
  548. } else {
  549. console.error('[InGameManager] 背景管理器节点未通过装饰器挂载,请在Inspector中拖拽BackgroundManager节点');
  550. }
  551. // 初始化地面燃烧区域管理器
  552. if (this.groundBurnAreaManagerNode) {
  553. this.groundBurnAreaManager = this.groundBurnAreaManagerNode.getComponent(GroundBurnAreaManager);
  554. if (this.groundBurnAreaManager) {
  555. console.log('[InGameManager] 地面燃烧区域管理器组件初始化成功');
  556. } else {
  557. console.error('[InGameManager] 地面燃烧区域管理器节点存在但GroundBurnAreaManager组件未找到');
  558. }
  559. } else {
  560. console.error('[InGameManager] 地面燃烧区域管理器节点未通过装饰器挂载,请在Inspector中拖拽GroundBurnAreaManager节点');
  561. }
  562. }
  563. /**
  564. * 更新能量条显示
  565. */
  566. private updateEnergyBar() {
  567. // 只有在游戏状态为PLAYING时才更新能量条,避免初始化阶段的报错
  568. if (this.currentState !== GameState.PLAYING) {
  569. return;
  570. }
  571. if (this.energyBar && this.energyMax > 0) {
  572. const progress = this.energyPoints / this.energyMax;
  573. this.energyBar.progress = Math.min(progress, 1.0);
  574. console.log(`[InGameManager] 能量条更新: ${this.energyPoints}/${this.energyMax} (${Math.round(progress * 100)}%)`);
  575. } else {
  576. console.warn('[InGameManager] 能量条组件未初始化或energyMax未设置,无法更新显示');
  577. }
  578. }
  579. /**
  580. * 能量满时的处理
  581. */
  582. private onEnergyFull() {
  583. console.log('[InGameManager] 能量已满,开始升级处理');
  584. // 升级能量条
  585. this.upgradeEnergySystem();
  586. // 显示技能选择UI
  587. this.showSkillSelection();
  588. }
  589. /**
  590. * 升级能量系统
  591. */
  592. private upgradeEnergySystem() {
  593. // 增加升级次数
  594. this.energyUpgradeCount++;
  595. // 更新能量最大值
  596. // energyMaxUpgrades数组索引0是初始值,索引1是第1次升级后的值,以此类推
  597. if (this.energyUpgradeCount < this.energyMaxUpgrades.length) {
  598. const newMaxEnergy = this.energyMaxUpgrades[this.energyUpgradeCount];
  599. this.energyMax = newMaxEnergy;
  600. console.log(`[InGameManager] 能量条升级 ${this.energyUpgradeCount} 次,新的最大值: ${this.energyMax}`);
  601. } else {
  602. // 超出配置次数,按照上一次的值+1递增
  603. this.energyMax = this.energyMax + 1;
  604. console.log(`[InGameManager] 能量条升级超出配置次数,使用递增模式,新的最大值: ${this.energyMax}`);
  605. }
  606. // 立即更新能量条显示,确保新的最大值生效
  607. this.updateEnergyBar();
  608. }
  609. /**
  610. * 显示技能选择UI
  611. */
  612. private showSkillSelection() {
  613. if (this.selectSkillUI) {
  614. this.selectSkillUI.active = true;
  615. // 使用技能选择专用暂停事件,所有小球停止运动
  616. EventBus.getInstance().emit(GameEvents.GAME_PAUSE_SKILL_SELECTION);
  617. // 注意:不调用StartGame.resetEnergy(),因为那会重置整个能量系统包括最大值
  618. // 能量点数已在onEnergyFull()中重置为0
  619. }
  620. }
  621. /**
  622. * 恢复游戏
  623. */
  624. private resumeGame() {
  625. console.log('[InGameManager] 恢复游戏');
  626. EventBus.getInstance().emit(GameEvents.GAME_RESUME);
  627. }
  628. /**
  629. * 检查游戏是否结束
  630. */
  631. private isGameOver(): boolean {
  632. let gameOver = false;
  633. EventBus.getInstance().emit(GameEvents.GAME_CHECK_OVER, (isOver: boolean) => {
  634. gameOver = isOver;
  635. });
  636. return gameOver;
  637. }
  638. /**
  639. * 设置当前波次
  640. */
  641. public setCurrentWave(wave: number, enemyCount: number = 0) {
  642. this.currentWave = wave;
  643. this.currentWaveEnemyCount = 0; // 重置当前击杀数
  644. this.currentWaveTotalEnemies = enemyCount; // 设置该波次总敌人数
  645. const totalWaves = this.levelWaves?.length || 1;
  646. // 获取波次敌人配置
  647. const waveEnemyConfigs = this.getWaveEnemyConfigs(wave);
  648. // 获取当前波次的血量系数
  649. let healthMultiplier = 1.0;
  650. if (this.levelWaves && this.levelWaves.length > 0) {
  651. const waveIndex = wave - 1; // 波次从1开始,数组从0开始
  652. if (waveIndex >= 0 && waveIndex < this.levelWaves.length) {
  653. const waveData = this.levelWaves[waveIndex];
  654. if (waveData && typeof waveData.healthMultiplier === 'number') {
  655. healthMultiplier = waveData.healthMultiplier;
  656. }
  657. }
  658. }
  659. // 通过事件系统启动波次
  660. EventBus.getInstance().emit(GameEvents.ENEMY_START_WAVE, {
  661. wave: wave,
  662. totalWaves: totalWaves,
  663. enemyCount: enemyCount,
  664. waveEnemyConfigs: waveEnemyConfigs,
  665. healthMultiplier: healthMultiplier
  666. });
  667. }
  668. /**
  669. * 更新当前波次敌人数量
  670. */
  671. public updateCurrentWaveEnemyCount(count: number) {
  672. this.currentWaveEnemyCount = count;
  673. }
  674. /**
  675. * 获取当前波次
  676. */
  677. public getCurrentWave(): number {
  678. return this.currentWave;
  679. }
  680. /**
  681. * 获取当前波次敌人数量
  682. */
  683. public getCurrentWaveEnemyCount(): number {
  684. return this.currentWaveEnemyCount;
  685. }
  686. /**
  687. * 获取当前波次总敌人数量
  688. */
  689. public getCurrentWaveTotalEnemies(): number {
  690. return this.currentWaveTotalEnemies;
  691. }
  692. /**
  693. * 进入下一波
  694. */
  695. public nextWave() {
  696. this.currentWave++;
  697. // 根据关卡配置获取下一波敌人数
  698. let enemyTotal = 0;
  699. if (this.levelWaves && this.levelWaves.length >= this.currentWave) {
  700. const waveCfg = this.levelWaves[this.currentWave - 1];
  701. if (waveCfg && waveCfg.enemies) {
  702. enemyTotal = waveCfg.enemies.reduce((t: number, g: any) => t + (g.count || 0), 0);
  703. }
  704. }
  705. this.setCurrentWave(this.currentWave, enemyTotal);
  706. }
  707. /**
  708. * 获取当前能量值
  709. */
  710. public getCurrentEnergy(): number {
  711. return this.energyPoints;
  712. }
  713. /**
  714. * 获取最大能量值
  715. */
  716. public getMaxEnergy(): number {
  717. return this.energyMax;
  718. }
  719. /**
  720. * 获取墙体健康度(返回主墙体健康度)
  721. */
  722. public getWallHealth(): number {
  723. if (this.wallComponent) {
  724. return this.wallComponent.getCurrentHealth();
  725. }
  726. return 0;
  727. }
  728. /**
  729. * 获取所有墙体的健康度
  730. */
  731. public getAllWallsHealth(): { main: number; topFence: number; bottomFence: number } {
  732. return {
  733. main: this.wallComponent ? this.wallComponent.getCurrentHealth() : 0,
  734. topFence: this.topFenceComponent ? this.topFenceComponent.getCurrentHealth() : 0,
  735. bottomFence: this.bottomFenceComponent ? this.bottomFenceComponent.getCurrentHealth() : 0
  736. };
  737. }
  738. /**
  739. * 根据等级获取墙体健康度
  740. */
  741. public getWallHealthByLevel(level: number): number {
  742. if (this.wallComponent) {
  743. return this.wallComponent.getWallHealthByLevel(level);
  744. }
  745. return 100;
  746. }
  747. /**
  748. * 获取当前墙体等级(返回主墙体等级)
  749. */
  750. public getCurrentWallLevel(): number {
  751. if (this.wallComponent) {
  752. return this.wallComponent.getCurrentWallLevel();
  753. }
  754. return 1;
  755. }
  756. /**
  757. * 获取当前墙体健康度(返回主墙体健康度)
  758. */
  759. public getCurrentWallHealth(): number {
  760. if (this.wallComponent) {
  761. return this.wallComponent.getCurrentHealth();
  762. }
  763. return 100;
  764. }
  765. /**
  766. * 获取所有墙体的等级
  767. */
  768. public getAllWallsLevel(): { main: number; topFence: number; bottomFence: number } {
  769. return {
  770. main: this.wallComponent ? this.wallComponent.getCurrentWallLevel() : 1,
  771. topFence: this.topFenceComponent ? this.topFenceComponent.getCurrentWallLevel() : 1,
  772. bottomFence: this.bottomFenceComponent ? this.bottomFenceComponent.getCurrentWallLevel() : 1
  773. };
  774. }
  775. /**
  776. * 处理确认操作(方块选择确认)
  777. */
  778. public handleConfirmAction() {
  779. console.log('[InGameManager] 处理方块选择确认操作');
  780. // 如果是在准备下一波的状态,需要先切换到下一波
  781. if (this.preparingNextWave) {
  782. console.log('[InGameManager] 检测到准备下一波状态,切换到下一波');
  783. this.nextWave();
  784. // 重置状态
  785. this.preparingNextWave = false;
  786. this.pendingBlockSelection = false;
  787. this.currentState = GameState.PLAYING;
  788. }
  789. // 触发进入游玩状态事件
  790. EventBus.getInstance().emit(GameEvents.ENTER_PLAYING_STATE);
  791. // 注意:不再发送GAME_START事件,避免重复触发游戏启动流程
  792. // 游戏启动流程已在用户点击战斗按钮时完成,这里只需要启动游戏逻辑
  793. // 通过事件系统启动球的移动
  794. EventBus.getInstance().emit(GameEvents.BALL_START);
  795. console.log('[InGameManager] 发送BALL_START事件,球已启动');
  796. // 通过事件系统开始当前波次的敌人生成
  797. EventBus.getInstance().emit(GameEvents.ENEMY_START_GAME);
  798. EventBus.getInstance().emit(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT);
  799. console.log(`[InGameManager] 波次 ${this.currentWave} 敌人生成已启动`);
  800. }
  801. /**
  802. * 重置能量值(供StartGame调用)
  803. */
  804. public resetEnergyValue() {
  805. this.energyPoints = 0;
  806. this.updateEnergyBar();
  807. console.log('[InGameManager] 能量值重置完成');
  808. }
  809. /**
  810. * 重置波次信息(供StartGame调用)
  811. */
  812. public resetWaveInfo() {
  813. this.currentWave = 1;
  814. this.currentWaveEnemyCount = 0;
  815. this.currentWaveTotalEnemies = 0;
  816. this.enemiesKilled = 0;
  817. this.totalEnemiesSpawned = 0;
  818. this.levelTotalEnemies = 0;
  819. console.log('[InGameManager] 波次信息重置完成');
  820. }
  821. /**
  822. * 重置能量系统(供StartGame调用)
  823. * 注意:只在游戏真正重新开始时重置升级状态,技能选择后不应重置升级状态
  824. */
  825. public resetEnergySystem() {
  826. this.energyPoints = 0;
  827. // 只有在游戏状态不是BLOCK_SELECTION时才重置升级状态
  828. // 这样可以避免技能选择后重置已获得的能量升级
  829. if (this.currentState !== GameState.BLOCK_SELECTION) {
  830. this.energyUpgradeCount = 0;
  831. // 重置energyMax到初始值(energyMaxUpgrades数组的第一个值)
  832. if (this.energyMaxUpgrades && this.energyMaxUpgrades.length > 0) {
  833. this.energyMax = this.energyMaxUpgrades[0];
  834. }
  835. console.log('[InGameManager] 能量系统完全重置(包括升级状态)');
  836. } else {
  837. console.log('[InGameManager] 技能选择状态下,仅重置能量点数,保持升级状态');
  838. }
  839. this.updateEnergyBar();
  840. console.log('[InGameManager] 能量系统重置完成');
  841. }
  842. /**
  843. * 清理游戏数据,为返回主页面做准备
  844. * 当游戏胜利或失败返回主页面时调用
  845. */
  846. private cleanupGameDataForMainMenu() {
  847. console.log('[InGameManager] 开始清理游戏数据,准备返回主页面');
  848. const eventBus = EventBus.getInstance();
  849. // 1. 清空场上的所有游戏对象
  850. console.log('[InGameManager] 清空场上敌人、方块、球');
  851. eventBus.emit(GameEvents.CLEAR_ALL_ENEMIES); // 清空所有敌人
  852. eventBus.emit(GameEvents.CLEAR_ALL_BULLETS); // 清空所有子弹
  853. eventBus.emit(GameEvents.CLEAR_ALL_GAME_OBJECTS); // 清空其他游戏对象
  854. // 2. 重置能量系统
  855. console.log('[InGameManager] 重置能量系统');
  856. this.energyPoints = 0;
  857. this.updateEnergyBar();
  858. // 3. 清空技能选择数据(重置临时技能状态)
  859. console.log('[InGameManager] 清空技能选择数据');
  860. const skillManager = SkillManager.getInstance();
  861. if (skillManager) {
  862. skillManager.resetAllSkillLevels();
  863. }
  864. // 4. 重置关卡数据和游戏状态
  865. console.log('[InGameManager] 重置关卡数据和游戏状态');
  866. this.currentWave = 1;
  867. this.currentWaveEnemyCount = 0;
  868. this.currentWaveTotalEnemies = 0;
  869. this.enemiesKilled = 0;
  870. this.totalEnemiesSpawned = 0;
  871. this.levelTotalEnemies = 0;
  872. this.levelWaves = [];
  873. this.gameStarted = false;
  874. this.enemySpawningStarted = false;
  875. this.preparingNextWave = false;
  876. this.pendingSkillSelection = false;
  877. this.pendingBlockSelection = false;
  878. this.shouldShowNextWavePrompt = false;
  879. // 5. 重置UI状态
  880. console.log('[InGameManager] 重置UI状态');
  881. if (this.selectSkillUI) {
  882. this.selectSkillUI.active = false;
  883. }
  884. // 6. 清理会话数据(局内金币等临时数据)
  885. console.log('[InGameManager] 清理会话数据');
  886. if (LevelSessionManager.inst) {
  887. LevelSessionManager.inst.clear(); // 清空局内金币等临时数据
  888. }
  889. // 7. 通过事件系统通知其他组件进行清理
  890. eventBus.emit(GameEvents.RESET_BALL_CONTROLLER); // 重置球控制器
  891. eventBus.emit(GameEvents.RESET_BLOCK_MANAGER); // 重置方块管理器
  892. eventBus.emit(GameEvents.RESET_BLOCK_SELECTION); // 重置方块选择
  893. eventBus.emit(GameEvents.RESET_ENEMY_CONTROLLER); // 重置敌人控制器
  894. eventBus.emit(GameEvents.RESET_WALL_HEALTH); // 重置墙体血量
  895. eventBus.emit(GameEvents.RESET_UI_STATES); // 重置UI状态
  896. // 8. 重置镜头位置
  897. console.log('[InGameManager] 重置镜头位置');
  898. if (this.gameStartMoveComponent) {
  899. this.gameStartMoveComponent.resetCameraToOriginalPositionImmediate();
  900. } else {
  901. console.warn('[InGameManager] GameStartMove组件未找到,无法重置镜头位置');
  902. }
  903. // 9. 发送游戏结束事件,确保游戏状态正确转换
  904. console.log('[InGameManager] 发送游戏结束事件');
  905. eventBus.emit('GAME_END');
  906. // 10. 重置游戏状态为初始状态
  907. this.currentState = GameState.PLAYING;
  908. console.log('[InGameManager] 游戏数据清理完成,可以安全返回主页面');
  909. }
  910. /**
  911. * 重置游戏状态(供StartGame调用)
  912. */
  913. public resetGameStates() {
  914. this.currentState = GameState.PLAYING;
  915. this.gameStarted = false;
  916. this.enemySpawningStarted = false;
  917. this.preparingNextWave = false;
  918. this.pendingSkillSelection = false;
  919. this.pendingBlockSelection = false;
  920. this.shouldShowNextWavePrompt = false;
  921. this.gameStartTime = 0;
  922. this.gameEndTime = 0;
  923. this.checkTimer = 0;
  924. console.log('[InGameManager] 游戏状态重置完成');
  925. }
  926. // resetGameRecord方法已被移除,避免与cleanupGameDataForMainMenu重复
  927. // 所有清理逻辑已统一在cleanupGameDataForMainMenu中处理
  928. /**
  929. * 手动触发游戏数据清理(供外部调用)
  930. * 可以在返回主菜单按钮点击时调用
  931. */
  932. public triggerGameDataCleanup() {
  933. this.cleanupGameDataForMainMenu();
  934. }
  935. /**
  936. * 应用关卡配置
  937. */
  938. public async applyLevelConfig(levelConfig: any) {
  939. console.log('[InGameManager] 应用关卡配置');
  940. // 应用能量配置 - 现在从energyMaxUpgrades数组获取初始值
  941. let initialEnergyMax = 5; // 默认值
  942. // 先读取energyMaxUpgrades配置以获取初始能量最大值
  943. if (levelConfig.levelSettings && levelConfig.levelSettings.energyMaxUpgrades && Array.isArray(levelConfig.levelSettings.energyMaxUpgrades) && levelConfig.levelSettings.energyMaxUpgrades.length > 0) {
  944. initialEnergyMax = levelConfig.levelSettings.energyMaxUpgrades[0];
  945. console.log(`[InGameManager] 从energyMaxUpgrades获取初始能量配置: ${initialEnergyMax}`);
  946. } else {
  947. console.warn('[InGameManager] 警告:关卡配置中缺少 energyMaxUpgrades 设置,使用默认值!');
  948. }
  949. this.energyMax = initialEnergyMax;
  950. this.updateEnergyBar();
  951. // 应用新的能量条升级配置
  952. if (levelConfig.levelSettings) {
  953. // 读取能量条升级后最大值配置
  954. if (levelConfig.levelSettings.energyMaxUpgrades && Array.isArray(levelConfig.levelSettings.energyMaxUpgrades)) {
  955. this.energyMaxUpgrades = [...levelConfig.levelSettings.energyMaxUpgrades];
  956. console.log(`[InGameManager] 应用能量条升级配置: ${this.energyMaxUpgrades.length}个配置`);
  957. } else {
  958. // 默认升级配置(基于初始最大值递增)
  959. this.energyMaxUpgrades = [];
  960. for (let i = 0; i < 20; i++) {
  961. this.energyMaxUpgrades.push(this.energyMax + i + 1);
  962. }
  963. console.log('[InGameManager] 使用默认能量条升级配置');
  964. }
  965. this.energyUpgradeCount = 0;
  966. console.log('[InGameManager] 初始化能量条升级系统');
  967. }
  968. // 如果有武器配置,应用武器
  969. if (levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
  970. console.log('[InGameManager] 应用武器配置');
  971. // TODO: 应用武器配置逻辑
  972. }
  973. // 如果有波次配置,设置敌人波次
  974. if (levelConfig.waves && Array.isArray(levelConfig.waves)) {
  975. this.levelWaves = levelConfig.waves;
  976. this.currentWave = 1;
  977. // 计算本关卡总敌人数
  978. this.levelTotalEnemies = 0;
  979. for (const wave of this.levelWaves) {
  980. for (const enemy of wave.enemies || []) {
  981. this.levelTotalEnemies += enemy.count || 0;
  982. }
  983. }
  984. console.log(`[InGameManager] 应用波次配置: ${this.levelWaves.length}波,总敌人数: ${this.levelTotalEnemies}`);
  985. // 通过事件系统通知 EnemyController 初始化第一波数据及 UI
  986. const firstWaveEnemies = this.levelWaves.length > 0 && this.levelWaves[0].enemies ?
  987. this.levelWaves[0].enemies.reduce((t: number, g: any) => t + (g.count || 0), 0) : 0;
  988. // 通过事件系统调用setCurrentWave
  989. this.setCurrentWave(1, firstWaveEnemies);
  990. }
  991. // 应用背景图片配置
  992. if (this.backgroundManager && levelConfig.backgroundImage) {
  993. // 转换路径格式:从 "images/LevelBackground/BG1" 转换为 "LevelBackground/BG1"
  994. const bundlePath = levelConfig.backgroundImage.replace('images/', '');
  995. await this.backgroundManager.setBackground(bundlePath);
  996. console.log(`[InGameManager] 应用背景配置: ${levelConfig.backgroundImage}`);
  997. } else if (this.backgroundManager) {
  998. // 如果没有指定背景图片,使用默认背景
  999. await this.backgroundManager.setBackground('LevelBackground/BG1');
  1000. console.log('[InGameManager] 使用默认背景: LevelBackground/BG1');
  1001. }
  1002. }
  1003. onDestroy() {
  1004. const eventBus = EventBus.getInstance();
  1005. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  1006. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  1007. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  1008. eventBus.off(GameEvents.GAME_RESUME_SKILL_SELECTION, this.onGameResumeEvent, this);
  1009. eventBus.off(GameEvents.GAME_RESUME_BLOCK_SELECTION, this.onGameResumeEvent, this);
  1010. eventBus.off('ENEMY_KILLED', this.onEnemyKilledEvent, this);
  1011. eventBus.off(GameEvents.RESET_ENERGY_SYSTEM, this.resetEnergySystem, this);
  1012. eventBus.off(GameEvents.WALL_DESTROYED, this.onWallDestroyedEvent, this);
  1013. }
  1014. }