BlockManager.ts 104 KB

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