BlockManager.ts 40 KB

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