BlockManager.ts 40 KB

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