GameManager.ts 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. } else {
  457. // 失败时保持当前关卡,不重置
  458. const currentLevel = this.saveDataManager.getCurrentLevel();
  459. console.log(`[GameManager] 游戏失败,保持当前关卡: ${currentLevel}`);
  460. }
  461. }
  462. // 6. 重置应用状态为主菜单
  463. this.currentAppState = AppState.MAIN_MENU;
  464. console.log('[GameManager] 应用状态已重置为MAIN_MENU');
  465. // 6. 触发返回主菜单事件
  466. eventBus.emit(GameEvents.RETURN_TO_MAIN_MENU);
  467. // 使用装饰器属性获取MainUI,避免使用find
  468. if (!this.mainUI) {
  469. console.error('[GameManager] MainUI节点未在编辑器中设置,请拖拽Canvas/MainUI到GameManager的mainUI属性');
  470. return;
  471. }
  472. const mainUIController = this.mainUI.getComponent('MainUIController' as any);
  473. if (mainUIController) {
  474. // 奖励动画已迁移到GameEnd.ts中,这里只需要普通返回主界面
  475. if (typeof (mainUIController as any).onReturnToMainUI === 'function') {
  476. console.log('[GameManager] 调用普通返回主界面方法');
  477. (mainUIController as any).onReturnToMainUI();
  478. } else {
  479. console.warn('[GameManager] 未找到返回主界面方法,使用兜底逻辑');
  480. this.fallbackMainMenuLogic(mainUIController);
  481. }
  482. } else {
  483. console.error('[GameManager] 未找到MainUIController组件');
  484. this.fallbackMainMenuLogic(null);
  485. }
  486. }
  487. /**
  488. * 兜底逻辑:当找不到MainUIController或相关方法时使用
  489. */
  490. private fallbackMainMenuLogic(mainUIController: any) {
  491. console.warn('[GameManager] 使用兜底逻辑返回主界面');
  492. if (this.mainUI) this.mainUI.active = true;
  493. if (mainUIController && typeof (mainUIController as any).updateUI === 'function') {
  494. (mainUIController as any).updateUI();
  495. }
  496. }
  497. private onUpgradeClick() {
  498. console.log('[GameManager] 升级按钮被点击');
  499. // TODO: 实现升级逻辑
  500. }
  501. private onReviveClick() {
  502. const reviveCost = 10; // 复活消耗的钻石数量
  503. if (this.saveDataManager && this.saveDataManager.spendDiamonds(reviveCost)) {
  504. this.revivePlayer();
  505. }
  506. }
  507. // === 复活玩家 ===
  508. private revivePlayer() {
  509. if (this.wallComponent) {
  510. this.wallComponent.setHealth(50);
  511. }
  512. // 通过事件系统进行完整重置
  513. const eventBus = EventBus.getInstance();
  514. eventBus.emit(GameEvents.GAME_RESTART);
  515. }
  516. // === 重新开始当前关卡 ===
  517. private restartCurrentLevel() {
  518. // 通过事件系统进行完整重置
  519. const eventBus = EventBus.getInstance();
  520. eventBus.emit(GameEvents.GAME_RESTART);
  521. }
  522. public startGame() {
  523. if (this.gameStarted) return;
  524. this.gameStarted = true;
  525. this.gameStartTime = Date.now();
  526. // 游戏状态管理已迁移到 InGameManager
  527. // 发送游戏开始事件,通知其他组件
  528. const eventBus = EventBus.getInstance();
  529. eventBus.emit(GameEvents.GAME_START);
  530. console.log('[GameManager] 发送游戏开始事件');
  531. // 开始生成球
  532. this.spawnBall();
  533. // 启动状态检查
  534. this.checkTimer = 0;
  535. // 设置UI按钮事件
  536. this.setupUIButtons();
  537. // 第一波提示UI后再开始生成敌人
  538. // 通过事件系统显示开始波次提示
  539. eventBus.emit(GameEvents.ENEMY_SHOW_START_WAVE_PROMPT);
  540. // 通过事件系统开始敌人生成
  541. eventBus.emit(GameEvents.ENEMY_START_GAME);
  542. // 注意:LevelSessionManager已在StartGame.startGameFlow()中正确初始化,无需重复初始化
  543. }
  544. private spawnBall() {
  545. // 通过事件系统启动球的移动
  546. const eventBus = EventBus.getInstance();
  547. eventBus.emit(GameEvents.BALL_START);
  548. console.log('[GameManager] 发送BALL_START事件,球已启动');
  549. }
  550. public gameOver() {
  551. this.triggerGameDefeat();
  552. }
  553. // === 公共方法 ===
  554. public setHealth(health: number) {
  555. this.wallComponent?.setHealth(health);
  556. }
  557. public takeDamage(damage: number) {
  558. this.wallComponent?.takeDamage(damage);
  559. if (this.wallComponent?.getCurrentHealth() <= 0) {
  560. this.triggerGameDefeat();
  561. }
  562. }
  563. /**
  564. * 获取当前全局应用状态
  565. */
  566. public getCurrentAppState(): AppState {
  567. return this.currentAppState;
  568. }
  569. /**
  570. * 设置全局应用状态
  571. */
  572. public setAppState(state: AppState): void {
  573. console.log(`[GameManager] 应用状态切换: ${this.currentAppState} -> ${state}`);
  574. this.currentAppState = state;
  575. // 根据状态控制UI栏显示
  576. this.updateUIBarsVisibility(state);
  577. // 发送应用状态切换事件,通知MenuController等组件
  578. const eventBus = EventBus.getInstance();
  579. eventBus.emit(GameEvents.APP_STATE_CHANGED, state);
  580. console.log(`[GameManager] 发送应用状态切换事件: ${state}`);
  581. // 游戏内状态管理已迁移到 InGameManager
  582. }
  583. /**
  584. * 根据应用状态更新UI栏显示
  585. */
  586. private updateUIBarsVisibility(state: AppState): void {
  587. const topBarNode = find('Canvas/TopBar');
  588. const navBarNode = find('Canvas/NavBar');
  589. if (state === AppState.IN_GAME) {
  590. // 游戏内状态:隐藏TopBar和NavBar
  591. if (topBarNode) topBarNode.active = false;
  592. if (navBarNode) navBarNode.active = false;
  593. console.log('[GameManager] 游戏内状态:隐藏TopBar和NavBar');
  594. } else {
  595. // 游戏外状态:显示TopBar和NavBar
  596. if (topBarNode) topBarNode.active = true;
  597. if (navBarNode) navBarNode.active = true;
  598. console.log('[GameManager] 游戏外状态:显示TopBar和NavBar');
  599. }
  600. }
  601. /**
  602. * 获取当前游戏内状态已迁移到 InGameManager
  603. * 请使用 InGameManager.getInstance().getCurrentState()
  604. */
  605. /**
  606. * 获取InGameManager实例
  607. * 用于访问游戏内状态和逻辑
  608. */
  609. public getInGameManager(): InGameManager | null {
  610. return this.inGameManager;
  611. }
  612. /**
  613. * 获取当前游戏内状态
  614. * 通过InGameManager获取
  615. */
  616. public getCurrentGameState(): GameState | null {
  617. return this.inGameManager ? this.inGameManager.getCurrentState() : null;
  618. }
  619. /**
  620. * 检查是否在游戏中
  621. */
  622. public isInGame(): boolean {
  623. return this.currentAppState === AppState.IN_GAME;
  624. }
  625. /**
  626. * 从方块选择状态切换到游戏进行状态
  627. * 当玩家完成方块选择后调用
  628. */
  629. public startGameFromBlockSelection(): void {
  630. if (this.currentAppState !== AppState.IN_GAME) {
  631. console.warn('[GameManager] 不在游戏中,无法开始游戏');
  632. return;
  633. }
  634. // 游戏状态检查已迁移到 InGameManager
  635. console.log('[GameManager] 从方块选择状态切换到游戏进行状态,播放退出动画');
  636. // 播放退出BLOCK_SELECTION状态的动画
  637. if (this.gameStartMoveComponent) {
  638. console.log('[GameManager] 执行退出BLOCK_SELECTION状态的动画');
  639. // 调用GameStartMove的退出方块选择模式方法
  640. if (this.gameStartMoveComponent && typeof this.gameStartMoveComponent['exitBlockSelectionMode'] === 'function') {
  641. (this.gameStartMoveComponent as any).exitBlockSelectionMode(300, 0.3);
  642. } else {
  643. console.warn('[GameManager] GameStartMove组件未实现exitBlockSelectionMode方法');
  644. }
  645. }
  646. // 游戏状态管理已迁移到 InGameManager
  647. // 发送游戏开始事件,通知GamePause等组件
  648. const eventBus = EventBus.getInstance();
  649. eventBus.emit(GameEvents.GAME_START);
  650. console.log('[GameManager] 从方块选择切换到游戏时发送游戏开始事件');
  651. }
  652. public restartGame() {
  653. console.log('[GameManager] 重新开始游戏');
  654. // 设置应用状态为游戏中
  655. this.currentAppState = AppState.IN_GAME;
  656. this.gameStarted = false;
  657. this.gameStartTime = 0;
  658. this.gameEndTime = 0;
  659. // 通过事件系统触发游戏重启,让StartGame组件处理完整的重置流程
  660. const eventBus = EventBus.getInstance();
  661. eventBus.emit(GameEvents.GAME_RESTART);
  662. console.log('[GameManager] 游戏重启事件已发送');
  663. }
  664. public forceGameSuccess() {
  665. this.triggerGameSuccess();
  666. }
  667. public forceGameDefeat() {
  668. this.triggerGameDefeat();
  669. }
  670. // === 触发游戏成功 ===
  671. private triggerGameSuccess() {
  672. console.log('[GameManager] 触发游戏成功');
  673. const eventBus = EventBus.getInstance();
  674. eventBus.emit(GameEvents.GAME_SUCCESS);
  675. }
  676. // === 触发游戏失败 ===
  677. private triggerGameDefeat() {
  678. console.log('[GameManager] 触发游戏失败');
  679. const eventBus = EventBus.getInstance();
  680. eventBus.emit(GameEvents.GAME_DEFEAT);
  681. }
  682. // === EnemyController相关方法已通过事件系统解耦,不再需要直接访问 ===
  683. public setTotalEnemiesSpawned(count: number) {
  684. this.totalEnemiesSpawned = count;
  685. }
  686. onDestroy() {
  687. // 清理GamePause事件监听
  688. const eventBus = EventBus.getInstance();
  689. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  690. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  691. eventBus.off(GameEvents.GAME_RESUME, this.onGameResumeEvent, this);
  692. eventBus.off(GameEvents.GAME_RESUME_SKILL_SELECTION, this.onGameResumeEvent, this);
  693. eventBus.off(GameEvents.GAME_RESUME_BLOCK_SELECTION, this.onGameResumeEvent, this);
  694. eventBus.off(GameEvents.GAME_RESTART, this.onGameRestartEvent, this);
  695. eventBus.off(GameEvents.RESET_GAME_MANAGER, this.onResetGameManagerEvent, this);
  696. eventBus.off('CONTINUE_CLICK', this.onMainMenuClick, this);
  697. // ENEMY_KILLED事件监听已迁移到 InGameManager
  698. // 按钮事件监听已迁移到 UIStateManager
  699. // 清理单例实例
  700. if (GameManager._instance === this) {
  701. GameManager._instance = null;
  702. }
  703. }
  704. // === 加载当前关卡配置 ===
  705. public async loadCurrentLevelConfig() {
  706. if (!this.saveDataManager || !this.levelConfigManager) return;
  707. const currentLevel = this.saveDataManager.getCurrentLevel();
  708. try {
  709. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  710. if (levelConfig) {
  711. await this.applyLevelConfig(levelConfig);
  712. } else {
  713. console.warn(`关卡 ${currentLevel} 配置加载失败`);
  714. }
  715. } catch (error) {
  716. console.error(`关卡 ${currentLevel} 配置加载错误:`, error);
  717. }
  718. }
  719. private async applyLevelConfig(levelConfig: any) {
  720. console.log('[GameManager] 委托关卡配置应用给InGameManager');
  721. // 委托给InGameManager处理关卡配置
  722. if (this.inGameManager) {
  723. await this.inGameManager.applyLevelConfig(levelConfig);
  724. } else {
  725. console.warn('[GameManager] InGameManager未初始化,无法应用关卡配置');
  726. // 备用方案:基本的波次配置处理(已简化)
  727. if (levelConfig.waves && Array.isArray(levelConfig.waves)) {
  728. this.currentWave = 1;
  729. console.log('[GameManager] 使用备用方案处理波次配置(功能有限)');
  730. console.warn('[GameManager] 建议确保InGameManager正确初始化以获得完整功能');
  731. }
  732. }
  733. }
  734. // === 获取当前关卡信息 ===
  735. public async getCurrentLevelInfo() {
  736. const currentLevel = this.saveDataManager ?
  737. this.saveDataManager.getCurrentLevel() :
  738. (this.levelManager ? this.levelManager.getCurrentLevel() : 1);
  739. const levelProgress = this.saveDataManager ?
  740. this.saveDataManager.getLevelProgress(currentLevel) : null;
  741. const levelData = this.levelManager ?
  742. this.levelManager.getLevelData(currentLevel) : null;
  743. const levelConfig = await this.loadCurrentLevelConfig();
  744. return {
  745. level: currentLevel,
  746. maxUnlockedLevel: this.saveDataManager ?
  747. this.saveDataManager.getMaxUnlockedLevel() :
  748. (this.levelManager ? this.levelManager.getMaxUnlockedLevel() : 1),
  749. progress: levelProgress,
  750. data: levelData,
  751. config: levelConfig,
  752. playerData: this.saveDataManager ? {
  753. money: this.saveDataManager.getMoney(),
  754. diamonds: this.saveDataManager.getDiamonds(),
  755. wallLevel: this.saveDataManager.getWallLevel()
  756. } : null
  757. };
  758. }
  759. // === 波次管理和能量系统已迁移到 InGameManager ===
  760. // 这些方法现在委托给 InGameManager 处理
  761. // === 获取当前波次(委托给InGameManager)===
  762. public getCurrentWave(): number {
  763. if (this.inGameManager) {
  764. return this.inGameManager.getCurrentWave();
  765. }
  766. return this.currentWave;
  767. }
  768. // === 获取当前能量值(委托给InGameManager)===
  769. public getCurrentEnergy(): number {
  770. if (this.inGameManager) {
  771. return this.inGameManager.getCurrentEnergy();
  772. }
  773. return 0; // 默认值
  774. }
  775. // === 获取最大能量值(委托给InGameManager)===
  776. public getMaxEnergy(): number {
  777. if (this.inGameManager) {
  778. return this.inGameManager.getMaxEnergy();
  779. }
  780. return 5; // 默认值
  781. }
  782. /* ========= 墙体血量 / 等级相关 ========= */
  783. // === 获取墙体血量(委托给InGameManager)===
  784. private getWallHealth(): number {
  785. if (this.inGameManager) {
  786. return this.inGameManager.getWallHealth();
  787. }
  788. // 备用方案:直接访问墙体组件
  789. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  790. }
  791. // === 墙体血量 / 等级相关方法 - 现在委托给InGameManager ===
  792. public getWallHealthByLevel(level: number): number {
  793. if (this.inGameManager) {
  794. return this.inGameManager.getWallHealthByLevel(level);
  795. }
  796. // 备用方案:直接访问墙体组件
  797. return this.wallComponent ? this.wallComponent.getWallHealthByLevel(level) : 100;
  798. }
  799. public getCurrentWallLevel(): number {
  800. if (this.inGameManager) {
  801. return this.inGameManager.getCurrentWallLevel();
  802. }
  803. // 备用方案:直接访问墙体组件
  804. return this.wallComponent ? this.wallComponent.getCurrentWallLevel() : 1;
  805. }
  806. public getCurrentWallHealth(): number {
  807. if (this.inGameManager) {
  808. return this.inGameManager.getCurrentWallHealth();
  809. }
  810. // 备用方案:直接访问墙体组件
  811. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  812. }
  813. // 初始化GameBlockSelection组件
  814. public initGameBlockSelection() {
  815. console.log('[GameManager] 初始化GameBlockSelection组件');
  816. console.log('[GameManager] gameBlockSelection节点:', !!this.gameBlockSelection, this.gameBlockSelection?.name);
  817. if (this.gameBlockSelection) {
  818. this.blockSelectionComponent = this.gameBlockSelection.getComponent(GameBlockSelection);
  819. console.log('[GameManager] GameBlockSelection组件获取结果:', !!this.blockSelectionComponent);
  820. if (this.blockSelectionComponent) {
  821. // 设置确认回调
  822. this.blockSelectionComponent.setConfirmCallback(() => {
  823. this.handleConfirmAction();
  824. });
  825. console.log('[GameManager] GameBlockSelection组件初始化成功,确认回调已设置');
  826. } else {
  827. console.error('[GameManager] 无法获取GameBlockSelection组件,请检查节点是否正确挂载了该组件');
  828. }
  829. } else {
  830. console.error('[GameManager] gameBlockSelection节点未设置,请在Inspector中拖拽正确的节点');
  831. }
  832. }
  833. // 初始化GameStartMove组件
  834. private initGameStartMove() {
  835. if (this.cameraNode) {
  836. this.gameStartMoveComponent = this.cameraNode.getComponent(GameStartMove);
  837. if (this.gameStartMoveComponent) {
  838. console.log('[GameManager] GameStartMove组件初始化成功');
  839. } else {
  840. console.warn('[GameManager] 未找到GameStartMove组件');
  841. }
  842. } else {
  843. console.warn('[GameManager] 摄像机节点未设置,无法初始化GameStartMove组件');
  844. }
  845. }
  846. // 处理确认操作(委托给InGameManager)
  847. private handleConfirmAction() {
  848. console.log('[GameManager] 方块选择确认,委托给InGameManager处理');
  849. // 委托给InGameManager处理确认操作
  850. if (this.inGameManager) {
  851. this.inGameManager.handleConfirmAction();
  852. } else {
  853. console.warn('[GameManager] InGameManager未初始化,无法处理确认操作');
  854. }
  855. }
  856. // === 单例模式支持 ===
  857. private static _instance: GameManager = null;
  858. /**
  859. * 获取GameManager单例实例
  860. */
  861. public static getInstance(): GameManager {
  862. return GameManager._instance;
  863. }
  864. /**
  865. * 设置GameManager单例实例
  866. */
  867. public static setInstance(instance: GameManager): void {
  868. GameManager._instance = instance;
  869. }
  870. onLoad() {
  871. // 设置单例实例
  872. GameManager.setInstance(this);
  873. }
  874. }