BlockManager.ts 39 KB

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