BlockManager.ts 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Color, Vec2, UITransform, find, Rect, Label, Size, Sprite, SpriteFrame, resources, Button, Collider2D, Material, tween, JsonAsset } from 'cc';
  2. import { ConfigManager, WeaponConfig } from '../Core/ConfigManager';
  3. import { SaveDataManager } from '../LevelSystem/SaveDataManager';
  4. import { LevelSessionManager } from '../Core/LevelSessionManager';
  5. import { LevelConfigManager } from '../LevelSystem/LevelConfigManager';
  6. import { BlockTag } from './BlockSelection/BlockTag';
  7. import { SkillManager } from './SkillSelection/SkillManager';
  8. import EventBus, { GameEvents } from '../Core/EventBus';
  9. import { sp } from 'cc';
  10. const { ccclass, property } = _decorator;
  11. @ccclass('BlockManager')
  12. export class BlockManager extends Component {
  13. // 预制体数组,存储10个预制体
  14. @property([Prefab])
  15. public blockPrefabs: Prefab[] = [];
  16. // 网格容器节点
  17. @property({
  18. type: Node,
  19. tooltip: '拖拽GridContainer节点到这里'
  20. })
  21. public gridContainer: Node = null;
  22. // 方块容器节点(kuang)
  23. @property({
  24. type: Node,
  25. tooltip: '拖拽kuang节点到这里'
  26. })
  27. public kuangContainer: Node = null;
  28. // 金币标签节点
  29. @property({
  30. type: Node,
  31. tooltip: '拖拽CoinLabel节点到这里'
  32. })
  33. public coinLabelNode: Node = null;
  34. // 已放置方块容器节点
  35. @property({
  36. type: Node,
  37. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)'
  38. })
  39. public placedBlocksContainer: Node = null;
  40. // 游戏是否已开始
  41. public gameStarted: boolean = false;
  42. // 移除移动冷却:相关属性/逻辑已废弃
  43. // SaveDataManager 单例
  44. private saveDataManager: SaveDataManager = null; // 仅用于局外数据
  45. private session: LevelSessionManager = null;
  46. // 方块价格标签映射
  47. private blockPriceMap: Map<Node, Node> = new Map();
  48. // 已经生成的块
  49. private blocks: Node[] = [];
  50. // 网格占用情况,用于控制台输出
  51. private gridOccupationMap: number[][] = [];
  52. // 网格行数和列数
  53. private readonly GRID_ROWS = 6;
  54. private readonly GRID_COLS = 11;
  55. // 是否已初始化网格信息
  56. private gridInitialized = false;
  57. // 存储网格节点信息
  58. private gridNodes: Node[][] = [];
  59. // 网格间距
  60. private gridSpacing = 54; // 默认值,将在initGridInfo中动态计算
  61. // 不参与占用的节点名称列表
  62. private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
  63. // 临时保存方块的原始占用格子
  64. private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  65. // 方块原始位置(在kuang中的位置)
  66. public originalPositions: Map<Node, Vec3> = new Map();
  67. // 方块当前所在的区域
  68. public blockLocations: Map<Node, string> = new Map();
  69. // 配置管理器
  70. private configManager: ConfigManager = null;
  71. // 关卡配置管理器
  72. private levelConfigManager: LevelConfigManager = null;
  73. // 方块武器配置映射
  74. private blockWeaponConfigs: Map<Node, WeaponConfig> = new Map();
  75. // 预加载的武器配置数据
  76. private preloadedWeaponsConfig: any = null;
  77. // 配置是否已预加载的标志
  78. private isWeaponsConfigPreloaded: boolean = false;
  79. // 调试绘制相关
  80. // 调试绘制功能已迁移到GameBlockSelection
  81. /** 冷却机制已废弃,方块随时可移动 */
  82. // 清除所有冷却(游戏重置时调用)
  83. public clearAllCooldowns() { /* no-op */ }
  84. /**
  85. * 设置预加载的武器配置数据
  86. * @param weaponsConfigData 从JsonAsset获取的武器配置数据
  87. */
  88. public setPreloadedWeaponsConfig(weaponsConfigData: any): void {
  89. console.log('[BlockManager] 接收到预加载的武器配置数据');
  90. this.preloadedWeaponsConfig = weaponsConfigData;
  91. this.isWeaponsConfigPreloaded = true;
  92. // 验证配置数据结构
  93. if (weaponsConfigData && weaponsConfigData.weapons && Array.isArray(weaponsConfigData.weapons)) {
  94. console.log(`[BlockManager] 武器配置验证成功,包含 ${weaponsConfigData.weapons.length} 个武器`);
  95. } else {
  96. console.warn('[BlockManager] 武器配置数据结构异常');
  97. this.isWeaponsConfigPreloaded = false;
  98. }
  99. }
  100. /**
  101. * 获取预加载的武器配置,如果没有预加载则返回null
  102. */
  103. private getPreloadedWeaponsConfig(): any {
  104. return this.isWeaponsConfigPreloaded ? this.preloadedWeaponsConfig : null;
  105. }
  106. // 获取当前关卡的武器列表
  107. private async getCurrentLevelWeapons(): Promise<string[]> {
  108. if (!this.levelConfigManager || !this.saveDataManager) {
  109. console.warn('关卡配置管理器或存档管理器未初始化,使用默认武器列表');
  110. return [];
  111. }
  112. try {
  113. const currentLevel = this.saveDataManager.getCurrentLevel();
  114. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  115. if (levelConfig && levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
  116. console.log(`关卡 ${currentLevel} 配置的武器:`, levelConfig.weapons);
  117. return levelConfig.weapons;
  118. } else {
  119. console.warn(`关卡 ${currentLevel} 没有配置武器列表`);
  120. return [];
  121. }
  122. } catch (error) {
  123. console.error('获取当前关卡武器配置失败:', error);
  124. return [];
  125. }
  126. }
  127. // 根据武器名称获取武器配置
  128. private getWeaponConfigByName(weaponName: string): WeaponConfig | null {
  129. // 优先使用预加载的配置数据
  130. const preloadedConfig = this.getPreloadedWeaponsConfig();
  131. if (preloadedConfig && preloadedConfig.weapons && Array.isArray(preloadedConfig.weapons)) {
  132. const weapon = preloadedConfig.weapons.find((w: any) => w.name === weaponName);
  133. if (weapon) {
  134. console.log(`[BlockManager] 从预加载配置中找到武器: ${weaponName}`);
  135. return weapon as WeaponConfig;
  136. }
  137. }
  138. // 如果预加载配置中没有找到,回退到ConfigManager
  139. if (!this.configManager) {
  140. console.warn(`[BlockManager] 武器配置未预加载且ConfigManager不可用,无法获取武器: ${weaponName}`);
  141. return null;
  142. }
  143. console.log(`[BlockManager] 从ConfigManager中查找武器: ${weaponName}`);
  144. const allWeapons = this.configManager.getAllWeapons();
  145. return allWeapons.find(weapon => weapon.name === weaponName) || null;
  146. }
  147. // 设置事件监听器
  148. private setupEventListeners() {
  149. const eventBus = EventBus.getInstance();
  150. // 监听重置方块管理器事件
  151. eventBus.on(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  152. // 监听方块生成事件
  153. eventBus.on(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  154. // 移除GAME_START事件监听,避免与GameBlockSelection重复生成方块
  155. // eventBus.on(GameEvents.GAME_START, this.onGameStartEvent, this);
  156. // 监听波次完成事件(每波结束后生成新方块)
  157. eventBus.on(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  158. }
  159. // 处理重置方块管理器事件
  160. private onResetBlockManagerEvent() {
  161. console.log('[BlockManager] 接收到重置方块管理器事件');
  162. this.onGameReset();
  163. }
  164. // 处理方块生成事件
  165. private onGenerateBlocksEvent() {
  166. console.log('[BlockManager] 接收到方块生成事件');
  167. this.generateRandomBlocksInKuang();
  168. }
  169. // 处理游戏开始事件 - 已废弃,避免与GameBlockSelection重复生成方块
  170. // private onGameStartEvent() {
  171. // console.log('[BlockManager] 接收到游戏开始事件,生成初始方块');
  172. // this.generateRandomBlocksInKuang();
  173. // }
  174. // 处理波次完成事件
  175. private onWaveCompletedEvent() {
  176. console.log('[BlockManager] 接收到波次完成事件,生成新方块');
  177. this.generateRandomBlocksInKuang();
  178. }
  179. start() {
  180. console.log('[BlockManager] 开始初始化BlockManager');
  181. // 获取配置管理器
  182. this.configManager = ConfigManager.getInstance();
  183. if (!this.configManager) {
  184. console.error('[BlockManager] 无法获取ConfigManager实例');
  185. } else {
  186. console.log('[BlockManager] ConfigManager实例获取成功,配置加载状态:', this.configManager.isConfigLoaded());
  187. }
  188. // 获取关卡配置管理器
  189. this.levelConfigManager = LevelConfigManager.getInstance();
  190. if (!this.levelConfigManager) {
  191. console.error('[BlockManager] 无法获取LevelConfigManager实例');
  192. } else {
  193. console.log('[BlockManager] LevelConfigManager实例获取成功');
  194. }
  195. // 如果没有指定GridContainer,尝试找到它
  196. if (!this.gridContainer) {
  197. this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
  198. if (!this.gridContainer) {
  199. console.error('找不到GridContainer节点');
  200. return;
  201. }
  202. }
  203. // 如果没有指定kuangContainer,尝试找到它
  204. if (!this.kuangContainer) {
  205. this.kuangContainer = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
  206. if (!this.kuangContainer) {
  207. console.error('找不到kuang节点');
  208. return;
  209. }
  210. }
  211. // 如果没有指定coinLabelNode,尝试找到它
  212. if (!this.coinLabelNode) {
  213. this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
  214. if (!this.coinLabelNode) {
  215. console.error('找不到CoinLabel节点');
  216. return;
  217. }
  218. }
  219. // 如果没有指定placedBlocksContainer,尝试找到它
  220. if (!this.placedBlocksContainer) {
  221. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  222. }
  223. // 确保有PlacedBlocks节点用于存放已放置的方块
  224. this.ensurePlacedBlocksNode();
  225. // 获取数据管理器
  226. this.saveDataManager = SaveDataManager.getInstance();
  227. this.session = LevelSessionManager.inst;
  228. // 初始化玩家金币显示
  229. this.updateCoinDisplay();
  230. // 初始化网格信息
  231. this.initGridInfo();
  232. // 初始化网格占用情况
  233. this.initGridOccupationMap();
  234. // 设置事件监听器
  235. this.setupEventListeners();
  236. // 调试绘制功能已迁移到GameBlockSelection
  237. // 移除自动生成方块逻辑,改为事件触发
  238. // 方块生成现在通过以下事件触发:
  239. // - GAME_START: 游戏开始时
  240. // - WAVE_COMPLETED: 每波敌人消灭后
  241. // - GENERATE_BLOCKS: 手动触发生成
  242. }
  243. // 确保有PlacedBlocks节点
  244. ensurePlacedBlocksNode() {
  245. // 如果已经通过拖拽设置了节点,直接使用
  246. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  247. return;
  248. }
  249. // 尝试查找节点
  250. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  251. if (this.placedBlocksContainer) {
  252. return;
  253. }
  254. // 如果找不到,创建新节点
  255. const gameLevelUI = find('Canvas/GameLevelUI');
  256. if (!gameLevelUI) {
  257. console.error('找不到GameLevelUI节点,无法创建PlacedBlocks');
  258. return;
  259. }
  260. this.placedBlocksContainer = new Node('PlacedBlocks');
  261. gameLevelUI.addChild(this.placedBlocksContainer);
  262. if (!this.placedBlocksContainer.getComponent(UITransform)) {
  263. this.placedBlocksContainer.addComponent(UITransform);
  264. }
  265. console.log('已在GameLevelUI下创建PlacedBlocks节点');
  266. }
  267. // 初始化网格信息
  268. initGridInfo() {
  269. if (!this.gridContainer || this.gridInitialized) return;
  270. this.gridNodes = [];
  271. for (let row = 0; row < this.GRID_ROWS; row++) {
  272. this.gridNodes[row] = [];
  273. }
  274. for (let i = 0; i < this.gridContainer.children.length; i++) {
  275. const grid = this.gridContainer.children[i];
  276. if (grid.name.startsWith('Grid_')) {
  277. const parts = grid.name.split('_');
  278. if (parts.length === 3) {
  279. const row = parseInt(parts[1]);
  280. const col = parseInt(parts[2]);
  281. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  282. this.gridNodes[row][col] = grid;
  283. }
  284. }
  285. }
  286. }
  287. // 动态计算网格间距,适应不同分辨率
  288. this.calculateGridSpacing();
  289. this.gridInitialized = true;
  290. }
  291. // 动态计算网格间距
  292. private calculateGridSpacing() {
  293. // 优先使用相邻行之间的距离计算间距
  294. if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
  295. if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
  296. const pos1 = this.gridNodes[0][0].position;
  297. const pos2 = this.gridNodes[1][0].position;
  298. this.gridSpacing = Math.abs(pos2.y - pos1.y);
  299. console.log(`动态计算网格间距(行间距): ${this.gridSpacing}`);
  300. return;
  301. }
  302. }
  303. // 如果行间距计算失败,尝试使用相邻列之间的距离
  304. if (this.GRID_COLS > 1 && this.GRID_ROWS > 0) {
  305. if (this.gridNodes[0][0] && this.gridNodes[0][1]) {
  306. const pos1 = this.gridNodes[0][0].position;
  307. const pos2 = this.gridNodes[0][1].position;
  308. this.gridSpacing = Math.abs(pos2.x - pos1.x);
  309. console.log(`动态计算网格间距(列间距): ${this.gridSpacing}`);
  310. return;
  311. }
  312. }
  313. // 如果都失败了,保持默认值
  314. console.warn(`无法动态计算网格间距,使用默认值: ${this.gridSpacing}`);
  315. }
  316. // 获取当前网格间距
  317. public getGridSpacing(): number {
  318. return this.gridSpacing;
  319. }
  320. // 初始化网格占用情况
  321. initGridOccupationMap() {
  322. this.gridOccupationMap = [];
  323. for (let row = 0; row < this.GRID_ROWS; row++) {
  324. const rowArray: number[] = [];
  325. for (let col = 0; col < this.GRID_COLS; col++) {
  326. rowArray.push(0);
  327. }
  328. this.gridOccupationMap.push(rowArray);
  329. }
  330. }
  331. // 在kuang下生成三个方块(基于关卡配置)
  332. private async generateRandomBlocksInKuang() {
  333. // 清除kuang区域中的旧方块,但不清除已放置在网格中的方块的标签
  334. this.clearBlocks();
  335. // 优先检查预加载的武器配置
  336. if (this.isWeaponsConfigPreloaded) {
  337. const preloadedConfig = this.getPreloadedWeaponsConfig();
  338. if (preloadedConfig && preloadedConfig.weapons && preloadedConfig.blockSizes) {
  339. console.log('[BlockManager] 使用预加载的武器配置生成方块');
  340. // 直接使用预加载配置继续生成方块
  341. // 跳过ConfigManager的等待逻辑
  342. } else {
  343. console.warn('[BlockManager] 预加载配置不完整,回退到ConfigManager模式');
  344. this.isWeaponsConfigPreloaded = false;
  345. }
  346. }
  347. // 如果没有预加载配置,检查ConfigManager
  348. if (!this.isWeaponsConfigPreloaded) {
  349. // 检查配置管理器是否可用
  350. if (!this.configManager) {
  351. console.error('[BlockManager] ConfigManager实例未找到,延迟2秒后重试');
  352. this.scheduleOnce(() => {
  353. this.generateRandomBlocksInKuang();
  354. }, 2.0);
  355. return;
  356. }
  357. // 检查武器配置是否已加载(不需要等待所有配置完成)
  358. const weaponsConfigLoaded = !!this.configManager['weaponsConfig'];
  359. const blockSizesAvailable = weaponsConfigLoaded && !!this.configManager['weaponsConfig'].blockSizes;
  360. if (!weaponsConfigLoaded) {
  361. console.log('[BlockManager] 武器配置未加载完成,延迟2秒后重试生成方块');
  362. console.log('[BlockManager] 整体配置状态:', this.configManager.isConfigLoaded());
  363. this.scheduleOnce(() => {
  364. this.generateRandomBlocksInKuang();
  365. }, 2.0);
  366. return;
  367. }
  368. if (!blockSizesAvailable) {
  369. console.warn('[BlockManager] 武器配置已加载但blockSizes缺失,延迟2秒后重试');
  370. console.log('[BlockManager] weaponsConfig keys:', Object.keys(this.configManager['weaponsConfig']));
  371. this.scheduleOnce(() => {
  372. this.generateRandomBlocksInKuang();
  373. }, 2.0);
  374. return;
  375. }
  376. }
  377. console.log('[BlockManager] 配置已加载完成,开始生成方块');
  378. if (this.blockPrefabs.length === 0) {
  379. console.error('没有可用的预制体');
  380. return;
  381. }
  382. const kuangNode = this.kuangContainer;
  383. if (!kuangNode) {
  384. console.error('找不到kuang节点');
  385. return;
  386. }
  387. const offsets = [
  388. new Vec3(-200, 0, 0),
  389. new Vec3(0, 0, 0),
  390. new Vec3(200, 0, 0)
  391. ];
  392. const dbNodes = [
  393. kuangNode.getChildByName('db01'),
  394. kuangNode.getChildByName('db02'),
  395. kuangNode.getChildByName('db03')
  396. ];
  397. // 获取当前关卡的武器配置列表
  398. const levelWeapons = await this.getCurrentLevelWeapons();
  399. for (let i = 0; i < 3; i++) {
  400. let weaponConfig: WeaponConfig | null = null;
  401. // 优先使用关卡配置的武器,确保符合关卡设计
  402. if (levelWeapons.length > 0) {
  403. const randomWeaponName = levelWeapons[Math.floor(Math.random() * levelWeapons.length)];
  404. weaponConfig = this.getWeaponConfigByName(randomWeaponName);
  405. if (!weaponConfig) {
  406. console.warn(`关卡配置的武器 "${randomWeaponName}" 在武器配置文件中未找到`);
  407. }
  408. }
  409. // 如果关卡没有配置武器或获取失败,使用随机武器
  410. if (!weaponConfig) {
  411. weaponConfig = this.configManager.getRandomWeapon();
  412. }
  413. // 最后的兜底处理
  414. if (!weaponConfig) {
  415. console.warn('无法获取武器配置,使用默认武器');
  416. // 尝试获取一个基础武器作为兜底
  417. const allWeapons = this.configManager.getAllWeapons();
  418. if (allWeapons.length > 0) {
  419. weaponConfig = allWeapons[0];
  420. }
  421. }
  422. if (!weaponConfig) {
  423. console.error(`无法获取第 ${i + 1} 个武器配置`);
  424. continue;
  425. }
  426. // 从武器配置的形状成本中随机选择一个形状ID
  427. let targetShapeId: string | null = null;
  428. try {
  429. const shapeCosts = weaponConfig.inGameCostConfig?.shapeCosts;
  430. if (shapeCosts && Object.keys(shapeCosts).length > 0) {
  431. const availableShapes = Object.keys(shapeCosts);
  432. targetShapeId = availableShapes[Math.floor(Math.random() * availableShapes.length)];
  433. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 选择形状: ${targetShapeId}`);
  434. console.log(`[BlockManager] 可用形状列表: ${availableShapes.join(', ')}`);
  435. } else {
  436. console.warn(`[BlockManager] 武器 ${weaponConfig.name} 没有配置shapeCosts或为空`);
  437. }
  438. } catch (error) {
  439. console.warn(`[BlockManager] 无法从武器配置获取形状信息: ${error}`);
  440. }
  441. // 基于武器配置和目标形状选择合适的预制体
  442. console.log(`[BlockManager] 开始为武器 ${weaponConfig.name} 选择预制体,目标形状: ${targetShapeId || '未指定'}`);
  443. const prefab = this.selectPrefabForWeapon(weaponConfig, targetShapeId);
  444. console.log(`[BlockManager] 预制体选择结果: ${prefab ? '成功' : '失败'}`);
  445. if (!prefab) {
  446. console.error(`无法为武器 ${weaponConfig.name} 选择合适的预制体`);
  447. continue;
  448. }
  449. const block = instantiate(prefab);
  450. kuangNode.addChild(block);
  451. block.position = offsets[i];
  452. // 设置方块名称
  453. block.name = `WeaponBlock_${weaponConfig.id}`;
  454. // 保存武器配置到方块
  455. this.blockWeaponConfigs.set(block, weaponConfig);
  456. block['weaponConfig'] = weaponConfig;
  457. block['weaponId'] = weaponConfig.id;
  458. this.originalPositions.set(block, offsets[i].clone());
  459. this.blockLocations.set(block, 'kuang');
  460. this.blocks.push(block);
  461. if (dbNodes[i]) {
  462. const priceNode = dbNodes[i].getChildByName('Price');
  463. if (priceNode) {
  464. this.blockPriceMap.set(block, priceNode);
  465. priceNode.active = true;
  466. // 根据武器配置和方块形状设置价格
  467. this.setBlockPriceByWeaponConfig(block, priceNode);
  468. }
  469. this.associateDbNodeWithBlock(block, dbNodes[i]);
  470. }
  471. // 设置方块的武器外观
  472. this.setupBlockWeaponVisual(block, weaponConfig);
  473. // 为新生成的方块添加标签
  474. BlockTag.addTag(block);
  475. console.log(`[BlockManager] 为方块 ${block.name} 添加标签,UUID: ${block.uuid}`);
  476. }
  477. // 通过事件机制通知GameBlockSelection为新生成的方块设置拖拽事件
  478. if (this.blocks.length > 0) {
  479. const eventBus = EventBus.getInstance();
  480. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.blocks.slice());
  481. console.log(`[BlockManager] 发送方块拖拽事件设置请求,方块数量: ${this.blocks.length}`);
  482. }
  483. this.updateCoinDisplay();
  484. }
  485. // 将db节点与方块关联
  486. associateDbNodeWithBlock(block: Node, dbNode: Node) {
  487. block['dbNode'] = dbNode;
  488. block.on(Node.EventType.TRANSFORM_CHANGED, () => {
  489. if (dbNode && block.parent) {
  490. const location = this.blockLocations.get(block);
  491. if (location === 'grid') {
  492. dbNode.active = false;
  493. return;
  494. }
  495. // 检查方块是否正在被拖动,如果是则隐藏价格标签
  496. if (block['isDragging']) {
  497. dbNode.active = false;
  498. return;
  499. }
  500. dbNode.active = true;
  501. const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position);
  502. const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  503. dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z);
  504. }
  505. });
  506. }
  507. // 更新金币显示
  508. updateCoinDisplay() {
  509. if (this.coinLabelNode) {
  510. const label = this.coinLabelNode.getComponent(Label);
  511. if (label) {
  512. const coins = this.session.getCoins();
  513. label.string = coins.toString();
  514. }
  515. }
  516. }
  517. // 获取方块价格
  518. getBlockPrice(block: Node): number {
  519. const priceNode = this.blockPriceMap.get(block);
  520. if (priceNode) {
  521. const label = priceNode.getComponent(Label);
  522. if (label) {
  523. const price = parseInt(label.string);
  524. if (!isNaN(price)) {
  525. return price;
  526. }
  527. }
  528. }
  529. return 50;
  530. }
  531. // 隐藏价格标签
  532. hidePriceLabel(block: Node) {
  533. const priceNode = this.blockPriceMap.get(block);
  534. if (priceNode) {
  535. priceNode.active = false;
  536. }
  537. }
  538. // 显示价格标签
  539. showPriceLabel(block: Node) {
  540. const priceNode = this.blockPriceMap.get(block);
  541. if (priceNode) {
  542. priceNode.active = true;
  543. }
  544. }
  545. // 扣除玩家金币
  546. deductPlayerCoins(amount: number): boolean {
  547. const success = this.session.spendCoins(amount);
  548. if (success) {
  549. this.updateCoinDisplay();
  550. }
  551. return success;
  552. }
  553. // 显示金币不足时的价格标签闪烁效果
  554. showInsufficientCoinsEffect(block: Node) {
  555. const priceNode = this.blockPriceMap.get(block);
  556. if (!priceNode) {
  557. console.warn('[BlockManager] 找不到方块对应的价格标签');
  558. return;
  559. }
  560. const label = priceNode.getComponent(Label);
  561. if (!label) {
  562. console.warn('[BlockManager] 价格节点缺少Label组件');
  563. return;
  564. }
  565. // 保存原始颜色
  566. const originalColor = label.color.clone();
  567. // 设置红色
  568. const redColor = new Color(255, 0, 0, 255);
  569. // 创建闪烁动画:变红 -> 恢复原色,重复3次,总时长2秒
  570. tween(label)
  571. .to(0.2, { color: redColor })
  572. .to(0.2, { color: originalColor })
  573. .to(0.2, { color: redColor })
  574. .to(0.2, { color: originalColor })
  575. .to(0.2, { color: redColor })
  576. .to(1.0, { color: originalColor })
  577. .start();
  578. // 发送显示Toast事件
  579. EventBus.getInstance().emit(GameEvents.SHOW_TOAST, {
  580. message: '金币不足',
  581. duration: 2.0
  582. });
  583. console.log('[BlockManager] 显示金币不足效果');
  584. }
  585. // 归还玩家金币
  586. refundPlayerCoins(amount: number) {
  587. this.session.addCoins(amount);
  588. this.updateCoinDisplay();
  589. }
  590. // 设置拖拽事件方法已迁移到GameBlockSelection
  591. // 清除临时保存的占用状态
  592. clearTempStoredOccupiedGrids(block: Node) {
  593. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  594. if (index === -1) return;
  595. this.tempRemovedOccupiedGrids.splice(index, 1);
  596. }
  597. // 尝试将方块放置到网格中
  598. tryPlaceBlockToGrid(block: Node): boolean {
  599. console.log(`[BlockManager] 尝试放置方块 ${block.name} 到网格`);
  600. if (!this.gridContainer || !this.gridInitialized) {
  601. console.log(`[BlockManager] 网格容器或网格未初始化`);
  602. return false;
  603. }
  604. let b1Node = block;
  605. if (block.name !== 'B1') {
  606. b1Node = block.getChildByName('B1');
  607. if (!b1Node) {
  608. console.log(`[BlockManager] 方块 ${block.name} 没有B1子节点`);
  609. return false;
  610. }
  611. }
  612. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  613. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  614. console.log(`[BlockManager] B1世界坐标:`, b1WorldPos);
  615. console.log(`[BlockManager] 网格本地坐标:`, gridPos);
  616. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  617. const halfWidth = gridSize.width / 2;
  618. const halfHeight = gridSize.height / 2;
  619. const tolerance = this.gridSpacing * 0.5;
  620. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  621. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  622. console.log(`[BlockManager] 方块超出网格边界`);
  623. return false;
  624. }
  625. const nearestGrid = this.findNearestGridNode(gridPos);
  626. if (!nearestGrid) {
  627. console.log(`[BlockManager] 找不到最近的网格节点`);
  628. return false;
  629. }
  630. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  631. }
  632. // 找到最近的网格节点
  633. public findNearestGridNode(position: Vec3): Node {
  634. if (!this.gridContainer || !this.gridInitialized) return null;
  635. let nearestNode: Node = null;
  636. let minDistance = Number.MAX_VALUE;
  637. for (let row = 0; row < this.GRID_ROWS; row++) {
  638. for (let col = 0; col < this.GRID_COLS; col++) {
  639. const grid = this.gridNodes[row][col];
  640. if (grid) {
  641. const distance = Vec3.distance(position, grid.position);
  642. if (distance < minDistance) {
  643. minDistance = distance;
  644. nearestNode = grid;
  645. }
  646. }
  647. }
  648. }
  649. if (minDistance > this.gridSpacing * 2) {
  650. return null;
  651. }
  652. return nearestNode;
  653. }
  654. // 尝试将方块放置到指定的网格节点
  655. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  656. let b1Node = block;
  657. if (block.name !== 'B1') {
  658. b1Node = block.getChildByName('B1');
  659. if (!b1Node) {
  660. return false;
  661. }
  662. }
  663. if (!this.canPlaceBlockAt(block, targetGrid)) {
  664. return false;
  665. }
  666. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  667. const targetWorldPos = gridCenterWorldPos.clone();
  668. const b1LocalPos = b1Node.position.clone();
  669. let rootTargetWorldPos;
  670. if (b1Node === block) {
  671. rootTargetWorldPos = targetWorldPos.clone();
  672. } else {
  673. rootTargetWorldPos = new Vec3(
  674. targetWorldPos.x - b1LocalPos.x,
  675. targetWorldPos.y - b1LocalPos.y,
  676. targetWorldPos.z
  677. );
  678. }
  679. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  680. block.position = rootTargetLocalPos;
  681. this.markOccupiedPositions(block, targetGrid);
  682. // 当方块从kuang区域拖到网格时,恢复植物图标的正常缩放
  683. const weaponNode = block.getChildByName('Weapon');
  684. if (weaponNode) {
  685. weaponNode.setScale(1.0, 1.0, 1.0);
  686. console.log(`[BlockManager] 方块 ${block.name} 放置到网格,植物图标缩放恢复为正常大小`);
  687. }
  688. return true;
  689. }
  690. // 检查方块是否可以放置在指定位置
  691. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  692. if (!this.gridInitialized) {
  693. console.log(`[BlockManager] 网格未初始化`);
  694. return false;
  695. }
  696. const targetRowCol = this.getGridRowCol(targetGrid);
  697. if (!targetRowCol) {
  698. console.log(`[BlockManager] 无法获取目标网格的行列信息`);
  699. return false;
  700. }
  701. const parts = this.getBlockParts(block);
  702. for (let i = 0; i < parts.length; i++) {
  703. const part = parts[i];
  704. const row = targetRowCol.row - part.y;
  705. const col = targetRowCol.col + part.x;
  706. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  707. console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`);
  708. return false;
  709. }
  710. if (this.gridOccupationMap[row][col] === 1) {
  711. console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`);
  712. return false;
  713. }
  714. }
  715. return true;
  716. }
  717. // 获取网格行列索引
  718. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  719. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  720. const parts = gridNode.name.split('_');
  721. if (parts.length === 3) {
  722. const row = parseInt(parts[1]);
  723. const col = parseInt(parts[2]);
  724. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  725. return { row, col };
  726. }
  727. }
  728. return null;
  729. }
  730. // 获取指定行列的网格世界坐标(用于调试绘制)
  731. public getGridWorldPosition(row: number, col: number): Vec3 | null {
  732. if (!this.gridInitialized || !this.gridNodes[row] || !this.gridNodes[row][col]) {
  733. return null;
  734. }
  735. const gridNode = this.gridNodes[row][col];
  736. return this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(gridNode.position);
  737. }
  738. // 获取方块的所有部分节点及其相对坐标
  739. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  740. const parts: { node: Node, x: number, y: number }[] = [];
  741. // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
  742. const b1Node = block.getChildByName('B1');
  743. if (b1Node) {
  744. // B1节点作为形状的根节点和坐标原点(0,0)
  745. // 将B1节点本身添加为第一个部分
  746. parts.push({ node: b1Node, x: 0, y: 0 });
  747. // 然后递归查找B1的子节点,但要避免重复添加B1本身
  748. this.findBlockParts(b1Node, parts, 0, 0, true);
  749. } else {
  750. // 没有B1节点,使用根节点作为形状根节点
  751. parts.push({ node: block, x: 0, y: 0 });
  752. this.findBlockParts(block, parts, 0, 0, false);
  753. }
  754. return parts;
  755. }
  756. // 递归查找方块的所有部分
  757. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number, skipRoot: boolean = false) {
  758. for (let i = 0; i < node.children.length; i++) {
  759. const child = node.children[i];
  760. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  761. continue;
  762. }
  763. let x = parentX;
  764. let y = parentY;
  765. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  766. if (match) {
  767. x = parseInt(match[1]);
  768. y = parseInt(match[2]);
  769. result.push({ node: child, x, y });
  770. } else if (child.name.startsWith('B')) {
  771. const relativeX = Math.round(child.position.x / this.gridSpacing);
  772. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  773. x = parentX + relativeX;
  774. y = parentY + relativeY;
  775. // 避免重复添加已经在result中的节点
  776. const existingPart = result.find(part => part.node === child);
  777. if (!existingPart) {
  778. result.push({ node: child, x, y });
  779. }
  780. }
  781. this.findBlockParts(child, result, x, y, false);
  782. }
  783. }
  784. // 标记方块占用的格子
  785. public markOccupiedPositions(block: Node, targetGrid: Node) {
  786. if (!this.gridInitialized) return;
  787. const targetRowCol = this.getGridRowCol(targetGrid);
  788. if (!targetRowCol) return;
  789. const parts = this.getBlockParts(block);
  790. block['occupiedGrids'] = [];
  791. for (const part of parts) {
  792. const row = targetRowCol.row - part.y;
  793. const col = targetRowCol.col + part.x;
  794. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  795. this.gridOccupationMap[row][col] = 1;
  796. block['occupiedGrids'] = block['occupiedGrids'] || [];
  797. block['occupiedGrids'].push({ row, col });
  798. }
  799. }
  800. }
  801. // 清除方块
  802. clearBlocks() {
  803. console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
  804. const blocksToRemove = [];
  805. for (const block of this.blocks) {
  806. if (block.isValid) {
  807. const location = this.blockLocations.get(block);
  808. if (location === 'kuang') {
  809. blocksToRemove.push(block);
  810. }
  811. }
  812. }
  813. console.log('[BlockManager] 找到需要清理的kuang区域方块数量:', blocksToRemove.length);
  814. for (const block of blocksToRemove) {
  815. const dbNode = block['dbNode'];
  816. if (dbNode && dbNode.isValid) {
  817. block.off(Node.EventType.TRANSFORM_CHANGED);
  818. const kuangNode = this.kuangContainer;
  819. if (kuangNode) {
  820. const dbName = dbNode.name;
  821. if (!kuangNode.getChildByName(dbName)) {
  822. dbNode.parent = kuangNode;
  823. }
  824. }
  825. }
  826. const index = this.blocks.indexOf(block);
  827. if (index !== -1) {
  828. this.blocks.splice(index, 1);
  829. }
  830. this.originalPositions.delete(block);
  831. this.blockLocations.delete(block);
  832. this.blockPriceMap.delete(block);
  833. // 清理武器配置映射
  834. this.blockWeaponConfigs.delete(block);
  835. console.log('[BlockManager] 销毁kuang区域方块:', block.name);
  836. block.destroy();
  837. }
  838. console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
  839. }
  840. // 游戏开始时调用
  841. onGameStart() {
  842. this.gameStarted = true;
  843. for (const block of this.blocks) {
  844. if (block.isValid) {
  845. const location = this.blockLocations.get(block);
  846. if (location === 'grid') {
  847. this.hidePriceLabel(block);
  848. const dbNode = block['dbNode'];
  849. if (dbNode) {
  850. dbNode.active = false;
  851. }
  852. this.moveBlockToPlacedBlocks(block);
  853. this.addLockedVisualHint(block);
  854. // 游戏开始后放置的方块移除标签,不能再放回kuang
  855. BlockTag.removeTag(block);
  856. }
  857. }
  858. }
  859. }
  860. // 游戏重置时调用
  861. onGameReset() {
  862. console.log('[BlockManager] 游戏重置,清理所有状态');
  863. console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
  864. this.gameStarted = false;
  865. this.clearAllCooldowns();
  866. // 清理已放置的方块
  867. console.log('[BlockManager] 开始清理已放置的方块');
  868. this.clearPlacedBlocks();
  869. // 重置网格占用状态
  870. console.log('[BlockManager] 开始重置网格占用状态');
  871. this.resetGridOccupation();
  872. // 清理kuang区域的方块
  873. console.log('[BlockManager] 开始清理kuang区域的方块');
  874. this.clearBlocks();
  875. // 清理所有方块标签
  876. console.log('[BlockManager] 开始清理所有方块标签');
  877. BlockTag.clearAllTags();
  878. console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
  879. console.log('[BlockManager] 游戏重置完成 - 方块生成将由StartGame流程处理');
  880. }
  881. // 清理已放置的方块
  882. private clearPlacedBlocks() {
  883. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  884. console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
  885. return;
  886. }
  887. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  888. // 清理PlacedBlocks容器中的所有方块
  889. const placedBlocks = [...this.placedBlocksContainer.children];
  890. let clearedCount = 0;
  891. for (const block of placedBlocks) {
  892. if (block && block.isValid) {
  893. // 从blocks数组中移除
  894. const index = this.blocks.indexOf(block);
  895. if (index !== -1) {
  896. this.blocks.splice(index, 1);
  897. }
  898. // 清理相关映射
  899. this.originalPositions.delete(block);
  900. this.blockLocations.delete(block);
  901. this.blockPriceMap.delete(block);
  902. this.blockWeaponConfigs.delete(block);
  903. console.log('[BlockManager] 销毁已放置方块:', block.name);
  904. // 销毁方块
  905. block.destroy();
  906. clearedCount++;
  907. }
  908. }
  909. console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
  910. }
  911. // 重置网格占用状态
  912. public resetGridOccupation() {
  913. console.log('[BlockManager] 重置网格占用状态');
  914. // 重新初始化网格占用地图
  915. this.gridOccupationMap = [];
  916. for (let row = 0; row < this.GRID_ROWS; row++) {
  917. this.gridOccupationMap[row] = [];
  918. for (let col = 0; col < this.GRID_COLS; col++) {
  919. this.gridOccupationMap[row][col] = 0;
  920. }
  921. }
  922. // 清理临时存储的占用状态
  923. this.tempRemovedOccupiedGrids = [];
  924. }
  925. // 添加视觉提示,表明方块已锁定
  926. addLockedVisualHint(block: Node) {
  927. const children = block.children;
  928. for (let i = 0; i < children.length; i++) {
  929. const child = children[i];
  930. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  931. continue;
  932. }
  933. child.setScale(new Vec3(0.95, 0.95, 1));
  934. }
  935. }
  936. // 将方块移动到PlacedBlocks节点下
  937. moveBlockToPlacedBlocks(block: Node) {
  938. if (!this.placedBlocksContainer) {
  939. console.error('PlacedBlocks容器未设置');
  940. return;
  941. }
  942. if (!this.placedBlocksContainer.isValid) {
  943. console.error('PlacedBlocks容器已失效');
  944. return;
  945. }
  946. const worldPosition = new Vec3();
  947. block.getWorldPosition(worldPosition);
  948. // 移除旧的触摸事件监听器
  949. block.off(Node.EventType.TOUCH_START);
  950. block.off(Node.EventType.TOUCH_MOVE);
  951. block.off(Node.EventType.TOUCH_END);
  952. block.off(Node.EventType.TOUCH_CANCEL);
  953. block.removeFromParent();
  954. this.placedBlocksContainer.addChild(block);
  955. block.setWorldPosition(worldPosition);
  956. // 通过事件机制重新设置拖拽事件
  957. const eventBus = EventBus.getInstance();
  958. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]);
  959. console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`);
  960. }
  961. // 根据武器配置选择合适的预制体
  962. private selectPrefabForWeapon(weaponConfig: WeaponConfig, targetShapeId?: string): Prefab | null {
  963. if (this.blockPrefabs.length === 0) {
  964. return null;
  965. }
  966. // 如果指定了目标形状ID,尝试找到匹配的预制体
  967. if (targetShapeId) {
  968. const matchingPrefab = this.findPrefabByShape(targetShapeId);
  969. if (matchingPrefab) {
  970. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 找到匹配形状 ${targetShapeId} 的预制体`);
  971. return matchingPrefab;
  972. }
  973. }
  974. // 如果没有指定形状或没有找到匹配的预制体,使用随机选择
  975. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  976. const selectedPrefab = this.blockPrefabs[randomIndex];
  977. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 选择随机预制体 (索引: ${randomIndex})`);
  978. return selectedPrefab;
  979. }
  980. // 根据形状ID查找匹配的预制体(按照Block+形状ID的命名规则)
  981. private findPrefabByShape(targetShapeId: string): Prefab | null {
  982. // 构建预期的预制体名称:Block + 形状ID
  983. const expectedPrefabName = `Block${targetShapeId}`;
  984. console.log(`[BlockManager] 寻找形状 ${targetShapeId} 的预制体,期望名称: ${expectedPrefabName}`);
  985. console.log(`[BlockManager] 当前可用预制体数量: ${this.blockPrefabs.length}`);
  986. // 输出所有可用预制体的详细信息
  987. this.blockPrefabs.forEach((prefab, index) => {
  988. console.log(`[BlockManager] 预制体[${index}]: ${prefab.name} (匹配: ${prefab.name === expectedPrefabName})`);
  989. });
  990. for (const prefab of this.blockPrefabs) {
  991. if (prefab.name === expectedPrefabName) {
  992. console.log(`[BlockManager] ✓ 找到匹配形状 ${targetShapeId} 的预制体: ${prefab.name}`);
  993. return prefab;
  994. }
  995. }
  996. console.log(`[BlockManager] ✗ 未找到匹配形状 ${targetShapeId} 的预制体 (期望名称: ${expectedPrefabName})`);
  997. return null;
  998. }
  999. // 根据稀有度设置方块价格
  1000. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  1001. const label = priceNode.getComponent(Label);
  1002. if (!label) {
  1003. return;
  1004. }
  1005. let basePrice: number;
  1006. switch (rarity) {
  1007. case 'common':
  1008. basePrice = 10;
  1009. break;
  1010. case 'uncommon':
  1011. basePrice = 20;
  1012. break;
  1013. case 'rare':
  1014. basePrice = 50;
  1015. break;
  1016. case 'epic':
  1017. basePrice = 100;
  1018. break;
  1019. case 'legendary':
  1020. basePrice = 150;
  1021. break;
  1022. default:
  1023. basePrice = 200;
  1024. }
  1025. // 应用便宜技能效果
  1026. const skillManager = SkillManager.getInstance();
  1027. let finalPrice = basePrice;
  1028. if (skillManager) {
  1029. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1030. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1031. }
  1032. label.string = finalPrice.toString();
  1033. }
  1034. // 根据武器配置和方块形状设置价格
  1035. private setBlockPriceByWeaponConfig(block: Node, priceNode: Node) {
  1036. const label = priceNode.getComponent(Label);
  1037. if (!label) {
  1038. return;
  1039. }
  1040. // 获取方块的武器配置
  1041. const weaponConfig = this.getBlockWeaponConfig(block);
  1042. if (!weaponConfig) {
  1043. // 如果没有武器配置,使用原有的稀有度定价方式
  1044. this.setBlockPriceByRarity(priceNode, 'common');
  1045. return;
  1046. }
  1047. // 获取方块形状
  1048. const shapeId = this.getBlockShape(block);
  1049. if (!shapeId) {
  1050. // 如果无法获取形状,使用基础价格
  1051. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common');
  1052. return;
  1053. }
  1054. // 从武器配置中获取局内金币花费配置
  1055. const inGameCostConfig = weaponConfig.inGameCostConfig;
  1056. if (!inGameCostConfig) {
  1057. // 如果没有局内金币配置,使用原有的稀有度定价方式
  1058. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common');
  1059. return;
  1060. }
  1061. // 根据形状获取价格
  1062. let basePrice = inGameCostConfig.shapeCosts[shapeId];
  1063. if (basePrice === undefined) {
  1064. // 如果没有找到对应形状的价格,使用基础价格
  1065. basePrice = inGameCostConfig.baseCost * this.getBlockGridCount(block);
  1066. }
  1067. // 应用便宜技能效果
  1068. const skillManager = SkillManager.getInstance();
  1069. let finalPrice = basePrice;
  1070. if (skillManager) {
  1071. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1072. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1073. }
  1074. label.string = finalPrice.toString();
  1075. }
  1076. // 计算方块占用的格子数量
  1077. private getBlockGridCount(block: Node): number {
  1078. const parts = this.getBlockParts(block);
  1079. return parts.length;
  1080. }
  1081. // 设置方块的武器外观
  1082. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  1083. // 确保方块节点上也有 weaponConfig 属性
  1084. block['weaponConfig'] = weaponConfig;
  1085. // 设置方块的稀有度颜色
  1086. this.setBlockRarityColor(block, weaponConfig.rarity || 'common');
  1087. // 加载武器图标
  1088. this.loadWeaponIcon(block, weaponConfig);
  1089. }
  1090. // 设置方块稀有度颜色
  1091. private setBlockRarityColor(block: Node, rarity: string) {
  1092. this.applyBlockRarityColor(block, rarity);
  1093. }
  1094. // 公共方法:应用方块稀有度颜色(供外部调用)
  1095. public applyBlockRarityColor(block: Node, rarity: string) {
  1096. // Add null safety check for block
  1097. if (!block || !block.isValid) {
  1098. return;
  1099. }
  1100. const sprite = block.getComponent(Sprite);
  1101. if (!sprite || !sprite.isValid) {
  1102. return;
  1103. }
  1104. // 根据稀有度设置颜色
  1105. let color: Color;
  1106. switch (rarity) {
  1107. case 'common':
  1108. color = new Color(255, 255, 255); // 白色
  1109. break;
  1110. case 'uncommon':
  1111. color = new Color(0, 255, 0); // 绿色
  1112. break;
  1113. case 'rare':
  1114. color = new Color(0, 100, 255); // 蓝色
  1115. break;
  1116. case 'epic':
  1117. color = new Color(160, 32, 240); // 紫色
  1118. break;
  1119. case 'legendary':
  1120. color = new Color(255, 165, 0); // 橙色
  1121. break;
  1122. default:
  1123. color = new Color(255, 255, 255); // 默认白色
  1124. }
  1125. sprite.color = color;
  1126. console.log(`[BlockManager] 设置方块稀有度颜色: ${rarity}`, color);
  1127. }
  1128. // 加载武器图标
  1129. private async loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  1130. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  1131. const b1Node = block.getChildByName('B1');
  1132. if (!b1Node) {
  1133. console.warn('找不到B1节点');
  1134. return;
  1135. }
  1136. const weaponNode = b1Node.getChildByName('Weapon');
  1137. if (!weaponNode) {
  1138. console.warn('找不到Weapon节点');
  1139. return;
  1140. }
  1141. const weaponSprite = weaponNode.getComponent(Sprite);
  1142. if (!weaponSprite) {
  1143. console.warn('Weapon节点上没有Sprite组件');
  1144. return;
  1145. }
  1146. // 获取武器配置中的图片路径
  1147. const spritePath = weaponConfig.visualConfig?.weaponSprites;
  1148. if (!spritePath) {
  1149. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  1150. return;
  1151. }
  1152. // 正确的SpriteFrame子资源路径
  1153. const spriteFramePath = `${spritePath}/spriteFrame`;
  1154. // 加载SpriteFrame子资源
  1155. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  1156. if (err) {
  1157. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  1158. return;
  1159. }
  1160. // Add comprehensive null safety checks before setting spriteFrame
  1161. if (weaponSprite && weaponSprite.isValid &&
  1162. weaponNode && weaponNode.isValid &&
  1163. block && block.isValid &&
  1164. spriteFrame && spriteFrame.isValid) {
  1165. weaponSprite.spriteFrame = spriteFrame;
  1166. // 武器图标已加载
  1167. // 应用武器图标的旋转(不再使用位置偏移)
  1168. const blockShape = this.getBlockShape(block);
  1169. this.rotateWeaponIconByShape(weaponNode, blockShape, weaponConfig.id);
  1170. }
  1171. });
  1172. }
  1173. // 武器类型和方块形状组合的旋转角度配置
  1174. private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
  1175. 'pea_shooter': {
  1176. 'I': 0, // 毛豆射手竖条形状
  1177. 'H-I': 90, // 毛豆射手横条形状
  1178. 'L': 0, // 毛豆射手L型
  1179. 'S': 0, // 毛豆射手S型
  1180. 'D-T': 0 // 毛豆射手倒T型
  1181. },
  1182. 'sharp_carrot': {
  1183. 'I': 0, // 尖胡萝卜竖条形状
  1184. 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
  1185. 'L': -15, // 尖胡萝卜L型,轻微调整
  1186. 'S': 15, // 尖胡萝卜S型,轻微调整
  1187. 'D-T': 0 // 尖胡萝卜倒T型
  1188. },
  1189. 'saw_grass': {
  1190. 'I': 0, // 锯齿草竖条形状
  1191. 'H-I': 0, // 锯齿草横条形状
  1192. 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
  1193. 'S': 30, // 锯齿草S型,适配锯齿弯曲
  1194. 'D-T': 0 // 锯齿草倒T型
  1195. },
  1196. 'watermelon_bomb': {
  1197. 'I': 0, // 西瓜炸弹竖条形状
  1198. 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
  1199. 'L': 0, // 西瓜炸弹L型
  1200. 'S': 0, // 西瓜炸弹S型
  1201. 'D-T': 0 // 西瓜炸弹倒T型
  1202. },
  1203. 'boomerang_plant': {
  1204. 'I': 0, // 回旋镖植物竖条形状
  1205. 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
  1206. 'L': -30, // 回旋镖植物L型
  1207. 'S': -10, // 回旋镖植物S型,适配回旋轨迹
  1208. 'D-T': -80 // 回旋镖植物倒T型
  1209. },
  1210. 'hot_pepper': {
  1211. 'I': 0, // 辣椒竖条形状
  1212. 'H-I': 90, // 辣椒横条形状
  1213. 'L': 0, // 辣椒L型
  1214. 'S': 0, // 辣椒S型
  1215. 'D-T': 0 // 辣椒倒T型
  1216. },
  1217. 'cactus_shotgun': {
  1218. 'I': 0, // 仙人掌霰弹枪竖条形状
  1219. 'H-I': 90, // 仙人掌霰弹枪横条形状
  1220. 'L': -20, // 仙人掌霰弹枪L型
  1221. 'S': 20, // 仙人掌霰弹枪S型
  1222. 'D-T': 0 // 仙人掌霰弹枪倒T型
  1223. },
  1224. 'okra_missile': {
  1225. 'I': 0, // 秋葵导弹竖条形状
  1226. 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
  1227. 'L': -10, // 秋葵导弹L型
  1228. 'S': 10, // 秋葵导弹S型
  1229. 'D-T': 0 // 秋葵导弹倒T型
  1230. },
  1231. 'mace_club': {
  1232. 'I': -45, // 狼牙棒竖条形状
  1233. 'H-I': 0, // 狼牙棒横条形状
  1234. 'L': -90, // 狼牙棒L型,适配棒状武器
  1235. 'S': -90, // 狼牙棒S型
  1236. 'D-T': 0 // 狼牙棒倒T型
  1237. }
  1238. };
  1239. // 默认旋转角度配置(当武器类型未配置时使用)
  1240. private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
  1241. 'I': 0, // 竖条形状,保持原始方向
  1242. 'H-I': 90, // 横I型,旋转90度适配水平方向
  1243. 'L': -15, // L型,轻微左倾适配L形状的转角
  1244. 'S': 15, // S型,轻微右倾适配S形状的弯曲
  1245. 'D-T': 0 // 倒T型,保持原始方向
  1246. };
  1247. // 根据武器类型和方块形状调整武器图标位置(完全保留预制体原始旋转值,不应用额外旋转)
  1248. private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1249. if (!weaponNode || !shapeId) return;
  1250. // 保存预制体的原始旋转角度
  1251. const originalAngle = weaponNode.angle;
  1252. // let additionalRotationAngle = 0;
  1253. // 注释掉旋转逻辑,完全保留预制体设置
  1254. /*
  1255. // 如果提供了武器ID,尝试获取特定武器的旋转角度
  1256. if (weaponId) {
  1257. additionalRotationAngle = this.getWeaponShapeRotationAngle(weaponId, shapeId);
  1258. console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定旋转角度: ${additionalRotationAngle}度,原始角度: ${originalAngle}度`);
  1259. } else {
  1260. // 使用默认配置
  1261. additionalRotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1262. console.log(`为形状 ${shapeId} 设置默认旋转角度: ${additionalRotationAngle}度,原始角度: ${originalAngle}度`);
  1263. }
  1264. // 应用旋转角度:叠加预制体原始角度和形状配置角度
  1265. weaponNode.angle = originalAngle + additionalRotationAngle;
  1266. */
  1267. console.log(`保留预制体原始旋转角度: ${originalAngle}度,不应用额外旋转`);
  1268. }
  1269. // 注释掉的原始方法(覆盖预制体旋转值的版本)
  1270. /*
  1271. private rotateWeaponIconByShape_Original(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1272. if (!weaponNode || !shapeId) return;
  1273. let rotationAngle = 0;
  1274. // 如果提供了武器ID,尝试获取特定武器的旋转角度
  1275. if (weaponId) {
  1276. rotationAngle = this.getWeaponShapeRotationAngle(weaponId, shapeId);
  1277. console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定旋转角度: ${rotationAngle}度`);
  1278. } else {
  1279. // 使用默认配置
  1280. rotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1281. console.log(`为形状 ${shapeId} 设置默认旋转角度: ${rotationAngle}度`);
  1282. }
  1283. // 应用旋转角度(直接覆盖,会丢失预制体设置)
  1284. weaponNode.angle = rotationAngle;
  1285. }
  1286. */
  1287. // 设置特定武器和形状的旋转角度
  1288. public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
  1289. if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1290. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
  1291. }
  1292. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
  1293. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1294. }
  1295. // 设置默认形状的旋转角度
  1296. public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
  1297. this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
  1298. console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1299. }
  1300. // 获取特定武器和形状的旋转角度
  1301. public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
  1302. if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1303. return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1304. }
  1305. return 0;
  1306. }
  1307. // 获取默认形状的旋转角度
  1308. public getDefaultShapeRotationAngle(shapeId: string): number {
  1309. return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1310. }
  1311. // 设置特定武器和形状的旋转角度
  1312. public setWeaponShapeTransform(weaponId: string, shapeId: string, angle: number) {
  1313. this.setWeaponShapeRotationAngle(weaponId, shapeId, angle);
  1314. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度: ${angle}度`);
  1315. }
  1316. // 设置默认形状的旋转角度
  1317. public setDefaultShapeTransform(shapeId: string, angle: number) {
  1318. this.setDefaultShapeRotationAngle(shapeId, angle);
  1319. console.log(`已更新默认形状 ${shapeId} 的旋转角度: ${angle}度`);
  1320. }
  1321. // 重新应用所有已放置方块的武器图标位置和旋转
  1322. public refreshAllWeaponIconRotations() {
  1323. // 遍历所有已放置的方块
  1324. if (this.placedBlocksContainer) {
  1325. this.placedBlocksContainer.children.forEach(block => {
  1326. const weaponConfig = this.getBlockWeaponConfig(block);
  1327. if (weaponConfig) {
  1328. const b1Node = block.getChildByName('B1');
  1329. if (b1Node) {
  1330. const weaponNode = b1Node.getChildByName('Weapon');
  1331. if (weaponNode) {
  1332. const shapeId = this.getBlockShape(block);
  1333. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1334. }
  1335. }
  1336. }
  1337. });
  1338. }
  1339. // 遍历kuang区域的方块
  1340. this.blocks.forEach(block => {
  1341. const weaponConfig = this.getBlockWeaponConfig(block);
  1342. if (weaponConfig) {
  1343. const b1Node = block.getChildByName('B1');
  1344. if (b1Node) {
  1345. const weaponNode = b1Node.getChildByName('Weapon');
  1346. if (weaponNode) {
  1347. const shapeId = this.getBlockShape(block);
  1348. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1349. }
  1350. }
  1351. }
  1352. });
  1353. }
  1354. // 根据方块获取武器配置
  1355. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  1356. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  1357. }
  1358. // 获取方块的武器ID
  1359. public getBlockWeaponId(block: Node): string | null {
  1360. const weaponConfig = this.getBlockWeaponConfig(block);
  1361. return weaponConfig ? weaponConfig.id : null;
  1362. }
  1363. // 获取方块的形状
  1364. public getBlockShape(block: Node): string | null {
  1365. const weaponConfig = this.getBlockWeaponConfig(block);
  1366. if (!weaponConfig) return null;
  1367. // 从方块结构推断形状
  1368. return this.inferBlockShapeFromStructure(block);
  1369. }
  1370. // 获取方块的详细形状信息(包括形状ID和名称)
  1371. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  1372. const actualShape = this.extractShapeFromBlock(block);
  1373. let blockShapes = null;
  1374. // 优先使用预加载的配置
  1375. if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
  1376. blockShapes = this.preloadedWeaponsConfig.blockSizes;
  1377. } else {
  1378. // 回退到ConfigManager
  1379. blockShapes = this.configManager.getBlockShapes();
  1380. }
  1381. if (!blockShapes) return null;
  1382. // 寻找匹配的形状配置
  1383. for (const shapeConfig of blockShapes) {
  1384. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1385. return {
  1386. id: shapeConfig.id,
  1387. name: shapeConfig.name,
  1388. shape: shapeConfig.shape
  1389. };
  1390. }
  1391. }
  1392. return null;
  1393. }
  1394. // 从方块结构推断形状
  1395. private inferBlockShapeFromStructure(block: Node): string {
  1396. // 直接从B1节点结构读取形状矩阵
  1397. const actualShape = this.extractShapeFromBlock(block);
  1398. // 返回默认形状ID,实际形状矩阵已通过extractShapeFromBlock获取
  1399. return 'I';
  1400. }
  1401. // 从方块实例中提取形状矩阵
  1402. private extractShapeFromBlock(block: Node): number[][] {
  1403. const parts = this.getBlockParts(block);
  1404. // 创建4x4矩阵
  1405. const matrix: number[][] = [];
  1406. for (let i = 0; i < 4; i++) {
  1407. matrix[i] = [0, 0, 0, 0];
  1408. }
  1409. // 找到最小坐标作为偏移基准
  1410. let minX = 0, minY = 0;
  1411. for (const part of parts) {
  1412. minX = Math.min(minX, part.x);
  1413. minY = Math.min(minY, part.y);
  1414. }
  1415. // 填充矩阵,将坐标标准化到从(0,0)开始
  1416. for (const part of parts) {
  1417. const matrixX = part.x - minX;
  1418. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  1419. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  1420. matrix[matrixY][matrixX] = 1;
  1421. }
  1422. }
  1423. // 移除矩阵翻转操作,保持原始坐标系
  1424. return matrix;
  1425. }
  1426. // 比较两个形状矩阵是否相同
  1427. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  1428. if (matrix1.length !== matrix2.length) return false;
  1429. for (let i = 0; i < matrix1.length; i++) {
  1430. if (matrix1[i].length !== matrix2[i].length) return false;
  1431. for (let j = 0; j < matrix1[i].length; j++) {
  1432. if (matrix1[i][j] !== matrix2[i][j]) return false;
  1433. }
  1434. }
  1435. return true;
  1436. }
  1437. // 检查两个方块是否可以合成(相同形状相同种类)
  1438. private canMergeBlocks(block1: Node, block2: Node): boolean {
  1439. // 检查稀有度
  1440. const rarity1 = this.getBlockRarity(block1);
  1441. const rarity2 = this.getBlockRarity(block2);
  1442. if (rarity1 !== rarity2) {
  1443. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  1444. return false;
  1445. }
  1446. // 检查武器ID(种类)
  1447. const weaponId1 = this.getBlockWeaponId(block1);
  1448. const weaponId2 = this.getBlockWeaponId(block2);
  1449. if (weaponId1 !== weaponId2) {
  1450. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  1451. return false;
  1452. }
  1453. // 使用精确的形状矩阵比较
  1454. const shape1 = this.extractShapeFromBlock(block1);
  1455. const shape2 = this.extractShapeFromBlock(block2);
  1456. if (!this.compareShapeMatrices(shape1, shape2)) {
  1457. console.log(`[BlockManager] 形状矩阵不匹配`);
  1458. return false;
  1459. }
  1460. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  1461. return true;
  1462. }
  1463. // 刷新方块 - 重新生成三个新的武器方块
  1464. public refreshBlocks() {
  1465. // 移除PlacedBlocks容器中所有方块的标签
  1466. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1467. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1468. }
  1469. // 保存已放置方块的占用信息
  1470. const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  1471. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1472. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1473. const block = this.placedBlocksContainer.children[i];
  1474. const occupiedGrids = block['occupiedGrids'];
  1475. if (occupiedGrids && occupiedGrids.length > 0) {
  1476. placedBlocksOccupation.push({
  1477. block: block,
  1478. occupiedGrids: [...occupiedGrids]
  1479. });
  1480. }
  1481. }
  1482. }
  1483. // 生成新的方块
  1484. this.generateRandomBlocksInKuang();
  1485. }
  1486. // 检查是否有已放置的方块
  1487. public hasPlacedBlocks(): boolean {
  1488. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1489. console.log('[BlockManager] PlacedBlocks容器无效');
  1490. return false;
  1491. }
  1492. const blockCount = this.placedBlocksContainer.children.length;
  1493. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1494. // 检查容器中是否有子节点(方块)
  1495. return blockCount > 0;
  1496. }
  1497. /* =================== 合成逻辑 =================== */
  1498. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  1499. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1500. public async tryMergeBlock(block: Node) {
  1501. try {
  1502. const rarity = this.getBlockRarity(block);
  1503. if (!rarity) return;
  1504. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1505. if (!this.placedBlocksContainer) return;
  1506. const blockBB = this.getWorldAABB(block);
  1507. for (const other of this.placedBlocksContainer.children) {
  1508. if (other === block) continue;
  1509. // 使用新的合成检查方法
  1510. if (!this.canMergeBlocks(block, other)) continue;
  1511. const otherBB = this.getWorldAABB(other);
  1512. if (this.rectIntersects(blockBB, otherBB)) {
  1513. // 找到合成目标
  1514. await this.performMerge(block, other, rarity);
  1515. break;
  1516. }
  1517. }
  1518. } catch (error) {
  1519. console.error('[BlockManager] tryMergeBlock 发生错误:', error);
  1520. // 合成失败不影响游戏继续,只记录错误
  1521. }
  1522. }
  1523. private async performMerge(target: Node, source: Node, rarity: string) {
  1524. try {
  1525. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1526. // 隐藏价格标签并处理 db 关联
  1527. this.hidePriceLabel(source);
  1528. const srcDb = source['dbNode'];
  1529. if (srcDb) srcDb.active = false;
  1530. // 销毁被合并方块
  1531. source.destroy();
  1532. // 升级稀有度
  1533. const nextRarity = this.getNextRarity(rarity);
  1534. if (nextRarity) {
  1535. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1536. // 获取当前武器配置
  1537. const currentConfig = this.blockWeaponConfigs.get(target);
  1538. if (currentConfig) {
  1539. // 保存原始武器名称用于日志输出
  1540. const originalWeaponName = currentConfig.name;
  1541. try {
  1542. // 获取当前关卡允许的武器列表
  1543. const levelWeapons = await this.getCurrentLevelWeapons();
  1544. // 检查是否应该限制在关卡配置的武器范围内
  1545. if (levelWeapons.length > 0) {
  1546. // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
  1547. if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
  1548. console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
  1549. }
  1550. // 无论如何,都只升级稀有度,不改变武器类型
  1551. const upgradedConfig = { ...currentConfig };
  1552. upgradedConfig.rarity = nextRarity;
  1553. this.blockWeaponConfigs.set(target, upgradedConfig);
  1554. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1555. (target as any)['weaponConfig'] = upgradedConfig;
  1556. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1557. } else {
  1558. // 如果没有关卡配置限制,正常升级稀有度
  1559. const upgradedConfig = { ...currentConfig };
  1560. upgradedConfig.rarity = nextRarity;
  1561. this.blockWeaponConfigs.set(target, upgradedConfig);
  1562. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1563. (target as any)['weaponConfig'] = upgradedConfig;
  1564. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1565. }
  1566. } catch (weaponError) {
  1567. console.error('[BlockManager] 获取关卡武器配置失败:', weaponError);
  1568. // 武器配置获取失败时,仍然升级稀有度
  1569. const upgradedConfig = { ...currentConfig };
  1570. upgradedConfig.rarity = nextRarity;
  1571. this.blockWeaponConfigs.set(target, upgradedConfig);
  1572. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1573. (target as any)['weaponConfig'] = upgradedConfig;
  1574. console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1575. }
  1576. }
  1577. // 更新方块颜色
  1578. this.setBlockRarityColor(target, nextRarity);
  1579. }
  1580. // 播放烟雾动画
  1581. const worldPos = new Vec3();
  1582. target.getWorldPosition(worldPos);
  1583. this.spawnMergeSmoke(worldPos);
  1584. // 递归检查是否还能继续合成
  1585. if (nextRarity) {
  1586. await this.tryMergeBlock(target);
  1587. }
  1588. console.log(`[BlockManager] 合成完成`);
  1589. } catch (error) {
  1590. console.error('[BlockManager] performMerge 发生错误:', error);
  1591. // 合成失败时重新抛出错误,让上层处理
  1592. throw error;
  1593. }
  1594. }
  1595. private getBlockRarity(block: Node): string | null {
  1596. const cfg = this.blockWeaponConfigs.get(block);
  1597. if (cfg) return cfg.rarity;
  1598. // fallback based on sprite color maybe
  1599. return null;
  1600. }
  1601. private getNextRarity(rarity: string): string | null {
  1602. const idx = this.rarityOrder.indexOf(rarity);
  1603. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1604. return this.rarityOrder[idx + 1];
  1605. }
  1606. private getWorldAABB(node: Node): Rect {
  1607. const ui = node.getComponent(UITransform);
  1608. if (!ui) return new Rect();
  1609. const pos = node.worldPosition;
  1610. const width = ui.width;
  1611. const height = ui.height;
  1612. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1613. }
  1614. private rectIntersects(a: Rect, b: Rect): boolean {
  1615. return a.x < b.x + b.width &&
  1616. a.x + a.width > b.x &&
  1617. a.y < b.y + b.height &&
  1618. a.y + a.height > b.y;
  1619. }
  1620. /** 生成烟雾特效 */
  1621. private spawnMergeSmoke(worldPos: Vec3) {
  1622. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1623. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1624. if (err || !sData) {
  1625. console.warn('加载合成烟雾动画失败', err);
  1626. return;
  1627. }
  1628. const node = new Node('MergeSmoke');
  1629. const skeleton = node.addComponent(sp.Skeleton);
  1630. skeleton.skeletonData = sData;
  1631. skeleton.premultipliedAlpha = false;
  1632. skeleton.setAnimation(0, 'animation', false);
  1633. skeleton.setCompleteListener(() => node.destroy());
  1634. const canvas = find('Canvas');
  1635. if (canvas) canvas.addChild(node);
  1636. node.setWorldPosition(worldPos);
  1637. });
  1638. }
  1639. /** 在放置失败时尝试与现有方块进行合成 */
  1640. public tryMergeOnOverlap(draggedBlock: Node): boolean {
  1641. if (!this.placedBlocksContainer) return false;
  1642. const rarity = this.getBlockRarity(draggedBlock);
  1643. if (!rarity) return false;
  1644. const dragBB = this.getWorldAABB(draggedBlock);
  1645. for (const target of this.placedBlocksContainer.children) {
  1646. if (target === draggedBlock) continue;
  1647. // 使用新的合成检查方法
  1648. if (!this.canMergeBlocks(draggedBlock, target)) continue;
  1649. const targetBB = this.getWorldAABB(target);
  1650. if (this.rectIntersects(dragBB, targetBB)) {
  1651. // 执行合并:目标保留,拖拽方块销毁
  1652. this.performMerge(target, draggedBlock, rarity);
  1653. return true;
  1654. }
  1655. }
  1656. return false;
  1657. }
  1658. // 调试绘制功能已迁移到GameBlockSelection
  1659. // 输出格子占用情况矩阵
  1660. public printGridOccupationMatrix() {
  1661. console.log('[BlockManager] 格子占用情况de矩阵 (6行11列):');
  1662. for (let row = 0; row < this.GRID_ROWS; row++) {
  1663. let rowStr = '';
  1664. for (let col = 0; col < this.GRID_COLS; col++) {
  1665. rowStr += this.gridOccupationMap[row][col] + ' ';
  1666. }
  1667. console.log(`第${row + 1}行: ${rowStr.trim()}`);
  1668. }
  1669. }
  1670. // 通过GameBlockSelection刷新方块占用情况
  1671. onDestroy() {
  1672. // 调试绘制功能已迁移到GameBlockSelection
  1673. // 清理事件监听
  1674. const eventBus = EventBus.getInstance();
  1675. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  1676. eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  1677. // 移除GAME_START事件清理,因为已不再监听该事件
  1678. // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1679. eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  1680. }
  1681. }