BlockManager.ts 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Color, Vec2, UITransform, find, Rect, Label, Size, Sprite, SpriteFrame, resources, Button, Collider2D, Material } 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 gridOccupationMap: number[][] = [];
  52. // 网格行数和列数
  53. private readonly GRID_ROWS = 6;
  54. private readonly GRID_COLS = 11;
  55. // 是否已初始化网格信息
  56. private gridInitialized = false;
  57. // 存储网格节点信息
  58. private gridNodes: Node[][] = [];
  59. // 网格间距
  60. private gridSpacing = 54;
  61. // 不参与占用的节点名称列表
  62. private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
  63. // 临时保存方块的原始占用格子
  64. private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  65. // 方块原始位置(在kuang中的位置)
  66. public originalPositions: Map<Node, Vec3> = new Map();
  67. // 方块当前所在的区域
  68. public blockLocations: Map<Node, string> = new Map();
  69. // 配置管理器
  70. private configManager: ConfigManager = null;
  71. // 关卡配置管理器
  72. private levelConfigManager: LevelConfigManager = null;
  73. // 方块武器配置映射
  74. private blockWeaponConfigs: Map<Node, WeaponConfig> = new Map();
  75. // 调试绘制相关
  76. // 调试绘制功能已迁移到GameBlockSelection
  77. /** 冷却机制已废弃,方块随时可移动 */
  78. // 清除所有冷却(游戏重置时调用)
  79. public clearAllCooldowns() { /* no-op */ }
  80. // 获取当前关卡的武器配置列表
  81. private async getCurrentLevelWeapons(): Promise<string[]> {
  82. if (!this.levelConfigManager || !this.saveDataManager) {
  83. console.warn('关卡配置管理器或存档管理器未初始化,使用默认武器列表');
  84. return [];
  85. }
  86. try {
  87. const currentLevel = this.saveDataManager.getCurrentLevel();
  88. const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
  89. if (levelConfig && levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
  90. console.log(`关卡 ${currentLevel} 配置的武器:`, levelConfig.weapons);
  91. return levelConfig.weapons;
  92. } else {
  93. console.warn(`关卡 ${currentLevel} 没有配置武器列表`);
  94. return [];
  95. }
  96. } catch (error) {
  97. console.error('获取当前关卡武器配置失败:', error);
  98. return [];
  99. }
  100. }
  101. // 根据武器名称获取武器配置
  102. private getWeaponConfigByName(weaponName: string): WeaponConfig | null {
  103. if (!this.configManager) return null;
  104. const allWeapons = this.configManager.getAllWeapons();
  105. return allWeapons.find(weapon => weapon.name === weaponName) || null;
  106. }
  107. // 设置事件监听器
  108. private setupEventListeners() {
  109. const eventBus = EventBus.getInstance();
  110. // 监听重置方块管理器事件
  111. eventBus.on(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  112. // 监听方块生成事件
  113. eventBus.on(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  114. // 移除GAME_START事件监听,避免与GameBlockSelection重复生成方块
  115. // eventBus.on(GameEvents.GAME_START, this.onGameStartEvent, this);
  116. // 监听波次完成事件(每波结束后生成新方块)
  117. eventBus.on(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  118. }
  119. // 处理重置方块管理器事件
  120. private onResetBlockManagerEvent() {
  121. console.log('[BlockManager] 接收到重置方块管理器事件');
  122. this.onGameReset();
  123. }
  124. // 处理方块生成事件
  125. private onGenerateBlocksEvent() {
  126. console.log('[BlockManager] 接收到方块生成事件');
  127. this.generateRandomBlocksInKuang();
  128. }
  129. // 处理游戏开始事件 - 已废弃,避免与GameBlockSelection重复生成方块
  130. // private onGameStartEvent() {
  131. // console.log('[BlockManager] 接收到游戏开始事件,生成初始方块');
  132. // this.generateRandomBlocksInKuang();
  133. // }
  134. // 处理波次完成事件
  135. private onWaveCompletedEvent() {
  136. console.log('[BlockManager] 接收到波次完成事件,生成新方块');
  137. this.generateRandomBlocksInKuang();
  138. }
  139. start() {
  140. // 获取配置管理器
  141. this.configManager = ConfigManager.getInstance();
  142. if (!this.configManager) {
  143. console.error('无法获取ConfigManager实例');
  144. }
  145. // 获取关卡配置管理器
  146. this.levelConfigManager = LevelConfigManager.getInstance();
  147. if (!this.levelConfigManager) {
  148. console.error('无法获取LevelConfigManager实例');
  149. }
  150. // 如果没有指定GridContainer,尝试找到它
  151. if (!this.gridContainer) {
  152. this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
  153. if (!this.gridContainer) {
  154. console.error('找不到GridContainer节点');
  155. return;
  156. }
  157. }
  158. // 如果没有指定kuangContainer,尝试找到它
  159. if (!this.kuangContainer) {
  160. this.kuangContainer = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
  161. if (!this.kuangContainer) {
  162. console.error('找不到kuang节点');
  163. return;
  164. }
  165. }
  166. // 如果没有指定coinLabelNode,尝试找到它
  167. if (!this.coinLabelNode) {
  168. this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
  169. if (!this.coinLabelNode) {
  170. console.error('找不到CoinLabel节点');
  171. return;
  172. }
  173. }
  174. // 如果没有指定placedBlocksContainer,尝试找到它
  175. if (!this.placedBlocksContainer) {
  176. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  177. }
  178. // 确保有PlacedBlocks节点用于存放已放置的方块
  179. this.ensurePlacedBlocksNode();
  180. // 获取数据管理器
  181. this.saveDataManager = SaveDataManager.getInstance();
  182. this.session = LevelSessionManager.inst;
  183. // 初始化玩家金币显示
  184. this.updateCoinDisplay();
  185. // 初始化网格信息
  186. this.initGridInfo();
  187. // 初始化网格占用情况
  188. this.initGridOccupationMap();
  189. // 设置事件监听器
  190. this.setupEventListeners();
  191. // 调试绘制功能已迁移到GameBlockSelection
  192. // 移除自动生成方块逻辑,改为事件触发
  193. // 方块生成现在通过以下事件触发:
  194. // - GAME_START: 游戏开始时
  195. // - WAVE_COMPLETED: 每波敌人消灭后
  196. // - GENERATE_BLOCKS: 手动触发生成
  197. }
  198. // 确保有PlacedBlocks节点
  199. ensurePlacedBlocksNode() {
  200. // 如果已经通过拖拽设置了节点,直接使用
  201. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  202. return;
  203. }
  204. // 尝试查找节点
  205. this.placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  206. if (this.placedBlocksContainer) {
  207. return;
  208. }
  209. // 如果找不到,创建新节点
  210. const gameLevelUI = find('Canvas/GameLevelUI');
  211. if (!gameLevelUI) {
  212. console.error('找不到GameLevelUI节点,无法创建PlacedBlocks');
  213. return;
  214. }
  215. this.placedBlocksContainer = new Node('PlacedBlocks');
  216. gameLevelUI.addChild(this.placedBlocksContainer);
  217. if (!this.placedBlocksContainer.getComponent(UITransform)) {
  218. this.placedBlocksContainer.addComponent(UITransform);
  219. }
  220. console.log('已在GameLevelUI下创建PlacedBlocks节点');
  221. }
  222. // 初始化网格信息
  223. initGridInfo() {
  224. if (!this.gridContainer || this.gridInitialized) return;
  225. this.gridNodes = [];
  226. for (let row = 0; row < this.GRID_ROWS; row++) {
  227. this.gridNodes[row] = [];
  228. }
  229. for (let i = 0; i < this.gridContainer.children.length; i++) {
  230. const grid = this.gridContainer.children[i];
  231. if (grid.name.startsWith('Grid_')) {
  232. const parts = grid.name.split('_');
  233. if (parts.length === 3) {
  234. const row = parseInt(parts[1]);
  235. const col = parseInt(parts[2]);
  236. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  237. this.gridNodes[row][col] = grid;
  238. }
  239. }
  240. }
  241. }
  242. if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
  243. if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
  244. const pos1 = this.gridNodes[0][0].position;
  245. const pos2 = this.gridNodes[1][0].position;
  246. this.gridSpacing = Math.abs(pos2.y - pos1.y);
  247. }
  248. }
  249. this.gridInitialized = true;
  250. }
  251. // 初始化网格占用情况
  252. initGridOccupationMap() {
  253. this.gridOccupationMap = [];
  254. for (let row = 0; row < this.GRID_ROWS; row++) {
  255. const rowArray: number[] = [];
  256. for (let col = 0; col < this.GRID_COLS; col++) {
  257. rowArray.push(0);
  258. }
  259. this.gridOccupationMap.push(rowArray);
  260. }
  261. }
  262. // 在kuang下生成三个方块(基于关卡配置)
  263. private async generateRandomBlocksInKuang() {
  264. // 清除kuang区域中的旧方块,但不清除已放置在网格中的方块的标签
  265. this.clearBlocks();
  266. // 检查配置管理器是否可用
  267. if (!this.configManager || !this.configManager.isConfigLoaded()) {
  268. console.warn('配置管理器未初始化或配置未加载完成,延迟生成方块');
  269. this.scheduleOnce(() => {
  270. this.generateRandomBlocksInKuang();
  271. }, 1.0);
  272. return;
  273. }
  274. if (this.blockPrefabs.length === 0) {
  275. console.error('没有可用的预制体');
  276. return;
  277. }
  278. const kuangNode = this.kuangContainer;
  279. if (!kuangNode) {
  280. console.error('找不到kuang节点');
  281. return;
  282. }
  283. const offsets = [
  284. new Vec3(-200, 0, 0),
  285. new Vec3(0, 0, 0),
  286. new Vec3(200, 0, 0)
  287. ];
  288. const dbNodes = [
  289. kuangNode.getChildByName('db01'),
  290. kuangNode.getChildByName('db02'),
  291. kuangNode.getChildByName('db03')
  292. ];
  293. // 获取当前关卡的武器配置列表
  294. const levelWeapons = await this.getCurrentLevelWeapons();
  295. for (let i = 0; i < 3; i++) {
  296. let weaponConfig: WeaponConfig | null = null;
  297. // 优先使用关卡配置的武器,确保符合关卡设计
  298. if (levelWeapons.length > 0) {
  299. const randomWeaponName = levelWeapons[Math.floor(Math.random() * levelWeapons.length)];
  300. weaponConfig = this.getWeaponConfigByName(randomWeaponName);
  301. if (!weaponConfig) {
  302. console.warn(`关卡配置的武器 "${randomWeaponName}" 在武器配置文件中未找到`);
  303. }
  304. }
  305. // 如果关卡没有配置武器或获取失败,使用随机武器
  306. if (!weaponConfig) {
  307. weaponConfig = this.configManager.getRandomWeapon();
  308. }
  309. // 最后的兜底处理
  310. if (!weaponConfig) {
  311. console.warn('无法获取武器配置,使用默认武器');
  312. // 尝试获取一个基础武器作为兜底
  313. const allWeapons = this.configManager.getAllWeapons();
  314. if (allWeapons.length > 0) {
  315. weaponConfig = allWeapons[0];
  316. }
  317. }
  318. if (!weaponConfig) {
  319. console.error(`无法获取第 ${i + 1} 个武器配置`);
  320. continue;
  321. }
  322. // 基于武器配置选择合适的预制体
  323. const prefab = this.selectPrefabForWeapon(weaponConfig);
  324. if (!prefab) {
  325. console.error(`无法为武器 ${weaponConfig.name} 选择合适的预制体`);
  326. continue;
  327. }
  328. const block = instantiate(prefab);
  329. kuangNode.addChild(block);
  330. block.position = offsets[i];
  331. // 设置方块名称
  332. block.name = `WeaponBlock_${weaponConfig.id}`;
  333. // 保存武器配置到方块
  334. this.blockWeaponConfigs.set(block, weaponConfig);
  335. block['weaponConfig'] = weaponConfig;
  336. block['weaponId'] = weaponConfig.id;
  337. this.originalPositions.set(block, offsets[i].clone());
  338. this.blockLocations.set(block, 'kuang');
  339. this.blocks.push(block);
  340. if (dbNodes[i]) {
  341. const priceNode = dbNodes[i].getChildByName('Price');
  342. if (priceNode) {
  343. this.blockPriceMap.set(block, priceNode);
  344. priceNode.active = true;
  345. // 根据武器稀有度设置价格
  346. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity);
  347. }
  348. this.associateDbNodeWithBlock(block, dbNodes[i]);
  349. }
  350. // 设置方块的武器外观
  351. this.setupBlockWeaponVisual(block, weaponConfig);
  352. // 为新生成的方块添加标签
  353. BlockTag.addTag(block);
  354. console.log(`[BlockManager] 为方块 ${block.name} 添加标签,UUID: ${block.uuid}`);
  355. }
  356. // 通过事件机制通知GameBlockSelection为新生成的方块设置拖拽事件
  357. if (this.blocks.length > 0) {
  358. const eventBus = EventBus.getInstance();
  359. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.blocks.slice());
  360. console.log(`[BlockManager] 发送方块拖拽事件设置请求,方块数量: ${this.blocks.length}`);
  361. }
  362. this.updateCoinDisplay();
  363. }
  364. // 将db节点与方块关联
  365. associateDbNodeWithBlock(block: Node, dbNode: Node) {
  366. block['dbNode'] = dbNode;
  367. block.on(Node.EventType.TRANSFORM_CHANGED, () => {
  368. if (dbNode && block.parent) {
  369. const location = this.blockLocations.get(block);
  370. if (location === 'grid') {
  371. dbNode.active = false;
  372. return;
  373. }
  374. dbNode.active = true;
  375. const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position);
  376. const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
  377. dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z);
  378. }
  379. });
  380. }
  381. // 更新金币显示
  382. updateCoinDisplay() {
  383. if (this.coinLabelNode) {
  384. const label = this.coinLabelNode.getComponent(Label);
  385. if (label) {
  386. const coins = this.session.getCoins();
  387. label.string = coins.toString();
  388. }
  389. }
  390. }
  391. // 获取方块价格
  392. getBlockPrice(block: Node): number {
  393. const priceNode = this.blockPriceMap.get(block);
  394. if (priceNode) {
  395. const label = priceNode.getComponent(Label);
  396. if (label) {
  397. const price = parseInt(label.string);
  398. if (!isNaN(price)) {
  399. return price;
  400. }
  401. }
  402. }
  403. return 50;
  404. }
  405. // 隐藏价格标签
  406. hidePriceLabel(block: Node) {
  407. const priceNode = this.blockPriceMap.get(block);
  408. if (priceNode) {
  409. priceNode.active = false;
  410. }
  411. }
  412. // 显示价格标签
  413. showPriceLabel(block: Node) {
  414. const priceNode = this.blockPriceMap.get(block);
  415. if (priceNode) {
  416. priceNode.active = true;
  417. }
  418. }
  419. // 扣除玩家金币
  420. deductPlayerCoins(amount: number): boolean {
  421. const success = this.session.spendCoins(amount);
  422. if (success) {
  423. this.updateCoinDisplay();
  424. }
  425. return success;
  426. }
  427. // 归还玩家金币
  428. refundPlayerCoins(amount: number) {
  429. this.session.addCoins(amount);
  430. this.updateCoinDisplay();
  431. }
  432. // 设置拖拽事件方法已迁移到GameBlockSelection
  433. // 临时保存方块占用的网格
  434. tempStoreBlockOccupiedGrids(block: Node) {
  435. const occupiedGrids = block['occupiedGrids'];
  436. if (!occupiedGrids || occupiedGrids.length === 0) return;
  437. this.tempRemovedOccupiedGrids.push({
  438. block: block,
  439. occupiedGrids: [...occupiedGrids]
  440. });
  441. for (const grid of occupiedGrids) {
  442. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  443. grid.col >= 0 && grid.col < this.GRID_COLS) {
  444. this.gridOccupationMap[grid.row][grid.col] = 0;
  445. }
  446. }
  447. block['occupiedGrids'] = [];
  448. }
  449. // 恢复方块原来的占用状态
  450. restoreBlockOccupiedGrids(block: Node) {
  451. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  452. if (index === -1) return;
  453. const savedItem = this.tempRemovedOccupiedGrids[index];
  454. for (const grid of savedItem.occupiedGrids) {
  455. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  456. grid.col >= 0 && grid.col < this.GRID_COLS) {
  457. this.gridOccupationMap[grid.row][grid.col] = 1;
  458. }
  459. }
  460. block['occupiedGrids'] = [...savedItem.occupiedGrids];
  461. this.tempRemovedOccupiedGrids.splice(index, 1);
  462. }
  463. // 清除临时保存的占用状态
  464. clearTempStoredOccupiedGrids(block: Node) {
  465. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  466. if (index === -1) return;
  467. this.tempRemovedOccupiedGrids.splice(index, 1);
  468. }
  469. // 尝试将方块放置到网格中
  470. tryPlaceBlockToGrid(block: Node): boolean {
  471. console.log(`[BlockManager] 尝试放置方块 ${block.name} 到网格`);
  472. if (!this.gridContainer || !this.gridInitialized) {
  473. console.log(`[BlockManager] 网格容器或网格未初始化`);
  474. return false;
  475. }
  476. let b1Node = block;
  477. if (block.name !== 'B1') {
  478. b1Node = block.getChildByName('B1');
  479. if (!b1Node) {
  480. console.log(`[BlockManager] 方块 ${block.name} 没有B1子节点`);
  481. return false;
  482. }
  483. }
  484. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  485. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  486. console.log(`[BlockManager] B1世界坐标:`, b1WorldPos);
  487. console.log(`[BlockManager] 网格本地坐标:`, gridPos);
  488. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  489. const halfWidth = gridSize.width / 2;
  490. const halfHeight = gridSize.height / 2;
  491. const tolerance = this.gridSpacing * 0.5;
  492. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  493. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  494. console.log(`[BlockManager] 方块超出网格边界`);
  495. return false;
  496. }
  497. const nearestGrid = this.findNearestGridNode(gridPos);
  498. if (!nearestGrid) {
  499. console.log(`[BlockManager] 找不到最近的网格节点`);
  500. return false;
  501. }
  502. console.log(`[BlockManager] 找到最近的网格节点: ${nearestGrid.name}`);
  503. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  504. }
  505. // 找到最近的网格节点
  506. public findNearestGridNode(position: Vec3): Node {
  507. if (!this.gridContainer || !this.gridInitialized) return null;
  508. let nearestNode: Node = null;
  509. let minDistance = Number.MAX_VALUE;
  510. for (let row = 0; row < this.GRID_ROWS; row++) {
  511. for (let col = 0; col < this.GRID_COLS; col++) {
  512. const grid = this.gridNodes[row][col];
  513. if (grid) {
  514. const distance = Vec3.distance(position, grid.position);
  515. if (distance < minDistance) {
  516. minDistance = distance;
  517. nearestNode = grid;
  518. }
  519. }
  520. }
  521. }
  522. if (minDistance > this.gridSpacing * 2) {
  523. return null;
  524. }
  525. return nearestNode;
  526. }
  527. // 尝试将方块放置到指定的网格节点
  528. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  529. let b1Node = block;
  530. if (block.name !== 'B1') {
  531. b1Node = block.getChildByName('B1');
  532. if (!b1Node) {
  533. return false;
  534. }
  535. }
  536. if (!this.canPlaceBlockAt(block, targetGrid)) {
  537. return false;
  538. }
  539. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  540. const targetWorldPos = gridCenterWorldPos.clone();
  541. const b1LocalPos = b1Node.position.clone();
  542. let rootTargetWorldPos;
  543. if (b1Node === block) {
  544. rootTargetWorldPos = targetWorldPos.clone();
  545. } else {
  546. rootTargetWorldPos = new Vec3(
  547. targetWorldPos.x - b1LocalPos.x,
  548. targetWorldPos.y - b1LocalPos.y,
  549. targetWorldPos.z
  550. );
  551. }
  552. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  553. block.position = rootTargetLocalPos;
  554. this.markOccupiedPositions(block, targetGrid);
  555. return true;
  556. }
  557. // 检查方块是否可以放置在指定位置
  558. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  559. if (!this.gridInitialized) {
  560. console.log(`[BlockManager] 网格未初始化`);
  561. return false;
  562. }
  563. const targetRowCol = this.getGridRowCol(targetGrid);
  564. if (!targetRowCol) {
  565. console.log(`[BlockManager] 无法获取目标网格的行列信息`);
  566. return false;
  567. }
  568. const parts = this.getBlockParts(block);
  569. for (let i = 0; i < parts.length; i++) {
  570. const part = parts[i];
  571. const row = targetRowCol.row - part.y;
  572. const col = targetRowCol.col + part.x;
  573. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  574. console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`);
  575. return false;
  576. }
  577. if (this.gridOccupationMap[row][col] === 1) {
  578. console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`);
  579. return false;
  580. }
  581. }
  582. return true;
  583. }
  584. // 获取网格行列索引
  585. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  586. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  587. const parts = gridNode.name.split('_');
  588. if (parts.length === 3) {
  589. const row = parseInt(parts[1]);
  590. const col = parseInt(parts[2]);
  591. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  592. return { row, col };
  593. }
  594. }
  595. return null;
  596. }
  597. // 获取指定行列的网格世界坐标(用于调试绘制)
  598. public getGridWorldPosition(row: number, col: number): Vec3 | null {
  599. if (!this.gridInitialized || !this.gridNodes[row] || !this.gridNodes[row][col]) {
  600. return null;
  601. }
  602. const gridNode = this.gridNodes[row][col];
  603. return this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(gridNode.position);
  604. }
  605. // 获取方块的所有部分节点及其相对坐标
  606. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  607. const parts: { node: Node, x: number, y: number }[] = [];
  608. // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
  609. const b1Node = block.getChildByName('B1');
  610. if (b1Node) {
  611. // B1节点作为(0,0)位置
  612. parts.push({ node: b1Node, x: 0, y: 0 });
  613. this.findBlockParts(b1Node, parts, 0, 0);
  614. } else {
  615. // 没有B1节点,使用根节点
  616. parts.push({ node: block, x: 0, y: 0 });
  617. this.findBlockParts(block, parts, 0, 0);
  618. }
  619. return parts;
  620. }
  621. // 递归查找方块的所有部分
  622. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  623. for (let i = 0; i < node.children.length; i++) {
  624. const child = node.children[i];
  625. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  626. continue;
  627. }
  628. let x = parentX;
  629. let y = parentY;
  630. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  631. if (match) {
  632. x = parseInt(match[1]);
  633. y = parseInt(match[2]);
  634. result.push({ node: child, x, y });
  635. } else if (child.name.startsWith('B')) {
  636. const relativeX = Math.round(child.position.x / this.gridSpacing);
  637. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  638. x = parentX + relativeX;
  639. y = parentY + relativeY;
  640. result.push({ node: child, x, y });
  641. }
  642. this.findBlockParts(child, result, x, y);
  643. }
  644. }
  645. // 标记方块占用的格子
  646. public markOccupiedPositions(block: Node, targetGrid: Node) {
  647. if (!this.gridInitialized) return;
  648. const targetRowCol = this.getGridRowCol(targetGrid);
  649. if (!targetRowCol) return;
  650. const parts = this.getBlockParts(block);
  651. block['occupiedGrids'] = [];
  652. for (const part of parts) {
  653. const row = targetRowCol.row - part.y;
  654. const col = targetRowCol.col + part.x;
  655. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  656. this.gridOccupationMap[row][col] = 1;
  657. block['occupiedGrids'] = block['occupiedGrids'] || [];
  658. block['occupiedGrids'].push({ row, col });
  659. }
  660. }
  661. }
  662. // 清除方块
  663. clearBlocks() {
  664. console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
  665. const blocksToRemove = [];
  666. for (const block of this.blocks) {
  667. if (block.isValid) {
  668. const location = this.blockLocations.get(block);
  669. if (location === 'kuang') {
  670. blocksToRemove.push(block);
  671. }
  672. }
  673. }
  674. console.log('[BlockManager] 找到需要清理的kuang区域方块数量:', blocksToRemove.length);
  675. for (const block of blocksToRemove) {
  676. const dbNode = block['dbNode'];
  677. if (dbNode && dbNode.isValid) {
  678. block.off(Node.EventType.TRANSFORM_CHANGED);
  679. const kuangNode = this.kuangContainer;
  680. if (kuangNode) {
  681. const dbName = dbNode.name;
  682. if (!kuangNode.getChildByName(dbName)) {
  683. dbNode.parent = kuangNode;
  684. }
  685. }
  686. }
  687. const index = this.blocks.indexOf(block);
  688. if (index !== -1) {
  689. this.blocks.splice(index, 1);
  690. }
  691. this.originalPositions.delete(block);
  692. this.blockLocations.delete(block);
  693. this.blockPriceMap.delete(block);
  694. // 清理武器配置映射
  695. this.blockWeaponConfigs.delete(block);
  696. console.log('[BlockManager] 销毁kuang区域方块:', block.name);
  697. block.destroy();
  698. }
  699. console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
  700. }
  701. // 游戏开始时调用
  702. onGameStart() {
  703. this.gameStarted = true;
  704. for (const block of this.blocks) {
  705. if (block.isValid) {
  706. const location = this.blockLocations.get(block);
  707. if (location === 'grid') {
  708. this.hidePriceLabel(block);
  709. const dbNode = block['dbNode'];
  710. if (dbNode) {
  711. dbNode.active = false;
  712. }
  713. this.moveBlockToPlacedBlocks(block);
  714. this.addLockedVisualHint(block);
  715. // 游戏开始后放置的方块移除标签,不能再放回kuang
  716. BlockTag.removeTag(block);
  717. }
  718. }
  719. }
  720. }
  721. // 游戏重置时调用
  722. onGameReset() {
  723. console.log('[BlockManager] 游戏重置,清理所有状态');
  724. console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
  725. this.gameStarted = false;
  726. this.clearAllCooldowns();
  727. // 清理已放置的方块
  728. console.log('[BlockManager] 开始清理已放置的方块');
  729. this.clearPlacedBlocks();
  730. // 重置网格占用状态
  731. console.log('[BlockManager] 开始重置网格占用状态');
  732. this.resetGridOccupation();
  733. // 清理kuang区域的方块
  734. console.log('[BlockManager] 开始清理kuang区域的方块');
  735. this.clearBlocks();
  736. // 清理所有方块标签
  737. console.log('[BlockManager] 开始清理所有方块标签');
  738. BlockTag.clearAllTags();
  739. console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
  740. // 重新生成方块
  741. console.log('[BlockManager] 开始重新生成方块');
  742. this.generateRandomBlocksInKuang();
  743. console.log('[BlockManager] 游戏重置完成');
  744. }
  745. // 清理已放置的方块
  746. private clearPlacedBlocks() {
  747. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  748. console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
  749. return;
  750. }
  751. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  752. // 清理PlacedBlocks容器中的所有方块
  753. const placedBlocks = [...this.placedBlocksContainer.children];
  754. let clearedCount = 0;
  755. for (const block of placedBlocks) {
  756. if (block && block.isValid) {
  757. // 从blocks数组中移除
  758. const index = this.blocks.indexOf(block);
  759. if (index !== -1) {
  760. this.blocks.splice(index, 1);
  761. }
  762. // 清理相关映射
  763. this.originalPositions.delete(block);
  764. this.blockLocations.delete(block);
  765. this.blockPriceMap.delete(block);
  766. this.blockWeaponConfigs.delete(block);
  767. console.log('[BlockManager] 销毁已放置方块:', block.name);
  768. // 销毁方块
  769. block.destroy();
  770. clearedCount++;
  771. }
  772. }
  773. console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
  774. }
  775. // 重置网格占用状态
  776. public resetGridOccupation() {
  777. console.log('[BlockManager] 重置网格占用状态');
  778. // 重新初始化网格占用地图
  779. this.gridOccupationMap = [];
  780. for (let row = 0; row < this.GRID_ROWS; row++) {
  781. this.gridOccupationMap[row] = [];
  782. for (let col = 0; col < this.GRID_COLS; col++) {
  783. this.gridOccupationMap[row][col] = 0;
  784. }
  785. }
  786. // 清理临时存储的占用状态
  787. this.tempRemovedOccupiedGrids = [];
  788. }
  789. // 添加视觉提示,表明方块已锁定
  790. addLockedVisualHint(block: Node) {
  791. const children = block.children;
  792. for (let i = 0; i < children.length; i++) {
  793. const child = children[i];
  794. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  795. continue;
  796. }
  797. child.setScale(new Vec3(0.95, 0.95, 1));
  798. }
  799. }
  800. // 将方块移动到PlacedBlocks节点下
  801. moveBlockToPlacedBlocks(block: Node) {
  802. if (!this.placedBlocksContainer) {
  803. console.error('PlacedBlocks容器未设置');
  804. return;
  805. }
  806. if (!this.placedBlocksContainer.isValid) {
  807. console.error('PlacedBlocks容器已失效');
  808. return;
  809. }
  810. const worldPosition = new Vec3();
  811. block.getWorldPosition(worldPosition);
  812. // 移除旧的触摸事件监听器
  813. block.off(Node.EventType.TOUCH_START);
  814. block.off(Node.EventType.TOUCH_MOVE);
  815. block.off(Node.EventType.TOUCH_END);
  816. block.off(Node.EventType.TOUCH_CANCEL);
  817. block.removeFromParent();
  818. this.placedBlocksContainer.addChild(block);
  819. block.setWorldPosition(worldPosition);
  820. // 通过事件机制重新设置拖拽事件
  821. const eventBus = EventBus.getInstance();
  822. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]);
  823. console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`);
  824. }
  825. // 根据武器配置选择合适的预制体
  826. private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null {
  827. if (this.blockPrefabs.length === 0) {
  828. return null;
  829. }
  830. // 获取所有可用的方块形状配置
  831. const blockShapes = this.configManager.getBlockShapes();
  832. if (!blockShapes || blockShapes.length === 0) {
  833. console.warn('没有可用的方块形状配置,使用随机预制体');
  834. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  835. return this.blockPrefabs[randomIndex];
  836. }
  837. // 随机选择一个方块形状
  838. const randomShapeIndex = Math.floor(Math.random() * blockShapes.length);
  839. const targetShape = blockShapes[randomShapeIndex];
  840. // 寻找与目标形状匹配的预制体
  841. const matchingPrefab = this.findMatchingPrefab(targetShape);
  842. if (matchingPrefab) {
  843. console.log(`为武器 ${weaponConfig.name} 选择了匹配的预制体,形状: ${targetShape.name}`);
  844. return matchingPrefab;
  845. }
  846. // 如果没有找到匹配的预制体,使用随机预制体
  847. console.warn(`没有找到匹配形状 ${targetShape.name} 的预制体,使用随机预制体`);
  848. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  849. return this.blockPrefabs[randomIndex];
  850. }
  851. // 根据稀有度设置方块价格
  852. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  853. const label = priceNode.getComponent(Label);
  854. if (!label) {
  855. return;
  856. }
  857. let basePrice: number;
  858. switch (rarity) {
  859. case 'common':
  860. basePrice = 10;
  861. break;
  862. case 'uncommon':
  863. basePrice = 20;
  864. break;
  865. case 'rare':
  866. basePrice = 50;
  867. break;
  868. case 'epic':
  869. basePrice = 100;
  870. break;
  871. case 'legendary':
  872. basePrice = 150;
  873. break;
  874. default:
  875. basePrice = 200;
  876. }
  877. // 应用便宜技能效果
  878. const skillManager = SkillManager.getInstance();
  879. let finalPrice = basePrice;
  880. if (skillManager) {
  881. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  882. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  883. }
  884. label.string = finalPrice.toString();
  885. }
  886. // 设置方块的武器外观
  887. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  888. // 设置方块的稀有度颜色
  889. this.setBlockRarityColor(block, weaponConfig.rarity);
  890. // 加载武器图标
  891. this.loadWeaponIcon(block, weaponConfig);
  892. }
  893. // 设置方块稀有度颜色
  894. private setBlockRarityColor(block: Node, rarity: string) {
  895. this.applyBlockRarityColor(block, rarity);
  896. }
  897. // 公共方法:应用方块稀有度颜色(供外部调用)
  898. public applyBlockRarityColor(block: Node, rarity: string) {
  899. // Add null safety check for block
  900. if (!block || !block.isValid) {
  901. return;
  902. }
  903. const sprite = block.getComponent(Sprite);
  904. if (!sprite || !sprite.isValid) {
  905. return;
  906. }
  907. // 根据稀有度设置颜色
  908. let color: Color;
  909. switch (rarity) {
  910. case 'common':
  911. color = new Color(255, 255, 255); // 白色
  912. break;
  913. case 'uncommon':
  914. color = new Color(0, 255, 0); // 绿色
  915. break;
  916. case 'rare':
  917. color = new Color(0, 100, 255); // 蓝色
  918. break;
  919. case 'epic':
  920. color = new Color(160, 32, 240); // 紫色
  921. break;
  922. case 'legendary':
  923. color = new Color(255, 165, 0); // 橙色
  924. break;
  925. default:
  926. color = new Color(255, 255, 255); // 默认白色
  927. }
  928. sprite.color = color;
  929. console.log(`[BlockManager] 设置方块稀有度颜色: ${rarity}`, color);
  930. }
  931. // 加载武器图标
  932. private loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  933. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  934. const b1Node = block.getChildByName('B1');
  935. if (!b1Node) {
  936. console.warn('找不到B1节点');
  937. return;
  938. }
  939. const weaponNode = b1Node.getChildByName('Weapon');
  940. if (!weaponNode) {
  941. console.warn('找不到Weapon节点');
  942. return;
  943. }
  944. const weaponSprite = weaponNode.getComponent(Sprite);
  945. if (!weaponSprite) {
  946. console.warn('Weapon节点上没有Sprite组件');
  947. return;
  948. }
  949. // 获取武器配置中的图片路径
  950. const spriteConfig = weaponConfig.visualConfig?.weaponSprites;
  951. if (!spriteConfig) {
  952. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  953. return;
  954. }
  955. // 获取方块的形状ID
  956. const blockShapeId = this.getBlockShape(block);
  957. // 根据方块形状选择合适的图片路径
  958. let spritePath = null;
  959. if (blockShapeId && spriteConfig[blockShapeId]) {
  960. spritePath = spriteConfig[blockShapeId];
  961. } else {
  962. // 如果没有找到对应形状的图片,使用备用顺序
  963. spritePath = spriteConfig['I'] || spriteConfig['H-I'] || spriteConfig['L'] || spriteConfig['S'] || spriteConfig['D-T'];
  964. }
  965. if (!spritePath) {
  966. console.warn(`武器 ${weaponConfig.name} 没有可用的图片路径`);
  967. return;
  968. }
  969. // 正确的SpriteFrame子资源路径
  970. const spriteFramePath = `${spritePath}/spriteFrame`;
  971. // 加载SpriteFrame子资源
  972. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  973. if (err) {
  974. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  975. return;
  976. }
  977. // Add comprehensive null safety checks before setting spriteFrame
  978. if (weaponSprite && weaponSprite.isValid &&
  979. weaponNode && weaponNode.isValid &&
  980. block && block.isValid &&
  981. spriteFrame && spriteFrame.isValid) {
  982. weaponSprite.spriteFrame = spriteFrame;
  983. // 应用武器图标的位置偏移和旋转
  984. this.rotateWeaponIconByShape(weaponNode, blockShapeId, weaponConfig.id);
  985. }
  986. });
  987. }
  988. // 武器类型和方块形状组合的位置偏移配置(相对于方块中心的偏移量)
  989. private readonly WEAPON_SHAPE_POSITION_OFFSETS: { [weaponId: string]: { [shapeId: string]: { x: number, y: number } } } = {
  990. 'pea_shooter': {
  991. 'I': { x: 3, y: -3 }, // 毛豆射手竖条形状,轻微向下偏移
  992. 'H-I': { x: 0, y: 5 }, // 毛豆射手横条形状,居中
  993. 'L': { x: 1, y: -10 }, // 毛豆射手L型,轻微向左下偏移
  994. 'S': { x: 5, y: -1 }, // 毛豆射手S型,轻微向右下偏移
  995. 'D-T': { x: 3, y: -1 } // 毛豆射手倒T型,轻微向下偏移
  996. },
  997. 'sharp_carrot': {
  998. 'I': { x: 0, y: -1 }, // 尖胡萝卜竖条形状,轻微向下偏移
  999. 'H-I': { x: 0, y: 0 }, // 尖胡萝卜横条形状,居中
  1000. 'L': { x: -1, y: -7 }, // 尖胡萝卜L型,轻微向左下偏移
  1001. 'S': { x: 1, y: -1 }, // 尖胡萝卜S型,轻微向右下偏移
  1002. 'D-T': { x: 0, y: -1 } // 尖胡萝卜倒T型,轻微向下偏移
  1003. },
  1004. 'saw_grass': {
  1005. 'I': { x: 0, y: -1 }, // 锯齿草竖条形状,轻微向下偏移
  1006. 'H-I': { x: 0, y: 0 }, // 锯齿草横条形状,居中
  1007. 'L': { x: -1, y: -1 }, // 锯齿草L型,轻微向左下偏移
  1008. 'S': { x: 1, y: -1 }, // 锯齿草S型,轻微向右下偏移
  1009. 'D-T': { x: 0, y: -5 } // 锯齿草倒T型,轻微向下偏移
  1010. },
  1011. 'watermelon_bomb': {
  1012. 'I': { x: 0, y: -1 }, // 西瓜炸弹竖条形状,轻微向下偏移
  1013. 'H-I': { x: 0, y: 0 }, // 西瓜炸弹横条形状,居中
  1014. 'L': { x: -1, y: -1 }, // 西瓜炸弹L型,轻微向左下偏移
  1015. 'S': { x: 1, y: -1 }, // 西瓜炸弹S型,轻微向右下偏移
  1016. 'D-T': { x: 0, y: -7 } // 西瓜炸弹倒T型,轻微向下偏移
  1017. },
  1018. 'boomerang_plant': {
  1019. 'I': { x: 0, y: -1 }, // 回旋镖植物竖条形状,轻微向下偏移
  1020. 'H-I': { x: 0, y: 0 }, // 回旋镖植物横条形状,居中
  1021. 'L': { x: -1, y: -8 }, // 回旋镖植物L型,轻微向左下偏移
  1022. 'S': { x: 1, y: -1 }, // 回旋镖植物S型,轻微向右下偏移
  1023. 'D-T': { x: -10, y: -13 } // 回旋镖植物倒T型,轻微向下偏移
  1024. },
  1025. 'hot_pepper': {
  1026. 'I': { x: 0, y: 5 }, // 辣椒竖条形状,轻微向下偏移
  1027. 'H-I': { x: 0, y: 0 }, // 辣椒横条形状,居中
  1028. 'L': { x: -1, y: -1 }, // 辣椒L型,轻微向左下偏移
  1029. 'S': { x: 1, y: -1 }, // 辣椒S型,轻微向右下偏移
  1030. 'D-T': { x: 0, y: 0 } // 辣椒倒T型,轻微向下偏移
  1031. },
  1032. 'cactus_shotgun': {
  1033. 'I': { x: 0, y: -1 }, // 仙人掌霰弹枪竖条形状,轻微向下偏移
  1034. 'H-I': { x: 0, y: 0 }, // 仙人掌霰弹枪横条形状,居中
  1035. 'L': { x: -1, y: -3 }, // 仙人掌霰弹枪L型,轻微向左下偏移
  1036. 'S': { x: 1, y: -1 }, // 仙人掌霰弹枪S型,轻微向右下偏移
  1037. 'D-T': { x: 0, y: -1 } // 仙人掌霰弹枪倒T型,轻微向下偏移
  1038. },
  1039. 'okra_missile': {
  1040. 'I': { x: -4, y:3 }, // 秋葵导弹竖条形状,轻微向下偏移
  1041. 'H-I': { x: 0, y: -3 }, // 秋葵导弹横条形状,居中
  1042. 'L': { x: -1, y: -9 }, // 秋葵导弹L型,轻微向左下偏移
  1043. 'S': { x: -6, y: 0 }, // 秋葵导弹S型,轻微向右下偏移
  1044. 'D-T': { x: -3, y: 3 } // 秋葵导弹倒T型,轻微向下偏移
  1045. },
  1046. 'mace_club': {
  1047. 'I': { x: 0, y: -1 }, // 狼牙棒竖条形状,轻微向下偏移
  1048. 'H-I': { x: 1, y: 0 }, // 狼牙棒横条形状,居中
  1049. 'L': { x: -1, y: -1 }, // 狼牙棒L型,轻微向左下偏移
  1050. 'S': { x: 1, y: -1 }, // 狼牙棒S型,轻微向右下偏移
  1051. 'D-T': { x: 0, y: -5 } // 狼牙棒倒T型,轻微向下偏移
  1052. }
  1053. };
  1054. // 默认位置偏移配置(当武器类型未配置时使用)
  1055. private readonly DEFAULT_SHAPE_POSITION_OFFSETS: { [key: string]: { x: number, y: number } } = {
  1056. 'I': { x: 0, y: -1 }, // 竖条形状,轻微向下偏移
  1057. 'H-I': { x: 0, y: 0 }, // 横I型,居中
  1058. 'L': { x: -1, y: -1 }, // L型,轻微向左下偏移
  1059. 'S': { x: 1, y: -1 }, // S型,轻微向右下偏移
  1060. 'D-T': { x: 0, y: -1 } // 倒T型,轻微向下偏移
  1061. };
  1062. // 武器类型和方块形状组合的旋转角度配置
  1063. private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
  1064. 'pea_shooter': {
  1065. 'I': 0, // 毛豆射手竖条形状
  1066. 'H-I': 90, // 毛豆射手横条形状
  1067. 'L': 0, // 毛豆射手L型
  1068. 'S': 0, // 毛豆射手S型
  1069. 'D-T': 0 // 毛豆射手倒T型
  1070. },
  1071. 'sharp_carrot': {
  1072. 'I': 0, // 尖胡萝卜竖条形状
  1073. 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
  1074. 'L': -15, // 尖胡萝卜L型,轻微调整
  1075. 'S': 15, // 尖胡萝卜S型,轻微调整
  1076. 'D-T': 0 // 尖胡萝卜倒T型
  1077. },
  1078. 'saw_grass': {
  1079. 'I': 0, // 锯齿草竖条形状
  1080. 'H-I': 0, // 锯齿草横条形状
  1081. 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
  1082. 'S': 30, // 锯齿草S型,适配锯齿弯曲
  1083. 'D-T': 0 // 锯齿草倒T型
  1084. },
  1085. 'watermelon_bomb': {
  1086. 'I': 0, // 西瓜炸弹竖条形状
  1087. 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
  1088. 'L': 0, // 西瓜炸弹L型
  1089. 'S': 0, // 西瓜炸弹S型
  1090. 'D-T': 0 // 西瓜炸弹倒T型
  1091. },
  1092. 'boomerang_plant': {
  1093. 'I': 0, // 回旋镖植物竖条形状
  1094. 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
  1095. 'L': -30, // 回旋镖植物L型
  1096. 'S': -10, // 回旋镖植物S型,适配回旋轨迹
  1097. 'D-T': -80 // 回旋镖植物倒T型
  1098. },
  1099. 'hot_pepper': {
  1100. 'I': 0, // 辣椒竖条形状
  1101. 'H-I': 90, // 辣椒横条形状
  1102. 'L': 0, // 辣椒L型
  1103. 'S': 0, // 辣椒S型
  1104. 'D-T': 0 // 辣椒倒T型
  1105. },
  1106. 'cactus_shotgun': {
  1107. 'I': 0, // 仙人掌霰弹枪竖条形状
  1108. 'H-I': 90, // 仙人掌霰弹枪横条形状
  1109. 'L': -20, // 仙人掌霰弹枪L型
  1110. 'S': 20, // 仙人掌霰弹枪S型
  1111. 'D-T': 0 // 仙人掌霰弹枪倒T型
  1112. },
  1113. 'okra_missile': {
  1114. 'I': 0, // 秋葵导弹竖条形状
  1115. 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
  1116. 'L': -10, // 秋葵导弹L型
  1117. 'S': 10, // 秋葵导弹S型
  1118. 'D-T': 0 // 秋葵导弹倒T型
  1119. },
  1120. 'mace_club': {
  1121. 'I': -45, // 狼牙棒竖条形状
  1122. 'H-I': 0, // 狼牙棒横条形状
  1123. 'L': -90, // 狼牙棒L型,适配棒状武器
  1124. 'S': -90, // 狼牙棒S型
  1125. 'D-T': 0 // 狼牙棒倒T型
  1126. }
  1127. };
  1128. // 默认旋转角度配置(当武器类型未配置时使用)
  1129. private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
  1130. 'I': 0, // 竖条形状,保持原始方向
  1131. 'H-I': 90, // 横I型,旋转90度适配水平方向
  1132. 'L': -15, // L型,轻微左倾适配L形状的转角
  1133. 'S': 15, // S型,轻微右倾适配S形状的弯曲
  1134. 'D-T': 0 // 倒T型,保持原始方向
  1135. };
  1136. // 根据武器类型和方块形状调整武器图标位置和旋转
  1137. private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1138. if (!weaponNode || !shapeId) return;
  1139. let rotationAngle = 0;
  1140. let positionOffset = { x: 0, y: 0 };
  1141. // 如果提供了武器ID,尝试获取特定武器的配置
  1142. if (weaponId && this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1143. rotationAngle = this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1144. positionOffset = this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]?.[shapeId] || { x: 0, y: 0 };
  1145. console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定配置: 旋转${rotationAngle}度, 偏移(${positionOffset.x}, ${positionOffset.y})`);
  1146. } else {
  1147. // 使用默认配置
  1148. rotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1149. positionOffset = this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] || { x: 0, y: 0 };
  1150. console.log(`为形状 ${shapeId} 设置默认配置: 旋转${rotationAngle}度, 偏移(${positionOffset.x}, ${positionOffset.y})`);
  1151. }
  1152. // 应用旋转
  1153. weaponNode.setRotationFromEuler(0, 0, rotationAngle);
  1154. // 应用位置偏移
  1155. const currentPos = weaponNode.position;
  1156. weaponNode.setPosition(currentPos.x + positionOffset.x, currentPos.y + positionOffset.y, currentPos.z);
  1157. }
  1158. // 设置特定武器和形状的旋转角度
  1159. public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
  1160. if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1161. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
  1162. }
  1163. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
  1164. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1165. }
  1166. // 设置默认形状的旋转角度
  1167. public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
  1168. this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
  1169. console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1170. }
  1171. // 设置特定武器和形状的位置偏移
  1172. public setWeaponShapePositionOffset(weaponId: string, shapeId: string, offset: { x: number, y: number }) {
  1173. if (!this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]) {
  1174. this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId] = {};
  1175. }
  1176. this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId][shapeId] = offset;
  1177. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的位置偏移为: (${offset.x}, ${offset.y})`);
  1178. }
  1179. // 设置默认形状的位置偏移
  1180. public setDefaultShapePositionOffset(shapeId: string, offset: { x: number, y: number }) {
  1181. this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] = offset;
  1182. console.log(`已更新默认形状 ${shapeId} 的位置偏移为: (${offset.x}, ${offset.y})`);
  1183. }
  1184. // 获取特定武器和形状的旋转角度
  1185. public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
  1186. if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1187. return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1188. }
  1189. return 0;
  1190. }
  1191. // 获取默认形状的旋转角度
  1192. public getDefaultShapeRotationAngle(shapeId: string): number {
  1193. return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1194. }
  1195. // 获取特定武器和形状的位置偏移
  1196. public getWeaponShapePositionOffset(weaponId: string, shapeId: string): { x: number, y: number } {
  1197. if (this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]) {
  1198. return this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId][shapeId] || { x: 0, y: 0 };
  1199. }
  1200. return { x: 0, y: 0 };
  1201. }
  1202. // 获取默认形状的位置偏移
  1203. public getDefaultShapePositionOffset(shapeId: string): { x: number, y: number } {
  1204. return this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] || { x: 0, y: 0 };
  1205. }
  1206. // 同时设置特定武器和形状的位置偏移和旋转角度
  1207. public setWeaponShapeTransform(weaponId: string, shapeId: string, offset: { x: number, y: number }, angle: number) {
  1208. this.setWeaponShapePositionOffset(weaponId, shapeId, offset);
  1209. this.setWeaponShapeRotationAngle(weaponId, shapeId, angle);
  1210. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的完整变换: 偏移(${offset.x}, ${offset.y}), 旋转${angle}度`);
  1211. }
  1212. // 同时设置默认形状的位置偏移和旋转角度
  1213. public setDefaultShapeTransform(shapeId: string, offset: { x: number, y: number }, angle: number) {
  1214. this.setDefaultShapePositionOffset(shapeId, offset);
  1215. this.setDefaultShapeRotationAngle(shapeId, angle);
  1216. console.log(`已更新默认形状 ${shapeId} 的完整变换: 偏移(${offset.x}, ${offset.y}), 旋转${angle}度`);
  1217. }
  1218. // 重新应用所有已放置方块的武器图标位置和旋转
  1219. public refreshAllWeaponIconRotations() {
  1220. // 遍历所有已放置的方块
  1221. if (this.placedBlocksContainer) {
  1222. this.placedBlocksContainer.children.forEach(block => {
  1223. const weaponConfig = this.getBlockWeaponConfig(block);
  1224. if (weaponConfig) {
  1225. const b1Node = block.getChildByName('B1');
  1226. if (b1Node) {
  1227. const weaponNode = b1Node.getChildByName('Weapon');
  1228. if (weaponNode) {
  1229. const shapeId = this.getBlockShape(block);
  1230. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1231. }
  1232. }
  1233. }
  1234. });
  1235. }
  1236. // 遍历kuang区域的方块
  1237. this.blocks.forEach(block => {
  1238. const weaponConfig = this.getBlockWeaponConfig(block);
  1239. if (weaponConfig) {
  1240. const b1Node = block.getChildByName('B1');
  1241. if (b1Node) {
  1242. const weaponNode = b1Node.getChildByName('Weapon');
  1243. if (weaponNode) {
  1244. const shapeId = this.getBlockShape(block);
  1245. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1246. }
  1247. }
  1248. }
  1249. });
  1250. }
  1251. // 根据方块获取武器配置
  1252. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  1253. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  1254. }
  1255. // 获取方块的武器ID
  1256. public getBlockWeaponId(block: Node): string | null {
  1257. const weaponConfig = this.getBlockWeaponConfig(block);
  1258. return weaponConfig ? weaponConfig.id : null;
  1259. }
  1260. // 获取方块的形状
  1261. public getBlockShape(block: Node): string | null {
  1262. const weaponConfig = this.getBlockWeaponConfig(block);
  1263. if (!weaponConfig) return null;
  1264. // 从方块结构推断形状
  1265. return this.inferBlockShapeFromStructure(block);
  1266. }
  1267. // 获取方块的详细形状信息(包括形状ID和名称)
  1268. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  1269. const actualShape = this.extractShapeFromBlock(block);
  1270. const blockShapes = this.configManager.getBlockShapes();
  1271. if (!blockShapes) return null;
  1272. // 寻找匹配的形状配置
  1273. for (const shapeConfig of blockShapes) {
  1274. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1275. return {
  1276. id: shapeConfig.id,
  1277. name: shapeConfig.name,
  1278. shape: shapeConfig.shape
  1279. };
  1280. }
  1281. }
  1282. return null;
  1283. }
  1284. // 从方块结构推断形状
  1285. private inferBlockShapeFromStructure(block: Node): string {
  1286. const actualShape = this.extractShapeFromBlock(block);
  1287. const blockShapes = this.configManager.getBlockShapes();
  1288. if (!blockShapes) {
  1289. console.warn('无法获取方块形状配置,使用默认形状');
  1290. return 'I';
  1291. }
  1292. // 寻找匹配的形状配置
  1293. for (const shapeConfig of blockShapes) {
  1294. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1295. console.log(`[BlockManager] 识别方块形状: ${shapeConfig.id} (${shapeConfig.name})`);
  1296. return shapeConfig.id;
  1297. }
  1298. }
  1299. console.warn('[BlockManager] 未找到匹配的形状配置,使用默认形状I');
  1300. return 'I';
  1301. }
  1302. // 寻找与目标形状匹配的预制体
  1303. private findMatchingPrefab(targetShape: any): Prefab | null {
  1304. for (const prefab of this.blockPrefabs) {
  1305. if (this.doesPrefabMatchShape(prefab, targetShape)) {
  1306. return prefab;
  1307. }
  1308. }
  1309. return null;
  1310. }
  1311. // 检查预制体是否匹配指定形状
  1312. private doesPrefabMatchShape(prefab: Prefab, targetShape: any): boolean {
  1313. // 创建临时实例来检查形状
  1314. const tempBlock = instantiate(prefab);
  1315. const parts = this.getBlockParts(tempBlock);
  1316. const actualShape = this.extractShapeFromBlock(tempBlock);
  1317. tempBlock.destroy();
  1318. // 比较形状矩阵
  1319. const matches = this.compareShapeMatrices(actualShape, targetShape.shape);
  1320. return matches;
  1321. }
  1322. // 从方块实例中提取形状矩阵
  1323. private extractShapeFromBlock(block: Node): number[][] {
  1324. const parts = this.getBlockParts(block);
  1325. // 创建4x4矩阵
  1326. const matrix: number[][] = [];
  1327. for (let i = 0; i < 4; i++) {
  1328. matrix[i] = [0, 0, 0, 0];
  1329. }
  1330. // 找到最小坐标作为偏移基准
  1331. let minX = 0, minY = 0;
  1332. for (const part of parts) {
  1333. minX = Math.min(minX, part.x);
  1334. minY = Math.min(minY, part.y);
  1335. }
  1336. // 填充矩阵,将坐标标准化到从(0,0)开始
  1337. for (const part of parts) {
  1338. const matrixX = part.x - minX;
  1339. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  1340. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  1341. matrix[matrixY][matrixX] = 1;
  1342. }
  1343. }
  1344. // 对矩阵进行上下翻转(交换第0行和第1行)
  1345. const temp = matrix[0];
  1346. matrix[0] = matrix[1];
  1347. matrix[1] = temp;
  1348. return matrix;
  1349. }
  1350. // 比较两个形状矩阵是否相同
  1351. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  1352. if (matrix1.length !== matrix2.length) return false;
  1353. for (let i = 0; i < matrix1.length; i++) {
  1354. if (matrix1[i].length !== matrix2[i].length) return false;
  1355. for (let j = 0; j < matrix1[i].length; j++) {
  1356. if (matrix1[i][j] !== matrix2[i][j]) return false;
  1357. }
  1358. }
  1359. return true;
  1360. }
  1361. // 检查两个方块是否可以合成(相同形状相同种类)
  1362. private canMergeBlocks(block1: Node, block2: Node): boolean {
  1363. // 检查稀有度
  1364. const rarity1 = this.getBlockRarity(block1);
  1365. const rarity2 = this.getBlockRarity(block2);
  1366. if (rarity1 !== rarity2) {
  1367. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  1368. return false;
  1369. }
  1370. // 检查武器ID(种类)
  1371. const weaponId1 = this.getBlockWeaponId(block1);
  1372. const weaponId2 = this.getBlockWeaponId(block2);
  1373. if (weaponId1 !== weaponId2) {
  1374. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  1375. return false;
  1376. }
  1377. // 使用精确的形状矩阵比较
  1378. const shape1 = this.extractShapeFromBlock(block1);
  1379. const shape2 = this.extractShapeFromBlock(block2);
  1380. if (!this.compareShapeMatrices(shape1, shape2)) {
  1381. console.log(`[BlockManager] 形状矩阵不匹配`);
  1382. return false;
  1383. }
  1384. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  1385. return true;
  1386. }
  1387. // 刷新方块 - 重新生成三个新的武器方块
  1388. public refreshBlocks() {
  1389. // 移除PlacedBlocks容器中所有方块的标签
  1390. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1391. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1392. }
  1393. // 保存已放置方块的占用信息
  1394. const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  1395. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1396. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1397. const block = this.placedBlocksContainer.children[i];
  1398. const occupiedGrids = block['occupiedGrids'];
  1399. if (occupiedGrids && occupiedGrids.length > 0) {
  1400. placedBlocksOccupation.push({
  1401. block: block,
  1402. occupiedGrids: [...occupiedGrids]
  1403. });
  1404. }
  1405. }
  1406. }
  1407. // 生成新的方块
  1408. this.generateRandomBlocksInKuang();
  1409. // 恢复已放置方块的占用信息
  1410. for (const item of placedBlocksOccupation) {
  1411. if (item.block && item.block.isValid) {
  1412. item.block['occupiedGrids'] = [...item.occupiedGrids];
  1413. // 重新标记网格占用状态
  1414. for (const grid of item.occupiedGrids) {
  1415. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  1416. grid.col >= 0 && grid.col < this.GRID_COLS) {
  1417. this.gridOccupationMap[grid.row][grid.col] = 1;
  1418. }
  1419. }
  1420. }
  1421. }
  1422. }
  1423. // 检查是否有已放置的方块
  1424. public hasPlacedBlocks(): boolean {
  1425. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1426. console.log('[BlockManager] PlacedBlocks容器无效');
  1427. return false;
  1428. }
  1429. const blockCount = this.placedBlocksContainer.children.length;
  1430. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1431. // 检查容器中是否有子节点(方块)
  1432. return blockCount > 0;
  1433. }
  1434. /* =================== 合成逻辑 =================== */
  1435. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  1436. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1437. public async tryMergeBlock(block: Node) {
  1438. try {
  1439. const rarity = this.getBlockRarity(block);
  1440. if (!rarity) return;
  1441. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1442. if (!this.placedBlocksContainer) return;
  1443. const blockBB = this.getWorldAABB(block);
  1444. for (const other of this.placedBlocksContainer.children) {
  1445. if (other === block) continue;
  1446. // 使用新的合成检查方法
  1447. if (!this.canMergeBlocks(block, other)) continue;
  1448. const otherBB = this.getWorldAABB(other);
  1449. if (this.rectIntersects(blockBB, otherBB)) {
  1450. // 找到合成目标
  1451. await this.performMerge(block, other, rarity);
  1452. break;
  1453. }
  1454. }
  1455. } catch (error) {
  1456. console.error('[BlockManager] tryMergeBlock 发生错误:', error);
  1457. // 合成失败不影响游戏继续,只记录错误
  1458. }
  1459. }
  1460. private async performMerge(target: Node, source: Node, rarity: string) {
  1461. try {
  1462. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1463. // 隐藏价格标签并处理 db 关联
  1464. this.hidePriceLabel(source);
  1465. const srcDb = source['dbNode'];
  1466. if (srcDb) srcDb.active = false;
  1467. // 销毁被合并方块
  1468. source.destroy();
  1469. // 升级稀有度
  1470. const nextRarity = this.getNextRarity(rarity);
  1471. if (nextRarity) {
  1472. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1473. // 获取当前武器配置
  1474. const currentConfig = this.blockWeaponConfigs.get(target);
  1475. if (currentConfig) {
  1476. // 保存原始武器名称用于日志输出
  1477. const originalWeaponName = currentConfig.name;
  1478. try {
  1479. // 获取当前关卡允许的武器列表
  1480. const levelWeapons = await this.getCurrentLevelWeapons();
  1481. // 检查是否应该限制在关卡配置的武器范围内
  1482. if (levelWeapons.length > 0) {
  1483. // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
  1484. if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
  1485. console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
  1486. }
  1487. // 无论如何,都只升级稀有度,不改变武器类型
  1488. const upgradedConfig = { ...currentConfig };
  1489. upgradedConfig.rarity = nextRarity;
  1490. this.blockWeaponConfigs.set(target, upgradedConfig);
  1491. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1492. } else {
  1493. // 如果没有关卡配置限制,正常升级稀有度
  1494. const upgradedConfig = { ...currentConfig };
  1495. upgradedConfig.rarity = nextRarity;
  1496. this.blockWeaponConfigs.set(target, upgradedConfig);
  1497. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1498. }
  1499. } catch (weaponError) {
  1500. console.error('[BlockManager] 获取关卡武器配置失败:', weaponError);
  1501. // 武器配置获取失败时,仍然升级稀有度
  1502. const upgradedConfig = { ...currentConfig };
  1503. upgradedConfig.rarity = nextRarity;
  1504. this.blockWeaponConfigs.set(target, upgradedConfig);
  1505. console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1506. }
  1507. }
  1508. // 更新方块颜色
  1509. this.setBlockRarityColor(target, nextRarity);
  1510. }
  1511. // 播放烟雾动画
  1512. const worldPos = new Vec3();
  1513. target.getWorldPosition(worldPos);
  1514. this.spawnMergeSmoke(worldPos);
  1515. // 递归检查是否还能继续合成
  1516. if (nextRarity) {
  1517. await this.tryMergeBlock(target);
  1518. }
  1519. console.log(`[BlockManager] 合成完成`);
  1520. } catch (error) {
  1521. console.error('[BlockManager] performMerge 发生错误:', error);
  1522. // 合成失败时重新抛出错误,让上层处理
  1523. throw error;
  1524. }
  1525. }
  1526. private getBlockRarity(block: Node): string | null {
  1527. const cfg = this.blockWeaponConfigs.get(block);
  1528. if (cfg) return cfg.rarity;
  1529. // fallback based on sprite color maybe
  1530. return null;
  1531. }
  1532. private getNextRarity(rarity: string): string | null {
  1533. const idx = this.rarityOrder.indexOf(rarity);
  1534. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1535. return this.rarityOrder[idx + 1];
  1536. }
  1537. private getWorldAABB(node: Node): Rect {
  1538. const ui = node.getComponent(UITransform);
  1539. if (!ui) return new Rect();
  1540. const pos = node.worldPosition;
  1541. const width = ui.width;
  1542. const height = ui.height;
  1543. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1544. }
  1545. private rectIntersects(a: Rect, b: Rect): boolean {
  1546. return a.x < b.x + b.width &&
  1547. a.x + a.width > b.x &&
  1548. a.y < b.y + b.height &&
  1549. a.y + a.height > b.y;
  1550. }
  1551. /** 生成烟雾特效 */
  1552. private spawnMergeSmoke(worldPos: Vec3) {
  1553. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1554. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1555. if (err || !sData) {
  1556. console.warn('加载合成烟雾动画失败', err);
  1557. return;
  1558. }
  1559. const node = new Node('MergeSmoke');
  1560. const skeleton = node.addComponent(sp.Skeleton);
  1561. skeleton.skeletonData = sData;
  1562. skeleton.premultipliedAlpha = false;
  1563. skeleton.setAnimation(0, 'animation', false);
  1564. skeleton.setCompleteListener(() => node.destroy());
  1565. const canvas = find('Canvas');
  1566. if (canvas) canvas.addChild(node);
  1567. node.setWorldPosition(worldPos);
  1568. });
  1569. }
  1570. /** 在放置失败时尝试与现有方块进行合成 */
  1571. public tryMergeOnOverlap(draggedBlock: Node): boolean {
  1572. if (!this.placedBlocksContainer) return false;
  1573. const rarity = this.getBlockRarity(draggedBlock);
  1574. if (!rarity) return false;
  1575. const dragBB = this.getWorldAABB(draggedBlock);
  1576. for (const target of this.placedBlocksContainer.children) {
  1577. if (target === draggedBlock) continue;
  1578. // 使用新的合成检查方法
  1579. if (!this.canMergeBlocks(draggedBlock, target)) continue;
  1580. const targetBB = this.getWorldAABB(target);
  1581. if (this.rectIntersects(dragBB, targetBB)) {
  1582. // 执行合并:目标保留,拖拽方块销毁
  1583. this.performMerge(target, draggedBlock, rarity);
  1584. return true;
  1585. }
  1586. }
  1587. return false;
  1588. }
  1589. // 调试绘制功能已迁移到GameBlockSelection
  1590. // 输出格子占用情况矩阵
  1591. public printGridOccupationMatrix() {
  1592. console.log('[BlockManager] 格子占用情况矩阵 (6行11列):');
  1593. for (let row = 0; row < this.GRID_ROWS; row++) {
  1594. let rowStr = '';
  1595. for (let col = 0; col < this.GRID_COLS; col++) {
  1596. rowStr += this.gridOccupationMap[row][col] + ' ';
  1597. }
  1598. console.log(`第${row + 1}行: ${rowStr.trim()}`);
  1599. }
  1600. }
  1601. // 通过GameBlockSelection刷新方块占用情况
  1602. onDestroy() {
  1603. // 调试绘制功能已迁移到GameBlockSelection
  1604. // 清理事件监听
  1605. const eventBus = EventBus.getInstance();
  1606. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  1607. eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  1608. // 移除GAME_START事件清理,因为已不再监听该事件
  1609. // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1610. eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  1611. }
  1612. }