BlockManager.ts 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Color, Vec2, UITransform, find, Rect, Label, Size, Sprite, SpriteFrame, resources, Button, Collider2D, Material, tween, JsonAsset } from 'cc';
  2. import { 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. // 预制体数组,存储10个预制体
  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. // 将B1节点本身添加为第一个部分
  729. parts.push({ node: b1Node, x: 0, y: 0 });
  730. // 然后递归查找B1的子节点,但要避免重复添加B1本身
  731. this.findBlockParts(b1Node, parts, 0, 0, true);
  732. } else {
  733. // 没有B1节点,使用根节点作为形状根节点
  734. parts.push({ node: block, x: 0, y: 0 });
  735. this.findBlockParts(block, parts, 0, 0, false);
  736. }
  737. return parts;
  738. }
  739. // 递归查找方块的所有部分
  740. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number, skipRoot: boolean = false) {
  741. for (let i = 0; i < node.children.length; i++) {
  742. const child = node.children[i];
  743. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  744. continue;
  745. }
  746. let x = parentX;
  747. let y = parentY;
  748. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  749. if (match) {
  750. x = parseInt(match[1]);
  751. y = parseInt(match[2]);
  752. result.push({ node: child, x, y });
  753. } else if (child.name.startsWith('B')) {
  754. const relativeX = Math.round(child.position.x / this.gridSpacing);
  755. const relativeY = -Math.round(child.position.y / this.gridSpacing);
  756. x = parentX + relativeX;
  757. y = parentY + relativeY;
  758. // 避免重复添加已经在result中的节点
  759. const existingPart = result.find(part => part.node === child);
  760. if (!existingPart) {
  761. result.push({ node: child, x, y });
  762. }
  763. }
  764. this.findBlockParts(child, result, x, y, false);
  765. }
  766. }
  767. // 标记方块占用的格子
  768. public markOccupiedPositions(block: Node, targetGrid: Node) {
  769. if (!this.gridInitialized) return;
  770. const targetRowCol = this.getGridRowCol(targetGrid);
  771. if (!targetRowCol) return;
  772. const parts = this.getBlockParts(block);
  773. block['occupiedGrids'] = [];
  774. for (const part of parts) {
  775. const row = targetRowCol.row - part.y;
  776. const col = targetRowCol.col + part.x;
  777. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  778. this.gridOccupationMap[row][col] = 1;
  779. block['occupiedGrids'] = block['occupiedGrids'] || [];
  780. block['occupiedGrids'].push({ row, col });
  781. }
  782. }
  783. }
  784. // 清除方块
  785. clearBlocks() {
  786. console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
  787. const blocksToRemove = [];
  788. for (const block of this.blocks) {
  789. if (block.isValid) {
  790. const location = this.blockLocations.get(block);
  791. if (location === 'kuang') {
  792. blocksToRemove.push(block);
  793. }
  794. }
  795. }
  796. console.log('[BlockManager] 找到需要清理的kuang区域方块数量:', blocksToRemove.length);
  797. for (const block of blocksToRemove) {
  798. const dbNode = block['dbNode'];
  799. if (dbNode && dbNode.isValid) {
  800. block.off(Node.EventType.TRANSFORM_CHANGED);
  801. const kuangNode = this.kuangContainer;
  802. if (kuangNode) {
  803. const dbName = dbNode.name;
  804. if (!kuangNode.getChildByName(dbName)) {
  805. dbNode.parent = kuangNode;
  806. }
  807. }
  808. }
  809. const index = this.blocks.indexOf(block);
  810. if (index !== -1) {
  811. this.blocks.splice(index, 1);
  812. }
  813. this.originalPositions.delete(block);
  814. this.blockLocations.delete(block);
  815. this.blockPriceMap.delete(block);
  816. // 清理武器配置映射
  817. this.blockWeaponConfigs.delete(block);
  818. console.log('[BlockManager] 销毁kuang区域方块:', block.name);
  819. block.destroy();
  820. }
  821. console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
  822. }
  823. // 游戏开始时调用
  824. onGameStart() {
  825. this.gameStarted = true;
  826. for (const block of this.blocks) {
  827. if (block.isValid) {
  828. const location = this.blockLocations.get(block);
  829. if (location === 'grid') {
  830. this.hidePriceLabel(block);
  831. const dbNode = block['dbNode'];
  832. if (dbNode) {
  833. dbNode.active = false;
  834. }
  835. this.moveBlockToPlacedBlocks(block);
  836. this.addLockedVisualHint(block);
  837. // 游戏开始后放置的方块移除标签,不能再放回kuang
  838. BlockTag.removeTag(block);
  839. }
  840. }
  841. }
  842. }
  843. // 游戏重置时调用
  844. onGameReset() {
  845. console.log('[BlockManager] 游戏重置,清理所有状态');
  846. console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
  847. this.gameStarted = false;
  848. this.clearAllCooldowns();
  849. // 清理已放置的方块
  850. console.log('[BlockManager] 开始清理已放置的方块');
  851. this.clearPlacedBlocks();
  852. // 重置网格占用状态
  853. console.log('[BlockManager] 开始重置网格占用状态');
  854. this.resetGridOccupation();
  855. // 清理kuang区域的方块
  856. console.log('[BlockManager] 开始清理kuang区域的方块');
  857. this.clearBlocks();
  858. // 清理所有方块标签
  859. console.log('[BlockManager] 开始清理所有方块标签');
  860. BlockTag.clearAllTags();
  861. console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
  862. console.log('[BlockManager] 游戏重置完成 - 方块生成将由StartGame流程处理');
  863. }
  864. // 清理已放置的方块
  865. private clearPlacedBlocks() {
  866. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  867. console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
  868. return;
  869. }
  870. console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
  871. // 清理PlacedBlocks容器中的所有方块
  872. const placedBlocks = [...this.placedBlocksContainer.children];
  873. let clearedCount = 0;
  874. for (const block of placedBlocks) {
  875. if (block && block.isValid) {
  876. // 从blocks数组中移除
  877. const index = this.blocks.indexOf(block);
  878. if (index !== -1) {
  879. this.blocks.splice(index, 1);
  880. }
  881. // 清理相关映射
  882. this.originalPositions.delete(block);
  883. this.blockLocations.delete(block);
  884. this.blockPriceMap.delete(block);
  885. this.blockWeaponConfigs.delete(block);
  886. console.log('[BlockManager] 销毁已放置方块:', block.name);
  887. // 销毁方块
  888. block.destroy();
  889. clearedCount++;
  890. }
  891. }
  892. console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
  893. }
  894. // 重置网格占用状态
  895. public resetGridOccupation() {
  896. console.log('[BlockManager] 重置网格占用状态');
  897. // 重新初始化网格占用地图
  898. this.gridOccupationMap = [];
  899. for (let row = 0; row < this.GRID_ROWS; row++) {
  900. this.gridOccupationMap[row] = [];
  901. for (let col = 0; col < this.GRID_COLS; col++) {
  902. this.gridOccupationMap[row][col] = 0;
  903. }
  904. }
  905. // 清理临时存储的占用状态
  906. this.tempRemovedOccupiedGrids = [];
  907. }
  908. // 添加视觉提示,表明方块已锁定
  909. addLockedVisualHint(block: Node) {
  910. const children = block.children;
  911. for (let i = 0; i < children.length; i++) {
  912. const child = children[i];
  913. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  914. continue;
  915. }
  916. child.setScale(new Vec3(0.95, 0.95, 1));
  917. }
  918. }
  919. // 将方块移动到PlacedBlocks节点下
  920. moveBlockToPlacedBlocks(block: Node) {
  921. if (!this.placedBlocksContainer) {
  922. console.error('PlacedBlocks容器未设置');
  923. return;
  924. }
  925. if (!this.placedBlocksContainer.isValid) {
  926. console.error('PlacedBlocks容器已失效');
  927. return;
  928. }
  929. const worldPosition = new Vec3();
  930. block.getWorldPosition(worldPosition);
  931. // 移除旧的触摸事件监听器
  932. block.off(Node.EventType.TOUCH_START);
  933. block.off(Node.EventType.TOUCH_MOVE);
  934. block.off(Node.EventType.TOUCH_END);
  935. block.off(Node.EventType.TOUCH_CANCEL);
  936. block.removeFromParent();
  937. this.placedBlocksContainer.addChild(block);
  938. block.setWorldPosition(worldPosition);
  939. // 通过事件机制重新设置拖拽事件
  940. const eventBus = EventBus.getInstance();
  941. eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]);
  942. console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`);
  943. }
  944. // 根据武器配置选择合适的预制体
  945. private selectPrefabForWeapon(weaponConfig: WeaponConfig): Prefab | null {
  946. if (this.blockPrefabs.length === 0) {
  947. return null;
  948. }
  949. // 简化逻辑:直接使用随机预制体,避免复杂的形状匹配
  950. // 这样可以避免形状匹配失败导致的问题,同时保持游戏的随机性
  951. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  952. const selectedPrefab = this.blockPrefabs[randomIndex];
  953. console.log(`[BlockManager] 为武器 ${weaponConfig.name} 选择随机预制体 (索引: ${randomIndex})`);
  954. return selectedPrefab;
  955. }
  956. // 根据稀有度设置方块价格
  957. private setBlockPriceByRarity(priceNode: Node, rarity: string) {
  958. const label = priceNode.getComponent(Label);
  959. if (!label) {
  960. return;
  961. }
  962. let basePrice: number;
  963. switch (rarity) {
  964. case 'common':
  965. basePrice = 10;
  966. break;
  967. case 'uncommon':
  968. basePrice = 20;
  969. break;
  970. case 'rare':
  971. basePrice = 50;
  972. break;
  973. case 'epic':
  974. basePrice = 100;
  975. break;
  976. case 'legendary':
  977. basePrice = 150;
  978. break;
  979. default:
  980. basePrice = 200;
  981. }
  982. // 应用便宜技能效果
  983. const skillManager = SkillManager.getInstance();
  984. let finalPrice = basePrice;
  985. if (skillManager) {
  986. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  987. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  988. }
  989. label.string = finalPrice.toString();
  990. }
  991. // 根据武器配置和方块形状设置价格
  992. private setBlockPriceByWeaponConfig(block: Node, priceNode: Node) {
  993. const label = priceNode.getComponent(Label);
  994. if (!label) {
  995. return;
  996. }
  997. // 获取方块的武器配置
  998. const weaponConfig = this.getBlockWeaponConfig(block);
  999. if (!weaponConfig) {
  1000. // 如果没有武器配置,使用原有的稀有度定价方式
  1001. this.setBlockPriceByRarity(priceNode, 'common');
  1002. return;
  1003. }
  1004. // 获取方块形状
  1005. const shapeId = this.getBlockShape(block);
  1006. if (!shapeId) {
  1007. // 如果无法获取形状,使用基础价格
  1008. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common');
  1009. return;
  1010. }
  1011. // 从武器配置中获取局内金币花费配置
  1012. const inGameCostConfig = weaponConfig.inGameCostConfig;
  1013. if (!inGameCostConfig) {
  1014. // 如果没有局内金币配置,使用原有的稀有度定价方式
  1015. this.setBlockPriceByRarity(priceNode, weaponConfig.rarity || 'common');
  1016. return;
  1017. }
  1018. // 根据形状获取价格
  1019. let basePrice = inGameCostConfig.shapeCosts[shapeId];
  1020. if (basePrice === undefined) {
  1021. // 如果没有找到对应形状的价格,使用基础价格
  1022. basePrice = inGameCostConfig.baseCost * this.getBlockGridCount(block);
  1023. }
  1024. // 应用便宜技能效果
  1025. const skillManager = SkillManager.getInstance();
  1026. let finalPrice = basePrice;
  1027. if (skillManager) {
  1028. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  1029. finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
  1030. }
  1031. label.string = finalPrice.toString();
  1032. }
  1033. // 计算方块占用的格子数量
  1034. private getBlockGridCount(block: Node): number {
  1035. const parts = this.getBlockParts(block);
  1036. return parts.length;
  1037. }
  1038. // 设置方块的武器外观
  1039. private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig) {
  1040. // 确保方块节点上也有 weaponConfig 属性
  1041. block['weaponConfig'] = weaponConfig;
  1042. // 设置方块的稀有度颜色
  1043. this.setBlockRarityColor(block, weaponConfig.rarity || 'common');
  1044. // 加载武器图标
  1045. this.loadWeaponIcon(block, weaponConfig);
  1046. }
  1047. // 设置方块稀有度颜色
  1048. private setBlockRarityColor(block: Node, rarity: string) {
  1049. this.applyBlockRarityColor(block, rarity);
  1050. }
  1051. // 公共方法:应用方块稀有度颜色(供外部调用)
  1052. public applyBlockRarityColor(block: Node, rarity: string) {
  1053. // Add null safety check for block
  1054. if (!block || !block.isValid) {
  1055. return;
  1056. }
  1057. const sprite = block.getComponent(Sprite);
  1058. if (!sprite || !sprite.isValid) {
  1059. return;
  1060. }
  1061. // 根据稀有度设置颜色
  1062. let color: Color;
  1063. switch (rarity) {
  1064. case 'common':
  1065. color = new Color(255, 255, 255); // 白色
  1066. break;
  1067. case 'uncommon':
  1068. color = new Color(0, 255, 0); // 绿色
  1069. break;
  1070. case 'rare':
  1071. color = new Color(0, 100, 255); // 蓝色
  1072. break;
  1073. case 'epic':
  1074. color = new Color(160, 32, 240); // 紫色
  1075. break;
  1076. case 'legendary':
  1077. color = new Color(255, 165, 0); // 橙色
  1078. break;
  1079. default:
  1080. color = new Color(255, 255, 255); // 默认白色
  1081. }
  1082. sprite.color = color;
  1083. console.log(`[BlockManager] 设置方块稀有度颜色: ${rarity}`, color);
  1084. }
  1085. // 加载武器图标
  1086. private async loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
  1087. // 根据预制体结构:WeaponBlock -> B1 -> Weapon
  1088. const b1Node = block.getChildByName('B1');
  1089. if (!b1Node) {
  1090. console.warn('找不到B1节点');
  1091. return;
  1092. }
  1093. const weaponNode = b1Node.getChildByName('Weapon');
  1094. if (!weaponNode) {
  1095. console.warn('找不到Weapon节点');
  1096. return;
  1097. }
  1098. const weaponSprite = weaponNode.getComponent(Sprite);
  1099. if (!weaponSprite) {
  1100. console.warn('Weapon节点上没有Sprite组件');
  1101. return;
  1102. }
  1103. // 获取武器配置中的图片路径
  1104. const spritePath = weaponConfig.visualConfig?.weaponSprites;
  1105. if (!spritePath) {
  1106. console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
  1107. return;
  1108. }
  1109. // 正确的SpriteFrame子资源路径
  1110. const spriteFramePath = `${spritePath}/spriteFrame`;
  1111. // 加载SpriteFrame子资源
  1112. resources.load(spriteFramePath, SpriteFrame, (err, spriteFrame) => {
  1113. if (err) {
  1114. console.warn(`加载武器图片失败: ${spriteFramePath}`, err);
  1115. return;
  1116. }
  1117. // Add comprehensive null safety checks before setting spriteFrame
  1118. if (weaponSprite && weaponSprite.isValid &&
  1119. weaponNode && weaponNode.isValid &&
  1120. block && block.isValid &&
  1121. spriteFrame && spriteFrame.isValid) {
  1122. weaponSprite.spriteFrame = spriteFrame;
  1123. // 武器图标已加载
  1124. // 应用武器图标的旋转(不再使用位置偏移)
  1125. const blockShape = this.getBlockShape(block);
  1126. this.rotateWeaponIconByShape(weaponNode, blockShape, weaponConfig.id);
  1127. }
  1128. });
  1129. }
  1130. // 武器类型和方块形状组合的旋转角度配置
  1131. private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
  1132. 'pea_shooter': {
  1133. 'I': 0, // 毛豆射手竖条形状
  1134. 'H-I': 90, // 毛豆射手横条形状
  1135. 'L': 0, // 毛豆射手L型
  1136. 'S': 0, // 毛豆射手S型
  1137. 'D-T': 0 // 毛豆射手倒T型
  1138. },
  1139. 'sharp_carrot': {
  1140. 'I': 0, // 尖胡萝卜竖条形状
  1141. 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
  1142. 'L': -15, // 尖胡萝卜L型,轻微调整
  1143. 'S': 15, // 尖胡萝卜S型,轻微调整
  1144. 'D-T': 0 // 尖胡萝卜倒T型
  1145. },
  1146. 'saw_grass': {
  1147. 'I': 0, // 锯齿草竖条形状
  1148. 'H-I': 0, // 锯齿草横条形状
  1149. 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
  1150. 'S': 30, // 锯齿草S型,适配锯齿弯曲
  1151. 'D-T': 0 // 锯齿草倒T型
  1152. },
  1153. 'watermelon_bomb': {
  1154. 'I': 0, // 西瓜炸弹竖条形状
  1155. 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
  1156. 'L': 0, // 西瓜炸弹L型
  1157. 'S': 0, // 西瓜炸弹S型
  1158. 'D-T': 0 // 西瓜炸弹倒T型
  1159. },
  1160. 'boomerang_plant': {
  1161. 'I': 0, // 回旋镖植物竖条形状
  1162. 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
  1163. 'L': -30, // 回旋镖植物L型
  1164. 'S': -10, // 回旋镖植物S型,适配回旋轨迹
  1165. 'D-T': -80 // 回旋镖植物倒T型
  1166. },
  1167. 'hot_pepper': {
  1168. 'I': 0, // 辣椒竖条形状
  1169. 'H-I': 90, // 辣椒横条形状
  1170. 'L': 0, // 辣椒L型
  1171. 'S': 0, // 辣椒S型
  1172. 'D-T': 0 // 辣椒倒T型
  1173. },
  1174. 'cactus_shotgun': {
  1175. 'I': 0, // 仙人掌霰弹枪竖条形状
  1176. 'H-I': 90, // 仙人掌霰弹枪横条形状
  1177. 'L': -20, // 仙人掌霰弹枪L型
  1178. 'S': 20, // 仙人掌霰弹枪S型
  1179. 'D-T': 0 // 仙人掌霰弹枪倒T型
  1180. },
  1181. 'okra_missile': {
  1182. 'I': 0, // 秋葵导弹竖条形状
  1183. 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
  1184. 'L': -10, // 秋葵导弹L型
  1185. 'S': 10, // 秋葵导弹S型
  1186. 'D-T': 0 // 秋葵导弹倒T型
  1187. },
  1188. 'mace_club': {
  1189. 'I': -45, // 狼牙棒竖条形状
  1190. 'H-I': 0, // 狼牙棒横条形状
  1191. 'L': -90, // 狼牙棒L型,适配棒状武器
  1192. 'S': -90, // 狼牙棒S型
  1193. 'D-T': 0 // 狼牙棒倒T型
  1194. }
  1195. };
  1196. // 默认旋转角度配置(当武器类型未配置时使用)
  1197. private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
  1198. 'I': 0, // 竖条形状,保持原始方向
  1199. 'H-I': 90, // 横I型,旋转90度适配水平方向
  1200. 'L': -15, // L型,轻微左倾适配L形状的转角
  1201. 'S': 15, // S型,轻微右倾适配S形状的弯曲
  1202. 'D-T': 0 // 倒T型,保持原始方向
  1203. };
  1204. // 根据武器类型和方块形状调整武器图标位置(完全保留预制体原始旋转值,不应用额外旋转)
  1205. private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1206. if (!weaponNode || !shapeId) return;
  1207. // 保存预制体的原始旋转角度
  1208. const originalAngle = weaponNode.angle;
  1209. // let additionalRotationAngle = 0;
  1210. // 注释掉旋转逻辑,完全保留预制体设置
  1211. /*
  1212. // 如果提供了武器ID,尝试获取特定武器的旋转角度
  1213. if (weaponId) {
  1214. additionalRotationAngle = this.getWeaponShapeRotationAngle(weaponId, shapeId);
  1215. console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定旋转角度: ${additionalRotationAngle}度,原始角度: ${originalAngle}度`);
  1216. } else {
  1217. // 使用默认配置
  1218. additionalRotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1219. console.log(`为形状 ${shapeId} 设置默认旋转角度: ${additionalRotationAngle}度,原始角度: ${originalAngle}度`);
  1220. }
  1221. // 应用旋转角度:叠加预制体原始角度和形状配置角度
  1222. weaponNode.angle = originalAngle + additionalRotationAngle;
  1223. */
  1224. console.log(`保留预制体原始旋转角度: ${originalAngle}度,不应用额外旋转`);
  1225. }
  1226. // 注释掉的原始方法(覆盖预制体旋转值的版本)
  1227. /*
  1228. private rotateWeaponIconByShape_Original(weaponNode: Node, shapeId: string | null, weaponId?: string) {
  1229. if (!weaponNode || !shapeId) return;
  1230. let rotationAngle = 0;
  1231. // 如果提供了武器ID,尝试获取特定武器的旋转角度
  1232. if (weaponId) {
  1233. rotationAngle = this.getWeaponShapeRotationAngle(weaponId, shapeId);
  1234. console.log(`为武器 ${weaponId} 形状 ${shapeId} 设置特定旋转角度: ${rotationAngle}度`);
  1235. } else {
  1236. // 使用默认配置
  1237. rotationAngle = this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1238. console.log(`为形状 ${shapeId} 设置默认旋转角度: ${rotationAngle}度`);
  1239. }
  1240. // 应用旋转角度(直接覆盖,会丢失预制体设置)
  1241. weaponNode.angle = rotationAngle;
  1242. }
  1243. */
  1244. // 设置特定武器和形状的旋转角度
  1245. public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
  1246. if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1247. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
  1248. }
  1249. this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
  1250. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1251. }
  1252. // 设置默认形状的旋转角度
  1253. public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
  1254. this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
  1255. console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
  1256. }
  1257. // 获取特定武器和形状的旋转角度
  1258. public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
  1259. if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
  1260. return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
  1261. }
  1262. return 0;
  1263. }
  1264. // 获取默认形状的旋转角度
  1265. public getDefaultShapeRotationAngle(shapeId: string): number {
  1266. return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
  1267. }
  1268. // 设置特定武器和形状的旋转角度
  1269. public setWeaponShapeTransform(weaponId: string, shapeId: string, angle: number) {
  1270. this.setWeaponShapeRotationAngle(weaponId, shapeId, angle);
  1271. console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度: ${angle}度`);
  1272. }
  1273. // 设置默认形状的旋转角度
  1274. public setDefaultShapeTransform(shapeId: string, angle: number) {
  1275. this.setDefaultShapeRotationAngle(shapeId, angle);
  1276. console.log(`已更新默认形状 ${shapeId} 的旋转角度: ${angle}度`);
  1277. }
  1278. // 重新应用所有已放置方块的武器图标位置和旋转
  1279. public refreshAllWeaponIconRotations() {
  1280. // 遍历所有已放置的方块
  1281. if (this.placedBlocksContainer) {
  1282. this.placedBlocksContainer.children.forEach(block => {
  1283. const weaponConfig = this.getBlockWeaponConfig(block);
  1284. if (weaponConfig) {
  1285. const b1Node = block.getChildByName('B1');
  1286. if (b1Node) {
  1287. const weaponNode = b1Node.getChildByName('Weapon');
  1288. if (weaponNode) {
  1289. const shapeId = this.getBlockShape(block);
  1290. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1291. }
  1292. }
  1293. }
  1294. });
  1295. }
  1296. // 遍历kuang区域的方块
  1297. this.blocks.forEach(block => {
  1298. const weaponConfig = this.getBlockWeaponConfig(block);
  1299. if (weaponConfig) {
  1300. const b1Node = block.getChildByName('B1');
  1301. if (b1Node) {
  1302. const weaponNode = b1Node.getChildByName('Weapon');
  1303. if (weaponNode) {
  1304. const shapeId = this.getBlockShape(block);
  1305. this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
  1306. }
  1307. }
  1308. }
  1309. });
  1310. }
  1311. // 根据方块获取武器配置
  1312. public getBlockWeaponConfig(block: Node): WeaponConfig | null {
  1313. return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
  1314. }
  1315. // 获取方块的武器ID
  1316. public getBlockWeaponId(block: Node): string | null {
  1317. const weaponConfig = this.getBlockWeaponConfig(block);
  1318. return weaponConfig ? weaponConfig.id : null;
  1319. }
  1320. // 获取方块的形状
  1321. public getBlockShape(block: Node): string | null {
  1322. const weaponConfig = this.getBlockWeaponConfig(block);
  1323. if (!weaponConfig) return null;
  1324. // 从方块结构推断形状
  1325. return this.inferBlockShapeFromStructure(block);
  1326. }
  1327. // 获取方块的详细形状信息(包括形状ID和名称)
  1328. public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
  1329. const actualShape = this.extractShapeFromBlock(block);
  1330. let blockShapes = null;
  1331. // 优先使用预加载的配置
  1332. if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
  1333. blockShapes = this.preloadedWeaponsConfig.blockSizes;
  1334. } else {
  1335. // 回退到ConfigManager
  1336. blockShapes = this.configManager.getBlockShapes();
  1337. }
  1338. if (!blockShapes) return null;
  1339. // 寻找匹配的形状配置
  1340. for (const shapeConfig of blockShapes) {
  1341. if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
  1342. return {
  1343. id: shapeConfig.id,
  1344. name: shapeConfig.name,
  1345. shape: shapeConfig.shape
  1346. };
  1347. }
  1348. }
  1349. return null;
  1350. }
  1351. // 从方块结构推断形状
  1352. private inferBlockShapeFromStructure(block: Node): string {
  1353. // 简化逻辑:直接返回随机形状,避免复杂的形状匹配
  1354. // 这样可以避免形状匹配失败导致的警告,同时保持游戏的多样性
  1355. const availableShapes = ['I', 'H-I', 'L', 'S', 'D-T', 'L2', 'L3', 'L4', 'S-F', 'T'];
  1356. const randomIndex = Math.floor(Math.random() * availableShapes.length);
  1357. const selectedShape = availableShapes[randomIndex];
  1358. console.log(`[BlockManager] 为方块分配随机形状: ${selectedShape}`);
  1359. return selectedShape;
  1360. }
  1361. // 寻找与目标形状匹配的预制体
  1362. // 注意:findMatchingPrefab 和 doesPrefabMatchShape 方法已被移除
  1363. // 因为我们简化了形状匹配逻辑,直接使用随机预制体选择
  1364. // 从方块实例中提取形状矩阵
  1365. private extractShapeFromBlock(block: Node): number[][] {
  1366. const parts = this.getBlockParts(block);
  1367. // 创建4x4矩阵
  1368. const matrix: number[][] = [];
  1369. for (let i = 0; i < 4; i++) {
  1370. matrix[i] = [0, 0, 0, 0];
  1371. }
  1372. // 找到最小坐标作为偏移基准
  1373. let minX = 0, minY = 0;
  1374. for (const part of parts) {
  1375. minX = Math.min(minX, part.x);
  1376. minY = Math.min(minY, part.y);
  1377. }
  1378. // 填充矩阵,将坐标标准化到从(0,0)开始
  1379. for (const part of parts) {
  1380. const matrixX = part.x - minX;
  1381. const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
  1382. if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
  1383. matrix[matrixY][matrixX] = 1;
  1384. }
  1385. }
  1386. // 移除矩阵翻转操作,保持原始坐标系
  1387. // 注释掉翻转逻辑,确保提取的矩阵与配置文件中的标准矩阵一致
  1388. // const temp = matrix[0];
  1389. // matrix[0] = matrix[1];
  1390. // matrix[1] = temp;
  1391. return matrix;
  1392. }
  1393. // 比较两个形状矩阵是否相同
  1394. private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
  1395. if (matrix1.length !== matrix2.length) return false;
  1396. for (let i = 0; i < matrix1.length; i++) {
  1397. if (matrix1[i].length !== matrix2[i].length) return false;
  1398. for (let j = 0; j < matrix1[i].length; j++) {
  1399. if (matrix1[i][j] !== matrix2[i][j]) return false;
  1400. }
  1401. }
  1402. return true;
  1403. }
  1404. // 检查两个方块是否可以合成(相同形状相同种类)
  1405. private canMergeBlocks(block1: Node, block2: Node): boolean {
  1406. // 检查稀有度
  1407. const rarity1 = this.getBlockRarity(block1);
  1408. const rarity2 = this.getBlockRarity(block2);
  1409. if (rarity1 !== rarity2) {
  1410. console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
  1411. return false;
  1412. }
  1413. // 检查武器ID(种类)
  1414. const weaponId1 = this.getBlockWeaponId(block1);
  1415. const weaponId2 = this.getBlockWeaponId(block2);
  1416. if (weaponId1 !== weaponId2) {
  1417. console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
  1418. return false;
  1419. }
  1420. // 使用精确的形状矩阵比较
  1421. const shape1 = this.extractShapeFromBlock(block1);
  1422. const shape2 = this.extractShapeFromBlock(block2);
  1423. if (!this.compareShapeMatrices(shape1, shape2)) {
  1424. console.log(`[BlockManager] 形状矩阵不匹配`);
  1425. return false;
  1426. }
  1427. console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
  1428. return true;
  1429. }
  1430. // 刷新方块 - 重新生成三个新的武器方块
  1431. public refreshBlocks() {
  1432. // 移除PlacedBlocks容器中所有方块的标签
  1433. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1434. BlockTag.removeTagsInContainer(this.placedBlocksContainer);
  1435. }
  1436. // 保存已放置方块的占用信息
  1437. const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  1438. if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
  1439. for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
  1440. const block = this.placedBlocksContainer.children[i];
  1441. const occupiedGrids = block['occupiedGrids'];
  1442. if (occupiedGrids && occupiedGrids.length > 0) {
  1443. placedBlocksOccupation.push({
  1444. block: block,
  1445. occupiedGrids: [...occupiedGrids]
  1446. });
  1447. }
  1448. }
  1449. }
  1450. // 生成新的方块
  1451. this.generateRandomBlocksInKuang();
  1452. }
  1453. // 检查是否有已放置的方块
  1454. public hasPlacedBlocks(): boolean {
  1455. if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
  1456. console.log('[BlockManager] PlacedBlocks容器无效');
  1457. return false;
  1458. }
  1459. const blockCount = this.placedBlocksContainer.children.length;
  1460. console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
  1461. // 检查容器中是否有子节点(方块)
  1462. return blockCount > 0;
  1463. }
  1464. /* =================== 合成逻辑 =================== */
  1465. private readonly rarityOrder: string[] = ['common','uncommon','rare','epic','legendary'];
  1466. /** 检查当前放置的方块能否与相同稀有度的方块合成 */
  1467. public async tryMergeBlock(block: Node) {
  1468. try {
  1469. const rarity = this.getBlockRarity(block);
  1470. if (!rarity) return;
  1471. // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
  1472. if (!this.placedBlocksContainer) return;
  1473. const blockBB = this.getWorldAABB(block);
  1474. for (const other of this.placedBlocksContainer.children) {
  1475. if (other === block) continue;
  1476. // 使用新的合成检查方法
  1477. if (!this.canMergeBlocks(block, other)) continue;
  1478. const otherBB = this.getWorldAABB(other);
  1479. if (this.rectIntersects(blockBB, otherBB)) {
  1480. // 找到合成目标
  1481. await this.performMerge(block, other, rarity);
  1482. break;
  1483. }
  1484. }
  1485. } catch (error) {
  1486. console.error('[BlockManager] tryMergeBlock 发生错误:', error);
  1487. // 合成失败不影响游戏继续,只记录错误
  1488. }
  1489. }
  1490. private async performMerge(target: Node, source: Node, rarity: string) {
  1491. try {
  1492. console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
  1493. // 隐藏价格标签并处理 db 关联
  1494. this.hidePriceLabel(source);
  1495. const srcDb = source['dbNode'];
  1496. if (srcDb) srcDb.active = false;
  1497. // 销毁被合并方块
  1498. source.destroy();
  1499. // 升级稀有度
  1500. const nextRarity = this.getNextRarity(rarity);
  1501. if (nextRarity) {
  1502. console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
  1503. // 获取当前武器配置
  1504. const currentConfig = this.blockWeaponConfigs.get(target);
  1505. if (currentConfig) {
  1506. // 保存原始武器名称用于日志输出
  1507. const originalWeaponName = currentConfig.name;
  1508. try {
  1509. // 获取当前关卡允许的武器列表
  1510. const levelWeapons = await this.getCurrentLevelWeapons();
  1511. // 检查是否应该限制在关卡配置的武器范围内
  1512. if (levelWeapons.length > 0) {
  1513. // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
  1514. if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
  1515. console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
  1516. }
  1517. // 无论如何,都只升级稀有度,不改变武器类型
  1518. const upgradedConfig = { ...currentConfig };
  1519. upgradedConfig.rarity = nextRarity;
  1520. this.blockWeaponConfigs.set(target, upgradedConfig);
  1521. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1522. (target as any)['weaponConfig'] = upgradedConfig;
  1523. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1524. } else {
  1525. // 如果没有关卡配置限制,正常升级稀有度
  1526. const upgradedConfig = { ...currentConfig };
  1527. upgradedConfig.rarity = nextRarity;
  1528. this.blockWeaponConfigs.set(target, upgradedConfig);
  1529. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1530. (target as any)['weaponConfig'] = upgradedConfig;
  1531. console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1532. }
  1533. } catch (weaponError) {
  1534. console.error('[BlockManager] 获取关卡武器配置失败:', weaponError);
  1535. // 武器配置获取失败时,仍然升级稀有度
  1536. const upgradedConfig = { ...currentConfig };
  1537. upgradedConfig.rarity = nextRarity;
  1538. this.blockWeaponConfigs.set(target, upgradedConfig);
  1539. // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
  1540. (target as any)['weaponConfig'] = upgradedConfig;
  1541. console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
  1542. }
  1543. }
  1544. // 更新方块颜色
  1545. this.setBlockRarityColor(target, nextRarity);
  1546. }
  1547. // 播放烟雾动画
  1548. const worldPos = new Vec3();
  1549. target.getWorldPosition(worldPos);
  1550. this.spawnMergeSmoke(worldPos);
  1551. // 递归检查是否还能继续合成
  1552. if (nextRarity) {
  1553. await this.tryMergeBlock(target);
  1554. }
  1555. console.log(`[BlockManager] 合成完成`);
  1556. } catch (error) {
  1557. console.error('[BlockManager] performMerge 发生错误:', error);
  1558. // 合成失败时重新抛出错误,让上层处理
  1559. throw error;
  1560. }
  1561. }
  1562. private getBlockRarity(block: Node): string | null {
  1563. const cfg = this.blockWeaponConfigs.get(block);
  1564. if (cfg) return cfg.rarity;
  1565. // fallback based on sprite color maybe
  1566. return null;
  1567. }
  1568. private getNextRarity(rarity: string): string | null {
  1569. const idx = this.rarityOrder.indexOf(rarity);
  1570. if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
  1571. return this.rarityOrder[idx + 1];
  1572. }
  1573. private getWorldAABB(node: Node): Rect {
  1574. const ui = node.getComponent(UITransform);
  1575. if (!ui) return new Rect();
  1576. const pos = node.worldPosition;
  1577. const width = ui.width;
  1578. const height = ui.height;
  1579. return new Rect(pos.x - width/2, pos.y - height/2, width, height);
  1580. }
  1581. private rectIntersects(a: Rect, b: Rect): boolean {
  1582. return a.x < b.x + b.width &&
  1583. a.x + a.width > b.x &&
  1584. a.y < b.y + b.height &&
  1585. a.y + a.height > b.y;
  1586. }
  1587. /** 生成烟雾特效 */
  1588. private spawnMergeSmoke(worldPos: Vec3) {
  1589. const path = 'Animation/WeaponTx/tx0003/tx0003';
  1590. resources.load(path, sp.SkeletonData, (err, sData: sp.SkeletonData) => {
  1591. if (err || !sData) {
  1592. console.warn('加载合成烟雾动画失败', err);
  1593. return;
  1594. }
  1595. const node = new Node('MergeSmoke');
  1596. const skeleton = node.addComponent(sp.Skeleton);
  1597. skeleton.skeletonData = sData;
  1598. skeleton.premultipliedAlpha = false;
  1599. skeleton.setAnimation(0, 'animation', false);
  1600. skeleton.setCompleteListener(() => node.destroy());
  1601. const canvas = find('Canvas');
  1602. if (canvas) canvas.addChild(node);
  1603. node.setWorldPosition(worldPos);
  1604. });
  1605. }
  1606. /** 在放置失败时尝试与现有方块进行合成 */
  1607. public tryMergeOnOverlap(draggedBlock: Node): boolean {
  1608. if (!this.placedBlocksContainer) return false;
  1609. const rarity = this.getBlockRarity(draggedBlock);
  1610. if (!rarity) return false;
  1611. const dragBB = this.getWorldAABB(draggedBlock);
  1612. for (const target of this.placedBlocksContainer.children) {
  1613. if (target === draggedBlock) continue;
  1614. // 使用新的合成检查方法
  1615. if (!this.canMergeBlocks(draggedBlock, target)) continue;
  1616. const targetBB = this.getWorldAABB(target);
  1617. if (this.rectIntersects(dragBB, targetBB)) {
  1618. // 执行合并:目标保留,拖拽方块销毁
  1619. this.performMerge(target, draggedBlock, rarity);
  1620. return true;
  1621. }
  1622. }
  1623. return false;
  1624. }
  1625. // 调试绘制功能已迁移到GameBlockSelection
  1626. // 输出格子占用情况矩阵
  1627. public printGridOccupationMatrix() {
  1628. console.log('[BlockManager] 格子占用情况de矩阵 (6行11列):');
  1629. for (let row = 0; row < this.GRID_ROWS; row++) {
  1630. let rowStr = '';
  1631. for (let col = 0; col < this.GRID_COLS; col++) {
  1632. rowStr += this.gridOccupationMap[row][col] + ' ';
  1633. }
  1634. console.log(`第${row + 1}行: ${rowStr.trim()}`);
  1635. }
  1636. }
  1637. // 通过GameBlockSelection刷新方块占用情况
  1638. onDestroy() {
  1639. // 调试绘制功能已迁移到GameBlockSelection
  1640. // 清理事件监听
  1641. const eventBus = EventBus.getInstance();
  1642. eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
  1643. eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
  1644. // 移除GAME_START事件清理,因为已不再监听该事件
  1645. // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1646. eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
  1647. }
  1648. }