BlockManager.ts 104 KB

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