BlockManager.ts 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172
  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. console.log(`[BlockManager] 找到最近的网格节点: ${nearestGrid.name}`);
  614. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  615. }
  616. // 找到最近的网格节点
  617. public findNearestGridNode(position: Vec3): Node {
  618. if (!this.gridContainer || !this.gridInitialized) return null;
  619. let nearestNode: Node = null;
  620. let minDistance = Number.MAX_VALUE;
  621. for (let row = 0; row < this.GRID_ROWS; row++) {
  622. for (let col = 0; col < this.GRID_COLS; col++) {
  623. const grid = this.gridNodes[row][col];
  624. if (grid) {
  625. const distance = Vec3.distance(position, grid.position);
  626. if (distance < minDistance) {
  627. minDistance = distance;
  628. nearestNode = grid;
  629. }
  630. }
  631. }
  632. }
  633. if (minDistance > this.gridSpacing * 2) {
  634. return null;
  635. }
  636. return nearestNode;
  637. }
  638. // 尝试将方块放置到指定的网格节点
  639. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  640. let b1Node = block;
  641. if (block.name !== 'B1') {
  642. b1Node = block.getChildByName('B1');
  643. if (!b1Node) {
  644. return false;
  645. }
  646. }
  647. if (!this.canPlaceBlockAt(block, targetGrid)) {
  648. return false;
  649. }
  650. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  651. const targetWorldPos = gridCenterWorldPos.clone();
  652. const b1LocalPos = b1Node.position.clone();
  653. let rootTargetWorldPos;
  654. if (b1Node === block) {
  655. rootTargetWorldPos = targetWorldPos.clone();
  656. } else {
  657. rootTargetWorldPos = new Vec3(
  658. targetWorldPos.x - b1LocalPos.x,
  659. targetWorldPos.y - b1LocalPos.y,
  660. targetWorldPos.z
  661. );
  662. }
  663. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  664. block.position = rootTargetLocalPos;
  665. this.markOccupiedPositions(block, targetGrid);
  666. // 当方块从kuang区域拖到网格时,恢复植物图标的正常缩放
  667. const weaponNode = block.getChildByName('Weapon');
  668. if (weaponNode) {
  669. weaponNode.setScale(1.0, 1.0, 1.0);
  670. console.log(`[BlockManager] 方块 ${block.name} 放置到网格,植物图标缩放恢复为正常大小`);
  671. }
  672. return true;
  673. }
  674. // 检查方块是否可以放置在指定位置
  675. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  676. if (!this.gridInitialized) {
  677. console.log(`[BlockManager] 网格未初始化`);
  678. return false;
  679. }
  680. const targetRowCol = this.getGridRowCol(targetGrid);
  681. if (!targetRowCol) {
  682. console.log(`[BlockManager] 无法获取目标网格的行列信息`);
  683. return false;
  684. }
  685. const parts = this.getBlockParts(block);
  686. for (let i = 0; i < parts.length; i++) {
  687. const part = parts[i];
  688. const row = targetRowCol.row - part.y;
  689. const col = targetRowCol.col + part.x;
  690. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  691. console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`);
  692. return false;
  693. }
  694. if (this.gridOccupationMap[row][col] === 1) {
  695. console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`);
  696. return false;
  697. }
  698. }
  699. return true;
  700. }
  701. // 获取网格行列索引
  702. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  703. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  704. const parts = gridNode.name.split('_');
  705. if (parts.length === 3) {
  706. const row = parseInt(parts[1]);
  707. const col = parseInt(parts[2]);
  708. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  709. return { row, col };
  710. }
  711. }
  712. return null;
  713. }
  714. // 获取指定行列的网格世界坐标(用于调试绘制)
  715. public getGridWorldPosition(row: number, col: number): Vec3 | null {
  716. if (!this.gridInitialized || !this.gridNodes[row] || !this.gridNodes[row][col]) {
  717. return null;
  718. }
  719. const gridNode = this.gridNodes[row][col];
  720. return this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(gridNode.position);
  721. }
  722. // 获取方块的所有部分节点及其相对坐标
  723. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  724. const parts: { node: Node, x: number, y: number }[] = [];
  725. // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
  726. const b1Node = block.getChildByName('B1');
  727. if (b1Node) {
  728. // B1节点作为(0,0)位置
  729. parts.push({ node: b1Node, x: 0, y: 0 });
  730. this.findBlockParts(b1Node, parts, 0, 0);
  731. } else {
  732. // 没有B1节点,使用根节点
  733. parts.push({ node: block, x: 0, y: 0 });
  734. this.findBlockParts(block, parts, 0, 0);
  735. }
  736. return parts;
  737. }
  738. // 递归查找方块的所有部分
  739. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  740. for (let i = 0; i < node.children.length; i++) {
  741. const child = node.children[i];
  742. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  743. continue;
  744. }
  745. let x = parentX;
  746. let y = parentY;
  747. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  748. if (match) {
  749. x = parseInt(match[1]);
  750. y = parseInt(match[2]);
  751. result.push({ node: child, x, y });
  752. } else if (child.name.startsWith('B')) {
  753. const relativeX = Math.round(child.position.x / this.gridSpacing);
  754. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  755. x = parentX + relativeX;
  756. y = parentY + relativeY;
  757. result.push({ node: child, x, y });
  758. }
  759. this.findBlockParts(child, result, x, y);
  760. }
  761. }
  762. // 标记方块占用的格子
  763. public markOccupiedPositions(block: Node, targetGrid: Node) {
  764. if (!this.gridInitialized) return;
  765. const targetRowCol = this.getGridRowCol(targetGrid);
  766. if (!targetRowCol) return;
  767. const parts = this.getBlockParts(block);
  768. block['occupiedGrids'] = [];
  769. for (const part of parts) {
  770. const row = targetRowCol.row - part.y;
  771. const col = targetRowCol.col + part.x;
  772. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  773. this.gridOccupationMap[row][col] = 1;
  774. block['occupiedGrids'] = block['occupiedGrids'] || [];
  775. block['occupiedGrids'].push({ row, col });
  776. }
  777. }
  778. }
  779. // 清除方块
  780. clearBlocks() {
  781. console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
  782. const blocksToRemove = [];
  783. for (const block of this.blocks) {
  784. if (block.isValid) {
  785. const location = this.blockLocations.get(block);
  786. if (location === 'kuang') {
  787. blocksToRemove.push(block);
  788. }
  789. }
  790. }
  791. console.log('[BlockManager] 找到需要清理的kuang区域方块数量:', blocksToRemove.length);
  792. for (const block of blocksToRemove) {
  793. const dbNode = block['dbNode'];
  794. if (dbNode && dbNode.isValid) {
  795. block.off(Node.EventType.TRANSFORM_CHANGED);
  796. const kuangNode = this.kuangContainer;
  797. if (kuangNode) {
  798. const dbName = dbNode.name;
  799. if (!kuangNode.getChildByName(dbName)) {
  800. dbNode.parent = kuangNode;
  801. }
  802. }
  803. }
  804. const index = this.blocks.indexOf(block);
  805. if (index !== -1) {
  806. this.blocks.splice(index, 1);
  807. }
  808. this.originalPositions.delete(block);
  809. this.blockLocations.delete(block);
  810. this.blockPriceMap.delete(block);
  811. // 清理武器配置映射
  812. this.blockWeaponConfigs.delete(block);
  813. console.log('[BlockManager] 销毁kuang区域方块:', block.name);
  814. block.destroy();
  815. }
  816. console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
  817. }
  818. // 游戏开始时调用
  819. onGameStart() {
  820. this.gameStarted = true;
  821. for (const block of this.blocks) {
  822. if (block.isValid) {
  823. const location = this.blockLocations.get(block);
  824. if (location === 'grid') {
  825. this.hidePriceLabel(block);
  826. const dbNode = block['dbNode'];
  827. if (dbNode) {
  828. dbNode.active = false;
  829. }
  830. this.moveBlockToPlacedBlocks(block);
  831. this.addLockedVisualHint(block);
  832. // 游戏开始后放置的方块移除标签,不能再放回kuang
  833. BlockTag.removeTag(block);
  834. }
  835. }
  836. }
  837. }
  838. // 游戏重置时调用
  839. onGameReset() {
  840. console.log('[BlockManager] 游戏重置,清理所有状态');
  841. console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
  842. this.gameStarted = false;
  843. this.clearAllCooldowns();
  844. // 清理已放置的方块
  845. console.log('[BlockManager] 开始清理已放置的方块');
  846. this.clearPlacedBlocks();
  847. // 重置网格占用状态
  848. console.log('[BlockManager] 开始重置网格占用状态');
  849. this.resetGridOccupation();
  850. // 清理kuang区域的方块
  851. console.log('[BlockManager] 开始清理kuang区域的方块');
  852. this.clearBlocks();
  853. // 清理所有方块标签
  854. console.log('[BlockManager] 开始清理所有方块标签');
  855. BlockTag.clearAllTags();
  856. console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
  857. console.log('[BlockManager] 游戏重置完成 - 方块生成将由StartGame流程处理');
  858. }
  859. // 清理已放置的方块
  860. private clearPlacedBlocks() {
  861. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  862. console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
  863. return;
  864. }
  865. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  866. // 清理PlacedBlocks容器中的所有方块
  867. const placedBlocks = [...this.placedBlocksContainer.children];
  868. let clearedCount = 0;
  869. for (const block of placedBlocks) {
  870. if (block && block.isValid) {
  871. // 从blocks数组中移除
  872. const index = this.blocks.indexOf(block);
  873. if (index !== -1) {
  874. this.blocks.splice(index, 1);
  875. }
  876. // 清理相关映射
  877. this.originalPositions.delete(block);
  878. this.blockLocations.delete(block);
  879. this.blockPriceMap.delete(block);
  880. this.blockWeaponConfigs.delete(block);
  881. console.log('[BlockManager] 销毁已放置方块:', block.name);
  882. // 销毁方块
  883. block.destroy();
  884. clearedCount++;
  885. }
  886. }
  887. console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
  888. }
  889. // 重置网格占用状态
  890. public resetGridOccupation() {
  891. console.log('[BlockManager] 重置网格占用状态');
  892. // 重新初始化网格占用地图
  893. this.gridOccupationMap = [];
  894. for (let row = 0; row < this.GRID_ROWS; row++) {
  895. this.gridOccupationMap[row] = [];
  896. for (let col = 0; col < this.GRID_COLS; col++) {
  897. this.gridOccupationMap[row][col] = 0;
  898. }
  899. }
  900. // 清理临时存储的占用状态
  901. this.tempRemovedOccupiedGrids = [];
  902. }
  903. // 添加视觉提示,表明方块已锁定
  904. addLockedVisualHint(block: Node) {
  905. const children = block.children;
  906. for (let i = 0; i < children.length; i++) {
  907. const child = children[i];
  908. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  909. continue;
  910. }
  911. child.setScale(new Vec3(0.95, 0.95, 1));
  912. }
  913. }
  914. // 将方块移动到PlacedBlocks节点下
  915. moveBlockToPlacedBlocks(block: Node) {
  916. if (!this.placedBlocksContainer) {
  917. console.error('PlacedBlocks容器未设置');
  918. return;
  919. }
  920. if (!this.placedBlocksContainer.isValid) {
  921. console.error('PlacedBlocks容器已失效');
  922. return;
  923. }
  924. const worldPosition = new Vec3();
  925. block.getWorldPosition(worldPosition);
  926. // 移除旧的触摸事件监听器
  927. block.off(Node.EventType.TOUCH_START);
  928. block.off(Node.EventType.TOUCH_MOVE);
  929. block.off(Node.EventType.TOUCH_END);
  930. block.off(Node.EventType.TOUCH_CANCEL);
  931. block.removeFromParent();
  932. this.placedBlocksContainer.addChild(block);
  933. block.setWorldPosition(worldPosition);
  934. // 通过事件机制重新设置拖拽事件
  935. const eventBus = EventBus.getInstance();
  936. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]);
  937. console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`);
  938. }
  939. // 根据武器配置选择合适的预制体
  940. private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null {
  941. if (this.blockPrefabs.length === 0) {
  942. return null;
  943. }
  944. // 获取所有可用的方块形状配置
  945. console.log('[BlockManager] 尝试获取方块形状配置...');
  946. let blockShapes = null;
  947. // 优先使用预加载的配置
  948. if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
  949. blockShapes = this.preloadedWeaponsConfig.blockSizes;
  950. console.log('[BlockManager] 使用预加载的方块形状配置');
  951. } else {
  952. // 回退到ConfigManager
  953. blockShapes = this.configManager.getBlockShapes();
  954. console.log('[BlockManager] 使用ConfigManager的方块形状配置');
  955. }
  956. if (!blockShapes || blockShapes.length === 0) {
  957. console.warn('[BlockManager] 未找到匹配的形状配置,使用默认形状I');
  958. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  959. return this.blockPrefabs[randomIndex];
  960. }
  961. console.log(`[BlockManager] ✅ 成功获取${blockShapes.length}个方块形状配置`);
  962. // 随机选择一个方块形状
  963. const randomShapeIndex = Math.floor(Math.random() * blockShapes.length);
  964. const targetShape = blockShapes[randomShapeIndex];
  965. // 寻找与目标形状匹配的预制体
  966. const matchingPrefab = this.findMatchingPrefab(targetShape);
  967. if (matchingPrefab) {
  968. console.log(`为武器 ${weaponConfig.name} 选择了匹配的预制体,形状: ${targetShape.name}`);
  969. return matchingPrefab;
  970. }
  971. // 如果没有找到匹配的预制体,使用随机预制体
  972. console.warn(`没有找到匹配形状 ${targetShape.name} 的预制体,使用随机预制体`);
  973. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  974. return this.blockPrefabs[randomIndex];
  975. }
  976. // 根据稀有度设置方块价格
  977. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  978. const label = priceNode.getComponent(Label);
  979. if (!label) {
  980. return;
  981. }
  982. let basePrice: number;
  983. switch (rarity) {
  984. case 'common':
  985. basePrice = 10;
  986. break;
  987. case 'uncommon':
  988. basePrice = 20;
  989. break;
  990. case 'rare':
  991. basePrice = 50;
  992. break;
  993. case 'epic':
  994. basePrice = 100;
  995. break;
  996. case 'legendary':
  997. basePrice = 150;
  998. break;
  999. default:
  1000. basePrice = 200;
  1001. }
  1002. // 应用便宜技能效果
  1003. const skillManager = SkillManager.getInstance();
  1004. let finalPrice = basePrice;
  1005. if (skillManager) {
  1006. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1007. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1008. }
  1009. label.string = finalPrice.toString();
  1010. }
  1011. // 根据武器配置和方块形状设置价格
  1012. private setBlockPriceByWeaponConfig(block: Node, priceNode: Node) {
  1013. const label = priceNode.getComponent(Label);
  1014. if (!label) {
  1015. return;
  1016. }
  1017. // 获取方块的武器配置
  1018. const weaponConfig = this.getBlockWeaponConfig(block);
  1019. if (!weaponConfig) {
  1020. // 如果没有武器配置,使用原有的稀有度定价方式
  1021. this.setBlockPriceByRarity(priceNode, 'common');
  1022. return;
  1023. }
  1024. // 获取方块形状
  1025. const shapeId = this.getBlockShape(block);
  1026. if (!shapeId) {
  1027. // 如果无法获取形状,使用基础价格
  1028. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common');
  1029. return;
  1030. }
  1031. // 从武器配置中获取局内金币花费配置
  1032. const inGameCostConfig = weaponConfig.inGameCostConfig;
  1033. if (!inGameCostConfig) {
  1034. // 如果没有局内金币配置,使用原有的稀有度定价方式
  1035. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common');
  1036. return;
  1037. }
  1038. // 根据形状获取价格
  1039. let basePrice = inGameCostConfig.shapeCosts[shapeId];
  1040. if (basePrice === undefined) {
  1041. // 如果没有找到对应形状的价格,使用基础价格
  1042. basePrice = inGameCostConfig.baseCost * this.getBlockGridCount(block);
  1043. }
  1044. // 应用便宜技能效果
  1045. const skillManager = SkillManager.getInstance();
  1046. let finalPrice = basePrice;
  1047. if (skillManager) {
  1048. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1049. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1050. }
  1051. label.string = finalPrice.toString();
  1052. }
  1053. // 计算方块占用的格子数量
  1054. private getBlockGridCount(block: Node): number {
  1055. const parts = this.getBlockParts(block);
  1056. return parts.length;
  1057. }
  1058. // 设置方块的武器外观
  1059. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  1060. // 确保方块节点上也有 weaponConfig 属性
  1061. block['weaponConfig'] = weaponConfig;
  1062. // 设置方块的稀有度颜色
  1063. this.setBlockRarityColor(block, weaponConfig.rarity || 'common');
  1064. // 加载武器图标
  1065. this.loadWeaponIcon(block, weaponConfig);
  1066. }
  1067. // 设置方块稀有度颜色
  1068. private setBlockRarityColor(block: Node, rarity: string) {
  1069. this.applyBlockRarityColor(block, rarity);
  1070. }
  1071. // 公共方法:应用方块稀有度颜色(供外部调用)
  1072. public applyBlockRarityColor(block: Node, rarity: string) {
  1073. // Add null safety check for block
  1074. if (!block || !block.isValid) {
  1075. return;
  1076. }
  1077. const sprite = block.getComponent(Sprite);
  1078. if (!sprite || !sprite.isValid) {
  1079. return;
  1080. }
  1081. // 根据稀有度设置颜色
  1082. let color: Color;
  1083. switch (rarity) {
  1084. case 'common':
  1085. color = new Color(255, 255, 255); // 白色
  1086. break;
  1087. case 'uncommon':
  1088. color = new Color(0, 255, 0); // 绿色
  1089. break;
  1090. case 'rare':
  1091. color = new Color(0, 100, 255); // 蓝色
  1092. break;
  1093. case 'epic':
  1094. color = new Color(160, 32, 240); // 紫色
  1095. break;
  1096. case 'legendary':
  1097. color = new Color(255, 165, 0); // 橙色
  1098. break;
  1099. default:
  1100. color = new Color(255, 255, 255); // 默认白色
  1101. }
  1102. sprite.color = color;
  1103. console.log(`[BlockManager] 设置方块稀有度颜色: ${rarity}`, color);
  1104. }
  1105. // 加载武器图标
  1106. private loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  1107. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  1108. const b1Node = block.getChildByName('B1');
  1109. if (!b1Node) {
  1110. console.warn('找不到B1节点');
  1111. return;
  1112. }
  1113. const weaponNode = b1Node.getChildByName('Weapon');
  1114. if (!weaponNode) {
  1115. console.warn('找不到Weapon节点');
  1116. return;
  1117. }
  1118. const weaponSprite = weaponNode.getComponent(Sprite);
  1119. if (!weaponSprite) {
  1120. console.warn('Weapon节点上没有Sprite组件');
  1121. return;
  1122. }
  1123. // 获取武器配置中的图片路径
  1124. const spriteConfig = weaponConfig.visualConfig?.weaponSprites;
  1125. if (!spriteConfig) {
  1126. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  1127. return;
  1128. }
  1129. // 获取方块的形状ID
  1130. const blockShapeId = this.getBlockShape(block);
  1131. // 根据方块形状选择合适的图片路径
  1132. let spritePath = null;
  1133. if (blockShapeId && spriteConfig[blockShapeId]) {
  1134. spritePath = spriteConfig[blockShapeId];
  1135. } else {
  1136. // 如果没有找到对应形状的图片,使用备用顺序
  1137. spritePath = spriteConfig['I'] || spriteConfig['H-I'] || spriteConfig['L'] || spriteConfig['S'] || spriteConfig['D-T'];
  1138. }
  1139. if (!spritePath) {
  1140. console.warn(`武器 ${weaponConfig.name} 没有可用的图片路径`);
  1141. return;
  1142. }
  1143. // 正确的SpriteFrame子资源路径
  1144. const spriteFramePath = `${spritePath}/spriteFrame`;
  1145. // 加载SpriteFrame子资源
  1146. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  1147. if (err) {
  1148. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  1149. return;
  1150. }
  1151. // Add comprehensive null safety checks before setting spriteFrame
  1152. if (weaponSprite && weaponSprite.isValid &&
  1153. weaponNode && weaponNode.isValid &&
  1154. block && block.isValid &&
  1155. spriteFrame && spriteFrame.isValid) {
  1156. weaponSprite.spriteFrame = spriteFrame;
  1157. // 检查方块是否在kuang区域,如果是则缩放植物图标至0.45倍
  1158. const blockLocation = this.blockLocations.get(block);
  1159. if (blockLocation === 'kuang') {
  1160. weaponNode.setScale(0.45, 0.45, 1);
  1161. console.log(`[BlockManager] 设置kuang区域植物图标缩放: 0.45倍`);
  1162. }
  1163. // 应用武器图标的位置偏移和旋转
  1164. this.rotateWeaponIconByShape(weaponNode, blockShapeId, weaponConfig.id);
  1165. }
  1166. });
  1167. }
  1168. // 武器类型和方块形状组合的位置偏移配置(相对于方块中心的偏移量)
  1169. private readonly WEAPON_SHAPE_POSITION_OFFSETS: { [weaponId: string]: { [shapeId: string]: { x: number, y: number } } } = {
  1170. 'pea_shooter': {
  1171. 'I': { x: 4, y: -3 }, // 毛豆射手竖条形状,轻微向下偏移
  1172. 'H-I': { x: 0, y: 5 }, // 毛豆射手横条形状,居中
  1173. 'L': { x: 1, y: -10 }, // 毛豆射手L型,轻微向左下偏移
  1174. 'S': { x: 5, y: -1 }, // 毛豆射手S型,轻微向右下偏移
  1175. 'D-T': { x: 4, y: -1 } // 毛豆射手倒T型,轻微向下偏移
  1176. },
  1177. 'sharp_carrot': {
  1178. 'I': { x: 0, y: -1 }, // 尖胡萝卜竖条形状,轻微向下偏移
  1179. 'H-I': { x: 0, y: 0 }, // 尖胡萝卜横条形状,居中
  1180. 'L': { x: -1, y: -7 }, // 尖胡萝卜L型,轻微向左下偏移
  1181. 'S': { x: 1, y: -1 }, // 尖胡萝卜S型,轻微向右下偏移
  1182. 'D-T': { x: 0, y: -1 } // 尖胡萝卜倒T型,轻微向下偏移
  1183. },
  1184. 'saw_grass': {
  1185. 'I': { x: 0, y: -1 }, // 锯齿草竖条形状,轻微向下偏移
  1186. 'H-I': { x: 0, y: 0 }, // 锯齿草横条形状,居中
  1187. 'L': { x: -1, y: -1 }, // 锯齿草L型,轻微向左下偏移
  1188. 'S': { x: 1, y: -1 }, // 锯齿草S型,轻微向右下偏移
  1189. 'D-T': { x: 0, y: -5 } // 锯齿草倒T型,轻微向下偏移
  1190. },
  1191. 'watermelon_bomb': {
  1192. 'I': { x: 0, y: -1 }, // 西瓜炸弹竖条形状,轻微向下偏移
  1193. 'H-I': { x: 0, y: 0 }, // 西瓜炸弹横条形状,居中
  1194. 'L': { x: -1, y: -1 }, // 西瓜炸弹L型,轻微向左下偏移
  1195. 'S': { x: 1, y: -1 }, // 西瓜炸弹S型,轻微向右下偏移
  1196. 'D-T': { x: 0, y: -7 } // 西瓜炸弹倒T型,轻微向下偏移
  1197. },
  1198. 'boomerang_plant': {
  1199. 'I': { x: 0, y: -1 }, // 回旋镖植物竖条形状,轻微向下偏移
  1200. 'H-I': { x: 0, y: 0 }, // 回旋镖植物横条形状,居中
  1201. 'L': { x: -1, y: -8 }, // 回旋镖植物L型,轻微向左下偏移
  1202. 'S': { x: 1, y: -1 }, // 回旋镖植物S型,轻微向右下偏移
  1203. 'D-T': { x: -10, y: -13 } // 回旋镖植物倒T型,轻微向下偏移
  1204. },
  1205. 'hot_pepper': {
  1206. 'I': { x: 0, y: 5 }, // 辣椒竖条形状,轻微向下偏移
  1207. 'H-I': { x: 0, y: 0 }, // 辣椒横条形状,居中
  1208. 'L': { x: -1, y: -1 }, // 辣椒L型,轻微向左下偏移
  1209. 'S': { x: 1, y: -1 }, // 辣椒S型,轻微向右下偏移
  1210. 'D-T': { x: 0, y: 0 } // 辣椒倒T型,轻微向下偏移
  1211. },
  1212. 'cactus_shotgun': {
  1213. 'I': { x: 0, y: -1 }, // 仙人掌霰弹枪竖条形状,轻微向下偏移
  1214. 'H-I': { x: 0, y: 0 }, // 仙人掌霰弹枪横条形状,居中
  1215. 'L': { x: -1, y: -3 }, // 仙人掌霰弹枪L型,轻微向左下偏移
  1216. 'S': { x: 1, y: -1 }, // 仙人掌霰弹枪S型,轻微向右下偏移
  1217. 'D-T': { x: 0, y: -1 } // 仙人掌霰弹枪倒T型,轻微向下偏移
  1218. },
  1219. 'okra_missile': {
  1220. 'I': { x: -4, y:3 }, // 秋葵导弹竖条形状,轻微向下偏移
  1221. 'H-I': { x: 0, y: -3 }, // 秋葵导弹横条形状,居中
  1222. 'L': { x: -1, y: -9 }, // 秋葵导弹L型,轻微向左下偏移
  1223. 'S': { x: -6, y: 0 }, // 秋葵导弹S型,轻微向右下偏移
  1224. 'D-T': { x: -3, y: 3 } // 秋葵导弹倒T型,轻微向下偏移
  1225. },
  1226. 'mace_club': {
  1227. 'I': { x: 0, y: -1 }, // 狼牙棒竖条形状,轻微向下偏移
  1228. 'H-I': { x: 1, y: 0 }, // 狼牙棒横条形状,居中
  1229. 'L': { x: -1, y: -1 }, // 狼牙棒L型,轻微向左下偏移
  1230. 'S': { x: 1, y: -1 }, // 狼牙棒S型,轻微向右下偏移
  1231. 'D-T': { x: 0, y: -5 } // 狼牙棒倒T型,轻微向下偏移
  1232. }
  1233. };
  1234. // 默认位置偏移配置(当武器类型未配置时使用)
  1235. private readonly DEFAULT_SHAPE_POSITION_OFFSETS: { [key: string]: { x: number, y: number } } = {
  1236. 'I': { x: 0, y: -1 }, // 竖条形状,轻微向下偏移
  1237. 'H-I': { x: 0, y: 0 }, // 横I型,居中
  1238. 'L': { x: -1, y: -1 }, // L型,轻微向左下偏移
  1239. 'S': { x: 1, y: -1 }, // S型,轻微向右下偏移
  1240. 'D-T': { x: 0, y: -1 } // 倒T型,轻微向下偏移
  1241. };
  1242. // 武器类型和方块形状组合的旋转角度配置
  1243. private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
  1244. 'pea_shooter': {
  1245. 'I': 0, // 毛豆射手竖条形状
  1246. 'H-I': 90, // 毛豆射手横条形状
  1247. 'L': 0, // 毛豆射手L型
  1248. 'S': 0, // 毛豆射手S型
  1249. 'D-T': 0 // 毛豆射手倒T型
  1250. },
  1251. 'sharp_carrot': {
  1252. 'I': 0, // 尖胡萝卜竖条形状
  1253. 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
  1254. 'L': -15, // 尖胡萝卜L型,轻微调整
  1255. 'S': 15, // 尖胡萝卜S型,轻微调整
  1256. 'D-T': 0 // 尖胡萝卜倒T型
  1257. },
  1258. 'saw_grass': {
  1259. 'I': 0, // 锯齿草竖条形状
  1260. 'H-I': 0, // 锯齿草横条形状
  1261. 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
  1262. 'S': 30, // 锯齿草S型,适配锯齿弯曲
  1263. 'D-T': 0 // 锯齿草倒T型
  1264. },
  1265. 'watermelon_bomb': {
  1266. 'I': 0, // 西瓜炸弹竖条形状
  1267. 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
  1268. 'L': 0, // 西瓜炸弹L型
  1269. 'S': 0, // 西瓜炸弹S型
  1270. 'D-T': 0 // 西瓜炸弹倒T型
  1271. },
  1272. 'boomerang_plant': {
  1273. 'I': 0, // 回旋镖植物竖条形状
  1274. 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
  1275. 'L': -30, // 回旋镖植物L型
  1276. 'S': -10, // 回旋镖植物S型,适配回旋轨迹
  1277. 'D-T': -80 // 回旋镖植物倒T型
  1278. },
  1279. 'hot_pepper': {
  1280. 'I': 0, // 辣椒竖条形状
  1281. 'H-I': 90, // 辣椒横条形状
  1282. 'L': 0, // 辣椒L型
  1283. 'S': 0, // 辣椒S型
  1284. 'D-T': 0 // 辣椒倒T型
  1285. },
  1286. 'cactus_shotgun': {
  1287. 'I': 0, // 仙人掌霰弹枪竖条形状
  1288. 'H-I': 90, // 仙人掌霰弹枪横条形状
  1289. 'L': -20, // 仙人掌霰弹枪L型
  1290. 'S': 20, // 仙人掌霰弹枪S型
  1291. 'D-T': 0 // 仙人掌霰弹枪倒T型
  1292. },
  1293. 'okra_missile': {
  1294. 'I': 0, // 秋葵导弹竖条形状
  1295. 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
  1296. 'L': -10, // 秋葵导弹L型
  1297. 'S': 10, // 秋葵导弹S型
  1298. 'D-T': 0 // 秋葵导弹倒T型
  1299. },
  1300. 'mace_club': {
  1301. 'I': -45, // 狼牙棒竖条形状
  1302. 'H-I': 0, // 狼牙棒横条形状
  1303. 'L': -90, // 狼牙棒L型,适配棒状武器
  1304. 'S': -90, // 狼牙棒S型
  1305. 'D-T': 0 // 狼牙棒倒T型
  1306. }
  1307. };
  1308. // 默认旋转角度配置(当武器类型未配置时使用)
  1309. private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
  1310. 'I': 0, // 竖条形状,保持原始方向
  1311. 'H-I': 90, // 横I型,旋转90度适配水平方向
  1312. 'L': -15, // L型,轻微左倾适配L形状的转角
  1313. 'S': 15, // S型,轻微右倾适配S形状的弯曲
  1314. 'D-T': 0 // 倒T型,保持原始方向
  1315. };
  1316. // 根据武器类型和方块形状调整武器图标位置和旋转
  1317. private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1318. if (!weaponNode || !shapeId) return;
  1319. let rotationAngle = 0;
  1320. let positionOffset = { x: 0, y: 0 };
  1321. // 如果提供了武器ID,尝试获取特定武器的配置
  1322. if (weaponId && this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1323. rotationAngle = this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1324. positionOffset = this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]?.[shapeId] || { x: 0, y: 0 };
  1325. console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定配置: 旋转${rotationAngle}度, 偏移(${positionOffset.x}, ${positionOffset.y})`);
  1326. } else {
  1327. // 使用默认配置
  1328. rotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1329. positionOffset = this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] || { x: 0, y: 0 };
  1330. console.log(`为形状 ${shapeId} 设置默认配置: 旋转${rotationAngle}度, 偏移(${positionOffset.x}, ${positionOffset.y})`);
  1331. }
  1332. // 应用旋转
  1333. weaponNode.setRotationFromEuler(0, 0, rotationAngle);
  1334. // 应用位置偏移
  1335. const currentPos = weaponNode.position;
  1336. weaponNode.setPosition(currentPos.x + positionOffset.x, currentPos.y + positionOffset.y, currentPos.z);
  1337. }
  1338. // 设置特定武器和形状的旋转角度
  1339. public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
  1340. if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1341. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
  1342. }
  1343. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
  1344. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1345. }
  1346. // 设置默认形状的旋转角度
  1347. public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
  1348. this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
  1349. console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1350. }
  1351. // 设置特定武器和形状的位置偏移
  1352. public setWeaponShapePositionOffset(weaponId: string, shapeId: string, offset: { x: number, y: number }) {
  1353. if (!this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]) {
  1354. this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId] = {};
  1355. }
  1356. this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId][shapeId] = offset;
  1357. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的位置偏移为: (${offset.x}, ${offset.y})`);
  1358. }
  1359. // 设置默认形状的位置偏移
  1360. public setDefaultShapePositionOffset(shapeId: string, offset: { x: number, y: number }) {
  1361. this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] = offset;
  1362. console.log(`已更新默认形状 ${shapeId} 的位置偏移为: (${offset.x}, ${offset.y})`);
  1363. }
  1364. // 获取特定武器和形状的旋转角度
  1365. public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
  1366. if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1367. return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1368. }
  1369. return 0;
  1370. }
  1371. // 获取默认形状的旋转角度
  1372. public getDefaultShapeRotationAngle(shapeId: string): number {
  1373. return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1374. }
  1375. // 获取特定武器和形状的位置偏移
  1376. public getWeaponShapePositionOffset(weaponId: string, shapeId: string): { x: number, y: number } {
  1377. if (this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId]) {
  1378. return this.WEAPON_SHAPE_POSITION_OFFSETS[weaponId][shapeId] || { x: 0, y: 0 };
  1379. }
  1380. return { x: 0, y: 0 };
  1381. }
  1382. // 获取默认形状的位置偏移
  1383. public getDefaultShapePositionOffset(shapeId: string): { x: number, y: number } {
  1384. return this.DEFAULT_SHAPE_POSITION_OFFSETS[shapeId] || { x: 0, y: 0 };
  1385. }
  1386. // 同时设置特定武器和形状的位置偏移和旋转角度
  1387. public setWeaponShapeTransform(weaponId: string, shapeId: string, offset: { x: number, y: number }, angle: number) {
  1388. this.setWeaponShapePositionOffset(weaponId, shapeId, offset);
  1389. this.setWeaponShapeRotationAngle(weaponId, shapeId, angle);
  1390. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的完整变换: 偏移(${offset.x}, ${offset.y}), 旋转${angle}度`);
  1391. }
  1392. // 同时设置默认形状的位置偏移和旋转角度
  1393. public setDefaultShapeTransform(shapeId: string, offset: { x: number, y: number }, angle: number) {
  1394. this.setDefaultShapePositionOffset(shapeId, offset);
  1395. this.setDefaultShapeRotationAngle(shapeId, angle);
  1396. console.log(`已更新默认形状 ${shapeId} 的完整变换: 偏移(${offset.x}, ${offset.y}), 旋转${angle}度`);
  1397. }
  1398. // 重新应用所有已放置方块的武器图标位置和旋转
  1399. public refreshAllWeaponIconRotations() {
  1400. // 遍历所有已放置的方块
  1401. if (this.placedBlocksContainer) {
  1402. this.placedBlocksContainer.children.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. // 遍历kuang区域的方块
  1417. this.blocks.forEach(block => {
  1418. const weaponConfig = this.getBlockWeaponConfig(block);
  1419. if (weaponConfig) {
  1420. const b1Node = block.getChildByName('B1');
  1421. if (b1Node) {
  1422. const weaponNode = b1Node.getChildByName('Weapon');
  1423. if (weaponNode) {
  1424. const shapeId = this.getBlockShape(block);
  1425. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1426. }
  1427. }
  1428. }
  1429. });
  1430. }
  1431. // 根据方块获取武器配置
  1432. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  1433. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  1434. }
  1435. // 获取方块的武器ID
  1436. public getBlockWeaponId(block: Node): string | null {
  1437. const weaponConfig = this.getBlockWeaponConfig(block);
  1438. return weaponConfig ? weaponConfig.id : null;
  1439. }
  1440. // 获取方块的形状
  1441. public getBlockShape(block: Node): string | null {
  1442. const weaponConfig = this.getBlockWeaponConfig(block);
  1443. if (!weaponConfig) return null;
  1444. // 从方块结构推断形状
  1445. return this.inferBlockShapeFromStructure(block);
  1446. }
  1447. // 获取方块的详细形状信息(包括形状ID和名称)
  1448. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  1449. const actualShape = this.extractShapeFromBlock(block);
  1450. let blockShapes = null;
  1451. // 优先使用预加载的配置
  1452. if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
  1453. blockShapes = this.preloadedWeaponsConfig.blockSizes;
  1454. } else {
  1455. // 回退到ConfigManager
  1456. blockShapes = this.configManager.getBlockShapes();
  1457. }
  1458. if (!blockShapes) return null;
  1459. // 寻找匹配的形状配置
  1460. for (const shapeConfig of blockShapes) {
  1461. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1462. return {
  1463. id: shapeConfig.id,
  1464. name: shapeConfig.name,
  1465. shape: shapeConfig.shape
  1466. };
  1467. }
  1468. }
  1469. return null;
  1470. }
  1471. // 从方块结构推断形状
  1472. private inferBlockShapeFromStructure(block: Node): string {
  1473. const actualShape = this.extractShapeFromBlock(block);
  1474. console.log('[BlockManager] 提取的方块形状矩阵:', actualShape);
  1475. let blockShapes = null;
  1476. // 优先使用预加载的配置
  1477. if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
  1478. blockShapes = this.preloadedWeaponsConfig.blockSizes;
  1479. console.log('[BlockManager] 使用预加载的方块形状配置');
  1480. } else {
  1481. // 回退到ConfigManager
  1482. blockShapes = this.configManager.getBlockShapes();
  1483. console.log('[BlockManager] 使用ConfigManager的方块形状配置');
  1484. }
  1485. if (!blockShapes || blockShapes.length === 0) {
  1486. console.warn('[BlockManager] 无法获取方块形状配置,使用默认形状I');
  1487. console.warn('[BlockManager] 配置状态 - isConfigLoaded:', this.configManager.isConfigLoaded());
  1488. console.warn('[BlockManager] 配置状态 - weaponsConfig存在:', !!this.configManager['weaponsConfig']);
  1489. console.warn('[BlockManager] 配置状态 - 预加载状态:', this.isWeaponsConfigPreloaded);
  1490. if (this.configManager['weaponsConfig']) {
  1491. console.warn('[BlockManager] 配置状态 - blockSizes存在:', !!this.configManager['weaponsConfig'].blockSizes);
  1492. }
  1493. return 'I';
  1494. }
  1495. console.log(`[BlockManager] 开始匹配形状,共有${blockShapes.length}个配置形状`);
  1496. // 寻找匹配的形状配置
  1497. for (const shapeConfig of blockShapes) {
  1498. console.log(`[BlockManager] 尝试匹配形状: ${shapeConfig.id} (${shapeConfig.name})`);
  1499. console.log(`[BlockManager] 配置形状矩阵:`, shapeConfig.shape);
  1500. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1501. console.log(`[BlockManager] ✅ 识别方块形状: ${shapeConfig.id} (${shapeConfig.name})`);
  1502. return shapeConfig.id;
  1503. }
  1504. }
  1505. console.warn('[BlockManager] 未找到匹配的形状配置,使用默认形状I');
  1506. return 'I';
  1507. }
  1508. // 寻找与目标形状匹配的预制体
  1509. private findMatchingPrefab(targetShape: any): Prefab | null {
  1510. for (const prefab of this.blockPrefabs) {
  1511. if (this.doesPrefabMatchShape(prefab, targetShape)) {
  1512. return prefab;
  1513. }
  1514. }
  1515. return null;
  1516. }
  1517. // 检查预制体是否匹配指定形状
  1518. private doesPrefabMatchShape(prefab: Prefab, targetShape: any): boolean {
  1519. // 创建临时实例来检查形状
  1520. const tempBlock = instantiate(prefab);
  1521. const parts = this.getBlockParts(tempBlock);
  1522. const actualShape = this.extractShapeFromBlock(tempBlock);
  1523. tempBlock.destroy();
  1524. // 比较形状矩阵
  1525. const matches = this.compareShapeMatrices(actualShape, targetShape.shape);
  1526. return matches;
  1527. }
  1528. // 从方块实例中提取形状矩阵
  1529. private extractShapeFromBlock(block: Node): number[][] {
  1530. const parts = this.getBlockParts(block);
  1531. // 创建4x4矩阵
  1532. const matrix: number[][] = [];
  1533. for (let i = 0; i < 4; i++) {
  1534. matrix[i] = [0, 0, 0, 0];
  1535. }
  1536. // 找到最小坐标作为偏移基准
  1537. let minX = 0, minY = 0;
  1538. for (const part of parts) {
  1539. minX = Math.min(minX, part.x);
  1540. minY = Math.min(minY, part.y);
  1541. }
  1542. // 填充矩阵,将坐标标准化到从(0,0)开始
  1543. for (const part of parts) {
  1544. const matrixX = part.x - minX;
  1545. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  1546. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  1547. matrix[matrixY][matrixX] = 1;
  1548. }
  1549. }
  1550. // 对矩阵进行上下翻转(交换第0行和第1行)
  1551. const temp = matrix[0];
  1552. matrix[0] = matrix[1];
  1553. matrix[1] = temp;
  1554. return matrix;
  1555. }
  1556. // 比较两个形状矩阵是否相同
  1557. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  1558. if (matrix1.length !== matrix2.length) return false;
  1559. for (let i = 0; i < matrix1.length; i++) {
  1560. if (matrix1[i].length !== matrix2[i].length) return false;
  1561. for (let j = 0; j < matrix1[i].length; j++) {
  1562. if (matrix1[i][j] !== matrix2[i][j]) return false;
  1563. }
  1564. }
  1565. return true;
  1566. }
  1567. // 检查两个方块是否可以合成(相同形状相同种类)
  1568. private canMergeBlocks(block1: Node, block2: Node): boolean {
  1569. // 检查稀有度
  1570. const rarity1 = this.getBlockRarity(block1);
  1571. const rarity2 = this.getBlockRarity(block2);
  1572. if (rarity1 !== rarity2) {
  1573. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  1574. return false;
  1575. }
  1576. // 检查武器ID(种类)
  1577. const weaponId1 = this.getBlockWeaponId(block1);
  1578. const weaponId2 = this.getBlockWeaponId(block2);
  1579. if (weaponId1 !== weaponId2) {
  1580. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  1581. return false;
  1582. }
  1583. // 使用精确的形状矩阵比较
  1584. const shape1 = this.extractShapeFromBlock(block1);
  1585. const shape2 = this.extractShapeFromBlock(block2);
  1586. if (!this.compareShapeMatrices(shape1, shape2)) {
  1587. console.log(`[BlockManager] 形状矩阵不匹配`);
  1588. return false;
  1589. }
  1590. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  1591. return true;
  1592. }
  1593. // 刷新方块 - 重新生成三个新的武器方块
  1594. public refreshBlocks() {
  1595. // 移除PlacedBlocks容器中所有方块的标签
  1596. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1597. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1598. }
  1599. // 保存已放置方块的占用信息
  1600. const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  1601. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1602. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1603. const block = this.placedBlocksContainer.children[i];
  1604. const occupiedGrids = block['occupiedGrids'];
  1605. if (occupiedGrids && occupiedGrids.length > 0) {
  1606. placedBlocksOccupation.push({
  1607. block: block,
  1608. occupiedGrids: [...occupiedGrids]
  1609. });
  1610. }
  1611. }
  1612. }
  1613. // 生成新的方块
  1614. this.generateRandomBlocksInKuang();
  1615. }
  1616. // 检查是否有已放置的方块
  1617. public hasPlacedBlocks(): boolean {
  1618. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1619. console.log('[BlockManager] PlacedBlocks容器无效');
  1620. return false;
  1621. }
  1622. const blockCount = this.placedBlocksContainer.children.length;
  1623. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1624. // 检查容器中是否有子节点(方块)
  1625. return blockCount > 0;
  1626. }
  1627. /* =================== 合成逻辑 =================== */
  1628. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  1629. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1630. public async tryMergeBlock(block: Node) {
  1631. try {
  1632. const rarity = this.getBlockRarity(block);
  1633. if (!rarity) return;
  1634. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1635. if (!this.placedBlocksContainer) return;
  1636. const blockBB = this.getWorldAABB(block);
  1637. for (const other of this.placedBlocksContainer.children) {
  1638. if (other === block) continue;
  1639. // 使用新的合成检查方法
  1640. if (!this.canMergeBlocks(block, other)) continue;
  1641. const otherBB = this.getWorldAABB(other);
  1642. if (this.rectIntersects(blockBB, otherBB)) {
  1643. // 找到合成目标
  1644. await this.performMerge(block, other, rarity);
  1645. break;
  1646. }
  1647. }
  1648. } catch (error) {
  1649. console.error('[BlockManager] tryMergeBlock 发生错误:', error);
  1650. // 合成失败不影响游戏继续,只记录错误
  1651. }
  1652. }
  1653. private async performMerge(target: Node, source: Node, rarity: string) {
  1654. try {
  1655. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1656. // 隐藏价格标签并处理 db 关联
  1657. this.hidePriceLabel(source);
  1658. const srcDb = source['dbNode'];
  1659. if (srcDb) srcDb.active = false;
  1660. // 销毁被合并方块
  1661. source.destroy();
  1662. // 升级稀有度
  1663. const nextRarity = this.getNextRarity(rarity);
  1664. if (nextRarity) {
  1665. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1666. // 获取当前武器配置
  1667. const currentConfig = this.blockWeaponConfigs.get(target);
  1668. if (currentConfig) {
  1669. // 保存原始武器名称用于日志输出
  1670. const originalWeaponName = currentConfig.name;
  1671. try {
  1672. // 获取当前关卡允许的武器列表
  1673. const levelWeapons = await this.getCurrentLevelWeapons();
  1674. // 检查是否应该限制在关卡配置的武器范围内
  1675. if (levelWeapons.length > 0) {
  1676. // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
  1677. if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
  1678. console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
  1679. }
  1680. // 无论如何,都只升级稀有度,不改变武器类型
  1681. const upgradedConfig = { ...currentConfig };
  1682. upgradedConfig.rarity = nextRarity;
  1683. this.blockWeaponConfigs.set(target, upgradedConfig);
  1684. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1685. (target as any)['weaponConfig'] = upgradedConfig;
  1686. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1687. } else {
  1688. // 如果没有关卡配置限制,正常升级稀有度
  1689. const upgradedConfig = { ...currentConfig };
  1690. upgradedConfig.rarity = nextRarity;
  1691. this.blockWeaponConfigs.set(target, upgradedConfig);
  1692. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1693. (target as any)['weaponConfig'] = upgradedConfig;
  1694. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1695. }
  1696. } catch (weaponError) {
  1697. console.error('[BlockManager] 获取关卡武器配置失败:', weaponError);
  1698. // 武器配置获取失败时,仍然升级稀有度
  1699. const upgradedConfig = { ...currentConfig };
  1700. upgradedConfig.rarity = nextRarity;
  1701. this.blockWeaponConfigs.set(target, upgradedConfig);
  1702. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1703. (target as any)['weaponConfig'] = upgradedConfig;
  1704. console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1705. }
  1706. }
  1707. // 更新方块颜色
  1708. this.setBlockRarityColor(target, nextRarity);
  1709. }
  1710. // 播放烟雾动画
  1711. const worldPos = new Vec3();
  1712. target.getWorldPosition(worldPos);
  1713. this.spawnMergeSmoke(worldPos);
  1714. // 递归检查是否还能继续合成
  1715. if (nextRarity) {
  1716. await this.tryMergeBlock(target);
  1717. }
  1718. console.log(`[BlockManager] 合成完成`);
  1719. } catch (error) {
  1720. console.error('[BlockManager] performMerge 发生错误:', error);
  1721. // 合成失败时重新抛出错误,让上层处理
  1722. throw error;
  1723. }
  1724. }
  1725. private getBlockRarity(block: Node): string | null {
  1726. const cfg = this.blockWeaponConfigs.get(block);
  1727. if (cfg) return cfg.rarity;
  1728. // fallback based on sprite color maybe
  1729. return null;
  1730. }
  1731. private getNextRarity(rarity: string): string | null {
  1732. const idx = this.rarityOrder.indexOf(rarity);
  1733. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1734. return this.rarityOrder[idx + 1];
  1735. }
  1736. private getWorldAABB(node: Node): Rect {
  1737. const ui = node.getComponent(UITransform);
  1738. if (!ui) return new Rect();
  1739. const pos = node.worldPosition;
  1740. const width = ui.width;
  1741. const height = ui.height;
  1742. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1743. }
  1744. private rectIntersects(a: Rect, b: Rect): boolean {
  1745. return a.x < b.x + b.width &&
  1746. a.x + a.width > b.x &&
  1747. a.y < b.y + b.height &&
  1748. a.y + a.height > b.y;
  1749. }
  1750. /** 生成烟雾特效 */
  1751. private spawnMergeSmoke(worldPos: Vec3) {
  1752. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1753. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1754. if (err || !sData) {
  1755. console.warn('加载合成烟雾动画失败', err);
  1756. return;
  1757. }
  1758. const node = new Node('MergeSmoke');
  1759. const skeleton = node.addComponent(sp.Skeleton);
  1760. skeleton.skeletonData = sData;
  1761. skeleton.premultipliedAlpha = false;
  1762. skeleton.setAnimation(0, 'animation', false);
  1763. skeleton.setCompleteListener(() => node.destroy());
  1764. const canvas = find('Canvas');
  1765. if (canvas) canvas.addChild(node);
  1766. node.setWorldPosition(worldPos);
  1767. });
  1768. }
  1769. /** 在放置失败时尝试与现有方块进行合成 */
  1770. public tryMergeOnOverlap(draggedBlock: Node): boolean {
  1771. if (!this.placedBlocksContainer) return false;
  1772. const rarity = this.getBlockRarity(draggedBlock);
  1773. if (!rarity) return false;
  1774. const dragBB = this.getWorldAABB(draggedBlock);
  1775. for (const target of this.placedBlocksContainer.children) {
  1776. if (target === draggedBlock) continue;
  1777. // 使用新的合成检查方法
  1778. if (!this.canMergeBlocks(draggedBlock, target)) continue;
  1779. const targetBB = this.getWorldAABB(target);
  1780. if (this.rectIntersects(dragBB, targetBB)) {
  1781. // 执行合并:目标保留,拖拽方块销毁
  1782. this.performMerge(target, draggedBlock, rarity);
  1783. return true;
  1784. }
  1785. }
  1786. return false;
  1787. }
  1788. // 调试绘制功能已迁移到GameBlockSelection
  1789. // 输出格子占用情况矩阵
  1790. public printGridOccupationMatrix() {
  1791. console.log('[BlockManager] 格子占用情况de矩阵 (6行11列):');
  1792. for (let row = 0; row < this.GRID_ROWS; row++) {
  1793. let rowStr = '';
  1794. for (let col = 0; col < this.GRID_COLS; col++) {
  1795. rowStr += this.gridOccupationMap[row][col] + ' ';
  1796. }
  1797. console.log(`第${row + 1}行: ${rowStr.trim()}`);
  1798. }
  1799. }
  1800. // 通过GameBlockSelection刷新方块占用情况
  1801. onDestroy() {
  1802. // 调试绘制功能已迁移到GameBlockSelection
  1803. // 清理事件监听
  1804. const eventBus = EventBus.getInstance();
  1805. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  1806. eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  1807. // 移除GAME_START事件清理,因为已不再监听该事件
  1808. // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1809. eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  1810. }
  1811. }