GameManager.ts 39 KB

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