GameManager.ts 36 KB

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