GameManager.ts 39 KB

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