BlockManager.ts 115 KB

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