BlockManager.ts 42 KB

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