BlockManager.ts 107 KB

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