BlockManager.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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. // 刷新方块按钮节点(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. // 拖拽开始时禁用碰撞体
  363. const collider = block.getComponent(Collider2D);
  364. if (collider) collider.enabled = false;
  365. }, this);
  366. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  367. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  368. if (!this.canMoveBlock(block)) {
  369. return;
  370. }
  371. }
  372. if (!this.currentDragBlock) return;
  373. const location = event.getUILocation();
  374. const deltaX = location.x - this.startPos.x;
  375. const deltaY = location.y - this.startPos.y;
  376. this.currentDragBlock.position = new Vec3(
  377. this.blockStartPos.x + deltaX,
  378. this.blockStartPos.y + deltaY,
  379. this.blockStartPos.z
  380. );
  381. }, this);
  382. block.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  383. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  384. if (!this.canMoveBlock(block)) {
  385. return;
  386. }
  387. }
  388. if (this.currentDragBlock) {
  389. this.handleBlockDrop(event);
  390. this.currentDragBlock = null;
  391. // 拖拽结束时恢复碰撞体
  392. const collider = block.getComponent(Collider2D);
  393. if (collider) collider.enabled = true;
  394. }
  395. }, this);
  396. block.on(Node.EventType.TOUCH_CANCEL, () => {
  397. if (this.currentDragBlock) {
  398. this.returnBlockToOriginalPosition();
  399. this.currentDragBlock = null;
  400. // 拖拽取消时恢复碰撞体
  401. const collider = block.getComponent(Collider2D);
  402. if (collider) collider.enabled = true;
  403. }
  404. }, this);
  405. }
  406. // 处理方块放下
  407. handleBlockDrop(event: EventTouch) {
  408. const touchPos = event.getLocation();
  409. const startLocation = this.currentDragBlock['startLocation'];
  410. if (this.isInKuangArea(touchPos)) {
  411. this.returnBlockToKuang(startLocation);
  412. } else if (this.tryPlaceBlockToGrid(this.currentDragBlock)) {
  413. this.handleSuccessfulPlacement(startLocation);
  414. } else {
  415. // 放置失败,尝试直接与重叠方块合成
  416. if (this.tryMergeOnOverlap(this.currentDragBlock)) {
  417. // 合成成功时,若来自 kuang 则扣费
  418. if (startLocation !== 'grid') {
  419. const price = this.getBlockPrice(this.currentDragBlock);
  420. this.deductPlayerCoins(price);
  421. }
  422. // 当前拖拽块已被销毁(合并时),无需复位
  423. } else {
  424. this.returnBlockToOriginalPosition();
  425. }
  426. }
  427. }
  428. // 返回方块到kuang区域
  429. returnBlockToKuang(startLocation: string) {
  430. const originalPos = this.originalPositions.get(this.currentDragBlock);
  431. if (originalPos) {
  432. const kuangNode = this.kuangContainer;
  433. if (kuangNode && this.currentDragBlock.parent !== kuangNode) {
  434. this.currentDragBlock.removeFromParent();
  435. kuangNode.addChild(this.currentDragBlock);
  436. }
  437. this.currentDragBlock.position = originalPos.clone();
  438. }
  439. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  440. this.blockLocations.set(this.currentDragBlock, 'kuang');
  441. this.showPriceLabel(this.currentDragBlock);
  442. if (startLocation === 'grid') {
  443. const price = this.getBlockPrice(this.currentDragBlock);
  444. this.refundPlayerCoins(price);
  445. this.currentDragBlock['placedBefore'] = false;
  446. }
  447. const dbNode = this.currentDragBlock['dbNode'];
  448. if (dbNode) {
  449. dbNode.active = true;
  450. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  451. }
  452. }
  453. // 处理成功放置
  454. handleSuccessfulPlacement(startLocation: string) {
  455. const price = this.getBlockPrice(this.currentDragBlock);
  456. if (startLocation === 'grid') {
  457. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  458. this.blockLocations.set(this.currentDragBlock, 'grid');
  459. this.hidePriceLabel(this.currentDragBlock);
  460. const dbNode = this.currentDragBlock['dbNode'];
  461. if (dbNode) {
  462. dbNode.active = false;
  463. }
  464. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  465. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  466. // 如果游戏已开始,添加锁定视觉提示
  467. if (this.gameStarted) {
  468. this.addLockedVisualHint(this.currentDragBlock);
  469. }
  470. // 检查并执行合成
  471. this.tryMergeBlock(this.currentDragBlock);
  472. } else {
  473. if (this.deductPlayerCoins(price)) {
  474. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  475. this.blockLocations.set(this.currentDragBlock, 'grid');
  476. this.hidePriceLabel(this.currentDragBlock);
  477. const dbNode = this.currentDragBlock['dbNode'];
  478. if (dbNode) {
  479. dbNode.active = false;
  480. }
  481. this.currentDragBlock['placedBefore'] = true;
  482. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  483. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  484. // 如果游戏已开始,添加锁定视觉提示
  485. if (this.gameStarted) {
  486. this.addLockedVisualHint(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. }
  770. }
  771. }
  772. }
  773. // 游戏重置时调用
  774. onGameReset() {
  775. this.gameStarted = false;
  776. this.clearAllCooldowns();
  777. }
  778. // 添加视觉提示,表明方块已锁定
  779. addLockedVisualHint(block: Node) {
  780. const children = block.children;
  781. for (let i = 0; i < children.length; i++) {
  782. const child = children[i];
  783. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  784. continue;
  785. }
  786. child.setScale(new Vec3(0.95, 0.95, 1));
  787. }
  788. }
  789. // 将方块移动到PlacedBlocks节点下
  790. moveBlockToPlacedBlocks(block: Node) {
  791. if (!this.placedBlocksContainer) {
  792. console.error('PlacedBlocks容器未设置');
  793. return;
  794. }
  795. if (!this.placedBlocksContainer.isValid) {
  796. console.error('PlacedBlocks容器已失效');
  797. return;
  798. }
  799. const worldPosition = new Vec3();
  800. block.getWorldPosition(worldPosition);
  801. // 移除旧的触摸事件监听器
  802. block.off(Node.EventType.TOUCH_START);
  803. block.off(Node.EventType.TOUCH_MOVE);
  804. block.off(Node.EventType.TOUCH_END);
  805. block.off(Node.EventType.TOUCH_CANCEL);
  806. block.removeFromParent();
  807. this.placedBlocksContainer.addChild(block);
  808. block.setWorldPosition(worldPosition);
  809. // 重新设置触摸事件监听器
  810. this.setupDragEvents(block);
  811. }
  812. // 根据武器配置选择合适的预制体
  813. private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null {
  814. if (this.blockPrefabs.length === 0) {
  815. return null;
  816. }
  817. // 根据武器类型或稀有度选择预制体
  818. // 这里可以根据实际需求来选择不同的预制体
  819. // 目前简单地随机选择一个预制体
  820. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  821. return this.blockPrefabs[randomIndex];
  822. }
  823. // 根据稀有度设置方块价格
  824. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  825. const label = priceNode.getComponent(Label);
  826. if (!label) {
  827. return;
  828. }
  829. let price: number;
  830. switch (rarity) {
  831. case 'common':
  832. price = 10;
  833. break;
  834. case 'uncommon':
  835. price = 20;
  836. break;
  837. case 'rare':
  838. price = 50;
  839. break;
  840. case 'epic':
  841. price = 100;
  842. break;
  843. case 'legendary':
  844. price = 150;
  845. break;
  846. default:
  847. price = 200;
  848. }
  849. label.string = price.toString();
  850. }
  851. // 设置方块的武器外观
  852. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  853. // 设置方块的稀有度颜色
  854. this.setBlockRarityColor(block, weaponConfig.rarity);
  855. // 加载武器图标
  856. this.loadWeaponIcon(block, weaponConfig);
  857. }
  858. // 设置方块稀有度颜色
  859. private setBlockRarityColor(block: Node, rarity: string) {
  860. const sprite = block.getComponent(Sprite);
  861. if (!sprite) {
  862. return;
  863. }
  864. // 根据稀有度设置颜色
  865. let color: Color;
  866. switch (rarity) {
  867. case 'common':
  868. color = new Color(255, 255, 255); // 白色
  869. break;
  870. case 'uncommon':
  871. color = new Color(0, 255, 0); // 绿色
  872. break;
  873. case 'rare':
  874. color = new Color(0, 100, 255); // 蓝色
  875. break;
  876. case 'epic':
  877. color = new Color(160, 32, 240); // 紫色
  878. break;
  879. case 'legendary':
  880. color = new Color(255, 165, 0); // 橙色
  881. break;
  882. default:
  883. color = new Color(255, 255, 255); // 默认白色
  884. }
  885. sprite.color = color;
  886. }
  887. // 加载武器图标
  888. private loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  889. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  890. const b1Node = block.getChildByName('B1');
  891. if (!b1Node) {
  892. console.warn('找不到B1节点');
  893. return;
  894. }
  895. const weaponNode = b1Node.getChildByName('Weapon');
  896. if (!weaponNode) {
  897. console.warn('找不到Weapon节点');
  898. return;
  899. }
  900. const weaponSprite = weaponNode.getComponent(Sprite);
  901. if (!weaponSprite) {
  902. console.warn('Weapon节点上没有Sprite组件');
  903. return;
  904. }
  905. // 获取武器配置中的图片路径
  906. const spriteConfig = weaponConfig.visualConfig?.weaponSprites;
  907. if (!spriteConfig) {
  908. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  909. return;
  910. }
  911. // 选择合适的图片路径(这里默认使用1x1)
  912. const spritePath = spriteConfig['1x1'] || spriteConfig['1x2'] || spriteConfig['2x1'] || spriteConfig['2x2'];
  913. if (!spritePath) {
  914. console.warn(`武器 ${weaponConfig.name} 没有可用的图片路径`);
  915. return;
  916. }
  917. // 正确的SpriteFrame子资源路径
  918. const spriteFramePath = `${spritePath}/spriteFrame`;
  919. // 加载SpriteFrame子资源
  920. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  921. if (err) {
  922. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  923. return;
  924. }
  925. if (weaponSprite && spriteFrame) {
  926. weaponSprite.spriteFrame = spriteFrame;
  927. }
  928. });
  929. }
  930. // 根据方块获取武器配置
  931. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  932. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  933. }
  934. // 获取方块的武器ID
  935. public getBlockWeaponId(block: Node): string | null {
  936. const weaponConfig = this.getBlockWeaponConfig(block);
  937. return weaponConfig ? weaponConfig.id : null;
  938. }
  939. // 刷新方块 - 重新生成三个新的武器方块
  940. public refreshBlocks() {
  941. this.generateRandomBlocksInKuang();
  942. }
  943. // 刷新按钮点击回调
  944. private onRefreshButtonClicked() {
  945. this.refreshBlocks();
  946. }
  947. /* =================== 合成逻辑 =================== */
  948. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  949. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  950. private tryMergeBlock(block: Node) {
  951. const rarity = this.getBlockRarity(block);
  952. if (!rarity) return;
  953. // 在 placedBlocksContainer 中寻找与之重叠且同稀有度的其他方块
  954. if (!this.placedBlocksContainer) return;
  955. const weaponId = this.getBlockWeaponId(block);
  956. const blockBB = this.getWorldAABB(block);
  957. for (const other of this.placedBlocksContainer.children) {
  958. if (other === block) continue;
  959. if (this.getBlockRarity(other) !== rarity) continue;
  960. if (this.getBlockWeaponId(other) !== weaponId) continue;
  961. const otherBB = this.getWorldAABB(other);
  962. if (this.rectIntersects(blockBB, otherBB)) {
  963. // 找到合成目标
  964. this.performMerge(block, other, rarity);
  965. break;
  966. }
  967. }
  968. }
  969. private performMerge(target: Node, source: Node, rarity: string) {
  970. // 隐藏价格标签并处理 db 关联
  971. this.hidePriceLabel(source);
  972. const srcDb = source['dbNode'];
  973. if (srcDb) srcDb.active = false;
  974. // 销毁被合并方块
  975. source.destroy();
  976. // 升级稀有度
  977. const nextRarity = this.getNextRarity(rarity);
  978. if (nextRarity) {
  979. this.setBlockRarityColor(target, nextRarity);
  980. // 如果有武器配置,也升级
  981. const cfg = this.blockWeaponConfigs.get(target);
  982. if (cfg) {
  983. cfg.rarity = nextRarity;
  984. this.blockWeaponConfigs.set(target, cfg);
  985. }
  986. }
  987. // 播放烟雾动画
  988. const worldPos = new Vec3();
  989. target.getWorldPosition(worldPos);
  990. this.spawnMergeSmoke(worldPos);
  991. // 递归检查是否还能继续合成
  992. if (nextRarity) {
  993. this.tryMergeBlock(target);
  994. }
  995. }
  996. private getBlockRarity(block: Node): string | null {
  997. const cfg = this.blockWeaponConfigs.get(block);
  998. if (cfg) return cfg.rarity;
  999. // fallback based on sprite color maybe
  1000. return null;
  1001. }
  1002. private getNextRarity(rarity: string): string | null {
  1003. const idx = this.rarityOrder.indexOf(rarity);
  1004. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1005. return this.rarityOrder[idx + 1];
  1006. }
  1007. private getWorldAABB(node: Node): Rect {
  1008. const ui = node.getComponent(UITransform);
  1009. if (!ui) return new Rect();
  1010. const pos = node.worldPosition;
  1011. const width = ui.width;
  1012. const height = ui.height;
  1013. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1014. }
  1015. private rectIntersects(a: Rect, b: Rect): boolean {
  1016. return a.x < b.x + b.width &&
  1017. a.x + a.width > b.x &&
  1018. a.y < b.y + b.height &&
  1019. a.y + a.height > b.y;
  1020. }
  1021. /** 生成烟雾特效 */
  1022. private spawnMergeSmoke(worldPos: Vec3) {
  1023. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1024. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1025. if (err || !sData) {
  1026. console.warn('加载合成烟雾动画失败', err);
  1027. return;
  1028. }
  1029. const node = new Node('MergeSmoke');
  1030. const skeleton = node.addComponent(sp.Skeleton);
  1031. skeleton.skeletonData = sData;
  1032. skeleton.premultipliedAlpha = false;
  1033. skeleton.setAnimation(0, 'animation', false);
  1034. skeleton.setCompleteListener(() => node.destroy());
  1035. const canvas = find('Canvas');
  1036. if (canvas) canvas.addChild(node);
  1037. node.setWorldPosition(worldPos);
  1038. });
  1039. }
  1040. /** 在放置失败时尝试与现有方块进行合成 */
  1041. private tryMergeOnOverlap(draggedBlock: Node): boolean {
  1042. if (!this.placedBlocksContainer) return false;
  1043. const rarity = this.getBlockRarity(draggedBlock);
  1044. if (!rarity) return false;
  1045. const weaponId = this.getBlockWeaponId(draggedBlock);
  1046. const dragBB = this.getWorldAABB(draggedBlock);
  1047. for (const target of this.placedBlocksContainer.children) {
  1048. if (target === draggedBlock) continue;
  1049. if (this.getBlockRarity(target) !== rarity) continue;
  1050. if (this.getBlockWeaponId(target) !== weaponId) continue;
  1051. const targetBB = this.getWorldAABB(target);
  1052. if (this.rectIntersects(dragBB, targetBB)) {
  1053. // 执行合并:目标保留,拖拽方块销毁
  1054. this.performMerge(target, draggedBlock, rarity);
  1055. return true;
  1056. }
  1057. }
  1058. return false;
  1059. }
  1060. }