BlockManager.ts 38 KB

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