BlockManager.ts 80 KB

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