GameManager.ts 40 KB

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