GameManager.ts 37 KB

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