BlockManager.ts 70 KB

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