BlockManager.ts 95 KB

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