BlockManager.ts 140 KB

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