BlockManager.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  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 { BlockTag } from './BlockSelection/BlockTag';
  6. import { sp } from 'cc';
  7. const { ccclass, property } = _decorator;
  8. @ccclass('BlockManager')
  9. export class BlockManager extends Component {
  10. // 预制体数组,存储5个预制体
  11. @property([Prefab])
  12. public blockPrefabs: Prefab[] = [];
  13. // 网格容器节点
  14. @property({
  15. type: Node,
  16. tooltip: '拖拽GridContainer节点到这里'
  17. })
  18. public gridContainer: Node = null;
  19. // 方块容器节点(kuang)
  20. @property({
  21. type: Node,
  22. tooltip: '拖拽kuang节点到这里'
  23. })
  24. public kuangContainer: Node = null;
  25. // 金币标签节点
  26. @property({
  27. type: Node,
  28. tooltip: '拖拽CoinLabel节点到这里'
  29. })
  30. public coinLabelNode: Node = null;
  31. // 已放置方块容器节点
  32. @property({
  33. type: Node,
  34. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)'
  35. })
  36. public placedBlocksContainer: Node = null;
  37. // 游戏是否已开始
  38. public gameStarted: boolean = false;
  39. // 移除移动冷却:相关属性/逻辑已废弃
  40. // SaveDataManager 单例
  41. private saveDataManager: SaveDataManager = null; // 仅用于局外数据
  42. private session: LevelSessionManager = null;
  43. // 方块价格标签映射
  44. private blockPriceMap: Map<Node, Node> = new Map();
  45. // 已经生成的块
  46. private blocks: Node[] = [];
  47. // 当前拖拽的块
  48. private currentDragBlock: Node | null = null;
  49. // 拖拽起始位置
  50. private startPos = new Vec2();
  51. // 块的起始位置
  52. private blockStartPos: Vec3 = new Vec3();
  53. // 网格占用情况,用于控制台输出
  54. private gridOccupationMap: number[][] = [];
  55. // 网格行数和列数
  56. private readonly GRID_ROWS = 6;
  57. private readonly GRID_COLS = 11;
  58. // 是否已初始化网格信息
  59. private gridInitialized = false;
  60. // 存储网格节点信息
  61. private gridNodes: Node[][] = [];
  62. // 网格间距
  63. private gridSpacing = 54;
  64. // 不参与占用的节点名称列表
  65. private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
  66. // 临时保存方块的原始占用格子
  67. private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  68. // 方块原始位置(在kuang中的位置)
  69. private originalPositions: Map<Node, Vec3> = new Map();
  70. // 方块当前所在的区域
  71. private blockLocations: Map<Node, string> = new Map();
  72. // 配置管理器
  73. private configManager: ConfigManager = null;
  74. // 方块武器配置映射
  75. private blockWeaponConfigs: Map<Node, WeaponConfig> = new Map();
  76. /** 冷却机制已废弃,方块随时可移动 */
  77. private canMoveBlock(block: Node): boolean { return true; }
  78. // 清除所有冷却(游戏重置时调用)
  79. public clearAllCooldowns() { /* no-op */ }
  80. start() {
  81. // 获取配置管理器
  82. this.configManager = ConfigManager.getInstance();
  83. if (!this.configManager) {
  84. console.error('无法获取ConfigManager实例');
  85. }
  86. // 如果没有指定GridContainer,尝试找到它
  87. if (!this.gridContainer) {
  88. this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
  89. if (!this.gridContainer) {
  90. console.error('找不到GridContainer节点');
  91. return;
  92. }
  93. }
  94. // 如果没有指定kuangContainer,尝试找到它
  95. if (!this.kuangContainer) {
  96. this.kuangContainer = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
  97. if (!this.kuangContainer) {
  98. console.error('找不到kuang节点');
  99. return;
  100. }
  101. }
  102. // 如果没有指定coinLabelNode,尝试找到它
  103. if (!this.coinLabelNode) {
  104. this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
  105. if (!this.coinLabelNode) {
  106. console.error('找不到CoinLabel节点');
  107. return;
  108. }
  109. }
  110. // 如果没有指定placedBlocksContainer,尝试找到它
  111. if (!this.placedBlocksContainer) {
  112. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  113. }
  114. // 确保有PlacedBlocks节点用于存放已放置的方块
  115. this.ensurePlacedBlocksNode();
  116. // 获取数据管理器
  117. this.saveDataManager = SaveDataManager.getInstance();
  118. this.session = LevelSessionManager.inst;
  119. // 初始化玩家金币显示
  120. this.updateCoinDisplay();
  121. // 初始化网格信息
  122. this.initGridInfo();
  123. // 初始化网格占用情况
  124. this.initGridOccupationMap();
  125. // 等待配置加载完成后生成方块
  126. this.scheduleOnce(() => {
  127. this.generateRandomBlocksInKuang();
  128. }, 0.5);
  129. }
  130. // 确保有PlacedBlocks节点
  131. ensurePlacedBlocksNode() {
  132. // 如果已经通过拖拽设置了节点,直接使用
  133. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  134. return;
  135. }
  136. // 尝试查找节点
  137. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  138. if (this.placedBlocksContainer) {
  139. return;
  140. }
  141. // 如果找不到,创建新节点
  142. const gameLevelUI = find('Canvas/GameLevelUI');
  143. if (!gameLevelUI) {
  144. console.error('找不到GameLevelUI节点,无法创建PlacedBlocks');
  145. return;
  146. }
  147. this.placedBlocksContainer = new Node('PlacedBlocks');
  148. gameLevelUI.addChild(this.placedBlocksContainer);
  149. if (!this.placedBlocksContainer.getComponent(UITransform)) {
  150. this.placedBlocksContainer.addComponent(UITransform);
  151. }
  152. console.log('已在GameLevelUI下创建PlacedBlocks节点');
  153. }
  154. // 初始化网格信息
  155. initGridInfo() {
  156. if (!this.gridContainer || this.gridInitialized) return;
  157. this.gridNodes = [];
  158. for (let row = 0; row < this.GRID_ROWS; row++) {
  159. this.gridNodes[row] = [];
  160. }
  161. for (let i = 0; i < this.gridContainer.children.length; i++) {
  162. const grid = this.gridContainer.children[i];
  163. if (grid.name.startsWith('Grid_')) {
  164. const parts = grid.name.split('_');
  165. if (parts.length === 3) {
  166. const row = parseInt(parts[1]);
  167. const col = parseInt(parts[2]);
  168. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  169. this.gridNodes[row][col] = grid;
  170. }
  171. }
  172. }
  173. }
  174. if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
  175. if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
  176. const pos1 = this.gridNodes[0][0].position;
  177. const pos2 = this.gridNodes[1][0].position;
  178. this.gridSpacing = Math.abs(pos2.y - pos1.y);
  179. }
  180. }
  181. this.gridInitialized = true;
  182. }
  183. // 初始化网格占用情况
  184. initGridOccupationMap() {
  185. this.gridOccupationMap = [];
  186. for (let row = 0; row < this.GRID_ROWS; row++) {
  187. const rowArray: number[] = [];
  188. for (let col = 0; col < this.GRID_COLS; col++) {
  189. rowArray.push(0);
  190. }
  191. this.gridOccupationMap.push(rowArray);
  192. }
  193. }
  194. // 在kuang下随机生成三个方块
  195. private generateRandomBlocksInKuang() {
  196. // 清除kuang区域中的旧方块,但不清除已放置在网格中的方块的标签
  197. this.clearBlocks();
  198. // 检查配置管理器是否可用
  199. if (!this.configManager || !this.configManager.isConfigLoaded()) {
  200. console.warn('配置管理器未初始化或配置未加载完成,延迟生成方块');
  201. this.scheduleOnce(() => {
  202. this.generateRandomBlocksInKuang();
  203. }, 1.0);
  204. return;
  205. }
  206. if (this.blockPrefabs.length === 0) {
  207. console.error('没有可用的预制体');
  208. return;
  209. }
  210. const kuangNode = this.kuangContainer;
  211. if (!kuangNode) {
  212. console.error('找不到kuang节点');
  213. return;
  214. }
  215. const offsets = [
  216. new Vec3(-200, 0, 0),
  217. new Vec3(0, 0, 0),
  218. new Vec3(200, 0, 0)
  219. ];
  220. const dbNodes = [
  221. kuangNode.getChildByName('db01'),
  222. kuangNode.getChildByName('db02'),
  223. kuangNode.getChildByName('db03')
  224. ];
  225. console.log('开始在kuang容器中生成随机武器方块');
  226. for (let i = 0; i < 3; i++) {
  227. // 获取随机武器配置
  228. const weaponConfig = this.configManager.getRandomWeapon();
  229. if (!weaponConfig) {
  230. console.error(`无法获取第 ${i + 1} 个武器配置`);
  231. continue;
  232. }
  233. // 基于武器配置选择合适的预制体
  234. const prefab = this.selectPrefabForWeapon(weaponConfig);
  235. if (!prefab) {
  236. console.error(`无法为武器 ${weaponConfig.name} 选择合适的预制体`);
  237. continue;
  238. }
  239. const block = instantiate(prefab);
  240. kuangNode.addChild(block);
  241. block.position = offsets[i];
  242. // 设置方块名称
  243. block.name = `WeaponBlock_${weaponConfig.id}`;
  244. // 保存武器配置到方块
  245. this.blockWeaponConfigs.set(block, weaponConfig);
  246. block['weaponConfig'] = weaponConfig;
  247. block['weaponId'] = weaponConfig.id;
  248. this.originalPositions.set(block, offsets[i].clone());
  249. this.blockLocations.set(block, 'kuang');
  250. this.blocks.push(block);
  251. if (dbNodes[i]) {
  252. const priceNode = dbNodes[i].getChildByName('Price');
  253. if (priceNode) {
  254. this.blockPriceMap.set(block, priceNode);
  255. priceNode.active = true;
  256. // 根据武器稀有度设置价格
  257. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity);
  258. }
  259. this.associateDbNodeWithBlock(block, dbNodes[i]);
  260. }
  261. // 设置方块的武器外观
  262. this.setupBlockWeaponVisual(block, weaponConfig);
  263. this.setupDragEvents(block);
  264. // 为新生成的方块添加标签
  265. BlockTag.addTag(block);
  266. }
  267. this.updateCoinDisplay();
  268. }
  269. // 将db节点与方块关联
  270. associateDbNodeWithBlock(block: Node, dbNode: Node) {
  271. block['dbNode'] = dbNode;
  272. block.on(Node.EventType.TRANSFORM_CHANGED, () => {
  273. if (dbNode && block.parent) {
  274. const location = this.blockLocations.get(block);
  275. if (location === 'grid') {
  276. dbNode.active = false;
  277. return;
  278. }
  279. dbNode.active = true;
  280. const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position);
  281. const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  282. dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z);
  283. }
  284. });
  285. }
  286. // 更新金币显示
  287. updateCoinDisplay() {
  288. if (this.coinLabelNode) {
  289. const label = this.coinLabelNode.getComponent(Label);
  290. if (label) {
  291. const coins = this.session.getCoins();
  292. label.string = coins.toString();
  293. }
  294. }
  295. }
  296. // 获取方块价格
  297. getBlockPrice(block: Node): number {
  298. const priceNode = this.blockPriceMap.get(block);
  299. if (priceNode) {
  300. const label = priceNode.getComponent(Label);
  301. if (label) {
  302. const price = parseInt(label.string);
  303. if (!isNaN(price)) {
  304. return price;
  305. }
  306. }
  307. }
  308. return 50;
  309. }
  310. // 隐藏价格标签
  311. hidePriceLabel(block: Node) {
  312. const priceNode = this.blockPriceMap.get(block);
  313. if (priceNode) {
  314. priceNode.active = false;
  315. }
  316. }
  317. // 显示价格标签
  318. showPriceLabel(block: Node) {
  319. const priceNode = this.blockPriceMap.get(block);
  320. if (priceNode) {
  321. priceNode.active = true;
  322. }
  323. }
  324. // 扣除玩家金币
  325. deductPlayerCoins(amount: number): boolean {
  326. const success = this.session.spendCoins(amount);
  327. if (success) {
  328. this.updateCoinDisplay();
  329. }
  330. return success;
  331. }
  332. // 归还玩家金币
  333. refundPlayerCoins(amount: number) {
  334. this.session.addCoins(amount);
  335. this.updateCoinDisplay();
  336. }
  337. // 设置拖拽事件
  338. setupDragEvents(block: Node) {
  339. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  340. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  341. if (!this.canMoveBlock(block)) {
  342. return;
  343. }
  344. }
  345. this.currentDragBlock = block;
  346. this.startPos = event.getUILocation();
  347. this.blockStartPos.set(block.position);
  348. this.currentDragBlock['startLocation'] = this.blockLocations.get(block);
  349. block.setSiblingIndex(block.parent.children.length - 1);
  350. this.tempStoreBlockOccupiedGrids(block);
  351. // 拖拽开始时禁用碰撞体
  352. const collider = block.getComponent(Collider2D);
  353. if (collider) collider.enabled = false;
  354. }, this);
  355. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  356. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  357. if (!this.canMoveBlock(block)) {
  358. return;
  359. }
  360. }
  361. if (!this.currentDragBlock) return;
  362. const location = event.getUILocation();
  363. const deltaX = location.x - this.startPos.x;
  364. const deltaY = location.y - this.startPos.y;
  365. this.currentDragBlock.position = new Vec3(
  366. this.blockStartPos.x + deltaX,
  367. this.blockStartPos.y + deltaY,
  368. this.blockStartPos.z
  369. );
  370. }, this);
  371. block.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  372. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  373. if (!this.canMoveBlock(block)) {
  374. return;
  375. }
  376. }
  377. if (this.currentDragBlock) {
  378. this.handleBlockDrop(event);
  379. this.currentDragBlock = null;
  380. // 拖拽结束时恢复碰撞体
  381. const collider = block.getComponent(Collider2D);
  382. if (collider) collider.enabled = true;
  383. }
  384. }, this);
  385. block.on(Node.EventType.TOUCH_CANCEL, () => {
  386. if (this.currentDragBlock) {
  387. this.returnBlockToOriginalPosition();
  388. this.currentDragBlock = null;
  389. // 拖拽取消时恢复碰撞体
  390. const collider = block.getComponent(Collider2D);
  391. if (collider) collider.enabled = true;
  392. }
  393. }, this);
  394. }
  395. // 处理方块放下
  396. handleBlockDrop(event: EventTouch) {
  397. const touchPos = event.getLocation();
  398. const startLocation = this.currentDragBlock['startLocation'];
  399. if (this.isInKuangArea(touchPos)) {
  400. // 检查是否有标签,只有有标签的方块才能放回kuang
  401. if (BlockTag.hasTag(this.currentDragBlock)) {
  402. this.returnBlockToKuang(startLocation);
  403. } else {
  404. // 没有标签的方块不能放回kuang,返回原位置
  405. console.log(`[BlockManager] 方块 ${this.currentDragBlock.name} 没有标签,不能放回kuang区域`);
  406. this.returnBlockToOriginalPosition();
  407. }
  408. } else if (this.tryPlaceBlockToGrid(this.currentDragBlock)) {
  409. this.handleSuccessfulPlacement(startLocation);
  410. } else {
  411. // 放置失败,尝试直接与重叠方块合成
  412. if (this.tryMergeOnOverlap(this.currentDragBlock)) {
  413. // 合成成功时,若来自 kuang 则扣费
  414. if (startLocation !== 'grid') {
  415. const price = this.getBlockPrice(this.currentDragBlock);
  416. this.deductPlayerCoins(price);
  417. }
  418. // 当前拖拽块已被销毁(合并时),无需复位
  419. } else {
  420. this.returnBlockToOriginalPosition();
  421. }
  422. }
  423. }
  424. // 返回方块到kuang区域
  425. returnBlockToKuang(startLocation: string) {
  426. const originalPos = this.originalPositions.get(this.currentDragBlock);
  427. if (originalPos) {
  428. const kuangNode = this.kuangContainer;
  429. if (kuangNode && this.currentDragBlock.parent !== kuangNode) {
  430. this.currentDragBlock.removeFromParent();
  431. kuangNode.addChild(this.currentDragBlock);
  432. }
  433. this.currentDragBlock.position = originalPos.clone();
  434. }
  435. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  436. this.blockLocations.set(this.currentDragBlock, 'kuang');
  437. this.showPriceLabel(this.currentDragBlock);
  438. if (startLocation === 'grid') {
  439. const price = this.getBlockPrice(this.currentDragBlock);
  440. this.refundPlayerCoins(price);
  441. this.currentDragBlock['placedBefore'] = false;
  442. }
  443. const dbNode = this.currentDragBlock['dbNode'];
  444. if (dbNode) {
  445. dbNode.active = true;
  446. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  447. }
  448. }
  449. // 处理成功放置
  450. handleSuccessfulPlacement(startLocation: string) {
  451. const price = this.getBlockPrice(this.currentDragBlock);
  452. if (startLocation === 'grid') {
  453. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  454. this.blockLocations.set(this.currentDragBlock, 'grid');
  455. this.hidePriceLabel(this.currentDragBlock);
  456. const dbNode = this.currentDragBlock['dbNode'];
  457. if (dbNode) {
  458. dbNode.active = false;
  459. }
  460. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  461. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  462. // 如果游戏已开始,添加锁定视觉提示
  463. if (this.gameStarted) {
  464. this.addLockedVisualHint(this.currentDragBlock);
  465. // 游戏开始后放置的方块移除标签,不能再放回kuang
  466. BlockTag.removeTag(this.currentDragBlock);
  467. }
  468. // 检查并执行合成
  469. this.tryMergeBlock(this.currentDragBlock);
  470. } else {
  471. if (this.deductPlayerCoins(price)) {
  472. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  473. this.blockLocations.set(this.currentDragBlock, 'grid');
  474. this.hidePriceLabel(this.currentDragBlock);
  475. const dbNode = this.currentDragBlock['dbNode'];
  476. if (dbNode) {
  477. dbNode.active = false;
  478. }
  479. this.currentDragBlock['placedBefore'] = true;
  480. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  481. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  482. // 如果游戏已开始,添加锁定视觉提示
  483. if (this.gameStarted) {
  484. this.addLockedVisualHint(this.currentDragBlock);
  485. // 游戏开始后放置的方块移除标签,不能再放回kuang
  486. BlockTag.removeTag(this.currentDragBlock);
  487. }
  488. // 检查并执行合成
  489. this.tryMergeBlock(this.currentDragBlock);
  490. } else {
  491. this.returnBlockToOriginalPosition();
  492. }
  493. }
  494. }
  495. // 返回方块到原位置
  496. returnBlockToOriginalPosition() {
  497. const currentLocation = this.blockLocations.get(this.currentDragBlock);
  498. if (currentLocation === 'kuang') {
  499. const originalPos = this.originalPositions.get(this.currentDragBlock);
  500. if (originalPos) {
  501. this.currentDragBlock.position = originalPos.clone();
  502. }
  503. } else {
  504. this.currentDragBlock.position = this.blockStartPos.clone();
  505. }
  506. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  507. this.showPriceLabel(this.currentDragBlock);
  508. const dbNode = this.currentDragBlock['dbNode'];
  509. if (dbNode) {
  510. dbNode.active = true;
  511. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  512. }
  513. }
  514. // 检查是否在kuang区域内
  515. isInKuangArea(touchPos: Vec2): boolean {
  516. if (!this.kuangContainer) return false;
  517. const kuangTransform = this.kuangContainer.getComponent(UITransform);
  518. if (!kuangTransform) return false;
  519. const kuangBoundingBox = new Rect(
  520. this.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  521. this.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  522. kuangTransform.width,
  523. kuangTransform.height
  524. );
  525. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  526. }
  527. // 临时保存方块占用的网格
  528. tempStoreBlockOccupiedGrids(block: Node) {
  529. const occupiedGrids = block['occupiedGrids'];
  530. if (!occupiedGrids || occupiedGrids.length === 0) return;
  531. this.tempRemovedOccupiedGrids.push({
  532. block: block,
  533. occupiedGrids: [...occupiedGrids]
  534. });
  535. for (const grid of occupiedGrids) {
  536. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  537. grid.col >= 0 && grid.col < this.GRID_COLS) {
  538. this.gridOccupationMap[grid.row][grid.col] = 0;
  539. }
  540. }
  541. block['occupiedGrids'] = [];
  542. }
  543. // 恢复方块原来的占用状态
  544. restoreBlockOccupiedGrids(block: Node) {
  545. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  546. if (index === -1) return;
  547. const savedItem = this.tempRemovedOccupiedGrids[index];
  548. for (const grid of savedItem.occupiedGrids) {
  549. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  550. grid.col >= 0 && grid.col < this.GRID_COLS) {
  551. this.gridOccupationMap[grid.row][grid.col] = 1;
  552. }
  553. }
  554. block['occupiedGrids'] = [...savedItem.occupiedGrids];
  555. this.tempRemovedOccupiedGrids.splice(index, 1);
  556. }
  557. // 清除临时保存的占用状态
  558. clearTempStoredOccupiedGrids(block: Node) {
  559. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  560. if (index === -1) return;
  561. this.tempRemovedOccupiedGrids.splice(index, 1);
  562. }
  563. // 尝试将方块放置到网格中
  564. tryPlaceBlockToGrid(block: Node): boolean {
  565. if (!this.gridContainer || !this.gridInitialized) return false;
  566. let b1Node = block;
  567. if (block.name !== 'B1') {
  568. b1Node = block.getChildByName('B1');
  569. if (!b1Node) {
  570. return false;
  571. }
  572. }
  573. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  574. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  575. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  576. const halfWidth = gridSize.width / 2;
  577. const halfHeight = gridSize.height / 2;
  578. const tolerance = this.gridSpacing * 0.5;
  579. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  580. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  581. return false;
  582. }
  583. const nearestGrid = this.findNearestGridNode(gridPos);
  584. if (!nearestGrid) {
  585. return false;
  586. }
  587. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  588. }
  589. // 找到最近的网格节点
  590. findNearestGridNode(position: Vec3): Node {
  591. if (!this.gridContainer || !this.gridInitialized) return null;
  592. let nearestNode: Node = null;
  593. let minDistance = Number.MAX_VALUE;
  594. for (let row = 0; row < this.GRID_ROWS; row++) {
  595. for (let col = 0; col < this.GRID_COLS; col++) {
  596. const grid = this.gridNodes[row][col];
  597. if (grid) {
  598. const distance = Vec3.distance(position, grid.position);
  599. if (distance < minDistance) {
  600. minDistance = distance;
  601. nearestNode = grid;
  602. }
  603. }
  604. }
  605. }
  606. if (minDistance > this.gridSpacing * 2) {
  607. return null;
  608. }
  609. return nearestNode;
  610. }
  611. // 尝试将方块放置到指定的网格节点
  612. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  613. let b1Node = block;
  614. if (block.name !== 'B1') {
  615. b1Node = block.getChildByName('B1');
  616. if (!b1Node) {
  617. return false;
  618. }
  619. }
  620. if (!this.canPlaceBlockAt(block, targetGrid)) {
  621. return false;
  622. }
  623. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  624. const targetWorldPos = gridCenterWorldPos.clone();
  625. const b1LocalPos = b1Node.position.clone();
  626. let rootTargetWorldPos;
  627. if (b1Node === block) {
  628. rootTargetWorldPos = targetWorldPos.clone();
  629. } else {
  630. rootTargetWorldPos = new Vec3(
  631. targetWorldPos.x - b1LocalPos.x,
  632. targetWorldPos.y - b1LocalPos.y,
  633. targetWorldPos.z
  634. );
  635. }
  636. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  637. block.position = rootTargetLocalPos;
  638. this.markOccupiedPositions(block, targetGrid);
  639. return true;
  640. }
  641. // 检查方块是否可以放置在指定位置
  642. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  643. if (!this.gridInitialized) return false;
  644. const targetRowCol = this.getGridRowCol(targetGrid);
  645. if (!targetRowCol) return false;
  646. const parts = this.getBlockParts(block);
  647. for (const part of parts) {
  648. const row = targetRowCol.row - part.y;
  649. const col = targetRowCol.col + part.x;
  650. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  651. return false;
  652. }
  653. if (this.gridOccupationMap[row][col] === 1) {
  654. return false;
  655. }
  656. }
  657. return true;
  658. }
  659. // 获取网格行列索引
  660. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  661. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  662. const parts = gridNode.name.split('_');
  663. if (parts.length === 3) {
  664. const row = parseInt(parts[1]);
  665. const col = parseInt(parts[2]);
  666. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  667. return { row, col };
  668. }
  669. }
  670. return null;
  671. }
  672. // 获取方块的所有部分节点及其相对坐标
  673. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  674. const parts: { node: Node, x: number, y: number }[] = [];
  675. parts.push({ node: block, x: 0, y: 0 });
  676. this.findBlockParts(block, parts, 0, 0);
  677. return parts;
  678. }
  679. // 递归查找方块的所有部分
  680. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  681. for (let i = 0; i < node.children.length; i++) {
  682. const child = node.children[i];
  683. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  684. continue;
  685. }
  686. let x = parentX;
  687. let y = parentY;
  688. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  689. if (match) {
  690. x = parseInt(match[1]);
  691. y = parseInt(match[2]);
  692. result.push({ node: child, x, y });
  693. } else if (child.name.startsWith('B')) {
  694. const relativeX = Math.round(child.position.x / this.gridSpacing);
  695. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  696. x = parentX + relativeX;
  697. y = parentY + relativeY;
  698. result.push({ node: child, x, y });
  699. }
  700. this.findBlockParts(child, result, x, y);
  701. }
  702. }
  703. // 标记方块占用的格子
  704. markOccupiedPositions(block: Node, targetGrid: Node) {
  705. if (!this.gridInitialized) return;
  706. const targetRowCol = this.getGridRowCol(targetGrid);
  707. if (!targetRowCol) return;
  708. const parts = this.getBlockParts(block);
  709. block['occupiedGrids'] = [];
  710. for (const part of parts) {
  711. const row = targetRowCol.row - part.y;
  712. const col = targetRowCol.col + part.x;
  713. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  714. this.gridOccupationMap[row][col] = 1;
  715. block['occupiedGrids'] = block['occupiedGrids'] || [];
  716. block['occupiedGrids'].push({ row, col });
  717. }
  718. }
  719. }
  720. // 清除方块
  721. clearBlocks() {
  722. const blocksToRemove = [];
  723. for (const block of this.blocks) {
  724. if (block.isValid) {
  725. const location = this.blockLocations.get(block);
  726. if (location === 'kuang') {
  727. blocksToRemove.push(block);
  728. }
  729. }
  730. }
  731. for (const block of blocksToRemove) {
  732. const dbNode = block['dbNode'];
  733. if (dbNode && dbNode.isValid) {
  734. block.off(Node.EventType.TRANSFORM_CHANGED);
  735. const kuangNode = this.kuangContainer;
  736. if (kuangNode) {
  737. const dbName = dbNode.name;
  738. if (!kuangNode.getChildByName(dbName)) {
  739. dbNode.parent = kuangNode;
  740. }
  741. }
  742. }
  743. const index = this.blocks.indexOf(block);
  744. if (index !== -1) {
  745. this.blocks.splice(index, 1);
  746. }
  747. this.originalPositions.delete(block);
  748. this.blockLocations.delete(block);
  749. this.blockPriceMap.delete(block);
  750. // 清理武器配置映射
  751. this.blockWeaponConfigs.delete(block);
  752. block.destroy();
  753. }
  754. }
  755. // 游戏开始时调用
  756. onGameStart() {
  757. this.gameStarted = true;
  758. for (const block of this.blocks) {
  759. if (block.isValid) {
  760. const location = this.blockLocations.get(block);
  761. if (location === 'grid') {
  762. this.hidePriceLabel(block);
  763. const dbNode = block['dbNode'];
  764. if (dbNode) {
  765. dbNode.active = false;
  766. }
  767. this.moveBlockToPlacedBlocks(block);
  768. this.addLockedVisualHint(block);
  769. // 游戏开始后放置的方块移除标签,不能再放回kuang
  770. BlockTag.removeTag(block);
  771. }
  772. }
  773. }
  774. }
  775. // 游戏重置时调用
  776. onGameReset() {
  777. this.gameStarted = false;
  778. this.clearAllCooldowns();
  779. }
  780. // 添加视觉提示,表明方块已锁定
  781. addLockedVisualHint(block: Node) {
  782. const children = block.children;
  783. for (let i = 0; i < children.length; i++) {
  784. const child = children[i];
  785. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  786. continue;
  787. }
  788. child.setScale(new Vec3(0.95, 0.95, 1));
  789. }
  790. }
  791. // 将方块移动到PlacedBlocks节点下
  792. moveBlockToPlacedBlocks(block: Node) {
  793. if (!this.placedBlocksContainer) {
  794. console.error('PlacedBlocks容器未设置');
  795. return;
  796. }
  797. if (!this.placedBlocksContainer.isValid) {
  798. console.error('PlacedBlocks容器已失效');
  799. return;
  800. }
  801. const worldPosition = new Vec3();
  802. block.getWorldPosition(worldPosition);
  803. // 移除旧的触摸事件监听器
  804. block.off(Node.EventType.TOUCH_START);
  805. block.off(Node.EventType.TOUCH_MOVE);
  806. block.off(Node.EventType.TOUCH_END);
  807. block.off(Node.EventType.TOUCH_CANCEL);
  808. block.removeFromParent();
  809. this.placedBlocksContainer.addChild(block);
  810. block.setWorldPosition(worldPosition);
  811. // 重新设置触摸事件监听器
  812. this.setupDragEvents(block);
  813. }
  814. // 根据武器配置选择合适的预制体
  815. private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null {
  816. if (this.blockPrefabs.length === 0) {
  817. return null;
  818. }
  819. // 根据武器类型或稀有度选择预制体
  820. // 目前简单地随机选择一个预制体
  821. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  822. return this.blockPrefabs[randomIndex];
  823. }
  824. // 根据稀有度设置方块价格
  825. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  826. const label = priceNode.getComponent(Label);
  827. if (!label) {
  828. return;
  829. }
  830. let price: number;
  831. switch (rarity) {
  832. case 'common':
  833. price = 10;
  834. break;
  835. case 'uncommon':
  836. price = 20;
  837. break;
  838. case 'rare':
  839. price = 50;
  840. break;
  841. case 'epic':
  842. price = 100;
  843. break;
  844. case 'legendary':
  845. price = 150;
  846. break;
  847. default:
  848. price = 200;
  849. }
  850. label.string = price.toString();
  851. }
  852. // 设置方块的武器外观
  853. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  854. // 设置方块的稀有度颜色
  855. this.setBlockRarityColor(block, weaponConfig.rarity);
  856. // 加载武器图标
  857. this.loadWeaponIcon(block, weaponConfig);
  858. }
  859. // 设置方块稀有度颜色
  860. private setBlockRarityColor(block: Node, rarity: string) {
  861. // Add null safety check for block
  862. if (!block || !block.isValid) {
  863. return;
  864. }
  865. const sprite = block.getComponent(Sprite);
  866. if (!sprite || !sprite.isValid) {
  867. return;
  868. }
  869. // 根据稀有度设置颜色
  870. let color: Color;
  871. switch (rarity) {
  872. case 'common':
  873. color = new Color(255, 255, 255); // 白色
  874. break;
  875. case 'uncommon':
  876. color = new Color(0, 255, 0); // 绿色
  877. break;
  878. case 'rare':
  879. color = new Color(0, 100, 255); // 蓝色
  880. break;
  881. case 'epic':
  882. color = new Color(160, 32, 240); // 紫色
  883. break;
  884. case 'legendary':
  885. color = new Color(255, 165, 0); // 橙色
  886. break;
  887. default:
  888. color = new Color(255, 255, 255); // 默认白色
  889. }
  890. sprite.color = color;
  891. }
  892. // 加载武器图标
  893. private loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  894. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  895. const b1Node = block.getChildByName('B1');
  896. if (!b1Node) {
  897. console.warn('找不到B1节点');
  898. return;
  899. }
  900. const weaponNode = b1Node.getChildByName('Weapon');
  901. if (!weaponNode) {
  902. console.warn('找不到Weapon节点');
  903. return;
  904. }
  905. const weaponSprite = weaponNode.getComponent(Sprite);
  906. if (!weaponSprite) {
  907. console.warn('Weapon节点上没有Sprite组件');
  908. return;
  909. }
  910. // 获取武器配置中的图片路径
  911. const spriteConfig = weaponConfig.visualConfig?.weaponSprites;
  912. if (!spriteConfig) {
  913. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  914. return;
  915. }
  916. // 选择合适的图片路径(这里默认使用1x1)
  917. const spritePath = spriteConfig['1x1'] || spriteConfig['1x2'] || spriteConfig['2x1'] || spriteConfig['2x2'];
  918. if (!spritePath) {
  919. console.warn(`武器 ${weaponConfig.name} 没有可用的图片路径`);
  920. return;
  921. }
  922. // 正确的SpriteFrame子资源路径
  923. const spriteFramePath = `${spritePath}/spriteFrame`;
  924. // 加载SpriteFrame子资源
  925. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  926. if (err) {
  927. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  928. return;
  929. }
  930. // Add comprehensive null safety checks before setting spriteFrame
  931. if (weaponSprite && weaponSprite.isValid &&
  932. weaponNode && weaponNode.isValid &&
  933. block && block.isValid &&
  934. spriteFrame && spriteFrame.isValid) {
  935. weaponSprite.spriteFrame = spriteFrame;
  936. }
  937. });
  938. }
  939. // 根据方块获取武器配置
  940. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  941. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  942. }
  943. // 获取方块的武器ID
  944. public getBlockWeaponId(block: Node): string | null {
  945. const weaponConfig = this.getBlockWeaponConfig(block);
  946. return weaponConfig ? weaponConfig.id : null;
  947. }
  948. // 获取方块的形状
  949. public getBlockShape(block: Node): string | null {
  950. const weaponConfig = this.getBlockWeaponConfig(block);
  951. if (!weaponConfig) return null;
  952. // 从方块结构推断形状
  953. return this.inferBlockShapeFromStructure(block);
  954. }
  955. // 从方块结构推断形状
  956. private inferBlockShapeFromStructure(block: Node): string {
  957. const parts = this.getBlockParts(block);
  958. if (parts.length === 0) return '1x1';
  959. // 计算方块的边界
  960. let minX = 0, maxX = 0, minY = 0, maxY = 0;
  961. for (const part of parts) {
  962. minX = Math.min(minX, part.x);
  963. maxX = Math.max(maxX, part.x);
  964. minY = Math.min(minY, part.y);
  965. maxY = Math.max(maxY, part.y);
  966. }
  967. const width = maxX - minX + 1;
  968. const height = maxY - minY + 1;
  969. return `${width}x${height}`;
  970. }
  971. // 检查两个方块是否可以合成(相同形状相同种类)
  972. private canMergeBlocks(block1: Node, block2: Node): boolean {
  973. // 检查稀有度
  974. const rarity1 = this.getBlockRarity(block1);
  975. const rarity2 = this.getBlockRarity(block2);
  976. if (rarity1 !== rarity2) {
  977. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  978. return false;
  979. }
  980. // 检查武器ID(种类)
  981. const weaponId1 = this.getBlockWeaponId(block1);
  982. const weaponId2 = this.getBlockWeaponId(block2);
  983. if (weaponId1 !== weaponId2) {
  984. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  985. return false;
  986. }
  987. // 检查形状
  988. const shape1 = this.getBlockShape(block1);
  989. const shape2 = this.getBlockShape(block2);
  990. if (shape1 !== shape2) {
  991. console.log(`[BlockManager] 形状不匹配: ${shape1} vs ${shape2}`);
  992. return false;
  993. }
  994. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}, 形状=${shape1}`);
  995. return true;
  996. }
  997. // 刷新方块 - 重新生成三个新的武器方块
  998. public refreshBlocks() {
  999. // 移除PlacedBlocks容器中所有方块的标签
  1000. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1001. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1002. }
  1003. // 生成新的方块
  1004. this.generateRandomBlocksInKuang();
  1005. }
  1006. // 检查是否有已放置的方块
  1007. public hasPlacedBlocks(): boolean {
  1008. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1009. console.log('[BlockManager] PlacedBlocks容器无效');
  1010. return false;
  1011. }
  1012. const blockCount = this.placedBlocksContainer.children.length;
  1013. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1014. // 检查容器中是否有子节点(方块)
  1015. return blockCount > 0;
  1016. }
  1017. /* =================== 合成逻辑 =================== */
  1018. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  1019. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1020. private tryMergeBlock(block: Node) {
  1021. const rarity = this.getBlockRarity(block);
  1022. if (!rarity) return;
  1023. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1024. if (!this.placedBlocksContainer) return;
  1025. const blockBB = this.getWorldAABB(block);
  1026. for (const other of this.placedBlocksContainer.children) {
  1027. if (other === block) continue;
  1028. // 使用新的合成检查方法
  1029. if (!this.canMergeBlocks(block, other)) continue;
  1030. const otherBB = this.getWorldAABB(other);
  1031. if (this.rectIntersects(blockBB, otherBB)) {
  1032. // 找到合成目标
  1033. this.performMerge(block, other, rarity);
  1034. break;
  1035. }
  1036. }
  1037. }
  1038. private performMerge(target: Node, source: Node, rarity: string) {
  1039. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1040. // 隐藏价格标签并处理 db 关联
  1041. this.hidePriceLabel(source);
  1042. const srcDb = source['dbNode'];
  1043. if (srcDb) srcDb.active = false;
  1044. // 销毁被合并方块
  1045. source.destroy();
  1046. // 升级稀有度
  1047. const nextRarity = this.getNextRarity(rarity);
  1048. if (nextRarity) {
  1049. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1050. this.setBlockRarityColor(target, nextRarity);
  1051. // 如果有武器配置,也升级
  1052. const cfg = this.blockWeaponConfigs.get(target);
  1053. if (cfg) {
  1054. cfg.rarity = nextRarity;
  1055. this.blockWeaponConfigs.set(target, cfg);
  1056. }
  1057. }
  1058. // 播放烟雾动画
  1059. const worldPos = new Vec3();
  1060. target.getWorldPosition(worldPos);
  1061. this.spawnMergeSmoke(worldPos);
  1062. // 递归检查是否还能继续合成
  1063. if (nextRarity) {
  1064. this.tryMergeBlock(target);
  1065. }
  1066. }
  1067. private getBlockRarity(block: Node): string | null {
  1068. const cfg = this.blockWeaponConfigs.get(block);
  1069. if (cfg) return cfg.rarity;
  1070. // fallback based on sprite color maybe
  1071. return null;
  1072. }
  1073. private getNextRarity(rarity: string): string | null {
  1074. const idx = this.rarityOrder.indexOf(rarity);
  1075. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1076. return this.rarityOrder[idx + 1];
  1077. }
  1078. private getWorldAABB(node: Node): Rect {
  1079. const ui = node.getComponent(UITransform);
  1080. if (!ui) return new Rect();
  1081. const pos = node.worldPosition;
  1082. const width = ui.width;
  1083. const height = ui.height;
  1084. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1085. }
  1086. private rectIntersects(a: Rect, b: Rect): boolean {
  1087. return a.x < b.x + b.width &&
  1088. a.x + a.width > b.x &&
  1089. a.y < b.y + b.height &&
  1090. a.y + a.height > b.y;
  1091. }
  1092. /** 生成烟雾特效 */
  1093. private spawnMergeSmoke(worldPos: Vec3) {
  1094. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1095. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1096. if (err || !sData) {
  1097. console.warn('加载合成烟雾动画失败', err);
  1098. return;
  1099. }
  1100. const node = new Node('MergeSmoke');
  1101. const skeleton = node.addComponent(sp.Skeleton);
  1102. skeleton.skeletonData = sData;
  1103. skeleton.premultipliedAlpha = false;
  1104. skeleton.setAnimation(0, 'animation', false);
  1105. skeleton.setCompleteListener(() => node.destroy());
  1106. const canvas = find('Canvas');
  1107. if (canvas) canvas.addChild(node);
  1108. node.setWorldPosition(worldPos);
  1109. });
  1110. }
  1111. /** 在放置失败时尝试与现有方块进行合成 */
  1112. private tryMergeOnOverlap(draggedBlock: Node): boolean {
  1113. if (!this.placedBlocksContainer) return false;
  1114. const rarity = this.getBlockRarity(draggedBlock);
  1115. if (!rarity) return false;
  1116. const dragBB = this.getWorldAABB(draggedBlock);
  1117. for (const target of this.placedBlocksContainer.children) {
  1118. if (target === draggedBlock) continue;
  1119. // 使用新的合成检查方法
  1120. if (!this.canMergeBlocks(draggedBlock, target)) continue;
  1121. const targetBB = this.getWorldAABB(target);
  1122. if (this.rectIntersects(dragBB, targetBB)) {
  1123. // 执行合并:目标保留,拖拽方块销毁
  1124. this.performMerge(target, draggedBlock, rarity);
  1125. return true;
  1126. }
  1127. }
  1128. return false;
  1129. }
  1130. }