GameManager.ts 37 KB

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