GameManager.ts 37 KB

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