BlockManager.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  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. // 生成三个随机块
  159. for (let i = 0; i < 3; i++) {
  160. // 随机选择一个预制体
  161. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  162. const prefab = this.blockPrefabs[randomIndex];
  163. // 实例化预制体
  164. const block = instantiate(prefab);
  165. this.node.addChild(block);
  166. // 设置位置
  167. block.position = offsets[i];
  168. // 保存原始位置
  169. this.originalPositions.set(block, offsets[i].clone());
  170. // 标记方块位置为kuang
  171. this.blockLocations.set(block, 'kuang');
  172. // 添加到块数组
  173. this.blocks.push(block);
  174. // 查找并保存价格标签节点
  175. this.findAndSavePriceNode(block);
  176. // 添加触摸事件
  177. this.setupDragEvents(block);
  178. }
  179. }
  180. // 查找并保存价格标签节点
  181. findAndSavePriceNode(block: Node) {
  182. // 查找db01节点
  183. let db01 = block.getChildByName('db01');
  184. // 如果没有db01节点,创建一个
  185. if (!db01) {
  186. db01 = new Node('db01');
  187. block.addChild(db01);
  188. db01.position = new Vec3(0, -80, 0); // 放在方块下方
  189. }
  190. // 查找Price节点
  191. let priceNode = db01.getChildByName('Price');
  192. // 如果没有Price节点,创建一个
  193. if (!priceNode) {
  194. priceNode = new Node('Price');
  195. db01.addChild(priceNode);
  196. // 添加UI变换组件
  197. const transform = priceNode.addComponent(UITransform);
  198. transform.contentSize = new Size(80, 30);
  199. // 添加标签组件
  200. const label = priceNode.addComponent(Label);
  201. label.string = this.generateRandomPrice().toString();
  202. label.fontSize = 20;
  203. label.color = new Color(255, 255, 0, 255); // 黄色
  204. // 居中显示
  205. label.horizontalAlign = Label.HorizontalAlign.CENTER;
  206. label.verticalAlign = Label.VerticalAlign.CENTER;
  207. }
  208. // 保存价格节点引用
  209. this.blockPriceMap.set(block, priceNode);
  210. // 确保价格标签可见
  211. priceNode.active = true;
  212. }
  213. // 生成随机价格
  214. generateRandomPrice(): number {
  215. // 生成50-100之间的随机价格
  216. return Math.floor(Math.random() * 51) + 50;
  217. }
  218. // 获取方块价格
  219. getBlockPrice(block: Node): number {
  220. const priceNode = this.blockPriceMap.get(block);
  221. if (priceNode) {
  222. const label = priceNode.getComponent(Label);
  223. if (label) {
  224. // 尝试解析价格
  225. const price = parseInt(label.string);
  226. if (!isNaN(price)) {
  227. return price;
  228. }
  229. }
  230. }
  231. // 默认价格
  232. return 50;
  233. }
  234. // 隐藏价格标签
  235. hidePriceLabel(block: Node) {
  236. const priceNode = this.blockPriceMap.get(block);
  237. if (priceNode) {
  238. priceNode.active = false;
  239. }
  240. }
  241. // 显示价格标签
  242. showPriceLabel(block: Node) {
  243. const priceNode = this.blockPriceMap.get(block);
  244. if (priceNode) {
  245. priceNode.active = true;
  246. }
  247. }
  248. // 扣除玩家金币
  249. deductPlayerCoins(amount: number): boolean {
  250. if (this.playerCoins >= amount) {
  251. this.playerCoins -= amount;
  252. this.updateCoinDisplay();
  253. return true;
  254. }
  255. return false;
  256. }
  257. setupDragEvents(block: Node) {
  258. // 添加触摸开始事件
  259. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  260. // 记录当前拖拽的块
  261. this.currentDragBlock = block;
  262. // 记录触摸起始位置
  263. this.startPos = event.getUILocation();
  264. // 记录块的起始位置
  265. this.blockStartPos.set(block.position);
  266. // 将块置于顶层
  267. block.setSiblingIndex(this.node.children.length - 1);
  268. // 临时保存方块占用的网格,而不是直接移除
  269. this.tempStoreBlockOccupiedGrids(block);
  270. }, this);
  271. // 添加触摸移动事件
  272. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  273. if (!this.currentDragBlock) return;
  274. // 计算触摸点位移
  275. const location = event.getUILocation();
  276. const deltaX = location.x - this.startPos.x;
  277. const deltaY = location.y - this.startPos.y;
  278. // 更新块的位置
  279. this.currentDragBlock.position = new Vec3(
  280. this.blockStartPos.x + deltaX,
  281. this.blockStartPos.y + deltaY,
  282. this.blockStartPos.z
  283. );
  284. }, this);
  285. // 添加触摸结束事件
  286. block.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  287. if (this.currentDragBlock) {
  288. // 获取当前触摸位置
  289. const touchPos = event.getUILocation();
  290. // 检查是否拖到了kuang区域
  291. if (this.isInKuangArea(touchPos)) {
  292. // 如果拖回kuang区域,恢复到原始位置
  293. const originalPos = this.originalPositions.get(this.currentDragBlock);
  294. if (originalPos) {
  295. this.currentDragBlock.position = originalPos.clone();
  296. }
  297. // 恢复方块原来的占用状态(如果有)
  298. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  299. // 更新方块位置标记
  300. this.blockLocations.set(this.currentDragBlock, 'kuang');
  301. // 确保价格标签显示
  302. this.showPriceLabel(this.currentDragBlock);
  303. } else if (this.tryPlaceBlockToGrid(this.currentDragBlock)) {
  304. // 获取方块价格
  305. const price = this.getBlockPrice(this.currentDragBlock);
  306. // 尝试扣除金币
  307. if (this.deductPlayerCoins(price)) {
  308. // 扣除成功,清除临时保存的占用状态
  309. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  310. // 更新方块位置标记
  311. this.blockLocations.set(this.currentDragBlock, 'grid');
  312. // 隐藏价格标签
  313. this.hidePriceLabel(this.currentDragBlock);
  314. } else {
  315. // 金币不足,放置失败,返回原位
  316. const originalPos = this.originalPositions.get(this.currentDragBlock);
  317. if (originalPos) {
  318. this.currentDragBlock.position = originalPos.clone();
  319. }
  320. // 恢复方块原来的占用状态
  321. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  322. // 确保价格标签显示
  323. this.showPriceLabel(this.currentDragBlock);
  324. }
  325. } else {
  326. // 放置失败,返回原位
  327. const currentLocation = this.blockLocations.get(this.currentDragBlock);
  328. if (currentLocation === 'kuang') {
  329. // 如果之前在kuang中,返回kuang中的位置
  330. const originalPos = this.originalPositions.get(this.currentDragBlock);
  331. if (originalPos) {
  332. this.currentDragBlock.position = originalPos.clone();
  333. }
  334. } else {
  335. // 否则返回拖拽开始的位置
  336. this.currentDragBlock.position = this.blockStartPos.clone();
  337. }
  338. // 恢复方块原来的占用状态
  339. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  340. // 确保价格标签显示
  341. this.showPriceLabel(this.currentDragBlock);
  342. }
  343. this.currentDragBlock = null;
  344. }
  345. }, this);
  346. // 添加触摸取消事件
  347. block.on(Node.EventType.TOUCH_CANCEL, () => {
  348. if (this.currentDragBlock) {
  349. // 触摸取消,返回原位
  350. this.currentDragBlock.position = this.blockStartPos.clone();
  351. // 恢复方块原来的占用状态
  352. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  353. // 确保价格标签显示
  354. this.showPriceLabel(this.currentDragBlock);
  355. this.currentDragBlock = null;
  356. }
  357. }, this);
  358. }
  359. // 检查是否在kuang区域内
  360. isInKuangArea(touchPos: Vec2): boolean {
  361. if (!this.kuangContainer) return false;
  362. // 获取kuang的世界矩形
  363. const kuangTransform = this.kuangContainer.getComponent(UITransform);
  364. if (!kuangTransform) return false;
  365. // 计算kuang的世界边界
  366. const kuangBoundingBox = new Rect(
  367. this.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  368. this.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  369. kuangTransform.width,
  370. kuangTransform.height
  371. );
  372. // 检查触摸点是否在kuang矩形内
  373. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  374. }
  375. // 临时保存方块占用的网格
  376. tempStoreBlockOccupiedGrids(block: Node) {
  377. // 获取方块占用的网格
  378. const occupiedGrids = block['occupiedGrids'];
  379. if (!occupiedGrids || occupiedGrids.length === 0) return;
  380. // 保存到临时数组
  381. this.tempRemovedOccupiedGrids.push({
  382. block: block,
  383. occupiedGrids: [...occupiedGrids] // 复制一份,避免引用问题
  384. });
  385. // 移除占用标记
  386. for (const grid of occupiedGrids) {
  387. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  388. grid.col >= 0 && grid.col < this.GRID_COLS) {
  389. this.gridOccupationMap[grid.row][grid.col] = 0;
  390. }
  391. }
  392. // 清空方块的占用记录
  393. block['occupiedGrids'] = [];
  394. }
  395. // 恢复方块原来的占用状态
  396. restoreBlockOccupiedGrids(block: Node) {
  397. // 查找临时保存的占用状态
  398. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  399. if (index === -1) return;
  400. const savedItem = this.tempRemovedOccupiedGrids[index];
  401. // 恢复占用标记
  402. for (const grid of savedItem.occupiedGrids) {
  403. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  404. grid.col >= 0 && grid.col < this.GRID_COLS) {
  405. this.gridOccupationMap[grid.row][grid.col] = 1;
  406. }
  407. }
  408. // 恢复方块的占用记录
  409. block['occupiedGrids'] = [...savedItem.occupiedGrids];
  410. // 从临时数组中移除
  411. this.tempRemovedOccupiedGrids.splice(index, 1);
  412. }
  413. // 清除临时保存的占用状态
  414. clearTempStoredOccupiedGrids(block: Node) {
  415. // 查找临时保存的占用状态
  416. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  417. if (index === -1) return;
  418. // 从临时数组中移除
  419. this.tempRemovedOccupiedGrids.splice(index, 1);
  420. }
  421. // 获取网格行列索引
  422. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  423. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  424. const parts = gridNode.name.split('_');
  425. if (parts.length === 3) {
  426. const row = parseInt(parts[1]);
  427. const col = parseInt(parts[2]);
  428. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  429. return { row, col };
  430. }
  431. }
  432. return null;
  433. }
  434. // 找到最近的网格节点
  435. findNearestGridNode(position: Vec3): Node {
  436. if (!this.gridContainer || !this.gridInitialized) return null;
  437. let nearestNode: Node = null;
  438. let minDistance = Number.MAX_VALUE;
  439. // 遍历所有网格节点
  440. for (let row = 0; row < this.GRID_ROWS; row++) {
  441. for (let col = 0; col < this.GRID_COLS; col++) {
  442. const grid = this.gridNodes[row][col];
  443. if (grid) {
  444. const distance = Vec3.distance(position, grid.position);
  445. if (distance < minDistance) {
  446. minDistance = distance;
  447. nearestNode = grid;
  448. }
  449. }
  450. }
  451. }
  452. // 增加容错性,放宽距离限制
  453. if (minDistance > this.gridSpacing * 2) {
  454. // 如果距离超过网格间距的4倍,可能是完全偏离了网格区域
  455. if (minDistance > this.gridSpacing * 4) {
  456. return null;
  457. }
  458. }
  459. return nearestNode;
  460. }
  461. // 尝试将方块放置到网格中
  462. tryPlaceBlockToGrid(block: Node): boolean {
  463. if (!this.gridContainer || !this.gridInitialized) return false;
  464. // 获取B1节点
  465. let b1Node = block;
  466. if (block.name !== 'B1') {
  467. // 查找B1节点
  468. b1Node = block.getChildByName('B1');
  469. if (!b1Node) {
  470. return false;
  471. }
  472. }
  473. // 获取方块B1节点在世界坐标中的位置
  474. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  475. // 将B1节点的世界坐标转换为GridContainer的本地坐标
  476. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  477. // 检查是否在GridContainer范围内
  478. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  479. const halfWidth = gridSize.width / 2;
  480. const halfHeight = gridSize.height / 2;
  481. // 增加容错性,放宽边界检查
  482. const tolerance = this.gridSpacing * 0.5;
  483. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  484. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  485. return false;
  486. }
  487. // 找到最近的网格节点
  488. const nearestGrid = this.findNearestGridNode(gridPos);
  489. if (!nearestGrid) {
  490. // 尝试使用网格行列直接定位
  491. const row = Math.floor((gridPos.y + halfHeight) / this.gridSpacing);
  492. const col = Math.floor((gridPos.x + halfWidth) / this.gridSpacing);
  493. // 检查计算出的行列是否在有效范围内
  494. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  495. const grid = this.gridNodes[row][col];
  496. if (grid) {
  497. return this.tryPlaceBlockToSpecificGrid(block, grid);
  498. }
  499. }
  500. return false;
  501. }
  502. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  503. }
  504. // 尝试将方块放置到指定的网格节点
  505. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  506. // 获取B1节点
  507. let b1Node = block;
  508. if (block.name !== 'B1') {
  509. b1Node = block.getChildByName('B1');
  510. if (!b1Node) {
  511. return false;
  512. }
  513. }
  514. // 检查方块的所有部分是否会与已占用的格子重叠
  515. if (!this.canPlaceBlockAt(block, targetGrid)) {
  516. return false;
  517. }
  518. // 获取网格节点的中心点世界坐标
  519. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  520. // 计算B1节点应该移动到的位置
  521. const targetWorldPos = gridCenterWorldPos.clone();
  522. // 计算根节点需要移动的位置
  523. // 1. 先计算B1节点相对于根节点的偏移
  524. const b1LocalPos = b1Node.position.clone();
  525. // 2. 计算根节点的目标世界坐标
  526. let rootTargetWorldPos;
  527. if (b1Node === block) {
  528. rootTargetWorldPos = targetWorldPos.clone();
  529. } else {
  530. // 如果B1是子节点,需要计算根节点应该在的位置,使B1对准网格中心
  531. rootTargetWorldPos = new Vec3(
  532. targetWorldPos.x - b1LocalPos.x,
  533. targetWorldPos.y - b1LocalPos.y,
  534. targetWorldPos.z
  535. );
  536. }
  537. // 3. 将世界坐标转换为根节点父节点的本地坐标
  538. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  539. // 设置方块位置,确保B1节点的中心与网格节点的中心对齐
  540. block.position = rootTargetLocalPos;
  541. // 标记占用的格子
  542. this.markOccupiedPositions(block, targetGrid);
  543. return true;
  544. }
  545. // 获取方块的所有部分节点及其相对坐标
  546. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  547. const parts: { node: Node, x: number, y: number }[] = [];
  548. // 添加B1节点本身(根节点)
  549. parts.push({ node: block, x: 0, y: 0 });
  550. // 递归查找所有子节点
  551. this.findBlockParts(block, parts, 0, 0);
  552. return parts;
  553. }
  554. // 递归查找方块的所有部分
  555. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  556. // 遍历所有子节点
  557. for (let i = 0; i < node.children.length; i++) {
  558. const child = node.children[i];
  559. // 跳过不参与占用的节点
  560. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  561. continue;
  562. }
  563. let x = parentX;
  564. let y = parentY;
  565. // 尝试从节点名称中解析坐标
  566. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  567. if (match) {
  568. // 如果节点名称是坐标格式,直接使用
  569. x = parseInt(match[1]);
  570. y = parseInt(match[2]);
  571. result.push({ node: child, x, y });
  572. } else if (child.name.startsWith('B')) {
  573. // 如果是B开头的节点,使用其相对位置
  574. // 计算相对于父节点的位置,并转换为网格单位
  575. const relativeX = Math.round(child.position.x / this.gridSpacing);
  576. const relativeY = -Math.round(child.position.y / this.gridSpacing); // Y轴向下为正
  577. x = parentX + relativeX;
  578. y = parentY + relativeY;
  579. result.push({ node: child, x, y });
  580. }
  581. // 递归处理子节点
  582. this.findBlockParts(child, result, x, y);
  583. }
  584. }
  585. // 检查方块是否可以放置在指定位置
  586. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  587. if (!this.gridInitialized) return false;
  588. // 获取目标网格的行列索引
  589. const targetRowCol = this.getGridRowCol(targetGrid);
  590. if (!targetRowCol) return false;
  591. // 获取方块的所有部分
  592. const parts = this.getBlockParts(block);
  593. // 检查每个部分是否与已占用的格子重叠
  594. for (const part of parts) {
  595. // 计算在网格中的行列位置
  596. const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
  597. const col = targetRowCol.col + part.x; // X轴向右为正
  598. // 检查是否超出网格范围
  599. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  600. return false;
  601. }
  602. // 检查该位置是否已被占用
  603. if (this.gridOccupationMap[row][col] === 1) {
  604. return false;
  605. }
  606. }
  607. return true;
  608. }
  609. // 标记方块占用的格子
  610. markOccupiedPositions(block: Node, targetGrid: Node) {
  611. if (!this.gridInitialized) return;
  612. // 获取目标网格的行列索引
  613. const targetRowCol = this.getGridRowCol(targetGrid);
  614. if (!targetRowCol) return;
  615. // 获取方块的所有部分
  616. const parts = this.getBlockParts(block);
  617. // 清除之前的占用记录
  618. block['occupiedGrids'] = [];
  619. // 为每个部分标记占用位置
  620. for (const part of parts) {
  621. // 计算在网格中的行列位置
  622. const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
  623. const col = targetRowCol.col + part.x; // X轴向右为正
  624. // 检查是否在有效范围内
  625. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  626. // 更新网格占用情况
  627. this.gridOccupationMap[row][col] = 1;
  628. // 存储方块与网格的关联
  629. block['occupiedGrids'] = block['occupiedGrids'] || [];
  630. block['occupiedGrids'].push({ row, col });
  631. }
  632. }
  633. }
  634. // 移除方块占用的格子
  635. removeBlockFromGrid(block: Node) {
  636. // 获取方块占用的网格
  637. const occupiedGrids = block['occupiedGrids'];
  638. if (!occupiedGrids) return;
  639. // 移除占用标记
  640. for (const grid of occupiedGrids) {
  641. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  642. grid.col >= 0 && grid.col < this.GRID_COLS) {
  643. this.gridOccupationMap[grid.row][grid.col] = 0;
  644. }
  645. }
  646. // 清空方块的占用记录
  647. block['occupiedGrids'] = [];
  648. }
  649. clearBlocks() {
  650. // 移除所有已经生成的块
  651. for (const block of this.blocks) {
  652. if (block.isValid) {
  653. // 移除占用的格子
  654. this.removeBlockFromGrid(block);
  655. // 销毁方块
  656. block.destroy();
  657. }
  658. }
  659. this.blocks = [];
  660. // 清空原始位置记录
  661. this.originalPositions.clear();
  662. // 清空位置标记
  663. this.blockLocations.clear();
  664. // 清空价格标签映射
  665. this.blockPriceMap.clear();
  666. // 重置网格占用情况
  667. this.initGridOccupationMap();
  668. }
  669. }