BlockManager.ts 39 KB

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