GameManager.ts 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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.getMoney(),
  728. diamonds: this.saveDataManager.getDiamonds(),
  729. wallLevel: this.saveDataManager.getWallLevel()
  730. } : null
  731. };
  732. }
  733. // === 波次管理和能量系统已迁移到 InGameManager ===
  734. // 这些方法现在委托给 InGameManager 处理
  735. // === 获取当前波次(委托给InGameManager)===
  736. public getCurrentWave(): number {
  737. if (this.inGameManager) {
  738. return this.inGameManager.getCurrentWave();
  739. }
  740. return this.currentWave;
  741. }
  742. // === 获取当前能量值(委托给InGameManager)===
  743. public getCurrentEnergy(): number {
  744. if (this.inGameManager) {
  745. return this.inGameManager.getCurrentEnergy();
  746. }
  747. return 0; // 默认值
  748. }
  749. // === 获取最大能量值(委托给InGameManager)===
  750. public getMaxEnergy(): number {
  751. if (this.inGameManager) {
  752. return this.inGameManager.getMaxEnergy();
  753. }
  754. return 5; // 默认值
  755. }
  756. /* ========= 墙体血量 / 等级相关 ========= */
  757. // === 获取墙体血量(委托给InGameManager)===
  758. private getWallHealth(): number {
  759. if (this.inGameManager) {
  760. return this.inGameManager.getWallHealth();
  761. }
  762. // 备用方案:直接访问墙体组件
  763. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  764. }
  765. // === 墙体血量 / 等级相关方法 - 现在委托给InGameManager ===
  766. public getWallHealthByLevel(level: number): number {
  767. if (this.inGameManager) {
  768. return this.inGameManager.getWallHealthByLevel(level);
  769. }
  770. // 备用方案:直接访问墙体组件
  771. return this.wallComponent ? this.wallComponent.getWallHealthByLevel(level) : 100;
  772. }
  773. public getCurrentWallLevel(): number {
  774. if (this.inGameManager) {
  775. return this.inGameManager.getCurrentWallLevel();
  776. }
  777. // 备用方案:直接访问墙体组件
  778. return this.wallComponent ? this.wallComponent.getCurrentWallLevel() : 1;
  779. }
  780. public getCurrentWallHealth(): number {
  781. if (this.inGameManager) {
  782. return this.inGameManager.getCurrentWallHealth();
  783. }
  784. // 备用方案:直接访问墙体组件
  785. return this.wallComponent ? this.wallComponent.getCurrentHealth() : 100;
  786. }
  787. public upgradeWallLevel(): { currentLevel: number; currentHp: number; nextLevel: number; nextHp: number } | null {
  788. if (this.inGameManager) {
  789. return this.inGameManager.upgradeWallLevel();
  790. }
  791. // 备用方案:直接访问墙体组件
  792. return this.wallComponent ? this.wallComponent.upgradeWallLevel() : null;
  793. }
  794. // 初始化GameBlockSelection组件
  795. public initGameBlockSelection() {
  796. console.log('[GameManager] 初始化GameBlockSelection组件');
  797. console.log('[GameManager] gameBlockSelection节点:', !!this.gameBlockSelection, this.gameBlockSelection?.name);
  798. if (this.gameBlockSelection) {
  799. this.blockSelectionComponent = this.gameBlockSelection.getComponent(GameBlockSelection);
  800. console.log('[GameManager] GameBlockSelection组件获取结果:', !!this.blockSelectionComponent);
  801. if (this.blockSelectionComponent) {
  802. // 设置确认回调
  803. this.blockSelectionComponent.setConfirmCallback(() => {
  804. this.handleConfirmAction();
  805. });
  806. console.log('[GameManager] GameBlockSelection组件初始化成功,确认回调已设置');
  807. } else {
  808. console.error('[GameManager] 无法获取GameBlockSelection组件,请检查节点是否正确挂载了该组件');
  809. }
  810. } else {
  811. console.error('[GameManager] gameBlockSelection节点未设置,请在Inspector中拖拽正确的节点');
  812. }
  813. }
  814. // 初始化GameStartMove组件
  815. private initGameStartMove() {
  816. if (this.cameraNode) {
  817. this.gameStartMoveComponent = this.cameraNode.getComponent(GameStartMove);
  818. if (this.gameStartMoveComponent) {
  819. console.log('[GameManager] GameStartMove组件初始化成功');
  820. } else {
  821. console.warn('[GameManager] 未找到GameStartMove组件');
  822. }
  823. } else {
  824. console.warn('[GameManager] 摄像机节点未设置,无法初始化GameStartMove组件');
  825. }
  826. }
  827. // 处理确认操作(委托给InGameManager)
  828. private handleConfirmAction() {
  829. console.log('[GameManager] 方块选择确认,委托给InGameManager处理');
  830. // 委托给InGameManager处理确认操作
  831. if (this.inGameManager) {
  832. this.inGameManager.handleConfirmAction();
  833. } else {
  834. console.warn('[GameManager] InGameManager未初始化,无法处理确认操作');
  835. }
  836. }
  837. // === 单例模式支持 ===
  838. private static _instance: GameManager = null;
  839. /**
  840. * 获取GameManager单例实例
  841. */
  842. public static getInstance(): GameManager {
  843. return GameManager._instance;
  844. }
  845. /**
  846. * 设置GameManager单例实例
  847. */
  848. public static setInstance(instance: GameManager): void {
  849. GameManager._instance = instance;
  850. }
  851. onLoad() {
  852. // 设置单例实例
  853. GameManager.setInstance(this);
  854. }
  855. }