GameManager.ts 36 KB

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