BlockManager.ts 102 KB

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