BlockManager.ts 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Vec2, UITransform, find, Rect, Label, Color, Size, Sprite, SpriteFrame, resources, Button, Collider2D } from 'cc';
  2. import { ConfigManager, WeaponConfig } from '../Core/ConfigManager';
  3. import { SaveDataManager } from '../LevelSystem/SaveDataManager';
  4. import { LevelSessionManager } from '../Core/LevelSessionManager';
  5. import { LevelConfigManager } from '../LevelSystem/LevelConfigManager';
  6. import { BlockTag } from './BlockSelection/BlockTag';
  7. import { SkillManager } from './SkillSelection/SkillManager';
  8. import EventBus, { GameEvents } from '../Core/EventBus';
  9. import { sp } from 'cc';
  10. const { ccclass, property } = _decorator;
  11. @ccclass('BlockManager')
  12. export class BlockManager extends Component {
  13. // 预制体数组,存储5个预制体
  14. @property([Prefab])
  15. public blockPrefabs: Prefab[] = [];
  16. // 网格容器节点
  17. @property({
  18. type: Node,
  19. tooltip: '拖拽GridContainer节点到这里'
  20. })
  21. public gridContainer: Node = null;
  22. // 方块容器节点(kuang)
  23. @property({
  24. type: Node,
  25. tooltip: '拖拽kuang节点到这里'
  26. })
  27. public kuangContainer: Node = null;
  28. // 金币标签节点
  29. @property({
  30. type: Node,
  31. tooltip: '拖拽CoinLabel节点到这里'
  32. })
  33. public coinLabelNode: Node = null;
  34. // 已放置方块容器节点
  35. @property({
  36. type: Node,
  37. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)'
  38. })
  39. public placedBlocksContainer: Node = null;
  40. // 游戏是否已开始
  41. public gameStarted: boolean = false;
  42. // 移除移动冷却:相关属性/逻辑已废弃
  43. // SaveDataManager 单例
  44. private saveDataManager: SaveDataManager = null; // 仅用于局外数据
  45. private session: LevelSessionManager = null;
  46. // 方块价格标签映射
  47. private blockPriceMap: Map<Node, Node> = new Map();
  48. // 已经生成的块
  49. private blocks: Node[] = [];
  50. // 当前拖拽的块
  51. private currentDragBlock: Node | null = null;
  52. // 拖拽起始位置
  53. private startPos = new Vec2();
  54. // 块的起始位置
  55. private blockStartPos: Vec3 = new Vec3();
  56. // 网格占用情况,用于控制台输出
  57. private gridOccupationMap: number[][] = [];
  58. // 网格行数和列数
  59. private readonly GRID_ROWS = 6;
  60. private readonly GRID_COLS = 11;
  61. // 是否已初始化网格信息
  62. private gridInitialized = false;
  63. // 存储网格节点信息
  64. private gridNodes: Node[][] = [];
  65. // 网格间距
  66. private gridSpacing = 54;
  67. // 不参与占用的节点名称列表
  68. private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
  69. // 临时保存方块的原始占用格子
  70. private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  71. // 方块原始位置(在kuang中的位置)
  72. private originalPositions: Map<Node, Vec3> = new Map();
  73. // 方块当前所在的区域
  74. private blockLocations: Map<Node, string> = new Map();
  75. // 配置管理器
  76. private configManager: ConfigManager = null;
  77. // 关卡配置管理器
  78. private levelConfigManager: LevelConfigManager = null;
  79. // 方块武器配置映射
  80. private blockWeaponConfigs: Map<Node, WeaponConfig> = new Map();
  81. /** 冷却机制已废弃,方块随时可移动 */
  82. private canMoveBlock(block: Node): boolean { return true; }
  83. // 清除所有冷却(游戏重置时调用)
  84. public clearAllCooldowns() { /* no-op */ }
  85. // 获取当前关卡的武器配置列表
  86. private async getCurrentLevelWeapons(): Promise<string[]> {
  87. if (!this.levelConfigManager || !this.saveDataManager) {
  88. console.warn('关卡配置管理器或存档管理器未初始化,使用默认武器列表');
  89. return [];
  90. }
  91. try {
  92. const currentLevel = this.saveDataManager.getCurrentLevel();
  93. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  94. if (levelConfig && levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
  95. console.log(`关卡 ${currentLevel} 配置的武器:`, levelConfig.weapons);
  96. return levelConfig.weapons;
  97. } else {
  98. console.warn(`关卡 ${currentLevel} 没有配置武器列表`);
  99. return [];
  100. }
  101. } catch (error) {
  102. console.error('获取当前关卡武器配置失败:', error);
  103. return [];
  104. }
  105. }
  106. // 根据武器名称获取武器配置
  107. private getWeaponConfigByName(weaponName: string): WeaponConfig | null {
  108. if (!this.configManager) return null;
  109. const allWeapons = this.configManager.getAllWeapons();
  110. return allWeapons.find(weapon => weapon.name === weaponName) || null;
  111. }
  112. // 设置事件监听器
  113. private setupEventListeners() {
  114. const eventBus = EventBus.getInstance();
  115. // 监听重置方块管理器事件
  116. eventBus.on(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  117. // 监听方块生成事件
  118. eventBus.on(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  119. // 移除GAME_START事件监听,避免与GameBlockSelection重复生成方块
  120. // eventBus.on(GameEvents.GAME_START, this.onGameStartEvent, this);
  121. // 监听波次完成事件(每波结束后生成新方块)
  122. eventBus.on(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  123. }
  124. // 处理重置方块管理器事件
  125. private onResetBlockManagerEvent() {
  126. console.log('[BlockManager] 接收到重置方块管理器事件');
  127. this.onGameReset();
  128. }
  129. // 处理方块生成事件
  130. private onGenerateBlocksEvent() {
  131. console.log('[BlockManager] 接收到方块生成事件');
  132. this.generateRandomBlocksInKuang();
  133. }
  134. // 处理游戏开始事件 - 已废弃,避免与GameBlockSelection重复生成方块
  135. // private onGameStartEvent() {
  136. // console.log('[BlockManager] 接收到游戏开始事件,生成初始方块');
  137. // this.generateRandomBlocksInKuang();
  138. // }
  139. // 处理波次完成事件
  140. private onWaveCompletedEvent() {
  141. console.log('[BlockManager] 接收到波次完成事件,生成新方块');
  142. this.generateRandomBlocksInKuang();
  143. }
  144. start() {
  145. // 获取配置管理器
  146. this.configManager = ConfigManager.getInstance();
  147. if (!this.configManager) {
  148. console.error('无法获取ConfigManager实例');
  149. }
  150. // 获取关卡配置管理器
  151. this.levelConfigManager = LevelConfigManager.getInstance();
  152. if (!this.levelConfigManager) {
  153. console.error('无法获取LevelConfigManager实例');
  154. }
  155. // 如果没有指定GridContainer,尝试找到它
  156. if (!this.gridContainer) {
  157. this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
  158. if (!this.gridContainer) {
  159. console.error('找不到GridContainer节点');
  160. return;
  161. }
  162. }
  163. // 如果没有指定kuangContainer,尝试找到它
  164. if (!this.kuangContainer) {
  165. this.kuangContainer = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
  166. if (!this.kuangContainer) {
  167. console.error('找不到kuang节点');
  168. return;
  169. }
  170. }
  171. // 如果没有指定coinLabelNode,尝试找到它
  172. if (!this.coinLabelNode) {
  173. this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
  174. if (!this.coinLabelNode) {
  175. console.error('找不到CoinLabel节点');
  176. return;
  177. }
  178. }
  179. // 如果没有指定placedBlocksContainer,尝试找到它
  180. if (!this.placedBlocksContainer) {
  181. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  182. }
  183. // 确保有PlacedBlocks节点用于存放已放置的方块
  184. this.ensurePlacedBlocksNode();
  185. // 获取数据管理器
  186. this.saveDataManager = SaveDataManager.getInstance();
  187. this.session = LevelSessionManager.inst;
  188. // 初始化玩家金币显示
  189. this.updateCoinDisplay();
  190. // 初始化网格信息
  191. this.initGridInfo();
  192. // 初始化网格占用情况
  193. this.initGridOccupationMap();
  194. // 设置事件监听器
  195. this.setupEventListeners();
  196. // 移除自动生成方块逻辑,改为事件触发
  197. // 方块生成现在通过以下事件触发:
  198. // - GAME_START: 游戏开始时
  199. // - WAVE_COMPLETED: 每波敌人消灭后
  200. // - GENERATE_BLOCKS: 手动触发生成
  201. }
  202. // 确保有PlacedBlocks节点
  203. ensurePlacedBlocksNode() {
  204. // 如果已经通过拖拽设置了节点,直接使用
  205. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  206. return;
  207. }
  208. // 尝试查找节点
  209. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  210. if (this.placedBlocksContainer) {
  211. return;
  212. }
  213. // 如果找不到,创建新节点
  214. const gameLevelUI = find('Canvas/GameLevelUI');
  215. if (!gameLevelUI) {
  216. console.error('找不到GameLevelUI节点,无法创建PlacedBlocks');
  217. return;
  218. }
  219. this.placedBlocksContainer = new Node('PlacedBlocks');
  220. gameLevelUI.addChild(this.placedBlocksContainer);
  221. if (!this.placedBlocksContainer.getComponent(UITransform)) {
  222. this.placedBlocksContainer.addComponent(UITransform);
  223. }
  224. console.log('已在GameLevelUI下创建PlacedBlocks节点');
  225. }
  226. // 初始化网格信息
  227. initGridInfo() {
  228. if (!this.gridContainer || this.gridInitialized) return;
  229. this.gridNodes = [];
  230. for (let row = 0; row < this.GRID_ROWS; row++) {
  231. this.gridNodes[row] = [];
  232. }
  233. for (let i = 0; i < this.gridContainer.children.length; i++) {
  234. const grid = this.gridContainer.children[i];
  235. if (grid.name.startsWith('Grid_')) {
  236. const parts = grid.name.split('_');
  237. if (parts.length === 3) {
  238. const row = parseInt(parts[1]);
  239. const col = parseInt(parts[2]);
  240. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  241. this.gridNodes[row][col] = grid;
  242. }
  243. }
  244. }
  245. }
  246. if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
  247. if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
  248. const pos1 = this.gridNodes[0][0].position;
  249. const pos2 = this.gridNodes[1][0].position;
  250. this.gridSpacing = Math.abs(pos2.y - pos1.y);
  251. }
  252. }
  253. this.gridInitialized = true;
  254. }
  255. // 初始化网格占用情况
  256. initGridOccupationMap() {
  257. this.gridOccupationMap = [];
  258. for (let row = 0; row < this.GRID_ROWS; row++) {
  259. const rowArray: number[] = [];
  260. for (let col = 0; col < this.GRID_COLS; col++) {
  261. rowArray.push(0);
  262. }
  263. this.gridOccupationMap.push(rowArray);
  264. }
  265. }
  266. // 在kuang下生成三个方块(基于关卡配置)
  267. private async generateRandomBlocksInKuang() {
  268. // 清除kuang区域中的旧方块,但不清除已放置在网格中的方块的标签
  269. this.clearBlocks();
  270. // 检查配置管理器是否可用
  271. if (!this.configManager || !this.configManager.isConfigLoaded()) {
  272. console.warn('配置管理器未初始化或配置未加载完成,延迟生成方块');
  273. this.scheduleOnce(() => {
  274. this.generateRandomBlocksInKuang();
  275. }, 1.0);
  276. return;
  277. }
  278. if (this.blockPrefabs.length === 0) {
  279. console.error('没有可用的预制体');
  280. return;
  281. }
  282. const kuangNode = this.kuangContainer;
  283. if (!kuangNode) {
  284. console.error('找不到kuang节点');
  285. return;
  286. }
  287. const offsets = [
  288. new Vec3(-200, 0, 0),
  289. new Vec3(0, 0, 0),
  290. new Vec3(200, 0, 0)
  291. ];
  292. const dbNodes = [
  293. kuangNode.getChildByName('db01'),
  294. kuangNode.getChildByName('db02'),
  295. kuangNode.getChildByName('db03')
  296. ];
  297. // 获取当前关卡的武器配置列表
  298. const levelWeapons = await this.getCurrentLevelWeapons();
  299. for (let i = 0; i < 3; i++) {
  300. let weaponConfig: WeaponConfig | null = null;
  301. // 优先使用关卡配置的武器,确保符合关卡设计
  302. if (levelWeapons.length > 0) {
  303. const randomWeaponName = levelWeapons[Math.floor(Math.random() * levelWeapons.length)];
  304. weaponConfig = this.getWeaponConfigByName(randomWeaponName);
  305. if (!weaponConfig) {
  306. console.warn(`关卡配置的武器 "${randomWeaponName}" 在武器配置文件中未找到`);
  307. }
  308. }
  309. // 如果关卡没有配置武器或获取失败,使用随机武器
  310. if (!weaponConfig) {
  311. weaponConfig = this.configManager.getRandomWeapon();
  312. }
  313. // 最后的兜底处理
  314. if (!weaponConfig) {
  315. console.warn('无法获取武器配置,使用默认武器');
  316. // 尝试获取一个基础武器作为兜底
  317. const allWeapons = this.configManager.getAllWeapons();
  318. if (allWeapons.length > 0) {
  319. weaponConfig = allWeapons[0];
  320. }
  321. }
  322. if (!weaponConfig) {
  323. console.error(`无法获取第 ${i + 1} 个武器配置`);
  324. continue;
  325. }
  326. // 基于武器配置选择合适的预制体
  327. const prefab = this.selectPrefabForWeapon(weaponConfig);
  328. if (!prefab) {
  329. console.error(`无法为武器 ${weaponConfig.name} 选择合适的预制体`);
  330. continue;
  331. }
  332. const block = instantiate(prefab);
  333. kuangNode.addChild(block);
  334. block.position = offsets[i];
  335. // 设置方块名称
  336. block.name = `WeaponBlock_${weaponConfig.id}`;
  337. // 保存武器配置到方块
  338. this.blockWeaponConfigs.set(block, weaponConfig);
  339. block['weaponConfig'] = weaponConfig;
  340. block['weaponId'] = weaponConfig.id;
  341. this.originalPositions.set(block, offsets[i].clone());
  342. this.blockLocations.set(block, 'kuang');
  343. this.blocks.push(block);
  344. if (dbNodes[i]) {
  345. const priceNode = dbNodes[i].getChildByName('Price');
  346. if (priceNode) {
  347. this.blockPriceMap.set(block, priceNode);
  348. priceNode.active = true;
  349. // 根据武器稀有度设置价格
  350. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity);
  351. }
  352. this.associateDbNodeWithBlock(block, dbNodes[i]);
  353. }
  354. // 设置方块的武器外观
  355. this.setupBlockWeaponVisual(block, weaponConfig);
  356. this.setupDragEvents(block);
  357. // 为新生成的方块添加标签
  358. BlockTag.addTag(block);
  359. console.log(`[BlockManager] 为方块 ${block.name} 添加标签,UUID: ${block.uuid}`);
  360. }
  361. this.updateCoinDisplay();
  362. }
  363. // 将db节点与方块关联
  364. associateDbNodeWithBlock(block: Node, dbNode: Node) {
  365. block['dbNode'] = dbNode;
  366. block.on(Node.EventType.TRANSFORM_CHANGED, () => {
  367. if (dbNode && block.parent) {
  368. const location = this.blockLocations.get(block);
  369. if (location === 'grid') {
  370. dbNode.active = false;
  371. return;
  372. }
  373. dbNode.active = true;
  374. const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position);
  375. const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  376. dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z);
  377. }
  378. });
  379. }
  380. // 更新金币显示
  381. updateCoinDisplay() {
  382. if (this.coinLabelNode) {
  383. const label = this.coinLabelNode.getComponent(Label);
  384. if (label) {
  385. const coins = this.session.getCoins();
  386. label.string = coins.toString();
  387. }
  388. }
  389. }
  390. // 获取方块价格
  391. getBlockPrice(block: Node): number {
  392. const priceNode = this.blockPriceMap.get(block);
  393. if (priceNode) {
  394. const label = priceNode.getComponent(Label);
  395. if (label) {
  396. const price = parseInt(label.string);
  397. if (!isNaN(price)) {
  398. return price;
  399. }
  400. }
  401. }
  402. return 50;
  403. }
  404. // 隐藏价格标签
  405. hidePriceLabel(block: Node) {
  406. const priceNode = this.blockPriceMap.get(block);
  407. if (priceNode) {
  408. priceNode.active = false;
  409. }
  410. }
  411. // 显示价格标签
  412. showPriceLabel(block: Node) {
  413. const priceNode = this.blockPriceMap.get(block);
  414. if (priceNode) {
  415. priceNode.active = true;
  416. }
  417. }
  418. // 扣除玩家金币
  419. deductPlayerCoins(amount: number): boolean {
  420. const success = this.session.spendCoins(amount);
  421. if (success) {
  422. this.updateCoinDisplay();
  423. }
  424. return success;
  425. }
  426. // 归还玩家金币
  427. refundPlayerCoins(amount: number) {
  428. this.session.addCoins(amount);
  429. this.updateCoinDisplay();
  430. }
  431. // 设置拖拽事件
  432. setupDragEvents(block: Node) {
  433. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  434. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  435. if (!this.canMoveBlock(block)) {
  436. return;
  437. }
  438. }
  439. this.currentDragBlock = block;
  440. this.startPos = event.getUILocation();
  441. this.blockStartPos.set(block.position);
  442. this.currentDragBlock['startLocation'] = this.blockLocations.get(block);
  443. block.setSiblingIndex(block.parent.children.length - 1);
  444. this.tempStoreBlockOccupiedGrids(block);
  445. // 拖拽开始时禁用碰撞体
  446. const collider = block.getComponent(Collider2D);
  447. if (collider) collider.enabled = false;
  448. }, this);
  449. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  450. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  451. if (!this.canMoveBlock(block)) {
  452. return;
  453. }
  454. }
  455. if (!this.currentDragBlock) return;
  456. const location = event.getUILocation();
  457. const deltaX = location.x - this.startPos.x;
  458. const deltaY = location.y - this.startPos.y;
  459. this.currentDragBlock.position = new Vec3(
  460. this.blockStartPos.x + deltaX,
  461. this.blockStartPos.y + deltaY,
  462. this.blockStartPos.z
  463. );
  464. }, this);
  465. block.on(Node.EventType.TOUCH_END, async (event: EventTouch) => {
  466. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  467. if (!this.canMoveBlock(block)) {
  468. return;
  469. }
  470. }
  471. if (this.currentDragBlock) {
  472. await this.handleBlockDrop(event);
  473. this.currentDragBlock = null;
  474. // 拖拽结束时恢复碰撞体
  475. const collider = block.getComponent(Collider2D);
  476. if (collider) collider.enabled = true;
  477. }
  478. }, this);
  479. block.on(Node.EventType.TOUCH_CANCEL, () => {
  480. if (this.currentDragBlock) {
  481. this.returnBlockToOriginalPosition();
  482. this.currentDragBlock = null;
  483. // 拖拽取消时恢复碰撞体
  484. const collider = block.getComponent(Collider2D);
  485. if (collider) collider.enabled = true;
  486. }
  487. }, this);
  488. }
  489. // 处理方块放下
  490. async handleBlockDrop(event: EventTouch) {
  491. const touchPos = event.getLocation();
  492. const startLocation = this.currentDragBlock['startLocation'];
  493. if (this.isInKuangArea(touchPos)) {
  494. // 检查是否有标签,只有有标签的方块才能放回kuang
  495. if (BlockTag.hasTag(this.currentDragBlock)) {
  496. this.returnBlockToKuang(startLocation);
  497. } else {
  498. // 没有标签的方块不能放回kuang,返回原位置
  499. console.log(`[BlockManager] 方块 ${this.currentDragBlock.name} 没有标签,不能放回kuang区域`);
  500. this.returnBlockToOriginalPosition();
  501. }
  502. } else if (this.tryPlaceBlockToGrid(this.currentDragBlock)) {
  503. await this.handleSuccessfulPlacement(startLocation);
  504. } else {
  505. console.log(`[BlockManager] 方块 ${this.currentDragBlock.name} 放置到网格失败`);
  506. console.log(`[BlockManager] 方块标签状态:`, BlockTag.hasTag(this.currentDragBlock));
  507. console.log(`[BlockManager] 方块UUID:`, this.currentDragBlock.uuid);
  508. // 放置失败,尝试直接与重叠方块合成
  509. if (this.tryMergeOnOverlap(this.currentDragBlock)) {
  510. // 合成成功时,若来自 kuang 则扣费
  511. if (startLocation !== 'grid') {
  512. const price = this.getBlockPrice(this.currentDragBlock);
  513. this.deductPlayerCoins(price);
  514. }
  515. // 当前拖拽块已被销毁(合并时),无需复位
  516. } else {
  517. console.log(`[BlockManager] 方块 ${this.currentDragBlock.name} 合成也失败,返回原位置`);
  518. this.returnBlockToOriginalPosition();
  519. }
  520. }
  521. }
  522. // 返回方块到kuang区域
  523. returnBlockToKuang(startLocation: string) {
  524. const originalPos = this.originalPositions.get(this.currentDragBlock);
  525. if (originalPos) {
  526. const kuangNode = this.kuangContainer;
  527. if (kuangNode && this.currentDragBlock.parent !== kuangNode) {
  528. this.currentDragBlock.removeFromParent();
  529. kuangNode.addChild(this.currentDragBlock);
  530. }
  531. this.currentDragBlock.position = originalPos.clone();
  532. }
  533. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  534. this.blockLocations.set(this.currentDragBlock, 'kuang');
  535. this.showPriceLabel(this.currentDragBlock);
  536. if (startLocation === 'grid') {
  537. const price = this.getBlockPrice(this.currentDragBlock);
  538. this.refundPlayerCoins(price);
  539. this.currentDragBlock['placedBefore'] = false;
  540. }
  541. const dbNode = this.currentDragBlock['dbNode'];
  542. if (dbNode) {
  543. dbNode.active = true;
  544. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  545. }
  546. }
  547. // 处理成功放置
  548. async handleSuccessfulPlacement(startLocation: string) {
  549. const price = this.getBlockPrice(this.currentDragBlock);
  550. if (startLocation === 'grid') {
  551. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  552. this.blockLocations.set(this.currentDragBlock, 'grid');
  553. this.hidePriceLabel(this.currentDragBlock);
  554. const dbNode = this.currentDragBlock['dbNode'];
  555. if (dbNode) {
  556. dbNode.active = false;
  557. }
  558. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  559. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  560. // 如果游戏已开始,添加锁定视觉提示
  561. if (this.gameStarted) {
  562. this.addLockedVisualHint(this.currentDragBlock);
  563. // 游戏开始后放置的方块移除标签,不能再放回kuang
  564. BlockTag.removeTag(this.currentDragBlock);
  565. }
  566. // 检查并执行合成
  567. await this.tryMergeBlock(this.currentDragBlock);
  568. } else {
  569. if (this.deductPlayerCoins(price)) {
  570. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  571. this.blockLocations.set(this.currentDragBlock, 'grid');
  572. this.hidePriceLabel(this.currentDragBlock);
  573. const dbNode = this.currentDragBlock['dbNode'];
  574. if (dbNode) {
  575. dbNode.active = false;
  576. }
  577. this.currentDragBlock['placedBefore'] = true;
  578. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  579. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  580. // 如果游戏已开始,添加锁定视觉提示
  581. if (this.gameStarted) {
  582. this.addLockedVisualHint(this.currentDragBlock);
  583. // 游戏开始后放置的方块移除标签,不能再放回kuang
  584. BlockTag.removeTag(this.currentDragBlock);
  585. }
  586. // 检查并执行合成
  587. await this.tryMergeBlock(this.currentDragBlock);
  588. } else {
  589. this.returnBlockToOriginalPosition();
  590. }
  591. }
  592. }
  593. // 返回方块到原位置
  594. returnBlockToOriginalPosition() {
  595. const currentLocation = this.blockLocations.get(this.currentDragBlock);
  596. if (currentLocation === 'kuang') {
  597. const originalPos = this.originalPositions.get(this.currentDragBlock);
  598. if (originalPos) {
  599. this.currentDragBlock.position = originalPos.clone();
  600. }
  601. } else {
  602. this.currentDragBlock.position = this.blockStartPos.clone();
  603. }
  604. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  605. this.showPriceLabel(this.currentDragBlock);
  606. const dbNode = this.currentDragBlock['dbNode'];
  607. if (dbNode) {
  608. dbNode.active = true;
  609. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  610. }
  611. }
  612. // 检查是否在kuang区域内
  613. isInKuangArea(touchPos: Vec2): boolean {
  614. if (!this.kuangContainer) return false;
  615. const kuangTransform = this.kuangContainer.getComponent(UITransform);
  616. if (!kuangTransform) return false;
  617. const kuangBoundingBox = new Rect(
  618. this.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  619. this.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  620. kuangTransform.width,
  621. kuangTransform.height
  622. );
  623. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  624. }
  625. // 临时保存方块占用的网格
  626. tempStoreBlockOccupiedGrids(block: Node) {
  627. const occupiedGrids = block['occupiedGrids'];
  628. if (!occupiedGrids || occupiedGrids.length === 0) return;
  629. this.tempRemovedOccupiedGrids.push({
  630. block: block,
  631. occupiedGrids: [...occupiedGrids]
  632. });
  633. for (const grid of occupiedGrids) {
  634. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  635. grid.col >= 0 && grid.col < this.GRID_COLS) {
  636. this.gridOccupationMap[grid.row][grid.col] = 0;
  637. }
  638. }
  639. block['occupiedGrids'] = [];
  640. }
  641. // 恢复方块原来的占用状态
  642. restoreBlockOccupiedGrids(block: Node) {
  643. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  644. if (index === -1) return;
  645. const savedItem = this.tempRemovedOccupiedGrids[index];
  646. for (const grid of savedItem.occupiedGrids) {
  647. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  648. grid.col >= 0 && grid.col < this.GRID_COLS) {
  649. this.gridOccupationMap[grid.row][grid.col] = 1;
  650. }
  651. }
  652. block['occupiedGrids'] = [...savedItem.occupiedGrids];
  653. this.tempRemovedOccupiedGrids.splice(index, 1);
  654. }
  655. // 清除临时保存的占用状态
  656. clearTempStoredOccupiedGrids(block: Node) {
  657. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  658. if (index === -1) return;
  659. this.tempRemovedOccupiedGrids.splice(index, 1);
  660. }
  661. // 尝试将方块放置到网格中
  662. tryPlaceBlockToGrid(block: Node): boolean {
  663. console.log(`[BlockManager] 尝试放置方块 ${block.name} 到网格`);
  664. if (!this.gridContainer || !this.gridInitialized) {
  665. console.log(`[BlockManager] 网格容器或网格未初始化`);
  666. return false;
  667. }
  668. let b1Node = block;
  669. if (block.name !== 'B1') {
  670. b1Node = block.getChildByName('B1');
  671. if (!b1Node) {
  672. console.log(`[BlockManager] 方块 ${block.name} 没有B1子节点`);
  673. return false;
  674. }
  675. }
  676. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  677. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  678. console.log(`[BlockManager] B1世界坐标:`, b1WorldPos);
  679. console.log(`[BlockManager] 网格本地坐标:`, gridPos);
  680. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  681. const halfWidth = gridSize.width / 2;
  682. const halfHeight = gridSize.height / 2;
  683. const tolerance = this.gridSpacing * 0.5;
  684. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  685. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  686. console.log(`[BlockManager] 方块超出网格边界`);
  687. return false;
  688. }
  689. const nearestGrid = this.findNearestGridNode(gridPos);
  690. if (!nearestGrid) {
  691. console.log(`[BlockManager] 找不到最近的网格节点`);
  692. return false;
  693. }
  694. console.log(`[BlockManager] 找到最近的网格节点: ${nearestGrid.name}`);
  695. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  696. }
  697. // 找到最近的网格节点
  698. findNearestGridNode(position: Vec3): Node {
  699. if (!this.gridContainer || !this.gridInitialized) return null;
  700. let nearestNode: Node = null;
  701. let minDistance = Number.MAX_VALUE;
  702. for (let row = 0; row < this.GRID_ROWS; row++) {
  703. for (let col = 0; col < this.GRID_COLS; col++) {
  704. const grid = this.gridNodes[row][col];
  705. if (grid) {
  706. const distance = Vec3.distance(position, grid.position);
  707. if (distance < minDistance) {
  708. minDistance = distance;
  709. nearestNode = grid;
  710. }
  711. }
  712. }
  713. }
  714. if (minDistance > this.gridSpacing * 2) {
  715. return null;
  716. }
  717. return nearestNode;
  718. }
  719. // 尝试将方块放置到指定的网格节点
  720. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  721. let b1Node = block;
  722. if (block.name !== 'B1') {
  723. b1Node = block.getChildByName('B1');
  724. if (!b1Node) {
  725. return false;
  726. }
  727. }
  728. if (!this.canPlaceBlockAt(block, targetGrid)) {
  729. return false;
  730. }
  731. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  732. const targetWorldPos = gridCenterWorldPos.clone();
  733. const b1LocalPos = b1Node.position.clone();
  734. let rootTargetWorldPos;
  735. if (b1Node === block) {
  736. rootTargetWorldPos = targetWorldPos.clone();
  737. } else {
  738. rootTargetWorldPos = new Vec3(
  739. targetWorldPos.x - b1LocalPos.x,
  740. targetWorldPos.y - b1LocalPos.y,
  741. targetWorldPos.z
  742. );
  743. }
  744. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  745. block.position = rootTargetLocalPos;
  746. this.markOccupiedPositions(block, targetGrid);
  747. return true;
  748. }
  749. // 检查方块是否可以放置在指定位置
  750. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  751. if (!this.gridInitialized) {
  752. console.log(`[BlockManager] 网格未初始化`);
  753. return false;
  754. }
  755. const targetRowCol = this.getGridRowCol(targetGrid);
  756. if (!targetRowCol) {
  757. console.log(`[BlockManager] 无法获取目标网格的行列信息`);
  758. return false;
  759. }
  760. const parts = this.getBlockParts(block);
  761. for (let i = 0; i < parts.length; i++) {
  762. const part = parts[i];
  763. const row = targetRowCol.row - part.y;
  764. const col = targetRowCol.col + part.x;
  765. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  766. console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`);
  767. return false;
  768. }
  769. if (this.gridOccupationMap[row][col] === 1) {
  770. console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`);
  771. return false;
  772. }
  773. }
  774. return true;
  775. }
  776. // 获取网格行列索引
  777. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  778. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  779. const parts = gridNode.name.split('_');
  780. if (parts.length === 3) {
  781. const row = parseInt(parts[1]);
  782. const col = parseInt(parts[2]);
  783. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  784. return { row, col };
  785. }
  786. }
  787. return null;
  788. }
  789. // 获取方块的所有部分节点及其相对坐标
  790. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  791. const parts: { node: Node, x: number, y: number }[] = [];
  792. // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
  793. const b1Node = block.getChildByName('B1');
  794. if (b1Node) {
  795. // B1节点作为(0,0)位置
  796. parts.push({ node: b1Node, x: 0, y: 0 });
  797. this.findBlockParts(b1Node, parts, 0, 0);
  798. } else {
  799. // 没有B1节点,使用根节点
  800. parts.push({ node: block, x: 0, y: 0 });
  801. this.findBlockParts(block, parts, 0, 0);
  802. }
  803. return parts;
  804. }
  805. // 递归查找方块的所有部分
  806. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  807. for (let i = 0; i < node.children.length; i++) {
  808. const child = node.children[i];
  809. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  810. continue;
  811. }
  812. let x = parentX;
  813. let y = parentY;
  814. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  815. if (match) {
  816. x = parseInt(match[1]);
  817. y = parseInt(match[2]);
  818. result.push({ node: child, x, y });
  819. } else if (child.name.startsWith('B')) {
  820. const relativeX = Math.round(child.position.x / this.gridSpacing);
  821. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  822. x = parentX + relativeX;
  823. y = parentY + relativeY;
  824. result.push({ node: child, x, y });
  825. }
  826. this.findBlockParts(child, result, x, y);
  827. }
  828. }
  829. // 标记方块占用的格子
  830. markOccupiedPositions(block: Node, targetGrid: Node) {
  831. if (!this.gridInitialized) return;
  832. const targetRowCol = this.getGridRowCol(targetGrid);
  833. if (!targetRowCol) return;
  834. const parts = this.getBlockParts(block);
  835. block['occupiedGrids'] = [];
  836. for (const part of parts) {
  837. const row = targetRowCol.row - part.y;
  838. const col = targetRowCol.col + part.x;
  839. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  840. this.gridOccupationMap[row][col] = 1;
  841. block['occupiedGrids'] = block['occupiedGrids'] || [];
  842. block['occupiedGrids'].push({ row, col });
  843. }
  844. }
  845. }
  846. // 清除方块
  847. clearBlocks() {
  848. console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
  849. const blocksToRemove = [];
  850. for (const block of this.blocks) {
  851. if (block.isValid) {
  852. const location = this.blockLocations.get(block);
  853. if (location === 'kuang') {
  854. blocksToRemove.push(block);
  855. }
  856. }
  857. }
  858. console.log('[BlockManager] 找到需要清理的kuang区域方块数量:', blocksToRemove.length);
  859. for (const block of blocksToRemove) {
  860. const dbNode = block['dbNode'];
  861. if (dbNode && dbNode.isValid) {
  862. block.off(Node.EventType.TRANSFORM_CHANGED);
  863. const kuangNode = this.kuangContainer;
  864. if (kuangNode) {
  865. const dbName = dbNode.name;
  866. if (!kuangNode.getChildByName(dbName)) {
  867. dbNode.parent = kuangNode;
  868. }
  869. }
  870. }
  871. const index = this.blocks.indexOf(block);
  872. if (index !== -1) {
  873. this.blocks.splice(index, 1);
  874. }
  875. this.originalPositions.delete(block);
  876. this.blockLocations.delete(block);
  877. this.blockPriceMap.delete(block);
  878. // 清理武器配置映射
  879. this.blockWeaponConfigs.delete(block);
  880. console.log('[BlockManager] 销毁kuang区域方块:', block.name);
  881. block.destroy();
  882. }
  883. console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
  884. }
  885. // 游戏开始时调用
  886. onGameStart() {
  887. this.gameStarted = true;
  888. for (const block of this.blocks) {
  889. if (block.isValid) {
  890. const location = this.blockLocations.get(block);
  891. if (location === 'grid') {
  892. this.hidePriceLabel(block);
  893. const dbNode = block['dbNode'];
  894. if (dbNode) {
  895. dbNode.active = false;
  896. }
  897. this.moveBlockToPlacedBlocks(block);
  898. this.addLockedVisualHint(block);
  899. // 游戏开始后放置的方块移除标签,不能再放回kuang
  900. BlockTag.removeTag(block);
  901. }
  902. }
  903. }
  904. }
  905. // 游戏重置时调用
  906. onGameReset() {
  907. console.log('[BlockManager] 游戏重置,清理所有状态');
  908. console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
  909. this.gameStarted = false;
  910. this.clearAllCooldowns();
  911. // 清理已放置的方块
  912. console.log('[BlockManager] 开始清理已放置的方块');
  913. this.clearPlacedBlocks();
  914. // 重置网格占用状态
  915. console.log('[BlockManager] 开始重置网格占用状态');
  916. this.resetGridOccupation();
  917. // 清理kuang区域的方块
  918. console.log('[BlockManager] 开始清理kuang区域的方块');
  919. this.clearBlocks();
  920. // 清理所有方块标签
  921. console.log('[BlockManager] 开始清理所有方块标签');
  922. BlockTag.clearAllTags();
  923. console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
  924. // 重新生成方块
  925. console.log('[BlockManager] 开始重新生成方块');
  926. this.generateRandomBlocksInKuang();
  927. console.log('[BlockManager] 游戏重置完成');
  928. }
  929. // 清理已放置的方块
  930. private clearPlacedBlocks() {
  931. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  932. console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
  933. return;
  934. }
  935. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  936. // 清理PlacedBlocks容器中的所有方块
  937. const placedBlocks = [...this.placedBlocksContainer.children];
  938. let clearedCount = 0;
  939. for (const block of placedBlocks) {
  940. if (block && block.isValid) {
  941. // 从blocks数组中移除
  942. const index = this.blocks.indexOf(block);
  943. if (index !== -1) {
  944. this.blocks.splice(index, 1);
  945. }
  946. // 清理相关映射
  947. this.originalPositions.delete(block);
  948. this.blockLocations.delete(block);
  949. this.blockPriceMap.delete(block);
  950. this.blockWeaponConfigs.delete(block);
  951. console.log('[BlockManager] 销毁已放置方块:', block.name);
  952. // 销毁方块
  953. block.destroy();
  954. clearedCount++;
  955. }
  956. }
  957. console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
  958. }
  959. // 重置网格占用状态
  960. private resetGridOccupation() {
  961. console.log('[BlockManager] 重置网格占用状态');
  962. // 重新初始化网格占用地图
  963. this.gridOccupationMap = [];
  964. for (let row = 0; row < this.GRID_ROWS; row++) {
  965. this.gridOccupationMap[row] = [];
  966. for (let col = 0; col < this.GRID_COLS; col++) {
  967. this.gridOccupationMap[row][col] = 0;
  968. }
  969. }
  970. // 清理临时存储的占用状态
  971. this.tempRemovedOccupiedGrids = [];
  972. }
  973. // 添加视觉提示,表明方块已锁定
  974. addLockedVisualHint(block: Node) {
  975. const children = block.children;
  976. for (let i = 0; i < children.length; i++) {
  977. const child = children[i];
  978. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  979. continue;
  980. }
  981. child.setScale(new Vec3(0.95, 0.95, 1));
  982. }
  983. }
  984. // 将方块移动到PlacedBlocks节点下
  985. moveBlockToPlacedBlocks(block: Node) {
  986. if (!this.placedBlocksContainer) {
  987. console.error('PlacedBlocks容器未设置');
  988. return;
  989. }
  990. if (!this.placedBlocksContainer.isValid) {
  991. console.error('PlacedBlocks容器已失效');
  992. return;
  993. }
  994. const worldPosition = new Vec3();
  995. block.getWorldPosition(worldPosition);
  996. // 移除旧的触摸事件监听器
  997. block.off(Node.EventType.TOUCH_START);
  998. block.off(Node.EventType.TOUCH_MOVE);
  999. block.off(Node.EventType.TOUCH_END);
  1000. block.off(Node.EventType.TOUCH_CANCEL);
  1001. block.removeFromParent();
  1002. this.placedBlocksContainer.addChild(block);
  1003. block.setWorldPosition(worldPosition);
  1004. // 重新设置触摸事件监听器
  1005. this.setupDragEvents(block);
  1006. }
  1007. // 根据武器配置选择合适的预制体
  1008. private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null {
  1009. if (this.blockPrefabs.length === 0) {
  1010. return null;
  1011. }
  1012. // 获取所有可用的方块形状配置
  1013. const blockShapes = this.configManager.getBlockShapes();
  1014. if (!blockShapes || blockShapes.length === 0) {
  1015. console.warn('没有可用的方块形状配置,使用随机预制体');
  1016. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  1017. return this.blockPrefabs[randomIndex];
  1018. }
  1019. // 随机选择一个方块形状
  1020. const randomShapeIndex = Math.floor(Math.random() * blockShapes.length);
  1021. const targetShape = blockShapes[randomShapeIndex];
  1022. // 寻找与目标形状匹配的预制体
  1023. const matchingPrefab = this.findMatchingPrefab(targetShape);
  1024. if (matchingPrefab) {
  1025. console.log(`为武器 ${weaponConfig.name} 选择了匹配的预制体,形状: ${targetShape.name}`);
  1026. return matchingPrefab;
  1027. }
  1028. // 如果没有找到匹配的预制体,使用随机预制体
  1029. console.warn(`没有找到匹配形状 ${targetShape.name} 的预制体,使用随机预制体`);
  1030. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  1031. return this.blockPrefabs[randomIndex];
  1032. }
  1033. // 根据稀有度设置方块价格
  1034. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  1035. const label = priceNode.getComponent(Label);
  1036. if (!label) {
  1037. return;
  1038. }
  1039. let basePrice: number;
  1040. switch (rarity) {
  1041. case 'common':
  1042. basePrice = 10;
  1043. break;
  1044. case 'uncommon':
  1045. basePrice = 20;
  1046. break;
  1047. case 'rare':
  1048. basePrice = 50;
  1049. break;
  1050. case 'epic':
  1051. basePrice = 100;
  1052. break;
  1053. case 'legendary':
  1054. basePrice = 150;
  1055. break;
  1056. default:
  1057. basePrice = 200;
  1058. }
  1059. // 应用便宜技能效果
  1060. const skillManager = SkillManager.getInstance();
  1061. let finalPrice = basePrice;
  1062. if (skillManager) {
  1063. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1064. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1065. }
  1066. label.string = finalPrice.toString();
  1067. }
  1068. // 设置方块的武器外观
  1069. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  1070. // 设置方块的稀有度颜色
  1071. this.setBlockRarityColor(block, weaponConfig.rarity);
  1072. // 加载武器图标
  1073. this.loadWeaponIcon(block, weaponConfig);
  1074. }
  1075. // 设置方块稀有度颜色
  1076. private setBlockRarityColor(block: Node, rarity: string) {
  1077. this.applyBlockRarityColor(block, rarity);
  1078. }
  1079. // 公共方法:应用方块稀有度颜色(供外部调用)
  1080. public applyBlockRarityColor(block: Node, rarity: string) {
  1081. // Add null safety check for block
  1082. if (!block || !block.isValid) {
  1083. return;
  1084. }
  1085. const sprite = block.getComponent(Sprite);
  1086. if (!sprite || !sprite.isValid) {
  1087. return;
  1088. }
  1089. // 根据稀有度设置颜色
  1090. let color: Color;
  1091. switch (rarity) {
  1092. case 'common':
  1093. color = new Color(255, 255, 255); // 白色
  1094. break;
  1095. case 'uncommon':
  1096. color = new Color(0, 255, 0); // 绿色
  1097. break;
  1098. case 'rare':
  1099. color = new Color(0, 100, 255); // 蓝色
  1100. break;
  1101. case 'epic':
  1102. color = new Color(160, 32, 240); // 紫色
  1103. break;
  1104. case 'legendary':
  1105. color = new Color(255, 165, 0); // 橙色
  1106. break;
  1107. default:
  1108. color = new Color(255, 255, 255); // 默认白色
  1109. }
  1110. sprite.color = color;
  1111. console.log(`[BlockManager] 设置方块稀有度颜色: ${rarity}`, color);
  1112. }
  1113. // 加载武器图标
  1114. private loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  1115. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  1116. const b1Node = block.getChildByName('B1');
  1117. if (!b1Node) {
  1118. console.warn('找不到B1节点');
  1119. return;
  1120. }
  1121. const weaponNode = b1Node.getChildByName('Weapon');
  1122. if (!weaponNode) {
  1123. console.warn('找不到Weapon节点');
  1124. return;
  1125. }
  1126. const weaponSprite = weaponNode.getComponent(Sprite);
  1127. if (!weaponSprite) {
  1128. console.warn('Weapon节点上没有Sprite组件');
  1129. return;
  1130. }
  1131. // 获取武器配置中的图片路径
  1132. const spriteConfig = weaponConfig.visualConfig?.weaponSprites;
  1133. if (!spriteConfig) {
  1134. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  1135. return;
  1136. }
  1137. // 获取方块的形状ID
  1138. const blockShapeId = this.getBlockShape(block);
  1139. // 根据方块形状选择合适的图片路径
  1140. let spritePath = null;
  1141. if (blockShapeId && spriteConfig[blockShapeId]) {
  1142. spritePath = spriteConfig[blockShapeId];
  1143. } else {
  1144. // 如果没有找到对应形状的图片,使用备用顺序
  1145. spritePath = spriteConfig['I'] || spriteConfig['H-I'] || spriteConfig['L'] || spriteConfig['S'] || spriteConfig['D-T'];
  1146. }
  1147. if (!spritePath) {
  1148. console.warn(`武器 ${weaponConfig.name} 没有可用的图片路径`);
  1149. return;
  1150. }
  1151. // 正确的SpriteFrame子资源路径
  1152. const spriteFramePath = `${spritePath}/spriteFrame`;
  1153. // 加载SpriteFrame子资源
  1154. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  1155. if (err) {
  1156. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  1157. return;
  1158. }
  1159. // Add comprehensive null safety checks before setting spriteFrame
  1160. if (weaponSprite && weaponSprite.isValid &&
  1161. weaponNode && weaponNode.isValid &&
  1162. block && block.isValid &&
  1163. spriteFrame && spriteFrame.isValid) {
  1164. weaponSprite.spriteFrame = spriteFrame;
  1165. // 根据武器类型和方块形状旋转图片
  1166. this.rotateWeaponIconByShape(weaponNode, blockShapeId, weaponConfig.id);
  1167. }
  1168. });
  1169. }
  1170. // 武器类型和方块形状组合的旋转角度配置
  1171. private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
  1172. 'pea_shooter': {
  1173. 'I': 0, // 毛豆射手竖条形状
  1174. 'H-I': 90, // 毛豆射手横条形状
  1175. 'L': 0, // 毛豆射手L型
  1176. 'S': 0, // 毛豆射手S型
  1177. 'D-T': 0 // 毛豆射手倒T型
  1178. },
  1179. 'sharp_carrot': {
  1180. 'I': 0, // 尖胡萝卜竖条形状
  1181. 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
  1182. 'L': -15, // 尖胡萝卜L型,轻微调整
  1183. 'S': 15, // 尖胡萝卜S型,轻微调整
  1184. 'D-T': 0 // 尖胡萝卜倒T型
  1185. },
  1186. 'saw_grass': {
  1187. 'I': 0, // 锯齿草竖条形状
  1188. 'H-I': 90, // 锯齿草横条形状
  1189. 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
  1190. 'S': 30, // 锯齿草S型,适配锯齿弯曲
  1191. 'D-T': 0 // 锯齿草倒T型
  1192. },
  1193. 'watermelon_bomb': {
  1194. 'I': 0, // 西瓜炸弹竖条形状
  1195. 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
  1196. 'L': 0, // 西瓜炸弹L型
  1197. 'S': 0, // 西瓜炸弹S型
  1198. 'D-T': 0 // 西瓜炸弹倒T型
  1199. },
  1200. 'boomerang_plant': {
  1201. 'I': 0, // 回旋镖植物竖条形状
  1202. 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
  1203. 'L': -30, // 回旋镖植物L型
  1204. 'S': 45, // 回旋镖植物S型,适配回旋轨迹
  1205. 'D-T': 0 // 回旋镖植物倒T型
  1206. },
  1207. 'hot_pepper': {
  1208. 'I': 0, // 辣椒竖条形状
  1209. 'H-I': 90, // 辣椒横条形状
  1210. 'L': 0, // 辣椒L型
  1211. 'S': 0, // 辣椒S型
  1212. 'D-T': 0 // 辣椒倒T型
  1213. },
  1214. 'cactus_shotgun': {
  1215. 'I': 0, // 仙人掌霰弹枪竖条形状
  1216. 'H-I': 90, // 仙人掌霰弹枪横条形状
  1217. 'L': -20, // 仙人掌霰弹枪L型
  1218. 'S': 20, // 仙人掌霰弹枪S型
  1219. 'D-T': 0 // 仙人掌霰弹枪倒T型
  1220. },
  1221. 'okra_missile': {
  1222. 'I': 0, // 秋葵导弹竖条形状
  1223. 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
  1224. 'L': -10, // 秋葵导弹L型
  1225. 'S': 10, // 秋葵导弹S型
  1226. 'D-T': 0 // 秋葵导弹倒T型
  1227. },
  1228. 'mace_club': {
  1229. 'I': 0, // 狼牙棒竖条形状
  1230. 'H-I': 90, // 狼牙棒横条形状
  1231. 'L': -25, // 狼牙棒L型,适配棒状武器
  1232. 'S': 25, // 狼牙棒S型
  1233. 'D-T': 0 // 狼牙棒倒T型
  1234. }
  1235. };
  1236. // 默认旋转角度配置(当武器类型未配置时使用)
  1237. private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
  1238. 'I': 0, // 竖条形状,保持原始方向
  1239. 'H-I': 90, // 横I型,旋转90度适配水平方向
  1240. 'L': -15, // L型,轻微左倾适配L形状的转角
  1241. 'S': 15, // S型,轻微右倾适配S形状的弯曲
  1242. 'D-T': 0 // 倒T型,保持原始方向
  1243. };
  1244. // 根据武器类型和方块形状旋转武器图标
  1245. private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1246. if (!weaponNode || !shapeId) return;
  1247. let rotationAngle = 0;
  1248. // 如果提供了武器ID,尝试获取特定武器的旋转角度
  1249. if (weaponId && this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1250. rotationAngle = this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1251. console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定旋转角度: ${rotationAngle}度`);
  1252. } else {
  1253. // 使用默认旋转角度配置
  1254. rotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1255. console.log(`为形状 ${shapeId} 设置默认旋转角度: ${rotationAngle}度`);
  1256. }
  1257. // 应用旋转
  1258. weaponNode.setRotationFromEuler(0, 0, rotationAngle);
  1259. }
  1260. // 设置特定武器和形状的旋转角度
  1261. public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
  1262. if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1263. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
  1264. }
  1265. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
  1266. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1267. }
  1268. // 设置默认形状的旋转角度
  1269. public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
  1270. this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
  1271. console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1272. }
  1273. // 获取特定武器和形状的旋转角度
  1274. public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
  1275. if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1276. return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1277. }
  1278. return 0;
  1279. }
  1280. // 获取默认形状的旋转角度
  1281. public getDefaultShapeRotationAngle(shapeId: string): number {
  1282. return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1283. }
  1284. // 重新应用所有已放置方块的武器图标旋转
  1285. public refreshAllWeaponIconRotations() {
  1286. // 遍历所有已放置的方块
  1287. if (this.placedBlocksContainer) {
  1288. this.placedBlocksContainer.children.forEach(block => {
  1289. const weaponConfig = this.getBlockWeaponConfig(block);
  1290. if (weaponConfig) {
  1291. const b1Node = block.getChildByName('B1');
  1292. if (b1Node) {
  1293. const weaponNode = b1Node.getChildByName('Weapon');
  1294. if (weaponNode) {
  1295. const shapeId = this.getBlockShape(block);
  1296. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1297. }
  1298. }
  1299. }
  1300. });
  1301. }
  1302. // 遍历kuang区域的方块
  1303. this.blocks.forEach(block => {
  1304. const weaponConfig = this.getBlockWeaponConfig(block);
  1305. if (weaponConfig) {
  1306. const b1Node = block.getChildByName('B1');
  1307. if (b1Node) {
  1308. const weaponNode = b1Node.getChildByName('Weapon');
  1309. if (weaponNode) {
  1310. const shapeId = this.getBlockShape(block);
  1311. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1312. }
  1313. }
  1314. }
  1315. });
  1316. }
  1317. // 根据方块获取武器配置
  1318. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  1319. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  1320. }
  1321. // 获取方块的武器ID
  1322. public getBlockWeaponId(block: Node): string | null {
  1323. const weaponConfig = this.getBlockWeaponConfig(block);
  1324. return weaponConfig ? weaponConfig.id : null;
  1325. }
  1326. // 获取方块的形状
  1327. public getBlockShape(block: Node): string | null {
  1328. const weaponConfig = this.getBlockWeaponConfig(block);
  1329. if (!weaponConfig) return null;
  1330. // 从方块结构推断形状
  1331. return this.inferBlockShapeFromStructure(block);
  1332. }
  1333. // 获取方块的详细形状信息(包括形状ID和名称)
  1334. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  1335. const actualShape = this.extractShapeFromBlock(block);
  1336. const blockShapes = this.configManager.getBlockShapes();
  1337. if (!blockShapes) return null;
  1338. // 寻找匹配的形状配置
  1339. for (const shapeConfig of blockShapes) {
  1340. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1341. return {
  1342. id: shapeConfig.id,
  1343. name: shapeConfig.name,
  1344. shape: shapeConfig.shape
  1345. };
  1346. }
  1347. }
  1348. return null;
  1349. }
  1350. // 从方块结构推断形状
  1351. private inferBlockShapeFromStructure(block: Node): string {
  1352. const actualShape = this.extractShapeFromBlock(block);
  1353. const blockShapes = this.configManager.getBlockShapes();
  1354. if (!blockShapes) {
  1355. console.warn('无法获取方块形状配置,使用默认形状');
  1356. return 'I';
  1357. }
  1358. // 寻找匹配的形状配置
  1359. for (const shapeConfig of blockShapes) {
  1360. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1361. console.log(`[BlockManager] 识别方块形状: ${shapeConfig.id} (${shapeConfig.name})`);
  1362. return shapeConfig.id;
  1363. }
  1364. }
  1365. console.warn('[BlockManager] 未找到匹配的形状配置,使用默认形状I');
  1366. return 'I';
  1367. }
  1368. // 寻找与目标形状匹配的预制体
  1369. private findMatchingPrefab(targetShape: any): Prefab | null {
  1370. for (const prefab of this.blockPrefabs) {
  1371. if (this.doesPrefabMatchShape(prefab, targetShape)) {
  1372. return prefab;
  1373. }
  1374. }
  1375. return null;
  1376. }
  1377. // 检查预制体是否匹配指定形状
  1378. private doesPrefabMatchShape(prefab: Prefab, targetShape: any): boolean {
  1379. // 创建临时实例来检查形状
  1380. const tempBlock = instantiate(prefab);
  1381. const parts = this.getBlockParts(tempBlock);
  1382. const actualShape = this.extractShapeFromBlock(tempBlock);
  1383. tempBlock.destroy();
  1384. // 比较形状矩阵
  1385. const matches = this.compareShapeMatrices(actualShape, targetShape.shape);
  1386. return matches;
  1387. }
  1388. // 从方块实例中提取形状矩阵
  1389. private extractShapeFromBlock(block: Node): number[][] {
  1390. const parts = this.getBlockParts(block);
  1391. // 创建4x4矩阵
  1392. const matrix: number[][] = [];
  1393. for (let i = 0; i < 4; i++) {
  1394. matrix[i] = [0, 0, 0, 0];
  1395. }
  1396. // 找到最小坐标作为偏移基准
  1397. let minX = 0, minY = 0;
  1398. for (const part of parts) {
  1399. minX = Math.min(minX, part.x);
  1400. minY = Math.min(minY, part.y);
  1401. }
  1402. // 填充矩阵,将坐标标准化到从(0,0)开始
  1403. for (const part of parts) {
  1404. const matrixX = part.x - minX;
  1405. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  1406. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  1407. matrix[matrixY][matrixX] = 1;
  1408. }
  1409. }
  1410. // 对矩阵进行上下翻转(交换第0行和第1行)
  1411. const temp = matrix[0];
  1412. matrix[0] = matrix[1];
  1413. matrix[1] = temp;
  1414. return matrix;
  1415. }
  1416. // 比较两个形状矩阵是否相同
  1417. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  1418. if (matrix1.length !== matrix2.length) return false;
  1419. for (let i = 0; i < matrix1.length; i++) {
  1420. if (matrix1[i].length !== matrix2[i].length) return false;
  1421. for (let j = 0; j < matrix1[i].length; j++) {
  1422. if (matrix1[i][j] !== matrix2[i][j]) return false;
  1423. }
  1424. }
  1425. return true;
  1426. }
  1427. // 检查两个方块是否可以合成(相同形状相同种类)
  1428. private canMergeBlocks(block1: Node, block2: Node): boolean {
  1429. // 检查稀有度
  1430. const rarity1 = this.getBlockRarity(block1);
  1431. const rarity2 = this.getBlockRarity(block2);
  1432. if (rarity1 !== rarity2) {
  1433. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  1434. return false;
  1435. }
  1436. // 检查武器ID(种类)
  1437. const weaponId1 = this.getBlockWeaponId(block1);
  1438. const weaponId2 = this.getBlockWeaponId(block2);
  1439. if (weaponId1 !== weaponId2) {
  1440. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  1441. return false;
  1442. }
  1443. // 使用精确的形状矩阵比较
  1444. const shape1 = this.extractShapeFromBlock(block1);
  1445. const shape2 = this.extractShapeFromBlock(block2);
  1446. if (!this.compareShapeMatrices(shape1, shape2)) {
  1447. console.log(`[BlockManager] 形状矩阵不匹配`);
  1448. return false;
  1449. }
  1450. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  1451. return true;
  1452. }
  1453. // 刷新方块 - 重新生成三个新的武器方块
  1454. public refreshBlocks() {
  1455. // 移除PlacedBlocks容器中所有方块的标签
  1456. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1457. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1458. }
  1459. // 生成新的方块
  1460. this.generateRandomBlocksInKuang();
  1461. }
  1462. // 检查是否有已放置的方块
  1463. public hasPlacedBlocks(): boolean {
  1464. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1465. console.log('[BlockManager] PlacedBlocks容器无效');
  1466. return false;
  1467. }
  1468. const blockCount = this.placedBlocksContainer.children.length;
  1469. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1470. // 检查容器中是否有子节点(方块)
  1471. return blockCount > 0;
  1472. }
  1473. /* =================== 合成逻辑 =================== */
  1474. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  1475. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1476. private async tryMergeBlock(block: Node) {
  1477. const rarity = this.getBlockRarity(block);
  1478. if (!rarity) return;
  1479. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1480. if (!this.placedBlocksContainer) return;
  1481. const blockBB = this.getWorldAABB(block);
  1482. for (const other of this.placedBlocksContainer.children) {
  1483. if (other === block) continue;
  1484. // 使用新的合成检查方法
  1485. if (!this.canMergeBlocks(block, other)) continue;
  1486. const otherBB = this.getWorldAABB(other);
  1487. if (this.rectIntersects(blockBB, otherBB)) {
  1488. // 找到合成目标
  1489. await this.performMerge(block, other, rarity);
  1490. break;
  1491. }
  1492. }
  1493. }
  1494. private async performMerge(target: Node, source: Node, rarity: string) {
  1495. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1496. // 隐藏价格标签并处理 db 关联
  1497. this.hidePriceLabel(source);
  1498. const srcDb = source['dbNode'];
  1499. if (srcDb) srcDb.active = false;
  1500. // 销毁被合并方块
  1501. source.destroy();
  1502. // 升级稀有度
  1503. const nextRarity = this.getNextRarity(rarity);
  1504. if (nextRarity) {
  1505. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1506. // 获取当前武器配置
  1507. const currentConfig = this.blockWeaponConfigs.get(target);
  1508. if (currentConfig) {
  1509. // 保存原始武器名称用于日志输出
  1510. const originalWeaponName = currentConfig.name;
  1511. // 获取当前关卡允许的武器列表
  1512. const levelWeapons = await this.getCurrentLevelWeapons();
  1513. // 检查是否应该限制在关卡配置的武器范围内
  1514. if (levelWeapons.length > 0) {
  1515. // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
  1516. if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
  1517. console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
  1518. }
  1519. // 无论如何,都只升级稀有度,不改变武器类型
  1520. const upgradedConfig = { ...currentConfig };
  1521. upgradedConfig.rarity = nextRarity;
  1522. this.blockWeaponConfigs.set(target, upgradedConfig);
  1523. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1524. } else {
  1525. // 如果没有关卡配置限制,正常升级稀有度
  1526. const upgradedConfig = { ...currentConfig };
  1527. upgradedConfig.rarity = nextRarity;
  1528. this.blockWeaponConfigs.set(target, upgradedConfig);
  1529. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1530. }
  1531. }
  1532. // 更新方块颜色
  1533. this.setBlockRarityColor(target, nextRarity);
  1534. }
  1535. // 播放烟雾动画
  1536. const worldPos = new Vec3();
  1537. target.getWorldPosition(worldPos);
  1538. this.spawnMergeSmoke(worldPos);
  1539. // 递归检查是否还能继续合成
  1540. if (nextRarity) {
  1541. await this.tryMergeBlock(target);
  1542. }
  1543. }
  1544. private getBlockRarity(block: Node): string | null {
  1545. const cfg = this.blockWeaponConfigs.get(block);
  1546. if (cfg) return cfg.rarity;
  1547. // fallback based on sprite color maybe
  1548. return null;
  1549. }
  1550. private getNextRarity(rarity: string): string | null {
  1551. const idx = this.rarityOrder.indexOf(rarity);
  1552. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1553. return this.rarityOrder[idx + 1];
  1554. }
  1555. private getWorldAABB(node: Node): Rect {
  1556. const ui = node.getComponent(UITransform);
  1557. if (!ui) return new Rect();
  1558. const pos = node.worldPosition;
  1559. const width = ui.width;
  1560. const height = ui.height;
  1561. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1562. }
  1563. private rectIntersects(a: Rect, b: Rect): boolean {
  1564. return a.x < b.x + b.width &&
  1565. a.x + a.width > b.x &&
  1566. a.y < b.y + b.height &&
  1567. a.y + a.height > b.y;
  1568. }
  1569. /** 生成烟雾特效 */
  1570. private spawnMergeSmoke(worldPos: Vec3) {
  1571. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1572. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1573. if (err || !sData) {
  1574. console.warn('加载合成烟雾动画失败', err);
  1575. return;
  1576. }
  1577. const node = new Node('MergeSmoke');
  1578. const skeleton = node.addComponent(sp.Skeleton);
  1579. skeleton.skeletonData = sData;
  1580. skeleton.premultipliedAlpha = false;
  1581. skeleton.setAnimation(0, 'animation', false);
  1582. skeleton.setCompleteListener(() => node.destroy());
  1583. const canvas = find('Canvas');
  1584. if (canvas) canvas.addChild(node);
  1585. node.setWorldPosition(worldPos);
  1586. });
  1587. }
  1588. /** 在放置失败时尝试与现有方块进行合成 */
  1589. private tryMergeOnOverlap(draggedBlock: Node): boolean {
  1590. if (!this.placedBlocksContainer) return false;
  1591. const rarity = this.getBlockRarity(draggedBlock);
  1592. if (!rarity) return false;
  1593. const dragBB = this.getWorldAABB(draggedBlock);
  1594. for (const target of this.placedBlocksContainer.children) {
  1595. if (target === draggedBlock) continue;
  1596. // 使用新的合成检查方法
  1597. if (!this.canMergeBlocks(draggedBlock, target)) continue;
  1598. const targetBB = this.getWorldAABB(target);
  1599. if (this.rectIntersects(dragBB, targetBB)) {
  1600. // 执行合并:目标保留,拖拽方块销毁
  1601. this.performMerge(target, draggedBlock, rarity);
  1602. return true;
  1603. }
  1604. }
  1605. return false;
  1606. }
  1607. onDestroy() {
  1608. // 清理事件监听
  1609. const eventBus = EventBus.getInstance();
  1610. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  1611. eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  1612. // 移除GAME_START事件清理,因为已不再监听该事件
  1613. // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1614. eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  1615. }
  1616. }