BlockManager.ts 85 KB

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