GameManager.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, find, director, Canvas, UITransform, Button, Label, ProgressBar, EPhysics2DDrawFlags, sys } from 'cc';
  2. import { LevelManager } from './LevelManager';
  3. import { LevelConfigManager } from './LevelConfigManager';
  4. import { SaveDataManager } from './SaveDataManager';
  5. // import { ShopManager } from '../ShopSystem/ShopManager';
  6. import { ConfigManager } from '../Core/ConfigManager';
  7. import { EnemyController } from '../CombatSystem/EnemyController';
  8. import EventBus, { GameEvents } from '../Core/EventBus';
  9. import { PhysicsManager } from '../Core/PhysicsManager';
  10. import { BallController } from '../CombatSystem/BallController';
  11. import { BlockManager } from '../CombatSystem/BlockManager';
  12. import { LevelSessionManager } from '../Core/LevelSessionManager';
  13. import { GameStartMove } from '../Animations/GameStartMove';
  14. import { GameBlockSelection } from '../CombatSystem/BlockSelection/GameBlockSelection';
  15. import { BlockTag } from '../CombatSystem/BlockSelection/BlockTag';
  16. import { GamePause } from '../CombatSystem/GamePause';
  17. const { ccclass, property } = _decorator;
  18. /**
  19. * 游戏状态枚举
  20. */
  21. enum GameState {
  22. PLAYING = 'playing',
  23. SUCCESS = 'success',
  24. DEFEAT = 'defeat',
  25. PAUSED = 'paused'
  26. }
  27. /**
  28. * 增强版游戏管理器
  29. * 整合了游戏启动、状态管理、UI控制等功能
  30. */
  31. @ccclass('GameManager')
  32. export class GameManager extends Component {
  33. // === 原GameManager属性 ===
  34. @property({
  35. type: Node,
  36. tooltip: '拖拽BallController节点到这里'
  37. })
  38. public ballController: Node = null;
  39. @property({
  40. type: Node,
  41. tooltip: '拖拽GameBlockSelection节点到这里'
  42. })
  43. public gameBlockSelection: Node = null;
  44. @property({
  45. type: Node,
  46. tooltip: '拖拽GameArea节点到这里'
  47. })
  48. public gameArea: Node = null;
  49. @property({
  50. type: Node,
  51. tooltip: '拖拽EnemyController节点到这里'
  52. })
  53. public enemyManager: Node = null;
  54. // === 游戏状态管理属性 ===
  55. @property({
  56. type: Node,
  57. tooltip: '血量显示节点 (HeartLabeld)'
  58. })
  59. public heartLabelNode: Node = null;
  60. @property({
  61. type: Node,
  62. tooltip: '游戏成功UI节点 (GameSuccess)'
  63. })
  64. public gameSuccessUI: Node = null;
  65. @property({
  66. type: Node,
  67. tooltip: '游戏失败UI节点 (GameDefeat)'
  68. })
  69. public gameDefeatUI: Node = null;
  70. // === 能量与技能选择 UI ===
  71. @property({
  72. type: Node,
  73. tooltip: '拖拽 EnergyBar (ProgressBar) 节点到这里'
  74. })
  75. public energyBarNode: Node = null;
  76. @property({
  77. type: Node,
  78. tooltip: '拖拽 SelectSkillUI 节点到这里'
  79. })
  80. public selectSkillUI: Node = null;
  81. // === 游戏配置属性 ===
  82. // 墙体基础血量由存档决定,不再通过属性面板设置
  83. private wallHealth: number = 100;
  84. @property({
  85. tooltip: '初始血量'
  86. })
  87. public initialHealth: number = 100;
  88. @property({
  89. tooltip: '状态检查间隔(秒)'
  90. })
  91. public checkInterval: number = 1.0;
  92. // === 私有属性 ===
  93. private gameStarted: boolean = false;
  94. private currentHealth: number = 100;
  95. private currentState: GameState = GameState.PLAYING;
  96. private checkTimer: number = 0;
  97. private heartLabel: Label = null;
  98. private enemyController: EnemyController = null;
  99. private levelManager: LevelManager = null;
  100. private levelConfigManager: LevelConfigManager = null;
  101. private saveDataManager: SaveDataManager = null;
  102. // private shopManager: ShopManager = null;
  103. private configManager: ConfigManager = null;
  104. private enemySpawningStarted: boolean = false;
  105. private totalEnemiesSpawned: number = 0;
  106. private currentWave: number = 1;
  107. private currentWaveEnemyCount: number = 0;
  108. private currentWaveTotalEnemies: number = 0; // 当前波次总敌人数
  109. private levelWaves: any[] = []; // 关卡波次配置
  110. private levelTotalEnemies: number = 0; // 本关卡总敌人数
  111. private enemiesKilled: number = 0; // 已击杀敌人数量
  112. // 游戏计时器
  113. private gameStartTime: number = 0;
  114. private gameEndTime: number = 0;
  115. // 游戏区域的边界
  116. private gameBounds = {
  117. left: 0,
  118. right: 0,
  119. top: 0,
  120. bottom: 0
  121. };
  122. private preparingNextWave = false;
  123. // 能量系统
  124. private energyPoints: number = 0;
  125. private readonly ENERGY_MAX: number = 5;
  126. private energyBar: ProgressBar = null;
  127. // GameBlockSelection组件
  128. private blockSelectionComponent: GameBlockSelection = null;
  129. start() {
  130. // 初始化物理系统
  131. this.initPhysicsSystem();
  132. // 初始化管理器
  133. this.initializeManagers();
  134. // 提前初始化本局数据,确保 BlockManager 在 start 时能拿到正确金币
  135. if (!LevelSessionManager.inst.runtime) {
  136. LevelSessionManager.inst.initialize(
  137. this.saveDataManager?.getCurrentLevel() || 1,
  138. this.wallHealth
  139. );
  140. }
  141. // 计算游戏区域边界
  142. this.calculateGameBounds();
  143. // 初始化游戏状态
  144. this.initializeGameState();
  145. // 查找UI节点
  146. this.findUINodes();
  147. // 查找敌人控制器
  148. this.findEnemyController();
  149. // 初始化墙体血量显示
  150. this.initWallHealthDisplay();
  151. // 设置敌人控制器
  152. this.setupEnemyController();
  153. // 设置UI按钮
  154. this.setupUIButtons();
  155. // 初始化GameBlockSelection组件
  156. this.initGameBlockSelection();
  157. // 加载当前关卡配置
  158. this.loadCurrentLevelConfig();
  159. // 监听GamePause状态变化事件
  160. this.setupGamePauseEventListeners();
  161. }
  162. /**
  163. * 设置GamePause事件监听器
  164. */
  165. private setupGamePauseEventListeners() {
  166. const eventBus = EventBus.getInstance();
  167. // 监听游戏成功事件
  168. eventBus.on(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  169. // 监听游戏失败事件
  170. eventBus.on(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  171. // 监听敌人被击杀事件
  172. eventBus.on('ENEMY_KILLED', this.onEnemyKilledEvent, this);
  173. }
  174. /**
  175. * 处理游戏成功事件
  176. */
  177. private onGameSuccessEvent() {
  178. console.log('[GameManager] 接收到游戏成功事件,执行成功处理');
  179. // 显示游戏成功UI
  180. if (this.gameSuccessUI) {
  181. this.gameSuccessUI.active = true;
  182. }
  183. // 执行游戏成功逻辑
  184. this.onGameSuccess();
  185. }
  186. /**
  187. * 处理游戏失败事件
  188. */
  189. private onGameDefeatEvent() {
  190. console.log('[GameManager] 接收到游戏失败事件,执行失败处理');
  191. // 显示游戏失败UI
  192. if (this.gameDefeatUI) {
  193. this.gameDefeatUI.active = true;
  194. }
  195. // 执行游戏失败逻辑
  196. this.onGameDefeat();
  197. }
  198. /**
  199. * 处理敌人被击杀事件
  200. */
  201. private onEnemyKilledEvent() {
  202. // 如果游戏已经结束,不执行后续逻辑
  203. const gamePause = GamePause.getInstance();
  204. if (gamePause.isGameOver()) {
  205. console.warn('[GameManager] 游戏已结束状态下onEnemyKilledEvent被调用!当前状态:', gamePause.getCurrentState());
  206. return;
  207. }
  208. this.enemiesKilled++;
  209. // 当前波击杀 +1
  210. this.currentWaveEnemyCount++;
  211. // 增加能量点
  212. this.incrementEnergy();
  213. const remaining = this.currentWaveTotalEnemies - this.currentWaveEnemyCount;
  214. console.log(`[GameManager] 敌人被消灭,当前波剩余敌人: ${remaining}/${this.currentWaveTotalEnemies}, 总击杀: ${this.enemiesKilled}`);
  215. if (remaining <= 0) {
  216. // 当前波结束
  217. if (this.currentWave < (this.levelWaves?.length || 1)) {
  218. // 还有下一波,显示提示
  219. console.log(`[GameManager] 当前波结束,准备显示下一波(${this.currentWave + 1}/${this.levelWaves?.length || 1})选择UI`);
  220. this.showNextWavePrompt();
  221. } else {
  222. // 最后一波也结束
  223. console.log('[GameManager] 最后一波结束,触发游戏胜利');
  224. this.triggerGameSuccess();
  225. }
  226. }
  227. }
  228. // === 暂停游戏 ===
  229. private pauseGame() {
  230. // 使用GamePause统一管理暂停逻辑
  231. const gamePause = GamePause.getInstance();
  232. if (gamePause) {
  233. gamePause.pauseGame();
  234. }
  235. }
  236. // === 恢复游戏 ===
  237. public resumeGame() {
  238. // 使用GamePause统一管理恢复逻辑
  239. const gamePause = GamePause.getInstance();
  240. if (gamePause) {
  241. gamePause.resumeGame();
  242. }
  243. if (this.gameSuccessUI) {
  244. this.gameSuccessUI.active = false;
  245. }
  246. if (this.gameDefeatUI) {
  247. this.gameDefeatUI.active = false;
  248. }
  249. }
  250. update(deltaTime: number) {
  251. if (this.currentState !== GameState.PLAYING) {
  252. return;
  253. }
  254. // 更新检查计时器
  255. this.checkTimer += deltaTime;
  256. if (this.checkTimer >= this.checkInterval) {
  257. this.checkTimer = 0;
  258. this.checkGameState();
  259. }
  260. // 检查自动保存
  261. if (this.saveDataManager) {
  262. this.saveDataManager.checkAutoSave();
  263. }
  264. }
  265. // === 物理系统初始化 ===
  266. private initPhysicsSystem() {
  267. // 确保 PhysicsManager 单例存在
  268. let pm = PhysicsManager.getInstance();
  269. if (!pm) {
  270. const physicsNode = new Node('PhysicsManager');
  271. director.getScene()?.addChild(physicsNode);
  272. pm = physicsNode.addComponent(PhysicsManager);
  273. }
  274. }
  275. // === 管理器初始化 ===
  276. private initializeManagers() {
  277. this.levelManager = LevelManager.getInstance();
  278. // this.shopManager = ShopManager.getInstance();
  279. this.configManager = ConfigManager.getInstance();
  280. this.levelConfigManager = LevelConfigManager.getInstance();
  281. this.enemyController = EnemyController.getInstance() || null;
  282. // 初始化存档管理器
  283. this.saveDataManager = SaveDataManager.getInstance();
  284. this.saveDataManager.initialize();
  285. // 从存档读取墙体基础血量
  286. const pd = this.saveDataManager.getPlayerData();
  287. if (pd && typeof pd.wallBaseHealth === 'number') {
  288. this.wallHealth = pd.wallBaseHealth;
  289. }
  290. }
  291. // === 游戏状态初始化 ===
  292. private initializeGameState() {
  293. this.currentHealth = this.initialHealth;
  294. this.currentState = GameState.PLAYING;
  295. this.checkTimer = 0;
  296. this.enemySpawningStarted = false;
  297. this.totalEnemiesSpawned = 0;
  298. this.currentWave = 1;
  299. this.currentWaveEnemyCount = 0;
  300. this.currentWaveTotalEnemies = 0; // 当前波次总敌人数
  301. // UI 初始化移交给 EnemyController
  302. }
  303. // === 计算游戏区域边界 ===
  304. private calculateGameBounds() {
  305. const canvas = find('Canvas');
  306. if (!canvas) {
  307. return;
  308. }
  309. const canvasUI = canvas.getComponent(UITransform);
  310. if (!canvasUI) {
  311. return;
  312. }
  313. const screenWidth = canvasUI.width;
  314. const screenHeight = canvasUI.height;
  315. const worldPos = canvas.worldPosition;
  316. this.gameBounds.left = worldPos.x - screenWidth / 2;
  317. this.gameBounds.right = worldPos.x + screenWidth / 2;
  318. this.gameBounds.bottom = worldPos.y - screenHeight / 2;
  319. this.gameBounds.top = worldPos.y + screenHeight / 2;
  320. }
  321. // === 查找UI节点 ===
  322. private findUINodes() {
  323. // 查找血量显示节点
  324. if (!this.heartLabelNode) {
  325. this.heartLabelNode = find('Canvas/GameLevelUI/HeartNode/HeartLabeld');
  326. }
  327. if (this.heartLabelNode) {
  328. this.heartLabel = this.heartLabelNode.getComponent(Label);
  329. }
  330. // 查找游戏成功UI
  331. if (!this.gameSuccessUI) {
  332. this.gameSuccessUI = find('Canvas/GameSuccess');
  333. }
  334. if (this.gameSuccessUI) {
  335. this.gameSuccessUI.active = false;
  336. }
  337. // 查找游戏失败UI
  338. if (!this.gameDefeatUI) {
  339. this.gameDefeatUI = find('Canvas/GameDefeat');
  340. }
  341. if (this.gameDefeatUI) {
  342. this.gameDefeatUI.active = false;
  343. }
  344. // 查找能量条
  345. if (!this.energyBarNode) {
  346. this.energyBarNode = find('Canvas/GameLevelUI/EnergyBar');
  347. }
  348. if (this.energyBarNode) {
  349. this.energyBar = this.energyBarNode.getComponent(ProgressBar);
  350. if (this.energyBar) {
  351. this.energyBar.progress = 0;
  352. }
  353. }
  354. // 查找技能选择 UI
  355. if (!this.selectSkillUI) {
  356. this.selectSkillUI = find('Canvas/SelectSkillUI');
  357. }
  358. if (this.selectSkillUI) {
  359. this.selectSkillUI.active = false;
  360. }
  361. }
  362. // === 查找敌人控制器 ===
  363. private findEnemyController() {
  364. if (this.enemyManager) {
  365. this.enemyController = this.enemyManager.getComponent(EnemyController);
  366. }
  367. if (!this.enemyController) {
  368. const enemyNode = find('Canvas/GameLevelUI/EnemyController');
  369. if (enemyNode) {
  370. this.enemyController = enemyNode.getComponent(EnemyController);
  371. }
  372. }
  373. }
  374. // === 初始化墙体血量显示 ===
  375. private initWallHealthDisplay() {
  376. if (this.heartLabelNode && this.heartLabel) {
  377. this.heartLabel.string = this.wallHealth.toString();
  378. }
  379. // 让 EnemyController 自行查找/刷新血量 UI
  380. if (this.enemyController.initWallHealthDisplay) {
  381. this.enemyController.initWallHealthDisplay();
  382. }
  383. }
  384. // === 设置敌人控制器 ===
  385. private setupEnemyController() {
  386. if (!this.enemyManager) {
  387. const gameLevelUI = find('Canvas/GameLevelUI');
  388. if (!gameLevelUI) {
  389. console.error('找不到GameLevelUI节点,无法创建EnemyController');
  390. return;
  391. }
  392. this.enemyManager = new Node('EnemyController');
  393. gameLevelUI.addChild(this.enemyManager);
  394. }
  395. if (!this.enemyController) {
  396. this.enemyController = this.enemyManager.addComponent(EnemyController);
  397. }
  398. // 无论 EnemyController 是否新建,都注入墙体血量
  399. this.enemyController.wallHealth = this.wallHealth;
  400. this.enemyController.updateWallHealthDisplay?.();
  401. }
  402. // === 游戏状态检查 ===
  403. private checkGameState() {
  404. // 更新血量
  405. this.updateHealthFromUI();
  406. if (this.currentHealth <= 0) {
  407. this.triggerGameDefeat();
  408. return;
  409. }
  410. // 检查是否全部击败
  411. if (this.checkAllEnemiesDefeated()) {
  412. this.triggerGameSuccess();
  413. return;
  414. }
  415. }
  416. // === 从UI更新血量 ===
  417. private updateHealthFromUI() {
  418. if (this.heartLabel) {
  419. const healthText = this.heartLabel.string;
  420. const healthMatch = healthText.match(/\d+/);
  421. if (healthMatch) {
  422. const newHealth = parseInt(healthMatch[0]);
  423. if (newHealth !== this.currentHealth) {
  424. this.currentHealth = newHealth;
  425. }
  426. }
  427. }
  428. }
  429. // === 检查所有敌人是否被击败 ===
  430. private checkAllEnemiesDefeated(): boolean {
  431. if (!this.enemyController) {
  432. return false;
  433. }
  434. // 检查敌人是否已开始生成(避免开局就胜利)
  435. if (!this.enemySpawningStarted) {
  436. if (this.enemyController.isGameStarted && this.enemyController.isGameStarted()) {
  437. this.enemySpawningStarted = true;
  438. } else {
  439. return false;
  440. }
  441. }
  442. // 获取当前敌人数量
  443. const currentEnemyCount = this.enemyController.getCurrentEnemyCount ?
  444. this.enemyController.getCurrentEnemyCount() : 0;
  445. // 如果关卡总敌人数已知,以击杀数为准判定胜利
  446. if (this.levelTotalEnemies > 0) {
  447. // 当击杀数达到或超过总敌数且场上没有存活敌人时胜利
  448. return this.enemiesKilled >= this.levelTotalEnemies && currentEnemyCount === 0;
  449. }
  450. // 否则退化到旧逻辑:依赖于是否曾经生成过敌人
  451. // 更新已生成敌人总数(记录曾经达到的最大值)
  452. if (currentEnemyCount > this.totalEnemiesSpawned) {
  453. this.totalEnemiesSpawned = currentEnemyCount;
  454. }
  455. const shouldCheckVictory = this.enemySpawningStarted &&
  456. currentEnemyCount === 0 &&
  457. this.totalEnemiesSpawned > 0;
  458. return shouldCheckVictory;
  459. }
  460. // === 触发游戏失败 ===
  461. private triggerGameDefeat() {
  462. // 使用GamePause统一管理游戏状态
  463. const gamePause = GamePause.getInstance();
  464. gamePause.triggerGameDefeat();
  465. }
  466. // === 触发游戏成功 ===
  467. private triggerGameSuccess() {
  468. // 使用GamePause统一管理游戏状态
  469. const gamePause = GamePause.getInstance();
  470. gamePause.triggerGameSuccess();
  471. }
  472. // === 游戏失败回调 ===
  473. private onGameDefeat() {
  474. this.gameEndTime = Date.now();
  475. // 记录游戏失败到存档
  476. if (this.saveDataManager) {
  477. const currentLevel = this.saveDataManager.getCurrentLevel();
  478. this.saveDataManager.failLevel(currentLevel);
  479. // 更新统计数据
  480. this.saveDataManager.updateStatistic('totalTimePlayed', this.getGameDuration());
  481. }
  482. }
  483. // === 游戏成功回调 ===
  484. private onGameSuccess() {
  485. this.gameEndTime = Date.now();
  486. this.giveReward();
  487. this.onLevelComplete();
  488. }
  489. // === 给予奖励 ===
  490. private giveReward() {
  491. if (!this.saveDataManager) return;
  492. const currentLevel = this.saveDataManager.getCurrentLevel();
  493. const baseReward = currentLevel * 50;
  494. const healthBonus = Math.floor(this.currentHealth * 0.1);
  495. const timeBonus = this.calculateTimeBonus();
  496. const totalCoins = baseReward + healthBonus + timeBonus;
  497. // 给予金币奖励
  498. this.saveDataManager.addCoins(totalCoins, `level_${currentLevel}_complete`);
  499. // 如果是首次完成,给予额外奖励
  500. if (!this.saveDataManager.isLevelCompleted(currentLevel)) {
  501. const firstClearBonus = currentLevel * 25;
  502. this.saveDataManager.addCoins(firstClearBonus, `level_${currentLevel}_first_clear`);
  503. }
  504. }
  505. // === 处理关卡完成 ===
  506. private onLevelComplete(score: number = 0, stars: number = 1) {
  507. if (!this.saveDataManager) return;
  508. const currentLevel = this.saveDataManager.getCurrentLevel();
  509. const gameTime = this.getGameDuration();
  510. // 计算得分(基于剩余血量、用时等)
  511. const calculatedScore = this.calculateScore();
  512. const finalScore = Math.max(score, calculatedScore);
  513. // 计算星级(基于表现)
  514. const calculatedStars = this.calculateStars();
  515. const finalStars = Math.max(stars, calculatedStars);
  516. // 记录关卡完成到存档
  517. this.saveDataManager.completeLevel(currentLevel, finalScore, gameTime, finalStars);
  518. // 更新统计数据
  519. this.saveDataManager.updateStatistic('totalTimePlayed', gameTime);
  520. this.saveDataManager.updateStatistic('totalEnemiesDefeated', this.totalEnemiesSpawned);
  521. // 兼容原有的LevelManager
  522. if (this.levelManager) {
  523. this.levelManager.completeLevel(currentLevel, finalScore, finalStars);
  524. }
  525. }
  526. // === 计算游戏时长 ===
  527. private getGameDuration(): number {
  528. if (this.gameStartTime === 0) return 0;
  529. const endTime = this.gameEndTime || Date.now();
  530. return Math.floor((endTime - this.gameStartTime) / 1000);
  531. }
  532. // === 计算时间奖励 ===
  533. private calculateTimeBonus(): number {
  534. const gameTime = this.getGameDuration();
  535. if (gameTime === 0) return 0;
  536. // 时间越短奖励越多,最多额外50%奖励
  537. const maxTime = 300; // 5分钟
  538. const timeRatio = Math.max(0, (maxTime - gameTime) / maxTime);
  539. const baseReward = this.saveDataManager.getCurrentLevel() * 50;
  540. return Math.floor(baseReward * timeRatio * 0.5);
  541. }
  542. // === 计算得分 ===
  543. private calculateScore(): number {
  544. const currentLevel = this.saveDataManager?.getCurrentLevel() || 1;
  545. const baseScore = currentLevel * 1000;
  546. const healthScore = this.currentHealth * 10;
  547. const enemyScore = this.totalEnemiesSpawned * 50;
  548. const timeScore = this.calculateTimeBonus();
  549. return baseScore + healthScore + enemyScore + timeScore;
  550. }
  551. // === 计算星级 ===
  552. private calculateStars(): number {
  553. const healthRatio = this.currentHealth / this.initialHealth;
  554. const gameTime = this.getGameDuration();
  555. // 基于血量剩余和用时计算星级
  556. if (healthRatio >= 0.8 && gameTime <= 120) {
  557. return 3; // 3星:血量80%以上,2分钟内完成
  558. } else if (healthRatio >= 0.5 && gameTime <= 300) {
  559. return 2; // 2星:血量50%以上,5分钟内完成
  560. } else if (healthRatio > 0) {
  561. return 1; // 1星:只要完成就有1星
  562. }
  563. return 1;
  564. }
  565. // === 设置UI按钮 ===
  566. private setupUIButtons() {
  567. this.setupSuccessUIButtons();
  568. this.setupDefeatUIButtons();
  569. }
  570. // === 设置成功界面按钮 ===
  571. private setupSuccessUIButtons() {
  572. if (this.gameSuccessUI) {
  573. const nextLevelBtn = this.gameSuccessUI.getChildByName('NextLevelBtn');
  574. const restartBtn = this.gameSuccessUI.getChildByName('RestartBtn');
  575. const mainMenuBtn = this.gameSuccessUI.getChildByName('MainMenuBtn');
  576. const shopBtn = this.gameSuccessUI.getChildByName('ShopBtn');
  577. if (nextLevelBtn) {
  578. const button = nextLevelBtn.getComponent(Button);
  579. if (button) {
  580. button.node.on(Button.EventType.CLICK, this.onRestartClick, this);
  581. }
  582. }
  583. if (restartBtn) {
  584. const button = restartBtn.getComponent(Button);
  585. if (button) {
  586. button.node.on(Button.EventType.CLICK, this.onRestartClick, this);
  587. }
  588. }
  589. if (mainMenuBtn) {
  590. const button = mainMenuBtn.getComponent(Button);
  591. if (button) {
  592. button.node.on(Button.EventType.CLICK, this.onMainMenuClick, this);
  593. }
  594. }
  595. if (shopBtn) {
  596. const button = shopBtn.getComponent(Button);
  597. if (button) {
  598. button.node.on(Button.EventType.CLICK, this.onShopClick, this);
  599. }
  600. }
  601. }
  602. }
  603. // === 设置失败界面按钮 ===
  604. private setupDefeatUIButtons() {
  605. if (this.gameDefeatUI) {
  606. const restartBtn = this.gameDefeatUI.getChildByName('RestartBtn');
  607. const mainMenuBtn = this.gameDefeatUI.getChildByName('MainMenuBtn');
  608. const shopBtn = this.gameDefeatUI.getChildByName('ShopBtn');
  609. const reviveBtn = this.gameDefeatUI.getChildByName('ReviveBtn');
  610. if (restartBtn) {
  611. const button = restartBtn.getComponent(Button);
  612. if (button) {
  613. button.node.on(Button.EventType.CLICK, this.onRestartClick, this);
  614. }
  615. }
  616. if (mainMenuBtn) {
  617. const button = mainMenuBtn.getComponent(Button);
  618. if (button) {
  619. button.node.on(Button.EventType.CLICK, this.onMainMenuClick, this);
  620. }
  621. }
  622. if (shopBtn) {
  623. const button = shopBtn.getComponent(Button);
  624. if (button) {
  625. button.node.on(Button.EventType.CLICK, this.onShopClick, this);
  626. }
  627. }
  628. if (reviveBtn) {
  629. const button = reviveBtn.getComponent(Button);
  630. if (button) {
  631. button.node.on(Button.EventType.CLICK, this.onReviveClick, this);
  632. }
  633. }
  634. }
  635. }
  636. // === 按钮点击事件处理 ===
  637. private onRestartClick() {
  638. this.restartGame();
  639. }
  640. private onMainMenuClick() {
  641. // 隐藏游戏界面,显示主界面
  642. const gameLevelUI = find('Canvas/GameLevelUI');
  643. const mainUI = find('Canvas/MainUI');
  644. if (gameLevelUI) gameLevelUI.active = false;
  645. if (mainUI) mainUI.active = true;
  646. // 更新主界面
  647. const mainUIController = mainUI?.getComponent('MainUIController' as any);
  648. if (mainUIController && typeof (mainUIController as any).updateUI === 'function') {
  649. (mainUIController as any).updateUI();
  650. }
  651. }
  652. private onShopClick() {
  653. // 打开商店界面
  654. const gameLevelUI = find('Canvas/GameLevelUI');
  655. const shopUI = find('Canvas/ShopUI');
  656. if (gameLevelUI) gameLevelUI.active = false;
  657. if (shopUI) shopUI.active = true;
  658. }
  659. private onReviveClick() {
  660. const reviveCost = 10; // 复活消耗的钻石数量
  661. if (this.saveDataManager && this.saveDataManager.spendDiamonds(reviveCost)) {
  662. this.revivePlayer();
  663. }
  664. }
  665. // === 复活玩家 ===
  666. private revivePlayer() {
  667. this.setHealth(50);
  668. this.restartGame();
  669. }
  670. // === 重新开始当前关卡 ===
  671. private restartCurrentLevel() {
  672. this.restartGame();
  673. }
  674. // === 原GameManager方法 ===
  675. // onConfirmButtonClicked方法已移除,逻辑已整合到handleConfirmAction中
  676. private preservePlacedBlocks() {
  677. const blockController = find('Canvas/GameLevelUI/BlockController');
  678. if (blockController) {
  679. const blockManager = blockController.getComponent('BlockManager') as any;
  680. if (blockManager) {
  681. blockManager.onGameStart();
  682. }
  683. }
  684. }
  685. public startGame() {
  686. if (this.gameStarted) return;
  687. this.gameStarted = true;
  688. this.gameStartTime = Date.now();
  689. this.currentState = GameState.PLAYING;
  690. // 开始生成球
  691. this.spawnBall();
  692. // 启动状态检查
  693. this.checkTimer = 0;
  694. // 设置UI按钮事件
  695. this.setupUIButtons();
  696. // 第一波提示UI后再开始生成敌人
  697. if (this.enemyController && this.enemyController.showStartWavePromptUI) {
  698. this.enemyController.showStartWavePromptUI();
  699. } else {
  700. this.forceStartEnemySpawning();
  701. }
  702. LevelSessionManager.inst.initialize(
  703. SaveDataManager.getInstance().getCurrentLevel(),
  704. this.wallHealth
  705. );
  706. }
  707. private spawnBall() {
  708. if (!this.ballController) return;
  709. const ballControllerComponent = this.ballController.getComponent(BallController);
  710. if (ballControllerComponent) {
  711. ballControllerComponent.startBall();
  712. }
  713. }
  714. public gameOver() {
  715. this.triggerGameDefeat();
  716. }
  717. // === 公共方法 ===
  718. public setHealth(health: number) {
  719. this.currentHealth = Math.max(0, health);
  720. }
  721. public takeDamage(damage: number) {
  722. this.currentHealth = Math.max(0, this.currentHealth - damage);
  723. if (this.currentHealth <= 0) {
  724. this.triggerGameDefeat();
  725. }
  726. }
  727. public getCurrentState(): GameState {
  728. return this.currentState;
  729. }
  730. public restartGame() {
  731. this.currentState = GameState.PLAYING;
  732. this.gameStarted = false;
  733. this.gameStartTime = 0;
  734. this.gameEndTime = 0;
  735. this.currentHealth = this.initialHealth;
  736. this.totalEnemiesSpawned = 0;
  737. this.enemiesKilled = 0;
  738. this.currentWave = 1;
  739. this.currentWaveEnemyCount = 0;
  740. // 重置GamePause状态
  741. const gamePause = GamePause.getInstance();
  742. gamePause.resetGameState();
  743. // 重置能量条
  744. this.energyPoints = 0;
  745. if (this.energyBar) {
  746. this.energyBar.progress = 0;
  747. }
  748. if (this.selectSkillUI) {
  749. this.selectSkillUI.active = false;
  750. }
  751. // 关闭胜利/失败界面,确保重新进入时是正常状态
  752. if (this.gameSuccessUI) {
  753. this.gameSuccessUI.active = false;
  754. }
  755. if (this.gameDefeatUI) {
  756. this.gameDefeatUI.active = false;
  757. }
  758. // 通知BlockManager游戏重置
  759. const blockMgrNode = find('Canvas/GameLevelUI/BlockController');
  760. const blockManager = blockMgrNode?.getComponent(BlockManager);
  761. if (blockManager) {
  762. blockManager.onGameReset?.();
  763. }
  764. // 清空关卡剩余敌人,不触发敌人死亡事件
  765. if (this.enemyController && this.enemyController.clearAllEnemies) {
  766. this.enemyController.clearAllEnemies(false);
  767. }
  768. // 重置墙体血量显示
  769. this.initWallHealthDisplay();
  770. // 初始化本局数据(金币45等)
  771. LevelSessionManager.inst.clear();
  772. LevelSessionManager.inst.initialize(
  773. this.saveDataManager.getCurrentLevel(),
  774. this.wallHealth
  775. );
  776. // 刷新方块金币显示(如果 BlockManager 已存在)
  777. if (blockManager) {
  778. blockManager.updateCoinDisplay?.();
  779. }
  780. }
  781. public isGameOver(): boolean {
  782. // 统一使用GamePause来判断游戏是否结束
  783. const gamePause = GamePause.getInstance();
  784. return gamePause.isGameOver();
  785. }
  786. public forceGameSuccess() {
  787. this.triggerGameSuccess();
  788. }
  789. public forceGameDefeat() {
  790. this.triggerGameDefeat();
  791. }
  792. // === 获取EnemyController组件 ===
  793. public getEnemyController() {
  794. return this.enemyController;
  795. }
  796. // === 调试方法 ===
  797. public getEnemyStatus() {
  798. if (!this.enemyController) return;
  799. const currentCount = this.enemyController.getCurrentEnemyCount();
  800. const gameStarted = this.enemyController.isGameStarted();
  801. const activeEnemies = this.enemyController.getActiveEnemies?.() || [];
  802. if (activeEnemies.length > 0) {
  803. for (let index = 0; index < activeEnemies.length; index++) {
  804. const enemy = activeEnemies[index];
  805. if (enemy?.isValid) {
  806. // 查看敌人状态
  807. } else {
  808. // 无效敌人节点
  809. }
  810. }
  811. }
  812. }
  813. public forceStartEnemySpawning() {
  814. if (this.enemyController) {
  815. this.enemyController.startGame();
  816. }
  817. }
  818. public setTotalEnemiesSpawned(count: number) {
  819. this.totalEnemiesSpawned = count;
  820. }
  821. public testEnemyDetection() {
  822. // 测试敌人检测功能
  823. this.getEnemyStatus();
  824. }
  825. public testComponentAccess() {
  826. // 测试组件访问
  827. if (this.enemyController) {
  828. // 组件访问正常
  829. }
  830. }
  831. public testEnemyAttackWall() {
  832. if (!this.enemyController) return;
  833. const currentHealth = this.enemyController.getCurrentWallHealth();
  834. const testDamage = 50;
  835. this.enemyController.damageWall(testDamage);
  836. const newHealth = this.enemyController.getCurrentWallHealth();
  837. }
  838. onDestroy() {
  839. // 清理GamePause事件监听
  840. const eventBus = EventBus.getInstance();
  841. eventBus.off(GameEvents.GAME_SUCCESS, this.onGameSuccessEvent, this);
  842. eventBus.off(GameEvents.GAME_DEFEAT, this.onGameDefeatEvent, this);
  843. eventBus.off('ENEMY_KILLED', this.onEnemyKilledEvent, this);
  844. // 清理按钮事件监听
  845. if (this.gameSuccessUI) {
  846. const buttons = this.gameSuccessUI.getComponentsInChildren(Button);
  847. buttons.forEach(button => {
  848. button.node.off(Button.EventType.CLICK);
  849. });
  850. }
  851. if (this.gameDefeatUI) {
  852. const buttons = this.gameDefeatUI.getComponentsInChildren(Button);
  853. buttons.forEach(button => {
  854. button.node.off(Button.EventType.CLICK);
  855. });
  856. }
  857. }
  858. // === 加载当前关卡配置 ===
  859. public async loadCurrentLevelConfig() {
  860. if (!this.saveDataManager || !this.levelConfigManager) return;
  861. const currentLevel = this.saveDataManager.getCurrentLevel();
  862. try {
  863. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  864. if (levelConfig) {
  865. this.applyLevelConfig(levelConfig);
  866. } else {
  867. console.warn(`关卡 ${currentLevel} 配置加载失败`);
  868. }
  869. } catch (error) {
  870. console.error(`关卡 ${currentLevel} 配置加载错误:`, error);
  871. }
  872. }
  873. private applyLevelConfig(levelConfig: any) {
  874. // 应用关卡配置
  875. // 如果有武器配置,应用武器
  876. if (levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
  877. // 应用武器配置
  878. }
  879. // 如果有波次配置,设置敌人波次
  880. if (levelConfig.waves && Array.isArray(levelConfig.waves)) {
  881. this.levelWaves = levelConfig.waves;
  882. this.currentWave = 1;
  883. // 计算本关卡总敌人数
  884. this.levelTotalEnemies = 0;
  885. for (const wave of this.levelWaves) {
  886. for (const enemy of wave.enemies || []) {
  887. this.levelTotalEnemies += enemy.count || 0;
  888. }
  889. }
  890. // 通知 EnemyController 初始化第一波数据及 UI
  891. if (this.enemyController) {
  892. const totalWaves = this.levelWaves.length;
  893. const firstWaveEnemies = this.levelWaves.length > 0 && this.levelWaves[0].enemies ?
  894. this.levelWaves[0].enemies.reduce((t: number, g: any) => t + (g.count || 0), 0) : 0;
  895. this.enemyController.startWave(1, totalWaves, firstWaveEnemies);
  896. // 同步 GameManager 当前波敌人数,避免剩余敌人数计算出错
  897. this.setCurrentWave(1, firstWaveEnemies);
  898. }
  899. }
  900. }
  901. // === 获取当前关卡信息 ===
  902. public async getCurrentLevelInfo() {
  903. const currentLevel = this.saveDataManager ?
  904. this.saveDataManager.getCurrentLevel() :
  905. (this.levelManager ? this.levelManager.getCurrentLevel() : 1);
  906. const levelProgress = this.saveDataManager ?
  907. this.saveDataManager.getLevelProgress(currentLevel) : null;
  908. const levelData = this.levelManager ?
  909. this.levelManager.getLevelData(currentLevel) : null;
  910. const levelConfig = await this.loadCurrentLevelConfig();
  911. return {
  912. level: currentLevel,
  913. maxUnlockedLevel: this.saveDataManager ?
  914. this.saveDataManager.getMaxUnlockedLevel() :
  915. (this.levelManager ? this.levelManager.getMaxUnlockedLevel() : 1),
  916. progress: levelProgress,
  917. data: levelData,
  918. config: levelConfig,
  919. playerData: this.saveDataManager ? {
  920. coins: this.saveDataManager.getCoins(),
  921. diamonds: this.saveDataManager.getDiamonds(),
  922. gems: this.saveDataManager.getGems(),
  923. playerLevel: this.saveDataManager.getPlayerLevel()
  924. } : null
  925. };
  926. }
  927. // === 更新波次显示 ===
  928. private updateWaveDisplay() {
  929. // UI 更新交由 EnemyController 处理
  930. }
  931. // === 更新敌人数量显示 ===
  932. private updateEnemyCountDisplay() {
  933. // UI 更新交由 EnemyController 处理
  934. }
  935. // === 设置当前波次 ===
  936. public setCurrentWave(wave: number, enemyCount: number = 0) {
  937. this.currentWave = wave;
  938. this.currentWaveEnemyCount = 0; // 重置当前击杀数
  939. this.currentWaveTotalEnemies = enemyCount; // 设置该波次总敌人数
  940. if (this.enemyController) {
  941. const totalWaves = this.levelWaves?.length || 1;
  942. this.enemyController.startWave(wave, totalWaves, enemyCount);
  943. }
  944. }
  945. // === 更新当前波次敌人数量 ===
  946. public updateCurrentWaveEnemyCount(count: number) {
  947. this.currentWaveEnemyCount = count;
  948. }
  949. // === 获取当前波次 ===
  950. public getCurrentWave(): number {
  951. return this.currentWave;
  952. }
  953. // === 获取当前波次敌人数量 ===
  954. public getCurrentWaveEnemyCount(): number {
  955. return this.currentWaveEnemyCount;
  956. }
  957. // === 获取当前波次总敌人数量 ===
  958. public getCurrentWaveTotalEnemies(): number {
  959. return this.currentWaveTotalEnemies;
  960. }
  961. // === 进入下一波 ===
  962. public nextWave() {
  963. this.currentWave++;
  964. // 根据关卡配置获取下一波敌人数
  965. let enemyTotal = 0;
  966. if (this.levelWaves && this.levelWaves.length >= this.currentWave) {
  967. const waveCfg = this.levelWaves[this.currentWave - 1];
  968. if (waveCfg && waveCfg.enemies) {
  969. enemyTotal = waveCfg.enemies.reduce((t: number, g: any) => t + (g.count || 0), 0);
  970. }
  971. }
  972. this.setCurrentWave(this.currentWave, enemyTotal);
  973. }
  974. /** 显示下一波提示并在短暂延迟后开始下一波 */
  975. private showNextWavePrompt() {
  976. this.showBlockSelectionForNextWave(); // 使用新的方法
  977. }
  978. // 显示方块选择UI用于下一波
  979. private showBlockSelectionForNextWave() {
  980. // 如果游戏已经结束,不显示方块选择UI
  981. if (this.isGameOver()) {
  982. const gamePause = GamePause.getInstance();
  983. console.warn('[GameManager] 游戏已经结束(胜利或失败),不显示下一波方块选择UI!当前状态:', gamePause.getCurrentState());
  984. return;
  985. }
  986. if (this.blockSelectionComponent) {
  987. this.blockSelectionComponent.showBlockSelection(true);
  988. this.preparingNextWave = true;
  989. // 使用GamePause来暂停游戏
  990. const gamePause = GamePause.getInstance();
  991. if (gamePause) {
  992. gamePause.pauseGame();
  993. }
  994. }
  995. }
  996. /** 敌人被消灭时由 EnemyController 调用 */
  997. public onEnemyKilled() {
  998. // 直接调用GamePause来处理
  999. const gamePause = GamePause.getInstance();
  1000. gamePause.onEnemyKilled();
  1001. }
  1002. /** 每击杀敌人调用,能量 +1,并更新进度条。满值时弹出技能选择界面 */
  1003. private incrementEnergy() {
  1004. this.energyPoints = Math.min(this.energyPoints + 1, this.ENERGY_MAX);
  1005. this.updateEnergyBar();
  1006. if (this.energyPoints >= this.ENERGY_MAX) {
  1007. this.onEnergyFull();
  1008. }
  1009. }
  1010. /** 更新能量条显示 */
  1011. private updateEnergyBar() {
  1012. if (this.energyBar) {
  1013. this.energyBar.progress = this.energyPoints / this.ENERGY_MAX;
  1014. }
  1015. }
  1016. /** 能量满时触发 */
  1017. private onEnergyFull() {
  1018. if (this.selectSkillUI && !this.selectSkillUI.active) {
  1019. // 暂停游戏后再弹出 UI
  1020. this.pauseGame();
  1021. this.selectSkillUI.active = true;
  1022. }
  1023. }
  1024. /** 供外部调用:重置能量值并刷新显示 */
  1025. public resetEnergy() {
  1026. this.energyPoints = 0;
  1027. this.updateEnergyBar();
  1028. }
  1029. /* ========= 墙体血量 / 等级相关 ========= */
  1030. private wallHpMap: Record<number, number> = {
  1031. 1: 100,
  1032. 2: 1000,
  1033. 3: 1200,
  1034. 4: 1500,
  1035. 5: 2000
  1036. };
  1037. /** 根据等级获取墙体血量 */
  1038. public getWallHealthByLevel(level: number): number {
  1039. return this.wallHpMap[level] || (100 + (level - 1) * 200);
  1040. }
  1041. /** 获取当前墙壁等级 */
  1042. public getCurrentWallLevel(): number {
  1043. return this.saveDataManager?.getPlayerData().playerLevel || 1;
  1044. }
  1045. /** 获取当前墙体血量 */
  1046. public getCurrentWallHealth(): number {
  1047. return this.saveDataManager?.getPlayerData().wallBaseHealth || this.getWallHealthByLevel(1);
  1048. }
  1049. /** 升级墙体等级,返回升级后信息,失败返回null */
  1050. public upgradeWallLevel(): { currentLevel: number; currentHp: number; nextLevel: number; nextHp: number } | null {
  1051. if (!this.saveDataManager) return null;
  1052. const pd = this.saveDataManager.getPlayerData();
  1053. const curLvl = pd.playerLevel || 1;
  1054. if (curLvl >= 5) return null; // 已达最高级
  1055. const newLvl = curLvl + 1;
  1056. const newHp = this.getWallHealthByLevel(newLvl);
  1057. pd.playerLevel = newLvl;
  1058. pd.wallBaseHealth = newHp;
  1059. this.saveDataManager.savePlayerData(true);
  1060. // 更新内存中的数值
  1061. this.wallHealth = newHp;
  1062. if (this.enemyController) {
  1063. this.enemyController.wallHealth = newHp;
  1064. this.enemyController.updateWallHealthDisplay?.();
  1065. }
  1066. return {
  1067. currentLevel: newLvl,
  1068. currentHp: newHp,
  1069. nextLevel: newLvl + 1,
  1070. nextHp: this.getWallHealthByLevel(newLvl + 1)
  1071. };
  1072. }
  1073. // 初始化GameBlockSelection组件
  1074. private initGameBlockSelection() {
  1075. if (this.gameBlockSelection) {
  1076. this.blockSelectionComponent = this.gameBlockSelection.getComponent(GameBlockSelection);
  1077. if (this.blockSelectionComponent) {
  1078. // 设置确认回调
  1079. this.blockSelectionComponent.setConfirmCallback(() => {
  1080. this.handleConfirmAction();
  1081. });
  1082. }
  1083. }
  1084. }
  1085. // 处理确认操作(替代原来的onConfirmButtonClicked)
  1086. private handleConfirmAction() {
  1087. if (this.preparingNextWave) {
  1088. // 进入下一波
  1089. this.preparingNextWave = false;
  1090. this.enemyController.showStartWavePromptUI(); // 弹 startWaveUI 后自动 startGame()
  1091. this.nextWave(); // 更新 wave 计数 & total
  1092. return;
  1093. }
  1094. // ---------- 首波逻辑(原有代码) ----------
  1095. this.startGame();
  1096. }
  1097. }