BlockManager.ts 103 KB

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