BlockManager.ts 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Vec2, UITransform, find, Rect, Label, Color, Size, Sprite, SpriteFrame, resources, Button, Collider2D } from 'cc';
  2. import { ConfigManager, WeaponConfig } from '../Core/ConfigManager';
  3. import { SaveDataManager } from '../LevelSystem/SaveDataManager';
  4. import { LevelSessionManager } from '../Core/LevelSessionManager';
  5. import { LevelConfigManager } from '../LevelSystem/LevelConfigManager';
  6. import { BlockTag } from './BlockSelection/BlockTag';
  7. import { SkillManager } from './SkillSelection/SkillManager';
  8. import EventBus, { GameEvents } from '../Core/EventBus';
  9. import { sp } from 'cc';
  10. const { ccclass, property } = _decorator;
  11. @ccclass('BlockManager')
  12. export class BlockManager extends Component {
  13. // 预制体数组,存储5个预制体
  14. @property([Prefab])
  15. public blockPrefabs: Prefab[] = [];
  16. // 网格容器节点
  17. @property({
  18. type: Node,
  19. tooltip: '拖拽GridContainer节点到这里'
  20. })
  21. public gridContainer: Node = null;
  22. // 方块容器节点(kuang)
  23. @property({
  24. type: Node,
  25. tooltip: '拖拽kuang节点到这里'
  26. })
  27. public kuangContainer: Node = null;
  28. // 金币标签节点
  29. @property({
  30. type: Node,
  31. tooltip: '拖拽CoinLabel节点到这里'
  32. })
  33. public coinLabelNode: Node = null;
  34. // 已放置方块容器节点
  35. @property({
  36. type: Node,
  37. tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/PlacedBlocks)'
  38. })
  39. public placedBlocksContainer: Node = null;
  40. // 游戏是否已开始
  41. public gameStarted: boolean = false;
  42. // 移除移动冷却:相关属性/逻辑已废弃
  43. // SaveDataManager 单例
  44. private saveDataManager: SaveDataManager = null; // 仅用于局外数据
  45. private session: LevelSessionManager = null;
  46. // 方块价格标签映射
  47. private blockPriceMap: Map<Node, Node> = new Map();
  48. // 已经生成的块
  49. private blocks: Node[] = [];
  50. // 当前拖拽的块
  51. private currentDragBlock: Node | null = null;
  52. // 拖拽起始位置
  53. private startPos = new Vec2();
  54. // 块的起始位置
  55. private blockStartPos: Vec3 = new Vec3();
  56. // 网格占用情况,用于控制台输出
  57. private gridOccupationMap: number[][] = [];
  58. // 网格行数和列数
  59. private readonly GRID_ROWS = 6;
  60. private readonly GRID_COLS = 11;
  61. // 是否已初始化网格信息
  62. private gridInitialized = false;
  63. // 存储网格节点信息
  64. private gridNodes: Node[][] = [];
  65. // 网格间距
  66. private gridSpacing = 54;
  67. // 不参与占用的节点名称列表
  68. private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
  69. // 临时保存方块的原始占用格子
  70. private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  71. // 方块原始位置(在kuang中的位置)
  72. private originalPositions: Map<Node, Vec3> = new Map();
  73. // 方块当前所在的区域
  74. private blockLocations: Map<Node, string> = new Map();
  75. // 配置管理器
  76. private configManager: ConfigManager = null;
  77. // 关卡配置管理器
  78. private levelConfigManager: LevelConfigManager = null;
  79. // 方块武器配置映射
  80. private blockWeaponConfigs: Map<Node, WeaponConfig> = new Map();
  81. /** 冷却机制已废弃,方块随时可移动 */
  82. private canMoveBlock(block: Node): boolean { return true; }
  83. // 清除所有冷却(游戏重置时调用)
  84. public clearAllCooldowns() { /* no-op */ }
  85. // 获取当前关卡的武器配置列表
  86. private async getCurrentLevelWeapons(): Promise<string[]> {
  87. if (!this.levelConfigManager || !this.saveDataManager) {
  88. console.warn('关卡配置管理器或存档管理器未初始化,使用默认武器列表');
  89. return [];
  90. }
  91. try {
  92. const currentLevel = this.saveDataManager.getCurrentLevel();
  93. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  94. if (levelConfig && levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
  95. console.log(`关卡 ${currentLevel} 配置的武器:`, levelConfig.weapons);
  96. return levelConfig.weapons;
  97. } else {
  98. console.warn(`关卡 ${currentLevel} 没有配置武器列表`);
  99. return [];
  100. }
  101. } catch (error) {
  102. console.error('获取当前关卡武器配置失败:', error);
  103. return [];
  104. }
  105. }
  106. // 根据武器名称获取武器配置
  107. private getWeaponConfigByName(weaponName: string): WeaponConfig | null {
  108. if (!this.configManager) return null;
  109. const allWeapons = this.configManager.getAllWeapons();
  110. return allWeapons.find(weapon => weapon.name === weaponName) || null;
  111. }
  112. // 设置事件监听器
  113. private setupEventListeners() {
  114. const eventBus = EventBus.getInstance();
  115. // 监听重置方块管理器事件
  116. eventBus.on(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  117. }
  118. // 处理重置方块管理器事件
  119. private onResetBlockManagerEvent() {
  120. console.log('[BlockManager] 接收到重置方块管理器事件');
  121. this.onGameReset();
  122. }
  123. start() {
  124. // 获取配置管理器
  125. this.configManager = ConfigManager.getInstance();
  126. if (!this.configManager) {
  127. console.error('无法获取ConfigManager实例');
  128. }
  129. // 获取关卡配置管理器
  130. this.levelConfigManager = LevelConfigManager.getInstance();
  131. if (!this.levelConfigManager) {
  132. console.error('无法获取LevelConfigManager实例');
  133. }
  134. // 如果没有指定GridContainer,尝试找到它
  135. if (!this.gridContainer) {
  136. this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
  137. if (!this.gridContainer) {
  138. console.error('找不到GridContainer节点');
  139. return;
  140. }
  141. }
  142. // 如果没有指定kuangContainer,尝试找到它
  143. if (!this.kuangContainer) {
  144. this.kuangContainer = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
  145. if (!this.kuangContainer) {
  146. console.error('找不到kuang节点');
  147. return;
  148. }
  149. }
  150. // 如果没有指定coinLabelNode,尝试找到它
  151. if (!this.coinLabelNode) {
  152. this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
  153. if (!this.coinLabelNode) {
  154. console.error('找不到CoinLabel节点');
  155. return;
  156. }
  157. }
  158. // 如果没有指定placedBlocksContainer,尝试找到它
  159. if (!this.placedBlocksContainer) {
  160. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  161. }
  162. // 确保有PlacedBlocks节点用于存放已放置的方块
  163. this.ensurePlacedBlocksNode();
  164. // 获取数据管理器
  165. this.saveDataManager = SaveDataManager.getInstance();
  166. this.session = LevelSessionManager.inst;
  167. // 初始化玩家金币显示
  168. this.updateCoinDisplay();
  169. // 初始化网格信息
  170. this.initGridInfo();
  171. // 初始化网格占用情况
  172. this.initGridOccupationMap();
  173. // 设置事件监听器
  174. this.setupEventListeners();
  175. // 等待配置加载完成后生成方块
  176. this.scheduleOnce(() => {
  177. this.generateRandomBlocksInKuang();
  178. }, 0.5);
  179. }
  180. // 确保有PlacedBlocks节点
  181. ensurePlacedBlocksNode() {
  182. // 如果已经通过拖拽设置了节点,直接使用
  183. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  184. return;
  185. }
  186. // 尝试查找节点
  187. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  188. if (this.placedBlocksContainer) {
  189. return;
  190. }
  191. // 如果找不到,创建新节点
  192. const gameLevelUI = find('Canvas/GameLevelUI');
  193. if (!gameLevelUI) {
  194. console.error('找不到GameLevelUI节点,无法创建PlacedBlocks');
  195. return;
  196. }
  197. this.placedBlocksContainer = new Node('PlacedBlocks');
  198. gameLevelUI.addChild(this.placedBlocksContainer);
  199. if (!this.placedBlocksContainer.getComponent(UITransform)) {
  200. this.placedBlocksContainer.addComponent(UITransform);
  201. }
  202. console.log('已在GameLevelUI下创建PlacedBlocks节点');
  203. }
  204. // 初始化网格信息
  205. initGridInfo() {
  206. if (!this.gridContainer || this.gridInitialized) return;
  207. this.gridNodes = [];
  208. for (let row = 0; row < this.GRID_ROWS; row++) {
  209. this.gridNodes[row] = [];
  210. }
  211. for (let i = 0; i < this.gridContainer.children.length; i++) {
  212. const grid = this.gridContainer.children[i];
  213. if (grid.name.startsWith('Grid_')) {
  214. const parts = grid.name.split('_');
  215. if (parts.length === 3) {
  216. const row = parseInt(parts[1]);
  217. const col = parseInt(parts[2]);
  218. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  219. this.gridNodes[row][col] = grid;
  220. }
  221. }
  222. }
  223. }
  224. if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
  225. if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
  226. const pos1 = this.gridNodes[0][0].position;
  227. const pos2 = this.gridNodes[1][0].position;
  228. this.gridSpacing = Math.abs(pos2.y - pos1.y);
  229. }
  230. }
  231. this.gridInitialized = true;
  232. }
  233. // 初始化网格占用情况
  234. initGridOccupationMap() {
  235. this.gridOccupationMap = [];
  236. for (let row = 0; row < this.GRID_ROWS; row++) {
  237. const rowArray: number[] = [];
  238. for (let col = 0; col < this.GRID_COLS; col++) {
  239. rowArray.push(0);
  240. }
  241. this.gridOccupationMap.push(rowArray);
  242. }
  243. }
  244. // 在kuang下生成三个方块(基于关卡配置)
  245. private async generateRandomBlocksInKuang() {
  246. // 清除kuang区域中的旧方块,但不清除已放置在网格中的方块的标签
  247. this.clearBlocks();
  248. // 检查配置管理器是否可用
  249. if (!this.configManager || !this.configManager.isConfigLoaded()) {
  250. console.warn('配置管理器未初始化或配置未加载完成,延迟生成方块');
  251. this.scheduleOnce(() => {
  252. this.generateRandomBlocksInKuang();
  253. }, 1.0);
  254. return;
  255. }
  256. if (this.blockPrefabs.length === 0) {
  257. console.error('没有可用的预制体');
  258. return;
  259. }
  260. const kuangNode = this.kuangContainer;
  261. if (!kuangNode) {
  262. console.error('找不到kuang节点');
  263. return;
  264. }
  265. const offsets = [
  266. new Vec3(-200, 0, 0),
  267. new Vec3(0, 0, 0),
  268. new Vec3(200, 0, 0)
  269. ];
  270. const dbNodes = [
  271. kuangNode.getChildByName('db01'),
  272. kuangNode.getChildByName('db02'),
  273. kuangNode.getChildByName('db03')
  274. ];
  275. // 获取当前关卡的武器配置列表
  276. const levelWeapons = await this.getCurrentLevelWeapons();
  277. console.log('开始在kuang容器中生成武器方块,关卡武器配置:', levelWeapons);
  278. for (let i = 0; i < 3; i++) {
  279. let weaponConfig: WeaponConfig | null = null;
  280. // 如果关卡配置了武器列表,从中随机选择
  281. if (levelWeapons.length > 0) {
  282. const randomWeaponName = levelWeapons[Math.floor(Math.random() * levelWeapons.length)];
  283. weaponConfig = this.getWeaponConfigByName(randomWeaponName);
  284. if (!weaponConfig) {
  285. console.warn(`关卡配置的武器 "${randomWeaponName}" 在武器配置文件中未找到,使用随机武器`);
  286. weaponConfig = this.configManager.getRandomWeapon();
  287. }
  288. } else {
  289. // 如果关卡没有配置武器列表,使用随机武器
  290. console.warn('关卡未配置武器列表,使用随机武器');
  291. weaponConfig = this.configManager.getRandomWeapon();
  292. }
  293. if (!weaponConfig) {
  294. console.error(`无法获取第 ${i + 1} 个武器配置`);
  295. continue;
  296. }
  297. // 基于武器配置选择合适的预制体
  298. const prefab = this.selectPrefabForWeapon(weaponConfig);
  299. if (!prefab) {
  300. console.error(`无法为武器 ${weaponConfig.name} 选择合适的预制体`);
  301. continue;
  302. }
  303. const block = instantiate(prefab);
  304. kuangNode.addChild(block);
  305. block.position = offsets[i];
  306. // 设置方块名称
  307. block.name = `WeaponBlock_${weaponConfig.id}`;
  308. // 保存武器配置到方块
  309. this.blockWeaponConfigs.set(block, weaponConfig);
  310. block['weaponConfig'] = weaponConfig;
  311. block['weaponId'] = weaponConfig.id;
  312. this.originalPositions.set(block, offsets[i].clone());
  313. this.blockLocations.set(block, 'kuang');
  314. this.blocks.push(block);
  315. if (dbNodes[i]) {
  316. const priceNode = dbNodes[i].getChildByName('Price');
  317. if (priceNode) {
  318. this.blockPriceMap.set(block, priceNode);
  319. priceNode.active = true;
  320. // 根据武器稀有度设置价格
  321. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity);
  322. }
  323. this.associateDbNodeWithBlock(block, dbNodes[i]);
  324. }
  325. // 设置方块的武器外观
  326. this.setupBlockWeaponVisual(block, weaponConfig);
  327. this.setupDragEvents(block);
  328. // 为新生成的方块添加标签
  329. BlockTag.addTag(block);
  330. }
  331. this.updateCoinDisplay();
  332. }
  333. // 将db节点与方块关联
  334. associateDbNodeWithBlock(block: Node, dbNode: Node) {
  335. block['dbNode'] = dbNode;
  336. block.on(Node.EventType.TRANSFORM_CHANGED, () => {
  337. if (dbNode && block.parent) {
  338. const location = this.blockLocations.get(block);
  339. if (location === 'grid') {
  340. dbNode.active = false;
  341. return;
  342. }
  343. dbNode.active = true;
  344. const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position);
  345. const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  346. dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z);
  347. }
  348. });
  349. }
  350. // 更新金币显示
  351. updateCoinDisplay() {
  352. if (this.coinLabelNode) {
  353. const label = this.coinLabelNode.getComponent(Label);
  354. if (label) {
  355. const coins = this.session.getCoins();
  356. label.string = coins.toString();
  357. }
  358. }
  359. }
  360. // 获取方块价格
  361. getBlockPrice(block: Node): number {
  362. const priceNode = this.blockPriceMap.get(block);
  363. if (priceNode) {
  364. const label = priceNode.getComponent(Label);
  365. if (label) {
  366. const price = parseInt(label.string);
  367. if (!isNaN(price)) {
  368. return price;
  369. }
  370. }
  371. }
  372. return 50;
  373. }
  374. // 隐藏价格标签
  375. hidePriceLabel(block: Node) {
  376. const priceNode = this.blockPriceMap.get(block);
  377. if (priceNode) {
  378. priceNode.active = false;
  379. }
  380. }
  381. // 显示价格标签
  382. showPriceLabel(block: Node) {
  383. const priceNode = this.blockPriceMap.get(block);
  384. if (priceNode) {
  385. priceNode.active = true;
  386. }
  387. }
  388. // 扣除玩家金币
  389. deductPlayerCoins(amount: number): boolean {
  390. const success = this.session.spendCoins(amount);
  391. if (success) {
  392. this.updateCoinDisplay();
  393. }
  394. return success;
  395. }
  396. // 归还玩家金币
  397. refundPlayerCoins(amount: number) {
  398. this.session.addCoins(amount);
  399. this.updateCoinDisplay();
  400. }
  401. // 设置拖拽事件
  402. setupDragEvents(block: Node) {
  403. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  404. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  405. if (!this.canMoveBlock(block)) {
  406. return;
  407. }
  408. }
  409. this.currentDragBlock = block;
  410. this.startPos = event.getUILocation();
  411. this.blockStartPos.set(block.position);
  412. this.currentDragBlock['startLocation'] = this.blockLocations.get(block);
  413. block.setSiblingIndex(block.parent.children.length - 1);
  414. this.tempStoreBlockOccupiedGrids(block);
  415. // 拖拽开始时禁用碰撞体
  416. const collider = block.getComponent(Collider2D);
  417. if (collider) collider.enabled = false;
  418. }, this);
  419. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  420. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  421. if (!this.canMoveBlock(block)) {
  422. return;
  423. }
  424. }
  425. if (!this.currentDragBlock) return;
  426. const location = event.getUILocation();
  427. const deltaX = location.x - this.startPos.x;
  428. const deltaY = location.y - this.startPos.y;
  429. this.currentDragBlock.position = new Vec3(
  430. this.blockStartPos.x + deltaX,
  431. this.blockStartPos.y + deltaY,
  432. this.blockStartPos.z
  433. );
  434. }, this);
  435. block.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  436. if (this.gameStarted && this.blockLocations.get(block) === 'grid') {
  437. if (!this.canMoveBlock(block)) {
  438. return;
  439. }
  440. }
  441. if (this.currentDragBlock) {
  442. this.handleBlockDrop(event);
  443. this.currentDragBlock = null;
  444. // 拖拽结束时恢复碰撞体
  445. const collider = block.getComponent(Collider2D);
  446. if (collider) collider.enabled = true;
  447. }
  448. }, this);
  449. block.on(Node.EventType.TOUCH_CANCEL, () => {
  450. if (this.currentDragBlock) {
  451. this.returnBlockToOriginalPosition();
  452. this.currentDragBlock = null;
  453. // 拖拽取消时恢复碰撞体
  454. const collider = block.getComponent(Collider2D);
  455. if (collider) collider.enabled = true;
  456. }
  457. }, this);
  458. }
  459. // 处理方块放下
  460. handleBlockDrop(event: EventTouch) {
  461. const touchPos = event.getLocation();
  462. const startLocation = this.currentDragBlock['startLocation'];
  463. if (this.isInKuangArea(touchPos)) {
  464. // 检查是否有标签,只有有标签的方块才能放回kuang
  465. if (BlockTag.hasTag(this.currentDragBlock)) {
  466. this.returnBlockToKuang(startLocation);
  467. } else {
  468. // 没有标签的方块不能放回kuang,返回原位置
  469. console.log(`[BlockManager] 方块 ${this.currentDragBlock.name} 没有标签,不能放回kuang区域`);
  470. this.returnBlockToOriginalPosition();
  471. }
  472. } else if (this.tryPlaceBlockToGrid(this.currentDragBlock)) {
  473. this.handleSuccessfulPlacement(startLocation);
  474. } else {
  475. // 放置失败,尝试直接与重叠方块合成
  476. if (this.tryMergeOnOverlap(this.currentDragBlock)) {
  477. // 合成成功时,若来自 kuang 则扣费
  478. if (startLocation !== 'grid') {
  479. const price = this.getBlockPrice(this.currentDragBlock);
  480. this.deductPlayerCoins(price);
  481. }
  482. // 当前拖拽块已被销毁(合并时),无需复位
  483. } else {
  484. this.returnBlockToOriginalPosition();
  485. }
  486. }
  487. }
  488. // 返回方块到kuang区域
  489. returnBlockToKuang(startLocation: string) {
  490. const originalPos = this.originalPositions.get(this.currentDragBlock);
  491. if (originalPos) {
  492. const kuangNode = this.kuangContainer;
  493. if (kuangNode && this.currentDragBlock.parent !== kuangNode) {
  494. this.currentDragBlock.removeFromParent();
  495. kuangNode.addChild(this.currentDragBlock);
  496. }
  497. this.currentDragBlock.position = originalPos.clone();
  498. }
  499. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  500. this.blockLocations.set(this.currentDragBlock, 'kuang');
  501. this.showPriceLabel(this.currentDragBlock);
  502. if (startLocation === 'grid') {
  503. const price = this.getBlockPrice(this.currentDragBlock);
  504. this.refundPlayerCoins(price);
  505. this.currentDragBlock['placedBefore'] = false;
  506. }
  507. const dbNode = this.currentDragBlock['dbNode'];
  508. if (dbNode) {
  509. dbNode.active = true;
  510. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  511. }
  512. }
  513. // 处理成功放置
  514. handleSuccessfulPlacement(startLocation: string) {
  515. const price = this.getBlockPrice(this.currentDragBlock);
  516. if (startLocation === 'grid') {
  517. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  518. this.blockLocations.set(this.currentDragBlock, 'grid');
  519. this.hidePriceLabel(this.currentDragBlock);
  520. const dbNode = this.currentDragBlock['dbNode'];
  521. if (dbNode) {
  522. dbNode.active = false;
  523. }
  524. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  525. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  526. // 如果游戏已开始,添加锁定视觉提示
  527. if (this.gameStarted) {
  528. this.addLockedVisualHint(this.currentDragBlock);
  529. // 游戏开始后放置的方块移除标签,不能再放回kuang
  530. BlockTag.removeTag(this.currentDragBlock);
  531. }
  532. // 检查并执行合成
  533. this.tryMergeBlock(this.currentDragBlock);
  534. } else {
  535. if (this.deductPlayerCoins(price)) {
  536. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  537. this.blockLocations.set(this.currentDragBlock, 'grid');
  538. this.hidePriceLabel(this.currentDragBlock);
  539. const dbNode = this.currentDragBlock['dbNode'];
  540. if (dbNode) {
  541. dbNode.active = false;
  542. }
  543. this.currentDragBlock['placedBefore'] = true;
  544. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  545. this.moveBlockToPlacedBlocks(this.currentDragBlock);
  546. // 如果游戏已开始,添加锁定视觉提示
  547. if (this.gameStarted) {
  548. this.addLockedVisualHint(this.currentDragBlock);
  549. // 游戏开始后放置的方块移除标签,不能再放回kuang
  550. BlockTag.removeTag(this.currentDragBlock);
  551. }
  552. // 检查并执行合成
  553. this.tryMergeBlock(this.currentDragBlock);
  554. } else {
  555. this.returnBlockToOriginalPosition();
  556. }
  557. }
  558. }
  559. // 返回方块到原位置
  560. returnBlockToOriginalPosition() {
  561. const currentLocation = this.blockLocations.get(this.currentDragBlock);
  562. if (currentLocation === 'kuang') {
  563. const originalPos = this.originalPositions.get(this.currentDragBlock);
  564. if (originalPos) {
  565. this.currentDragBlock.position = originalPos.clone();
  566. }
  567. } else {
  568. this.currentDragBlock.position = this.blockStartPos.clone();
  569. }
  570. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  571. this.showPriceLabel(this.currentDragBlock);
  572. const dbNode = this.currentDragBlock['dbNode'];
  573. if (dbNode) {
  574. dbNode.active = true;
  575. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  576. }
  577. }
  578. // 检查是否在kuang区域内
  579. isInKuangArea(touchPos: Vec2): boolean {
  580. if (!this.kuangContainer) return false;
  581. const kuangTransform = this.kuangContainer.getComponent(UITransform);
  582. if (!kuangTransform) return false;
  583. const kuangBoundingBox = new Rect(
  584. this.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  585. this.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  586. kuangTransform.width,
  587. kuangTransform.height
  588. );
  589. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  590. }
  591. // 临时保存方块占用的网格
  592. tempStoreBlockOccupiedGrids(block: Node) {
  593. const occupiedGrids = block['occupiedGrids'];
  594. if (!occupiedGrids || occupiedGrids.length === 0) return;
  595. this.tempRemovedOccupiedGrids.push({
  596. block: block,
  597. occupiedGrids: [...occupiedGrids]
  598. });
  599. for (const grid of occupiedGrids) {
  600. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  601. grid.col >= 0 && grid.col < this.GRID_COLS) {
  602. this.gridOccupationMap[grid.row][grid.col] = 0;
  603. }
  604. }
  605. block['occupiedGrids'] = [];
  606. }
  607. // 恢复方块原来的占用状态
  608. restoreBlockOccupiedGrids(block: Node) {
  609. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  610. if (index === -1) return;
  611. const savedItem = this.tempRemovedOccupiedGrids[index];
  612. for (const grid of savedItem.occupiedGrids) {
  613. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  614. grid.col >= 0 && grid.col < this.GRID_COLS) {
  615. this.gridOccupationMap[grid.row][grid.col] = 1;
  616. }
  617. }
  618. block['occupiedGrids'] = [...savedItem.occupiedGrids];
  619. this.tempRemovedOccupiedGrids.splice(index, 1);
  620. }
  621. // 清除临时保存的占用状态
  622. clearTempStoredOccupiedGrids(block: Node) {
  623. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  624. if (index === -1) return;
  625. this.tempRemovedOccupiedGrids.splice(index, 1);
  626. }
  627. // 尝试将方块放置到网格中
  628. tryPlaceBlockToGrid(block: Node): boolean {
  629. if (!this.gridContainer || !this.gridInitialized) return false;
  630. let b1Node = block;
  631. if (block.name !== 'B1') {
  632. b1Node = block.getChildByName('B1');
  633. if (!b1Node) {
  634. return false;
  635. }
  636. }
  637. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  638. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  639. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  640. const halfWidth = gridSize.width / 2;
  641. const halfHeight = gridSize.height / 2;
  642. const tolerance = this.gridSpacing * 0.5;
  643. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  644. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  645. return false;
  646. }
  647. const nearestGrid = this.findNearestGridNode(gridPos);
  648. if (!nearestGrid) {
  649. return false;
  650. }
  651. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  652. }
  653. // 找到最近的网格节点
  654. findNearestGridNode(position: Vec3): Node {
  655. if (!this.gridContainer || !this.gridInitialized) return null;
  656. let nearestNode: Node = null;
  657. let minDistance = Number.MAX_VALUE;
  658. for (let row = 0; row < this.GRID_ROWS; row++) {
  659. for (let col = 0; col < this.GRID_COLS; col++) {
  660. const grid = this.gridNodes[row][col];
  661. if (grid) {
  662. const distance = Vec3.distance(position, grid.position);
  663. if (distance < minDistance) {
  664. minDistance = distance;
  665. nearestNode = grid;
  666. }
  667. }
  668. }
  669. }
  670. if (minDistance > this.gridSpacing * 2) {
  671. return null;
  672. }
  673. return nearestNode;
  674. }
  675. // 尝试将方块放置到指定的网格节点
  676. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  677. let b1Node = block;
  678. if (block.name !== 'B1') {
  679. b1Node = block.getChildByName('B1');
  680. if (!b1Node) {
  681. return false;
  682. }
  683. }
  684. if (!this.canPlaceBlockAt(block, targetGrid)) {
  685. return false;
  686. }
  687. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  688. const targetWorldPos = gridCenterWorldPos.clone();
  689. const b1LocalPos = b1Node.position.clone();
  690. let rootTargetWorldPos;
  691. if (b1Node === block) {
  692. rootTargetWorldPos = targetWorldPos.clone();
  693. } else {
  694. rootTargetWorldPos = new Vec3(
  695. targetWorldPos.x - b1LocalPos.x,
  696. targetWorldPos.y - b1LocalPos.y,
  697. targetWorldPos.z
  698. );
  699. }
  700. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  701. block.position = rootTargetLocalPos;
  702. this.markOccupiedPositions(block, targetGrid);
  703. return true;
  704. }
  705. // 检查方块是否可以放置在指定位置
  706. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  707. if (!this.gridInitialized) return false;
  708. const targetRowCol = this.getGridRowCol(targetGrid);
  709. if (!targetRowCol) return false;
  710. const parts = this.getBlockParts(block);
  711. for (const part of parts) {
  712. const row = targetRowCol.row - part.y;
  713. const col = targetRowCol.col + part.x;
  714. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  715. return false;
  716. }
  717. if (this.gridOccupationMap[row][col] === 1) {
  718. return false;
  719. }
  720. }
  721. return true;
  722. }
  723. // 获取网格行列索引
  724. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  725. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  726. const parts = gridNode.name.split('_');
  727. if (parts.length === 3) {
  728. const row = parseInt(parts[1]);
  729. const col = parseInt(parts[2]);
  730. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  731. return { row, col };
  732. }
  733. }
  734. return null;
  735. }
  736. // 获取方块的所有部分节点及其相对坐标
  737. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  738. const parts: { node: Node, x: number, y: number }[] = [];
  739. // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
  740. const b1Node = block.getChildByName('B1');
  741. if (b1Node) {
  742. // B1节点作为(0,0)位置
  743. parts.push({ node: b1Node, x: 0, y: 0 });
  744. this.findBlockParts(b1Node, parts, 0, 0);
  745. } else {
  746. // 没有B1节点,使用根节点
  747. parts.push({ node: block, x: 0, y: 0 });
  748. this.findBlockParts(block, parts, 0, 0);
  749. }
  750. return parts;
  751. }
  752. // 递归查找方块的所有部分
  753. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  754. for (let i = 0; i < node.children.length; i++) {
  755. const child = node.children[i];
  756. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  757. continue;
  758. }
  759. let x = parentX;
  760. let y = parentY;
  761. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  762. if (match) {
  763. x = parseInt(match[1]);
  764. y = parseInt(match[2]);
  765. result.push({ node: child, x, y });
  766. } else if (child.name.startsWith('B')) {
  767. const relativeX = Math.round(child.position.x / this.gridSpacing);
  768. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  769. x = parentX + relativeX;
  770. y = parentY + relativeY;
  771. result.push({ node: child, x, y });
  772. }
  773. this.findBlockParts(child, result, x, y);
  774. }
  775. }
  776. // 标记方块占用的格子
  777. markOccupiedPositions(block: Node, targetGrid: Node) {
  778. if (!this.gridInitialized) return;
  779. const targetRowCol = this.getGridRowCol(targetGrid);
  780. if (!targetRowCol) return;
  781. const parts = this.getBlockParts(block);
  782. block['occupiedGrids'] = [];
  783. for (const part of parts) {
  784. const row = targetRowCol.row - part.y;
  785. const col = targetRowCol.col + part.x;
  786. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  787. this.gridOccupationMap[row][col] = 1;
  788. block['occupiedGrids'] = block['occupiedGrids'] || [];
  789. block['occupiedGrids'].push({ row, col });
  790. }
  791. }
  792. }
  793. // 清除方块
  794. clearBlocks() {
  795. const blocksToRemove = [];
  796. for (const block of this.blocks) {
  797. if (block.isValid) {
  798. const location = this.blockLocations.get(block);
  799. if (location === 'kuang') {
  800. blocksToRemove.push(block);
  801. }
  802. }
  803. }
  804. for (const block of blocksToRemove) {
  805. const dbNode = block['dbNode'];
  806. if (dbNode && dbNode.isValid) {
  807. block.off(Node.EventType.TRANSFORM_CHANGED);
  808. const kuangNode = this.kuangContainer;
  809. if (kuangNode) {
  810. const dbName = dbNode.name;
  811. if (!kuangNode.getChildByName(dbName)) {
  812. dbNode.parent = kuangNode;
  813. }
  814. }
  815. }
  816. const index = this.blocks.indexOf(block);
  817. if (index !== -1) {
  818. this.blocks.splice(index, 1);
  819. }
  820. this.originalPositions.delete(block);
  821. this.blockLocations.delete(block);
  822. this.blockPriceMap.delete(block);
  823. // 清理武器配置映射
  824. this.blockWeaponConfigs.delete(block);
  825. block.destroy();
  826. }
  827. }
  828. // 游戏开始时调用
  829. onGameStart() {
  830. this.gameStarted = true;
  831. for (const block of this.blocks) {
  832. if (block.isValid) {
  833. const location = this.blockLocations.get(block);
  834. if (location === 'grid') {
  835. this.hidePriceLabel(block);
  836. const dbNode = block['dbNode'];
  837. if (dbNode) {
  838. dbNode.active = false;
  839. }
  840. this.moveBlockToPlacedBlocks(block);
  841. this.addLockedVisualHint(block);
  842. // 游戏开始后放置的方块移除标签,不能再放回kuang
  843. BlockTag.removeTag(block);
  844. }
  845. }
  846. }
  847. }
  848. // 游戏重置时调用
  849. onGameReset() {
  850. console.log('[BlockManager] 游戏重置,清理所有状态');
  851. this.gameStarted = false;
  852. this.clearAllCooldowns();
  853. // 清理已放置的方块
  854. this.clearPlacedBlocks();
  855. // 重置网格占用状态
  856. this.resetGridOccupation();
  857. // 清理kuang区域的方块
  858. this.clearBlocks();
  859. // 清理所有方块标签
  860. BlockTag.clearAllTags();
  861. // 重新生成方块
  862. this.generateRandomBlocksInKuang();
  863. console.log('[BlockManager] 游戏重置完成');
  864. }
  865. // 清理已放置的方块
  866. private clearPlacedBlocks() {
  867. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  868. return;
  869. }
  870. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  871. // 清理PlacedBlocks容器中的所有方块
  872. const placedBlocks = [...this.placedBlocksContainer.children];
  873. for (const block of placedBlocks) {
  874. if (block && block.isValid) {
  875. // 从blocks数组中移除
  876. const index = this.blocks.indexOf(block);
  877. if (index !== -1) {
  878. this.blocks.splice(index, 1);
  879. }
  880. // 清理相关映射
  881. this.originalPositions.delete(block);
  882. this.blockLocations.delete(block);
  883. this.blockPriceMap.delete(block);
  884. this.blockWeaponConfigs.delete(block);
  885. // 销毁方块
  886. block.destroy();
  887. }
  888. }
  889. }
  890. // 重置网格占用状态
  891. private resetGridOccupation() {
  892. console.log('[BlockManager] 重置网格占用状态');
  893. // 重新初始化网格占用地图
  894. this.gridOccupationMap = [];
  895. for (let row = 0; row < this.GRID_ROWS; row++) {
  896. this.gridOccupationMap[row] = [];
  897. for (let col = 0; col < this.GRID_COLS; col++) {
  898. this.gridOccupationMap[row][col] = 0;
  899. }
  900. }
  901. // 清理临时存储的占用状态
  902. this.tempRemovedOccupiedGrids = [];
  903. }
  904. // 添加视觉提示,表明方块已锁定
  905. addLockedVisualHint(block: Node) {
  906. const children = block.children;
  907. for (let i = 0; i < children.length; i++) {
  908. const child = children[i];
  909. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  910. continue;
  911. }
  912. child.setScale(new Vec3(0.95, 0.95, 1));
  913. }
  914. }
  915. // 将方块移动到PlacedBlocks节点下
  916. moveBlockToPlacedBlocks(block: Node) {
  917. if (!this.placedBlocksContainer) {
  918. console.error('PlacedBlocks容器未设置');
  919. return;
  920. }
  921. if (!this.placedBlocksContainer.isValid) {
  922. console.error('PlacedBlocks容器已失效');
  923. return;
  924. }
  925. const worldPosition = new Vec3();
  926. block.getWorldPosition(worldPosition);
  927. // 移除旧的触摸事件监听器
  928. block.off(Node.EventType.TOUCH_START);
  929. block.off(Node.EventType.TOUCH_MOVE);
  930. block.off(Node.EventType.TOUCH_END);
  931. block.off(Node.EventType.TOUCH_CANCEL);
  932. block.removeFromParent();
  933. this.placedBlocksContainer.addChild(block);
  934. block.setWorldPosition(worldPosition);
  935. // 重新设置触摸事件监听器
  936. this.setupDragEvents(block);
  937. }
  938. // 根据武器配置选择合适的预制体
  939. private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null {
  940. if (this.blockPrefabs.length === 0) {
  941. return null;
  942. }
  943. // 获取所有可用的方块形状配置
  944. const blockShapes = this.configManager.getBlockShapes();
  945. if (!blockShapes || blockShapes.length === 0) {
  946. console.warn('没有可用的方块形状配置,使用随机预制体');
  947. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  948. return this.blockPrefabs[randomIndex];
  949. }
  950. // 随机选择一个方块形状
  951. const randomShapeIndex = Math.floor(Math.random() * blockShapes.length);
  952. const targetShape = blockShapes[randomShapeIndex];
  953. // 寻找与目标形状匹配的预制体
  954. const matchingPrefab = this.findMatchingPrefab(targetShape);
  955. if (matchingPrefab) {
  956. console.log(`为武器 ${weaponConfig.name} 选择了匹配的预制体,形状: ${targetShape.name}`);
  957. return matchingPrefab;
  958. }
  959. // 如果没有找到匹配的预制体,使用随机预制体
  960. console.warn(`没有找到匹配形状 ${targetShape.name} 的预制体,使用随机预制体`);
  961. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  962. return this.blockPrefabs[randomIndex];
  963. }
  964. // 根据稀有度设置方块价格
  965. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  966. const label = priceNode.getComponent(Label);
  967. if (!label) {
  968. return;
  969. }
  970. let basePrice: number;
  971. switch (rarity) {
  972. case 'common':
  973. basePrice = 10;
  974. break;
  975. case 'uncommon':
  976. basePrice = 20;
  977. break;
  978. case 'rare':
  979. basePrice = 50;
  980. break;
  981. case 'epic':
  982. basePrice = 100;
  983. break;
  984. case 'legendary':
  985. basePrice = 150;
  986. break;
  987. default:
  988. basePrice = 200;
  989. }
  990. // 应用便宜技能效果
  991. const skillManager = SkillManager.getInstance();
  992. let finalPrice = basePrice;
  993. if (skillManager) {
  994. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  995. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  996. }
  997. label.string = finalPrice.toString();
  998. }
  999. // 设置方块的武器外观
  1000. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  1001. // 设置方块的稀有度颜色
  1002. this.setBlockRarityColor(block, weaponConfig.rarity);
  1003. // 加载武器图标
  1004. this.loadWeaponIcon(block, weaponConfig);
  1005. }
  1006. // 设置方块稀有度颜色
  1007. private setBlockRarityColor(block: Node, rarity: string) {
  1008. // Add null safety check for block
  1009. if (!block || !block.isValid) {
  1010. return;
  1011. }
  1012. const sprite = block.getComponent(Sprite);
  1013. if (!sprite || !sprite.isValid) {
  1014. return;
  1015. }
  1016. // 根据稀有度设置颜色
  1017. let color: Color;
  1018. switch (rarity) {
  1019. case 'common':
  1020. color = new Color(255, 255, 255); // 白色
  1021. break;
  1022. case 'uncommon':
  1023. color = new Color(0, 255, 0); // 绿色
  1024. break;
  1025. case 'rare':
  1026. color = new Color(0, 100, 255); // 蓝色
  1027. break;
  1028. case 'epic':
  1029. color = new Color(160, 32, 240); // 紫色
  1030. break;
  1031. case 'legendary':
  1032. color = new Color(255, 165, 0); // 橙色
  1033. break;
  1034. default:
  1035. color = new Color(255, 255, 255); // 默认白色
  1036. }
  1037. sprite.color = color;
  1038. }
  1039. // 加载武器图标
  1040. private loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  1041. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  1042. const b1Node = block.getChildByName('B1');
  1043. if (!b1Node) {
  1044. console.warn('找不到B1节点');
  1045. return;
  1046. }
  1047. const weaponNode = b1Node.getChildByName('Weapon');
  1048. if (!weaponNode) {
  1049. console.warn('找不到Weapon节点');
  1050. return;
  1051. }
  1052. const weaponSprite = weaponNode.getComponent(Sprite);
  1053. if (!weaponSprite) {
  1054. console.warn('Weapon节点上没有Sprite组件');
  1055. return;
  1056. }
  1057. // 获取武器配置中的图片路径
  1058. const spriteConfig = weaponConfig.visualConfig?.weaponSprites;
  1059. if (!spriteConfig) {
  1060. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  1061. return;
  1062. }
  1063. // 选择合适的图片路径(这里默认使用1x1)
  1064. const spritePath = spriteConfig['1x1'] || spriteConfig['1x2'] || spriteConfig['2x1'] || spriteConfig['2x2'];
  1065. if (!spritePath) {
  1066. console.warn(`武器 ${weaponConfig.name} 没有可用的图片路径`);
  1067. return;
  1068. }
  1069. // 正确的SpriteFrame子资源路径
  1070. const spriteFramePath = `${spritePath}/spriteFrame`;
  1071. // 加载SpriteFrame子资源
  1072. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  1073. if (err) {
  1074. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  1075. return;
  1076. }
  1077. // Add comprehensive null safety checks before setting spriteFrame
  1078. if (weaponSprite && weaponSprite.isValid &&
  1079. weaponNode && weaponNode.isValid &&
  1080. block && block.isValid &&
  1081. spriteFrame && spriteFrame.isValid) {
  1082. weaponSprite.spriteFrame = spriteFrame;
  1083. }
  1084. });
  1085. }
  1086. // 根据方块获取武器配置
  1087. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  1088. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  1089. }
  1090. // 获取方块的武器ID
  1091. public getBlockWeaponId(block: Node): string | null {
  1092. const weaponConfig = this.getBlockWeaponConfig(block);
  1093. return weaponConfig ? weaponConfig.id : null;
  1094. }
  1095. // 获取方块的形状
  1096. public getBlockShape(block: Node): string | null {
  1097. const weaponConfig = this.getBlockWeaponConfig(block);
  1098. if (!weaponConfig) return null;
  1099. // 从方块结构推断形状
  1100. return this.inferBlockShapeFromStructure(block);
  1101. }
  1102. // 获取方块的详细形状信息(包括形状ID和名称)
  1103. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  1104. const actualShape = this.extractShapeFromBlock(block);
  1105. const blockShapes = this.configManager.getBlockShapes();
  1106. if (!blockShapes) return null;
  1107. // 寻找匹配的形状配置
  1108. for (const shapeConfig of blockShapes) {
  1109. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1110. return {
  1111. id: shapeConfig.id,
  1112. name: shapeConfig.name,
  1113. shape: shapeConfig.shape
  1114. };
  1115. }
  1116. }
  1117. return null;
  1118. }
  1119. // 从方块结构推断形状
  1120. private inferBlockShapeFromStructure(block: Node): string {
  1121. const parts = this.getBlockParts(block);
  1122. if (parts.length === 0) return '1x1';
  1123. // 计算方块的边界
  1124. let minX = 0, maxX = 0, minY = 0, maxY = 0;
  1125. for (const part of parts) {
  1126. minX = Math.min(minX, part.x);
  1127. maxX = Math.max(maxX, part.x);
  1128. minY = Math.min(minY, part.y);
  1129. maxY = Math.max(maxY, part.y);
  1130. }
  1131. const width = maxX - minX + 1;
  1132. const height = maxY - minY + 1;
  1133. return `${width}x${height}`;
  1134. }
  1135. // 寻找与目标形状匹配的预制体
  1136. private findMatchingPrefab(targetShape: any): Prefab | null {
  1137. for (const prefab of this.blockPrefabs) {
  1138. if (this.doesPrefabMatchShape(prefab, targetShape)) {
  1139. return prefab;
  1140. }
  1141. }
  1142. return null;
  1143. }
  1144. // 检查预制体是否匹配指定形状
  1145. private doesPrefabMatchShape(prefab: Prefab, targetShape: any): boolean {
  1146. // 创建临时实例来检查形状
  1147. const tempBlock = instantiate(prefab);
  1148. const parts = this.getBlockParts(tempBlock);
  1149. console.log(`${prefab.name} 的部件坐标:`, parts.map(p => `(${p.x},${p.y})`));
  1150. const actualShape = this.extractShapeFromBlock(tempBlock);
  1151. tempBlock.destroy();
  1152. // 添加调试日志
  1153. console.log(`检查预制体 ${prefab.name} 是否匹配形状 ${targetShape.name}`);
  1154. console.log('预制体实际形状:', actualShape);
  1155. console.log('目标形状:', targetShape.shape);
  1156. // 比较形状矩阵
  1157. const matches = this.compareShapeMatrices(actualShape, targetShape.shape);
  1158. console.log('匹配结果:', matches);
  1159. return matches;
  1160. }
  1161. // 从方块实例中提取形状矩阵
  1162. private extractShapeFromBlock(block: Node): number[][] {
  1163. const parts = this.getBlockParts(block);
  1164. // 创建4x4矩阵
  1165. const matrix: number[][] = [];
  1166. for (let i = 0; i < 4; i++) {
  1167. matrix[i] = [0, 0, 0, 0];
  1168. }
  1169. // 找到最小坐标作为偏移基准
  1170. let minX = 0, minY = 0;
  1171. for (const part of parts) {
  1172. minX = Math.min(minX, part.x);
  1173. minY = Math.min(minY, part.y);
  1174. }
  1175. // 填充矩阵,将坐标标准化到从(0,0)开始
  1176. for (const part of parts) {
  1177. const matrixX = part.x - minX;
  1178. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  1179. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  1180. matrix[matrixY][matrixX] = 1;
  1181. }
  1182. }
  1183. // 对矩阵进行上下翻转(交换第0行和第1行)
  1184. const temp = matrix[0];
  1185. matrix[0] = matrix[1];
  1186. matrix[1] = temp;
  1187. return matrix;
  1188. }
  1189. // 比较两个形状矩阵是否相同
  1190. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  1191. if (matrix1.length !== matrix2.length) return false;
  1192. for (let i = 0; i < matrix1.length; i++) {
  1193. if (matrix1[i].length !== matrix2[i].length) return false;
  1194. for (let j = 0; j < matrix1[i].length; j++) {
  1195. if (matrix1[i][j] !== matrix2[i][j]) return false;
  1196. }
  1197. }
  1198. return true;
  1199. }
  1200. // 检查两个方块是否可以合成(相同形状相同种类)
  1201. private canMergeBlocks(block1: Node, block2: Node): boolean {
  1202. // 检查稀有度
  1203. const rarity1 = this.getBlockRarity(block1);
  1204. const rarity2 = this.getBlockRarity(block2);
  1205. if (rarity1 !== rarity2) {
  1206. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  1207. return false;
  1208. }
  1209. // 检查武器ID(种类)
  1210. const weaponId1 = this.getBlockWeaponId(block1);
  1211. const weaponId2 = this.getBlockWeaponId(block2);
  1212. if (weaponId1 !== weaponId2) {
  1213. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  1214. return false;
  1215. }
  1216. // 使用精确的形状矩阵比较
  1217. const shape1 = this.extractShapeFromBlock(block1);
  1218. const shape2 = this.extractShapeFromBlock(block2);
  1219. if (!this.compareShapeMatrices(shape1, shape2)) {
  1220. console.log(`[BlockManager] 形状矩阵不匹配`);
  1221. return false;
  1222. }
  1223. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  1224. return true;
  1225. }
  1226. // 刷新方块 - 重新生成三个新的武器方块
  1227. public refreshBlocks() {
  1228. // 移除PlacedBlocks容器中所有方块的标签
  1229. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1230. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1231. }
  1232. // 生成新的方块
  1233. this.generateRandomBlocksInKuang();
  1234. }
  1235. // 检查是否有已放置的方块
  1236. public hasPlacedBlocks(): boolean {
  1237. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1238. console.log('[BlockManager] PlacedBlocks容器无效');
  1239. return false;
  1240. }
  1241. const blockCount = this.placedBlocksContainer.children.length;
  1242. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1243. // 检查容器中是否有子节点(方块)
  1244. return blockCount > 0;
  1245. }
  1246. /* =================== 合成逻辑 =================== */
  1247. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  1248. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1249. private tryMergeBlock(block: Node) {
  1250. const rarity = this.getBlockRarity(block);
  1251. if (!rarity) return;
  1252. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1253. if (!this.placedBlocksContainer) return;
  1254. const blockBB = this.getWorldAABB(block);
  1255. for (const other of this.placedBlocksContainer.children) {
  1256. if (other === block) continue;
  1257. // 使用新的合成检查方法
  1258. if (!this.canMergeBlocks(block, other)) continue;
  1259. const otherBB = this.getWorldAABB(other);
  1260. if (this.rectIntersects(blockBB, otherBB)) {
  1261. // 找到合成目标
  1262. this.performMerge(block, other, rarity);
  1263. break;
  1264. }
  1265. }
  1266. }
  1267. private performMerge(target: Node, source: Node, rarity: string) {
  1268. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1269. // 隐藏价格标签并处理 db 关联
  1270. this.hidePriceLabel(source);
  1271. const srcDb = source['dbNode'];
  1272. if (srcDb) srcDb.active = false;
  1273. // 销毁被合并方块
  1274. source.destroy();
  1275. // 升级稀有度
  1276. const nextRarity = this.getNextRarity(rarity);
  1277. if (nextRarity) {
  1278. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1279. this.setBlockRarityColor(target, nextRarity);
  1280. // 如果有武器配置,也升级
  1281. const cfg = this.blockWeaponConfigs.get(target);
  1282. if (cfg) {
  1283. cfg.rarity = nextRarity;
  1284. this.blockWeaponConfigs.set(target, cfg);
  1285. }
  1286. }
  1287. // 播放烟雾动画
  1288. const worldPos = new Vec3();
  1289. target.getWorldPosition(worldPos);
  1290. this.spawnMergeSmoke(worldPos);
  1291. // 递归检查是否还能继续合成
  1292. if (nextRarity) {
  1293. this.tryMergeBlock(target);
  1294. }
  1295. }
  1296. private getBlockRarity(block: Node): string | null {
  1297. const cfg = this.blockWeaponConfigs.get(block);
  1298. if (cfg) return cfg.rarity;
  1299. // fallback based on sprite color maybe
  1300. return null;
  1301. }
  1302. private getNextRarity(rarity: string): string | null {
  1303. const idx = this.rarityOrder.indexOf(rarity);
  1304. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1305. return this.rarityOrder[idx + 1];
  1306. }
  1307. private getWorldAABB(node: Node): Rect {
  1308. const ui = node.getComponent(UITransform);
  1309. if (!ui) return new Rect();
  1310. const pos = node.worldPosition;
  1311. const width = ui.width;
  1312. const height = ui.height;
  1313. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1314. }
  1315. private rectIntersects(a: Rect, b: Rect): boolean {
  1316. return a.x < b.x + b.width &&
  1317. a.x + a.width > b.x &&
  1318. a.y < b.y + b.height &&
  1319. a.y + a.height > b.y;
  1320. }
  1321. /** 生成烟雾特效 */
  1322. private spawnMergeSmoke(worldPos: Vec3) {
  1323. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1324. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1325. if (err || !sData) {
  1326. console.warn('加载合成烟雾动画失败', err);
  1327. return;
  1328. }
  1329. const node = new Node('MergeSmoke');
  1330. const skeleton = node.addComponent(sp.Skeleton);
  1331. skeleton.skeletonData = sData;
  1332. skeleton.premultipliedAlpha = false;
  1333. skeleton.setAnimation(0, 'animation', false);
  1334. skeleton.setCompleteListener(() => node.destroy());
  1335. const canvas = find('Canvas');
  1336. if (canvas) canvas.addChild(node);
  1337. node.setWorldPosition(worldPos);
  1338. });
  1339. }
  1340. /** 在放置失败时尝试与现有方块进行合成 */
  1341. private tryMergeOnOverlap(draggedBlock: Node): boolean {
  1342. if (!this.placedBlocksContainer) return false;
  1343. const rarity = this.getBlockRarity(draggedBlock);
  1344. if (!rarity) return false;
  1345. const dragBB = this.getWorldAABB(draggedBlock);
  1346. for (const target of this.placedBlocksContainer.children) {
  1347. if (target === draggedBlock) continue;
  1348. // 使用新的合成检查方法
  1349. if (!this.canMergeBlocks(draggedBlock, target)) continue;
  1350. const targetBB = this.getWorldAABB(target);
  1351. if (this.rectIntersects(dragBB, targetBB)) {
  1352. // 执行合并:目标保留,拖拽方块销毁
  1353. this.performMerge(target, draggedBlock, rarity);
  1354. return true;
  1355. }
  1356. }
  1357. return false;
  1358. }
  1359. onDestroy() {
  1360. // 清理事件监听
  1361. const eventBus = EventBus.getInstance();
  1362. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  1363. }
  1364. }