GameManager.ts 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. // 检查是否需要解锁商店功能(第3关完成后解锁)
  349. this.checkShopUnlock(currentLevel);
  350. console.log(`[GameManager] 关卡完成记录已保存,关卡: ${currentLevel}, 游戏时长: ${gameTime}秒`);
  351. }
  352. /**
  353. * 检查商店解锁条件
  354. * @param completedLevel 完成的关卡数
  355. */
  356. private checkShopUnlock(completedLevel: number) {
  357. // 第3关完成后解锁商店
  358. if (completedLevel >= 3) {
  359. const navBarNode = find('Canvas/NavBar');
  360. if (navBarNode) {
  361. const navBarController = navBarNode.getComponent('NavBarController') as any;
  362. if (navBarController && typeof navBarController.unlockButton === 'function') {
  363. // 解锁商店按钮(索引3对应商店按钮)
  364. navBarController.unlockButton(3);
  365. console.log('[GameManager] 商店功能已解锁');
  366. }
  367. }
  368. }
  369. }
  370. // clearPreviousGameRecord方法已被移除,其功能已整合到onMainMenuClick中
  371. // 避免重复清理游戏数据
  372. // === 计算游戏时长 ===
  373. private getGameDuration(): number {
  374. if (this.gameStartTime === 0) return 0;
  375. const endTime = this.gameEndTime || Date.now();
  376. return Math.floor((endTime - this.gameStartTime) / 1000);
  377. }
  378. // === 设置UI按钮 ===
  379. private setupUIButtons() {
  380. this.setupEndUIButtons();
  381. }
  382. // === 设置游戏结束界面按钮 ===
  383. private setupEndUIButtons() {
  384. // UI按钮事件处理已迁移到 UIStateManager
  385. // 通过事件系统处理按钮点击事件
  386. }
  387. // === 按钮点击事件处理 ===
  388. private onMainMenuClick() {
  389. console.log('[GameManager] 返回主菜单');
  390. // 1. 获取当前游戏状态,判断是否为获胜状态
  391. const inGameManager = this.getInGameManager();
  392. const currentGameState = inGameManager?.getCurrentState();
  393. const isGameSuccess = currentGameState === GameState.SUCCESS;
  394. console.log(`[GameManager] 当前游戏状态:${currentGameState},开始清理游戏数据`);
  395. console.log(`[GameManager] GameState.SUCCESS值:${GameState.SUCCESS}`);
  396. console.log(`[GameManager] 状态比较结果 isGameSuccess:${isGameSuccess}`);
  397. console.log(`[GameManager] 严格比较:${currentGameState} === ${GameState.SUCCESS} = ${currentGameState === GameState.SUCCESS}`);
  398. // 2. 统一进行游戏数据清理(只调用一次,避免重复清理)
  399. if (inGameManager) {
  400. console.log('[GameManager] 触发游戏数据清理');
  401. inGameManager.triggerGameDataCleanup();
  402. } else {
  403. console.warn('[GameManager] 未找到InGameManager,跳过游戏数据清理');
  404. }
  405. // 3. 发送重置UI状态事件,让UIStateManager统一关闭所有相关面板
  406. const eventBus = EventBus.getInstance();
  407. eventBus.emit(GameEvents.RESET_UI_STATES);
  408. // 4. 重置GameManager自身的记录(不调用InGameManager的重复清理)
  409. this.gameStartTime = 0;
  410. this.gameEndTime = 0;
  411. this.totalEnemiesSpawned = 0;
  412. console.log('[GameManager] GameManager记录已重置');
  413. // 5. 根据游戏结果决定关卡处理:获胜时进入下一关,失败时保持当前关
  414. if (this.saveDataManager) {
  415. if (isGameSuccess) {
  416. // 获胜后进入下一关
  417. const currentLevel = this.saveDataManager.getCurrentLevel();
  418. const nextLevel = currentLevel + 1;
  419. this.saveDataManager.setCurrentLevel(nextLevel);
  420. console.log(`[GameManager] 游戏获胜,从第${currentLevel}关进入第${nextLevel}关`);
  421. } else {
  422. // 失败时保持当前关卡,不重置
  423. const currentLevel = this.saveDataManager.getCurrentLevel();
  424. console.log(`[GameManager] 游戏失败,保持当前关卡: ${currentLevel}`);
  425. }
  426. }
  427. // 6. 重置应用状态为主菜单
  428. this.currentAppState = AppState.MAIN_MENU;
  429. console.log('[GameManager] 应用状态已重置为MAIN_MENU');
  430. // 6. 触发返回主菜单事件
  431. eventBus.emit(GameEvents.RETURN_TO_MAIN_MENU);
  432. // 使用装饰器属性获取MainUI,避免使用find
  433. if (!this.mainUI) {
  434. console.error('[GameManager] MainUI节点未在编辑器中设置,请拖拽Canvas/MainUI到GameManager的mainUI属性');
  435. return;
  436. }
  437. const mainUIController = this.mainUI.getComponent('MainUIController' as any);
  438. if (mainUIController) {
  439. // 奖励动画已迁移到GameEnd.ts中,这里只需要普通返回主界面
  440. if (typeof (mainUIController as any).onReturnToMainUI === 'function') {
  441. console.log('[GameManager] 调用普通返回主界面方法');
  442. (mainUIController as any).onReturnToMainUI();
  443. } else {
  444. console.warn('[GameManager] 未找到返回主界面方法,使用兜底逻辑');
  445. this.fallbackMainMenuLogic(mainUIController);
  446. }
  447. } else {
  448. console.error('[GameManager] 未找到MainUIController组件');
  449. this.fallbackMainMenuLogic(null);
  450. }
  451. }
  452. /**
  453. * 兜底逻辑:当找不到MainUIController或相关方法时使用
  454. */
  455. private fallbackMainMenuLogic(mainUIController: any) {
  456. console.warn('[GameManager] 使用兜底逻辑返回主界面');
  457. if (this.mainUI) this.mainUI.active = true;
  458. if (mainUIController && typeof (mainUIController as any).updateUI === 'function') {
  459. (mainUIController as any).updateUI();
  460. }
  461. }
  462. private onUpgradeClick() {
  463. console.log('[GameManager] 升级按钮被点击');
  464. // TODO: 实现升级逻辑
  465. }
  466. private onReviveClick() {
  467. const reviveCost = 10; // 复活消耗的钻石数量
  468. if (this.saveDataManager && this.saveDataManager.spendDiamonds(reviveCost)) {
  469. this.revivePlayer();
  470. }
  471. }
  472. // === 复活玩家 ===
  473. private revivePlayer() {
  474. if (this.wallComponent) {
  475. this.wallComponent.setHealth(50);
  476. }
  477. // 通过事件系统进行完整重置
  478. const eventBus = EventBus.getInstance();
  479. eventBus.emit(GameEvents.GAME_RESTART);
  480. }
  481. // === 重新开始当前关卡 ===
  482. private restartCurrentLevel() {
  483. // 通过事件系统进行完整重置
  484. const eventBus = EventBus.getInstance();
  485. eventBus.emit(GameEvents.GAME_RESTART);
  486. }
  487. public startGame() {
  488. if (this.gameStarted) return;
  489. this.gameStarted = true;
  490. this.gameStartTime = Date.now();
  491. // 游戏状态管理已迁移到 InGameManager
  492. // 发送游戏开始事件,通知其他组件
  493. const eventBus = EventBus.getInstance();
  494. eventBus.emit(GameEvents.GAME_START);
  495. console.log('[GameManager] 发送游戏开始事件');
  496. // 开始生成球
  497. this.spawnBall();
  498. // 启动状态检查
  499. this.checkTimer = 0;
  500. // 设置UI按钮事件
  501. this.setupUIButtons();
  502. // 第一波提示UI后再开始生成敌人
  503. // 通过事件系统显示开始波次提示
  504. eventBus.emit(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT);
  505. // 通过事件系统开始敌人生成
  506. eventBus.emit(GameEvents.ENEMY_START_GAME);
  507. // 注意:LevelSessionManager已在StartGame.startGameFlow()中正确初始化,无需重复初始化
  508. }
  509. private spawnBall() {
  510. // 通过事件系统启动球的移动
  511. const eventBus = EventBus.getInstance();
  512. eventBus.emit(GameEvents.BALL_START);
  513. console.log('[GameManager] 发送BALL_START事件,球已启动');
  514. }
  515. public gameOver() {
  516. this.triggerGameDefeat();
  517. }
  518. // === 公共方法 ===
  519. public setHealth(health: number) {
  520. this.wallComponent?.setHealth(health);
  521. }
  522. public takeDamage(damage: number) {
  523. this.wallComponent?.takeDamage(damage);
  524. if (this.wallComponent?.getCurrentHealth() <= 0) {
  525. this.triggerGameDefeat();
  526. }
  527. }
  528. /**
  529. * 获取当前全局应用状态
  530. */
  531. public getCurrentAppState(): AppState {
  532. return this.currentAppState;
  533. }
  534. /**
  535. * 设置全局应用状态
  536. */
  537. public setAppState(state: AppState): void {
  538. console.log(`[GameManager] 应用状态切换: ${this.currentAppState} -> ${state}`);
  539. this.currentAppState = state;
  540. // 根据状态控制UI栏显示
  541. this.updateUIBarsVisibility(state);
  542. // 发送应用状态切换事件,通知MenuController等组件
  543. const eventBus = EventBus.getInstance();
  544. eventBus.emit(GameEvents.APP_STATE_CHANGED, state);
  545. console.log(`[GameManager] 发送应用状态切换事件: ${state}`);
  546. // 游戏内状态管理已迁移到 InGameManager
  547. }
  548. /**
  549. * 根据应用状态更新UI栏显示
  550. */
  551. private updateUIBarsVisibility(state: AppState): void {
  552. const topBarNode = find('Canvas/TopBar');
  553. const navBarNode = find('Canvas/NavBar');
  554. if (state === AppState.IN_GAME) {
  555. // 游戏内状态:隐藏TopBar和NavBar
  556. if (topBarNode) topBarNode.active = false;
  557. if (navBarNode) navBarNode.active = false;
  558. console.log('[GameManager] 游戏内状态:隐藏TopBar和NavBar');
  559. } else {
  560. // 游戏外状态:显示TopBar和NavBar
  561. if (topBarNode) topBarNode.active = true;
  562. if (navBarNode) navBarNode.active = true;
  563. console.log('[GameManager] 游戏外状态:显示TopBar和NavBar');
  564. }
  565. }
  566. /**
  567. * 获取当前游戏内状态已迁移到 InGameManager
  568. * 请使用 InGameManager.getInstance().getCurrentState()
  569. */
  570. /**
  571. * 获取InGameManager实例
  572. * 用于访问游戏内状态和逻辑
  573. */
  574. public getInGameManager(): InGameManager | null {
  575. return this.inGameManager;
  576. }
  577. /**
  578. * 获取当前游戏内状态
  579. * 通过InGameManager获取
  580. */
  581. public getCurrentGameState(): GameState | null {
  582. return this.inGameManager ? this.inGameManager.getCurrentState() : null;
  583. }
  584. /**
  585. * 检查是否在游戏中
  586. */
  587. public isInGame(): boolean {
  588. return this.currentAppState === AppState.IN_GAME;
  589. }
  590. /**
  591. * 从方块选择状态切换到游戏进行状态
  592. * 当玩家完成方块选择后调用
  593. */
  594. public startGameFromBlockSelection(): void {
  595. if (this.currentAppState !== AppState.IN_GAME) {
  596. console.warn('[GameManager] 不在游戏中,无法开始游戏');
  597. return;
  598. }
  599. // 游戏状态检查已迁移到 InGameManager
  600. console.log('[GameManager] 从方块选择状态切换到游戏进行状态,播放退出动画');
  601. // 播放退出BLOCK_SELECTION状态的动画
  602. if (this.gameStartMoveComponent) {
  603. console.log('[GameManager] 执行退出BLOCK_SELECTION状态的动画');
  604. // 调用GameStartMove的退出方块选择模式方法
  605. if (this.gameStartMoveComponent && typeof this.gameStartMoveComponent['exitBlockSelectionMode'] === 'function') {
  606. (this.gameStartMoveComponent as any).exitBlockSelectionMode(300, 0.3);
  607. } else {
  608. console.warn('[GameManager] GameStartMove组件未实现exitBlockSelectionMode方法');
  609. }
  610. }
  611. // 游戏状态管理已迁移到 InGameManager
  612. // 发送游戏开始事件,通知GamePause等组件
  613. const eventBus = EventBus.getInstance();
  614. eventBus.emit(GameEvents.GAME_START);
  615. console.log('[GameManager] 从方块选择切换到游戏时发送游戏开始事件');
  616. }
  617. public restartGame() {
  618. console.log('[GameManager] 重新开始游戏');
  619. // 设置应用状态为游戏中
  620. this.currentAppState = AppState.IN_GAME;
  621. this.gameStarted = false;
  622. this.gameStartTime = 0;
  623. this.gameEndTime = 0;
  624. // 通过事件系统触发游戏重启,让StartGame组件处理完整的重置流程
  625. const eventBus = EventBus.getInstance();
  626. eventBus.emit(GameEvents.GAME_RESTART);
  627. console.log('[GameManager] 游戏重启事件已发送');
  628. }
  629. public forceGameSuccess() {
  630. this.triggerGameSuccess();
  631. }
  632. public forceGameDefeat() {
  633. this.triggerGameDefeat();
  634. }
  635. // === 触发游戏成功 ===
  636. private triggerGameSuccess() {
  637. console.log('[GameManager] 触发游戏成功');
  638. const eventBus = EventBus.getInstance();
  639. eventBus.emit(GameEvents.GAME_SUCCESS);
  640. }
  641. // === 触发游戏失败 ===
  642. private triggerGameDefeat() {
  643. console.log('[GameManager] 触发游戏失败');
  644. const eventBus = EventBus.getInstance();
  645. eventBus.emit(GameEvents.GAME_DEFEAT);
  646. }
  647. // === EnemyController相关方法已通过事件系统解耦,不再需要直接访问 ===
  648. public setTotalEnemiesSpawned(count: number) {
  649. this.totalEnemiesSpawned = count;
  650. }
  651. onDestroy() {
  652. // 清理GamePause事件监听
  653. const eventBus = EventBus.getInstance();
  654. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  655. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  656. eventBus.off(GameEvents.GAME_RESTART, this.onGameRestartEvent, this);
  657. eventBus.off(GameEvents.RESET_GAME_MANAGER, this.onResetGameManagerEvent, this);
  658. eventBus.off('CONTINUE_CLICK', this.onMainMenuClick, this);
  659. // ENEMY_KILLED事件监听已迁移到 InGameManager
  660. // 按钮事件监听已迁移到 UIStateManager
  661. // 清理单例实例
  662. if (GameManager._instance === this) {
  663. GameManager._instance = null;
  664. }
  665. }
  666. // === 加载当前关卡配置 ===
  667. public async loadCurrentLevelConfig() {
  668. if (!this.saveDataManager || !this.levelConfigManager) return;
  669. const currentLevel = this.saveDataManager.getCurrentLevel();
  670. try {
  671. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  672. if (levelConfig) {
  673. await this.applyLevelConfig(levelConfig);
  674. } else {
  675. console.warn(`关卡 ${currentLevel} 配置加载失败`);
  676. }
  677. } catch (error) {
  678. console.error(`关卡 ${currentLevel} 配置加载错误:`, error);
  679. }
  680. }
  681. private async applyLevelConfig(levelConfig: any) {
  682. console.log('[GameManager] 委托关卡配置应用给InGameManager');
  683. // 委托给InGameManager处理关卡配置
  684. if (this.inGameManager) {
  685. await this.inGameManager.applyLevelConfig(levelConfig);
  686. } else {
  687. console.warn('[GameManager] InGameManager未初始化,无法应用关卡配置');
  688. // 备用方案:基本的波次配置处理(已简化)
  689. if (levelConfig.waves && Array.isArray(levelConfig.waves)) {
  690. this.currentWave = 1;
  691. console.log('[GameManager] 使用备用方案处理波次配置(功能有限)');
  692. console.warn('[GameManager] 建议确保InGameManager正确初始化以获得完整功能');
  693. }
  694. }
  695. }
  696. // === 获取当前关卡信息 ===
  697. public async getCurrentLevelInfo() {
  698. const currentLevel = this.saveDataManager ?
  699. this.saveDataManager.getCurrentLevel() :
  700. (this.levelManager ? this.levelManager.getCurrentLevel() : 1);
  701. const levelProgress = this.saveDataManager ?
  702. this.saveDataManager.getLevelProgress(currentLevel) : null;
  703. const levelData = this.levelManager ?
  704. this.levelManager.getLevelData(currentLevel) : null;
  705. const levelConfig = await this.loadCurrentLevelConfig();
  706. return {
  707. level: currentLevel,
  708. maxUnlockedLevel: this.saveDataManager ?
  709. this.saveDataManager.getMaxUnlockedLevel() :
  710. (this.levelManager ? this.levelManager.getMaxUnlockedLevel() : 1),
  711. progress: levelProgress,
  712. data: levelData,
  713. config: levelConfig,
  714. playerData: this.saveDataManager ? {
  715. money: this.saveDataManager.getMoney(),
  716. diamonds: this.saveDataManager.getDiamonds(),
  717. wallLevel: this.saveDataManager.getWallLevel()
  718. } : null
  719. };
  720. }
  721. // === 波次管理和能量系统已迁移到 InGameManager ===
  722. // 这些方法现在委托给 InGameManager 处理
  723. // === 获取当前波次(委托给InGameManager)===
  724. public getCurrentWave(): number {
  725. if (this.inGameManager) {
  726. return this.inGameManager.getCurrentWave();
  727. }
  728. return this.currentWave;
  729. }
  730. // === 获取当前能量值(委托给InGameManager)===
  731. public getCurrentEnergy(): number {
  732. if (this.inGameManager) {
  733. return this.inGameManager.getCurrentEnergy();
  734. }
  735. return 0; // 默认值
  736. }
  737. // === 获取最大能量值(委托给InGameManager)===
  738. public getMaxEnergy(): number {
  739. if (this.inGameManager) {
  740. return this.inGameManager.getMaxEnergy();
  741. }
  742. return 5; // 默认值
  743. }
  744. /* ========= 墙体血量 / 等级相关 ========= */
  745. // === 获取墙体血量(委托给InGameManager)===
  746. private getWallHealth(): number {
  747. if (this.inGameManager) {
  748. return this.inGameManager.getWallHealth();
  749. }
  750. // 备用方案:直接访问墙体组件
  751. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  752. }
  753. // === 墙体血量 / 等级相关方法 - 现在委托给InGameManager ===
  754. public getWallHealthByLevel(level: number): number {
  755. if (this.inGameManager) {
  756. return this.inGameManager.getWallHealthByLevel(level);
  757. }
  758. // 备用方案:直接访问墙体组件
  759. return this.wallComponent ? this.wallComponent.getWallHealthByLevel(level) : 100;
  760. }
  761. public getCurrentWallLevel(): number {
  762. if (this.inGameManager) {
  763. return this.inGameManager.getCurrentWallLevel();
  764. }
  765. // 备用方案:直接访问墙体组件
  766. return this.wallComponent ? this.wallComponent.getCurrentWallLevel() : 1;
  767. }
  768. public getCurrentWallHealth(): number {
  769. if (this.inGameManager) {
  770. return this.inGameManager.getCurrentWallHealth();
  771. }
  772. // 备用方案:直接访问墙体组件
  773. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  774. }
  775. // 初始化GameBlockSelection组件
  776. public initGameBlockSelection() {
  777. console.log('[GameManager] 初始化GameBlockSelection组件');
  778. console.log('[GameManager] gameBlockSelection节点:', !!this.gameBlockSelection, this.gameBlockSelection?.name);
  779. if (this.gameBlockSelection) {
  780. this.blockSelectionComponent = this.gameBlockSelection.getComponent(GameBlockSelection);
  781. console.log('[GameManager] GameBlockSelection组件获取结果:', !!this.blockSelectionComponent);
  782. if (this.blockSelectionComponent) {
  783. // 设置确认回调
  784. this.blockSelectionComponent.setConfirmCallback(() => {
  785. this.handleConfirmAction();
  786. });
  787. console.log('[GameManager] GameBlockSelection组件初始化成功,确认回调已设置');
  788. } else {
  789. console.error('[GameManager] 无法获取GameBlockSelection组件,请检查节点是否正确挂载了该组件');
  790. }
  791. } else {
  792. console.error('[GameManager] gameBlockSelection节点未设置,请在Inspector中拖拽正确的节点');
  793. }
  794. }
  795. // 初始化GameStartMove组件
  796. private initGameStartMove() {
  797. if (this.cameraNode) {
  798. this.gameStartMoveComponent = this.cameraNode.getComponent(GameStartMove);
  799. if (this.gameStartMoveComponent) {
  800. console.log('[GameManager] GameStartMove组件初始化成功');
  801. } else {
  802. console.warn('[GameManager] 未找到GameStartMove组件');
  803. }
  804. } else {
  805. console.warn('[GameManager] 摄像机节点未设置,无法初始化GameStartMove组件');
  806. }
  807. }
  808. // 处理确认操作(委托给InGameManager)
  809. private handleConfirmAction() {
  810. console.log('[GameManager] 方块选择确认,委托给InGameManager处理');
  811. // 委托给InGameManager处理确认操作
  812. if (this.inGameManager) {
  813. this.inGameManager.handleConfirmAction();
  814. } else {
  815. console.warn('[GameManager] InGameManager未初始化,无法处理确认操作');
  816. }
  817. }
  818. // === 单例模式支持 ===
  819. private static _instance: GameManager = null;
  820. /**
  821. * 获取GameManager单例实例
  822. */
  823. public static getInstance(): GameManager {
  824. return GameManager._instance;
  825. }
  826. /**
  827. * 设置GameManager单例实例
  828. */
  829. public static setInstance(instance: GameManager): void {
  830. GameManager._instance = instance;
  831. }
  832. onLoad() {
  833. // 设置单例实例
  834. GameManager.setInstance(this);
  835. }
  836. }