GameManager.ts 35 KB

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