BlockManager.ts 44 KB

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