BlockManager.ts 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570
  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. const priceNode = this.blockPriceMap.get(block);
  604. if (location === 'grid') {
  605. // 方块在网格区域时,隐藏价格标签
  606. if (priceNode) {
  607. priceNode.active = false;
  608. }
  609. return;
  610. }
  611. // 检查方块是否正在被拖动,如果是则隐藏价格标签
  612. if (block['isDragging']) {
  613. if (priceNode) {
  614. priceNode.active = false;
  615. }
  616. return;
  617. }
  618. // 方块在Block容器区域时,显示价格标签
  619. if (priceNode && location && location.startsWith('block')) {
  620. priceNode.active = true;
  621. }
  622. }
  623. });
  624. }
  625. // 保留原方法以兼容可能的调用(现在委托给新方法)
  626. associateDbNodeWithBlock(block: Node, dbNode: Node) {
  627. this.associateBlockContainerWithBlock(block, dbNode);
  628. }
  629. // 更新金币显示
  630. updateCoinDisplay() {
  631. if (this.coinLabelNode) {
  632. const label = this.coinLabelNode.getComponent(Label);
  633. if (label) {
  634. const coins = this.session.getCoins();
  635. label.string = coins.toString();
  636. }
  637. }
  638. }
  639. // 获取方块价格
  640. getBlockPrice(block: Node): number {
  641. const priceNode = this.blockPriceMap.get(block);
  642. if (priceNode) {
  643. const label = priceNode.getComponent(Label);
  644. if (label) {
  645. const price = parseInt(label.string);
  646. if (!isNaN(price)) {
  647. return price;
  648. }
  649. }
  650. }
  651. return 50;
  652. }
  653. // 隐藏价格标签
  654. hidePriceLabel(block: Node) {
  655. const priceNode = this.blockPriceMap.get(block);
  656. if (priceNode) {
  657. priceNode.active = false;
  658. }
  659. }
  660. // 显示价格标签
  661. showPriceLabel(block: Node) {
  662. const priceNode = this.blockPriceMap.get(block);
  663. if (priceNode) {
  664. priceNode.active = true;
  665. }
  666. }
  667. // 扣除玩家金币
  668. deductPlayerCoins(amount: number): boolean {
  669. const success = this.session.spendCoins(amount);
  670. if (success) {
  671. this.updateCoinDisplay();
  672. }
  673. return success;
  674. }
  675. // 显示金币不足时的价格标签闪烁效果
  676. showInsufficientCoinsEffect(block: Node) {
  677. const priceNode = this.blockPriceMap.get(block);
  678. if (!priceNode) {
  679. console.warn('[BlockManager] 找不到方块对应的价格标签');
  680. return;
  681. }
  682. const label = priceNode.getComponent(Label);
  683. if (!label) {
  684. console.warn('[BlockManager] 价格节点缺少Label组件');
  685. return;
  686. }
  687. // 保存原始颜色
  688. const originalColor = label.color.clone();
  689. // 设置红色
  690. const redColor = new Color(255, 0, 0, 255);
  691. // 创建闪烁动画:变红 -> 恢复原色,重复3次,总时长2秒
  692. tween(label)
  693. .to(0.2, { color: redColor })
  694. .to(0.2, { color: originalColor })
  695. .to(0.2, { color: redColor })
  696. .to(0.2, { color: originalColor })
  697. .to(0.2, { color: redColor })
  698. .to(1.0, { color: originalColor })
  699. .start();
  700. // 发送显示资源不足Toast事件
  701. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  702. message: '金币不足',
  703. duration: 2.0
  704. });
  705. console.log('[BlockManager] 显示金币不足效果');
  706. }
  707. // 归还玩家金币
  708. refundPlayerCoins(amount: number) {
  709. this.session.addCoins(amount);
  710. this.updateCoinDisplay();
  711. }
  712. // 设置拖拽事件方法已迁移到GameBlockSelection
  713. // 清除临时保存的占用状态
  714. clearTempStoredOccupiedGrids(block: Node) {
  715. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  716. if (index === -1) return;
  717. this.tempRemovedOccupiedGrids.splice(index, 1);
  718. }
  719. // 清除特定方块的占用状态
  720. public clearOccupiedPositions(block: Node) {
  721. if (!this.gridInitialized) return;
  722. const occupiedGrids = block['occupiedGrids'];
  723. if (!occupiedGrids || occupiedGrids.length === 0) return;
  724. // 清除网格占用状态
  725. for (const grid of occupiedGrids) {
  726. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  727. grid.col >= 0 && grid.col < this.GRID_COLS) {
  728. this.gridOccupationMap[grid.row][grid.col] = 0;
  729. }
  730. }
  731. // 清除方块的占用记录
  732. block['occupiedGrids'] = [];
  733. }
  734. // 尝试将方块放置到网格中
  735. tryPlaceBlockToGrid(block: Node): boolean {
  736. console.log(`[BlockManager] 尝试放置方块 ${block.name} 到网格`);
  737. if (!this.gridContainer || !this.gridInitialized) {
  738. console.log(`[BlockManager] 网格容器或网格未初始化`);
  739. return false;
  740. }
  741. let b1Node = block;
  742. if (block.name !== 'B1') {
  743. b1Node = block.getChildByName('B1');
  744. if (!b1Node) {
  745. console.log(`[BlockManager] 方块 ${block.name} 没有B1子节点`);
  746. return false;
  747. }
  748. }
  749. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  750. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  751. console.log(`[BlockManager] B1世界坐标:`, b1WorldPos);
  752. console.log(`[BlockManager] 网格本地坐标:`, gridPos);
  753. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  754. const halfWidth = gridSize.width / 2;
  755. const halfHeight = gridSize.height / 2;
  756. const tolerance = this.gridSpacing * 0.5;
  757. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  758. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  759. console.log(`[BlockManager] 方块超出网格边界`);
  760. return false;
  761. }
  762. const nearestGrid = this.findNearestGridNode(gridPos);
  763. if (!nearestGrid) {
  764. console.log(`[BlockManager] 找不到最近的网格节点`);
  765. return false;
  766. }
  767. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  768. }
  769. // 找到最近的网格节点
  770. public findNearestGridNode(position: Vec3): Node {
  771. if (!this.gridContainer || !this.gridInitialized) return null;
  772. let nearestNode: Node = null;
  773. let minDistance = Number.MAX_VALUE;
  774. for (let row = 0; row < this.GRID_ROWS; row++) {
  775. for (let col = 0; col < this.GRID_COLS; col++) {
  776. const grid = this.gridNodes[row][col];
  777. if (grid) {
  778. const distance = Vec3.distance(position, grid.position);
  779. if (distance < minDistance) {
  780. minDistance = distance;
  781. nearestNode = grid;
  782. }
  783. }
  784. }
  785. }
  786. if (minDistance > this.gridSpacing * 2) {
  787. return null;
  788. }
  789. return nearestNode;
  790. }
  791. // 尝试将方块放置到指定的网格节点
  792. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  793. let b1Node = block;
  794. if (block.name !== 'B1') {
  795. b1Node = block.getChildByName('B1');
  796. if (!b1Node) {
  797. return false;
  798. }
  799. }
  800. if (!this.canPlaceBlockAt(block, targetGrid)) {
  801. return false;
  802. }
  803. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  804. const targetWorldPos = gridCenterWorldPos.clone();
  805. const b1LocalPos = b1Node.position.clone();
  806. let rootTargetWorldPos;
  807. if (b1Node === block) {
  808. rootTargetWorldPos = targetWorldPos.clone();
  809. } else {
  810. rootTargetWorldPos = new Vec3(
  811. targetWorldPos.x - b1LocalPos.x,
  812. targetWorldPos.y - b1LocalPos.y,
  813. targetWorldPos.z
  814. );
  815. }
  816. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  817. block.position = rootTargetLocalPos;
  818. this.markOccupiedPositions(block, targetGrid);
  819. // 当方块从kuang区域拖到网格时,恢复植物图标的正常缩放
  820. // 根据新的预制体结构,武器节点直接位于方块根节点下
  821. let weaponNode = block.getChildByName('Weapon');
  822. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  823. if (!weaponNode && b1Node) {
  824. weaponNode = b1Node.getChildByName('Weapon');
  825. }
  826. if (weaponNode) {
  827. weaponNode.setScale(0.4, 0.4, 1.0);
  828. console.log(`[BlockManager] 方块 ${block.name} 放置到网格,植物图标缩放设置为0.4倍`);
  829. }
  830. return true;
  831. }
  832. // 检查方块是否可以放置在指定位置
  833. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  834. if (!this.gridInitialized) {
  835. console.log(`[BlockManager] 网格未初始化`);
  836. return false;
  837. }
  838. const targetRowCol = this.getGridRowCol(targetGrid);
  839. if (!targetRowCol) {
  840. console.log(`[BlockManager] 无法获取目标网格的行列信息`);
  841. return false;
  842. }
  843. const parts = this.getBlockParts(block);
  844. for (let i = 0; i < parts.length; i++) {
  845. const part = parts[i];
  846. const row = targetRowCol.row - part.y;
  847. const col = targetRowCol.col + part.x;
  848. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  849. console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`);
  850. return false;
  851. }
  852. if (this.gridOccupationMap[row][col] === 1) {
  853. console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`);
  854. return false;
  855. }
  856. }
  857. return true;
  858. }
  859. // 获取网格行列索引
  860. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  861. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  862. const parts = gridNode.name.split('_');
  863. if (parts.length === 3) {
  864. const row = parseInt(parts[1]);
  865. const col = parseInt(parts[2]);
  866. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  867. return { row, col };
  868. }
  869. }
  870. return null;
  871. }
  872. // 获取指定行列的网格世界坐标(用于调试绘制)
  873. public getGridWorldPosition(row: number, col: number): Vec3 | null {
  874. if (!this.gridInitialized || !this.gridNodes[row] || !this.gridNodes[row][col]) {
  875. return null;
  876. }
  877. const gridNode = this.gridNodes[row][col];
  878. return this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(gridNode.position);
  879. }
  880. // 获取方块的所有部分节点及其相对坐标
  881. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  882. const parts: { node: Node, x: number, y: number }[] = [];
  883. // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
  884. const b1Node = block.getChildByName('B1');
  885. if (b1Node) {
  886. // B1节点作为形状的根节点和坐标原点(0,0)
  887. // 将B1节点本身添加为第一个部分
  888. parts.push({ node: b1Node, x: 0, y: 0 });
  889. // 然后递归查找B1的子节点,但要避免重复添加B1本身
  890. this.findBlockParts(b1Node, parts, 0, 0, true);
  891. } else {
  892. // 没有B1节点,使用根节点作为形状根节点
  893. parts.push({ node: block, x: 0, y: 0 });
  894. this.findBlockParts(block, parts, 0, 0, false);
  895. }
  896. return parts;
  897. }
  898. // 递归查找方块的所有部分
  899. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number, skipRoot: boolean = false) {
  900. for (let i = 0; i < node.children.length; i++) {
  901. const child = node.children[i];
  902. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  903. continue;
  904. }
  905. let x = parentX;
  906. let y = parentY;
  907. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  908. if (match) {
  909. x = parseInt(match[1]);
  910. y = parseInt(match[2]);
  911. result.push({ node: child, x, y });
  912. } else if (child.name.startsWith('B')) {
  913. const relativeX = Math.round(child.position.x / this.gridSpacing);
  914. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  915. x = parentX + relativeX;
  916. y = parentY + relativeY;
  917. // 避免重复添加已经在result中的节点
  918. const existingPart = result.find(part => part.node === child);
  919. if (!existingPart) {
  920. result.push({ node: child, x, y });
  921. }
  922. }
  923. this.findBlockParts(child, result, x, y, false);
  924. }
  925. }
  926. // 标记方块占用的格子
  927. public markOccupiedPositions(block: Node, targetGrid: Node) {
  928. if (!this.gridInitialized) return;
  929. const targetRowCol = this.getGridRowCol(targetGrid);
  930. if (!targetRowCol) return;
  931. const parts = this.getBlockParts(block);
  932. block['occupiedGrids'] = [];
  933. for (const part of parts) {
  934. const row = targetRowCol.row - part.y;
  935. const col = targetRowCol.col + part.x;
  936. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  937. this.gridOccupationMap[row][col] = 1;
  938. block['occupiedGrids'] = block['occupiedGrids'] || [];
  939. block['occupiedGrids'].push({ row, col });
  940. }
  941. }
  942. }
  943. // 清除方块
  944. clearBlocks() {
  945. console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
  946. const blocksToRemove = [];
  947. for (const block of this.blocks) {
  948. if (block.isValid) {
  949. const location = this.blockLocations.get(block);
  950. // 清除kuang区域和Block容器中的方块
  951. if (location === 'kuang' || location === 'block1' || location === 'block2' || location === 'block3') {
  952. blocksToRemove.push(block);
  953. }
  954. }
  955. }
  956. console.log('[BlockManager] 找到需要清理的方块数量:', blocksToRemove.length);
  957. for (const block of blocksToRemove) {
  958. const dbNode = block['dbNode'];
  959. if (dbNode && dbNode.isValid) {
  960. block.off(Node.EventType.TRANSFORM_CHANGED);
  961. const kuangNode = this.kuangContainer;
  962. if (kuangNode) {
  963. const dbName = dbNode.name;
  964. if (!kuangNode.getChildByName(dbName)) {
  965. dbNode.parent = kuangNode;
  966. }
  967. }
  968. }
  969. const index = this.blocks.indexOf(block);
  970. if (index !== -1) {
  971. this.blocks.splice(index, 1);
  972. }
  973. this.originalPositions.delete(block);
  974. this.blockLocations.delete(block);
  975. this.blockPriceMap.delete(block);
  976. // 清理武器配置映射
  977. this.blockWeaponConfigs.delete(block);
  978. console.log('[BlockManager] 销毁方块:', block.name, '位置:', this.blockLocations.get(block));
  979. block.destroy();
  980. }
  981. console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
  982. }
  983. // 游戏开始时调用
  984. onGameStart() {
  985. this.gameStarted = true;
  986. for (const block of this.blocks) {
  987. if (block.isValid) {
  988. const location = this.blockLocations.get(block);
  989. if (location === 'grid') {
  990. const dbNode = block['dbNode'];
  991. if (dbNode) {
  992. dbNode.active = false;
  993. }
  994. this.moveBlockToPlacedBlocks(block);
  995. this.addLockedVisualHint(block);
  996. // 游戏开始后放置的方块移除标签,不能再放回kuang
  997. BlockTag.removeTag(block);
  998. }
  999. }
  1000. }
  1001. }
  1002. // 游戏重置时调用
  1003. onGameReset() {
  1004. console.log('[BlockManager] 游戏重置,清理所有状态');
  1005. console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
  1006. this.gameStarted = false;
  1007. this.clearAllCooldowns();
  1008. // 清理已放置的方块
  1009. console.log('[BlockManager] 开始清理已放置的方块');
  1010. this.clearPlacedBlocks();
  1011. // 重置网格占用状态
  1012. console.log('[BlockManager] 开始重置网格占用状态');
  1013. this.resetGridOccupation();
  1014. // 清理kuang区域的方块
  1015. console.log('[BlockManager] 开始清理kuang区域的方块');
  1016. this.clearBlocks();
  1017. // 清理所有方块标签
  1018. console.log('[BlockManager] 开始清理所有方块标签');
  1019. BlockTag.clearAllTags();
  1020. console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
  1021. console.log('[BlockManager] 游戏重置完成 - 方块生成将由StartGame流程处理');
  1022. }
  1023. // 清理已放置的方块
  1024. private clearPlacedBlocks() {
  1025. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1026. console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
  1027. return;
  1028. }
  1029. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  1030. // 清理PlacedBlocks容器中的所有方块
  1031. const placedBlocks = [...this.placedBlocksContainer.children];
  1032. let clearedCount = 0;
  1033. for (const block of placedBlocks) {
  1034. if (block && block.isValid) {
  1035. // 从blocks数组中移除
  1036. const index = this.blocks.indexOf(block);
  1037. if (index !== -1) {
  1038. this.blocks.splice(index, 1);
  1039. }
  1040. // 清理相关映射
  1041. this.originalPositions.delete(block);
  1042. this.blockLocations.delete(block);
  1043. this.blockPriceMap.delete(block);
  1044. this.blockWeaponConfigs.delete(block);
  1045. console.log('[BlockManager] 销毁已放置方块:', block.name);
  1046. // 销毁方块
  1047. block.destroy();
  1048. clearedCount++;
  1049. }
  1050. }
  1051. console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
  1052. }
  1053. // 重置网格占用状态
  1054. public resetGridOccupation() {
  1055. console.log('[BlockManager] 重置网格占用状态');
  1056. // 重新初始化网格占用地图
  1057. this.gridOccupationMap = [];
  1058. for (let row = 0; row < this.GRID_ROWS; row++) {
  1059. this.gridOccupationMap[row] = [];
  1060. for (let col = 0; col < this.GRID_COLS; col++) {
  1061. this.gridOccupationMap[row][col] = 0;
  1062. }
  1063. }
  1064. // 清理临时存储的占用状态
  1065. this.tempRemovedOccupiedGrids = [];
  1066. }
  1067. // 添加视觉提示,表明方块已锁定
  1068. addLockedVisualHint(block: Node) {
  1069. const children = block.children;
  1070. for (let i = 0; i < children.length; i++) {
  1071. const child = children[i];
  1072. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  1073. continue;
  1074. }
  1075. child.setScale(new Vec3(0.95, 0.95, 1));
  1076. }
  1077. }
  1078. // 将方块移动到PlacedBlocks节点下
  1079. moveBlockToPlacedBlocks(block: Node) {
  1080. if (!this.placedBlocksContainer) {
  1081. console.error('PlacedBlocks容器未设置');
  1082. return;
  1083. }
  1084. if (!this.placedBlocksContainer.isValid) {
  1085. console.error('PlacedBlocks容器已失效');
  1086. return;
  1087. }
  1088. const worldPosition = new Vec3();
  1089. block.getWorldPosition(worldPosition);
  1090. // 移除旧的触摸事件监听器
  1091. block.off(Node.EventType.TOUCH_START);
  1092. block.off(Node.EventType.TOUCH_MOVE);
  1093. block.off(Node.EventType.TOUCH_END);
  1094. block.off(Node.EventType.TOUCH_CANCEL);
  1095. block.removeFromParent();
  1096. this.placedBlocksContainer.addChild(block);
  1097. block.setWorldPosition(worldPosition);
  1098. // 通过事件机制重新设置拖拽事件
  1099. const eventBus = EventBus.getInstance();
  1100. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]);
  1101. console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`);
  1102. }
  1103. // 根据武器配置选择合适的预制体
  1104. private selectPrefabForWeapon(weaponConfig: WeaponConfig, targetShapeId?: string): Prefab | null {
  1105. if (this.blockPrefabs.length === 0) {
  1106. return null;
  1107. }
  1108. // 如果指定了目标形状ID,尝试找到匹配的预制体
  1109. if (targetShapeId) {
  1110. const matchingPrefab = this.findPrefabByShape(targetShapeId);
  1111. if (matchingPrefab) {
  1112. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 找到匹配形状 ${targetShapeId} 的预制体`);
  1113. return matchingPrefab;
  1114. }
  1115. }
  1116. // 如果没有指定形状或没有找到匹配的预制体,使用随机选择
  1117. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  1118. const selectedPrefab = this.blockPrefabs[randomIndex];
  1119. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 选择随机预制体 (索引: ${randomIndex})`);
  1120. return selectedPrefab;
  1121. }
  1122. // 根据形状ID查找匹配的预制体(按照Block+形状ID的命名规则)
  1123. private findPrefabByShape(targetShapeId: string): Prefab | null {
  1124. // 构建预期的预制体名称:Block + 形状ID
  1125. const expectedPrefabName = `Block${targetShapeId}`;
  1126. console.log(`[BlockManager] 寻找形状 ${targetShapeId} 的预制体,期望名称: ${expectedPrefabName}`);
  1127. console.log(`[BlockManager] 当前可用预制体数量: ${this.blockPrefabs.length}`);
  1128. // 输出所有可用预制体的详细信息
  1129. this.blockPrefabs.forEach((prefab, index) => {
  1130. console.log(`[BlockManager] 预制体[${index}]: ${prefab.name} (匹配: ${prefab.name === expectedPrefabName})`);
  1131. });
  1132. for (const prefab of this.blockPrefabs) {
  1133. if (prefab.name === expectedPrefabName) {
  1134. console.log(`[BlockManager] ✓ 找到匹配形状 ${targetShapeId} 的预制体: ${prefab.name}`);
  1135. return prefab;
  1136. }
  1137. }
  1138. console.log(`[BlockManager] ✗ 未找到匹配形状 ${targetShapeId} 的预制体 (期望名称: ${expectedPrefabName})`);
  1139. return null;
  1140. }
  1141. // 根据稀有度设置方块价格
  1142. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  1143. const label = priceNode.getComponent(Label);
  1144. if (!label) {
  1145. return;
  1146. }
  1147. let basePrice: number;
  1148. switch (rarity) {
  1149. case 'common':
  1150. basePrice = 0;
  1151. break;
  1152. case 'uncommon':
  1153. basePrice = 20;
  1154. break;
  1155. case 'rare':
  1156. basePrice = 50;
  1157. break;
  1158. case 'epic':
  1159. basePrice = 100;
  1160. break;
  1161. default:
  1162. basePrice = 0;
  1163. }
  1164. // 应用便宜技能效果
  1165. const skillManager = SkillManager.getInstance();
  1166. let finalPrice = basePrice;
  1167. if (skillManager) {
  1168. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1169. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1170. }
  1171. label.string = finalPrice.toString();
  1172. }
  1173. // 根据武器配置和方块形状设置价格
  1174. private setBlockPriceByWeaponConfig(block: Node, priceNode: Node) {
  1175. const label = priceNode.getComponent(Label);
  1176. if (!label) {
  1177. return;
  1178. }
  1179. // 从Node子节点获取BlockInfo组件(新预制体结构)
  1180. const nodeChild = block.getChildByName('Node');
  1181. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1182. if (!blockInfo) {
  1183. label.string = "10";
  1184. return;
  1185. }
  1186. // 直接使用BlockInfo的shapePrice,如果为0则使用默认价格10
  1187. let basePrice = blockInfo.shapePrice > 0 ? blockInfo.shapePrice : 10;
  1188. // 应用便宜技能效果
  1189. const skillManager = SkillManager.getInstance();
  1190. let finalPrice = basePrice;
  1191. if (skillManager) {
  1192. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1193. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1194. }
  1195. label.string = finalPrice.toString();
  1196. }
  1197. // 计算方块占用的格子数量
  1198. // 设置方块的武器外观
  1199. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig, targetShapeId?: string) {
  1200. // 确保方块节点上也有 weaponConfig 属性
  1201. block['weaponConfig'] = weaponConfig;
  1202. // 如果提供了目标形状ID,直接使用它加载对应的稀有度图片
  1203. if (targetShapeId) {
  1204. this.loadBlockRarityImageByShape(block, weaponConfig.rarity || 'common', targetShapeId);
  1205. } else {
  1206. // 否则使用原有逻辑从方块结构推断形状
  1207. this.loadBlockRarityImage(block, weaponConfig.rarity || 'common');
  1208. }
  1209. // 加载武器图标
  1210. this.loadWeaponIcon(block, weaponConfig);
  1211. }
  1212. /**
  1213. * 设置方块的BlockInfo组件信息
  1214. * @param block 方块节点
  1215. * @param weaponConfig 武器配置
  1216. * @param targetShapeId 目标形状ID
  1217. * @param blockLocation 方块所在位置
  1218. */
  1219. private setupBlockInfo(block: Node, weaponConfig: WeaponConfig, targetShapeId?: string, blockLocation?: string) {
  1220. // 从Node子节点获取BlockInfo组件(新预制体结构)
  1221. const nodeChild = block.getChildByName('Node');
  1222. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1223. if (!blockInfo) {
  1224. console.warn(`[BlockManager] 方块 ${block.name} 没有BlockInfo组件`);
  1225. return;
  1226. }
  1227. // 设置基础信息
  1228. blockInfo.blockName = weaponConfig.name || block.name;
  1229. blockInfo.blockId = weaponConfig.id || weaponConfig.name;
  1230. // 设置稀有度
  1231. const rarityMap = { 'common': 0, 'uncommon': 1, 'rare': 2, 'epic': 3 };
  1232. blockInfo.rarity = rarityMap[weaponConfig.rarity] || 0;
  1233. // 设置稀有度颜色
  1234. blockInfo.rarityColor = this.getRarityColor(weaponConfig.rarity);
  1235. // 设置形状信息
  1236. if (targetShapeId) {
  1237. blockInfo.shapeId = targetShapeId;
  1238. const shapeInfo = this.getBlockShapeInfo(block);
  1239. if (shapeInfo && shapeInfo.shape) {
  1240. // 计算形状大小
  1241. const rows = shapeInfo.shape.length;
  1242. const cols = shapeInfo.shape[0] ? shapeInfo.shape[0].length : 0;
  1243. blockInfo.shapeSize = new cc.Vec2(cols, rows);
  1244. }
  1245. }
  1246. // 设置武器配置(在形状ID设置之后,这样可以正确计算形状价格)
  1247. blockInfo.setWeaponConfig(weaponConfig);
  1248. // 设置位置信息
  1249. blockInfo.currentLocation = blockLocation || 'kuang';
  1250. blockInfo.gridPosition = new cc.Vec2(-1, -1);
  1251. // 设置状态信息
  1252. blockInfo.isPlaced = false;
  1253. blockInfo.isDraggable = true;
  1254. blockInfo.isMergeable = true;
  1255. // 设置方块标签
  1256. const tags = [];
  1257. if (weaponConfig.type) tags.push(weaponConfig.type);
  1258. if (weaponConfig.rarity) tags.push(weaponConfig.rarity);
  1259. if (targetShapeId) tags.push(targetShapeId);
  1260. blockInfo.setBlockTags(tags);
  1261. // 查找稀有度和武器图标
  1262. // 根据新的预制体结构,武器节点直接位于方块根节点下
  1263. let weaponNode = block.getChildByName('Weapon');
  1264. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  1265. if (!weaponNode) {
  1266. const b1Node = block.getChildByName('B1');
  1267. if (b1Node) {
  1268. weaponNode = b1Node.getChildByName('Weapon');
  1269. }
  1270. }
  1271. if (weaponNode) {
  1272. const weaponSprite = weaponNode.getComponent(Sprite);
  1273. if (weaponSprite) {
  1274. blockInfo.weaponSprite = weaponSprite;
  1275. }
  1276. }
  1277. // 更新显示
  1278. blockInfo.updatePriceDisplay();
  1279. blockInfo.updateRarityDisplay();
  1280. console.log(`[BlockManager] 已设置方块 ${block.name} 的BlockInfo组件信息`);
  1281. }
  1282. /**
  1283. * 获取稀有度对应的颜色
  1284. * @param rarity 稀有度
  1285. * @returns 颜色对象
  1286. */
  1287. private getRarityColor(rarity: string): cc.Color {
  1288. switch (rarity) {
  1289. case 'common':
  1290. return cc.Color.WHITE;
  1291. case 'uncommon':
  1292. return cc.Color.GREEN;
  1293. case 'rare':
  1294. return cc.Color.BLUE;
  1295. case 'epic':
  1296. return cc.Color.MAGENTA;
  1297. default:
  1298. return cc.Color.WHITE;
  1299. }
  1300. }
  1301. // 设置方块稀有度颜色
  1302. private setBlockRarityColor(block: Node, rarity: string) {
  1303. this.loadBlockRarityImage(block, rarity);
  1304. }
  1305. // 公共方法:应用方块稀有度图片(供外部调用)
  1306. public applyBlockRarityColor(block: Node, rarity: string) {
  1307. // Add null safety check for block
  1308. if (!block || !block.isValid) {
  1309. return;
  1310. }
  1311. // 使用图片替代颜色
  1312. this.loadBlockRarityImage(block, rarity);
  1313. }
  1314. // 根据稀有度和指定形状ID加载对应的图片
  1315. private async loadBlockRarityImageByShape(block: Node, rarity: string, shapeId: string) {
  1316. if (!block || !block.isValid) {
  1317. return;
  1318. }
  1319. console.log(`[BlockManager] 直接使用形状ID ${shapeId} 加载稀有度图片`);
  1320. // 首先尝试从BlockInfo组件获取稀有度图标(新预制体结构)
  1321. const nodeChild = block.getChildByName('Node');
  1322. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1323. if (blockInfo) {
  1324. const rarityIcon = blockInfo.getRarityIcon();
  1325. if (rarityIcon) {
  1326. this.applySpriteFrameToBlock(block, rarityIcon);
  1327. console.log(`[BlockManager] ✓ 从BlockInfo组件获取稀有度图标: ${rarity}`);
  1328. return;
  1329. } else {
  1330. console.warn(`[BlockManager] BlockInfo组件中没有找到稀有度图标,稀有度: ${rarity}`);
  1331. }
  1332. } else {
  1333. console.warn(`[BlockManager] 方块没有BlockInfo组件,回退到路径加载模式`);
  1334. }
  1335. // 回退到原有的路径加载逻辑
  1336. const baseImageName = this.getBaseImageNameByShape(shapeId);
  1337. if (!baseImageName) {
  1338. console.warn(`[BlockManager] 无法映射形状ID ${shapeId} 到图片名称`);
  1339. this.applyBlockRarityColorFallback(block, rarity);
  1340. return;
  1341. }
  1342. // 构建图片路径
  1343. const imagePath = `images/Blocks/${rarity}/${baseImageName}/spriteFrame`;
  1344. console.log(`[BlockManager] 回退加载图片路径: ${imagePath}`);
  1345. try {
  1346. // 优先使用 assetManager.getBundle('resources')
  1347. const resourcesBundle = cc.assetManager.getBundle('resources');
  1348. if (resourcesBundle) {
  1349. resourcesBundle.load(imagePath, SpriteFrame, (err, spriteFrame) => {
  1350. if (err) {
  1351. console.warn(`[BlockManager] Bundle加载失败: ${err.message},尝试使用resources.load`);
  1352. this.loadImageWithResourcesLoad(block, imagePath);
  1353. } else {
  1354. this.applySpriteFrameToBlock(block, spriteFrame);
  1355. console.log(`[BlockManager] ✓ Bundle成功加载图片: ${imagePath}`);
  1356. }
  1357. });
  1358. } else {
  1359. console.warn('[BlockManager] resources bundle不可用,使用resources.load');
  1360. this.loadImageWithResourcesLoad(block, imagePath);
  1361. }
  1362. } catch (error) {
  1363. console.error(`[BlockManager] 加载图片时发生错误: ${error}`);
  1364. this.applyBlockRarityColorFallback(block, rarity);
  1365. }
  1366. }
  1367. // 根据稀有度和方块形状加载对应的图片
  1368. private async loadBlockRarityImage(block: Node, rarity: string) {
  1369. if (!block || !block.isValid) {
  1370. return;
  1371. }
  1372. // 首先尝试从BlockInfo组件获取稀有度图标(新预制体结构)
  1373. const nodeChild = block.getChildByName('Node');
  1374. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1375. if (blockInfo) {
  1376. const rarityIcon = blockInfo.getRarityIcon();
  1377. if (rarityIcon) {
  1378. this.applySpriteFrameToBlock(block, rarityIcon);
  1379. console.log(`[BlockManager] ✓ 从BlockInfo组件获取稀有度图标: ${rarity}`);
  1380. return;
  1381. } else {
  1382. console.warn(`[BlockManager] BlockInfo组件中没有找到稀有度图标,稀有度: ${rarity}`);
  1383. }
  1384. } else {
  1385. console.warn(`[BlockManager] 方块没有BlockInfo组件,回退到路径加载模式`);
  1386. }
  1387. // 回退到原有的路径加载逻辑
  1388. const shapeId = this.getBlockShape(block);
  1389. if (!shapeId) {
  1390. console.warn('[BlockManager] 无法获取方块形状,跳过图片加载');
  1391. this.applyBlockRarityColorFallback(block, rarity);
  1392. return;
  1393. }
  1394. // 使用形状ID加载图片
  1395. this.loadBlockRarityImageByShape(block, rarity, shapeId);
  1396. }
  1397. // 辅助方法:使用resources.load加载图片
  1398. private loadImageWithResourcesLoad(block: Node, imagePath: string) {
  1399. resources.load(imagePath, SpriteFrame, (err, spriteFrame) => {
  1400. if (err) {
  1401. console.error(`[BlockManager] ✗ 图片加载失败: ${imagePath}, 错误: ${err.message}`);
  1402. // 使用颜色回退方案
  1403. const rarity = this.getBlockRarity(block) || 'common';
  1404. this.applyBlockRarityColorFallback(block, rarity);
  1405. } else {
  1406. this.applySpriteFrameToBlock(block, spriteFrame);
  1407. console.log(`[BlockManager] ✓ Resources成功加载图片: ${imagePath}`);
  1408. }
  1409. });
  1410. }
  1411. // 辅助方法:将SpriteFrame应用到方块
  1412. private applySpriteFrameToBlock(block: Node, spriteFrame: SpriteFrame) {
  1413. // 新的预制体结构:Sprite组件在Node子节点上
  1414. const nodeChild = block.getChildByName('Node');
  1415. if (nodeChild) {
  1416. const sprite = nodeChild.getComponent(Sprite);
  1417. if (sprite) {
  1418. sprite.spriteFrame = spriteFrame;
  1419. } else {
  1420. console.warn('[BlockManager] Node子节点没有Sprite组件');
  1421. }
  1422. } else {
  1423. console.warn('[BlockManager] 方块节点没有找到Node子节点');
  1424. }
  1425. }
  1426. // 根据形状ID映射到基础图片名称
  1427. private getBaseImageNameByShape(shapeId: string): string | null {
  1428. // 根据实际图片文件名映射,不包含文件扩展名
  1429. switch (shapeId) {
  1430. case 'I':
  1431. return 'BlockI';
  1432. case 'H-I':
  1433. return 'BlockH-I';
  1434. case 'L':
  1435. case 'L2':
  1436. case 'L3':
  1437. case 'L4':
  1438. return 'BlockL';
  1439. case 'S':
  1440. case 'F-S':
  1441. return 'BlockS';
  1442. case 'T':
  1443. case 'D-T':
  1444. return 'BlockD-T';
  1445. default:
  1446. // 对于未知形状,尝试直接使用形状ID
  1447. return `Block${shapeId}`;
  1448. }
  1449. }
  1450. // 颜色模式回退方法(当图片加载失败时使用)
  1451. private applyBlockRarityColorFallback(block: Node, rarity: string) {
  1452. // 新的预制体结构:Sprite组件在Node子节点上
  1453. const nodeChild = block.getChildByName('Node');
  1454. if (!nodeChild) {
  1455. console.warn('[BlockManager] 方块节点没有找到Node子节点');
  1456. return;
  1457. }
  1458. const sprite = nodeChild.getComponent(Sprite);
  1459. if (!sprite || !sprite.isValid) {
  1460. console.warn('[BlockManager] Node子节点没有Sprite组件');
  1461. return;
  1462. }
  1463. // 根据稀有度设置颜色
  1464. let color: Color;
  1465. switch (rarity) {
  1466. case 'common':
  1467. color = new Color(255, 255, 255); // 白色
  1468. break;
  1469. case 'uncommon':
  1470. color = new Color(0, 255, 0); // 绿色
  1471. break;
  1472. case 'rare':
  1473. color = new Color(0, 100, 255); // 蓝色
  1474. break;
  1475. case 'epic':
  1476. color = new Color(160, 32, 240); // 紫色
  1477. break;
  1478. default:
  1479. color = new Color(255, 255, 255); // 默认白色
  1480. }
  1481. sprite.color = color;
  1482. console.log(`[BlockManager] 回退到颜色模式设置方块稀有度: ${rarity}`, color);
  1483. }
  1484. // 加载武器图标
  1485. private async loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  1486. // 根据新的预制体结构,武器节点直接位于方块根节点下
  1487. let weaponNode = block.getChildByName('Weapon');
  1488. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  1489. if (!weaponNode) {
  1490. const b1Node = block.getChildByName('B1');
  1491. if (b1Node) {
  1492. weaponNode = b1Node.getChildByName('Weapon');
  1493. }
  1494. }
  1495. if (!weaponNode) {
  1496. console.warn('找不到Weapon节点');
  1497. return;
  1498. }
  1499. const weaponSprite = weaponNode.getComponent(Sprite);
  1500. if (!weaponSprite) {
  1501. console.warn('Weapon节点上没有Sprite组件');
  1502. return;
  1503. }
  1504. // 获取武器配置中的图片路径
  1505. const spritePath = weaponConfig.visualConfig?.weaponSprites;
  1506. if (!spritePath) {
  1507. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  1508. return;
  1509. }
  1510. // 正确的SpriteFrame子资源路径
  1511. const spriteFramePath = `${spritePath}/spriteFrame`;
  1512. // 加载SpriteFrame子资源
  1513. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  1514. if (err) {
  1515. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  1516. return;
  1517. }
  1518. // Add comprehensive null safety checks before setting spriteFrame
  1519. if (weaponSprite && weaponSprite.isValid &&
  1520. weaponNode && weaponNode.isValid &&
  1521. block && block.isValid &&
  1522. spriteFrame && spriteFrame.isValid) {
  1523. weaponSprite.spriteFrame = spriteFrame;
  1524. // 设置武器图标初始大小为0.4倍
  1525. weaponNode.setScale(0.4, 0.4, 1.0);
  1526. console.log(`[BlockManager] 武器图标加载完成,设置初始缩放为0.4倍: ${weaponConfig.name}`);
  1527. // 应用武器图标的旋转(不再使用位置偏移)
  1528. const blockShape = this.getBlockShape(block);
  1529. this.rotateWeaponIconByShape(weaponNode, blockShape, weaponConfig.id);
  1530. }
  1531. });
  1532. }
  1533. // 武器类型和方块形状组合的旋转角度配置
  1534. private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
  1535. 'pea_shooter': {
  1536. 'I': 0, // 毛豆射手竖条形状
  1537. 'H-I': 90, // 毛豆射手横条形状
  1538. 'L': 0, // 毛豆射手L型
  1539. 'S': 0, // 毛豆射手S型
  1540. 'D-T': 0 // 毛豆射手倒T型
  1541. },
  1542. 'sharp_carrot': {
  1543. 'I': 0, // 尖胡萝卜竖条形状
  1544. 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
  1545. 'L': -15, // 尖胡萝卜L型,轻微调整
  1546. 'S': 15, // 尖胡萝卜S型,轻微调整
  1547. 'D-T': 0 // 尖胡萝卜倒T型
  1548. },
  1549. 'saw_grass': {
  1550. 'I': 0, // 锯齿草竖条形状
  1551. 'H-I': 0, // 锯齿草横条形状
  1552. 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
  1553. 'S': 30, // 锯齿草S型,适配锯齿弯曲
  1554. 'D-T': 0 // 锯齿草倒T型
  1555. },
  1556. 'watermelon_bomb': {
  1557. 'I': 0, // 西瓜炸弹竖条形状
  1558. 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
  1559. 'L': 0, // 西瓜炸弹L型
  1560. 'S': 0, // 西瓜炸弹S型
  1561. 'D-T': 0 // 西瓜炸弹倒T型
  1562. },
  1563. 'boomerang_plant': {
  1564. 'I': 0, // 回旋镖植物竖条形状
  1565. 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
  1566. 'L': -30, // 回旋镖植物L型
  1567. 'S': -10, // 回旋镖植物S型,适配回旋轨迹
  1568. 'D-T': -80 // 回旋镖植物倒T型
  1569. },
  1570. 'hot_pepper': {
  1571. 'I': 0, // 辣椒竖条形状
  1572. 'H-I': 90, // 辣椒横条形状
  1573. 'L': 0, // 辣椒L型
  1574. 'S': 0, // 辣椒S型
  1575. 'D-T': 0 // 辣椒倒T型
  1576. },
  1577. 'cactus_shotgun': {
  1578. 'I': 0, // 仙人掌霰弹枪竖条形状
  1579. 'H-I': 90, // 仙人掌霰弹枪横条形状
  1580. 'L': -20, // 仙人掌霰弹枪L型
  1581. 'S': 20, // 仙人掌霰弹枪S型
  1582. 'D-T': 0 // 仙人掌霰弹枪倒T型
  1583. },
  1584. 'okra_missile': {
  1585. 'I': 0, // 秋葵导弹竖条形状
  1586. 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
  1587. 'L': -10, // 秋葵导弹L型
  1588. 'S': 10, // 秋葵导弹S型
  1589. 'D-T': 0 // 秋葵导弹倒T型
  1590. },
  1591. 'mace_club': {
  1592. 'I': -45, // 狼牙棒竖条形状
  1593. 'H-I': 0, // 狼牙棒横条形状
  1594. 'L': -90, // 狼牙棒L型,适配棒状武器
  1595. 'S': -90, // 狼牙棒S型
  1596. 'D-T': 0 // 狼牙棒倒T型
  1597. }
  1598. };
  1599. // 默认旋转角度配置(当武器类型未配置时使用)
  1600. private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
  1601. 'I': 0, // 竖条形状,保持原始方向
  1602. 'H-I': 90, // 横I型,旋转90度适配水平方向
  1603. 'L': -15, // L型,轻微左倾适配L形状的转角
  1604. 'S': 15, // S型,轻微右倾适配S形状的弯曲
  1605. 'D-T': 0 // 倒T型,保持原始方向
  1606. };
  1607. // 根据武器类型和方块形状调整武器图标位置(完全保留预制体原始旋转值,不应用额外旋转)
  1608. private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1609. if (!weaponNode || !shapeId) return;
  1610. // 保存预制体的原始旋转角度
  1611. const originalAngle = weaponNode.angle;
  1612. console.log(`保留预制体原始旋转角度: ${originalAngle}度,不应用额外旋转`);
  1613. }
  1614. // 设置特定武器和形状的旋转角度
  1615. public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
  1616. if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1617. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
  1618. }
  1619. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
  1620. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1621. }
  1622. // 设置默认形状的旋转角度
  1623. public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
  1624. this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
  1625. console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1626. }
  1627. // 获取特定武器和形状的旋转角度
  1628. public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
  1629. if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1630. return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1631. }
  1632. return 0;
  1633. }
  1634. // 获取默认形状的旋转角度
  1635. public getDefaultShapeRotationAngle(shapeId: string): number {
  1636. return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1637. }
  1638. // 设置特定武器和形状的旋转角度
  1639. public setWeaponShapeTransform(weaponId: string, shapeId: string, angle: number) {
  1640. this.setWeaponShapeRotationAngle(weaponId, shapeId, angle);
  1641. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度: ${angle}度`);
  1642. }
  1643. // 设置默认形状的旋转角度
  1644. public setDefaultShapeTransform(shapeId: string, angle: number) {
  1645. this.setDefaultShapeRotationAngle(shapeId, angle);
  1646. console.log(`已更新默认形状 ${shapeId} 的旋转角度: ${angle}度`);
  1647. }
  1648. // 重新应用所有已放置方块的武器图标位置和旋转
  1649. public refreshAllWeaponIconRotations() {
  1650. // 遍历所有已放置的方块
  1651. if (this.placedBlocksContainer) {
  1652. this.placedBlocksContainer.children.forEach(block => {
  1653. const weaponConfig = this.getBlockWeaponConfig(block);
  1654. if (weaponConfig) {
  1655. // 根据新的预制体结构:Weapon节点直接在方块根节点下
  1656. let weaponNode = block.getChildByName('Weapon');
  1657. // 向后兼容:如果没找到,尝试旧的B1/Weapon路径
  1658. if (!weaponNode) {
  1659. const b1Node = block.getChildByName('B1');
  1660. if (b1Node) {
  1661. weaponNode = b1Node.getChildByName('Weapon');
  1662. }
  1663. }
  1664. if (weaponNode) {
  1665. const shapeId = this.getBlockShape(block);
  1666. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1667. }
  1668. }
  1669. });
  1670. }
  1671. // 遍历kuang区域的方块
  1672. this.blocks.forEach(block => {
  1673. const weaponConfig = this.getBlockWeaponConfig(block);
  1674. if (weaponConfig) {
  1675. // 根据新的预制体结构:Weapon节点直接在方块根节点下
  1676. let weaponNode = block.getChildByName('Weapon');
  1677. // 向后兼容:如果没找到,尝试旧的B1/Weapon路径
  1678. if (!weaponNode) {
  1679. const b1Node = block.getChildByName('B1');
  1680. if (b1Node) {
  1681. weaponNode = b1Node.getChildByName('Weapon');
  1682. }
  1683. }
  1684. if (weaponNode) {
  1685. const shapeId = this.getBlockShape(block);
  1686. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1687. }
  1688. }
  1689. });
  1690. }
  1691. // 根据方块获取武器配置
  1692. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  1693. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  1694. }
  1695. // 获取方块的武器ID
  1696. public getBlockWeaponId(block: Node): string | null {
  1697. const weaponConfig = this.getBlockWeaponConfig(block);
  1698. return weaponConfig ? weaponConfig.id : null;
  1699. }
  1700. // 获取方块的形状
  1701. public getBlockShape(block: Node): string | null {
  1702. const weaponConfig = this.getBlockWeaponConfig(block);
  1703. if (!weaponConfig) return null;
  1704. // 从方块结构推断形状
  1705. const shapeInfo = this.getBlockShapeInfo(block);
  1706. return shapeInfo ? shapeInfo.id : 'I';
  1707. }
  1708. // 获取方块的详细形状信息(包括形状ID和名称)
  1709. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  1710. const actualShape = this.extractShapeFromBlock(block);
  1711. console.log(`[BlockManager] 提取的实际形状矩阵:`, actualShape);
  1712. let blockShapes = null;
  1713. // 优先使用预加载的配置
  1714. if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
  1715. blockShapes = this.preloadedWeaponsConfig.blockSizes;
  1716. console.log(`[BlockManager] 使用预加载配置,形状数量: ${blockShapes ? blockShapes.length : 0}`);
  1717. } else {
  1718. // 回退到ConfigManager
  1719. blockShapes = this.configManager.getBlockShapes();
  1720. console.log(`[BlockManager] 使用ConfigManager,形状数量: ${blockShapes ? blockShapes.length : 0}`);
  1721. }
  1722. if (!blockShapes) {
  1723. console.log(`[BlockManager] 警告:无法获取形状配置`);
  1724. return null;
  1725. }
  1726. // 寻找匹配的形状配置
  1727. for (const shapeConfig of blockShapes) {
  1728. console.log(`[BlockManager] 比较形状 ${shapeConfig.id}:`, shapeConfig.shape);
  1729. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1730. console.log(`[BlockManager] 找到匹配形状: ${shapeConfig.id}`);
  1731. return {
  1732. id: shapeConfig.id,
  1733. name: shapeConfig.name,
  1734. shape: shapeConfig.shape
  1735. };
  1736. }
  1737. }
  1738. console.log(`[BlockManager] 警告:未找到匹配的形状,使用默认形状 I`);
  1739. return null;
  1740. }
  1741. // 从方块结构推断形状
  1742. private inferBlockShapeFromStructure(block: Node): string {
  1743. // 直接从B1节点结构读取形状矩阵
  1744. const actualShape = this.extractShapeFromBlock(block);
  1745. // 返回默认形状ID,实际形状矩阵已通过extractShapeFromBlock获取
  1746. return 'I';
  1747. }
  1748. // 从方块实例中提取形状矩阵
  1749. private extractShapeFromBlock(block: Node): number[][] {
  1750. const parts = this.getBlockParts(block);
  1751. // 创建4x4矩阵
  1752. const matrix: number[][] = [];
  1753. for (let i = 0; i < 4; i++) {
  1754. matrix[i] = [0, 0, 0, 0];
  1755. }
  1756. // 找到最小坐标作为偏移基准
  1757. let minX = 0, minY = 0;
  1758. for (const part of parts) {
  1759. minX = Math.min(minX, part.x);
  1760. minY = Math.min(minY, part.y);
  1761. }
  1762. // 填充矩阵,将坐标标准化到从(0,0)开始
  1763. for (const part of parts) {
  1764. const matrixX = part.x - minX;
  1765. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  1766. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  1767. matrix[matrixY][matrixX] = 1;
  1768. }
  1769. }
  1770. // 移除矩阵翻转操作,保持原始坐标系
  1771. return matrix;
  1772. }
  1773. // 比较两个形状矩阵是否相同
  1774. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  1775. if (matrix1.length !== matrix2.length) return false;
  1776. for (let i = 0; i < matrix1.length; i++) {
  1777. if (matrix1[i].length !== matrix2[i].length) return false;
  1778. for (let j = 0; j < matrix1[i].length; j++) {
  1779. if (matrix1[i][j] !== matrix2[i][j]) return false;
  1780. }
  1781. }
  1782. return true;
  1783. }
  1784. // 检查两个方块是否可以合成(相同形状相同种类)
  1785. private canMergeBlocks(block1: Node, block2: Node): boolean {
  1786. console.log(`[BlockManager] 开始检查方块合成条件`);
  1787. console.log(`[BlockManager] 方块1名称: ${block1.name}, 方块2名称: ${block2.name}`);
  1788. // 检查稀有度
  1789. const rarity1 = this.getBlockRarity(block1);
  1790. const rarity2 = this.getBlockRarity(block2);
  1791. console.log(`[BlockManager] 稀有度检查: ${rarity1} vs ${rarity2}`);
  1792. if (rarity1 !== rarity2) {
  1793. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  1794. return false;
  1795. }
  1796. // 检查武器ID(种类)
  1797. const weaponId1 = this.getBlockWeaponId(block1);
  1798. const weaponId2 = this.getBlockWeaponId(block2);
  1799. console.log(`[BlockManager] 武器ID检查: ${weaponId1} vs ${weaponId2}`);
  1800. if (weaponId1 !== weaponId2) {
  1801. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  1802. return false;
  1803. }
  1804. // 使用精确的形状矩阵比较
  1805. const shape1 = this.extractShapeFromBlock(block1);
  1806. const shape2 = this.extractShapeFromBlock(block2);
  1807. console.log(`[BlockManager] 形状矩阵1:`, shape1);
  1808. console.log(`[BlockManager] 形状矩阵2:`, shape2);
  1809. if (!this.compareShapeMatrices(shape1, shape2)) {
  1810. console.log(`[BlockManager] 形状矩阵不匹配`);
  1811. return false;
  1812. }
  1813. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  1814. return true;
  1815. }
  1816. /**
  1817. * 显示所有db标签节点
  1818. */
  1819. showAllDbNodes() {
  1820. if (this.block1DbNode) {
  1821. this.block1DbNode.active = true;
  1822. console.log("显示Block1的db标签节点");
  1823. }
  1824. if (this.block2DbNode) {
  1825. this.block2DbNode.active = true;
  1826. console.log("显示Block2的db标签节点");
  1827. }
  1828. if (this.block3DbNode) {
  1829. this.block3DbNode.active = true;
  1830. console.log("显示Block3的db标签节点");
  1831. }
  1832. }
  1833. // 刷新方块 - 重新生成三个新的武器方块
  1834. public refreshBlocks() {
  1835. // 移除PlacedBlocks容器中所有方块的标签
  1836. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1837. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1838. }
  1839. // 保存已放置方块的占用信息
  1840. const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  1841. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1842. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1843. const block = this.placedBlocksContainer.children[i];
  1844. const occupiedGrids = block['occupiedGrids'];
  1845. if (occupiedGrids && occupiedGrids.length > 0) {
  1846. placedBlocksOccupation.push({
  1847. block: block,
  1848. occupiedGrids: [...occupiedGrids]
  1849. });
  1850. }
  1851. }
  1852. }
  1853. // 生成新的方块
  1854. this.generateRandomBlocksInKuang();
  1855. // 显示所有db标签节点
  1856. this.showAllDbNodes();
  1857. }
  1858. // 检查是否有已放置的方块
  1859. public hasPlacedBlocks(): boolean {
  1860. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1861. console.log('[BlockManager] PlacedBlocks容器无效');
  1862. return false;
  1863. }
  1864. const blockCount = this.placedBlocksContainer.children.length;
  1865. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1866. // 检查容器中是否有子节点(方块)
  1867. return blockCount > 0;
  1868. }
  1869. /* =================== 合成逻辑 =================== */
  1870. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic'];
  1871. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1872. public async tryMergeBlock(block: Node) {
  1873. try {
  1874. const rarity = this.getBlockRarity(block);
  1875. if (!rarity) return;
  1876. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1877. if (!this.placedBlocksContainer) return;
  1878. const blockBB = this.getWorldAABB(block);
  1879. for (const other of this.placedBlocksContainer.children) {
  1880. if (other === block) continue;
  1881. // 使用新的合成检查方法
  1882. if (!this.canMergeBlocks(block, other)) continue;
  1883. const otherBB = this.getWorldAABB(other);
  1884. if (this.rectIntersects(blockBB, otherBB)) {
  1885. // 找到合成目标
  1886. await this.performMerge(block, other, rarity);
  1887. break;
  1888. }
  1889. }
  1890. } catch (error) {
  1891. console.error('[BlockManager] tryMergeBlock 发生错误:', error);
  1892. // 合成失败不影响游戏继续,只记录错误
  1893. }
  1894. }
  1895. private async performMerge(target: Node, source: Node, rarity: string) {
  1896. try {
  1897. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1898. // 隐藏价格标签并处理 db 关联
  1899. this.hidePriceLabel(source);
  1900. const srcDb = source['dbNode'];
  1901. if (srcDb) srcDb.active = false;
  1902. // 隐藏目标方块的db标签(合成后目标方块也应该隐藏db标签)
  1903. const targetDb = target['dbNode'];
  1904. if (targetDb) {
  1905. targetDb.active = false;
  1906. console.log(`[BlockManager] 隐藏目标方块db标签: ${targetDb.name}`);
  1907. }
  1908. // 销毁被合并方块
  1909. source.destroy();
  1910. // 升级稀有度
  1911. const nextRarity = this.getNextRarity(rarity);
  1912. if (nextRarity) {
  1913. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1914. // 获取当前武器配置
  1915. const currentConfig = this.blockWeaponConfigs.get(target);
  1916. if (currentConfig) {
  1917. // 保存原始武器名称用于日志输出
  1918. const originalWeaponName = currentConfig.name;
  1919. try {
  1920. // 获取当前关卡允许的武器列表
  1921. const levelWeapons = await this.getCurrentLevelWeapons();
  1922. // 检查是否应该限制在关卡配置的武器范围内
  1923. if (levelWeapons.length > 0) {
  1924. // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
  1925. if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
  1926. console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
  1927. }
  1928. // 无论如何,都只升级稀有度,不改变武器类型
  1929. const upgradedConfig = { ...currentConfig };
  1930. upgradedConfig.rarity = nextRarity;
  1931. this.blockWeaponConfigs.set(target, upgradedConfig);
  1932. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1933. (target as any)['weaponConfig'] = upgradedConfig;
  1934. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1935. } else {
  1936. // 如果没有关卡配置限制,正常升级稀有度
  1937. const upgradedConfig = { ...currentConfig };
  1938. upgradedConfig.rarity = nextRarity;
  1939. this.blockWeaponConfigs.set(target, upgradedConfig);
  1940. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1941. (target as any)['weaponConfig'] = upgradedConfig;
  1942. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1943. }
  1944. } catch (weaponError) {
  1945. console.error('[BlockManager] 获取关卡武器配置失败:', weaponError);
  1946. // 武器配置获取失败时,仍然升级稀有度
  1947. const upgradedConfig = { ...currentConfig };
  1948. upgradedConfig.rarity = nextRarity;
  1949. this.blockWeaponConfigs.set(target, upgradedConfig);
  1950. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1951. (target as any)['weaponConfig'] = upgradedConfig;
  1952. console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1953. }
  1954. }
  1955. // 同步更新BlockInfo组件的稀有度(新预制体结构)
  1956. const nodeChild = target.getChildByName('Node');
  1957. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1958. if (blockInfo) {
  1959. // 将稀有度字符串转换为数字
  1960. const rarityMap = { 'common': 0, 'uncommon': 1, 'rare': 2, 'epic': 3 };
  1961. const rarityNumber = rarityMap[nextRarity] !== undefined ? rarityMap[nextRarity] : 0;
  1962. blockInfo.rarity = rarityNumber;
  1963. // 更新稀有度显示
  1964. blockInfo.updateRarityDisplay();
  1965. console.log(`[BlockManager] BlockInfo稀有度已更新: ${rarity} -> ${nextRarity} (${rarityNumber})`);
  1966. } else {
  1967. console.warn(`[BlockManager] 未找到BlockInfo组件,无法更新稀有度显示`);
  1968. }
  1969. // 更新方块图片
  1970. this.loadBlockRarityImage(target, nextRarity);
  1971. }
  1972. // 播放烟雾动画
  1973. const worldPos = new Vec3();
  1974. target.getWorldPosition(worldPos);
  1975. this.spawnMergeSmoke(worldPos);
  1976. // 播放升级特效动画
  1977. this.playUpgradeEffect(target);
  1978. // 递归检查是否还能继续合成
  1979. if (nextRarity) {
  1980. await this.tryMergeBlock(target);
  1981. }
  1982. console.log(`[BlockManager] 合成完成`);
  1983. } catch (error) {
  1984. console.error('[BlockManager] performMerge 发生错误:', error);
  1985. // 合成失败时重新抛出错误,让上层处理
  1986. throw error;
  1987. }
  1988. }
  1989. private getBlockRarity(block: Node): string | null {
  1990. console.log(`[BlockManager] getBlockRarity 调用,方块名称: ${block.name}, UUID: ${block.uuid}`);
  1991. // 从Node子节点获取BlockInfo组件(适配新的预制体结构)
  1992. const nodeChild = block.getChildByName('Node');
  1993. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1994. if (blockInfo) {
  1995. const rarityName = blockInfo.getRarityName();
  1996. console.log(`[BlockManager] 从BlockInfo组件获取稀有度: ${rarityName}`);
  1997. return rarityName;
  1998. }
  1999. console.log(`[BlockManager] 未找到BlockInfo组件`);
  2000. return null;
  2001. }
  2002. private getNextRarity(rarity: string): string | null {
  2003. const idx = this.rarityOrder.indexOf(rarity);
  2004. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  2005. return this.rarityOrder[idx + 1];
  2006. }
  2007. private getWorldAABB(node: Node): Rect {
  2008. const ui = node.getComponent(UITransform);
  2009. if (!ui) return new Rect();
  2010. const pos = node.worldPosition;
  2011. const width = ui.width;
  2012. const height = ui.height;
  2013. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  2014. }
  2015. private rectIntersects(a: Rect, b: Rect): boolean {
  2016. return a.x < b.x + b.width &&
  2017. a.x + a.width > b.x &&
  2018. a.y < b.y + b.height &&
  2019. a.y + a.height > b.y;
  2020. }
  2021. /** 生成烟雾特效 */
  2022. private spawnMergeSmoke(worldPos: Vec3) {
  2023. const path = 'Animation/WeaponTx/tx0003/tx0003';
  2024. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  2025. if (err || !sData) {
  2026. console.warn('加载合成烟雾动画失败', err);
  2027. return;
  2028. }
  2029. const node = new Node('MergeSmoke');
  2030. const skeleton = node.addComponent(sp.Skeleton);
  2031. skeleton.skeletonData = sData;
  2032. skeleton.premultipliedAlpha = false;
  2033. skeleton.setAnimation(0, 'animation', false);
  2034. skeleton.setCompleteListener(() => node.destroy());
  2035. const canvas = find('Canvas');
  2036. if (canvas) canvas.addChild(node);
  2037. node.setWorldPosition(worldPos);
  2038. });
  2039. }
  2040. /** 播放升级特效动画 */
  2041. private playUpgradeEffect(target: Node) {
  2042. try {
  2043. // 获取目标方块的世界坐标
  2044. const worldPos = new Vec3();
  2045. target.getWorldPosition(worldPos);
  2046. // 加载升级特效动画
  2047. const path = 'Animation/WeaponBurnAni/shengji/skeleton';
  2048. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  2049. if (err || !sData) {
  2050. console.warn('[BlockManager] 加载升级特效动画失败:', err);
  2051. return;
  2052. }
  2053. // 创建特效节点
  2054. const effectNode = new Node('UpgradeEffect');
  2055. const skeleton = effectNode.addComponent(sp.Skeleton);
  2056. skeleton.skeletonData = sData;
  2057. skeleton.premultipliedAlpha = false;
  2058. // 播放动画
  2059. skeleton.setAnimation(0, 'animation', false);
  2060. // 监听动画完成事件,播放完成后销毁节点
  2061. skeleton.setCompleteListener(() => {
  2062. effectNode.destroy();
  2063. console.log('[BlockManager] 升级特效播放完成');
  2064. });
  2065. // 添加到Canvas并设置位置
  2066. const canvas = find('Canvas');
  2067. if (canvas) {
  2068. canvas.addChild(effectNode);
  2069. effectNode.setWorldPosition(worldPos);
  2070. console.log('[BlockManager] 开始播放升级特效动画');
  2071. } else {
  2072. console.warn('[BlockManager] 未找到Canvas节点,无法播放升级特效');
  2073. effectNode.destroy();
  2074. }
  2075. });
  2076. } catch (error) {
  2077. console.error('[BlockManager] 播放升级特效失败:', error);
  2078. }
  2079. }
  2080. /** 在放置失败时尝试与现有方块进行合成 */
  2081. public tryMergeOnOverlap(draggedBlock: Node): boolean {
  2082. console.log(`[BlockManager] tryMergeOnOverlap 开始检查合成`);
  2083. console.log(`[BlockManager] 拖拽方块名称: ${draggedBlock.name}`);
  2084. if (!this.placedBlocksContainer) {
  2085. console.log(`[BlockManager] placedBlocksContainer 不存在`);
  2086. return false;
  2087. }
  2088. const rarity = this.getBlockRarity(draggedBlock);
  2089. if (!rarity) {
  2090. console.log(`[BlockManager] 拖拽方块稀有度为空`);
  2091. return false;
  2092. }
  2093. console.log(`[BlockManager] 拖拽方块稀有度: ${rarity}`);
  2094. console.log(`[BlockManager] 已放置方块数量: ${this.placedBlocksContainer.children.length}`);
  2095. const dragBB = this.getWorldAABB(draggedBlock);
  2096. for (const target of this.placedBlocksContainer.children) {
  2097. if (target === draggedBlock) continue;
  2098. console.log(`[BlockManager] 检查与方块 ${target.name} 的合成可能性`);
  2099. // 使用新的合成检查方法
  2100. if (!this.canMergeBlocks(draggedBlock, target)) {
  2101. console.log(`[BlockManager] 与方块 ${target.name} 无法合成`);
  2102. continue;
  2103. }
  2104. const targetBB = this.getWorldAABB(target);
  2105. console.log(`[BlockManager] 检查方块碰撞`);
  2106. if (this.rectIntersects(dragBB, targetBB)) {
  2107. console.log(`[BlockManager] 方块重叠,执行合成`);
  2108. // 执行合并:目标保留,拖拽方块销毁
  2109. this.performMerge(target, draggedBlock, rarity);
  2110. return true;
  2111. } else {
  2112. console.log(`[BlockManager] 方块不重叠,跳过合成`);
  2113. }
  2114. }
  2115. console.log(`[BlockManager] 没有找到可合成的方块`);
  2116. return false;
  2117. }
  2118. // 调试绘制功能已迁移到GameBlockSelection
  2119. // 输出格子占用情况矩阵
  2120. public printGridOccupationMatrix() {
  2121. console.log('[BlockManager] 格子占用情况de矩阵 (6行11列):');
  2122. for (let row = 0; row < this.GRID_ROWS; row++) {
  2123. let rowStr = '';
  2124. for (let col = 0; col < this.GRID_COLS; col++) {
  2125. rowStr += this.gridOccupationMap[row][col] + ' ';
  2126. }
  2127. console.log(`第${row + 1}行: ${rowStr.trim()}`);
  2128. }
  2129. }
  2130. // 通过GameBlockSelection刷新方块占用情况
  2131. onDestroy() {
  2132. // 调试绘制功能已迁移到GameBlockSelection
  2133. // 清理事件监听
  2134. const eventBus = EventBus.getInstance();
  2135. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  2136. eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  2137. // 移除GAME_START事件清理,因为已不再监听该事件
  2138. // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  2139. eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  2140. }
  2141. }