BlockManager.ts 44 KB

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