GameManager.ts 40 KB

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