BlockManager.ts 89 KB

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