BlockManager.ts 76 KB

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