BlockManager.ts 112 KB

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