BlockManager.ts 76 KB

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