BlockManager.ts 63 KB

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