BlockManager.ts 93 KB

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