GameManager.ts 35 KB

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