BlockManager.ts 136 KB

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