GameManager.ts 37 KB

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