| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246 |
- import { _decorator, Component, Node, Prefab, instantiate, Vec3, find, director, Canvas, UITransform, Button, Label, ProgressBar, EPhysics2DDrawFlags, sys } from 'cc';
- import { LevelManager } from './LevelManager';
- import { LevelConfigManager } from './LevelConfigManager';
- import { SaveDataManager } from './SaveDataManager';
- import { ShopManager } from '../ShopSystem/ShopManager';
- import { ConfigManager } from '../Core/ConfigManager';
- import { EnemyController } from '../CombatSystem/EnemyController';
- import EventBus, { GameEvents } from '../Core/EventBus';
- import { PhysicsManager } from '../Core/PhysicsManager';
- import { MainUIController } from './MainUIController';
- import { BallController } from '../CombatSystem/BallController';
- import { BlockManager } from '../CombatSystem/BlockManager';
- import { LevelSessionManager } from '../Core/LevelSessionManager';
- const { ccclass, property } = _decorator;
- /**
- * 游戏状态枚举
- */
- enum GameState {
- PLAYING = 'playing',
- SUCCESS = 'success',
- DEFEAT = 'defeat',
- PAUSED = 'paused'
- }
- /**
- * 增强版游戏管理器
- * 整合了游戏启动、状态管理、UI控制等功能
- */
- @ccclass('GameManager')
- export class GameManager extends Component {
-
- // === 原GameManager属性 ===
- @property({
- type: Node,
- tooltip: '拖拽BallController节点到这里'
- })
- public ballController: Node = null;
- @property({
- type: Node,
- tooltip: '拖拽BlockSelectionUI节点到这里'
- })
- public blockSelectionUI: Node = null;
- @property({
- type: Node,
- tooltip: '拖拽GameArea节点到这里'
- })
- public gameArea: Node = null;
- @property({
- type: Node,
- tooltip: '拖拽EnemyController节点到这里'
- })
- public enemyManager: Node = null;
- // === 游戏状态管理属性 ===
- @property({
- type: Node,
- tooltip: '血量显示节点 (HeartLabeld)'
- })
- public heartLabelNode: Node = null;
- @property({
- type: Node,
- tooltip: '游戏成功UI节点 (GameSuccess)'
- })
- public gameSuccessUI: Node = null;
- @property({
- type: Node,
- tooltip: '游戏失败UI节点 (GameDefeat)'
- })
- public gameDefeatUI: Node = null;
- // === 能量与技能选择 UI ===
- @property({
- type: Node,
- tooltip: '拖拽 EnergyBar (ProgressBar) 节点到这里'
- })
- public energyBarNode: Node = null;
- @property({
- type: Node,
- tooltip: '拖拽 SelectSkillUI 节点到这里'
- })
- public selectSkillUI: Node = null;
- // === 游戏配置属性 ===
- // 墙体基础血量由存档决定,不再通过属性面板设置
- private wallHealth: number = 100;
- @property({
- tooltip: '初始血量'
- })
- public initialHealth: number = 100;
- @property({
- tooltip: '状态检查间隔(秒)'
- })
- public checkInterval: number = 1.0;
- // === 私有属性 ===
- private gameStarted: boolean = false;
- private currentHealth: number = 100;
- private currentState: GameState = GameState.PLAYING;
- private checkTimer: number = 0;
- private heartLabel: Label = null;
- private enemyController: EnemyController = null;
- private levelManager: LevelManager = null;
- private levelConfigManager: LevelConfigManager = null;
- private saveDataManager: SaveDataManager = null;
- private shopManager: ShopManager = null;
- private configManager: ConfigManager = null;
- private enemySpawningStarted: boolean = false;
- private totalEnemiesSpawned: number = 0;
- private currentWave: number = 1;
- private currentWaveEnemyCount: number = 0;
- private currentWaveTotalEnemies: number = 0; // 当前波次总敌人数
- private levelWaves: any[] = []; // 关卡波次配置
- private levelTotalEnemies: number = 0; // 本关卡总敌人数
- private enemiesKilled: number = 0; // 已击杀敌人数量
-
- // 游戏计时器
- private gameStartTime: number = 0;
- private gameEndTime: number = 0;
- // 游戏区域的边界
- private gameBounds = {
- left: 0,
- right: 0,
- top: 0,
- bottom: 0
- };
- private preparingNextWave = false;
- // 能量系统
- private energyPoints: number = 0;
- private readonly ENERGY_MAX: number = 5;
- private energyBar: ProgressBar = null;
- start() {
- // 初始化物理系统
- this.initPhysicsSystem();
-
- // 初始化管理器
- this.initializeManagers();
- // 提前初始化本局数据,确保 BlockManager 在 start 时能拿到正确金币
- if (!LevelSessionManager.inst.runtime) {
- LevelSessionManager.inst.initialize(
- this.saveDataManager?.getCurrentLevel() || 1,
- this.wallHealth
- );
- }
-
- // 计算游戏区域边界
- this.calculateGameBounds();
-
- // 初始化游戏状态
- this.initializeGameState();
-
- // 查找UI节点
- this.findUINodes();
-
- // 查找敌人控制器
- this.findEnemyController();
-
- // 初始化墙体血量显示
- this.initWallHealthDisplay();
-
- // 设置敌人控制器
- this.setupEnemyController();
-
- // 设置UI按钮
- this.setupUIButtons();
-
- // 加载当前关卡配置
- this.loadCurrentLevelConfig();
- }
- update(deltaTime: number) {
- if (this.currentState !== GameState.PLAYING) {
- return;
- }
- // 更新检查计时器
- this.checkTimer += deltaTime;
-
- if (this.checkTimer >= this.checkInterval) {
- this.checkTimer = 0;
- this.checkGameState();
- }
-
- // 检查自动保存
- if (this.saveDataManager) {
- this.saveDataManager.checkAutoSave();
- }
- }
- // === 物理系统初始化 ===
- private initPhysicsSystem() {
- // 确保 PhysicsManager 单例存在
- let pm = PhysicsManager.getInstance();
- if (!pm) {
- const physicsNode = new Node('PhysicsManager');
- director.getScene()?.addChild(physicsNode);
- pm = physicsNode.addComponent(PhysicsManager);
- }
- }
- // === 管理器初始化 ===
- private initializeManagers() {
- this.levelManager = LevelManager.getInstance();
- this.shopManager = ShopManager.getInstance();
- this.configManager = ConfigManager.getInstance();
- this.levelConfigManager = LevelConfigManager.getInstance();
- this.enemyController = EnemyController.getInstance() || null;
-
- // 初始化存档管理器
- this.saveDataManager = SaveDataManager.getInstance();
- this.saveDataManager.initialize();
- // 从存档读取墙体基础血量
- const pd = this.saveDataManager.getPlayerData();
- if (pd && typeof pd.wallBaseHealth === 'number') {
- this.wallHealth = pd.wallBaseHealth;
- }
- }
- // === 游戏状态初始化 ===
- private initializeGameState() {
- this.currentHealth = this.initialHealth;
- this.currentState = GameState.PLAYING;
- this.checkTimer = 0;
- this.enemySpawningStarted = false;
- this.totalEnemiesSpawned = 0;
- this.currentWave = 1;
- this.currentWaveEnemyCount = 0;
- this.currentWaveTotalEnemies = 0; // 当前波次总敌人数
-
- // UI 初始化移交给 EnemyController
- }
- // === 计算游戏区域边界 ===
- private calculateGameBounds() {
- const canvas = find('Canvas');
- if (!canvas) {
- return;
- }
- const canvasUI = canvas.getComponent(UITransform);
- if (!canvasUI) {
- return;
- }
- const screenWidth = canvasUI.width;
- const screenHeight = canvasUI.height;
- const worldPos = canvas.worldPosition;
- this.gameBounds.left = worldPos.x - screenWidth / 2;
- this.gameBounds.right = worldPos.x + screenWidth / 2;
- this.gameBounds.bottom = worldPos.y - screenHeight / 2;
- this.gameBounds.top = worldPos.y + screenHeight / 2;
- }
- // === 查找UI节点 ===
- private findUINodes() {
- // 查找血量显示节点
- if (!this.heartLabelNode) {
- this.heartLabelNode = find('Canvas/GameLevelUI/HeartNode/HeartLabeld');
- }
-
- if (this.heartLabelNode) {
- this.heartLabel = this.heartLabelNode.getComponent(Label);
- }
-
- // 查找游戏成功UI
- if (!this.gameSuccessUI) {
- this.gameSuccessUI = find('Canvas/GameSuccess');
- }
-
- if (this.gameSuccessUI) {
- this.gameSuccessUI.active = false;
- }
-
- // 查找游戏失败UI
- if (!this.gameDefeatUI) {
- this.gameDefeatUI = find('Canvas/GameDefeat');
- }
-
- if (this.gameDefeatUI) {
- this.gameDefeatUI.active = false;
- }
- // 查找能量条
- if (!this.energyBarNode) {
- this.energyBarNode = find('Canvas/GameLevelUI/EnergyBar');
- }
- if (this.energyBarNode) {
- this.energyBar = this.energyBarNode.getComponent(ProgressBar);
- if (this.energyBar) {
- this.energyBar.progress = 0;
- }
- }
- // 查找技能选择 UI
- if (!this.selectSkillUI) {
- this.selectSkillUI = find('Canvas/SelectSkillUI');
- }
- if (this.selectSkillUI) {
- this.selectSkillUI.active = false;
- }
- }
- // === 查找敌人控制器 ===
- private findEnemyController() {
- if (this.enemyManager) {
- this.enemyController = this.enemyManager.getComponent(EnemyController);
- }
-
- if (!this.enemyController) {
- const enemyNode = find('Canvas/GameLevelUI/EnemyController');
- if (enemyNode) {
- this.enemyController = enemyNode.getComponent(EnemyController);
- }
- }
- }
- // === 初始化墙体血量显示 ===
- private initWallHealthDisplay() {
- if (this.heartLabelNode && this.heartLabel) {
- this.heartLabel.string = this.wallHealth.toString();
- }
-
- // 让 EnemyController 自行查找/刷新血量 UI
- if (this.enemyController.initWallHealthDisplay) {
- this.enemyController.initWallHealthDisplay();
- }
- }
- // === 设置敌人控制器 ===
- private setupEnemyController() {
- if (!this.enemyManager) {
- const gameLevelUI = find('Canvas/GameLevelUI');
- if (!gameLevelUI) {
- console.error('找不到GameLevelUI节点,无法创建EnemyController');
- return;
- }
-
- this.enemyManager = new Node('EnemyController');
- gameLevelUI.addChild(this.enemyManager);
- }
-
- if (!this.enemyController) {
- this.enemyController = this.enemyManager.addComponent(EnemyController);
- this.enemyController.wallHealth = this.wallHealth;
- }
- }
- // === 游戏状态检查 ===
- private checkGameState() {
- // 更新血量
- this.updateHealthFromUI();
-
- if (this.currentHealth <= 0) {
- this.triggerGameDefeat();
- return;
- }
- // 检查是否全部击败
- if (this.checkAllEnemiesDefeated()) {
- this.triggerGameSuccess();
- return;
- }
- }
- // === 从UI更新血量 ===
- private updateHealthFromUI() {
- if (this.heartLabel) {
- const healthText = this.heartLabel.string;
- const healthMatch = healthText.match(/\d+/);
- if (healthMatch) {
- const newHealth = parseInt(healthMatch[0]);
- if (newHealth !== this.currentHealth) {
- this.currentHealth = newHealth;
- }
- }
- }
- }
- // === 检查所有敌人是否被击败 ===
- private checkAllEnemiesDefeated(): boolean {
- if (!this.enemyController) {
- return false;
- }
- // 检查敌人是否已开始生成(避免开局就胜利)
- if (!this.enemySpawningStarted) {
- if (this.enemyController.isGameStarted && this.enemyController.isGameStarted()) {
- this.enemySpawningStarted = true;
- } else {
- return false;
- }
- }
- // 获取当前敌人数量
- const currentEnemyCount = this.enemyController.getCurrentEnemyCount ?
- this.enemyController.getCurrentEnemyCount() : 0;
- // 如果关卡总敌人数已知,以击杀数为准判定胜利
- if (this.levelTotalEnemies > 0) {
- // 当击杀数达到或超过总敌数且场上没有存活敌人时胜利
- return this.enemiesKilled >= this.levelTotalEnemies && currentEnemyCount === 0;
- }
- // 否则退化到旧逻辑:依赖于是否曾经生成过敌人
- // 更新已生成敌人总数(记录曾经达到的最大值)
- if (currentEnemyCount > this.totalEnemiesSpawned) {
- this.totalEnemiesSpawned = currentEnemyCount;
- }
- const shouldCheckVictory = this.enemySpawningStarted &&
- currentEnemyCount === 0 &&
- this.totalEnemiesSpawned > 0;
- return shouldCheckVictory;
- }
- // === 触发游戏失败 ===
- private triggerGameDefeat() {
- if (this.currentState === GameState.DEFEAT) {
- return;
- }
- this.currentState = GameState.DEFEAT;
- this.pauseGame();
- if (this.gameDefeatUI) {
- this.gameDefeatUI.active = true;
- }
- this.onGameDefeat();
- // 派发游戏失败事件
- EventBus.getInstance().emit(GameEvents.GAME_DEFEAT);
- }
- // === 触发游戏成功 ===
- private triggerGameSuccess() {
- if (this.currentState === GameState.SUCCESS) {
- return;
- }
- this.currentState = GameState.SUCCESS;
- this.pauseGame();
- if (this.gameSuccessUI) {
- this.gameSuccessUI.active = true;
- }
- this.onGameSuccess();
- // 派发游戏成功事件
- EventBus.getInstance().emit(GameEvents.GAME_SUCCESS);
- }
- // === 暂停游戏 ===
- private pauseGame() {
- this.gameStarted = false;
-
- if (this.enemyController && this.enemyController.pauseSpawning) {
- this.enemyController.pauseSpawning();
- }
- }
- // === 恢复游戏 ===
- public resumeGame() {
- this.currentState = GameState.PLAYING;
- this.gameStarted = true;
-
- if (this.enemyController && this.enemyController.resumeSpawning) {
- this.enemyController.resumeSpawning();
- }
- if (this.gameSuccessUI) {
- this.gameSuccessUI.active = false;
- }
- if (this.gameDefeatUI) {
- this.gameDefeatUI.active = false;
- }
- }
- // === 游戏失败回调 ===
- private onGameDefeat() {
- this.gameEndTime = Date.now();
-
- // 记录游戏失败到存档
- if (this.saveDataManager) {
- const currentLevel = this.saveDataManager.getCurrentLevel();
- this.saveDataManager.failLevel(currentLevel);
-
- // 更新统计数据
- this.saveDataManager.updateStatistic('totalTimePlayed', this.getGameDuration());
- }
- }
- // === 游戏成功回调 ===
- private onGameSuccess() {
- this.gameEndTime = Date.now();
-
- this.giveReward();
- this.onLevelComplete();
- }
- // === 给予奖励 ===
- private giveReward() {
- if (!this.saveDataManager) return;
- const currentLevel = this.saveDataManager.getCurrentLevel();
- const baseReward = currentLevel * 50;
- const healthBonus = Math.floor(this.currentHealth * 0.1);
- const timeBonus = this.calculateTimeBonus();
- const totalCoins = baseReward + healthBonus + timeBonus;
-
- // 给予金币奖励
- this.saveDataManager.addCoins(totalCoins, `level_${currentLevel}_complete`);
-
- // 如果是首次完成,给予额外奖励
- if (!this.saveDataManager.isLevelCompleted(currentLevel)) {
- const firstClearBonus = currentLevel * 25;
- this.saveDataManager.addCoins(firstClearBonus, `level_${currentLevel}_first_clear`);
- }
- }
- // === 处理关卡完成 ===
- private onLevelComplete(score: number = 0, stars: number = 1) {
- if (!this.saveDataManager) return;
-
- const currentLevel = this.saveDataManager.getCurrentLevel();
- const gameTime = this.getGameDuration();
-
- // 计算得分(基于剩余血量、用时等)
- const calculatedScore = this.calculateScore();
- const finalScore = Math.max(score, calculatedScore);
-
- // 计算星级(基于表现)
- const calculatedStars = this.calculateStars();
- const finalStars = Math.max(stars, calculatedStars);
-
- // 记录关卡完成到存档
- this.saveDataManager.completeLevel(currentLevel, finalScore, gameTime, finalStars);
-
- // 更新统计数据
- this.saveDataManager.updateStatistic('totalTimePlayed', gameTime);
- this.saveDataManager.updateStatistic('totalEnemiesDefeated', this.totalEnemiesSpawned);
-
- // 兼容原有的LevelManager
- if (this.levelManager) {
- this.levelManager.completeLevel(currentLevel, finalScore, finalStars);
- }
- }
-
- // === 计算游戏时长 ===
- private getGameDuration(): number {
- if (this.gameStartTime === 0) return 0;
- const endTime = this.gameEndTime || Date.now();
- return Math.floor((endTime - this.gameStartTime) / 1000);
- }
-
- // === 计算时间奖励 ===
- private calculateTimeBonus(): number {
- const gameTime = this.getGameDuration();
- if (gameTime === 0) return 0;
-
- // 时间越短奖励越多,最多额外50%奖励
- const maxTime = 300; // 5分钟
- const timeRatio = Math.max(0, (maxTime - gameTime) / maxTime);
- const baseReward = this.saveDataManager.getCurrentLevel() * 50;
- return Math.floor(baseReward * timeRatio * 0.5);
- }
-
- // === 计算得分 ===
- private calculateScore(): number {
- const currentLevel = this.saveDataManager?.getCurrentLevel() || 1;
- const baseScore = currentLevel * 1000;
- const healthScore = this.currentHealth * 10;
- const enemyScore = this.totalEnemiesSpawned * 50;
- const timeScore = this.calculateTimeBonus();
-
- return baseScore + healthScore + enemyScore + timeScore;
- }
-
- // === 计算星级 ===
- private calculateStars(): number {
- const healthRatio = this.currentHealth / this.initialHealth;
- const gameTime = this.getGameDuration();
-
- // 基于血量剩余和用时计算星级
- if (healthRatio >= 0.8 && gameTime <= 120) {
- return 3; // 3星:血量80%以上,2分钟内完成
- } else if (healthRatio >= 0.5 && gameTime <= 300) {
- return 2; // 2星:血量50%以上,5分钟内完成
- } else if (healthRatio > 0) {
- return 1; // 1星:只要完成就有1星
- }
-
- return 1;
- }
- // === 设置UI按钮 ===
- private setupUIButtons() {
- this.setupSuccessUIButtons();
- this.setupDefeatUIButtons();
- }
- // === 设置成功界面按钮 ===
- private setupSuccessUIButtons() {
- if (this.gameSuccessUI) {
- const nextLevelBtn = this.gameSuccessUI.getChildByName('NextLevelBtn');
- const restartBtn = this.gameSuccessUI.getChildByName('RestartBtn');
- const mainMenuBtn = this.gameSuccessUI.getChildByName('MainMenuBtn');
- const shopBtn = this.gameSuccessUI.getChildByName('ShopBtn');
- if (nextLevelBtn) {
- const button = nextLevelBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onRestartClick, this);
- }
- }
- if (restartBtn) {
- const button = restartBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onRestartClick, this);
- }
- }
- if (mainMenuBtn) {
- const button = mainMenuBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onMainMenuClick, this);
- }
- }
- if (shopBtn) {
- const button = shopBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onShopClick, this);
- }
- }
- }
- }
- // === 设置失败界面按钮 ===
- private setupDefeatUIButtons() {
- if (this.gameDefeatUI) {
- const restartBtn = this.gameDefeatUI.getChildByName('RestartBtn');
- const mainMenuBtn = this.gameDefeatUI.getChildByName('MainMenuBtn');
- const shopBtn = this.gameDefeatUI.getChildByName('ShopBtn');
- const reviveBtn = this.gameDefeatUI.getChildByName('ReviveBtn');
- if (restartBtn) {
- const button = restartBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onRestartClick, this);
- }
- }
- if (mainMenuBtn) {
- const button = mainMenuBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onMainMenuClick, this);
- }
- }
- if (shopBtn) {
- const button = shopBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onShopClick, this);
- }
- }
- if (reviveBtn) {
- const button = reviveBtn.getComponent(Button);
- if (button) {
- button.node.on(Button.EventType.CLICK, this.onReviveClick, this);
- }
- }
- }
- }
- // === 按钮点击事件处理 ===
- private onRestartClick() {
- this.restartGame();
- }
-
- private onMainMenuClick() {
- // 隐藏游戏界面,显示主界面
- const gameLevelUI = find('Canvas/GameLevelUI');
- const mainUI = find('Canvas/MainUI');
- if (gameLevelUI) gameLevelUI.active = false;
- if (mainUI) mainUI.active = true;
-
- // 更新主界面
- const mainUIController = mainUI?.getComponent(MainUIController);
- if (mainUIController) {
- mainUIController.updateUI();
- }
- }
-
- private onShopClick() {
- // 打开商店界面
- const gameLevelUI = find('Canvas/GameLevelUI');
- const shopUI = find('Canvas/ShopUI');
- if (gameLevelUI) gameLevelUI.active = false;
- if (shopUI) shopUI.active = true;
- }
-
- private onReviveClick() {
- const reviveCost = 10; // 复活消耗的钻石数量
-
- if (this.saveDataManager && this.saveDataManager.spendDiamonds(reviveCost)) {
- this.revivePlayer();
- }
- }
- // === 复活玩家 ===
- private revivePlayer() {
- this.setHealth(50);
- this.restartGame();
- }
- // === 重新开始当前关卡 ===
- private restartCurrentLevel() {
- this.restartGame();
- }
- // === 原GameManager方法 ===
- public onConfirmButtonClicked() {
- if (this.blockSelectionUI) this.blockSelectionUI.active = false;
- if (this.preparingNextWave) {
- // 进入下一波
- this.preparingNextWave = false;
- this.enemyController.showStartWavePromptUI(); // 弹 startWaveUI 后自动 startGame()
- this.nextWave(); // 更新 wave 计数 & total
- return;
- }
- // ---------- 首波逻辑(原有代码) ----------
- const gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
- if (gridContainer) {
- gridContainer.active = true;
- }
-
- this.preservePlacedBlocks();
- this.startGame();
- }
-
- private preservePlacedBlocks() {
- const blockController = find('Canvas/GameLevelUI/BlockController');
-
- if (blockController) {
- const blockManager = blockController.getComponent('BlockManager') as any;
-
- if (blockManager) {
- blockManager.onGameStart();
- }
- }
- }
- public startGame() {
- if (this.gameStarted) return;
-
- this.gameStarted = true;
- this.gameStartTime = Date.now();
- this.currentState = GameState.PLAYING;
-
- // 开始生成球
- this.spawnBall();
-
- // 启动状态检查
- this.checkTimer = 0;
-
- // 设置UI按钮事件
- this.setupUIButtons();
- // 第一波提示UI后再开始生成敌人
- if (this.enemyController && this.enemyController.showStartWavePromptUI) {
- this.enemyController.showStartWavePromptUI();
- } else {
- this.forceStartEnemySpawning();
- }
- LevelSessionManager.inst.initialize(
- SaveDataManager.getInstance().getCurrentLevel(),
- this.wallHealth
- );
- }
-
- private spawnBall() {
- if (!this.ballController) return;
-
- const ballControllerComponent = this.ballController.getComponent(BallController);
- if (ballControllerComponent) {
- ballControllerComponent.startBall();
- }
- }
- public gameOver() {
- this.triggerGameDefeat();
- }
- // === 公共方法 ===
- public setHealth(health: number) {
- this.currentHealth = Math.max(0, health);
- }
- public takeDamage(damage: number) {
- this.currentHealth = Math.max(0, this.currentHealth - damage);
-
- if (this.currentHealth <= 0) {
- this.triggerGameDefeat();
- }
- }
- public getCurrentState(): GameState {
- return this.currentState;
- }
- public restartGame() {
- this.currentState = GameState.PLAYING;
- this.gameStarted = false;
- this.gameStartTime = 0;
- this.gameEndTime = 0;
- this.currentHealth = this.initialHealth;
- this.totalEnemiesSpawned = 0;
- this.enemiesKilled = 0;
- this.currentWave = 1;
- this.currentWaveEnemyCount = 0;
- // 重置能量条
- this.energyPoints = 0;
- if (this.energyBar) {
- this.energyBar.progress = 0;
- }
- if (this.selectSkillUI) {
- this.selectSkillUI.active = false;
- }
-
- // 关闭胜利/失败界面,确保重新进入时是正常状态
- if (this.gameSuccessUI) {
- this.gameSuccessUI.active = false;
- }
- if (this.gameDefeatUI) {
- this.gameDefeatUI.active = false;
- }
-
- // 通知BlockManager游戏重置
- const blockMgrNode = find('Canvas/GameLevelUI/BlockController');
- const blockManager = blockMgrNode?.getComponent(BlockManager);
- if (blockManager) {
- blockManager.onGameReset?.();
- }
-
- // 清空关卡剩余敌人
- if (this.enemyController && this.enemyController.clearAllEnemies) {
- this.enemyController.clearAllEnemies();
- }
-
- // 重置墙体血量显示
- this.initWallHealthDisplay();
-
- // 初始化本局数据(金币45等)
- LevelSessionManager.inst.clear();
- LevelSessionManager.inst.initialize(
- this.saveDataManager.getCurrentLevel(),
- this.wallHealth
- );
- // 刷新方块金币显示(如果 BlockManager 已存在)
- if (blockManager) {
- blockManager.updateCoinDisplay?.();
- }
- }
- public isGameOver(): boolean {
- return this.currentState === GameState.SUCCESS || this.currentState === GameState.DEFEAT;
- }
- public forceGameSuccess() {
- this.triggerGameSuccess();
- }
- public forceGameDefeat() {
- this.triggerGameDefeat();
- }
- // === 获取EnemyController组件 ===
- public getEnemyController() {
- return this.enemyController;
- }
- // === 调试方法 ===
- public getEnemyStatus() {
- if (!this.enemyController) return;
-
- const currentCount = this.enemyController.getCurrentEnemyCount();
- const gameStarted = this.enemyController.isGameStarted();
-
- const activeEnemies = this.enemyController.getActiveEnemies?.() || [];
-
- if (activeEnemies.length > 0) {
- for (let index = 0; index < activeEnemies.length; index++) {
- const enemy = activeEnemies[index];
- if (enemy?.isValid) {
- // 查看敌人状态
- } else {
- // 无效敌人节点
- }
- }
- }
- }
-
- public forceStartEnemySpawning() {
- if (this.enemyController) {
- this.enemyController.startGame();
- }
- }
-
- public setTotalEnemiesSpawned(count: number) {
- this.totalEnemiesSpawned = count;
- }
-
- public testEnemyDetection() {
- // 测试敌人检测功能
- this.getEnemyStatus();
- }
-
- public testComponentAccess() {
- // 测试组件访问
- if (this.enemyController) {
- // 组件访问正常
- }
- }
-
- public testEnemyAttackWall() {
- if (!this.enemyController) return;
-
- const currentHealth = this.enemyController.getCurrentWallHealth();
- const testDamage = 50;
-
- this.enemyController.damageWall(testDamage);
-
- const newHealth = this.enemyController.getCurrentWallHealth();
- }
- onDestroy() {
- // 清理按钮事件监听
- if (this.gameSuccessUI) {
- const buttons = this.gameSuccessUI.getComponentsInChildren(Button);
- buttons.forEach(button => {
- button.node.off(Button.EventType.CLICK);
- });
- }
- if (this.gameDefeatUI) {
- const buttons = this.gameDefeatUI.getComponentsInChildren(Button);
- buttons.forEach(button => {
- button.node.off(Button.EventType.CLICK);
- });
- }
- }
- // === 加载当前关卡配置 ===
- public async loadCurrentLevelConfig() {
- if (!this.saveDataManager || !this.levelConfigManager) return;
-
- const currentLevel = this.saveDataManager.getCurrentLevel();
-
- try {
- const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
- if (levelConfig) {
- this.applyLevelConfig(levelConfig);
- } else {
- console.warn(`关卡 ${currentLevel} 配置加载失败`);
- }
- } catch (error) {
- console.error(`关卡 ${currentLevel} 配置加载错误:`, error);
- }
- }
-
- private applyLevelConfig(levelConfig: any) {
- // 应用关卡配置
-
- // 如果有武器配置,应用武器
- if (levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
- // 应用武器配置
- }
-
- // 如果有波次配置,设置敌人波次
- if (levelConfig.waves && Array.isArray(levelConfig.waves)) {
- this.levelWaves = levelConfig.waves;
- this.currentWave = 1;
-
- // 计算本关卡总敌人数
- this.levelTotalEnemies = 0;
- for (const wave of this.levelWaves) {
- for (const enemy of wave.enemies || []) {
- this.levelTotalEnemies += enemy.count || 0;
- }
- }
-
- // 通知 EnemyController 初始化第一波数据及 UI
- if (this.enemyController) {
- const totalWaves = this.levelWaves.length;
- const firstWaveEnemies = this.levelWaves.length > 0 && this.levelWaves[0].enemies ?
- this.levelWaves[0].enemies.reduce((t: number, g: any) => t + (g.count || 0), 0) : 0;
- this.enemyController.startWave(1, totalWaves, firstWaveEnemies);
- // 同步 GameManager 当前波敌人数,避免剩余敌人数计算出错
- this.setCurrentWave(1, firstWaveEnemies);
- }
- }
- }
- // === 获取当前关卡信息 ===
- public async getCurrentLevelInfo() {
- const currentLevel = this.saveDataManager ?
- this.saveDataManager.getCurrentLevel() :
- (this.levelManager ? this.levelManager.getCurrentLevel() : 1);
-
- const levelProgress = this.saveDataManager ?
- this.saveDataManager.getLevelProgress(currentLevel) : null;
-
- const levelData = this.levelManager ?
- this.levelManager.getLevelData(currentLevel) : null;
-
- const levelConfig = await this.loadCurrentLevelConfig();
- return {
- level: currentLevel,
- maxUnlockedLevel: this.saveDataManager ?
- this.saveDataManager.getMaxUnlockedLevel() :
- (this.levelManager ? this.levelManager.getMaxUnlockedLevel() : 1),
- progress: levelProgress,
- data: levelData,
- config: levelConfig,
- playerData: this.saveDataManager ? {
- coins: this.saveDataManager.getCoins(),
- diamonds: this.saveDataManager.getDiamonds(),
- gems: this.saveDataManager.getGems(),
- playerLevel: this.saveDataManager.getPlayerLevel()
- } : null
- };
- }
- // === 更新波次显示 ===
- private updateWaveDisplay() {
- // UI 更新交由 EnemyController 处理
- }
- // === 更新敌人数量显示 ===
- private updateEnemyCountDisplay() {
- // UI 更新交由 EnemyController 处理
- }
- // === 设置当前波次 ===
- public setCurrentWave(wave: number, enemyCount: number = 0) {
- this.currentWave = wave;
- this.currentWaveEnemyCount = 0; // 重置当前击杀数
- this.currentWaveTotalEnemies = enemyCount; // 设置该波次总敌人数
- if (this.enemyController) {
- const totalWaves = this.levelWaves?.length || 1;
- this.enemyController.startWave(wave, totalWaves, enemyCount);
- }
- }
- // === 更新当前波次敌人数量 ===
- public updateCurrentWaveEnemyCount(count: number) {
- this.currentWaveEnemyCount = count;
- }
- // === 获取当前波次 ===
- public getCurrentWave(): number {
- return this.currentWave;
- }
- // === 获取当前波次敌人数量 ===
- public getCurrentWaveEnemyCount(): number {
- return this.currentWaveEnemyCount;
- }
- // === 获取当前波次总敌人数量 ===
- public getCurrentWaveTotalEnemies(): number {
- return this.currentWaveTotalEnemies;
- }
- // === 进入下一波 ===
- public nextWave() {
- this.currentWave++;
- // 根据关卡配置获取下一波敌人数
- let enemyTotal = 0;
- if (this.levelWaves && this.levelWaves.length >= this.currentWave) {
- const waveCfg = this.levelWaves[this.currentWave - 1];
- if (waveCfg && waveCfg.enemies) {
- enemyTotal = waveCfg.enemies.reduce((t: number, g: any) => t + (g.count || 0), 0);
- }
- }
- this.setCurrentWave(this.currentWave, enemyTotal);
- }
- /** 显示下一波提示并在短暂延迟后开始下一波 */
- private showNextWavePrompt() {
- this.openBlockSelectionUIForNextWave(); // 只打开布阵,不弹 StartWaveUI
- }
- /** 敌人被消灭时由 EnemyController 调用 */
- public onEnemyKilled() {
- this.enemiesKilled++;
- // 当前波击杀 +1
- this.currentWaveEnemyCount++;
- // 增加能量点
- this.incrementEnergy();
-
- const remaining = this.currentWaveTotalEnemies - this.currentWaveEnemyCount;
- if (remaining <= 0) {
- // 当前波结束
- if (this.currentWave < (this.levelWaves?.length || 1)) {
- // 还有下一波,显示提示
- this.showNextWavePrompt();
- } else {
- // 最后一波也结束
- this.triggerGameSuccess();
- }
- }
- }
- /** 每击杀敌人调用,能量 +1,并更新进度条。满值时弹出技能选择界面 */
- private incrementEnergy() {
- this.energyPoints = Math.min(this.energyPoints + 1, this.ENERGY_MAX);
- this.updateEnergyBar();
- if (this.energyPoints >= this.ENERGY_MAX) {
- this.onEnergyFull();
- }
- }
- /** 更新能量条显示 */
- private updateEnergyBar() {
- if (this.energyBar) {
- this.energyBar.progress = this.energyPoints / this.ENERGY_MAX;
- }
- }
- /** 能量满时触发 */
- private onEnergyFull() {
- if (this.selectSkillUI && !this.selectSkillUI.active) {
- // 暂停游戏后再弹出 UI
- this.pauseGame();
- this.selectSkillUI.active = true;
- }
- }
- /** 供外部调用:重置能量值并刷新显示 */
- public resetEnergy() {
- this.energyPoints = 0;
- this.updateEnergyBar();
- }
- /* ========= 墙体血量 / 等级相关 ========= */
- private wallHpMap: Record<number, number> = {
- 1: 100,
- 2: 1000,
- 3: 1200,
- 4: 1500,
- 5: 2000
- };
- /** 根据等级获取墙体血量 */
- public getWallHealthByLevel(level: number): number {
- return this.wallHpMap[level] || (100 + (level - 1) * 200);
- }
- /** 获取当前墙壁等级 */
- public getCurrentWallLevel(): number {
- return this.saveDataManager?.getPlayerData().playerLevel || 1;
- }
- /** 获取当前墙体血量 */
- public getCurrentWallHealth(): number {
- return this.saveDataManager?.getPlayerData().wallBaseHealth || this.getWallHealthByLevel(1);
- }
- /** 升级墙体等级,返回升级后信息,失败返回null */
- public upgradeWallLevel(): { currentLevel: number; currentHp: number; nextLevel: number; nextHp: number } | null {
- if (!this.saveDataManager) return null;
- const pd = this.saveDataManager.getPlayerData();
- const curLvl = pd.playerLevel || 1;
- if (curLvl >= 5) return null; // 已达最高级
- const newLvl = curLvl + 1;
- const newHp = this.getWallHealthByLevel(newLvl);
- pd.playerLevel = newLvl;
- pd.wallBaseHealth = newHp;
- this.saveDataManager.savePlayerData(true);
- // 更新内存中的数值
- this.wallHealth = newHp;
- if (this.enemyController) {
- this.enemyController.wallHealth = newHp;
- this.enemyController.updateWallHealthDisplay?.();
- }
- return {
- currentLevel: newLvl,
- currentHp: newHp,
- nextLevel: newLvl + 1,
- nextHp: this.getWallHealthByLevel(newLvl + 1)
- };
- }
- private openBlockSelectionUIForNextWave() {
- if (this.blockSelectionUI) this.blockSelectionUI.active = true;
- const grid = find('Canvas/GameLevelUI/GameArea/GridContainer');
- if (grid) grid.active = true;
- this.preparingNextWave = true;
- this.enemyController.pauseSpawning(); // 保险
- }
- }
|