GameManager.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  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 { GamePause } from '../CombatSystem/GamePause';
  16. const { ccclass, property } = _decorator;
  17. /**
  18. * 游戏状态枚举
  19. */
  20. enum GameState {
  21. PLAYING = 'playing',
  22. SUCCESS = 'success',
  23. DEFEAT = 'defeat',
  24. PAUSED = 'paused'
  25. }
  26. /**
  27. * 增强版游戏管理器
  28. * 整合了游戏启动、状态管理、UI控制等功能
  29. */
  30. @ccclass('GameManager')
  31. export class GameManager extends Component {
  32. // === 原GameManager属性 ===
  33. @property({
  34. type: Node,
  35. tooltip: '拖拽BallController节点到这里'
  36. })
  37. public ballController: Node = null;
  38. @property({
  39. type: Node,
  40. tooltip: '拖拽GameBlockSelection节点到这里'
  41. })
  42. public gameBlockSelection: Node = null;
  43. @property({
  44. type: Node,
  45. tooltip: '拖拽GameArea节点到这里'
  46. })
  47. public gameArea: Node = null;
  48. @property({
  49. type: Node,
  50. tooltip: '拖拽EnemyController节点到这里'
  51. })
  52. public enemyManager: Node = null;
  53. // === 游戏状态管理属性 ===
  54. @property({
  55. type: Node,
  56. tooltip: '血量显示节点 (HeartLabeld)'
  57. })
  58. public heartLabelNode: Node = null;
  59. @property({
  60. type: Node,
  61. tooltip: '游戏成功UI节点 (GameSuccess)'
  62. })
  63. public gameSuccessUI: Node = null;
  64. @property({
  65. type: Node,
  66. tooltip: '游戏失败UI节点 (GameDefeat)'
  67. })
  68. public gameDefeatUI: Node = null;
  69. // === 能量与技能选择 UI ===
  70. @property({
  71. type: Node,
  72. tooltip: '拖拽 EnergyBar (ProgressBar) 节点到这里'
  73. })
  74. public energyBarNode: Node = null;
  75. @property({
  76. type: Node,
  77. tooltip: '拖拽 SelectSkillUI 节点到这里'
  78. })
  79. public selectSkillUI: Node = null;
  80. // === 游戏配置属性 ===
  81. // 墙体基础血量由存档决定,不再通过属性面板设置
  82. private wallHealth: number = 100;
  83. @property({
  84. tooltip: '初始血量'
  85. })
  86. public initialHealth: number = 100;
  87. @property({
  88. tooltip: '状态检查间隔(秒)'
  89. })
  90. public checkInterval: number = 1.0;
  91. // === 私有属性 ===
  92. private gameStarted: boolean = false;
  93. private currentHealth: number = 100;
  94. private currentState: GameState = GameState.PLAYING;
  95. private checkTimer: number = 0;
  96. private heartLabel: Label = null;
  97. private enemyController: EnemyController = null;
  98. private levelManager: LevelManager = null;
  99. private levelConfigManager: LevelConfigManager = null;
  100. private saveDataManager: SaveDataManager = null;
  101. // private shopManager: ShopManager = null;
  102. private configManager: ConfigManager = null;
  103. private enemySpawningStarted: boolean = false;
  104. private totalEnemiesSpawned: number = 0;
  105. private currentWave: number = 1;
  106. private currentWaveEnemyCount: number = 0;
  107. private currentWaveTotalEnemies: number = 0; // 当前波次总敌人数
  108. private levelWaves: any[] = []; // 关卡波次配置
  109. private levelTotalEnemies: number = 0; // 本关卡总敌人数
  110. private enemiesKilled: number = 0; // 已击杀敌人数量
  111. // 游戏计时器
  112. private gameStartTime: number = 0;
  113. private gameEndTime: number = 0;
  114. // 游戏区域的边界
  115. private gameBounds = {
  116. left: 0,
  117. right: 0,
  118. top: 0,
  119. bottom: 0
  120. };
  121. private preparingNextWave = false;
  122. // 能量系统
  123. private energyPoints: number = 0;
  124. private readonly ENERGY_MAX: number = 5;
  125. private energyBar: ProgressBar = null;
  126. // GameBlockSelection组件
  127. private blockSelectionComponent: GameBlockSelection = null;
  128. start() {
  129. // 初始化物理系统
  130. this.initPhysicsSystem();
  131. // 初始化管理器
  132. this.initializeManagers();
  133. // 提前初始化本局数据,确保 BlockManager 在 start 时能拿到正确金币
  134. if (!LevelSessionManager.inst.runtime) {
  135. LevelSessionManager.inst.initialize(
  136. this.saveDataManager?.getCurrentLevel() || 1,
  137. this.wallHealth
  138. );
  139. }
  140. // 计算游戏区域边界
  141. this.calculateGameBounds();
  142. // 初始化游戏状态
  143. this.initializeGameState();
  144. // 查找UI节点
  145. this.findUINodes();
  146. // 查找敌人控制器
  147. this.findEnemyController();
  148. // 初始化墙体血量显示
  149. this.initWallHealthDisplay();
  150. // 设置敌人控制器
  151. this.setupEnemyController();
  152. // 设置UI按钮
  153. this.setupUIButtons();
  154. // 初始化GameBlockSelection组件
  155. this.initGameBlockSelection();
  156. // 加载当前关卡配置
  157. this.loadCurrentLevelConfig();
  158. }
  159. update(deltaTime: number) {
  160. if (this.currentState !== GameState.PLAYING) {
  161. return;
  162. }
  163. // 更新检查计时器
  164. this.checkTimer += deltaTime;
  165. if (this.checkTimer >= this.checkInterval) {
  166. this.checkTimer = 0;
  167. this.checkGameState();
  168. }
  169. // 检查自动保存
  170. if (this.saveDataManager) {
  171. this.saveDataManager.checkAutoSave();
  172. }
  173. }
  174. // === 物理系统初始化 ===
  175. private initPhysicsSystem() {
  176. // 确保 PhysicsManager 单例存在
  177. let pm = PhysicsManager.getInstance();
  178. if (!pm) {
  179. const physicsNode = new Node('PhysicsManager');
  180. director.getScene()?.addChild(physicsNode);
  181. pm = physicsNode.addComponent(PhysicsManager);
  182. }
  183. }
  184. // === 管理器初始化 ===
  185. private initializeManagers() {
  186. this.levelManager = LevelManager.getInstance();
  187. // this.shopManager = ShopManager.getInstance();
  188. this.configManager = ConfigManager.getInstance();
  189. this.levelConfigManager = LevelConfigManager.getInstance();
  190. this.enemyController = EnemyController.getInstance() || null;
  191. // 初始化存档管理器
  192. this.saveDataManager = SaveDataManager.getInstance();
  193. this.saveDataManager.initialize();
  194. // 从存档读取墙体基础血量
  195. const pd = this.saveDataManager.getPlayerData();
  196. if (pd && typeof pd.wallBaseHealth === 'number') {
  197. this.wallHealth = pd.wallBaseHealth;
  198. }
  199. }
  200. // === 游戏状态初始化 ===
  201. private initializeGameState() {
  202. this.currentHealth = this.initialHealth;
  203. this.currentState = GameState.PLAYING;
  204. this.checkTimer = 0;
  205. this.enemySpawningStarted = false;
  206. this.totalEnemiesSpawned = 0;
  207. this.currentWave = 1;
  208. this.currentWaveEnemyCount = 0;
  209. this.currentWaveTotalEnemies = 0; // 当前波次总敌人数
  210. // UI 初始化移交给 EnemyController
  211. }
  212. // === 计算游戏区域边界 ===
  213. private calculateGameBounds() {
  214. const canvas = find('Canvas');
  215. if (!canvas) {
  216. return;
  217. }
  218. const canvasUI = canvas.getComponent(UITransform);
  219. if (!canvasUI) {
  220. return;
  221. }
  222. const screenWidth = canvasUI.width;
  223. const screenHeight = canvasUI.height;
  224. const worldPos = canvas.worldPosition;
  225. this.gameBounds.left = worldPos.x - screenWidth / 2;
  226. this.gameBounds.right = worldPos.x + screenWidth / 2;
  227. this.gameBounds.bottom = worldPos.y - screenHeight / 2;
  228. this.gameBounds.top = worldPos.y + screenHeight / 2;
  229. }
  230. // === 查找UI节点 ===
  231. private findUINodes() {
  232. // 查找血量显示节点
  233. if (!this.heartLabelNode) {
  234. this.heartLabelNode = find('Canvas/GameLevelUI/HeartNode/HeartLabeld');
  235. }
  236. if (this.heartLabelNode) {
  237. this.heartLabel = this.heartLabelNode.getComponent(Label);
  238. }
  239. // 查找游戏成功UI
  240. if (!this.gameSuccessUI) {
  241. this.gameSuccessUI = find('Canvas/GameSuccess');
  242. }
  243. if (this.gameSuccessUI) {
  244. this.gameSuccessUI.active = false;
  245. }
  246. // 查找游戏失败UI
  247. if (!this.gameDefeatUI) {
  248. this.gameDefeatUI = find('Canvas/GameDefeat');
  249. }
  250. if (this.gameDefeatUI) {
  251. this.gameDefeatUI.active = false;
  252. }
  253. // 查找能量条
  254. if (!this.energyBarNode) {
  255. this.energyBarNode = find('Canvas/GameLevelUI/EnergyBar');
  256. }
  257. if (this.energyBarNode) {
  258. this.energyBar = this.energyBarNode.getComponent(ProgressBar);
  259. if (this.energyBar) {
  260. this.energyBar.progress = 0;
  261. }
  262. }
  263. // 查找技能选择 UI
  264. if (!this.selectSkillUI) {
  265. this.selectSkillUI = find('Canvas/SelectSkillUI');
  266. }
  267. if (this.selectSkillUI) {
  268. this.selectSkillUI.active = false;
  269. }
  270. }
  271. // === 查找敌人控制器 ===
  272. private findEnemyController() {
  273. if (this.enemyManager) {
  274. this.enemyController = this.enemyManager.getComponent(EnemyController);
  275. }
  276. if (!this.enemyController) {
  277. const enemyNode = find('Canvas/GameLevelUI/EnemyController');
  278. if (enemyNode) {
  279. this.enemyController = enemyNode.getComponent(EnemyController);
  280. }
  281. }
  282. }
  283. // === 初始化墙体血量显示 ===
  284. private initWallHealthDisplay() {
  285. if (this.heartLabelNode && this.heartLabel) {
  286. this.heartLabel.string = this.wallHealth.toString();
  287. }
  288. // 让 EnemyController 自行查找/刷新血量 UI
  289. if (this.enemyController.initWallHealthDisplay) {
  290. this.enemyController.initWallHealthDisplay();
  291. }
  292. }
  293. // === 设置敌人控制器 ===
  294. private setupEnemyController() {
  295. if (!this.enemyManager) {
  296. const gameLevelUI = find('Canvas/GameLevelUI');
  297. if (!gameLevelUI) {
  298. console.error('找不到GameLevelUI节点,无法创建EnemyController');
  299. return;
  300. }
  301. this.enemyManager = new Node('EnemyController');
  302. gameLevelUI.addChild(this.enemyManager);
  303. }
  304. if (!this.enemyController) {
  305. this.enemyController = this.enemyManager.addComponent(EnemyController);
  306. }
  307. // 无论 EnemyController 是否新建,都注入墙体血量
  308. this.enemyController.wallHealth = this.wallHealth;
  309. this.enemyController.updateWallHealthDisplay?.();
  310. }
  311. // === 游戏状态检查 ===
  312. private checkGameState() {
  313. // 更新血量
  314. this.updateHealthFromUI();
  315. if (this.currentHealth <= 0) {
  316. this.triggerGameDefeat();
  317. return;
  318. }
  319. // 检查是否全部击败
  320. if (this.checkAllEnemiesDefeated()) {
  321. this.triggerGameSuccess();
  322. return;
  323. }
  324. }
  325. // === 从UI更新血量 ===
  326. private updateHealthFromUI() {
  327. if (this.heartLabel) {
  328. const healthText = this.heartLabel.string;
  329. const healthMatch = healthText.match(/\d+/);
  330. if (healthMatch) {
  331. const newHealth = parseInt(healthMatch[0]);
  332. if (newHealth !== this.currentHealth) {
  333. this.currentHealth = newHealth;
  334. }
  335. }
  336. }
  337. }
  338. // === 检查所有敌人是否被击败 ===
  339. private checkAllEnemiesDefeated(): boolean {
  340. if (!this.enemyController) {
  341. return false;
  342. }
  343. // 检查敌人是否已开始生成(避免开局就胜利)
  344. if (!this.enemySpawningStarted) {
  345. if (this.enemyController.isGameStarted && this.enemyController.isGameStarted()) {
  346. this.enemySpawningStarted = true;
  347. } else {
  348. return false;
  349. }
  350. }
  351. // 获取当前敌人数量
  352. const currentEnemyCount = this.enemyController.getCurrentEnemyCount ?
  353. this.enemyController.getCurrentEnemyCount() : 0;
  354. // 如果关卡总敌人数已知,以击杀数为准判定胜利
  355. if (this.levelTotalEnemies > 0) {
  356. // 当击杀数达到或超过总敌数且场上没有存活敌人时胜利
  357. return this.enemiesKilled >= this.levelTotalEnemies && currentEnemyCount === 0;
  358. }
  359. // 否则退化到旧逻辑:依赖于是否曾经生成过敌人
  360. // 更新已生成敌人总数(记录曾经达到的最大值)
  361. if (currentEnemyCount > this.totalEnemiesSpawned) {
  362. this.totalEnemiesSpawned = currentEnemyCount;
  363. }
  364. const shouldCheckVictory = this.enemySpawningStarted &&
  365. currentEnemyCount === 0 &&
  366. this.totalEnemiesSpawned > 0;
  367. return shouldCheckVictory;
  368. }
  369. // === 触发游戏失败 ===
  370. private triggerGameDefeat() {
  371. if (this.currentState === GameState.DEFEAT) {
  372. return;
  373. }
  374. this.currentState = GameState.DEFEAT;
  375. this.pauseGame();
  376. if (this.gameDefeatUI) {
  377. this.gameDefeatUI.active = true;
  378. }
  379. this.onGameDefeat();
  380. // 派发游戏失败事件
  381. EventBus.getInstance().emit(GameEvents.GAME_DEFEAT);
  382. }
  383. // === 触发游戏成功 ===
  384. private triggerGameSuccess() {
  385. if (this.currentState === GameState.SUCCESS) {
  386. return;
  387. }
  388. this.currentState = GameState.SUCCESS;
  389. this.pauseGame();
  390. if (this.gameSuccessUI) {
  391. this.gameSuccessUI.active = true;
  392. }
  393. this.onGameSuccess();
  394. // 派发游戏成功事件
  395. EventBus.getInstance().emit(GameEvents.GAME_SUCCESS);
  396. }
  397. // === 暂停游戏 ===
  398. private pauseGame() {
  399. // 设置状态为暂停
  400. this.currentState = GameState.PAUSED;
  401. this.gameStarted = false;
  402. // 使用GamePause统一管理暂停逻辑
  403. const gamePause = GamePause.getInstance();
  404. if (gamePause) {
  405. gamePause.pauseGame();
  406. }
  407. }
  408. // === 恢复游戏 ===
  409. public resumeGame() {
  410. this.currentState = GameState.PLAYING;
  411. this.gameStarted = true;
  412. // 使用GamePause统一管理恢复逻辑
  413. const gamePause = GamePause.getInstance();
  414. if (gamePause) {
  415. gamePause.resumeGame();
  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' as any);
  600. if (mainUIController && typeof (mainUIController as any).updateUI === 'function') {
  601. (mainUIController as any).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. // onConfirmButtonClicked方法已移除,逻辑已整合到handleConfirmAction中
  628. private preservePlacedBlocks() {
  629. const blockController = find('Canvas/GameLevelUI/BlockController');
  630. if (blockController) {
  631. const blockManager = blockController.getComponent('BlockManager') as any;
  632. if (blockManager) {
  633. blockManager.onGameStart();
  634. }
  635. }
  636. }
  637. public startGame() {
  638. if (this.gameStarted) return;
  639. this.gameStarted = true;
  640. this.gameStartTime = Date.now();
  641. this.currentState = GameState.PLAYING;
  642. // 开始生成球
  643. this.spawnBall();
  644. // 启动状态检查
  645. this.checkTimer = 0;
  646. // 设置UI按钮事件
  647. this.setupUIButtons();
  648. // 第一波提示UI后再开始生成敌人
  649. if (this.enemyController && this.enemyController.showStartWavePromptUI) {
  650. this.enemyController.showStartWavePromptUI();
  651. } else {
  652. this.forceStartEnemySpawning();
  653. }
  654. LevelSessionManager.inst.initialize(
  655. SaveDataManager.getInstance().getCurrentLevel(),
  656. this.wallHealth
  657. );
  658. }
  659. private spawnBall() {
  660. if (!this.ballController) return;
  661. const ballControllerComponent = this.ballController.getComponent(BallController);
  662. if (ballControllerComponent) {
  663. ballControllerComponent.startBall();
  664. }
  665. }
  666. public gameOver() {
  667. this.triggerGameDefeat();
  668. }
  669. // === 公共方法 ===
  670. public setHealth(health: number) {
  671. this.currentHealth = Math.max(0, health);
  672. }
  673. public takeDamage(damage: number) {
  674. this.currentHealth = Math.max(0, this.currentHealth - damage);
  675. if (this.currentHealth <= 0) {
  676. this.triggerGameDefeat();
  677. }
  678. }
  679. public getCurrentState(): GameState {
  680. return this.currentState;
  681. }
  682. public restartGame() {
  683. this.currentState = GameState.PLAYING;
  684. this.gameStarted = false;
  685. this.gameStartTime = 0;
  686. this.gameEndTime = 0;
  687. this.currentHealth = this.initialHealth;
  688. this.totalEnemiesSpawned = 0;
  689. this.enemiesKilled = 0;
  690. this.currentWave = 1;
  691. this.currentWaveEnemyCount = 0;
  692. // 重置能量条
  693. this.energyPoints = 0;
  694. if (this.energyBar) {
  695. this.energyBar.progress = 0;
  696. }
  697. if (this.selectSkillUI) {
  698. this.selectSkillUI.active = false;
  699. }
  700. // 关闭胜利/失败界面,确保重新进入时是正常状态
  701. if (this.gameSuccessUI) {
  702. this.gameSuccessUI.active = false;
  703. }
  704. if (this.gameDefeatUI) {
  705. this.gameDefeatUI.active = false;
  706. }
  707. // 通知BlockManager游戏重置
  708. const blockMgrNode = find('Canvas/GameLevelUI/BlockController');
  709. const blockManager = blockMgrNode?.getComponent(BlockManager);
  710. if (blockManager) {
  711. blockManager.onGameReset?.();
  712. }
  713. // 清空关卡剩余敌人
  714. if (this.enemyController && this.enemyController.clearAllEnemies) {
  715. this.enemyController.clearAllEnemies();
  716. }
  717. // 重置墙体血量显示
  718. this.initWallHealthDisplay();
  719. // 初始化本局数据(金币45等)
  720. LevelSessionManager.inst.clear();
  721. LevelSessionManager.inst.initialize(
  722. this.saveDataManager.getCurrentLevel(),
  723. this.wallHealth
  724. );
  725. // 刷新方块金币显示(如果 BlockManager 已存在)
  726. if (blockManager) {
  727. blockManager.updateCoinDisplay?.();
  728. }
  729. }
  730. public isGameOver(): boolean {
  731. return this.currentState === GameState.SUCCESS || this.currentState === GameState.DEFEAT;
  732. }
  733. public forceGameSuccess() {
  734. this.triggerGameSuccess();
  735. }
  736. public forceGameDefeat() {
  737. this.triggerGameDefeat();
  738. }
  739. // === 获取EnemyController组件 ===
  740. public getEnemyController() {
  741. return this.enemyController;
  742. }
  743. // === 调试方法 ===
  744. public getEnemyStatus() {
  745. if (!this.enemyController) return;
  746. const currentCount = this.enemyController.getCurrentEnemyCount();
  747. const gameStarted = this.enemyController.isGameStarted();
  748. const activeEnemies = this.enemyController.getActiveEnemies?.() || [];
  749. if (activeEnemies.length > 0) {
  750. for (let index = 0; index < activeEnemies.length; index++) {
  751. const enemy = activeEnemies[index];
  752. if (enemy?.isValid) {
  753. // 查看敌人状态
  754. } else {
  755. // 无效敌人节点
  756. }
  757. }
  758. }
  759. }
  760. public forceStartEnemySpawning() {
  761. if (this.enemyController) {
  762. this.enemyController.startGame();
  763. }
  764. }
  765. public setTotalEnemiesSpawned(count: number) {
  766. this.totalEnemiesSpawned = count;
  767. }
  768. public testEnemyDetection() {
  769. // 测试敌人检测功能
  770. this.getEnemyStatus();
  771. }
  772. public testComponentAccess() {
  773. // 测试组件访问
  774. if (this.enemyController) {
  775. // 组件访问正常
  776. }
  777. }
  778. public testEnemyAttackWall() {
  779. if (!this.enemyController) return;
  780. const currentHealth = this.enemyController.getCurrentWallHealth();
  781. const testDamage = 50;
  782. this.enemyController.damageWall(testDamage);
  783. const newHealth = this.enemyController.getCurrentWallHealth();
  784. }
  785. onDestroy() {
  786. // 清理按钮事件监听
  787. if (this.gameSuccessUI) {
  788. const buttons = this.gameSuccessUI.getComponentsInChildren(Button);
  789. buttons.forEach(button => {
  790. button.node.off(Button.EventType.CLICK);
  791. });
  792. }
  793. if (this.gameDefeatUI) {
  794. const buttons = this.gameDefeatUI.getComponentsInChildren(Button);
  795. buttons.forEach(button => {
  796. button.node.off(Button.EventType.CLICK);
  797. });
  798. }
  799. }
  800. // === 加载当前关卡配置 ===
  801. public async loadCurrentLevelConfig() {
  802. if (!this.saveDataManager || !this.levelConfigManager) return;
  803. const currentLevel = this.saveDataManager.getCurrentLevel();
  804. try {
  805. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  806. if (levelConfig) {
  807. this.applyLevelConfig(levelConfig);
  808. } else {
  809. console.warn(`关卡 ${currentLevel} 配置加载失败`);
  810. }
  811. } catch (error) {
  812. console.error(`关卡 ${currentLevel} 配置加载错误:`, error);
  813. }
  814. }
  815. private applyLevelConfig(levelConfig: any) {
  816. // 应用关卡配置
  817. // 如果有武器配置,应用武器
  818. if (levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
  819. // 应用武器配置
  820. }
  821. // 如果有波次配置,设置敌人波次
  822. if (levelConfig.waves && Array.isArray(levelConfig.waves)) {
  823. this.levelWaves = levelConfig.waves;
  824. this.currentWave = 1;
  825. // 计算本关卡总敌人数
  826. this.levelTotalEnemies = 0;
  827. for (const wave of this.levelWaves) {
  828. for (const enemy of wave.enemies || []) {
  829. this.levelTotalEnemies += enemy.count || 0;
  830. }
  831. }
  832. // 通知 EnemyController 初始化第一波数据及 UI
  833. if (this.enemyController) {
  834. const totalWaves = this.levelWaves.length;
  835. const firstWaveEnemies = this.levelWaves.length > 0 && this.levelWaves[0].enemies ?
  836. this.levelWaves[0].enemies.reduce((t: number, g: any) => t + (g.count || 0), 0) : 0;
  837. this.enemyController.startWave(1, totalWaves, firstWaveEnemies);
  838. // 同步 GameManager 当前波敌人数,避免剩余敌人数计算出错
  839. this.setCurrentWave(1, firstWaveEnemies);
  840. }
  841. }
  842. }
  843. // === 获取当前关卡信息 ===
  844. public async getCurrentLevelInfo() {
  845. const currentLevel = this.saveDataManager ?
  846. this.saveDataManager.getCurrentLevel() :
  847. (this.levelManager ? this.levelManager.getCurrentLevel() : 1);
  848. const levelProgress = this.saveDataManager ?
  849. this.saveDataManager.getLevelProgress(currentLevel) : null;
  850. const levelData = this.levelManager ?
  851. this.levelManager.getLevelData(currentLevel) : null;
  852. const levelConfig = await this.loadCurrentLevelConfig();
  853. return {
  854. level: currentLevel,
  855. maxUnlockedLevel: this.saveDataManager ?
  856. this.saveDataManager.getMaxUnlockedLevel() :
  857. (this.levelManager ? this.levelManager.getMaxUnlockedLevel() : 1),
  858. progress: levelProgress,
  859. data: levelData,
  860. config: levelConfig,
  861. playerData: this.saveDataManager ? {
  862. coins: this.saveDataManager.getCoins(),
  863. diamonds: this.saveDataManager.getDiamonds(),
  864. gems: this.saveDataManager.getGems(),
  865. playerLevel: this.saveDataManager.getPlayerLevel()
  866. } : null
  867. };
  868. }
  869. // === 更新波次显示 ===
  870. private updateWaveDisplay() {
  871. // UI 更新交由 EnemyController 处理
  872. }
  873. // === 更新敌人数量显示 ===
  874. private updateEnemyCountDisplay() {
  875. // UI 更新交由 EnemyController 处理
  876. }
  877. // === 设置当前波次 ===
  878. public setCurrentWave(wave: number, enemyCount: number = 0) {
  879. this.currentWave = wave;
  880. this.currentWaveEnemyCount = 0; // 重置当前击杀数
  881. this.currentWaveTotalEnemies = enemyCount; // 设置该波次总敌人数
  882. if (this.enemyController) {
  883. const totalWaves = this.levelWaves?.length || 1;
  884. this.enemyController.startWave(wave, totalWaves, enemyCount);
  885. }
  886. }
  887. // === 更新当前波次敌人数量 ===
  888. public updateCurrentWaveEnemyCount(count: number) {
  889. this.currentWaveEnemyCount = count;
  890. }
  891. // === 获取当前波次 ===
  892. public getCurrentWave(): number {
  893. return this.currentWave;
  894. }
  895. // === 获取当前波次敌人数量 ===
  896. public getCurrentWaveEnemyCount(): number {
  897. return this.currentWaveEnemyCount;
  898. }
  899. // === 获取当前波次总敌人数量 ===
  900. public getCurrentWaveTotalEnemies(): number {
  901. return this.currentWaveTotalEnemies;
  902. }
  903. // === 进入下一波 ===
  904. public nextWave() {
  905. this.currentWave++;
  906. // 根据关卡配置获取下一波敌人数
  907. let enemyTotal = 0;
  908. if (this.levelWaves && this.levelWaves.length >= this.currentWave) {
  909. const waveCfg = this.levelWaves[this.currentWave - 1];
  910. if (waveCfg && waveCfg.enemies) {
  911. enemyTotal = waveCfg.enemies.reduce((t: number, g: any) => t + (g.count || 0), 0);
  912. }
  913. }
  914. this.setCurrentWave(this.currentWave, enemyTotal);
  915. }
  916. /** 显示下一波提示并在短暂延迟后开始下一波 */
  917. private showNextWavePrompt() {
  918. this.showBlockSelectionForNextWave(); // 使用新的方法
  919. }
  920. // 显示方块选择UI用于下一波
  921. private showBlockSelectionForNextWave() {
  922. if (this.blockSelectionComponent) {
  923. this.blockSelectionComponent.showBlockSelection(true);
  924. this.preparingNextWave = true;
  925. // 使用GamePause来暂停游戏
  926. const gamePause = GamePause.getInstance();
  927. if (gamePause) {
  928. gamePause.pauseGame();
  929. }
  930. }
  931. }
  932. /** 敌人被消灭时由 EnemyController 调用 */
  933. public onEnemyKilled() {
  934. this.enemiesKilled++;
  935. // 当前波击杀 +1
  936. this.currentWaveEnemyCount++;
  937. // 增加能量点
  938. this.incrementEnergy();
  939. const remaining = this.currentWaveTotalEnemies - this.currentWaveEnemyCount;
  940. if (remaining <= 0) {
  941. // 当前波结束
  942. if (this.currentWave < (this.levelWaves?.length || 1)) {
  943. // 还有下一波,显示提示
  944. this.showNextWavePrompt();
  945. } else {
  946. // 最后一波也结束
  947. this.triggerGameSuccess();
  948. }
  949. }
  950. }
  951. /** 每击杀敌人调用,能量 +1,并更新进度条。满值时弹出技能选择界面 */
  952. private incrementEnergy() {
  953. this.energyPoints = Math.min(this.energyPoints + 1, this.ENERGY_MAX);
  954. this.updateEnergyBar();
  955. if (this.energyPoints >= this.ENERGY_MAX) {
  956. this.onEnergyFull();
  957. }
  958. }
  959. /** 更新能量条显示 */
  960. private updateEnergyBar() {
  961. if (this.energyBar) {
  962. this.energyBar.progress = this.energyPoints / this.ENERGY_MAX;
  963. }
  964. }
  965. /** 能量满时触发 */
  966. private onEnergyFull() {
  967. if (this.selectSkillUI && !this.selectSkillUI.active) {
  968. // 暂停游戏后再弹出 UI
  969. this.pauseGame();
  970. this.selectSkillUI.active = true;
  971. }
  972. }
  973. /** 供外部调用:重置能量值并刷新显示 */
  974. public resetEnergy() {
  975. this.energyPoints = 0;
  976. this.updateEnergyBar();
  977. }
  978. /* ========= 墙体血量 / 等级相关 ========= */
  979. private wallHpMap: Record<number, number> = {
  980. 1: 100,
  981. 2: 1000,
  982. 3: 1200,
  983. 4: 1500,
  984. 5: 2000
  985. };
  986. /** 根据等级获取墙体血量 */
  987. public getWallHealthByLevel(level: number): number {
  988. return this.wallHpMap[level] || (100 + (level - 1) * 200);
  989. }
  990. /** 获取当前墙壁等级 */
  991. public getCurrentWallLevel(): number {
  992. return this.saveDataManager?.getPlayerData().playerLevel || 1;
  993. }
  994. /** 获取当前墙体血量 */
  995. public getCurrentWallHealth(): number {
  996. return this.saveDataManager?.getPlayerData().wallBaseHealth || this.getWallHealthByLevel(1);
  997. }
  998. /** 升级墙体等级,返回升级后信息,失败返回null */
  999. public upgradeWallLevel(): { currentLevel: number; currentHp: number; nextLevel: number; nextHp: number } | null {
  1000. if (!this.saveDataManager) return null;
  1001. const pd = this.saveDataManager.getPlayerData();
  1002. const curLvl = pd.playerLevel || 1;
  1003. if (curLvl >= 5) return null; // 已达最高级
  1004. const newLvl = curLvl + 1;
  1005. const newHp = this.getWallHealthByLevel(newLvl);
  1006. pd.playerLevel = newLvl;
  1007. pd.wallBaseHealth = newHp;
  1008. this.saveDataManager.savePlayerData(true);
  1009. // 更新内存中的数值
  1010. this.wallHealth = newHp;
  1011. if (this.enemyController) {
  1012. this.enemyController.wallHealth = newHp;
  1013. this.enemyController.updateWallHealthDisplay?.();
  1014. }
  1015. return {
  1016. currentLevel: newLvl,
  1017. currentHp: newHp,
  1018. nextLevel: newLvl + 1,
  1019. nextHp: this.getWallHealthByLevel(newLvl + 1)
  1020. };
  1021. }
  1022. // 初始化GameBlockSelection组件
  1023. private initGameBlockSelection() {
  1024. if (this.gameBlockSelection) {
  1025. this.blockSelectionComponent = this.gameBlockSelection.getComponent(GameBlockSelection);
  1026. if (this.blockSelectionComponent) {
  1027. // 设置确认回调
  1028. this.blockSelectionComponent.setConfirmCallback(() => {
  1029. this.handleConfirmAction();
  1030. });
  1031. }
  1032. }
  1033. }
  1034. // 处理确认操作(替代原来的onConfirmButtonClicked)
  1035. private handleConfirmAction() {
  1036. if (this.preparingNextWave) {
  1037. // 进入下一波
  1038. this.preparingNextWave = false;
  1039. this.enemyController.showStartWavePromptUI(); // 弹 startWaveUI 后自动 startGame()
  1040. this.nextWave(); // 更新 wave 计数 & total
  1041. return;
  1042. }
  1043. // ---------- 首波逻辑(原有代码) ----------
  1044. this.startGame();
  1045. }
  1046. }