import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Color, Vec2, UITransform, find, Rect, Label, Size, Sprite, SpriteFrame, resources, Button, Collider2D, Material, tween } from 'cc'; import { ConfigManager, WeaponConfig } from '../Core/ConfigManager'; import { SaveDataManager } from '../LevelSystem/SaveDataManager'; import { LevelSessionManager } from '../Core/LevelSessionManager'; import { LevelConfigManager } from '../LevelSystem/LevelConfigManager'; import { BlockTag } from './BlockSelection/BlockTag'; import { SkillManager } from './SkillSelection/SkillManager'; import EventBus, { GameEvents } from '../Core/EventBus'; import { sp } from 'cc'; const { ccclass, property } = _decorator; @ccclass('BlockManager') export class BlockManager extends Component { // 预制体数组,存储5个预制体 @property([Prefab]) public blockPrefabs: Prefab[] = []; // 网格容器节点 @property({ type: Node, tooltip: '拖拽GridContainer节点到这里' }) public gridContainer: Node = null; // 方块容器节点(kuang) @property({ type: Node, tooltip: '拖拽kuang节点到这里' }) public kuangContainer: Node = null; // 金币标签节点 @property({ type: Node, tooltip: '拖拽CoinLabel节点到这里' }) public coinLabelNode: Node = null; // 已放置方块容器节点 @property({ type: Node, tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)' }) public placedBlocksContainer: Node = null; // 游戏是否已开始 public gameStarted: boolean = false; // 移除移动冷却:相关属性/逻辑已废弃 // SaveDataManager 单例 private saveDataManager: SaveDataManager = null; // 仅用于局外数据 private session: LevelSessionManager = null; // 方块价格标签映射 private blockPriceMap: Map = new Map(); // 已经生成的块 private blocks: Node[] = []; // 网格占用情况,用于控制台输出 private gridOccupationMap: number[][] = []; // 网格行数和列数 private readonly GRID_ROWS = 6; private readonly GRID_COLS = 11; // 是否已初始化网格信息 private gridInitialized = false; // 存储网格节点信息 private gridNodes: Node[][] = []; // 网格间距 private gridSpacing = 54; // 默认值,将在initGridInfo中动态计算 // 不参与占用的节点名称列表 private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price']; // 临时保存方块的原始占用格子 private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = []; // 方块原始位置(在kuang中的位置) public originalPositions: Map = new Map(); // 方块当前所在的区域 public blockLocations: Map = new Map(); // 配置管理器 private configManager: ConfigManager = null; // 关卡配置管理器 private levelConfigManager: LevelConfigManager = null; // 方块武器配置映射 private blockWeaponConfigs: Map = new Map(); // 预加载的武器配置数据 private preloadedWeaponsConfig: any = null; // 配置是否已预加载的标志 private isWeaponsConfigPreloaded: boolean = false; // 调试绘制相关 // 调试绘制功能已迁移到GameBlockSelection /** 冷却机制已废弃,方块随时可移动 */ // 清除所有冷却(游戏重置时调用) public clearAllCooldowns() { /* no-op */ } /** * 设置预加载的武器配置数据 * @param weaponsConfigData 从JsonAsset获取的武器配置数据 */ public setPreloadedWeaponsConfig(weaponsConfigData: any): void { console.log('[BlockManager] 接收到预加载的武器配置数据'); this.preloadedWeaponsConfig = weaponsConfigData; this.isWeaponsConfigPreloaded = true; // 验证配置数据结构 if (weaponsConfigData && weaponsConfigData.weapons && Array.isArray(weaponsConfigData.weapons)) { console.log(`[BlockManager] 武器配置验证成功,包含 ${weaponsConfigData.weapons.length} 个武器`); } else { console.warn('[BlockManager] 武器配置数据结构异常'); this.isWeaponsConfigPreloaded = false; } } /** * 获取预加载的武器配置,如果没有预加载则返回null */ private getPreloadedWeaponsConfig(): any { return this.isWeaponsConfigPreloaded ? this.preloadedWeaponsConfig : null; } // 获取当前关卡的武器列表 private async getCurrentLevelWeapons(): Promise { if (!this.levelConfigManager || !this.saveDataManager) { console.warn('关卡配置管理器或存档管理器未初始化,使用默认武器列表'); return []; } try { const currentLevel = this.saveDataManager.getCurrentLevel(); const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel); if (levelConfig && levelConfig.weapons && Array.isArray(levelConfig.weapons)) { console.log(`关卡 ${currentLevel} 配置的武器:`, levelConfig.weapons); return levelConfig.weapons; } else { console.warn(`关卡 ${currentLevel} 没有配置武器列表`); return []; } } catch (error) { console.error('获取当前关卡武器配置失败:', error); return []; } } // 根据武器名称获取武器配置 private getWeaponConfigByName(weaponName: string): WeaponConfig | null { // 优先使用预加载的配置数据 const preloadedConfig = this.getPreloadedWeaponsConfig(); if (preloadedConfig && preloadedConfig.weapons && Array.isArray(preloadedConfig.weapons)) { const weapon = preloadedConfig.weapons.find((w: any) => w.name === weaponName); if (weapon) { console.log(`[BlockManager] 从预加载配置中找到武器: ${weaponName}`); return weapon as WeaponConfig; } } // 如果预加载配置中没有找到,回退到ConfigManager if (!this.configManager) { console.warn(`[BlockManager] 武器配置未预加载且ConfigManager不可用,无法获取武器: ${weaponName}`); return null; } console.log(`[BlockManager] 从ConfigManager中查找武器: ${weaponName}`); const allWeapons = this.configManager.getAllWeapons(); return allWeapons.find(weapon => weapon.name === weaponName) || null; } // 设置事件监听器 private setupEventListeners() { const eventBus = EventBus.getInstance(); // 监听重置方块管理器事件 eventBus.on(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this); // 监听方块生成事件 eventBus.on(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this); // 移除GAME_START事件监听,避免与GameBlockSelection重复生成方块 // eventBus.on(GameEvents.GAME_START, this.onGameStartEvent, this); // 监听波次完成事件(每波结束后生成新方块) eventBus.on(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this); } // 处理重置方块管理器事件 private onResetBlockManagerEvent() { console.log('[BlockManager] 接收到重置方块管理器事件'); this.onGameReset(); } // 处理方块生成事件 private onGenerateBlocksEvent() { console.log('[BlockManager] 接收到方块生成事件'); this.generateRandomBlocksInKuang(); } // 处理游戏开始事件 - 已废弃,避免与GameBlockSelection重复生成方块 // private onGameStartEvent() { // console.log('[BlockManager] 接收到游戏开始事件,生成初始方块'); // this.generateRandomBlocksInKuang(); // } // 处理波次完成事件 private onWaveCompletedEvent() { console.log('[BlockManager] 接收到波次完成事件,生成新方块'); this.generateRandomBlocksInKuang(); } start() { console.log('[BlockManager] 开始初始化BlockManager'); // 获取配置管理器 this.configManager = ConfigManager.getInstance(); if (!this.configManager) { console.error('[BlockManager] 无法获取ConfigManager实例'); } else { console.log('[BlockManager] ConfigManager实例获取成功,配置加载状态:', this.configManager.isConfigLoaded()); } // 获取关卡配置管理器 this.levelConfigManager = LevelConfigManager.getInstance(); if (!this.levelConfigManager) { console.error('[BlockManager] 无法获取LevelConfigManager实例'); } else { console.log('[BlockManager] LevelConfigManager实例获取成功'); } // 如果没有指定GridContainer,尝试找到它 if (!this.gridContainer) { this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer'); if (!this.gridContainer) { console.error('找不到GridContainer节点'); return; } } // 如果没有指定kuangContainer,尝试找到它 if (!this.kuangContainer) { this.kuangContainer = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang'); if (!this.kuangContainer) { console.error('找不到kuang节点'); return; } } // 如果没有指定coinLabelNode,尝试找到它 if (!this.coinLabelNode) { this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel'); if (!this.coinLabelNode) { console.error('找不到CoinLabel节点'); return; } } // 如果没有指定placedBlocksContainer,尝试找到它 if (!this.placedBlocksContainer) { this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks'); } // 确保有PlacedBlocks节点用于存放已放置的方块 this.ensurePlacedBlocksNode(); // 获取数据管理器 this.saveDataManager = SaveDataManager.getInstance(); this.session = LevelSessionManager.inst; // 初始化玩家金币显示 this.updateCoinDisplay(); // 初始化网格信息 this.initGridInfo(); // 初始化网格占用情况 this.initGridOccupationMap(); // 设置事件监听器 this.setupEventListeners(); // 调试绘制功能已迁移到GameBlockSelection // 移除自动生成方块逻辑,改为事件触发 // 方块生成现在通过以下事件触发: // - GAME_START: 游戏开始时 // - WAVE_COMPLETED: 每波敌人消灭后 // - GENERATE_BLOCKS: 手动触发生成 } // 确保有PlacedBlocks节点 ensurePlacedBlocksNode() { // 如果已经通过拖拽设置了节点,直接使用 if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) { return; } // 尝试查找节点 this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks'); if (this.placedBlocksContainer) { return; } // 如果找不到,创建新节点 const gameLevelUI = find('Canvas/GameLevelUI'); if (!gameLevelUI) { console.error('找不到GameLevelUI节点,无法创建PlacedBlocks'); return; } this.placedBlocksContainer = new Node('PlacedBlocks'); gameLevelUI.addChild(this.placedBlocksContainer); if (!this.placedBlocksContainer.getComponent(UITransform)) { this.placedBlocksContainer.addComponent(UITransform); } console.log('已在GameLevelUI下创建PlacedBlocks节点'); } // 初始化网格信息 initGridInfo() { if (!this.gridContainer || this.gridInitialized) return; this.gridNodes = []; for (let row = 0; row < this.GRID_ROWS; row++) { this.gridNodes[row] = []; } for (let i = 0; i < this.gridContainer.children.length; i++) { const grid = this.gridContainer.children[i]; if (grid.name.startsWith('Grid_')) { const parts = grid.name.split('_'); if (parts.length === 3) { const row = parseInt(parts[1]); const col = parseInt(parts[2]); if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) { this.gridNodes[row][col] = grid; } } } } // 动态计算网格间距,适应不同分辨率 this.calculateGridSpacing(); this.gridInitialized = true; } // 动态计算网格间距 private calculateGridSpacing() { // 优先使用相邻行之间的距离计算间距 if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) { if (this.gridNodes[0][0] && this.gridNodes[1][0]) { const pos1 = this.gridNodes[0][0].position; const pos2 = this.gridNodes[1][0].position; this.gridSpacing = Math.abs(pos2.y - pos1.y); console.log(`动态计算网格间距(行间距): ${this.gridSpacing}`); return; } } // 如果行间距计算失败,尝试使用相邻列之间的距离 if (this.GRID_COLS > 1 && this.GRID_ROWS > 0) { if (this.gridNodes[0][0] && this.gridNodes[0][1]) { const pos1 = this.gridNodes[0][0].position; const pos2 = this.gridNodes[0][1].position; this.gridSpacing = Math.abs(pos2.x - pos1.x); console.log(`动态计算网格间距(列间距): ${this.gridSpacing}`); return; } } // 如果都失败了,保持默认值 console.warn(`无法动态计算网格间距,使用默认值: ${this.gridSpacing}`); } // 获取当前网格间距 public getGridSpacing(): number { return this.gridSpacing; } // 初始化网格占用情况 initGridOccupationMap() { this.gridOccupationMap = []; for (let row = 0; row < this.GRID_ROWS; row++) { const rowArray: number[] = []; for (let col = 0; col < this.GRID_COLS; col++) { rowArray.push(0); } this.gridOccupationMap.push(rowArray); } } // 在kuang下生成三个方块(基于关卡配置) private async generateRandomBlocksInKuang() { // 清除kuang区域中的旧方块,但不清除已放置在网格中的方块的标签 this.clearBlocks(); // 优先检查预加载的武器配置 if (this.isWeaponsConfigPreloaded) { const preloadedConfig = this.getPreloadedWeaponsConfig(); if (preloadedConfig && preloadedConfig.weapons && preloadedConfig.blockSizes) { console.log('[BlockManager] 使用预加载的武器配置生成方块'); // 直接使用预加载配置继续生成方块 // 跳过ConfigManager的等待逻辑 } else { console.warn('[BlockManager] 预加载配置不完整,回退到ConfigManager模式'); this.isWeaponsConfigPreloaded = false; } } // 如果没有预加载配置,检查ConfigManager if (!this.isWeaponsConfigPreloaded) { // 检查配置管理器是否可用 if (!this.configManager) { console.error('[BlockManager] ConfigManager实例未找到,延迟2秒后重试'); this.scheduleOnce(() => { this.generateRandomBlocksInKuang(); }, 2.0); return; } // 检查武器配置是否已加载(不需要等待所有配置完成) const weaponsConfigLoaded = !!this.configManager['weaponsConfig']; const blockSizesAvailable = weaponsConfigLoaded && !!this.configManager['weaponsConfig'].blockSizes; if (!weaponsConfigLoaded) { console.log('[BlockManager] 武器配置未加载完成,延迟2秒后重试生成方块'); console.log('[BlockManager] 整体配置状态:', this.configManager.isConfigLoaded()); this.scheduleOnce(() => { this.generateRandomBlocksInKuang(); }, 2.0); return; } if (!blockSizesAvailable) { console.warn('[BlockManager] 武器配置已加载但blockSizes缺失,延迟2秒后重试'); console.log('[BlockManager] weaponsConfig keys:', Object.keys(this.configManager['weaponsConfig'])); this.scheduleOnce(() => { this.generateRandomBlocksInKuang(); }, 2.0); return; } } console.log('[BlockManager] 配置已加载完成,开始生成方块'); if (this.blockPrefabs.length === 0) { console.error('没有可用的预制体'); return; } const kuangNode = this.kuangContainer; if (!kuangNode) { console.error('找不到kuang节点'); return; } const offsets = [ new Vec3(-200, 0, 0), new Vec3(0, 0, 0), new Vec3(200, 0, 0) ]; const dbNodes = [ kuangNode.getChildByName('db01'), kuangNode.getChildByName('db02'), kuangNode.getChildByName('db03') ]; // 获取当前关卡的武器配置列表 const levelWeapons = await this.getCurrentLevelWeapons(); for (let i = 0; i < 3; i++) { let weaponConfig: WeaponConfig | null = null; // 优先使用关卡配置的武器,确保符合关卡设计 if (levelWeapons.length > 0) { const randomWeaponName = levelWeapons[Math.floor(Math.random() * levelWeapons.length)]; weaponConfig = this.getWeaponConfigByName(randomWeaponName); if (!weaponConfig) { console.warn(`关卡配置的武器 "${randomWeaponName}" 在武器配置文件中未找到`); } } // 如果关卡没有配置武器或获取失败,使用随机武器 if (!weaponConfig) { weaponConfig = this.configManager.getRandomWeapon(); } // 最后的兜底处理 if (!weaponConfig) { console.warn('无法获取武器配置,使用默认武器'); // 尝试获取一个基础武器作为兜底 const allWeapons = this.configManager.getAllWeapons(); if (allWeapons.length > 0) { weaponConfig = allWeapons[0]; } } if (!weaponConfig) { console.error(`无法获取第 ${i + 1} 个武器配置`); continue; } // 基于武器配置选择合适的预制体 const prefab = this.selectPrefabForWeapon(weaponConfig); if (!prefab) { console.error(`无法为武器 ${weaponConfig.name} 选择合适的预制体`); continue; } const block = instantiate(prefab); kuangNode.addChild(block); block.position = offsets[i]; // 设置方块名称 block.name = `WeaponBlock_${weaponConfig.id}`; // 保存武器配置到方块 this.blockWeaponConfigs.set(block, weaponConfig); block['weaponConfig'] = weaponConfig; block['weaponId'] = weaponConfig.id; this.originalPositions.set(block, offsets[i].clone()); this.blockLocations.set(block, 'kuang'); this.blocks.push(block); if (dbNodes[i]) { const priceNode = dbNodes[i].getChildByName('Price'); if (priceNode) { this.blockPriceMap.set(block, priceNode); priceNode.active = true; // 根据武器配置和方块形状设置价格 this.setBlockPriceByWeaponConfig(block, priceNode); } this.associateDbNodeWithBlock(block, dbNodes[i]); } // 设置方块的武器外观 this.setupBlockWeaponVisual(block, weaponConfig); // 为新生成的方块添加标签 BlockTag.addTag(block); console.log(`[BlockManager] 为方块 ${block.name} 添加标签,UUID: ${block.uuid}`); } // 通过事件机制通知GameBlockSelection为新生成的方块设置拖拽事件 if (this.blocks.length > 0) { const eventBus = EventBus.getInstance(); eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.blocks.slice()); console.log(`[BlockManager] 发送方块拖拽事件设置请求,方块数量: ${this.blocks.length}`); } this.updateCoinDisplay(); } // 将db节点与方块关联 associateDbNodeWithBlock(block: Node, dbNode: Node) { block['dbNode'] = dbNode; block.on(Node.EventType.TRANSFORM_CHANGED, () => { if (dbNode && block.parent) { const location = this.blockLocations.get(block); if (location === 'grid') { dbNode.active = false; return; } // 检查方块是否正在被拖动,如果是则隐藏价格标签 if (block['isDragging']) { dbNode.active = false; return; } dbNode.active = true; const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position); const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos); dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z); } }); } // 更新金币显示 updateCoinDisplay() { if (this.coinLabelNode) { const label = this.coinLabelNode.getComponent(Label); if (label) { const coins = this.session.getCoins(); label.string = coins.toString(); } } } // 获取方块价格 getBlockPrice(block: Node): number { const priceNode = this.blockPriceMap.get(block); if (priceNode) { const label = priceNode.getComponent(Label); if (label) { const price = parseInt(label.string); if (!isNaN(price)) { return price; } } } return 50; } // 隐藏价格标签 hidePriceLabel(block: Node) { const priceNode = this.blockPriceMap.get(block); if (priceNode) { priceNode.active = false; } } // 显示价格标签 showPriceLabel(block: Node) { const priceNode = this.blockPriceMap.get(block); if (priceNode) { priceNode.active = true; } } // 扣除玩家金币 deductPlayerCoins(amount: number): boolean { const success = this.session.spendCoins(amount); if (success) { this.updateCoinDisplay(); } return success; } // 显示金币不足时的价格标签闪烁效果 showInsufficientCoinsEffect(block: Node) { const priceNode = this.blockPriceMap.get(block); if (!priceNode) { console.warn('[BlockManager] 找不到方块对应的价格标签'); return; } const label = priceNode.getComponent(Label); if (!label) { console.warn('[BlockManager] 价格节点缺少Label组件'); return; } // 保存原始颜色 const originalColor = label.color.clone(); // 设置红色 const redColor = new Color(255, 0, 0, 255); // 创建闪烁动画:变红 -> 恢复原色,重复3次,总时长2秒 tween(label) .to(0.2, { color: redColor }) .to(0.2, { color: originalColor }) .to(0.2, { color: redColor }) .to(0.2, { color: originalColor }) .to(0.2, { color: redColor }) .to(1.0, { color: originalColor }) .start(); // 发送显示Toast事件 EventBus.getInstance().emit(GameEvents.SHOW_TOAST, { message: '金币不足', duration: 2.0 }); console.log('[BlockManager] 显示金币不足效果'); } // 归还玩家金币 refundPlayerCoins(amount: number) { this.session.addCoins(amount); this.updateCoinDisplay(); } // 设置拖拽事件方法已迁移到GameBlockSelection // 清除临时保存的占用状态 clearTempStoredOccupiedGrids(block: Node) { const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block); if (index === -1) return; this.tempRemovedOccupiedGrids.splice(index, 1); } // 尝试将方块放置到网格中 tryPlaceBlockToGrid(block: Node): boolean { console.log(`[BlockManager] 尝试放置方块 ${block.name} 到网格`); if (!this.gridContainer || !this.gridInitialized) { console.log(`[BlockManager] 网格容器或网格未初始化`); return false; } let b1Node = block; if (block.name !== 'B1') { b1Node = block.getChildByName('B1'); if (!b1Node) { console.log(`[BlockManager] 方块 ${block.name} 没有B1子节点`); return false; } } const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position); const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos); console.log(`[BlockManager] B1世界坐标:`, b1WorldPos); console.log(`[BlockManager] 网格本地坐标:`, gridPos); const gridSize = this.gridContainer.getComponent(UITransform).contentSize; const halfWidth = gridSize.width / 2; const halfHeight = gridSize.height / 2; const tolerance = this.gridSpacing * 0.5; if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance || gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) { console.log(`[BlockManager] 方块超出网格边界`); return false; } const nearestGrid = this.findNearestGridNode(gridPos); if (!nearestGrid) { console.log(`[BlockManager] 找不到最近的网格节点`); return false; } console.log(`[BlockManager] 找到最近的网格节点: ${nearestGrid.name}`); return this.tryPlaceBlockToSpecificGrid(block, nearestGrid); } // 找到最近的网格节点 public findNearestGridNode(position: Vec3): Node { if (!this.gridContainer || !this.gridInitialized) return null; let nearestNode: Node = null; let minDistance = Number.MAX_VALUE; for (let row = 0; row < this.GRID_ROWS; row++) { for (let col = 0; col < this.GRID_COLS; col++) { const grid = this.gridNodes[row][col]; if (grid) { const distance = Vec3.distance(position, grid.position); if (distance < minDistance) { minDistance = distance; nearestNode = grid; } } } } if (minDistance > this.gridSpacing * 2) { return null; } return nearestNode; } // 尝试将方块放置到指定的网格节点 tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean { let b1Node = block; if (block.name !== 'B1') { b1Node = block.getChildByName('B1'); if (!b1Node) { return false; } } if (!this.canPlaceBlockAt(block, targetGrid)) { return false; } const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position); const targetWorldPos = gridCenterWorldPos.clone(); const b1LocalPos = b1Node.position.clone(); let rootTargetWorldPos; if (b1Node === block) { rootTargetWorldPos = targetWorldPos.clone(); } else { rootTargetWorldPos = new Vec3( targetWorldPos.x - b1LocalPos.x, targetWorldPos.y - b1LocalPos.y, targetWorldPos.z ); } const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos); block.position = rootTargetLocalPos; this.markOccupiedPositions(block, targetGrid); // 当方块从kuang区域拖到网格时,恢复植物图标的正常缩放 const weaponNode = block.getChildByName('Weapon'); if (weaponNode) { weaponNode.setScale(1.0, 1.0, 1.0); console.log(`[BlockManager] 方块 ${block.name} 放置到网格,植物图标缩放恢复为正常大小`); } return true; } // 检查方块是否可以放置在指定位置 canPlaceBlockAt(block: Node, targetGrid: Node): boolean { if (!this.gridInitialized) { console.log(`[BlockManager] 网格未初始化`); return false; } const targetRowCol = this.getGridRowCol(targetGrid); if (!targetRowCol) { console.log(`[BlockManager] 无法获取目标网格的行列信息`); return false; } const parts = this.getBlockParts(block); for (let i = 0; i < parts.length; i++) { const part = parts[i]; const row = targetRowCol.row - part.y; const col = targetRowCol.col + part.x; if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) { console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`); return false; } if (this.gridOccupationMap[row][col] === 1) { console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`); return false; } } return true; } // 获取网格行列索引 getGridRowCol(gridNode: Node): { row: number, col: number } | null { if (!gridNode || !gridNode.name.startsWith('Grid_')) return null; const parts = gridNode.name.split('_'); if (parts.length === 3) { const row = parseInt(parts[1]); const col = parseInt(parts[2]); if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) { return { row, col }; } } return null; } // 获取指定行列的网格世界坐标(用于调试绘制) public getGridWorldPosition(row: number, col: number): Vec3 | null { if (!this.gridInitialized || !this.gridNodes[row] || !this.gridNodes[row][col]) { return null; } const gridNode = this.gridNodes[row][col]; return this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(gridNode.position); } // 获取方块的所有部分节点及其相对坐标 getBlockParts(block: Node): { node: Node, x: number, y: number }[] { const parts: { node: Node, x: number, y: number }[] = []; // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点 const b1Node = block.getChildByName('B1'); if (b1Node) { // B1节点作为(0,0)位置 parts.push({ node: b1Node, x: 0, y: 0 }); this.findBlockParts(b1Node, parts, 0, 0); } else { // 没有B1节点,使用根节点 parts.push({ node: block, x: 0, y: 0 }); this.findBlockParts(block, parts, 0, 0); } return parts; } // 递归查找方块的所有部分 findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) { for (let i = 0; i < node.children.length; i++) { const child = node.children[i]; if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) { continue; } let x = parentX; let y = parentY; const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/); if (match) { x = parseInt(match[1]); y = parseInt(match[2]); result.push({ node: child, x, y }); } else if (child.name.startsWith('B')) { const relativeX = Math.round(child.position.x / this.gridSpacing); const relativeY = -Math.round(child.position.y / this.gridSpacing); x = parentX + relativeX; y = parentY + relativeY; result.push({ node: child, x, y }); } this.findBlockParts(child, result, x, y); } } // 标记方块占用的格子 public markOccupiedPositions(block: Node, targetGrid: Node) { if (!this.gridInitialized) return; const targetRowCol = this.getGridRowCol(targetGrid); if (!targetRowCol) return; const parts = this.getBlockParts(block); block['occupiedGrids'] = []; for (const part of parts) { const row = targetRowCol.row - part.y; const col = targetRowCol.col + part.x; if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) { this.gridOccupationMap[row][col] = 1; block['occupiedGrids'] = block['occupiedGrids'] || []; block['occupiedGrids'].push({ row, col }); } } } // 清除方块 clearBlocks() { console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length); const blocksToRemove = []; for (const block of this.blocks) { if (block.isValid) { const location = this.blockLocations.get(block); if (location === 'kuang') { blocksToRemove.push(block); } } } console.log('[BlockManager] 找到需要清理的kuang区域方块数量:', blocksToRemove.length); for (const block of blocksToRemove) { const dbNode = block['dbNode']; if (dbNode && dbNode.isValid) { block.off(Node.EventType.TRANSFORM_CHANGED); const kuangNode = this.kuangContainer; if (kuangNode) { const dbName = dbNode.name; if (!kuangNode.getChildByName(dbName)) { dbNode.parent = kuangNode; } } } const index = this.blocks.indexOf(block); if (index !== -1) { this.blocks.splice(index, 1); } this.originalPositions.delete(block); this.blockLocations.delete(block); this.blockPriceMap.delete(block); // 清理武器配置映射 this.blockWeaponConfigs.delete(block); console.log('[BlockManager] 销毁kuang区域方块:', block.name); block.destroy(); } console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length); } // 游戏开始时调用 onGameStart() { this.gameStarted = true; for (const block of this.blocks) { if (block.isValid) { const location = this.blockLocations.get(block); if (location === 'grid') { this.hidePriceLabel(block); const dbNode = block['dbNode']; if (dbNode) { dbNode.active = false; } this.moveBlockToPlacedBlocks(block); this.addLockedVisualHint(block); // 游戏开始后放置的方块移除标签,不能再放回kuang BlockTag.removeTag(block); } } } } // 游戏重置时调用 onGameReset() { console.log('[BlockManager] 游戏重置,清理所有状态'); console.log('[BlockManager] 重置前方块总数:', this.blocks.length); this.gameStarted = false; this.clearAllCooldowns(); // 清理已放置的方块 console.log('[BlockManager] 开始清理已放置的方块'); this.clearPlacedBlocks(); // 重置网格占用状态 console.log('[BlockManager] 开始重置网格占用状态'); this.resetGridOccupation(); // 清理kuang区域的方块 console.log('[BlockManager] 开始清理kuang区域的方块'); this.clearBlocks(); // 清理所有方块标签 console.log('[BlockManager] 开始清理所有方块标签'); BlockTag.clearAllTags(); console.log('[BlockManager] 清理后方块总数:', this.blocks.length); console.log('[BlockManager] 游戏重置完成 - 方块生成将由StartGame流程处理'); } // 清理已放置的方块 private clearPlacedBlocks() { if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) { console.log('[BlockManager] PlacedBlocks容器无效,跳过清理'); return; } console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`); // 清理PlacedBlocks容器中的所有方块 const placedBlocks = [...this.placedBlocksContainer.children]; let clearedCount = 0; for (const block of placedBlocks) { if (block && block.isValid) { // 从blocks数组中移除 const index = this.blocks.indexOf(block); if (index !== -1) { this.blocks.splice(index, 1); } // 清理相关映射 this.originalPositions.delete(block); this.blockLocations.delete(block); this.blockPriceMap.delete(block); this.blockWeaponConfigs.delete(block); console.log('[BlockManager] 销毁已放置方块:', block.name); // 销毁方块 block.destroy(); clearedCount++; } } console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`); } // 重置网格占用状态 public resetGridOccupation() { console.log('[BlockManager] 重置网格占用状态'); // 重新初始化网格占用地图 this.gridOccupationMap = []; for (let row = 0; row < this.GRID_ROWS; row++) { this.gridOccupationMap[row] = []; for (let col = 0; col < this.GRID_COLS; col++) { this.gridOccupationMap[row][col] = 0; } } // 清理临时存储的占用状态 this.tempRemovedOccupiedGrids = []; } // 添加视觉提示,表明方块已锁定 addLockedVisualHint(block: Node) { const children = block.children; for (let i = 0; i < children.length; i++) { const child = children[i]; if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) { continue; } child.setScale(new Vec3(0.95, 0.95, 1)); } } // 将方块移动到PlacedBlocks节点下 moveBlockToPlacedBlocks(block: Node) { if (!this.placedBlocksContainer) { console.error('PlacedBlocks容器未设置'); return; } if (!this.placedBlocksContainer.isValid) { console.error('PlacedBlocks容器已失效'); return; } const worldPosition = new Vec3(); block.getWorldPosition(worldPosition); // 移除旧的触摸事件监听器 block.off(Node.EventType.TOUCH_START); block.off(Node.EventType.TOUCH_MOVE); block.off(Node.EventType.TOUCH_END); block.off(Node.EventType.TOUCH_CANCEL); block.removeFromParent(); this.placedBlocksContainer.addChild(block); block.setWorldPosition(worldPosition); // 通过事件机制重新设置拖拽事件 const eventBus = EventBus.getInstance(); eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]); console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`); } // 根据武器配置选择合适的预制体 private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null { if (this.blockPrefabs.length === 0) { return null; } // 获取所有可用的方块形状配置 console.log('[BlockManager] 尝试获取方块形状配置...'); let blockShapes = null; // 优先使用预加载的配置 if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) { blockShapes = this.preloadedWeaponsConfig.blockSizes; console.log('[BlockManager] 使用预加载的方块形状配置'); } else { // 回退到ConfigManager blockShapes = this.configManager.getBlockShapes(); console.log('[BlockManager] 使用ConfigManager的方块形状配置'); } if (!blockShapes || blockShapes.length === 0) { console.warn('[BlockManager] 未找到匹配的形状配置,使用默认形状I'); const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length); return this.blockPrefabs[randomIndex]; } console.log(`[BlockManager] ✅ 成功获取${blockShapes.length}个方块形状配置`); // 随机选择一个方块形状 const randomShapeIndex = Math.floor(Math.random() * blockShapes.length); const targetShape = blockShapes[randomShapeIndex]; // 寻找与目标形状匹配的预制体 const matchingPrefab = this.findMatchingPrefab(targetShape); if (matchingPrefab) { console.log(`为武器 ${weaponConfig.name} 选择了匹配的预制体,形状: ${targetShape.name}`); return matchingPrefab; } // 如果没有找到匹配的预制体,使用随机预制体 console.warn(`没有找到匹配形状 ${targetShape.name} 的预制体,使用随机预制体`); const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length); return this.blockPrefabs[randomIndex]; } // 根据稀有度设置方块价格 private setBlockPriceByRarity(priceNode: Node, rarity: string) { const label = priceNode.getComponent(Label); if (!label) { return; } let basePrice: number; switch (rarity) { case 'common': basePrice = 10; break; case 'uncommon': basePrice = 20; break; case 'rare': basePrice = 50; break; case 'epic': basePrice = 100; break; case 'legendary': basePrice = 150; break; default: basePrice = 200; } // 应用便宜技能效果 const skillManager = SkillManager.getInstance(); let finalPrice = basePrice; if (skillManager) { const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units'); finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel)); } label.string = finalPrice.toString(); } // 根据武器配置和方块形状设置价格 private setBlockPriceByWeaponConfig(block: Node, priceNode: Node) { const label = priceNode.getComponent(Label); if (!label) { return; } // 获取方块的武器配置 const weaponConfig = this.getBlockWeaponConfig(block); if (!weaponConfig) { // 如果没有武器配置,使用原有的稀有度定价方式 this.setBlockPriceByRarity(priceNode, 'common'); return; } // 获取方块形状 const shapeId = this.getBlockShape(block); if (!shapeId) { // 如果无法获取形状,使用基础价格 this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common'); return; } // 从武器配置中获取局内金币花费配置 const inGameCostConfig = weaponConfig.inGameCostConfig; if (!inGameCostConfig) { // 如果没有局内金币配置,使用原有的稀有度定价方式 this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common'); return; } // 根据形状获取价格 let basePrice = inGameCostConfig.shapeCosts[shapeId]; if (basePrice === undefined) { // 如果没有找到对应形状的价格,使用基础价格 basePrice = inGameCostConfig.baseCost * this.getBlockGridCount(block); } // 应用便宜技能效果 const skillManager = SkillManager.getInstance(); let finalPrice = basePrice; if (skillManager) { const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units'); finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel)); } label.string = finalPrice.toString(); } // 计算方块占用的格子数量 private getBlockGridCount(block: Node): number { const parts = this.getBlockParts(block); return parts.length; } // 设置方块的武器外观 private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) { // 确保方块节点上也有 weaponConfig 属性 block['weaponConfig'] = weaponConfig; // 设置方块的稀有度颜色 this.setBlockRarityColor(block, weaponConfig.rarity || 'common'); // 加载武器图标 this.loadWeaponIcon(block, weaponConfig); } // 设置方块稀有度颜色 private setBlockRarityColor(block: Node, rarity: string) { this.applyBlockRarityColor(block, rarity); } // 公共方法:应用方块稀有度颜色(供外部调用) public applyBlockRarityColor(block: Node, rarity: string) { // Add null safety check for block if (!block || !block.isValid) { return; } const sprite = block.getComponent(Sprite); if (!sprite || !sprite.isValid) { return; } // 根据稀有度设置颜色 let color: Color; switch (rarity) { case 'common': color = new Color(255, 255, 255); // 白色 break; case 'uncommon': color = new Color(0, 255, 0); // 绿色 break; case 'rare': color = new Color(0, 100, 255); // 蓝色 break; case 'epic': color = new Color(160, 32, 240); // 紫色 break; case 'legendary': color = new Color(255, 165, 0); // 橙色 break; default: color = new Color(255, 255, 255); // 默认白色 } sprite.color = color; console.log(`[BlockManager] 设置方块稀有度颜色: ${rarity}`, color); } // 加载武器图标 private loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) { // 根据预制体结构:WeaponBlock -> B1 -> Weapon const b1Node = block.getChildByName('B1'); if (!b1Node) { console.warn('找不到B1节点'); return; } const weaponNode = b1Node.getChildByName('Weapon'); if (!weaponNode) { console.warn('找不到Weapon节点'); return; } const weaponSprite = weaponNode.getComponent(Sprite); if (!weaponSprite) { console.warn('Weapon节点上没有Sprite组件'); return; } // 获取武器配置中的图片路径 const spriteConfig = weaponConfig.visualConfig?.weaponSprites; if (!spriteConfig) { console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`); return; } // 获取方块的形状ID const blockShapeId = this.getBlockShape(block); // 根据方块形状选择合适的图片路径 let spritePath = null; if (blockShapeId && spriteConfig[blockShapeId]) { spritePath = spriteConfig[blockShapeId]; } else { // 如果没有找到对应形状的图片,使用备用顺序 spritePath = spriteConfig['I'] || spriteConfig['H-I'] || spriteConfig['L'] || spriteConfig['S'] || spriteConfig['D-T']; } if (!spritePath) { console.warn(`武器 ${weaponConfig.name} 没有可用的图片路径`); return; } // 正确的SpriteFrame子资源路径 const spriteFramePath = `${spritePath}/spriteFrame`; // 加载SpriteFrame子资源 resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => { if (err) { console.warn(`加载武器图片失败: ${spriteFramePath}`, err); return; } // Add comprehensive null safety checks before setting spriteFrame if (weaponSprite && weaponSprite.isValid && weaponNode && weaponNode.isValid && block && block.isValid && spriteFrame && spriteFrame.isValid) { weaponSprite.spriteFrame = spriteFrame; // 检查方块是否在kuang区域,如果是则缩放植物图标至0.45倍 const blockLocation = this.blockLocations.get(block); if (blockLocation === 'kuang') { weaponNode.setScale(0.45, 0.45, 1); console.log(`[BlockManager] 设置kuang区域植物图标缩放: 0.45倍`); } // 应用武器图标的位置偏移和旋转 this.rotateWeaponIconByShape(weaponNode, blockShapeId, weaponConfig.id); } }); } // 武器类型和方块形状组合的位置偏移配置(相对于方块中心的偏移量) private readonly WEAPON_SHAPE_POSITION_OFFSETS: { [weaponId: string]: { [shapeId: string]: { x: number, y: number } } } = { 'pea_shooter': { 'I': { x: 4, y: -3 }, // 毛豆射手竖条形状,轻微向下偏移 'H-I': { x: 0, y: 5 }, // 毛豆射手横条形状,居中 'L': { x: 1, y: -10 }, // 毛豆射手L型,轻微向左下偏移 'S': { x: 5, y: -1 }, // 毛豆射手S型,轻微向右下偏移 'D-T': { x: 4, y: -1 } // 毛豆射手倒T型,轻微向下偏移 }, 'sharp_carrot': { 'I': { x: 0, y: -1 }, // 尖胡萝卜竖条形状,轻微向下偏移 'H-I': { x: 0, y: 0 }, // 尖胡萝卜横条形状,居中 'L': { x: -1, y: -7 }, // 尖胡萝卜L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // 尖胡萝卜S型,轻微向右下偏移 'D-T': { x: 0, y: -1 } // 尖胡萝卜倒T型,轻微向下偏移 }, 'saw_grass': { 'I': { x: 0, y: -1 }, // 锯齿草竖条形状,轻微向下偏移 'H-I': { x: 0, y: 0 }, // 锯齿草横条形状,居中 'L': { x: -1, y: -1 }, // 锯齿草L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // 锯齿草S型,轻微向右下偏移 'D-T': { x: 0, y: -5 } // 锯齿草倒T型,轻微向下偏移 }, 'watermelon_bomb': { 'I': { x: 0, y: -1 }, // 西瓜炸弹竖条形状,轻微向下偏移 'H-I': { x: 0, y: 0 }, // 西瓜炸弹横条形状,居中 'L': { x: -1, y: -1 }, // 西瓜炸弹L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // 西瓜炸弹S型,轻微向右下偏移 'D-T': { x: 0, y: -7 } // 西瓜炸弹倒T型,轻微向下偏移 }, 'boomerang_plant': { 'I': { x: 0, y: -1 }, // 回旋镖植物竖条形状,轻微向下偏移 'H-I': { x: 0, y: 0 }, // 回旋镖植物横条形状,居中 'L': { x: -1, y: -8 }, // 回旋镖植物L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // 回旋镖植物S型,轻微向右下偏移 'D-T': { x: -10, y: -13 } // 回旋镖植物倒T型,轻微向下偏移 }, 'hot_pepper': { 'I': { x: 0, y: 5 }, // 辣椒竖条形状,轻微向下偏移 'H-I': { x: 0, y: 0 }, // 辣椒横条形状,居中 'L': { x: -1, y: -1 }, // 辣椒L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // 辣椒S型,轻微向右下偏移 'D-T': { x: 0, y: 0 } // 辣椒倒T型,轻微向下偏移 }, 'cactus_shotgun': { 'I': { x: 0, y: -1 }, // 仙人掌霰弹枪竖条形状,轻微向下偏移 'H-I': { x: 0, y: 0 }, // 仙人掌霰弹枪横条形状,居中 'L': { x: -1, y: -3 }, // 仙人掌霰弹枪L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // 仙人掌霰弹枪S型,轻微向右下偏移 'D-T': { x: 0, y: -1 } // 仙人掌霰弹枪倒T型,轻微向下偏移 }, 'okra_missile': { 'I': { x: -4, y:3 }, // 秋葵导弹竖条形状,轻微向下偏移 'H-I': { x: 0, y: -3 }, // 秋葵导弹横条形状,居中 'L': { x: -1, y: -9 }, // 秋葵导弹L型,轻微向左下偏移 'S': { x: -6, y: 0 }, // 秋葵导弹S型,轻微向右下偏移 'D-T': { x: -3, y: 3 } // 秋葵导弹倒T型,轻微向下偏移 }, 'mace_club': { 'I': { x: 0, y: -1 }, // 狼牙棒竖条形状,轻微向下偏移 'H-I': { x: 1, y: 0 }, // 狼牙棒横条形状,居中 'L': { x: -1, y: -1 }, // 狼牙棒L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // 狼牙棒S型,轻微向右下偏移 'D-T': { x: 0, y: -5 } // 狼牙棒倒T型,轻微向下偏移 } }; // 默认位置偏移配置(当武器类型未配置时使用) private readonly DEFAULT_SHAPE_POSITION_OFFSETS: { [key: string]: { x: number, y: number } } = { 'I': { x: 0, y: -1 }, // 竖条形状,轻微向下偏移 'H-I': { x: 0, y: 0 }, // 横I型,居中 'L': { x: -1, y: -1 }, // L型,轻微向左下偏移 'S': { x: 1, y: -1 }, // S型,轻微向右下偏移 'D-T': { x: 0, y: -1 } // 倒T型,轻微向下偏移 }; // 武器类型和方块形状组合的旋转角度配置 private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = { 'pea_shooter': { 'I': 0, // 毛豆射手竖条形状 'H-I': 90, // 毛豆射手横条形状 'L': 0, // 毛豆射手L型 'S': 0, // 毛豆射手S型 'D-T': 0 // 毛豆射手倒T型 }, 'sharp_carrot': { 'I': 0, // 尖胡萝卜竖条形状 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向 'L': -15, // 尖胡萝卜L型,轻微调整 'S': 15, // 尖胡萝卜S型,轻微调整 'D-T': 0 // 尖胡萝卜倒T型 }, 'saw_grass': { 'I': 0, // 锯齿草竖条形状 'H-I': 0, // 锯齿草横条形状 'L': -45, // 锯齿草L型,更大角度适配锯齿形状 'S': 30, // 锯齿草S型,适配锯齿弯曲 'D-T': 0 // 锯齿草倒T型 }, 'watermelon_bomb': { 'I': 0, // 西瓜炸弹竖条形状 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转 'L': 0, // 西瓜炸弹L型 'S': 0, // 西瓜炸弹S型 'D-T': 0 // 西瓜炸弹倒T型 }, 'boomerang_plant': { 'I': 0, // 回旋镖植物竖条形状 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向 'L': -30, // 回旋镖植物L型 'S': -10, // 回旋镖植物S型,适配回旋轨迹 'D-T': -80 // 回旋镖植物倒T型 }, 'hot_pepper': { 'I': 0, // 辣椒竖条形状 'H-I': 90, // 辣椒横条形状 'L': 0, // 辣椒L型 'S': 0, // 辣椒S型 'D-T': 0 // 辣椒倒T型 }, 'cactus_shotgun': { 'I': 0, // 仙人掌霰弹枪竖条形状 'H-I': 90, // 仙人掌霰弹枪横条形状 'L': -20, // 仙人掌霰弹枪L型 'S': 20, // 仙人掌霰弹枪S型 'D-T': 0 // 仙人掌霰弹枪倒T型 }, 'okra_missile': { 'I': 0, // 秋葵导弹竖条形状 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向 'L': -10, // 秋葵导弹L型 'S': 10, // 秋葵导弹S型 'D-T': 0 // 秋葵导弹倒T型 }, 'mace_club': { 'I': -45, // 狼牙棒竖条形状 'H-I': 0, // 狼牙棒横条形状 'L': -90, // 狼牙棒L型,适配棒状武器 'S': -90, // 狼牙棒S型 'D-T': 0 // 狼牙棒倒T型 } }; // 默认旋转角度配置(当武器类型未配置时使用) private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = { 'I': 0, // 竖条形状,保持原始方向 'H-I': 90, // 横I型,旋转90度适配水平方向 'L': -15, // L型,轻微左倾适配L形状的转角 'S': 15, // S型,轻微右倾适配S形状的弯曲 'D-T': 0 // 倒T型,保持原始方向 }; // 根据武器类型和方块形状调整武器图标位置和旋转 private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) { if (!weaponNode || !shapeId) return; let rotationAngle = 0; let positionOffset = { x: 0, y: 0 }; // 如果提供了武器ID,尝试获取特定武器的配置 if (weaponId && this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) { rotationAngle = this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0; positionOffset = this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]?.[shapeId] || { x: 0, y: 0 }; console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定配置: 旋转${rotationAngle}度, 偏移(${positionOffset.x}, ${positionOffset.y})`); } else { // 使用默认配置 rotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0; positionOffset = this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] || { x: 0, y: 0 }; console.log(`为形状 ${shapeId} 设置默认配置: 旋转${rotationAngle}度, 偏移(${positionOffset.x}, ${positionOffset.y})`); } // 应用旋转 weaponNode.setRotationFromEuler(0, 0, rotationAngle); // 应用位置偏移 const currentPos = weaponNode.position; weaponNode.setPosition(currentPos.x + positionOffset.x, currentPos.y + positionOffset.y, currentPos.z); } // 设置特定武器和形状的旋转角度 public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) { if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) { this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {}; } this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle; console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`); } // 设置默认形状的旋转角度 public setDefaultShapeRotationAngle(shapeId: string, angle: number) { this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle; console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`); } // 设置特定武器和形状的位置偏移 public setWeaponShapePositionOffset(weaponId: string, shapeId: string, offset: { x: number, y: number }) { if (!this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]) { this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId] = {}; } this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId][shapeId] = offset; console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的位置偏移为: (${offset.x}, ${offset.y})`); } // 设置默认形状的位置偏移 public setDefaultShapePositionOffset(shapeId: string, offset: { x: number, y: number }) { this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] = offset; console.log(`已更新默认形状 ${shapeId} 的位置偏移为: (${offset.x}, ${offset.y})`); } // 获取特定武器和形状的旋转角度 public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number { if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) { return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0; } return 0; } // 获取默认形状的旋转角度 public getDefaultShapeRotationAngle(shapeId: string): number { return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0; } // 获取特定武器和形状的位置偏移 public getWeaponShapePositionOffset(weaponId: string, shapeId: string): { x: number, y: number } { if (this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]) { return this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId][shapeId] || { x: 0, y: 0 }; } return { x: 0, y: 0 }; } // 获取默认形状的位置偏移 public getDefaultShapePositionOffset(shapeId: string): { x: number, y: number } { return this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] || { x: 0, y: 0 }; } // 同时设置特定武器和形状的位置偏移和旋转角度 public setWeaponShapeTransform(weaponId: string, shapeId: string, offset: { x: number, y: number }, angle: number) { this.setWeaponShapePositionOffset(weaponId, shapeId, offset); this.setWeaponShapeRotationAngle(weaponId, shapeId, angle); console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的完整变换: 偏移(${offset.x}, ${offset.y}), 旋转${angle}度`); } // 同时设置默认形状的位置偏移和旋转角度 public setDefaultShapeTransform(shapeId: string, offset: { x: number, y: number }, angle: number) { this.setDefaultShapePositionOffset(shapeId, offset); this.setDefaultShapeRotationAngle(shapeId, angle); console.log(`已更新默认形状 ${shapeId} 的完整变换: 偏移(${offset.x}, ${offset.y}), 旋转${angle}度`); } // 重新应用所有已放置方块的武器图标位置和旋转 public refreshAllWeaponIconRotations() { // 遍历所有已放置的方块 if (this.placedBlocksContainer) { this.placedBlocksContainer.children.forEach(block => { const weaponConfig = this.getBlockWeaponConfig(block); if (weaponConfig) { const b1Node = block.getChildByName('B1'); if (b1Node) { const weaponNode = b1Node.getChildByName('Weapon'); if (weaponNode) { const shapeId = this.getBlockShape(block); this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id); } } } }); } // 遍历kuang区域的方块 this.blocks.forEach(block => { const weaponConfig = this.getBlockWeaponConfig(block); if (weaponConfig) { const b1Node = block.getChildByName('B1'); if (b1Node) { const weaponNode = b1Node.getChildByName('Weapon'); if (weaponNode) { const shapeId = this.getBlockShape(block); this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id); } } } }); } // 根据方块获取武器配置 public getBlockWeaponConfig(block: Node): WeaponConfig | null { return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null; } // 获取方块的武器ID public getBlockWeaponId(block: Node): string | null { const weaponConfig = this.getBlockWeaponConfig(block); return weaponConfig ? weaponConfig.id : null; } // 获取方块的形状 public getBlockShape(block: Node): string | null { const weaponConfig = this.getBlockWeaponConfig(block); if (!weaponConfig) return null; // 从方块结构推断形状 return this.inferBlockShapeFromStructure(block); } // 获取方块的详细形状信息(包括形状ID和名称) public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null { const actualShape = this.extractShapeFromBlock(block); let blockShapes = null; // 优先使用预加载的配置 if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) { blockShapes = this.preloadedWeaponsConfig.blockSizes; } else { // 回退到ConfigManager blockShapes = this.configManager.getBlockShapes(); } if (!blockShapes) return null; // 寻找匹配的形状配置 for (const shapeConfig of blockShapes) { if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) { return { id: shapeConfig.id, name: shapeConfig.name, shape: shapeConfig.shape }; } } return null; } // 从方块结构推断形状 private inferBlockShapeFromStructure(block: Node): string { const actualShape = this.extractShapeFromBlock(block); console.log('[BlockManager] 提取的方块形状矩阵:', actualShape); let blockShapes = null; // 优先使用预加载的配置 if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) { blockShapes = this.preloadedWeaponsConfig.blockSizes; console.log('[BlockManager] 使用预加载的方块形状配置'); } else { // 回退到ConfigManager blockShapes = this.configManager.getBlockShapes(); console.log('[BlockManager] 使用ConfigManager的方块形状配置'); } if (!blockShapes || blockShapes.length === 0) { console.warn('[BlockManager] 无法获取方块形状配置,使用默认形状I'); console.warn('[BlockManager] 配置状态 - isConfigLoaded:', this.configManager.isConfigLoaded()); console.warn('[BlockManager] 配置状态 - weaponsConfig存在:', !!this.configManager['weaponsConfig']); console.warn('[BlockManager] 配置状态 - 预加载状态:', this.isWeaponsConfigPreloaded); if (this.configManager['weaponsConfig']) { console.warn('[BlockManager] 配置状态 - blockSizes存在:', !!this.configManager['weaponsConfig'].blockSizes); } return 'I'; } console.log(`[BlockManager] 开始匹配形状,共有${blockShapes.length}个配置形状`); // 寻找匹配的形状配置 for (const shapeConfig of blockShapes) { console.log(`[BlockManager] 尝试匹配形状: ${shapeConfig.id} (${shapeConfig.name})`); console.log(`[BlockManager] 配置形状矩阵:`, shapeConfig.shape); if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) { console.log(`[BlockManager] ✅ 识别方块形状: ${shapeConfig.id} (${shapeConfig.name})`); return shapeConfig.id; } } console.warn('[BlockManager] 未找到匹配的形状配置,使用默认形状I'); return 'I'; } // 寻找与目标形状匹配的预制体 private findMatchingPrefab(targetShape: any): Prefab | null { for (const prefab of this.blockPrefabs) { if (this.doesPrefabMatchShape(prefab, targetShape)) { return prefab; } } return null; } // 检查预制体是否匹配指定形状 private doesPrefabMatchShape(prefab: Prefab, targetShape: any): boolean { // 创建临时实例来检查形状 const tempBlock = instantiate(prefab); const parts = this.getBlockParts(tempBlock); const actualShape = this.extractShapeFromBlock(tempBlock); tempBlock.destroy(); // 比较形状矩阵 const matches = this.compareShapeMatrices(actualShape, targetShape.shape); return matches; } // 从方块实例中提取形状矩阵 private extractShapeFromBlock(block: Node): number[][] { const parts = this.getBlockParts(block); // 创建4x4矩阵 const matrix: number[][] = []; for (let i = 0; i < 4; i++) { matrix[i] = [0, 0, 0, 0]; } // 找到最小坐标作为偏移基准 let minX = 0, minY = 0; for (const part of parts) { minX = Math.min(minX, part.x); minY = Math.min(minY, part.y); } // 填充矩阵,将坐标标准化到从(0,0)开始 for (const part of parts) { const matrixX = part.x - minX; const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标 if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) { matrix[matrixY][matrixX] = 1; } } // 对矩阵进行上下翻转(交换第0行和第1行) const temp = matrix[0]; matrix[0] = matrix[1]; matrix[1] = temp; return matrix; } // 比较两个形状矩阵是否相同 private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean { if (matrix1.length !== matrix2.length) return false; for (let i = 0; i < matrix1.length; i++) { if (matrix1[i].length !== matrix2[i].length) return false; for (let j = 0; j < matrix1[i].length; j++) { if (matrix1[i][j] !== matrix2[i][j]) return false; } } return true; } // 检查两个方块是否可以合成(相同形状相同种类) private canMergeBlocks(block1: Node, block2: Node): boolean { // 检查稀有度 const rarity1 = this.getBlockRarity(block1); const rarity2 = this.getBlockRarity(block2); if (rarity1 !== rarity2) { console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`); return false; } // 检查武器ID(种类) const weaponId1 = this.getBlockWeaponId(block1); const weaponId2 = this.getBlockWeaponId(block2); if (weaponId1 !== weaponId2) { console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`); return false; } // 使用精确的形状矩阵比较 const shape1 = this.extractShapeFromBlock(block1); const shape2 = this.extractShapeFromBlock(block2); if (!this.compareShapeMatrices(shape1, shape2)) { console.log(`[BlockManager] 形状矩阵不匹配`); return false; } console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`); return true; } // 刷新方块 - 重新生成三个新的武器方块 public refreshBlocks() { // 移除PlacedBlocks容器中所有方块的标签 if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) { BlockTag.removeTagsInContainer(this.placedBlocksContainer); } // 保存已放置方块的占用信息 const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = []; if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) { for (let i = 0; i < this.placedBlocksContainer.children.length; i++) { const block = this.placedBlocksContainer.children[i]; const occupiedGrids = block['occupiedGrids']; if (occupiedGrids && occupiedGrids.length > 0) { placedBlocksOccupation.push({ block: block, occupiedGrids: [...occupiedGrids] }); } } } // 生成新的方块 this.generateRandomBlocksInKuang(); } // 检查是否有已放置的方块 public hasPlacedBlocks(): boolean { if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) { console.log('[BlockManager] PlacedBlocks容器无效'); return false; } const blockCount = this.placedBlocksContainer.children.length; console.log(`[BlockManager] 已放置方块数量: ${blockCount}`); // 检查容器中是否有子节点(方块) return blockCount > 0; } /* =================== 合成逻辑 =================== */ private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary']; /** 检查当前放置的方块能否与相同稀有度的方块合成 */ public async tryMergeBlock(block: Node) { try { const rarity = this.getBlockRarity(block); if (!rarity) return; // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块 if (!this.placedBlocksContainer) return; const blockBB = this.getWorldAABB(block); for (const other of this.placedBlocksContainer.children) { if (other === block) continue; // 使用新的合成检查方法 if (!this.canMergeBlocks(block, other)) continue; const otherBB = this.getWorldAABB(other); if (this.rectIntersects(blockBB, otherBB)) { // 找到合成目标 await this.performMerge(block, other, rarity); break; } } } catch (error) { console.error('[BlockManager] tryMergeBlock 发生错误:', error); // 合成失败不影响游戏继续,只记录错误 } } private async performMerge(target: Node, source: Node, rarity: string) { try { console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`); // 隐藏价格标签并处理 db 关联 this.hidePriceLabel(source); const srcDb = source['dbNode']; if (srcDb) srcDb.active = false; // 销毁被合并方块 source.destroy(); // 升级稀有度 const nextRarity = this.getNextRarity(rarity); if (nextRarity) { console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`); // 获取当前武器配置 const currentConfig = this.blockWeaponConfigs.get(target); if (currentConfig) { // 保存原始武器名称用于日志输出 const originalWeaponName = currentConfig.name; try { // 获取当前关卡允许的武器列表 const levelWeapons = await this.getCurrentLevelWeapons(); // 检查是否应该限制在关卡配置的武器范围内 if (levelWeapons.length > 0) { // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度 if (!levelWeapons.some(weapon => weapon === originalWeaponName)) { console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`); } // 无论如何,都只升级稀有度,不改变武器类型 const upgradedConfig = { ...currentConfig }; upgradedConfig.rarity = nextRarity; this.blockWeaponConfigs.set(target, upgradedConfig); // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用 (target as any)['weaponConfig'] = upgradedConfig; console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`); } else { // 如果没有关卡配置限制,正常升级稀有度 const upgradedConfig = { ...currentConfig }; upgradedConfig.rarity = nextRarity; this.blockWeaponConfigs.set(target, upgradedConfig); // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用 (target as any)['weaponConfig'] = upgradedConfig; console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`); } } catch (weaponError) { console.error('[BlockManager] 获取关卡武器配置失败:', weaponError); // 武器配置获取失败时,仍然升级稀有度 const upgradedConfig = { ...currentConfig }; upgradedConfig.rarity = nextRarity; this.blockWeaponConfigs.set(target, upgradedConfig); // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用 (target as any)['weaponConfig'] = upgradedConfig; console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`); } } // 更新方块颜色 this.setBlockRarityColor(target, nextRarity); } // 播放烟雾动画 const worldPos = new Vec3(); target.getWorldPosition(worldPos); this.spawnMergeSmoke(worldPos); // 递归检查是否还能继续合成 if (nextRarity) { await this.tryMergeBlock(target); } console.log(`[BlockManager] 合成完成`); } catch (error) { console.error('[BlockManager] performMerge 发生错误:', error); // 合成失败时重新抛出错误,让上层处理 throw error; } } private getBlockRarity(block: Node): string | null { const cfg = this.blockWeaponConfigs.get(block); if (cfg) return cfg.rarity; // fallback based on sprite color maybe return null; } private getNextRarity(rarity: string): string | null { const idx = this.rarityOrder.indexOf(rarity); if (idx === -1 || idx >= this.rarityOrder.length - 1) return null; return this.rarityOrder[idx + 1]; } private getWorldAABB(node: Node): Rect { const ui = node.getComponent(UITransform); if (!ui) return new Rect(); const pos = node.worldPosition; const width = ui.width; const height = ui.height; return new Rect(pos.x - width/2, pos.y - height/2, width, height); } private rectIntersects(a: Rect, b: Rect): boolean { return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y; } /** 生成烟雾特效 */ private spawnMergeSmoke(worldPos: Vec3) { const path = 'Animation/WeaponTx/tx0003/tx0003'; resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => { if (err || !sData) { console.warn('加载合成烟雾动画失败', err); return; } const node = new Node('MergeSmoke'); const skeleton = node.addComponent(sp.Skeleton); skeleton.skeletonData = sData; skeleton.premultipliedAlpha = false; skeleton.setAnimation(0, 'animation', false); skeleton.setCompleteListener(() => node.destroy()); const canvas = find('Canvas'); if (canvas) canvas.addChild(node); node.setWorldPosition(worldPos); }); } /** 在放置失败时尝试与现有方块进行合成 */ public tryMergeOnOverlap(draggedBlock: Node): boolean { if (!this.placedBlocksContainer) return false; const rarity = this.getBlockRarity(draggedBlock); if (!rarity) return false; const dragBB = this.getWorldAABB(draggedBlock); for (const target of this.placedBlocksContainer.children) { if (target === draggedBlock) continue; // 使用新的合成检查方法 if (!this.canMergeBlocks(draggedBlock, target)) continue; const targetBB = this.getWorldAABB(target); if (this.rectIntersects(dragBB, targetBB)) { // 执行合并:目标保留,拖拽方块销毁 this.performMerge(target, draggedBlock, rarity); return true; } } return false; } // 调试绘制功能已迁移到GameBlockSelection // 输出格子占用情况矩阵 public printGridOccupationMatrix() { console.log('[BlockManager] 格子占用情况de矩阵 (6行11列):'); for (let row = 0; row < this.GRID_ROWS; row++) { let rowStr = ''; for (let col = 0; col < this.GRID_COLS; col++) { rowStr += this.gridOccupationMap[row][col] + ' '; } console.log(`第${row + 1}行: ${rowStr.trim()}`); } } // 通过GameBlockSelection刷新方块占用情况 onDestroy() { // 调试绘制功能已迁移到GameBlockSelection // 清理事件监听 const eventBus = EventBus.getInstance(); eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this); eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this); // 移除GAME_START事件清理,因为已不再监听该事件 // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this); eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this); } }