BlockManager.ts 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346
  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. // 教程第四步完成后,强制结束场上任何拖拽并恢复碰撞
  1417. this.forceEnableBlockCollidersAndEndDrags();
  1418. console.log(`[BlockManager] 教程第四步完成`);
  1419. }
  1420. return;
  1421. }
  1422. // 第2步:使用 _tutorialTargetGridsStep2 + 期望方块校验(fingerStartNodes[1])
  1423. if (this._tutorialStep >= 2) {
  1424. const expected = this.guideUIController ? this.guideUIController.fingerStartNodes[1] : null;
  1425. const completed = this.isTutorialPlacementCompleted(block, targetGrid, this._tutorialTargetGridsStep2, expected || undefined);
  1426. if (!completed) return;
  1427. EventBus.getInstance().emit(GameEvents.TUTORIAL_BLOCK_2_PLACED);
  1428. this._tutorialStep = 3;
  1429. console.log(`[BlockManager] 教程第二步完成`);
  1430. return;
  1431. }
  1432. // 第1步:使用 _tutorialTargetGrids + 期望方块校验(fingerStartNodes[0])
  1433. {
  1434. const expected = this.guideUIController ? this.guideUIController.fingerStartNodes[0] : null;
  1435. const completed = this.isTutorialPlacementCompleted(block, targetGrid, this._tutorialTargetGrids, expected || undefined);
  1436. if (!completed) return;
  1437. EventBus.getInstance().emit(GameEvents.TUTORIAL_BLOCK_1_PLACED);
  1438. // 运行时注入 Drag[2] 的起点为刚刚放置到场上的方块(Drag[0] 的结果)
  1439. if (this.guideUIController) {
  1440. try {
  1441. this.guideUIController.setStartNodeForDragConfigIndex(2, block);
  1442. } catch (e) {
  1443. console.warn(`[BlockManager] 注入 Drag[2] 起点失败: ${e}`);
  1444. }
  1445. }
  1446. this._tutorialStep = 2;
  1447. console.log(`[BlockManager] 教程第一步完成`);
  1448. return;
  1449. }
  1450. }
  1451. /**
  1452. * 教程保护:强制让场上方块立即可被小球碰撞,并结束拖拽状态
  1453. * 适用场景:例如第四步自动放置发生在玩家仍在拖拽时
  1454. */
  1455. private forceEnableBlockCollidersAndEndDrags(): void {
  1456. try {
  1457. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1458. return;
  1459. }
  1460. const children = this.placedBlocksContainer.children.slice();
  1461. for (let i = 0; i < children.length; i++) {
  1462. const block = children[i];
  1463. if (!block || !block.isValid) continue;
  1464. // 只处理有效的方块节点(根或含B1)
  1465. const isBlockLike = block.name.includes('Block') || !!block.getChildByName('B1');
  1466. if (!isBlockLike) continue;
  1467. // 清除拖拽标记
  1468. (block as any)['isDragging'] = false;
  1469. // 在教程保护场景下,确保位置标记为 grid(避免后续逻辑误判)
  1470. this.blockLocations.set(block, 'grid');
  1471. // 启用根节点碰撞体
  1472. const rootCol = block.getComponent(Collider2D);
  1473. if (rootCol && !rootCol.enabled) {
  1474. rootCol.enabled = true;
  1475. }
  1476. // 启用B1子节点的碰撞体(如存在)
  1477. const b1 = block.getChildByName('B1');
  1478. if (b1) {
  1479. const b1Col = b1.getComponent(Collider2D);
  1480. if (b1Col && !b1Col.enabled) {
  1481. b1Col.enabled = true;
  1482. }
  1483. }
  1484. // 通知BallController拖拽结束,确保不再忽略碰撞
  1485. try {
  1486. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block });
  1487. } catch (e) {
  1488. // 安静失败,不影响主流程
  1489. }
  1490. }
  1491. // 循环处理完毕后,广播全局强制结束拖拽事件,清理拖拽上下文
  1492. try {
  1493. EventBus.getInstance().emit(GameEvents.FORCE_END_ALL_DRAGS);
  1494. } catch (e) {
  1495. // 安静失败,不影响主流程
  1496. }
  1497. } catch (e) {
  1498. console.warn('[BlockManager] 教程保护:恢复方块碰撞与拖拽状态失败:', e);
  1499. }
  1500. }
  1501. // 检查方块是否可以放置在指定位置
  1502. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  1503. if (!this.gridInitialized) {
  1504. console.log(`[BlockManager] 网格未初始化`);
  1505. return false;
  1506. }
  1507. const targetRowCol = this.getGridRowCol(targetGrid);
  1508. if (!targetRowCol) {
  1509. console.log(`[BlockManager] 无法获取目标网格的行列信息`);
  1510. return false;
  1511. }
  1512. const parts = this.getBlockParts(block);
  1513. for (let i = 0; i < parts.length; i++) {
  1514. const part = parts[i];
  1515. const row = targetRowCol.row - part.y;
  1516. const col = targetRowCol.col + part.x;
  1517. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  1518. console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`);
  1519. return false;
  1520. }
  1521. if (this.gridOccupationMap[row][col] === 1) {
  1522. console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`);
  1523. return false;
  1524. }
  1525. }
  1526. return true;
  1527. }
  1528. // 获取网格行列索引
  1529. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  1530. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  1531. const parts = gridNode.name.split('_');
  1532. if (parts.length === 3) {
  1533. const row = parseInt(parts[1]);
  1534. const col = parseInt(parts[2]);
  1535. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  1536. return { row, col };
  1537. }
  1538. }
  1539. return null;
  1540. }
  1541. // 获取指定行列的网格世界坐标(用于调试绘制)
  1542. public getGridWorldPosition(row: number, col: number): Vec3 | null {
  1543. if (!this.gridInitialized || !this.gridNodes[row] || !this.gridNodes[row][col]) {
  1544. return null;
  1545. }
  1546. const gridNode = this.gridNodes[row][col];
  1547. return this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(gridNode.position);
  1548. }
  1549. // 获取方块的所有部分节点及其相对坐标
  1550. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  1551. const parts: { node: Node, x: number, y: number }[] = [];
  1552. // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
  1553. const b1Node = block.getChildByName('B1');
  1554. if (b1Node) {
  1555. // B1节点作为形状的根节点和坐标原点(0,0)
  1556. // 将B1节点本身添加为第一个部分
  1557. parts.push({ node: b1Node, x: 0, y: 0 });
  1558. // 然后递归查找B1的子节点,但要避免重复添加B1本身
  1559. this.findBlockParts(b1Node, parts, 0, 0, true);
  1560. } else {
  1561. // 没有B1节点,使用根节点作为形状根节点
  1562. parts.push({ node: block, x: 0, y: 0 });
  1563. this.findBlockParts(block, parts, 0, 0, false);
  1564. }
  1565. return parts;
  1566. }
  1567. // 递归查找方块的所有部分
  1568. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number, skipRoot: boolean = false) {
  1569. for (let i = 0; i < node.children.length; i++) {
  1570. const child = node.children[i];
  1571. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  1572. continue;
  1573. }
  1574. let x = parentX;
  1575. let y = parentY;
  1576. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  1577. if (match) {
  1578. x = parseInt(match[1]);
  1579. y = parseInt(match[2]);
  1580. result.push({ node: child, x, y });
  1581. } else if (child.name.startsWith('B')) {
  1582. const relativeX = Math.round(child.position.x / this.gridSpacing);
  1583. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  1584. x = parentX + relativeX;
  1585. y = parentY + relativeY;
  1586. // 避免重复添加已经在result中的节点
  1587. const existingPart = result.find(part => part.node === child);
  1588. if (!existingPart) {
  1589. result.push({ node: child, x, y });
  1590. }
  1591. }
  1592. this.findBlockParts(child, result, x, y, false);
  1593. }
  1594. }
  1595. // 标记方块占用的格子
  1596. public markOccupiedPositions(block: Node, targetGrid: Node) {
  1597. if (!this.gridInitialized) return;
  1598. const targetRowCol = this.getGridRowCol(targetGrid);
  1599. if (!targetRowCol) return;
  1600. const parts = this.getBlockParts(block);
  1601. block['occupiedGrids'] = [];
  1602. for (const part of parts) {
  1603. const row = targetRowCol.row - part.y;
  1604. const col = targetRowCol.col + part.x;
  1605. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  1606. this.gridOccupationMap[row][col] = 1;
  1607. block['occupiedGrids'] = block['occupiedGrids'] || [];
  1608. block['occupiedGrids'].push({ row, col });
  1609. }
  1610. }
  1611. }
  1612. // 清除方块
  1613. clearBlocks() {
  1614. console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
  1615. const blocksToRemove = [];
  1616. for (const block of this.blocks) {
  1617. if (block.isValid) {
  1618. const location = this.blockLocations.get(block);
  1619. // 清除kuang区域和Block容器中的方块
  1620. if (location === 'kuang' || location === 'block1' || location === 'block2' || location === 'block3') {
  1621. blocksToRemove.push(block);
  1622. }
  1623. }
  1624. }
  1625. console.log('[BlockManager] 找到需要清理的方块数量:', blocksToRemove.length);
  1626. for (const block of blocksToRemove) {
  1627. const dbNode = block['dbNode'];
  1628. if (dbNode && dbNode.isValid) {
  1629. block.off(Node.EventType.TRANSFORM_CHANGED);
  1630. const kuangNode = this.kuangContainer;
  1631. if (kuangNode) {
  1632. const dbName = dbNode.name;
  1633. if (!kuangNode.getChildByName(dbName)) {
  1634. dbNode.parent = kuangNode;
  1635. }
  1636. }
  1637. }
  1638. const index = this.blocks.indexOf(block);
  1639. if (index !== -1) {
  1640. this.blocks.splice(index, 1);
  1641. }
  1642. this.originalPositions.delete(block);
  1643. this.blockLocations.delete(block);
  1644. this.blockPriceMap.delete(block);
  1645. // 清理武器配置映射
  1646. this.blockWeaponConfigs.delete(block);
  1647. console.log('[BlockManager] 销毁方块:', block.name, '位置:', this.blockLocations.get(block));
  1648. block.destroy();
  1649. }
  1650. console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
  1651. }
  1652. // 游戏开始时调用
  1653. onGameStart() {
  1654. this.gameStarted = true;
  1655. for (const block of this.blocks) {
  1656. if (block.isValid) {
  1657. const location = this.blockLocations.get(block);
  1658. if (location === 'grid') {
  1659. const dbNode = block['dbNode'];
  1660. if (dbNode) {
  1661. dbNode.active = false;
  1662. }
  1663. this.moveBlockToPlacedBlocks(block);
  1664. this.addLockedVisualHint(block);
  1665. // 游戏开始后放置的方块移除标签,不能再放回kuang
  1666. BlockTag.removeTag(block);
  1667. }
  1668. }
  1669. }
  1670. }
  1671. // 游戏重置时调用
  1672. onGameReset() {
  1673. console.log('[BlockManager] 游戏重置,清理所有状态');
  1674. console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
  1675. this.gameStarted = false;
  1676. this.clearAllCooldowns();
  1677. // 清理已放置的方块
  1678. console.log('[BlockManager] 开始清理已放置的方块');
  1679. this.clearPlacedBlocks();
  1680. // 重置网格占用状态
  1681. console.log('[BlockManager] 开始重置网格占用状态');
  1682. this.resetGridOccupation();
  1683. // 清理kuang区域的方块
  1684. console.log('[BlockManager] 开始清理kuang区域的方块');
  1685. this.clearBlocks();
  1686. // 清理所有方块标签
  1687. console.log('[BlockManager] 开始清理所有方块标签');
  1688. BlockTag.clearAllTags();
  1689. console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
  1690. console.log('[BlockManager] 游戏重置完成 - 方块生成将由StartGame流程处理');
  1691. }
  1692. // 清理已放置的方块
  1693. private clearPlacedBlocks() {
  1694. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1695. console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
  1696. return;
  1697. }
  1698. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  1699. // 清理PlacedBlocks容器中的所有方块
  1700. const placedBlocks = [...this.placedBlocksContainer.children];
  1701. let clearedCount = 0;
  1702. for (const block of placedBlocks) {
  1703. if (block && block.isValid) {
  1704. // 从blocks数组中移除
  1705. const index = this.blocks.indexOf(block);
  1706. if (index !== -1) {
  1707. this.blocks.splice(index, 1);
  1708. }
  1709. // 清理相关映射
  1710. this.originalPositions.delete(block);
  1711. this.blockLocations.delete(block);
  1712. this.blockPriceMap.delete(block);
  1713. this.blockWeaponConfigs.delete(block);
  1714. console.log('[BlockManager] 销毁已放置方块:', block.name);
  1715. // 销毁方块
  1716. block.destroy();
  1717. clearedCount++;
  1718. }
  1719. }
  1720. console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
  1721. }
  1722. // 重置网格占用状态
  1723. public resetGridOccupation() {
  1724. console.log('[BlockManager] 重置网格占用状态');
  1725. // 重新初始化网格占用地图
  1726. this.gridOccupationMap = [];
  1727. for (let row = 0; row < this.GRID_ROWS; row++) {
  1728. this.gridOccupationMap[row] = [];
  1729. for (let col = 0; col < this.GRID_COLS; col++) {
  1730. this.gridOccupationMap[row][col] = 0;
  1731. }
  1732. }
  1733. // 清理临时存储的占用状态
  1734. this.tempRemovedOccupiedGrids = [];
  1735. }
  1736. // 添加视觉提示,表明方块已锁定
  1737. addLockedVisualHint(block: Node) {
  1738. const children = block.children;
  1739. for (let i = 0; i < children.length; i++) {
  1740. const child = children[i];
  1741. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  1742. continue;
  1743. }
  1744. child.setScale(new Vec3(0.95, 0.95, 1));
  1745. }
  1746. }
  1747. // 将方块移动到PlacedBlocks节点下
  1748. moveBlockToPlacedBlocks(block: Node) {
  1749. if (!this.placedBlocksContainer) {
  1750. console.error('PlacedBlocks容器未设置');
  1751. return;
  1752. }
  1753. if (!this.placedBlocksContainer.isValid) {
  1754. console.error('PlacedBlocks容器已失效');
  1755. return;
  1756. }
  1757. const worldPosition = new Vec3();
  1758. block.getWorldPosition(worldPosition);
  1759. // 移除旧的触摸事件监听器
  1760. block.off(Node.EventType.TOUCH_START);
  1761. block.off(Node.EventType.TOUCH_MOVE);
  1762. block.off(Node.EventType.TOUCH_END);
  1763. block.off(Node.EventType.TOUCH_CANCEL);
  1764. block.removeFromParent();
  1765. this.placedBlocksContainer.addChild(block);
  1766. block.setWorldPosition(worldPosition);
  1767. // 通过事件机制重新设置拖拽事件
  1768. const eventBus = EventBus.getInstance();
  1769. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]);
  1770. console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`);
  1771. }
  1772. // 根据武器配置选择合适的预制体
  1773. private selectPrefabForWeapon(weaponConfig: WeaponConfig, targetShapeId?: string): Prefab | null {
  1774. if (this.blockPrefabs.length === 0) {
  1775. return null;
  1776. }
  1777. // 如果指定了目标形状ID,尝试找到匹配的预制体
  1778. if (targetShapeId) {
  1779. const matchingPrefab = this.findPrefabByShape(targetShapeId);
  1780. if (matchingPrefab) {
  1781. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 找到匹配形状 ${targetShapeId} 的预制体`);
  1782. return matchingPrefab;
  1783. }
  1784. }
  1785. // 如果没有指定形状或没有找到匹配的预制体,使用随机选择
  1786. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  1787. const selectedPrefab = this.blockPrefabs[randomIndex];
  1788. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 选择随机预制体 (索引: ${randomIndex})`);
  1789. return selectedPrefab;
  1790. }
  1791. // 根据形状ID查找匹配的预制体(按照Block+形状ID的命名规则)
  1792. private findPrefabByShape(targetShapeId: string): Prefab | null {
  1793. // 构建预期的预制体名称:Block + 形状ID
  1794. const expectedPrefabName = `Block${targetShapeId}`;
  1795. console.log(`[BlockManager] 寻找形状 ${targetShapeId} 的预制体,期望名称: ${expectedPrefabName}`);
  1796. console.log(`[BlockManager] 当前可用预制体数量: ${this.blockPrefabs.length}`);
  1797. // 输出所有可用预制体的详细信息
  1798. this.blockPrefabs.forEach((prefab, index) => {
  1799. console.log(`[BlockManager] 预制体[${index}]: ${prefab.name} (匹配: ${prefab.name === expectedPrefabName})`);
  1800. });
  1801. for (const prefab of this.blockPrefabs) {
  1802. if (prefab.name === expectedPrefabName) {
  1803. console.log(`[BlockManager] ✓ 找到匹配形状 ${targetShapeId} 的预制体: ${prefab.name}`);
  1804. return prefab;
  1805. }
  1806. }
  1807. console.log(`[BlockManager] ✗ 未找到匹配形状 ${targetShapeId} 的预制体 (期望名称: ${expectedPrefabName})`);
  1808. return null;
  1809. }
  1810. // 根据武器配置和方块形状设置价格
  1811. private setBlockPriceByWeaponConfig(block: Node, priceNode: Node) {
  1812. const label = priceNode.getComponent(Label);
  1813. if (!label) {
  1814. return;
  1815. }
  1816. // 从Node子节点获取BlockInfo组件(新预制体结构)
  1817. const nodeChild = block.getChildByName('Node');
  1818. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1819. if (!blockInfo) {
  1820. label.string = "10";
  1821. return;
  1822. }
  1823. // 直接使用BlockInfo的shapePrice,如果为0则使用默认价格10
  1824. let basePrice = blockInfo.shapePrice > 0 ? blockInfo.shapePrice : 10;
  1825. // 应用便宜技能效果
  1826. const skillManager = SkillManager.getInstance();
  1827. let finalPrice = basePrice;
  1828. if (skillManager) {
  1829. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1830. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1831. }
  1832. label.string = finalPrice.toString();
  1833. }
  1834. // 计算方块占用的格子数量
  1835. // 设置方块的武器外观
  1836. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig, targetShapeId?: string) {
  1837. // 确保方块节点上也有 weaponConfig 属性
  1838. block['weaponConfig'] = weaponConfig;
  1839. // 如果提供了目标形状ID,直接使用它加载对应的稀有度图片
  1840. if (targetShapeId) {
  1841. this.loadBlockRarityImageByShape(block, weaponConfig.rarity || 'common', targetShapeId);
  1842. } else {
  1843. // 否则使用原有逻辑从方块结构推断形状
  1844. this.loadBlockRarityImage(block, weaponConfig.rarity || 'common');
  1845. }
  1846. // 加载武器图标
  1847. this.loadWeaponIcon(block, weaponConfig);
  1848. }
  1849. /**
  1850. * 设置方块的BlockInfo组件信息
  1851. * @param block 方块节点
  1852. * @param weaponConfig 武器配置
  1853. * @param targetShapeId 目标形状ID
  1854. * @param blockLocation 方块所在位置
  1855. */
  1856. private setupBlockInfo(block: Node, weaponConfig: WeaponConfig, targetShapeId?: string, blockLocation?: string) {
  1857. // 从Node子节点获取BlockInfo组件(新预制体结构)
  1858. const nodeChild = block.getChildByName('Node');
  1859. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  1860. if (!blockInfo) {
  1861. console.warn(`[BlockManager] 方块 ${block.name} 没有BlockInfo组件`);
  1862. return;
  1863. }
  1864. // 设置基础信息
  1865. blockInfo.blockName = weaponConfig.name || block.name;
  1866. blockInfo.blockId = weaponConfig.id || weaponConfig.name;
  1867. // 设置稀有度
  1868. const rarityMap = { 'common': 0, 'uncommon': 1, 'rare': 2, 'epic': 3 };
  1869. blockInfo.rarity = rarityMap[weaponConfig.rarity] || 0;
  1870. // 设置稀有度颜色
  1871. blockInfo.rarityColor = this.getRarityColor(weaponConfig.rarity);
  1872. // 设置形状信息
  1873. if (targetShapeId) {
  1874. blockInfo.shapeId = targetShapeId;
  1875. const shapeInfo = this.getBlockShapeInfo(block);
  1876. if (shapeInfo && shapeInfo.shape) {
  1877. // 计算形状大小
  1878. const rows = shapeInfo.shape.length;
  1879. const cols = shapeInfo.shape[0] ? shapeInfo.shape[0].length : 0;
  1880. blockInfo.shapeSize = new cc.Vec2(cols, rows);
  1881. }
  1882. }
  1883. // 设置武器配置(在形状ID设置之后,这样可以正确计算形状价格)
  1884. blockInfo.setWeaponConfig(weaponConfig);
  1885. // 设置位置信息
  1886. blockInfo.currentLocation = blockLocation || 'kuang';
  1887. blockInfo.gridPosition = new cc.Vec2(-1, -1);
  1888. // 设置状态信息
  1889. blockInfo.isPlaced = false;
  1890. blockInfo.isDraggable = true;
  1891. blockInfo.isMergeable = true;
  1892. // 设置方块标签
  1893. const tags = [];
  1894. if (weaponConfig.type) tags.push(weaponConfig.type);
  1895. if (weaponConfig.rarity) tags.push(weaponConfig.rarity);
  1896. if (targetShapeId) tags.push(targetShapeId);
  1897. blockInfo.setBlockTags(tags);
  1898. // 查找稀有度和武器图标
  1899. // 根据新的预制体结构,武器节点直接位于方块根节点下
  1900. let weaponNode = block.getChildByName('Weapon');
  1901. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  1902. if (!weaponNode) {
  1903. const b1Node = block.getChildByName('B1');
  1904. if (b1Node) {
  1905. weaponNode = b1Node.getChildByName('Weapon');
  1906. }
  1907. }
  1908. if (weaponNode) {
  1909. const weaponSprite = weaponNode.getComponent(Sprite);
  1910. if (weaponSprite) {
  1911. blockInfo.weaponSprite = weaponSprite;
  1912. }
  1913. }
  1914. // 更新显示
  1915. blockInfo.updatePriceDisplay();
  1916. blockInfo.updateRarityDisplay();
  1917. console.log(`[BlockManager] 已设置方块 ${block.name} 的BlockInfo组件信息`);
  1918. }
  1919. /**
  1920. * 获取稀有度对应的颜色
  1921. * @param rarity 稀有度
  1922. * @returns 颜色对象
  1923. */
  1924. private getRarityColor(rarity: string): cc.Color {
  1925. switch (rarity) {
  1926. case 'common':
  1927. return cc.Color.WHITE;
  1928. case 'uncommon':
  1929. return cc.Color.GREEN;
  1930. case 'rare':
  1931. return cc.Color.BLUE;
  1932. case 'epic':
  1933. return cc.Color.MAGENTA;
  1934. default:
  1935. return cc.Color.WHITE;
  1936. }
  1937. }
  1938. // 设置方块稀有度颜色
  1939. private setBlockRarityColor(block: Node, rarity: string) {
  1940. this.loadBlockRarityImage(block, rarity);
  1941. }
  1942. // 公共方法:应用方块稀有度图片(供外部调用)
  1943. public applyBlockRarityColor(block: Node, rarity: string) {
  1944. // Add null safety check for block
  1945. if (!block || !block.isValid) {
  1946. return;
  1947. }
  1948. // 使用图片替代颜色
  1949. this.loadBlockRarityImage(block, rarity);
  1950. }
  1951. // 根据稀有度和指定形状ID加载对应的图片
  1952. private async loadBlockRarityImageByShape(block: Node, rarity: string, shapeId: string) {
  1953. if (!block || !block.isValid) {
  1954. return;
  1955. }
  1956. console.log(`[BlockManager] 直接使用形状ID ${shapeId} 加载稀有度图片`);
  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 baseImageName = this.getBaseImageNameByShape(shapeId);
  1974. if (!baseImageName) {
  1975. console.warn(`[BlockManager] 无法映射形状ID ${shapeId} 到图片名称`);
  1976. this.applyBlockRarityColorFallback(block, rarity);
  1977. return;
  1978. }
  1979. // 构建图片路径
  1980. const imagePath = `images/Blocks/${rarity}/${baseImageName}/spriteFrame`;
  1981. console.log(`[BlockManager] 回退加载图片路径: ${imagePath}`);
  1982. try {
  1983. // 优先使用 assetManager.getBundle('resources')
  1984. const resourcesBundle = cc.assetManager.getBundle('resources');
  1985. if (resourcesBundle) {
  1986. resourcesBundle.load(imagePath, SpriteFrame, (err, spriteFrame) => {
  1987. if (err) {
  1988. console.warn(`[BlockManager] Bundle加载失败: ${err.message},尝试使用resources.load`);
  1989. this.loadImageWithResourcesLoad(block, imagePath);
  1990. } else {
  1991. this.applySpriteFrameToBlock(block, spriteFrame);
  1992. console.log(`[BlockManager] ✓ Bundle成功加载图片: ${imagePath}`);
  1993. }
  1994. });
  1995. } else {
  1996. console.warn('[BlockManager] resources bundle不可用,使用resources.load');
  1997. this.loadImageWithResourcesLoad(block, imagePath);
  1998. }
  1999. } catch (error) {
  2000. console.error(`[BlockManager] 加载图片时发生错误: ${error}`);
  2001. this.applyBlockRarityColorFallback(block, rarity);
  2002. }
  2003. }
  2004. // 根据稀有度和方块形状加载对应的图片
  2005. private async loadBlockRarityImage(block: Node, rarity: string) {
  2006. if (!block || !block.isValid) {
  2007. return;
  2008. }
  2009. // 首先尝试从BlockInfo组件获取稀有度图标(新预制体结构)
  2010. const nodeChild = block.getChildByName('Node');
  2011. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  2012. if (blockInfo) {
  2013. const rarityIcon = blockInfo.getRarityIcon();
  2014. if (rarityIcon) {
  2015. this.applySpriteFrameToBlock(block, rarityIcon);
  2016. console.log(`[BlockManager] ✓ 从BlockInfo组件获取稀有度图标: ${rarity}`);
  2017. return;
  2018. } else {
  2019. console.warn(`[BlockManager] BlockInfo组件中没有找到稀有度图标,稀有度: ${rarity}`);
  2020. }
  2021. } else {
  2022. console.warn(`[BlockManager] 方块没有BlockInfo组件,回退到路径加载模式`);
  2023. }
  2024. // 回退到原有的路径加载逻辑
  2025. const shapeId = this.getBlockShape(block);
  2026. if (!shapeId) {
  2027. console.warn('[BlockManager] 无法获取方块形状,跳过图片加载');
  2028. this.applyBlockRarityColorFallback(block, rarity);
  2029. return;
  2030. }
  2031. // 使用形状ID加载图片
  2032. this.loadBlockRarityImageByShape(block, rarity, shapeId);
  2033. }
  2034. // 辅助方法:使用resources.load加载图片
  2035. private loadImageWithResourcesLoad(block: Node, imagePath: string) {
  2036. resources.load(imagePath, SpriteFrame, (err, spriteFrame) => {
  2037. if (err) {
  2038. console.error(`[BlockManager] ✗ 图片加载失败: ${imagePath}, 错误: ${err.message}`);
  2039. // 使用颜色回退方案
  2040. const rarity = this.getBlockRarity(block) || 'common';
  2041. this.applyBlockRarityColorFallback(block, rarity);
  2042. } else {
  2043. this.applySpriteFrameToBlock(block, spriteFrame);
  2044. console.log(`[BlockManager] ✓ Resources成功加载图片: ${imagePath}`);
  2045. }
  2046. });
  2047. }
  2048. // 辅助方法:将SpriteFrame应用到方块
  2049. private applySpriteFrameToBlock(block: Node, spriteFrame: SpriteFrame) {
  2050. // 新的预制体结构:Sprite组件在Node子节点上
  2051. const nodeChild = block.getChildByName('Node');
  2052. if (nodeChild) {
  2053. const sprite = nodeChild.getComponent(Sprite);
  2054. if (sprite) {
  2055. sprite.spriteFrame = spriteFrame;
  2056. } else {
  2057. console.warn('[BlockManager] Node子节点没有Sprite组件');
  2058. }
  2059. } else {
  2060. console.warn('[BlockManager] 方块节点没有找到Node子节点');
  2061. }
  2062. }
  2063. // 根据形状ID映射到基础图片名称
  2064. private getBaseImageNameByShape(shapeId: string): string | null {
  2065. // 根据实际图片文件名映射,不包含文件扩展名
  2066. switch (shapeId) {
  2067. case 'I':
  2068. return 'BlockI';
  2069. case 'H-I':
  2070. return 'BlockH-I';
  2071. case 'L':
  2072. case 'L2':
  2073. case 'L3':
  2074. case 'L4':
  2075. return 'BlockL';
  2076. case 'S':
  2077. case 'F-S':
  2078. return 'BlockS';
  2079. case 'T':
  2080. case 'D-T':
  2081. return 'BlockD-T';
  2082. default:
  2083. // 对于未知形状,尝试直接使用形状ID
  2084. return `Block${shapeId}`;
  2085. }
  2086. }
  2087. // 颜色模式回退方法(当图片加载失败时使用)
  2088. private applyBlockRarityColorFallback(block: Node, rarity: string) {
  2089. // 新的预制体结构:Sprite组件在Node子节点上
  2090. const nodeChild = block.getChildByName('Node');
  2091. if (!nodeChild) {
  2092. console.warn('[BlockManager] 方块节点没有找到Node子节点');
  2093. return;
  2094. }
  2095. const sprite = nodeChild.getComponent(Sprite);
  2096. if (!sprite || !sprite.isValid) {
  2097. console.warn('[BlockManager] Node子节点没有Sprite组件');
  2098. return;
  2099. }
  2100. // 根据稀有度设置颜色
  2101. let color: Color;
  2102. switch (rarity) {
  2103. case 'common':
  2104. color = new Color(255, 255, 255); // 白色
  2105. break;
  2106. case 'uncommon':
  2107. color = new Color(0, 255, 0); // 绿色
  2108. break;
  2109. case 'rare':
  2110. color = new Color(0, 100, 255); // 蓝色
  2111. break;
  2112. case 'epic':
  2113. color = new Color(160, 32, 240); // 紫色
  2114. break;
  2115. default:
  2116. color = new Color(255, 255, 255); // 默认白色
  2117. }
  2118. sprite.color = color;
  2119. console.log(`[BlockManager] 回退到颜色模式设置方块稀有度: ${rarity}`, color);
  2120. }
  2121. // 加载武器图标
  2122. private async loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  2123. // 根据新的预制体结构,武器节点直接位于方块根节点下
  2124. let weaponNode = block.getChildByName('Weapon');
  2125. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  2126. if (!weaponNode) {
  2127. const b1Node = block.getChildByName('B1');
  2128. if (b1Node) {
  2129. weaponNode = b1Node.getChildByName('Weapon');
  2130. }
  2131. }
  2132. if (!weaponNode) {
  2133. console.warn('找不到Weapon节点');
  2134. return;
  2135. }
  2136. const weaponSprite = weaponNode.getComponent(Sprite);
  2137. if (!weaponSprite) {
  2138. console.warn('Weapon节点上没有Sprite组件');
  2139. return;
  2140. }
  2141. // 获取武器配置中的图片路径
  2142. const weaponSprites = weaponConfig.visualConfig?.weaponSprites;
  2143. if (!weaponSprites) {
  2144. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  2145. return;
  2146. }
  2147. // 获取第一个可用的精灵路径(通常是'I'形状)
  2148. let spritePath: string;
  2149. if (typeof weaponSprites === 'string') {
  2150. spritePath = weaponSprites;
  2151. } else {
  2152. // 优先使用'I'形状,如果没有则使用第一个可用的
  2153. const keys = Object.keys(weaponSprites);
  2154. spritePath = weaponSprites['I'] || (keys.length > 0 ? weaponSprites[keys[0]] : null);
  2155. }
  2156. if (!spritePath) {
  2157. console.warn(`武器 ${weaponConfig.name} 没有可用的精灵路径`);
  2158. return;
  2159. }
  2160. // 转换路径格式,去除"images/"前缀
  2161. const bundlePath = spritePath.replace(/^images\//, '');
  2162. try {
  2163. // 使用BundleLoader从images Bundle加载SpriteFrame,添加/spriteFrame后缀
  2164. const spriteFrame = await this.bundleLoader.loadSpriteFrame(`${bundlePath}/spriteFrame`);
  2165. // Add comprehensive null safety checks before setting spriteFrame
  2166. if (weaponSprite && weaponSprite.isValid &&
  2167. weaponNode && weaponNode.isValid &&
  2168. block && block.isValid &&
  2169. spriteFrame && spriteFrame.isValid) {
  2170. weaponSprite.spriteFrame = spriteFrame;
  2171. // 设置武器图标初始大小为0.4倍
  2172. weaponNode.setScale(0.4, 0.4, 1.0);
  2173. console.log(`[BlockManager] 武器图标加载完成,设置初始缩放为0.4倍: ${weaponConfig.name}`);
  2174. // 应用武器图标的旋转(不再使用位置偏移)
  2175. const blockShape = this.getBlockShape(block);
  2176. this.rotateWeaponIconByShape(weaponNode, blockShape, weaponConfig.id);
  2177. }
  2178. } catch (err) {
  2179. console.warn(`加载武器图片失败: ${bundlePath}`, err);
  2180. }
  2181. }
  2182. // 武器类型和方块形状组合的旋转角度配置
  2183. private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
  2184. 'pea_shooter': {
  2185. 'I': 0, // 毛豆射手竖条形状
  2186. 'H-I': 90, // 毛豆射手横条形状
  2187. 'L': 0, // 毛豆射手L型
  2188. 'S': 0, // 毛豆射手S型
  2189. 'D-T': 0 // 毛豆射手倒T型
  2190. },
  2191. 'sharp_carrot': {
  2192. 'I': 0, // 尖胡萝卜竖条形状
  2193. 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
  2194. 'L': -15, // 尖胡萝卜L型,轻微调整
  2195. 'S': 15, // 尖胡萝卜S型,轻微调整
  2196. 'D-T': 0 // 尖胡萝卜倒T型
  2197. },
  2198. 'saw_grass': {
  2199. 'I': 0, // 锯齿草竖条形状
  2200. 'H-I': 0, // 锯齿草横条形状
  2201. 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
  2202. 'S': 30, // 锯齿草S型,适配锯齿弯曲
  2203. 'D-T': 0 // 锯齿草倒T型
  2204. },
  2205. 'watermelon_bomb': {
  2206. 'I': 0, // 西瓜炸弹竖条形状
  2207. 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
  2208. 'L': 0, // 西瓜炸弹L型
  2209. 'S': 0, // 西瓜炸弹S型
  2210. 'D-T': 0 // 西瓜炸弹倒T型
  2211. },
  2212. 'boomerang_plant': {
  2213. 'I': 0, // 回旋镖植物竖条形状
  2214. 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
  2215. 'L': -30, // 回旋镖植物L型
  2216. 'S': -10, // 回旋镖植物S型,适配回旋轨迹
  2217. 'D-T': -80 // 回旋镖植物倒T型
  2218. },
  2219. 'hot_pepper': {
  2220. 'I': 0, // 辣椒竖条形状
  2221. 'H-I': 90, // 辣椒横条形状
  2222. 'L': 0, // 辣椒L型
  2223. 'S': 0, // 辣椒S型
  2224. 'D-T': 0 // 辣椒倒T型
  2225. },
  2226. 'cactus_shotgun': {
  2227. 'I': 0, // 仙人掌霰弹枪竖条形状
  2228. 'H-I': 90, // 仙人掌霰弹枪横条形状
  2229. 'L': -20, // 仙人掌霰弹枪L型
  2230. 'S': 20, // 仙人掌霰弹枪S型
  2231. 'D-T': 0 // 仙人掌霰弹枪倒T型
  2232. },
  2233. 'okra_missile': {
  2234. 'I': 0, // 秋葵导弹竖条形状
  2235. 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
  2236. 'L': -10, // 秋葵导弹L型
  2237. 'S': 10, // 秋葵导弹S型
  2238. 'D-T': 0 // 秋葵导弹倒T型
  2239. },
  2240. 'mace_club': {
  2241. 'I': -45, // 狼牙棒竖条形状
  2242. 'H-I': 0, // 狼牙棒横条形状
  2243. 'L': -90, // 狼牙棒L型,适配棒状武器
  2244. 'S': -90, // 狼牙棒S型
  2245. 'D-T': 0 // 狼牙棒倒T型
  2246. }
  2247. };
  2248. // 默认旋转角度配置(当武器类型未配置时使用)
  2249. private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
  2250. 'I': 0, // 竖条形状,保持原始方向
  2251. 'H-I': 90, // 横I型,旋转90度适配水平方向
  2252. 'L': -15, // L型,轻微左倾适配L形状的转角
  2253. 'S': 15, // S型,轻微右倾适配S形状的弯曲
  2254. 'D-T': 0 // 倒T型,保持原始方向
  2255. };
  2256. // 根据武器类型和方块形状调整武器图标位置(完全保留预制体原始旋转值,不应用额外旋转)
  2257. private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  2258. if (!weaponNode || !shapeId) return;
  2259. // 保存预制体的原始旋转角度
  2260. const originalAngle = weaponNode.angle;
  2261. console.log(`保留预制体原始旋转角度: ${originalAngle}度,不应用额外旋转`);
  2262. }
  2263. // 设置特定武器和形状的旋转角度
  2264. public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
  2265. if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  2266. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
  2267. }
  2268. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
  2269. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
  2270. }
  2271. // 设置默认形状的旋转角度
  2272. public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
  2273. this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
  2274. console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
  2275. }
  2276. // 获取特定武器和形状的旋转角度
  2277. public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
  2278. if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  2279. return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  2280. }
  2281. return 0;
  2282. }
  2283. // 获取默认形状的旋转角度
  2284. public getDefaultShapeRotationAngle(shapeId: string): number {
  2285. return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  2286. }
  2287. // 设置特定武器和形状的旋转角度
  2288. public setWeaponShapeTransform(weaponId: string, shapeId: string, angle: number) {
  2289. this.setWeaponShapeRotationAngle(weaponId, shapeId, angle);
  2290. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度: ${angle}度`);
  2291. }
  2292. // 设置默认形状的旋转角度
  2293. public setDefaultShapeTransform(shapeId: string, angle: number) {
  2294. this.setDefaultShapeRotationAngle(shapeId, angle);
  2295. console.log(`已更新默认形状 ${shapeId} 的旋转角度: ${angle}度`);
  2296. }
  2297. // 重新应用所有已放置方块的武器图标位置和旋转
  2298. public refreshAllWeaponIconRotations() {
  2299. // 遍历所有已放置的方块
  2300. if (this.placedBlocksContainer) {
  2301. this.placedBlocksContainer.children.forEach(block => {
  2302. const weaponConfig = this.getBlockWeaponConfig(block);
  2303. if (weaponConfig) {
  2304. // 根据新的预制体结构:Weapon节点直接在方块根节点下
  2305. let weaponNode = block.getChildByName('Weapon');
  2306. // 向后兼容:如果没找到,尝试旧的B1/Weapon路径
  2307. if (!weaponNode) {
  2308. const b1Node = block.getChildByName('B1');
  2309. if (b1Node) {
  2310. weaponNode = b1Node.getChildByName('Weapon');
  2311. }
  2312. }
  2313. if (weaponNode) {
  2314. const shapeId = this.getBlockShape(block);
  2315. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  2316. }
  2317. }
  2318. });
  2319. }
  2320. // 遍历kuang区域的方块
  2321. this.blocks.forEach(block => {
  2322. const weaponConfig = this.getBlockWeaponConfig(block);
  2323. if (weaponConfig) {
  2324. // 根据新的预制体结构:Weapon节点直接在方块根节点下
  2325. let weaponNode = block.getChildByName('Weapon');
  2326. // 向后兼容:如果没找到,尝试旧的B1/Weapon路径
  2327. if (!weaponNode) {
  2328. const b1Node = block.getChildByName('B1');
  2329. if (b1Node) {
  2330. weaponNode = b1Node.getChildByName('Weapon');
  2331. }
  2332. }
  2333. if (weaponNode) {
  2334. const shapeId = this.getBlockShape(block);
  2335. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  2336. }
  2337. }
  2338. });
  2339. }
  2340. // 根据方块获取武器配置
  2341. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  2342. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  2343. }
  2344. // 获取方块的武器ID
  2345. public getBlockWeaponId(block: Node): string | null {
  2346. const weaponConfig = this.getBlockWeaponConfig(block);
  2347. return weaponConfig ? weaponConfig.id : null;
  2348. }
  2349. // 获取方块的形状
  2350. public getBlockShape(block: Node): string | null {
  2351. const weaponConfig = this.getBlockWeaponConfig(block);
  2352. if (!weaponConfig) return null;
  2353. // 从方块结构推断形状
  2354. const shapeInfo = this.getBlockShapeInfo(block);
  2355. return shapeInfo ? shapeInfo.id : 'I';
  2356. }
  2357. // 获取方块的详细形状信息(包括形状ID和名称)
  2358. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  2359. const actualShape = this.extractShapeFromBlock(block);
  2360. console.log(`[BlockManager] 提取的实际形状矩阵:`, actualShape);
  2361. let blockShapes = null;
  2362. // 优先使用预加载的配置
  2363. if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
  2364. blockShapes = this.preloadedWeaponsConfig.blockSizes;
  2365. console.log(`[BlockManager] 使用预加载配置,形状数量: ${blockShapes ? blockShapes.length : 0}`);
  2366. } else {
  2367. // 回退到ConfigManager
  2368. blockShapes = this.configManager.getBlockShapes();
  2369. console.log(`[BlockManager] 使用ConfigManager,形状数量: ${blockShapes ? blockShapes.length : 0}`);
  2370. }
  2371. if (!blockShapes) {
  2372. console.log(`[BlockManager] 警告:无法获取形状配置`);
  2373. return null;
  2374. }
  2375. // 寻找匹配的形状配置
  2376. for (const shapeConfig of blockShapes) {
  2377. console.log(`[BlockManager] 比较形状 ${shapeConfig.id}:`, shapeConfig.shape);
  2378. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  2379. console.log(`[BlockManager] 找到匹配形状: ${shapeConfig.id}`);
  2380. return {
  2381. id: shapeConfig.id,
  2382. name: shapeConfig.name,
  2383. shape: shapeConfig.shape
  2384. };
  2385. }
  2386. }
  2387. console.log(`[BlockManager] 警告:未找到匹配的形状,使用默认形状 I`);
  2388. return null;
  2389. }
  2390. // 从方块结构推断形状
  2391. private inferBlockShapeFromStructure(block: Node): string {
  2392. // 直接从B1节点结构读取形状矩阵
  2393. const actualShape = this.extractShapeFromBlock(block);
  2394. // 返回默认形状ID,实际形状矩阵已通过extractShapeFromBlock获取
  2395. return 'I';
  2396. }
  2397. // 从方块实例中提取形状矩阵
  2398. private extractShapeFromBlock(block: Node): number[][] {
  2399. const parts = this.getBlockParts(block);
  2400. // 创建4x4矩阵
  2401. const matrix: number[][] = [];
  2402. for (let i = 0; i < 4; i++) {
  2403. matrix[i] = [0, 0, 0, 0];
  2404. }
  2405. // 找到最小坐标作为偏移基准
  2406. let minX = 0, minY = 0;
  2407. for (const part of parts) {
  2408. minX = Math.min(minX, part.x);
  2409. minY = Math.min(minY, part.y);
  2410. }
  2411. // 填充矩阵,将坐标标准化到从(0,0)开始
  2412. for (const part of parts) {
  2413. const matrixX = part.x - minX;
  2414. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  2415. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  2416. matrix[matrixY][matrixX] = 1;
  2417. }
  2418. }
  2419. // 移除矩阵翻转操作,保持原始坐标系
  2420. return matrix;
  2421. }
  2422. // 比较两个形状矩阵是否相同
  2423. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  2424. if (matrix1.length !== matrix2.length) return false;
  2425. for (let i = 0; i < matrix1.length; i++) {
  2426. if (matrix1[i].length !== matrix2[i].length) return false;
  2427. for (let j = 0; j < matrix1[i].length; j++) {
  2428. if (matrix1[i][j] !== matrix2[i][j]) return false;
  2429. }
  2430. }
  2431. return true;
  2432. }
  2433. // 检查两个方块是否可以合成(相同形状相同种类)
  2434. private canMergeBlocks(block1: Node, block2: Node): boolean {
  2435. console.log(`[BlockManager] 开始检查方块合成条件`);
  2436. console.log(`[BlockManager] 方块1名称: ${block1.name}, 方块2名称: ${block2.name}`);
  2437. // 检查稀有度
  2438. const rarity1 = this.getBlockRarity(block1);
  2439. const rarity2 = this.getBlockRarity(block2);
  2440. console.log(`[BlockManager] 稀有度检查: ${rarity1} vs ${rarity2}`);
  2441. if (rarity1 !== rarity2) {
  2442. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  2443. return false;
  2444. }
  2445. // 检查武器ID(种类)
  2446. const weaponId1 = this.getBlockWeaponId(block1);
  2447. const weaponId2 = this.getBlockWeaponId(block2);
  2448. console.log(`[BlockManager] 武器ID检查: ${weaponId1} vs ${weaponId2}`);
  2449. if (weaponId1 !== weaponId2) {
  2450. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  2451. return false;
  2452. }
  2453. // 使用精确的形状矩阵比较
  2454. const shape1 = this.extractShapeFromBlock(block1);
  2455. const shape2 = this.extractShapeFromBlock(block2);
  2456. console.log(`[BlockManager] 形状矩阵1:`, shape1);
  2457. console.log(`[BlockManager] 形状矩阵2:`, shape2);
  2458. if (!this.compareShapeMatrices(shape1, shape2)) {
  2459. console.log(`[BlockManager] 形状矩阵不匹配`);
  2460. return false;
  2461. }
  2462. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  2463. return true;
  2464. }
  2465. /**
  2466. * 显示所有db标签节点
  2467. */
  2468. showAllDbNodes() {
  2469. if (this.block1DbNode) {
  2470. this.block1DbNode.active = true;
  2471. console.log("显示Block1的db标签节点");
  2472. }
  2473. if (this.block2DbNode) {
  2474. this.block2DbNode.active = true;
  2475. console.log("显示Block2的db标签节点");
  2476. }
  2477. if (this.block3DbNode) {
  2478. this.block3DbNode.active = true;
  2479. console.log("显示Block3的db标签节点");
  2480. }
  2481. }
  2482. // 刷新方块 - 重新生成三个新的武器方块
  2483. public refreshBlocks() {
  2484. // 移除PlacedBlocks容器中所有方块的标签
  2485. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  2486. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  2487. }
  2488. // 保存已放置方块的占用信息
  2489. const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  2490. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  2491. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  2492. const block = this.placedBlocksContainer.children[i];
  2493. const occupiedGrids = block['occupiedGrids'];
  2494. if (occupiedGrids && occupiedGrids.length > 0) {
  2495. placedBlocksOccupation.push({
  2496. block: block,
  2497. occupiedGrids: [...occupiedGrids]
  2498. });
  2499. }
  2500. }
  2501. }
  2502. // 生成新的方块
  2503. this.generateRandomBlocksInKuang();
  2504. // 显示所有db标签节点
  2505. this.showAllDbNodes();
  2506. }
  2507. // 检查是否有已放置的方块
  2508. public hasPlacedBlocks(): boolean {
  2509. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  2510. console.log('[BlockManager] PlacedBlocks容器无效');
  2511. return false;
  2512. }
  2513. const blockCount = this.placedBlocksContainer.children.length;
  2514. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  2515. // 检查容器中是否有子节点(方块)
  2516. return blockCount > 0;
  2517. }
  2518. /* =================== 合成逻辑 =================== */
  2519. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic'];
  2520. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  2521. public async tryMergeBlock(block: Node) {
  2522. try {
  2523. const rarity = this.getBlockRarity(block);
  2524. if (!rarity) return;
  2525. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  2526. if (!this.placedBlocksContainer) return;
  2527. const blockBB = this.getWorldAABB(block);
  2528. for (const other of this.placedBlocksContainer.children) {
  2529. if (other === block) continue;
  2530. // 使用新的合成检查方法
  2531. if (!this.canMergeBlocks(block, other)) continue;
  2532. const otherBB = this.getWorldAABB(other);
  2533. if (this.rectIntersects(blockBB, otherBB)) {
  2534. // 找到合成目标
  2535. await this.performMerge(block, other, rarity);
  2536. break;
  2537. }
  2538. }
  2539. } catch (error) {
  2540. console.error('[BlockManager] tryMergeBlock 发生错误:', error);
  2541. // 合成失败不影响游戏继续,只记录错误
  2542. }
  2543. }
  2544. private async performMerge(target: Node, source: Node, rarity: string) {
  2545. try {
  2546. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  2547. // 先立即触发合成特效,避免后续异步逻辑造成播放延迟
  2548. const worldPos = new Vec3();
  2549. target.getWorldPosition(worldPos);
  2550. this.spawnMergeSmoke(worldPos);
  2551. this.playUpgradeEffect(target);
  2552. // 注意:参与合成的方块都在网格中,它们的db标签本来就应该是隐藏的
  2553. // 不需要调用hideDbLabel,因为这些方块已经不在block容器中了
  2554. // 在扩展教程(第5-6步)中,合成即可视为完成,触发教程完成判断
  2555. if (this.isExtendedTutorialEventContext()) {
  2556. let gridNode: Node | null = null;
  2557. const occupied = (target as any)['occupiedGrids'];
  2558. if (occupied && occupied.length > 0) {
  2559. const first = occupied[0];
  2560. if (first && this.gridNodes[first.row] && this.gridNodes[first.row][first.col]) {
  2561. gridNode = this.gridNodes[first.row][first.col];
  2562. }
  2563. }
  2564. // 如果能定位到目标格子,则用源方块+该格子进行教程完成判定
  2565. if (gridNode) {
  2566. this.handleTutorialBlockPlacement(source, gridNode);
  2567. }
  2568. }
  2569. // 销毁被合并方块
  2570. source.destroy();
  2571. // 升级稀有度
  2572. const nextRarity = this.getNextRarity(rarity);
  2573. if (nextRarity) {
  2574. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  2575. // 播放合成成功音效
  2576. Audio.playSFX('data/弹球音效/level up 2');
  2577. // 追踪合成等级达成事件(仅追踪2-4级)
  2578. const rarityMap = { 'uncommon': 2, 'rare': 3, 'epic': 4 };
  2579. const mergeLevel = rarityMap[nextRarity];
  2580. if (mergeLevel) {
  2581. // 获取武器和形状信息用于埋点
  2582. const weaponConfig = this.blockWeaponConfigs.get(target);
  2583. const weaponType = weaponConfig ? weaponConfig.name : 'unknown';
  2584. const shapeType = this.getBlockShape(target) || 'unknown';
  2585. // 调用埋点方法
  2586. Analytics.trackBlockMergeLevel(mergeLevel, weaponType, shapeType);
  2587. console.log(`[BlockManager] 埋点追踪: 合成等级${mergeLevel}, 武器=${weaponType}, 形状=${shapeType}`);
  2588. }
  2589. // 获取当前武器配置
  2590. const currentConfig = this.blockWeaponConfigs.get(target);
  2591. if (currentConfig) {
  2592. // 保存原始武器名称用于日志输出
  2593. const originalWeaponName = currentConfig.name;
  2594. try {
  2595. // 获取当前关卡允许的武器列表
  2596. const levelWeapons = await this.getCurrentLevelWeapons();
  2597. // 检查是否应该限制在关卡配置的武器范围内
  2598. if (levelWeapons.length > 0) {
  2599. // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
  2600. if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
  2601. console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
  2602. }
  2603. // 无论如何,都只升级稀有度,不改变武器类型
  2604. const upgradedConfig = { ...currentConfig };
  2605. upgradedConfig.rarity = nextRarity;
  2606. this.blockWeaponConfigs.set(target, upgradedConfig);
  2607. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  2608. (target as any)['weaponConfig'] = upgradedConfig;
  2609. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  2610. } else {
  2611. // 如果没有关卡配置限制,正常升级稀有度
  2612. const upgradedConfig = { ...currentConfig };
  2613. upgradedConfig.rarity = nextRarity;
  2614. this.blockWeaponConfigs.set(target, upgradedConfig);
  2615. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  2616. (target as any)['weaponConfig'] = upgradedConfig;
  2617. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  2618. }
  2619. } catch (weaponError) {
  2620. console.error('[BlockManager] 获取关卡武器配置失败:', weaponError);
  2621. // 武器配置获取失败时,仍然升级稀有度
  2622. const upgradedConfig = { ...currentConfig };
  2623. upgradedConfig.rarity = nextRarity;
  2624. this.blockWeaponConfigs.set(target, upgradedConfig);
  2625. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  2626. (target as any)['weaponConfig'] = upgradedConfig;
  2627. console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  2628. }
  2629. }
  2630. // 同步更新BlockInfo组件的稀有度(新预制体结构)
  2631. const nodeChild = target.getChildByName('Node');
  2632. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  2633. if (blockInfo) {
  2634. // 将稀有度字符串转换为数字
  2635. const rarityMap = { 'common': 0, 'uncommon': 1, 'rare': 2, 'epic': 3 };
  2636. const rarityNumber = rarityMap[nextRarity] !== undefined ? rarityMap[nextRarity] : 0;
  2637. blockInfo.rarity = rarityNumber;
  2638. // 更新稀有度显示
  2639. blockInfo.updateRarityDisplay();
  2640. console.log(`[BlockManager] BlockInfo稀有度已更新: ${rarity} -> ${nextRarity} (${rarityNumber})`);
  2641. } else {
  2642. console.warn(`[BlockManager] 未找到BlockInfo组件,无法更新稀有度显示`);
  2643. }
  2644. // 更新方块图片
  2645. this.loadBlockRarityImage(target, nextRarity);
  2646. }
  2647. // 递归检查是否还能继续合成
  2648. if (nextRarity) {
  2649. await this.tryMergeBlock(target);
  2650. }
  2651. console.log(`[BlockManager] 合成完成`);
  2652. } catch (error) {
  2653. console.error('[BlockManager] performMerge 发生错误:', error);
  2654. // 合成失败时重新抛出错误,让上层处理
  2655. throw error;
  2656. }
  2657. }
  2658. private getBlockRarity(block: Node): string | null {
  2659. console.log(`[BlockManager] getBlockRarity 调用,方块名称: ${block.name}, UUID: ${block.uuid}`);
  2660. // 从Node子节点获取BlockInfo组件(适配新的预制体结构)
  2661. const nodeChild = block.getChildByName('Node');
  2662. const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
  2663. if (blockInfo) {
  2664. const rarityName = blockInfo.getRarityName();
  2665. console.log(`[BlockManager] 从BlockInfo组件获取稀有度: ${rarityName}`);
  2666. return rarityName;
  2667. }
  2668. console.log(`[BlockManager] 未找到BlockInfo组件`);
  2669. return null;
  2670. }
  2671. private getNextRarity(rarity: string): string | null {
  2672. const idx = this.rarityOrder.indexOf(rarity);
  2673. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  2674. return this.rarityOrder[idx + 1];
  2675. }
  2676. private getWorldAABB(node: Node): Rect {
  2677. const ui = node.getComponent(UITransform);
  2678. if (!ui) return new Rect();
  2679. const pos = node.worldPosition;
  2680. const width = ui.width;
  2681. const height = ui.height;
  2682. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  2683. }
  2684. private rectIntersects(a: Rect, b: Rect): boolean {
  2685. return a.x < b.x + b.width &&
  2686. a.x + a.width > b.x &&
  2687. a.y < b.y + b.height &&
  2688. a.y + a.height > b.y;
  2689. }
  2690. /** 生成烟雾特效 */
  2691. private spawnMergeSmoke(worldPos: Vec3) {
  2692. // 使用BundleLoader加载Animation Bundle中的特效资源
  2693. // 转换路径格式,去除"Animation/"前缀
  2694. const bundlePath = 'WeaponTx/tx0003/tx0003';
  2695. BundleLoader.loadSkeletonData(bundlePath).then((sData: sp.SkeletonData) => {
  2696. if (!sData) {
  2697. console.warn('加载合成烟雾动画失败: 资源为空');
  2698. return;
  2699. }
  2700. const node = new Node('MergeSmoke');
  2701. const skeleton = node.addComponent(sp.Skeleton);
  2702. skeleton.skeletonData = sData;
  2703. skeleton.premultipliedAlpha = false;
  2704. skeleton.setAnimation(0, 'animation', false);
  2705. skeleton.setCompleteListener(() => node.destroy());
  2706. const canvas = find('Canvas');
  2707. if (canvas) canvas.addChild(node);
  2708. node.setWorldPosition(worldPos);
  2709. }).catch((err) => {
  2710. console.warn('加载合成烟雾动画失败:', err);
  2711. });
  2712. }
  2713. /** 播放升级特效动画 */
  2714. private playUpgradeEffect(target: Node) {
  2715. try {
  2716. // 获取目标方块的世界坐标
  2717. const worldPos = new Vec3();
  2718. target.getWorldPosition(worldPos);
  2719. // 使用BundleLoader加载升级特效动画
  2720. const path = 'WeaponBurnAni/shengji';
  2721. BundleLoader.loadSkeletonData(path).then((sData: sp.SkeletonData) => {
  2722. if (!sData) {
  2723. console.warn('[BlockManager] 加载升级特效动画失败: 资源为空');
  2724. return;
  2725. }
  2726. // 创建特效节点
  2727. const effectNode = new Node('UpgradeEffect');
  2728. const skeleton = effectNode.addComponent(sp.Skeleton);
  2729. skeleton.skeletonData = sData;
  2730. skeleton.premultipliedAlpha = false;
  2731. // 播放动画
  2732. skeleton.setAnimation(0, 'animation', false);
  2733. // 监听动画完成事件,播放完成后销毁节点
  2734. skeleton.setCompleteListener(() => {
  2735. effectNode.destroy();
  2736. console.log('[BlockManager] 升级特效播放完成');
  2737. });
  2738. // 添加到Canvas并设置位置
  2739. const canvas = find('Canvas');
  2740. if (canvas) {
  2741. canvas.addChild(effectNode);
  2742. effectNode.setWorldPosition(worldPos);
  2743. console.log('[BlockManager] 开始播放升级特效动画');
  2744. } else {
  2745. console.warn('[BlockManager] 未找到Canvas节点,无法播放升级特效');
  2746. effectNode.destroy();
  2747. }
  2748. }).catch((err) => {
  2749. console.warn('[BlockManager] 加载升级特效动画失败:', err);
  2750. });
  2751. } catch (error) {
  2752. console.error('[BlockManager] 播放升级特效失败:', error);
  2753. }
  2754. }
  2755. /** 在放置失败时尝试与现有方块进行合成 */
  2756. public tryMergeOnOverlap(draggedBlock: Node): boolean {
  2757. console.log(`[BlockManager] tryMergeOnOverlap 开始检查合成`);
  2758. console.log(`[BlockManager] 拖拽方块名称: ${draggedBlock.name}`);
  2759. if (!this.placedBlocksContainer) {
  2760. console.log(`[BlockManager] placedBlocksContainer 不存在`);
  2761. return false;
  2762. }
  2763. const rarity = this.getBlockRarity(draggedBlock);
  2764. if (!rarity) {
  2765. console.log(`[BlockManager] 拖拽方块稀有度为空`);
  2766. return false;
  2767. }
  2768. console.log(`[BlockManager] 拖拽方块稀有度: ${rarity}`);
  2769. console.log(`[BlockManager] 已放置方块数量: ${this.placedBlocksContainer.children.length}`);
  2770. const dragBB = this.getWorldAABB(draggedBlock);
  2771. for (const target of this.placedBlocksContainer.children) {
  2772. if (target === draggedBlock) continue;
  2773. console.log(`[BlockManager] 检查与方块 ${target.name} 的合成可能性`);
  2774. // 使用新的合成检查方法
  2775. if (!this.canMergeBlocks(draggedBlock, target)) {
  2776. console.log(`[BlockManager] 与方块 ${target.name} 无法合成`);
  2777. continue;
  2778. }
  2779. const targetBB = this.getWorldAABB(target);
  2780. console.log(`[BlockManager] 检查方块碰撞`);
  2781. if (this.rectIntersects(dragBB, targetBB)) {
  2782. console.log(`[BlockManager] 方块重叠,执行合成`);
  2783. // 扩展教程(第5-6步):仅允许在指定格子处合成
  2784. if (this._tutorialStep >= 5 && this._tutorialStep < 7) {
  2785. const basePair = this._tutorialStep >= 6 ? this._tutorialTargetGridsStep4 : this._tutorialTargetGridsStep2;
  2786. if (basePair && basePair.length === 2) {
  2787. const pairKey = (arr: string[]) => arr.slice().sort().join('|');
  2788. const occupied = (target as any)['occupiedGrids'] as { row: number, col: number }[] | undefined;
  2789. if (occupied && occupied.length >= 2) {
  2790. const occupiedNames = occupied.map(g => `Grid_${g.row}_${g.col}`);
  2791. const parse = (name: string) => {
  2792. const m = name.match(/^Grid_(\d+)_(\d+)$/);
  2793. return m ? { row: parseInt(m[1]), col: parseInt(m[2]) } : null;
  2794. };
  2795. const p0 = parse(basePair[0]);
  2796. const p1 = parse(basePair[1]);
  2797. if (p0 && p1) {
  2798. let anchor = p0;
  2799. if (p0.row !== p1.row) {
  2800. anchor = p0.row < p1.row ? p0 : p1;
  2801. } else if (p0.col !== p1.col) {
  2802. anchor = p0.col < p1.col ? p0 : p1;
  2803. }
  2804. const horizontalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row}_${anchor.col + 1}`];
  2805. const verticalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row + 1}_${anchor.col}`];
  2806. const allowedPairs = new Set<string>([
  2807. pairKey(horizontalPair),
  2808. pairKey(verticalPair),
  2809. pairKey(basePair),
  2810. ]);
  2811. const occupiedKey = pairKey(occupiedNames);
  2812. if (!allowedPairs.has(occupiedKey)) {
  2813. console.log(`[BlockManager] 扩展教程:目标位置不在要求格子,禁止合成`);
  2814. continue;
  2815. }
  2816. }
  2817. }
  2818. }
  2819. }
  2820. // 执行合并:目标保留,拖拽方块销毁
  2821. this.performMerge(target, draggedBlock, rarity);
  2822. return true;
  2823. } else {
  2824. console.log(`[BlockManager] 方块不重叠,跳过合成`);
  2825. }
  2826. }
  2827. console.log(`[BlockManager] 没有找到可合成的方块`);
  2828. return false;
  2829. }
  2830. // 调试绘制功能已迁移到GameBlockSelection
  2831. // 输出格子占用情况矩阵
  2832. public printGridOccupationMatrix() {
  2833. console.log('[BlockManager] 格子占用情况de矩阵 (6行11列):');
  2834. for (let row = 0; row < this.GRID_ROWS; row++) {
  2835. let rowStr = '';
  2836. for (let col = 0; col < this.GRID_COLS; col++) {
  2837. rowStr += this.gridOccupationMap[row][col] + ' ';
  2838. }
  2839. console.log(`第${row + 1}行: ${rowStr.trim()}`);
  2840. }
  2841. }
  2842. // 通过GameBlockSelection刷新方块占用情况
  2843. onDestroy() {
  2844. // 调试绘制功能已迁移到GameBlockSelection
  2845. // 清理事件监听
  2846. const eventBus = EventBus.getInstance();
  2847. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  2848. eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  2849. // 移除GAME_START事件清理,因为已不再监听该事件
  2850. // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  2851. eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  2852. }
  2853. }