BlockManager.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Vec2, UITransform, find, Rect, Label, Color, Size } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('BlockManager')
  4. export class BlockManager extends Component {
  5. // 预制体数组,存储5个预制体
  6. @property([Prefab])
  7. public blockPrefabs: Prefab[] = [];
  8. // 网格容器节点
  9. @property({
  10. type: Node,
  11. tooltip: '拖拽GridContainer节点到这里'
  12. })
  13. public gridContainer: Node = null;
  14. // 方块容器节点(kuang)
  15. @property({
  16. type: Node,
  17. tooltip: '拖拽kuang节点到这里'
  18. })
  19. public kuangContainer: Node = null;
  20. // 金币标签节点
  21. @property({
  22. type: Node,
  23. tooltip: '拖拽CoinLabel节点到这里'
  24. })
  25. public coinLabelNode: Node = null;
  26. // 玩家金币数量
  27. private playerCoins: number = 200;
  28. // 方块价格标签映射
  29. private blockPriceMap: Map<Node, Node> = new Map();
  30. // 已经生成的块
  31. private blocks: Node[] = [];
  32. // 当前拖拽的块
  33. private currentDragBlock: Node | null = null;
  34. // 拖拽起始位置
  35. private startPos = new Vec2();
  36. // 块的起始位置
  37. private blockStartPos: Vec3 = new Vec3();
  38. // 网格占用情况,用于控制台输出
  39. private gridOccupationMap: number[][] = [];
  40. // 网格行数和列数
  41. private readonly GRID_ROWS = 6;
  42. private readonly GRID_COLS = 11;
  43. // 是否已初始化网格信息
  44. private gridInitialized = false;
  45. // 存储网格节点信息
  46. private gridNodes: Node[][] = [];
  47. // 网格间距
  48. private gridSpacing = 54;
  49. // 不参与占用的节点名称列表
  50. private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
  51. // 临时保存方块的原始占用格子
  52. private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  53. // 方块原始位置(在kuang中的位置)
  54. private originalPositions: Map<Node, Vec3> = new Map();
  55. // 方块当前所在的区域
  56. private blockLocations: Map<Node, string> = new Map();
  57. start() {
  58. // 如果没有指定GridContainer,尝试找到它
  59. if (!this.gridContainer) {
  60. this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
  61. if (!this.gridContainer) {
  62. console.error('找不到GridContainer节点');
  63. return;
  64. }
  65. }
  66. // 如果没有指定kuangContainer,尝试找到它
  67. if (!this.kuangContainer) {
  68. this.kuangContainer = find('Canvas/GameLevelUI/kuang');
  69. if (!this.kuangContainer) {
  70. console.error('找不到kuang节点');
  71. return;
  72. }
  73. }
  74. // 如果没有指定coinLabelNode,尝试找到它
  75. if (!this.coinLabelNode) {
  76. this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
  77. if (!this.coinLabelNode) {
  78. console.error('找不到CoinLabel节点');
  79. return;
  80. }
  81. }
  82. // 初始化玩家金币显示
  83. this.updateCoinDisplay();
  84. // 初始化网格信息
  85. this.initGridInfo();
  86. // 初始化网格占用情况
  87. this.initGridOccupationMap();
  88. // 生成随机的三个块
  89. this.generateRandomBlocks();
  90. }
  91. // 更新金币显示
  92. updateCoinDisplay() {
  93. if (this.coinLabelNode) {
  94. const label = this.coinLabelNode.getComponent(Label);
  95. if (label) {
  96. label.string = this.playerCoins.toString();
  97. }
  98. }
  99. }
  100. // 初始化网格信息
  101. initGridInfo() {
  102. if (!this.gridContainer || this.gridInitialized) return;
  103. // 创建二维数组存储网格节点
  104. this.gridNodes = [];
  105. for (let row = 0; row < this.GRID_ROWS; row++) {
  106. this.gridNodes[row] = [];
  107. }
  108. // 遍历所有网格节点,将它们放入二维数组
  109. for (let i = 0; i < this.gridContainer.children.length; i++) {
  110. const grid = this.gridContainer.children[i];
  111. if (grid.name.startsWith('Grid_')) {
  112. // 从节点名称解析行列信息,例如Grid_2_3表示第2行第3列
  113. const parts = grid.name.split('_');
  114. if (parts.length === 3) {
  115. const row = parseInt(parts[1]);
  116. const col = parseInt(parts[2]);
  117. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  118. this.gridNodes[row][col] = grid;
  119. }
  120. }
  121. }
  122. }
  123. // 计算网格间距
  124. if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
  125. if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
  126. const pos1 = this.gridNodes[0][0].position;
  127. const pos2 = this.gridNodes[1][0].position;
  128. this.gridSpacing = Math.abs(pos2.y - pos1.y);
  129. }
  130. }
  131. this.gridInitialized = true;
  132. }
  133. // 初始化网格占用情况
  134. initGridOccupationMap() {
  135. this.gridOccupationMap = [];
  136. for (let row = 0; row < this.GRID_ROWS; row++) {
  137. const rowArray: number[] = [];
  138. for (let col = 0; col < this.GRID_COLS; col++) {
  139. rowArray.push(0);
  140. }
  141. this.gridOccupationMap.push(rowArray);
  142. }
  143. }
  144. generateRandomBlocks() {
  145. // 清除现有的块
  146. this.clearBlocks();
  147. // 检查是否有预制体可用
  148. if (this.blockPrefabs.length === 0) {
  149. console.error('没有可用的预制体');
  150. return;
  151. }
  152. // 位置偏移量
  153. const offsets = [
  154. new Vec3(-200, 0, 0),
  155. new Vec3(0, 0, 0),
  156. new Vec3(200, 0, 0)
  157. ];
  158. // 获取kuang节点下的db01、db02、db03节点
  159. const dbNodes = [
  160. find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/db01'),
  161. find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/db02'),
  162. find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/db03')
  163. ];
  164. // 生成三个随机块
  165. for (let i = 0; i < 3; i++) {
  166. // 随机选择一个预制体
  167. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  168. const prefab = this.blockPrefabs[randomIndex];
  169. // 实例化预制体
  170. const block = instantiate(prefab);
  171. this.node.addChild(block);
  172. // 设置位置
  173. block.position = offsets[i];
  174. // 保存原始位置
  175. this.originalPositions.set(block, offsets[i].clone());
  176. // 标记方块位置为kuang
  177. this.blockLocations.set(block, 'kuang');
  178. // 添加到块数组
  179. this.blocks.push(block);
  180. // 将对应的db节点与方块关联
  181. if (dbNodes[i]) {
  182. // 保存价格节点引用 (Price是db节点的子节点)
  183. const priceNode = dbNodes[i].getChildByName('Price');
  184. if (priceNode) {
  185. this.blockPriceMap.set(block, priceNode);
  186. priceNode.active = true;
  187. }
  188. // 将db节点作为方块的子节点
  189. this.associateDbNodeWithBlock(block, dbNodes[i]);
  190. }
  191. // 添加触摸事件
  192. this.setupDragEvents(block);
  193. }
  194. }
  195. // 将db节点与方块关联
  196. associateDbNodeWithBlock(block: Node, dbNode: Node) {
  197. // 记录db节点与方块的关联
  198. block['dbNode'] = dbNode;
  199. // 当方块移动时,db节点也跟随移动
  200. block.on(Node.EventType.TRANSFORM_CHANGED, () => {
  201. if (dbNode && block.parent) {
  202. // 检查方块当前位置
  203. const location = this.blockLocations.get(block);
  204. // 如果方块在网格中,不需要显示db节点
  205. if (location === 'grid') {
  206. dbNode.active = false;
  207. return;
  208. }
  209. // 确保db节点可见
  210. dbNode.active = true;
  211. // 获取方块在世界坐标系中的位置
  212. const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position);
  213. // 将世界坐标转换为db节点父节点的本地坐标
  214. const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  215. // 设置db节点位置,放在方块下方
  216. dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z);
  217. }
  218. });
  219. }
  220. // 获取方块价格
  221. getBlockPrice(block: Node): number {
  222. const priceNode = this.blockPriceMap.get(block);
  223. if (priceNode) {
  224. const label = priceNode.getComponent(Label);
  225. if (label) {
  226. // 尝试解析价格
  227. const price = parseInt(label.string);
  228. if (!isNaN(price)) {
  229. return price;
  230. }
  231. }
  232. }
  233. // 默认价格
  234. return 50;
  235. }
  236. // 隐藏价格标签
  237. hidePriceLabel(block: Node) {
  238. const priceNode = this.blockPriceMap.get(block);
  239. if (priceNode) {
  240. priceNode.active = false;
  241. }
  242. }
  243. // 显示价格标签
  244. showPriceLabel(block: Node) {
  245. const priceNode = this.blockPriceMap.get(block);
  246. if (priceNode) {
  247. priceNode.active = true;
  248. }
  249. }
  250. // 扣除玩家金币
  251. deductPlayerCoins(amount: number): boolean {
  252. if (this.playerCoins >= amount) {
  253. this.playerCoins -= amount;
  254. this.updateCoinDisplay();
  255. return true;
  256. }
  257. return false;
  258. }
  259. setupDragEvents(block: Node) {
  260. // 添加触摸开始事件
  261. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  262. // 记录当前拖拽的块
  263. this.currentDragBlock = block;
  264. // 记录触摸起始位置
  265. this.startPos = event.getUILocation();
  266. // 记录块的起始位置
  267. this.blockStartPos.set(block.position);
  268. // 记录块的起始位置类型
  269. this.currentDragBlock['startLocation'] = this.blockLocations.get(block);
  270. // 将块置于顶层
  271. block.setSiblingIndex(this.node.children.length - 1);
  272. // 临时保存方块占用的网格,而不是直接移除
  273. this.tempStoreBlockOccupiedGrids(block);
  274. }, this);
  275. // 添加触摸移动事件
  276. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  277. if (!this.currentDragBlock) return;
  278. // 计算触摸点位移
  279. const location = event.getUILocation();
  280. const deltaX = location.x - this.startPos.x;
  281. const deltaY = location.y - this.startPos.y;
  282. // 更新块的位置
  283. this.currentDragBlock.position = new Vec3(
  284. this.blockStartPos.x + deltaX,
  285. this.blockStartPos.y + deltaY,
  286. this.blockStartPos.z
  287. );
  288. }, this);
  289. // 添加触摸结束事件
  290. block.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  291. if (this.currentDragBlock) {
  292. // 获取当前触摸位置
  293. const touchPos = event.getUILocation();
  294. // 获取起始位置类型
  295. const startLocation = this.currentDragBlock['startLocation'];
  296. // 检查是否拖到了kuang区域
  297. if (this.isInKuangArea(touchPos)) {
  298. // 如果拖回kuang区域,恢复到原始位置
  299. const originalPos = this.originalPositions.get(this.currentDragBlock);
  300. if (originalPos) {
  301. this.currentDragBlock.position = originalPos.clone();
  302. }
  303. // 恢复方块原来的占用状态(如果有)
  304. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  305. // 更新方块位置标记
  306. this.blockLocations.set(this.currentDragBlock, 'kuang');
  307. // 确保价格标签显示
  308. this.showPriceLabel(this.currentDragBlock);
  309. // 如果方块之前在网格中,需要恢复金币
  310. if (startLocation === 'grid') {
  311. // 获取方块价格
  312. const price = this.getBlockPrice(this.currentDragBlock);
  313. // 恢复金币
  314. this.playerCoins += price;
  315. // 更新金币显示
  316. this.updateCoinDisplay();
  317. // 重置已放置标记
  318. this.currentDragBlock['placedBefore'] = false;
  319. }
  320. // 确保db节点可见并回到正确位置
  321. const dbNode = this.currentDragBlock['dbNode'];
  322. if (dbNode) {
  323. dbNode.active = true;
  324. // 触发一次位置更新,确保db节点位置正确
  325. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  326. }
  327. } else if (this.tryPlaceBlockToGrid(this.currentDragBlock)) {
  328. // 获取方块价格
  329. const price = this.getBlockPrice(this.currentDragBlock);
  330. // 如果方块之前在网格中,不需要重复扣除金币
  331. if (startLocation === 'grid') {
  332. // 清除临时保存的占用状态
  333. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  334. // 更新方块位置标记
  335. this.blockLocations.set(this.currentDragBlock, 'grid');
  336. // 隐藏价格标签
  337. this.hidePriceLabel(this.currentDragBlock);
  338. } else {
  339. // 尝试扣除金币
  340. if (this.deductPlayerCoins(price)) {
  341. // 扣除成功,清除临时保存的占用状态
  342. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  343. // 更新方块位置标记
  344. this.blockLocations.set(this.currentDragBlock, 'grid');
  345. // 隐藏价格标签
  346. this.hidePriceLabel(this.currentDragBlock);
  347. // 标记方块已经放置过
  348. this.currentDragBlock['placedBefore'] = true;
  349. } else {
  350. // 金币不足,放置失败,返回原位
  351. const originalPos = this.originalPositions.get(this.currentDragBlock);
  352. if (originalPos) {
  353. this.currentDragBlock.position = originalPos.clone();
  354. }
  355. // 恢复方块原来的占用状态
  356. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  357. // 确保价格标签显示
  358. this.showPriceLabel(this.currentDragBlock);
  359. // 确保db节点可见并回到正确位置
  360. const dbNode = this.currentDragBlock['dbNode'];
  361. if (dbNode) {
  362. dbNode.active = true;
  363. // 触发一次位置更新,确保db节点位置正确
  364. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  365. }
  366. }
  367. }
  368. } else {
  369. // 放置失败,返回原位
  370. const currentLocation = this.blockLocations.get(this.currentDragBlock);
  371. if (currentLocation === 'kuang') {
  372. // 如果之前在kuang中,返回kuang中的位置
  373. const originalPos = this.originalPositions.get(this.currentDragBlock);
  374. if (originalPos) {
  375. this.currentDragBlock.position = originalPos.clone();
  376. }
  377. } else {
  378. // 否则返回拖拽开始的位置
  379. this.currentDragBlock.position = this.blockStartPos.clone();
  380. }
  381. // 恢复方块原来的占用状态
  382. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  383. // 确保价格标签显示
  384. this.showPriceLabel(this.currentDragBlock);
  385. // 确保db节点可见并回到正确位置
  386. const dbNode = this.currentDragBlock['dbNode'];
  387. if (dbNode) {
  388. dbNode.active = true;
  389. // 触发一次位置更新,确保db节点位置正确
  390. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  391. }
  392. }
  393. this.currentDragBlock = null;
  394. }
  395. }, this);
  396. // 添加触摸取消事件
  397. block.on(Node.EventType.TOUCH_CANCEL, () => {
  398. if (this.currentDragBlock) {
  399. // 获取起始位置类型
  400. const startLocation = this.currentDragBlock['startLocation'];
  401. // 触摸取消,返回原位
  402. this.currentDragBlock.position = this.blockStartPos.clone();
  403. // 恢复方块原来的占用状态
  404. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  405. // 确保价格标签显示
  406. this.showPriceLabel(this.currentDragBlock);
  407. // 如果方块之前在网格中且现在在kuang区域,需要恢复金币
  408. if (startLocation === 'grid' &&
  409. this.blockLocations.get(this.currentDragBlock) === 'kuang') {
  410. // 获取方块价格
  411. const price = this.getBlockPrice(this.currentDragBlock);
  412. // 恢复金币
  413. this.playerCoins += price;
  414. // 更新金币显示
  415. this.updateCoinDisplay();
  416. // 重置已放置标记
  417. this.currentDragBlock['placedBefore'] = false;
  418. }
  419. // 确保db节点可见并回到正确位置
  420. const dbNode = this.currentDragBlock['dbNode'];
  421. if (dbNode) {
  422. dbNode.active = true;
  423. // 触发一次位置更新,确保db节点位置正确
  424. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  425. }
  426. this.currentDragBlock = null;
  427. }
  428. }, this);
  429. }
  430. // 检查是否在kuang区域内
  431. isInKuangArea(touchPos: Vec2): boolean {
  432. if (!this.kuangContainer) return false;
  433. // 获取kuang的世界矩形
  434. const kuangTransform = this.kuangContainer.getComponent(UITransform);
  435. if (!kuangTransform) return false;
  436. // 计算kuang的世界边界
  437. const kuangBoundingBox = new Rect(
  438. this.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  439. this.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  440. kuangTransform.width,
  441. kuangTransform.height
  442. );
  443. // 检查触摸点是否在kuang矩形内
  444. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  445. }
  446. // 临时保存方块占用的网格
  447. tempStoreBlockOccupiedGrids(block: Node) {
  448. // 获取方块占用的网格
  449. const occupiedGrids = block['occupiedGrids'];
  450. if (!occupiedGrids || occupiedGrids.length === 0) return;
  451. // 保存到临时数组
  452. this.tempRemovedOccupiedGrids.push({
  453. block: block,
  454. occupiedGrids: [...occupiedGrids] // 复制一份,避免引用问题
  455. });
  456. // 移除占用标记
  457. for (const grid of occupiedGrids) {
  458. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  459. grid.col >= 0 && grid.col < this.GRID_COLS) {
  460. this.gridOccupationMap[grid.row][grid.col] = 0;
  461. }
  462. }
  463. // 清空方块的占用记录
  464. block['occupiedGrids'] = [];
  465. }
  466. // 恢复方块原来的占用状态
  467. restoreBlockOccupiedGrids(block: Node) {
  468. // 查找临时保存的占用状态
  469. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  470. if (index === -1) return;
  471. const savedItem = this.tempRemovedOccupiedGrids[index];
  472. // 恢复占用标记
  473. for (const grid of savedItem.occupiedGrids) {
  474. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  475. grid.col >= 0 && grid.col < this.GRID_COLS) {
  476. this.gridOccupationMap[grid.row][grid.col] = 1;
  477. }
  478. }
  479. // 恢复方块的占用记录
  480. block['occupiedGrids'] = [...savedItem.occupiedGrids];
  481. // 从临时数组中移除
  482. this.tempRemovedOccupiedGrids.splice(index, 1);
  483. }
  484. // 清除临时保存的占用状态
  485. clearTempStoredOccupiedGrids(block: Node) {
  486. // 查找临时保存的占用状态
  487. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  488. if (index === -1) return;
  489. // 从临时数组中移除
  490. this.tempRemovedOccupiedGrids.splice(index, 1);
  491. }
  492. // 获取网格行列索引
  493. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  494. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  495. const parts = gridNode.name.split('_');
  496. if (parts.length === 3) {
  497. const row = parseInt(parts[1]);
  498. const col = parseInt(parts[2]);
  499. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  500. return { row, col };
  501. }
  502. }
  503. return null;
  504. }
  505. // 找到最近的网格节点
  506. findNearestGridNode(position: Vec3): Node {
  507. if (!this.gridContainer || !this.gridInitialized) return null;
  508. let nearestNode: Node = null;
  509. let minDistance = Number.MAX_VALUE;
  510. // 遍历所有网格节点
  511. for (let row = 0; row < this.GRID_ROWS; row++) {
  512. for (let col = 0; col < this.GRID_COLS; col++) {
  513. const grid = this.gridNodes[row][col];
  514. if (grid) {
  515. const distance = Vec3.distance(position, grid.position);
  516. if (distance < minDistance) {
  517. minDistance = distance;
  518. nearestNode = grid;
  519. }
  520. }
  521. }
  522. }
  523. // 增加容错性,放宽距离限制
  524. if (minDistance > this.gridSpacing * 2) {
  525. // 如果距离超过网格间距的4倍,可能是完全偏离了网格区域
  526. if (minDistance > this.gridSpacing * 4) {
  527. return null;
  528. }
  529. }
  530. return nearestNode;
  531. }
  532. // 尝试将方块放置到网格中
  533. tryPlaceBlockToGrid(block: Node): boolean {
  534. if (!this.gridContainer || !this.gridInitialized) return false;
  535. // 记录方块之前的位置
  536. const previousLocation = this.blockLocations.get(block);
  537. // 获取B1节点
  538. let b1Node = block;
  539. if (block.name !== 'B1') {
  540. // 查找B1节点
  541. b1Node = block.getChildByName('B1');
  542. if (!b1Node) {
  543. return false;
  544. }
  545. }
  546. // 获取方块B1节点在世界坐标中的位置
  547. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  548. // 将B1节点的世界坐标转换为GridContainer的本地坐标
  549. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  550. // 检查是否在GridContainer范围内
  551. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  552. const halfWidth = gridSize.width / 2;
  553. const halfHeight = gridSize.height / 2;
  554. // 增加容错性,放宽边界检查
  555. const tolerance = this.gridSpacing * 0.5;
  556. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  557. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  558. return false;
  559. }
  560. // 找到最近的网格节点
  561. const nearestGrid = this.findNearestGridNode(gridPos);
  562. if (!nearestGrid) {
  563. // 尝试使用网格行列直接定位
  564. const row = Math.floor((gridPos.y + halfHeight) / this.gridSpacing);
  565. const col = Math.floor((gridPos.x + halfWidth) / this.gridSpacing);
  566. // 检查计算出的行列是否在有效范围内
  567. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  568. const grid = this.gridNodes[row][col];
  569. if (grid) {
  570. const result = this.tryPlaceBlockToSpecificGrid(block, grid);
  571. // 如果放置成功,处理db节点
  572. if (result) {
  573. const dbNode = block['dbNode'];
  574. if (dbNode) {
  575. // 隐藏db节点
  576. dbNode.active = false;
  577. }
  578. // 如果方块之前在网格中,不需要重复扣除金币
  579. if (previousLocation === 'grid') {
  580. block['placedBefore'] = true;
  581. }
  582. }
  583. return result;
  584. }
  585. }
  586. return false;
  587. }
  588. const result = this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  589. // 如果放置成功,处理db节点
  590. if (result) {
  591. const dbNode = block['dbNode'];
  592. if (dbNode) {
  593. // 隐藏db节点
  594. dbNode.active = false;
  595. }
  596. // 如果方块之前在网格中,不需要重复扣除金币
  597. if (previousLocation === 'grid') {
  598. block['placedBefore'] = true;
  599. }
  600. }
  601. return result;
  602. }
  603. // 尝试将方块放置到指定的网格节点
  604. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  605. // 获取B1节点
  606. let b1Node = block;
  607. if (block.name !== 'B1') {
  608. b1Node = block.getChildByName('B1');
  609. if (!b1Node) {
  610. return false;
  611. }
  612. }
  613. // 检查方块的所有部分是否会与已占用的格子重叠
  614. if (!this.canPlaceBlockAt(block, targetGrid)) {
  615. return false;
  616. }
  617. // 获取网格节点的中心点世界坐标
  618. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  619. // 计算B1节点应该移动到的位置
  620. const targetWorldPos = gridCenterWorldPos.clone();
  621. // 计算根节点需要移动的位置
  622. // 1. 先计算B1节点相对于根节点的偏移
  623. const b1LocalPos = b1Node.position.clone();
  624. // 2. 计算根节点的目标世界坐标
  625. let rootTargetWorldPos;
  626. if (b1Node === block) {
  627. rootTargetWorldPos = targetWorldPos.clone();
  628. } else {
  629. // 如果B1是子节点,需要计算根节点应该在的位置,使B1对准网格中心
  630. rootTargetWorldPos = new Vec3(
  631. targetWorldPos.x - b1LocalPos.x,
  632. targetWorldPos.y - b1LocalPos.y,
  633. targetWorldPos.z
  634. );
  635. }
  636. // 3. 将世界坐标转换为根节点父节点的本地坐标
  637. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  638. // 设置方块位置,确保B1节点的中心与网格节点的中心对齐
  639. block.position = rootTargetLocalPos;
  640. // 标记占用的格子
  641. this.markOccupiedPositions(block, targetGrid);
  642. return true;
  643. }
  644. // 获取方块的所有部分节点及其相对坐标
  645. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  646. const parts: { node: Node, x: number, y: number }[] = [];
  647. // 添加B1节点本身(根节点)
  648. parts.push({ node: block, x: 0, y: 0 });
  649. // 递归查找所有子节点
  650. this.findBlockParts(block, parts, 0, 0);
  651. return parts;
  652. }
  653. // 递归查找方块的所有部分
  654. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  655. // 遍历所有子节点
  656. for (let i = 0; i < node.children.length; i++) {
  657. const child = node.children[i];
  658. // 跳过不参与占用的节点
  659. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  660. continue;
  661. }
  662. let x = parentX;
  663. let y = parentY;
  664. // 尝试从节点名称中解析坐标
  665. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  666. if (match) {
  667. // 如果节点名称是坐标格式,直接使用
  668. x = parseInt(match[1]);
  669. y = parseInt(match[2]);
  670. result.push({ node: child, x, y });
  671. } else if (child.name.startsWith('B')) {
  672. // 如果是B开头的节点,使用其相对位置
  673. // 计算相对于父节点的位置,并转换为网格单位
  674. const relativeX = Math.round(child.position.x / this.gridSpacing);
  675. const relativeY = -Math.round(child.position.y / this.gridSpacing); // Y轴向下为正
  676. x = parentX + relativeX;
  677. y = parentY + relativeY;
  678. result.push({ node: child, x, y });
  679. }
  680. // 递归处理子节点
  681. this.findBlockParts(child, result, x, y);
  682. }
  683. }
  684. // 检查方块是否可以放置在指定位置
  685. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  686. if (!this.gridInitialized) return false;
  687. // 获取目标网格的行列索引
  688. const targetRowCol = this.getGridRowCol(targetGrid);
  689. if (!targetRowCol) return false;
  690. // 获取方块的所有部分
  691. const parts = this.getBlockParts(block);
  692. // 检查每个部分是否与已占用的格子重叠
  693. for (const part of parts) {
  694. // 计算在网格中的行列位置
  695. const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
  696. const col = targetRowCol.col + part.x; // X轴向右为正
  697. // 检查是否超出网格范围
  698. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  699. return false;
  700. }
  701. // 检查该位置是否已被占用
  702. if (this.gridOccupationMap[row][col] === 1) {
  703. return false;
  704. }
  705. }
  706. return true;
  707. }
  708. // 标记方块占用的格子
  709. markOccupiedPositions(block: Node, targetGrid: Node) {
  710. if (!this.gridInitialized) return;
  711. // 获取目标网格的行列索引
  712. const targetRowCol = this.getGridRowCol(targetGrid);
  713. if (!targetRowCol) return;
  714. // 获取方块的所有部分
  715. const parts = this.getBlockParts(block);
  716. // 清除之前的占用记录
  717. block['occupiedGrids'] = [];
  718. // 为每个部分标记占用位置
  719. for (const part of parts) {
  720. // 计算在网格中的行列位置
  721. const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
  722. const col = targetRowCol.col + part.x; // X轴向右为正
  723. // 检查是否在有效范围内
  724. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  725. // 更新网格占用情况
  726. this.gridOccupationMap[row][col] = 1;
  727. // 存储方块与网格的关联
  728. block['occupiedGrids'] = block['occupiedGrids'] || [];
  729. block['occupiedGrids'].push({ row, col });
  730. }
  731. }
  732. }
  733. // 移除方块占用的格子
  734. removeBlockFromGrid(block: Node) {
  735. // 获取方块占用的网格
  736. const occupiedGrids = block['occupiedGrids'];
  737. if (!occupiedGrids) return;
  738. // 移除占用标记
  739. for (const grid of occupiedGrids) {
  740. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  741. grid.col >= 0 && grid.col < this.GRID_COLS) {
  742. this.gridOccupationMap[grid.row][grid.col] = 0;
  743. }
  744. }
  745. // 清空方块的占用记录
  746. block['occupiedGrids'] = [];
  747. }
  748. clearBlocks() {
  749. // 移除所有已经生成的块
  750. for (const block of this.blocks) {
  751. if (block.isValid) {
  752. // 移除占用的格子
  753. this.removeBlockFromGrid(block);
  754. // 如果有关联的db节点,恢复其位置
  755. const dbNode = block['dbNode'];
  756. if (dbNode && dbNode.isValid) {
  757. // 移除方块移动时的监听
  758. block.off(Node.EventType.TRANSFORM_CHANGED);
  759. // 恢复db节点到原始位置
  760. const originalParent = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
  761. if (originalParent) {
  762. // 确保db节点回到原来的父节点下
  763. const dbName = dbNode.name;
  764. if (!originalParent.getChildByName(dbName)) {
  765. dbNode.parent = originalParent;
  766. }
  767. }
  768. }
  769. // 销毁方块
  770. block.destroy();
  771. }
  772. }
  773. this.blocks = [];
  774. // 清空原始位置记录
  775. this.originalPositions.clear();
  776. // 清空位置标记
  777. this.blockLocations.clear();
  778. // 清空价格标签映射
  779. this.blockPriceMap.clear();
  780. // 重置网格占用情况
  781. this.initGridOccupationMap();
  782. }
  783. }