GameManager.ts 39 KB

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