BlockManager.ts 74 KB

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