BlockManager.ts 43 KB

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