BlockManager.ts 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264
  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. }