BlockManager.ts 135 KB

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