GameManager.ts 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. import { _decorator, Component, Node, find, director, UITransform, Button, Label, ProgressBar, } from 'cc';
  2. import { LevelManager } from './LevelManager';
  3. import { LevelConfigManager } from './LevelConfigManager';
  4. import { SaveDataManager } from './SaveDataManager';
  5. import { ConfigManager } from '../Core/ConfigManager';
  6. // EnemyController已通过事件系统解耦,不再需要直接导入
  7. import EventBus, { GameEvents } from '../Core/EventBus';
  8. import { PhysicsManager } from '../Core/PhysicsManager';
  9. import { LevelSessionManager } from '../Core/LevelSessionManager';
  10. import { GameBlockSelection } from '../CombatSystem/BlockSelection/GameBlockSelection';
  11. // GamePause已通过事件系统解耦,不再需要直接导入
  12. import { Wall } from '../CombatSystem/Wall';
  13. import { GameStartMove } from '../Animations/GameStartMove';
  14. import { ReStartGame } from './ReStartGame';
  15. import { InGameManager, GameState } from './IN_game';
  16. const { ccclass, property } = _decorator;
  17. /**
  18. * 全局应用状态枚举
  19. * 区分游戏外状态和游戏内状态
  20. */
  21. export enum AppState {
  22. // 游戏外状态 - 主界面相关
  23. MAIN_MENU = 'main_menu', // 主界面
  24. SHOP = 'shop', // 商店
  25. SKILLS = 'skills', // 技能界面
  26. SETTINGS = 'settings', // 设置界面
  27. // 游戏内状态 - 战斗相关
  28. IN_GAME = 'in_game' // 游戏进行中(包含所有游戏内子状态)
  29. }
  30. // GameState 枚举已迁移到 IN_game.ts
  31. /**
  32. * 增强版游戏管理器
  33. * 整合了游戏启动、状态管理、UI控制等功能
  34. */
  35. @ccclass('GameManager')
  36. export class GameManager extends Component {
  37. // === 原GameManager属性 ===
  38. @property({
  39. type: Node,
  40. tooltip: '拖拽BallController节点到这里'
  41. })
  42. public ballController: Node = null;
  43. @property({
  44. type: Node,
  45. tooltip: '拖拽GameBlockSelection节点到这里'
  46. })
  47. public gameBlockSelection: Node = null;
  48. @property({
  49. type: Node,
  50. tooltip: '拖拽GameArea节点到这里'
  51. })
  52. public gameArea: Node = null;
  53. @property({
  54. type: Node,
  55. tooltip: '拖拽EnemyController节点到这里'
  56. })
  57. public enemyManager: Node = null;
  58. // === 游戏状态管理属性 ===
  59. @property({
  60. type: Node,
  61. tooltip: '游戏结束UI节点 (GameEnd)'
  62. })
  63. public gameEndUI: Node = null;
  64. // === 游戏内管理器 ===
  65. @property({
  66. type: Node,
  67. tooltip: '游戏内状态管理器节点'
  68. })
  69. public inGameManagerNode: Node = null;
  70. // === UI节点引用 ===
  71. @property({
  72. type: Node,
  73. tooltip: '主界面UI节点 (Canvas/MainUI)'
  74. })
  75. public mainUI: Node = null;
  76. // === 动画组件引用 ===
  77. @property({
  78. type: Node,
  79. tooltip: '摄像机节点,用于获取GameStartMove组件'
  80. })
  81. public cameraNode: Node = null;
  82. // === 游戏配置属性 ===
  83. @property({
  84. tooltip: '状态检查间隔(秒)'
  85. })
  86. public checkInterval: number = 1.0;
  87. // === 私有属性 ===
  88. private gameStarted: boolean = false;
  89. private currentAppState: AppState = AppState.MAIN_MENU; // 全局应用状态
  90. private levelManager: LevelManager = null;
  91. private levelConfigManager: LevelConfigManager = null;
  92. private saveDataManager: SaveDataManager = null;
  93. private configManager: ConfigManager = null;
  94. // enemyController已通过事件系统解耦,不再需要直接引用
  95. // 游戏内管理器引用
  96. private inGameManager: InGameManager = null;
  97. // 游戏区域的边界
  98. private gameBounds = {
  99. left: 0,
  100. right: 0,
  101. top: 0,
  102. bottom: 0
  103. };
  104. // === 波次相关属性(已迁移到 InGameManager,保留用于兼容性) ===
  105. private currentWave: number = 1;
  106. private currentWaveEnemyCount: number = 0;
  107. private currentWaveTotalEnemies: number = 0;
  108. private totalEnemiesSpawned: number = 0;
  109. // levelWaves 和 levelTotalEnemies 已迁移到 InGameManager
  110. // === 能量系统属性已迁移到 InGameManager ===
  111. // === UI状态属性 ===
  112. private pendingSkillSelection: boolean = false;
  113. private shouldShowNextWavePrompt: boolean = false;
  114. // === 游戏计时器 ===
  115. private gameStartTime: number = 0;
  116. private gameEndTime: number = 0;
  117. private checkTimer: number = 0;
  118. // === 组件引用 ===
  119. private blockSelectionComponent: GameBlockSelection = null;
  120. private wallComponent: Wall = null;
  121. private gameStartMoveComponent: GameStartMove = null;
  122. // 游戏内状态相关方法已迁移到 InGameManager
  123. // === 游戏状态检查方法 ===
  124. private isGameOver(): boolean {
  125. // 通过事件系统检查游戏是否结束
  126. let isGameOver = false;
  127. const eventBus = EventBus.getInstance();
  128. eventBus.emit(GameEvents.GAME_CHECK_OVER, (result: boolean) => {
  129. isGameOver = result;
  130. });
  131. return isGameOver;
  132. }
  133. start() {
  134. // 初始化物理系统
  135. this.initPhysicsSystem();
  136. // 初始化管理器
  137. this.initializeManagers();
  138. // 提前初始化本局数据,确保 BlockManager 在 start 时能拿到正确金币
  139. if (!LevelSessionManager.inst.runtime) {
  140. LevelSessionManager.inst.initialize(
  141. this.saveDataManager?.getCurrentLevel() || 1,
  142. this.getWallHealth()
  143. );
  144. }
  145. // 计算游戏区域边界
  146. this.calculateGameBounds();
  147. // 初始化游戏状态
  148. this.initializeGameState();
  149. // 初始化UI节点
  150. this.initUINodes();
  151. // 敌人控制器已通过事件系统解耦,不再需要直接查找和设置
  152. // 设置UI按钮
  153. this.setupUIButtons();
  154. // 初始化组件
  155. this.initGameBlockSelection();
  156. this.initGameStartMove();
  157. // 加载当前关卡配置
  158. this.loadCurrentLevelConfig();
  159. // 监听GamePause状态变化事件
  160. this.setupGamePauseEventListeners();
  161. // 初始化游戏计时器
  162. this.gameStartTime = Date.now();
  163. }
  164. /**
  165. * 设置GamePause事件监听器
  166. */
  167. private setupGamePauseEventListeners() {
  168. const eventBus = EventBus.getInstance();
  169. // 监听游戏成功事件
  170. eventBus.on(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  171. // 监听游戏失败事件
  172. eventBus.on(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  173. // 监听游戏恢复事件
  174. eventBus.on(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  175. // 监听游戏重启事件
  176. eventBus.on(GameEvents.GAME_RESTART, this.onGameRestartEvent, this);
  177. // 监听重置游戏管理器事件
  178. eventBus.on(GameEvents.RESET_GAME_MANAGER, this.onResetGameManagerEvent, this);
  179. // 敌人击杀事件监听已迁移到 InGameManager
  180. }
  181. /**
  182. * 处理游戏成功事件
  183. */
  184. private onGameSuccessEvent() {
  185. console.log('[GameManager] 接收到游戏成功事件,执行成功处理');
  186. // 游戏状态管理已迁移到 InGameManager
  187. // 注意:不在这里切换到MAIN_MENU状态,保持IN_GAME状态
  188. // 只有用户点击成功界面的按钮时才切换到主界面
  189. // 显示游戏结束UI并设置成功文本
  190. if (this.gameEndUI) {
  191. this.gameEndUI.active = true;
  192. this.setEndLabelText('SUCCESS');
  193. }
  194. // 执行游戏成功逻辑
  195. this.onGameSuccess();
  196. }
  197. /**
  198. * 处理游戏失败事件
  199. */
  200. private onGameDefeatEvent() {
  201. console.log('[GameManager] 接收到游戏失败事件,执行失败处理');
  202. // 游戏状态管理已迁移到 InGameManager
  203. // 注意:不在这里切换到MAIN_MENU状态,保持IN_GAME状态
  204. // 只有用户点击失败界面的按钮时才切换到主界面
  205. // 显示游戏结束UI并设置失败文本
  206. if (this.gameEndUI) {
  207. this.gameEndUI.active = true;
  208. this.setEndLabelText('DEFEAT');
  209. }
  210. // 执行游戏失败逻辑
  211. this.onGameDefeat().catch(error => {
  212. console.error('[GameManager] 游戏失败处理出错:', error);
  213. });
  214. }
  215. /**
  216. * 处理游戏恢复事件
  217. */
  218. private onGameResumeEvent() {
  219. console.log('[GameManager] 接收到游戏恢复事件');
  220. // GameManager在这里可以处理恢复相关的逻辑
  221. // 但不直接调用EnemyController的方法,避免重复调用
  222. }
  223. /**
  224. * 处理游戏重启事件
  225. */
  226. private onGameRestartEvent() {
  227. console.log('[GameManager] 接收到游戏重启事件');
  228. this.restartGame();
  229. }
  230. /**
  231. * 处理重置游戏管理器事件
  232. */
  233. private onResetGameManagerEvent() {
  234. console.log('[GameManager] 接收到重置游戏管理器事件');
  235. // 重置游戏管理器状态
  236. this.currentAppState = AppState.IN_GAME;
  237. this.gameStarted = false;
  238. this.gameStartTime = 0;
  239. this.gameEndTime = 0;
  240. console.log('[GameManager] 游戏管理器状态已重置');
  241. }
  242. // 敌人击杀事件处理已迁移到 InGameManager
  243. // 游戏状态调试方法已迁移到 InGameManager
  244. // === 暂停游戏 ===
  245. private pauseGame() {
  246. // 通过事件系统触发游戏暂停
  247. const eventBus = EventBus.getInstance();
  248. eventBus.emit(GameEvents.GAME_PAUSE);
  249. }
  250. // === 恢复游戏 ===
  251. public resumeGame() {
  252. // 通过事件系统触发游戏恢复
  253. const eventBus = EventBus.getInstance();
  254. eventBus.emit(GameEvents.GAME_RESUME);
  255. if (this.gameEndUI) {
  256. this.gameEndUI.active = false;
  257. }
  258. // === 新增:恢复时弹出下一波提示Toast ===
  259. if (this.shouldShowNextWavePrompt) {
  260. this.shouldShowNextWavePrompt = false;
  261. // 通过事件系统显示下一波提示
  262. eventBus.emit(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT);
  263. }
  264. }
  265. update(deltaTime: number) {
  266. // 只有在游戏中时才进行游戏逻辑更新
  267. if (this.currentAppState !== AppState.IN_GAME) {
  268. return;
  269. }
  270. // 检查自动保存
  271. if (this.saveDataManager) {
  272. this.saveDataManager.checkAutoSave();
  273. }
  274. }
  275. // === 物理系统初始化 ===
  276. private initPhysicsSystem() {
  277. // 确保 PhysicsManager 单例存在
  278. let pm = PhysicsManager.getInstance();
  279. if (!pm) {
  280. const physicsNode = new Node('PhysicsManager');
  281. director.getScene()?.addChild(physicsNode);
  282. pm = physicsNode.addComponent(PhysicsManager);
  283. }
  284. }
  285. // === 管理器初始化 ===
  286. private initializeManagers() {
  287. this.levelManager = LevelManager.getInstance();
  288. // this.shopManager = ShopManager.getInstance();
  289. this.configManager = ConfigManager.getInstance();
  290. this.levelConfigManager = LevelConfigManager.getInstance();
  291. // enemyController已通过事件系统解耦,不再需要直接初始化
  292. // 初始化存档管理器
  293. this.saveDataManager = SaveDataManager.getInstance();
  294. this.saveDataManager.initialize();
  295. }
  296. // === 游戏状态初始化 ===
  297. private initializeGameState() {
  298. // 默认初始化为主菜单状态,游戏开始时会切换到IN_GAME
  299. this.currentAppState = AppState.MAIN_MENU;
  300. // 游戏内状态管理已迁移到 InGameManager
  301. this.pendingSkillSelection = false;
  302. }
  303. // === 计算游戏区域边界 ===
  304. private calculateGameBounds() {
  305. const canvas = find('Canvas');
  306. if (!canvas) {
  307. return;
  308. }
  309. const canvasUI = canvas.getComponent(UITransform);
  310. if (!canvasUI) {
  311. return;
  312. }
  313. const screenWidth = canvasUI.width;
  314. const screenHeight = canvasUI.height;
  315. const worldPos = canvas.worldPosition;
  316. this.gameBounds.left = worldPos.x - screenWidth / 2;
  317. this.gameBounds.right = worldPos.x + screenWidth / 2;
  318. this.gameBounds.bottom = worldPos.y - screenHeight / 2;
  319. this.gameBounds.top = worldPos.y + screenHeight / 2;
  320. }
  321. // === 初始化UI节点 ===
  322. private initUINodes() {
  323. // 初始化游戏结束UI
  324. if (this.gameEndUI) {
  325. this.gameEndUI.active = false;
  326. }
  327. // 初始化游戏内管理器
  328. if (this.inGameManagerNode) {
  329. this.inGameManager = this.inGameManagerNode.getComponent(InGameManager);
  330. }
  331. }
  332. // === 敌人控制器相关方法已通过事件系统解耦,不再需要 ===
  333. // === 游戏失败回调 ===
  334. private async onGameDefeat() {
  335. this.gameEndTime = Date.now();
  336. // 记录游戏失败到存档
  337. if (this.saveDataManager) {
  338. const currentLevel = this.saveDataManager.getCurrentLevel();
  339. this.saveDataManager.failLevel(currentLevel);
  340. // 计算波数完成比例并给予失败奖励
  341. // 波数信息已迁移到 InGameManager,通过InGameManager获取
  342. const inGameManager = this.getInGameManager();
  343. const totalWaves = inGameManager?.levelWaves?.length || 1;
  344. const completedWaves = inGameManager ? Math.max(0, inGameManager.getCurrentWave() - 1) : 0;
  345. const waveCompletionRatio = completedWaves / totalWaves;
  346. console.log(`[GameManager] 游戏失败 - 完成波数: ${completedWaves}/${totalWaves}, 比例: ${(waveCompletionRatio * 100).toFixed(1)}%`);
  347. // 给予基于波数比例的失败奖励
  348. await this.saveDataManager.giveFailureRewards(currentLevel, waveCompletionRatio, this.getGameDuration());
  349. // 更新统计数据
  350. this.saveDataManager.updateStatistic('totalTimePlayed', this.getGameDuration());
  351. }
  352. }
  353. // === 游戏成功回调 ===
  354. private async onGameSuccess() {
  355. this.gameEndTime = Date.now();
  356. await this.giveReward();
  357. this.onLevelComplete();
  358. }
  359. // === 给予奖励 ===
  360. private async giveReward() {
  361. if (!this.saveDataManager) return;
  362. const currentLevel = this.saveDataManager.getCurrentLevel();
  363. // 给予JSON配置中的基础奖励
  364. await this.saveDataManager.giveCompletionRewards(currentLevel);
  365. }
  366. // === 处理关卡完成 ===
  367. private onLevelComplete() {
  368. if (!this.saveDataManager) return;
  369. const currentLevel = this.saveDataManager.getCurrentLevel();
  370. const gameTime = this.getGameDuration();
  371. // 记录关卡完成到存档
  372. this.saveDataManager.completeLevel(currentLevel, 0, gameTime);
  373. // 更新统计数据
  374. this.saveDataManager.updateStatistic('totalTimePlayed', gameTime);
  375. this.saveDataManager.updateStatistic('totalEnemiesDefeated', this.totalEnemiesSpawned);
  376. // 兼容原有的LevelManager
  377. if (this.levelManager) {
  378. this.levelManager.completeLevel(currentLevel, 0);
  379. }
  380. }
  381. // === 计算游戏时长 ===
  382. private getGameDuration(): number {
  383. if (this.gameStartTime === 0) return 0;
  384. const endTime = this.gameEndTime || Date.now();
  385. return Math.floor((endTime - this.gameStartTime) / 1000);
  386. }
  387. // === 设置UI按钮 ===
  388. private setupUIButtons() {
  389. this.setupEndUIButtons();
  390. }
  391. /**
  392. * 设置游戏结束UI的EndLabel文本
  393. * @param text 要显示的文本 ('SUCCESS' 或 'DEFEAT')
  394. */
  395. private setEndLabelText(text: string) {
  396. if (!this.gameEndUI) return;
  397. const endLabel = this.gameEndUI.getChildByPath('Sprite/EndLabel');
  398. if (endLabel) {
  399. const labelComponent = endLabel.getComponent(Label);
  400. if (labelComponent) {
  401. labelComponent.string = text;
  402. console.log(`[GameManager] 设置EndLabel文本为: ${text}`);
  403. } else {
  404. console.warn('[GameManager] 未找到EndLabel的Label组件');
  405. }
  406. } else {
  407. console.warn('[GameManager] 未找到EndLabel节点路径: Sprite/EndLabel');
  408. }
  409. }
  410. // === 设置游戏结束界面按钮 ===
  411. private setupEndUIButtons() {
  412. if (this.gameEndUI) {
  413. const restartBtn = this.gameEndUI.getChildByName('RestartBtn');
  414. const mainMenuBtn = this.gameEndUI.getChildByName('MainMenuBtn');
  415. const shopBtn = this.gameEndUI.getChildByName('ShopBtn');
  416. const reviveBtn = this.gameEndUI.getChildByName('ReviveBtn');
  417. if (restartBtn) {
  418. const button = restartBtn.getComponent(Button);
  419. if (button) {
  420. button.node.on(Button.EventType.CLICK, this.onRestartClick, this);
  421. }
  422. }
  423. if (mainMenuBtn) {
  424. const button = mainMenuBtn.getComponent(Button);
  425. if (button) {
  426. button.node.on(Button.EventType.CLICK, this.onMainMenuClick, this);
  427. }
  428. }
  429. if (shopBtn) {
  430. const button = shopBtn.getComponent(Button);
  431. if (button) {
  432. button.node.on(Button.EventType.CLICK, this.onShopClick, this);
  433. }
  434. }
  435. if (reviveBtn) {
  436. const button = reviveBtn.getComponent(Button);
  437. if (button) {
  438. button.node.on(Button.EventType.CLICK, this.onReviveClick, this);
  439. }
  440. }
  441. }
  442. }
  443. // === 按钮点击事件处理 ===
  444. private onRestartClick() {
  445. console.log('[GameManager] 重新开始游戏');
  446. // 通过事件系统触发游戏重启
  447. const eventBus = EventBus.getInstance();
  448. eventBus.emit(GameEvents.GAME_RESTART);
  449. }
  450. private onMainMenuClick() {
  451. console.log('[GameManager] 返回主菜单');
  452. // 首先清理游戏数据
  453. if (this.inGameManager) {
  454. console.log('[GameManager] 触发游戏数据清理');
  455. this.inGameManager.triggerGameDataCleanup();
  456. }
  457. // 使用装饰器属性获取MainUI,避免使用find
  458. if (!this.mainUI) {
  459. console.error('[GameManager] MainUI节点未在编辑器中设置,请拖拽Canvas/MainUI到GameManager的mainUI属性');
  460. return;
  461. }
  462. const mainUIController = this.mainUI.getComponent('MainUIController' as any);
  463. if (mainUIController) {
  464. // 游戏状态检查已迁移到 InGameManager,这里使用默认的奖励动画返回
  465. if (typeof (mainUIController as any).onReturnToMainUIWithReward === 'function') {
  466. console.log('[GameManager] 调用带奖励动画的返回主界面方法');
  467. (mainUIController as any).onReturnToMainUIWithReward();
  468. } else if (typeof (mainUIController as any).onReturnToMainUI === 'function') {
  469. console.log('[GameManager] 调用普通返回主界面方法');
  470. (mainUIController as any).onReturnToMainUI();
  471. } else {
  472. console.warn('[GameManager] 未找到返回主界面方法,使用兜底逻辑');
  473. this.fallbackMainMenuLogic(mainUIController);
  474. }
  475. } else {
  476. console.error('[GameManager] 未找到MainUIController组件');
  477. this.fallbackMainMenuLogic(null);
  478. }
  479. }
  480. /**
  481. * 兜底逻辑:当找不到MainUIController或相关方法时使用
  482. */
  483. private fallbackMainMenuLogic(mainUIController: any) {
  484. console.warn('[GameManager] 使用兜底逻辑返回主界面');
  485. const gameLevelUI = find('Canvas/GameLevelUI');
  486. if (gameLevelUI) gameLevelUI.active = false;
  487. if (this.mainUI) this.mainUI.active = true;
  488. if (mainUIController && typeof (mainUIController as any).updateUI === 'function') {
  489. (mainUIController as any).updateUI();
  490. }
  491. }
  492. private onShopClick() {
  493. console.log('[GameManager] 商店按钮被点击');
  494. // TODO: 实现商店逻辑
  495. }
  496. private onReviveClick() {
  497. const reviveCost = 10; // 复活消耗的钻石数量
  498. if (this.saveDataManager && this.saveDataManager.spendDiamonds(reviveCost)) {
  499. this.revivePlayer();
  500. }
  501. }
  502. // === 复活玩家 ===
  503. private revivePlayer() {
  504. if (this.wallComponent) {
  505. this.wallComponent.setHealth(50);
  506. }
  507. // 通过事件系统进行完整重置
  508. const eventBus = EventBus.getInstance();
  509. eventBus.emit(GameEvents.GAME_RESTART);
  510. }
  511. // === 重新开始当前关卡 ===
  512. private restartCurrentLevel() {
  513. // 通过事件系统进行完整重置
  514. const eventBus = EventBus.getInstance();
  515. eventBus.emit(GameEvents.GAME_RESTART);
  516. }
  517. public startGame() {
  518. if (this.gameStarted) return;
  519. this.gameStarted = true;
  520. this.gameStartTime = Date.now();
  521. // 游戏状态管理已迁移到 InGameManager
  522. // 发送游戏开始事件,通知其他组件
  523. const eventBus = EventBus.getInstance();
  524. eventBus.emit(GameEvents.GAME_START);
  525. console.log('[GameManager] 发送游戏开始事件');
  526. // 开始生成球
  527. this.spawnBall();
  528. // 启动状态检查
  529. this.checkTimer = 0;
  530. // 设置UI按钮事件
  531. this.setupUIButtons();
  532. // 第一波提示UI后再开始生成敌人
  533. // 通过事件系统显示开始波次提示
  534. eventBus.emit(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT);
  535. // 通过事件系统开始敌人生成
  536. eventBus.emit(GameEvents.ENEMY_START_GAME);
  537. LevelSessionManager.inst.initialize(
  538. SaveDataManager.getInstance().getCurrentLevel(),
  539. this.getWallHealth()
  540. );
  541. }
  542. private spawnBall() {
  543. // 通过事件系统启动球的移动
  544. const eventBus = EventBus.getInstance();
  545. eventBus.emit(GameEvents.BALL_START);
  546. console.log('[GameManager] 发送BALL_START事件,球已启动');
  547. }
  548. public gameOver() {
  549. this.triggerGameDefeat();
  550. }
  551. // === 公共方法 ===
  552. public setHealth(health: number) {
  553. this.wallComponent?.setHealth(health);
  554. }
  555. public takeDamage(damage: number) {
  556. this.wallComponent?.takeDamage(damage);
  557. if (this.wallComponent?.getCurrentHealth() <= 0) {
  558. this.triggerGameDefeat();
  559. }
  560. }
  561. /**
  562. * 获取当前全局应用状态
  563. */
  564. public getCurrentAppState(): AppState {
  565. return this.currentAppState;
  566. }
  567. /**
  568. * 设置全局应用状态
  569. */
  570. public setAppState(state: AppState): void {
  571. console.log(`[GameManager] 应用状态切换: ${this.currentAppState} -> ${state}`);
  572. this.currentAppState = state;
  573. // 根据状态控制UI栏显示
  574. this.updateUIBarsVisibility(state);
  575. // 游戏内状态管理已迁移到 InGameManager
  576. }
  577. /**
  578. * 根据应用状态更新UI栏显示
  579. */
  580. private updateUIBarsVisibility(state: AppState): void {
  581. const topBarNode = find('Canvas/TopBar');
  582. const navBarNode = find('Canvas/NavBar');
  583. if (state === AppState.IN_GAME) {
  584. // 游戏内状态:隐藏TopBar和NavBar
  585. if (topBarNode) topBarNode.active = false;
  586. if (navBarNode) navBarNode.active = false;
  587. console.log('[GameManager] 游戏内状态:隐藏TopBar和NavBar');
  588. } else {
  589. // 游戏外状态:显示TopBar和NavBar
  590. if (topBarNode) topBarNode.active = true;
  591. if (navBarNode) navBarNode.active = true;
  592. console.log('[GameManager] 游戏外状态:显示TopBar和NavBar');
  593. }
  594. }
  595. /**
  596. * 获取当前游戏内状态已迁移到 InGameManager
  597. * 请使用 InGameManager.getInstance().getCurrentState()
  598. */
  599. /**
  600. * 获取InGameManager实例
  601. * 用于访问游戏内状态和逻辑
  602. */
  603. public getInGameManager(): InGameManager | null {
  604. return this.inGameManager;
  605. }
  606. /**
  607. * 获取当前游戏内状态
  608. * 通过InGameManager获取
  609. */
  610. public getCurrentGameState(): GameState | null {
  611. return this.inGameManager ? this.inGameManager.getCurrentState() : null;
  612. }
  613. /**
  614. * 检查是否在游戏中
  615. */
  616. public isInGame(): boolean {
  617. return this.currentAppState === AppState.IN_GAME;
  618. }
  619. /**
  620. * 从方块选择状态切换到游戏进行状态
  621. * 当玩家完成方块选择后调用
  622. */
  623. public startGameFromBlockSelection(): void {
  624. if (this.currentAppState !== AppState.IN_GAME) {
  625. console.warn('[GameManager] 不在游戏中,无法开始游戏');
  626. return;
  627. }
  628. // 游戏状态检查已迁移到 InGameManager
  629. console.log('[GameManager] 从方块选择状态切换到游戏进行状态,播放退出动画');
  630. // 播放退出BLOCK_SELECTION状态的动画
  631. if (this.gameStartMoveComponent) {
  632. console.log('[GameManager] 执行退出BLOCK_SELECTION状态的动画');
  633. this.gameStartMoveComponent.exitBlockSelectionMode(300, 0.3);
  634. }
  635. // 游戏状态管理已迁移到 InGameManager
  636. // 发送游戏开始事件,通知GamePause等组件
  637. const eventBus = EventBus.getInstance();
  638. eventBus.emit(GameEvents.GAME_START);
  639. console.log('[GameManager] 从方块选择切换到游戏时发送游戏开始事件');
  640. }
  641. public restartGame() {
  642. console.log('[GameManager] 重新开始游戏');
  643. // 设置应用状态为游戏中
  644. this.currentAppState = AppState.IN_GAME;
  645. this.gameStarted = false;
  646. this.gameStartTime = 0;
  647. this.gameEndTime = 0;
  648. // 通过事件系统重置游戏状态
  649. const eventBus = EventBus.getInstance();
  650. eventBus.emit(GameEvents.RESET_GAME_MANAGER);
  651. console.log('[GameManager] 游戏状态重置完成');
  652. }
  653. public forceGameSuccess() {
  654. this.triggerGameSuccess();
  655. }
  656. public forceGameDefeat() {
  657. this.triggerGameDefeat();
  658. }
  659. // === 触发游戏成功 ===
  660. private triggerGameSuccess() {
  661. console.log('[GameManager] 触发游戏成功');
  662. const eventBus = EventBus.getInstance();
  663. eventBus.emit(GameEvents.GAME_SUCCESS);
  664. }
  665. // === 触发游戏失败 ===
  666. private triggerGameDefeat() {
  667. console.log('[GameManager] 触发游戏失败');
  668. const eventBus = EventBus.getInstance();
  669. eventBus.emit(GameEvents.GAME_DEFEAT);
  670. }
  671. // === EnemyController相关方法已通过事件系统解耦,不再需要直接访问 ===
  672. public setTotalEnemiesSpawned(count: number) {
  673. this.totalEnemiesSpawned = count;
  674. }
  675. onDestroy() {
  676. // 清理GamePause事件监听
  677. const eventBus = EventBus.getInstance();
  678. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  679. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  680. eventBus.off(GameEvents.GAME_RESTART, this.onGameRestartEvent, this);
  681. eventBus.off(GameEvents.RESET_GAME_MANAGER, this.onResetGameManagerEvent, this);
  682. // ENEMY_KILLED事件监听已迁移到 InGameManager
  683. // 清理按钮事件监听
  684. if (this.gameEndUI) {
  685. const buttons = this.gameEndUI.getComponentsInChildren(Button);
  686. buttons.forEach(button => {
  687. button.node.off(Button.EventType.CLICK);
  688. });
  689. }
  690. // 清理单例实例
  691. if (GameManager._instance === this) {
  692. GameManager._instance = null;
  693. }
  694. }
  695. // === 加载当前关卡配置 ===
  696. public async loadCurrentLevelConfig() {
  697. if (!this.saveDataManager || !this.levelConfigManager) return;
  698. const currentLevel = this.saveDataManager.getCurrentLevel();
  699. try {
  700. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  701. if (levelConfig) {
  702. this.applyLevelConfig(levelConfig);
  703. } else {
  704. console.warn(`关卡 ${currentLevel} 配置加载失败`);
  705. }
  706. } catch (error) {
  707. console.error(`关卡 ${currentLevel} 配置加载错误:`, error);
  708. }
  709. }
  710. private applyLevelConfig(levelConfig: any) {
  711. console.log('[GameManager] 委托关卡配置应用给InGameManager');
  712. // 委托给InGameManager处理关卡配置
  713. if (this.inGameManager) {
  714. this.inGameManager.applyLevelConfig(levelConfig);
  715. } else {
  716. console.warn('[GameManager] InGameManager未初始化,无法应用关卡配置');
  717. // 备用方案:基本的波次配置处理(已简化)
  718. if (levelConfig.waves && Array.isArray(levelConfig.waves)) {
  719. this.currentWave = 1;
  720. console.log('[GameManager] 使用备用方案处理波次配置(功能有限)');
  721. console.warn('[GameManager] 建议确保InGameManager正确初始化以获得完整功能');
  722. }
  723. }
  724. }
  725. // === 获取当前关卡信息 ===
  726. public async getCurrentLevelInfo() {
  727. const currentLevel = this.saveDataManager ?
  728. this.saveDataManager.getCurrentLevel() :
  729. (this.levelManager ? this.levelManager.getCurrentLevel() : 1);
  730. const levelProgress = this.saveDataManager ?
  731. this.saveDataManager.getLevelProgress(currentLevel) : null;
  732. const levelData = this.levelManager ?
  733. this.levelManager.getLevelData(currentLevel) : null;
  734. const levelConfig = await this.loadCurrentLevelConfig();
  735. return {
  736. level: currentLevel,
  737. maxUnlockedLevel: this.saveDataManager ?
  738. this.saveDataManager.getMaxUnlockedLevel() :
  739. (this.levelManager ? this.levelManager.getMaxUnlockedLevel() : 1),
  740. progress: levelProgress,
  741. data: levelData,
  742. config: levelConfig,
  743. playerData: this.saveDataManager ? {
  744. coins: this.saveDataManager.getCoins(),
  745. diamonds: this.saveDataManager.getDiamonds(),
  746. gems: this.saveDataManager.getGems(),
  747. wallLevel: this.saveDataManager.getWallLevel()
  748. } : null
  749. };
  750. }
  751. // === 波次管理和能量系统已迁移到 InGameManager ===
  752. // 这些方法现在委托给 InGameManager 处理
  753. // === 获取当前波次(委托给InGameManager)===
  754. public getCurrentWave(): number {
  755. if (this.inGameManager) {
  756. return this.inGameManager.getCurrentWave();
  757. }
  758. return this.currentWave;
  759. }
  760. // === 获取当前能量值(委托给InGameManager)===
  761. public getCurrentEnergy(): number {
  762. if (this.inGameManager) {
  763. return this.inGameManager.getCurrentEnergy();
  764. }
  765. return 0; // 默认值
  766. }
  767. // === 获取最大能量值(委托给InGameManager)===
  768. public getMaxEnergy(): number {
  769. if (this.inGameManager) {
  770. return this.inGameManager.getMaxEnergy();
  771. }
  772. return 5; // 默认值
  773. }
  774. /* ========= 墙体血量 / 等级相关 ========= */
  775. // === 获取墙体血量(委托给InGameManager)===
  776. private getWallHealth(): number {
  777. if (this.inGameManager) {
  778. return this.inGameManager.getWallHealth();
  779. }
  780. // 备用方案:直接访问墙体组件
  781. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  782. }
  783. // === 墙体血量 / 等级相关方法 - 现在委托给InGameManager ===
  784. public getWallHealthByLevel(level: number): number {
  785. if (this.inGameManager) {
  786. return this.inGameManager.getWallHealthByLevel(level);
  787. }
  788. // 备用方案:直接访问墙体组件
  789. return this.wallComponent ? this.wallComponent.getWallHealthByLevel(level) : 100;
  790. }
  791. public getCurrentWallLevel(): number {
  792. if (this.inGameManager) {
  793. return this.inGameManager.getCurrentWallLevel();
  794. }
  795. // 备用方案:直接访问墙体组件
  796. return this.wallComponent ? this.wallComponent.getCurrentWallLevel() : 1;
  797. }
  798. public getCurrentWallHealth(): number {
  799. if (this.inGameManager) {
  800. return this.inGameManager.getCurrentWallHealth();
  801. }
  802. // 备用方案:直接访问墙体组件
  803. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  804. }
  805. public upgradeWallLevel(): { currentLevel: number; currentHp: number; nextLevel: number; nextHp: number } | null {
  806. if (this.inGameManager) {
  807. return this.inGameManager.upgradeWallLevel();
  808. }
  809. // 备用方案:直接访问墙体组件
  810. return this.wallComponent ? this.wallComponent.upgradeWallLevel() : null;
  811. }
  812. // 初始化GameBlockSelection组件
  813. private initGameBlockSelection() {
  814. if (this.gameBlockSelection) {
  815. this.blockSelectionComponent = this.gameBlockSelection.getComponent(GameBlockSelection);
  816. if (this.blockSelectionComponent) {
  817. // 设置确认回调
  818. this.blockSelectionComponent.setConfirmCallback(() => {
  819. this.handleConfirmAction();
  820. });
  821. }
  822. }
  823. }
  824. // 初始化GameStartMove组件
  825. private initGameStartMove() {
  826. if (this.cameraNode) {
  827. this.gameStartMoveComponent = this.cameraNode.getComponent(GameStartMove);
  828. if (this.gameStartMoveComponent) {
  829. console.log('[GameManager] GameStartMove组件初始化成功');
  830. } else {
  831. console.warn('[GameManager] 未找到GameStartMove组件');
  832. }
  833. } else {
  834. console.warn('[GameManager] 摄像机节点未设置,无法初始化GameStartMove组件');
  835. }
  836. }
  837. // 处理确认操作(委托给InGameManager)
  838. private handleConfirmAction() {
  839. console.log('[GameManager] 方块选择确认,委托给InGameManager处理');
  840. // 委托给InGameManager处理确认操作
  841. if (this.inGameManager) {
  842. this.inGameManager.handleConfirmAction();
  843. } else {
  844. console.warn('[GameManager] InGameManager未初始化,无法处理确认操作');
  845. }
  846. }
  847. // === 单例模式支持 ===
  848. private static _instance: GameManager = null;
  849. /**
  850. * 获取GameManager单例实例
  851. */
  852. public static getInstance(): GameManager {
  853. return GameManager._instance;
  854. }
  855. /**
  856. * 设置GameManager单例实例
  857. */
  858. public static setInstance(instance: GameManager): void {
  859. GameManager._instance = instance;
  860. }
  861. onLoad() {
  862. // 设置单例实例
  863. GameManager.setInstance(this);
  864. }
  865. }