BlockManager.ts 105 KB

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