BlockManager.ts 74 KB

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