BlockManager.ts 134 KB

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