BlockManager.ts 80 KB

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