| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223 |
- import { _decorator, Component, Node, Prefab, instantiate, Vec3, find, director, Canvas, UITransform, Button, Label, 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';
- 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;
- @property({
- type: Node,
- tooltip: '波次显示节点 (WaveNumber)'
- })
- public waveNumberNode: Node = null;
- @property({
- type: Node,
- tooltip: '敌人数量显示节点 (EnemyNumber)'
- })
- public enemyNumberNode: Node = null;
- // === 游戏配置属性 ===
- @property({
- tooltip: '墙体初始血量'
- })
- public wallHealth: number = 1200;
- @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 waveNumberLabel: Label = null;
- private enemyNumberLabel: 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
- };
- start() {
- // 初始化物理系统
- this.initPhysicsSystem();
-
- // 初始化管理器
- this.initializeManagers();
-
- // 计算游戏区域边界
- 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();
- }
- // === 游戏状态初始化 ===
- 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显示
- this.updateWaveDisplay();
- this.updateEnemyCountDisplay();
- }
- // === 计算游戏区域边界 ===
- 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);
- }
-
- // 查找波次显示节点
- if (!this.waveNumberNode) {
- this.waveNumberNode = find('Canvas/GameLevelUI/WaveInfo/WaveNumber');
- }
-
- if (this.waveNumberNode) {
- this.waveNumberLabel = this.waveNumberNode.getComponent(Label);
- }
-
- // 查找敌人数量显示节点
- if (!this.enemyNumberNode) {
- this.enemyNumberNode = find('Canvas/GameLevelUI/EnemyNode/EnemyNumber');
- }
-
- if (this.enemyNumberNode) {
- this.enemyNumberLabel = this.enemyNumberNode.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;
- }
- }
- // === 查找敌人控制器 ===
- 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();
- }
-
- // 通知敌人控制器墙体血量节点
- if (this.enemyController && this.heartLabelNode) {
- this.updateEnemyControllerWallHealth(this.heartLabelNode);
- }
- }
- // === 更新EnemyController的墙体血量 ===
- private updateEnemyControllerWallHealth(wallHealthNode: Node) {
- if (this.enemyController) {
- // 同步血量值
- this.enemyController.wallHealth = this.wallHealth;
-
- // 设置血量显示节点
- const heartLabelNode = find('Canvas/GameLevelUI/HeartNode/HeartLabeld');
- if (heartLabelNode) {
- this.enemyController.wallHealthNode = heartLabelNode;
- }
-
- // 让EnemyController更新显示
- this.enemyController.updateWallHealthDisplay();
- }
- }
- // === 设置敌人控制器 ===
- 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;
- }
- // 更新当前敌人数量(用于波次UI显示等,不影响胜利逻辑)
- if (this.enemyController) {
- const currentEnemyCount = this.enemyController.getCurrentEnemyCount ?
- this.enemyController.getCurrentEnemyCount() : 0;
- this.updateCurrentWaveEnemyCount(currentEnemyCount);
- }
- // 检查是否全部击败
- 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();
- }
- }
- // === 恢复游戏 ===
- private 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() {
- console.log('处理游戏失败逻辑');
- this.gameEndTime = Date.now();
-
- // 记录游戏失败到存档
- if (this.saveDataManager) {
- const currentLevel = this.saveDataManager.getCurrentLevel();
- this.saveDataManager.failLevel(currentLevel);
-
- // 更新统计数据
- this.saveDataManager.updateStatistic('totalTimePlayed', this.getGameDuration());
- }
- }
- // === 游戏成功回调 ===
- private onGameSuccess() {
- console.log('处理游戏成功逻辑');
- 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`);
- }
-
- console.log(`🎉 关卡奖励:金币 +${totalCoins},健康奖励 +${healthBonus},时间奖励 +${timeBonus}`);
- }
- // === 处理关卡完成 ===
- 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);
-
- console.log(`🏆 关卡 ${currentLevel} 完成!得分: ${finalScore}, 星级: ${finalStars}, 用时: ${gameTime}秒`);
-
- // 兼容原有的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.onNextLevelClick, 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 async onNextLevelClick() {
- if (!this.saveDataManager) {
- console.warn('SaveDataManager 未初始化');
- return;
- }
- const currentLevel = this.saveDataManager.getCurrentLevel();
- const nextLevel = currentLevel + 1;
- if (!this.saveDataManager.isLevelUnlocked(nextLevel)) {
- console.log('下一关卡尚未解锁');
- return;
- }
- // 设置当前关卡为下一关
- this.saveDataManager.getPlayerData().currentLevel = nextLevel;
- this.saveDataManager.savePlayerData();
- // 隐藏结算面板
- if (this.gameSuccessUI) this.gameSuccessUI.active = false;
- if (this.gameDefeatUI) this.gameDefeatUI.active = false;
- // 停止并清理敌人
- if (this.enemyController) {
- this.enemyController.stopGame();
- this.enemyController.clearAllEnemies();
- }
- // 重置方块、子弹等(通过 BlockManager)
- const blockManager = find('Canvas/GameLevelUI')?.getComponent('BlockManager');
- if (blockManager) {
- if (blockManager['clearBlocks']) blockManager['clearBlocks']();
- if (blockManager['onGameReset']) blockManager['onGameReset']();
- }
- // 重置内部状态
- this.restartGame();
- // 加载并应用新关卡配置
- await this.loadCurrentLevelConfig();
- // 直接开始游戏(如果需要再次确认,可移除此行)
- this.startGame();
- }
- private onRestartClick() {
- this.restartCurrentLevel();
- }
- private onMainMenuClick() {
- // 保存数据
- if (this.saveDataManager) {
- this.saveDataManager.savePlayerData(true);
- }
- // 隐藏结算面板
- if (this.gameSuccessUI) this.gameSuccessUI.active = false;
- if (this.gameDefeatUI) this.gameDefeatUI.active = false;
- // 停止并清理游戏内容
- if (this.enemyController) {
- this.enemyController.stopGame();
- this.enemyController.clearAllEnemies();
- }
- this.restartGame();
- // UI 切换:隐藏关卡界面,显示主界面
- const mainUI = find('Canvas/MainUI');
- const gameLevelUI = find('Canvas/GameLevelUI');
- if (mainUI) mainUI.active = true;
- if (gameLevelUI) gameLevelUI.active = false;
- console.log('返回主界面');
- }
- private onShopClick() {
- console.log('打开商店');
- }
- private onReviveClick() {
- // 消费钻石复活
- if (this.saveDataManager) {
- const reviveCost = 10; // 复活需要10钻石
- if (this.saveDataManager.spendDiamonds(reviveCost)) {
- this.revivePlayer();
- console.log(`💎 消费 ${reviveCost} 钻石复活`);
- } else {
- console.log('钻石不足,无法复活');
- }
- }
- }
- // === 复活玩家 ===
- private revivePlayer() {
- this.setHealth(50);
- this.restartGame();
- }
- // === 重新开始当前关卡 ===
- private restartCurrentLevel() {
- this.restartGame();
- }
- // === 原GameManager方法 ===
- public onConfirmButtonClicked() {
- if (this.blockSelectionUI) {
- this.blockSelectionUI.active = false;
-
- 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() {
- this.gameStarted = true;
- this.gameStartTime = Date.now();
- this.gameEndTime = 0;
- this.currentState = GameState.PLAYING;
-
- // 通知BlockManager游戏开始
- const blockManager = find('Canvas/GameLevelUI')?.getComponent('BlockManager');
- if (blockManager && blockManager['onGameStart']) {
- blockManager['onGameStart']();
- }
-
- this.spawnBall();
-
- console.log('🎮 游戏开始!');
- if (this.enemyController) {
- this.enemyController.startGame();
- }
- }
- private spawnBall() {
- console.log('🎯 === GameManager: 启动小球 ===');
-
- if (!this.ballController) {
- console.error('❌ BallController 节点未设置');
- return;
- }
- // 获取BallController组件
- const ballControllerComp = this.ballController.getComponent('BallController') as any;
- if (ballControllerComp) {
- console.log('✅ 找到BallController组件,启动小球...');
- // 调用startBall方法而不是initialize,确保小球在确定按钮点击后才开始运动
- ballControllerComp.startBall();
- console.log('🚀 小球启动完成');
- } else {
- console.error('❌ 找不到BallController组件');
- }
-
- console.log('🎯 === GameManager: 小球启动流程完成 ===');
- }
- 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;
-
- // 通知BlockManager游戏重置
- const blockManager = find('Canvas/GameLevelUI')?.getComponent('BlockManager');
- if (blockManager && blockManager['onGameReset']) {
- blockManager['onGameReset']();
- }
- }
- 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 ?
- this.enemyController.getCurrentEnemyCount() : 0;
- const gameStarted = this.enemyController.isGameStarted();
- console.log('=== 敌人状态调试信息 ===');
- console.log(`敌人生成已开始: ${this.enemySpawningStarted}`);
- console.log(`当前敌人数量: ${currentCount}`);
- console.log(`曾生成最大敌人数: ${this.totalEnemiesSpawned}`);
- console.log(`EnemyController游戏已开始: ${gameStarted}`);
- console.log(`GameManager游戏状态: ${this.currentState}`);
- console.log(`GameManager游戏已开始: ${this.gameStarted}`);
- console.log(`当前血量: ${this.currentHealth}`);
-
- // 显示活跃敌人的详细信息
- if (this.enemyController.getActiveEnemies) {
- const activeEnemies = this.enemyController.getActiveEnemies();
- console.log(`活跃敌人列表 (${activeEnemies.length}个):`);
- activeEnemies.forEach((enemy, index) => {
- if (enemy && enemy.isValid) {
- console.log(` ${index + 1}. ${enemy.name} - 位置: (${enemy.position.x.toFixed(1)}, ${enemy.position.y.toFixed(1)})`);
- } else {
- console.log(` ${index + 1}. 无效敌人节点`);
- }
- });
- }
- }
- public forceStartEnemySpawning() {
- this.enemySpawningStarted = true;
- }
- public setTotalEnemiesSpawned(count: number) {
- this.totalEnemiesSpawned = count;
- }
- // === 测试方法 ===
- public testEnemyDetection() {
- const result = this.checkAllEnemiesDefeated();
- this.getEnemyStatus();
- return result;
- }
- // 测试组件获取是否正常
- public testComponentAccess() {
- console.log('=== 测试组件访问 ===');
-
- if (this.enemyController) {
- console.log('✅ EnemyController 访问正常');
- console.log(`当前敌人数量: ${this.enemyController.getCurrentEnemyCount()}`);
- console.log(`游戏是否开始: ${this.enemyController.isGameStarted()}`);
- } else {
- console.log('❌ EnemyController 未找到');
- }
-
- console.log('组件测试完成');
- }
- // === 测试敌人攻击 ===
- public testEnemyAttackWall() {
- console.log('=== GameManager: 测试敌人攻击墙体 ===');
-
- if (this.enemyController) {
- console.log(`攻击前墙体血量: ${this.enemyController.getCurrentWallHealth()}`);
-
- // 测试EnemyController的攻击功能
- const newHealth = this.enemyController.testEnemyAttack();
- console.log(`攻击后墙体血量: ${newHealth}`);
-
- // 强制所有敌人攻击
- this.enemyController.forceEnemyAttack();
-
- return newHealth;
- } else {
- console.error('EnemyController未找到');
- return -1;
- }
- }
- 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.levelConfigManager) {
- return null;
- }
- try {
- // 优先使用存档系统的关卡信息
- const currentLevel = this.saveDataManager ?
- this.saveDataManager.getCurrentLevel() :
- (this.levelManager ? this.levelManager.getCurrentLevel() : 1);
-
- console.log(`加载关卡 ${currentLevel} 配置`);
-
- const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
-
- if (levelConfig) {
- console.log(`关卡 ${currentLevel} 配置加载成功:`, levelConfig);
- this.applyLevelConfig(levelConfig);
- return levelConfig;
- } else {
- console.warn(`关卡 ${currentLevel} 的配置文件不存在`);
- return null;
- }
- } catch (error) {
- console.error('加载关卡配置失败:', error);
- return null;
- }
- }
- // === 应用关卡配置 ===
- private applyLevelConfig(levelConfig: any) {
- if (!levelConfig) return;
- // 应用关卡设置
- if (levelConfig.settings) {
- const settings = levelConfig.settings;
-
- if (settings.initialHealth !== undefined) {
- this.wallHealth = settings.initialHealth;
- this.initialHealth = settings.initialHealth;
- this.currentHealth = settings.initialHealth;
- }
-
- if (settings.checkInterval !== undefined) {
- this.checkInterval = settings.checkInterval;
- }
- }
- // 记录武器配置信息
- if (levelConfig.weapons) {
- console.log('关卡武器配置:', levelConfig.weapons);
- }
- // 记录敌人波次配置信息并初始化第一波
- if (levelConfig.waves && levelConfig.waves.length > 0) {
- this.levelWaves = levelConfig.waves;
- console.log('关卡敌人波次配置:', this.levelWaves);
- // 计算整关卡总敌人数
- this.levelTotalEnemies = this.levelWaves.reduce((levelTotal: number, wave: any) => {
- if (!wave || !wave.enemies) return levelTotal;
- const waveTotal = wave.enemies.reduce((t: number, g: any) => t + (g.count || 0), 0);
- return levelTotal + waveTotal;
- }, 0);
- console.log(`📊 本关卡共有敌人: ${this.levelTotalEnemies}`);
- // 初始化第一波
- const firstWave = this.levelWaves[0];
- if (firstWave && firstWave.enemies) {
- const totalEnemiesInFirstWave = firstWave.enemies.reduce((total: number, enemyGroup: any) => {
- return total + (enemyGroup.count || 0);
- }, 0);
- this.setCurrentWave(1, totalEnemiesInFirstWave);
- }
- }
- }
- // === 获取当前关卡信息 ===
- 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() {
- if (this.waveNumberLabel) {
- this.waveNumberLabel.string = this.currentWave.toString();
- }
- }
- // === 更新敌人数量显示 ===
- private updateEnemyCountDisplay() {
- if (this.enemyNumberLabel) {
- this.enemyNumberLabel.string = this.currentWaveTotalEnemies.toString();
- }
- }
- // === 设置当前波次 ===
- public setCurrentWave(wave: number, enemyCount: number = 0) {
- this.currentWave = wave;
- this.currentWaveEnemyCount = 0; // 重置当前敌人数量为0
- this.currentWaveTotalEnemies = enemyCount; // 设置该波次总敌人数
- this.updateWaveDisplay();
- this.updateEnemyCountDisplay();
- }
- // === 更新当前波次敌人数量 ===
- public updateCurrentWaveEnemyCount(count: number) {
- this.currentWaveEnemyCount = count;
- // 不应该修改总敌人数,总敌人数只在设置波次时确定
- // this.currentWaveTotalEnemies = count; // 移除这行
- // 敌人数量显示的是总数,不需要在这里更新
- // this.updateEnemyCountDisplay(); // 移除这行
- }
- // === 获取当前波次 ===
- 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);
- }
- /** 敌人被消灭时由 EnemyController 调用 */
- public onEnemyKilled() {
- this.enemiesKilled++;
- const remaining = Math.max(0, this.levelTotalEnemies - this.enemiesKilled);
- console.log(`⚔️ 已击杀: ${this.enemiesKilled}, 剩余敌人数量: ${remaining}`);
- // 如果需要在 UI 上实时显示剩余敌人数量,可在此赋值
- if (this.enemyNumberLabel) {
- this.enemyNumberLabel.string = remaining.toString();
- }
- }
- }
|