GameManager.ts 41 KB

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