GameBlockSelection.ts 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. import { _decorator, Component, Node, Button, Label, find, EventTouch, Vec2, Vec3, UITransform, Rect, Collider2D, Graphics, Color, Sprite } from 'cc';
  2. import { LevelSessionManager } from '../../Core/LevelSessionManager';
  3. import { BallController } from '../BallController';
  4. import { BlockManager } from '../BlockManager';
  5. import { ConfigManager } from '../../Core/ConfigManager';
  6. import { BlockTag } from './BlockTag';
  7. import { WeaponInfo } from './WeaponInfo';
  8. import { SkillManager } from '../SkillSelection/SkillManager';
  9. import { Audio } from '../../AudioManager/AudioManager';
  10. import { AdManager } from '../../Ads/AdManager';
  11. import { JsonConfigLoader } from '../../Core/JsonConfigLoader';
  12. import { AnalyticsManager, BlockSelectionClickProperties } from '../../Utils/AnalyticsManager';
  13. import EventBus, { GameEvents } from '../../Core/EventBus';
  14. import { NewbieGuideManager } from '../../Core/NewbieGuideManager';
  15. import { SaveDataManager } from '../../LevelSystem/SaveDataManager';
  16. import { InGameManager } from '../../LevelSystem/IN_game';
  17. const { ccclass, property } = _decorator;
  18. @ccclass('GameBlockSelection')
  19. export class GameBlockSelection extends Component {
  20. @property({
  21. type: Node,
  22. tooltip: '拖拽diban/ann001按钮节点到这里'
  23. })
  24. public addBallButton: Node = null;
  25. @property({
  26. type: Node,
  27. tooltip: '拖拽diban/ann002按钮节点到这里'
  28. })
  29. public addCoinButton: Node = null;
  30. @property({
  31. type: Node,
  32. tooltip: '拖拽diban/ann003按钮节点到这里'
  33. })
  34. public refreshButton: Node = null;
  35. @property({
  36. type: Node,
  37. tooltip: '拖拽Canvas-001/TopArea/CoinNode/CoinLabel节点到这里'
  38. })
  39. public coinLabelNode: Node = null;
  40. @property({
  41. type: Node,
  42. tooltip: '拖拽Canvas/GameLevelUI/BallController节点到这里'
  43. })
  44. public ballControllerNode: Node = null;
  45. @property({
  46. type: Node,
  47. tooltip: '拖拽Canvas/GameLevelUI/BlockController节点到这里'
  48. })
  49. public blockManagerNode: Node = null;
  50. @property({
  51. type: Node,
  52. tooltip: '拖拽Canvas/GameLevelUI/GameArea/GridContainer节点到这里'
  53. })
  54. public gridContainer: Node = null;
  55. @property({
  56. type: Node,
  57. tooltip: '拖拽confirm按钮节点到这里'
  58. })
  59. public confirmButton: Node = null;
  60. @property({
  61. type: Node,
  62. tooltip: '拖拽Canvas/GameLevelUI/InGameManager节点到这里'
  63. })
  64. public inGameManagerNode: Node = null;
  65. @property({
  66. type: Node,
  67. tooltip: '拖拽Canvas/Camera节点到这里'
  68. })
  69. public cameraNode: Node = null;
  70. // 武器配置数据,通过 BundleLoader 异步加载
  71. private weaponsConfigData: any = null;
  72. // 小球价格配置数据 - 通过BundleLoader动态加载
  73. private ballPriceConfigData: any = null;
  74. // 新增小球价格显示节点 - 对应addBallPricing
  75. @property({
  76. type: Node,
  77. tooltip: '拖拽Canvas/GameLevelUI/BlockSelectionUI/diban/ann001/Ball/db01/Price节点到这里'
  78. })
  79. public addBallPriceNode: Node = null;
  80. // 刷新方块价格显示节点 - 对应refreshBlockPricing
  81. @property({
  82. type: Node,
  83. tooltip: '拖拽Canvas/GameLevelUI/BlockSelectionUI/diban/ann003/Ball/db01/Price节点到这里'
  84. })
  85. public refreshBlockPriceNode: Node = null;
  86. // 增加金币奖励显示节点 - 对应addCoinReward
  87. @property({
  88. type: Node,
  89. tooltip: '拖拽Canvas/GameLevelUI/BlockSelectionUI/diban/ann002/db01/addCoin节点到这里'
  90. })
  91. public addCoinRewardNode: Node = null;
  92. // 价格配置默认值
  93. private readonly DEFAULT_ADD_BALL_BASE_PRICE = 80;
  94. private readonly DEFAULT_ADD_BALL_INCREMENT = 10;
  95. private readonly DEFAULT_ADD_BALL_MAX_PRICE = 500;
  96. private readonly DEFAULT_REFRESH_BASE_PRICE = 5;
  97. private readonly DEFAULT_REFRESH_INCREMENT = 2;
  98. private readonly DEFAULT_REFRESH_MAX_PRICE = 50;
  99. private readonly DEFAULT_ADD_COIN_BASE_REWARD = 60;
  100. private readonly DEFAULT_ADD_COIN_INCREMENT = 10;
  101. private readonly DEFAULT_ADD_COIN_MAX_REWARD = 200;
  102. // 获取增加金币奖励数量
  103. private getAddCoinReward(): number {
  104. // 优先从JSON配置中获取奖励数量
  105. if (this.ballPriceConfigData && this.ballPriceConfigData.addCoinReward) {
  106. const config = this.ballPriceConfigData.addCoinReward;
  107. const baseReward = config.initialPrice ?? this.DEFAULT_ADD_COIN_BASE_REWARD;
  108. const increment = config.priceIncrement ?? this.DEFAULT_ADD_COIN_INCREMENT;
  109. const maxReward = config.maxPrice ?? this.DEFAULT_ADD_COIN_MAX_REWARD;
  110. // 获取当前使用次数
  111. const session = this.session || LevelSessionManager.inst;
  112. const usageCount = session ? session.getAddCoinUsageCount() : 0;
  113. // 计算当前奖励数量
  114. const currentReward = Math.min(baseReward + (usageCount * increment), maxReward);
  115. return currentReward;
  116. }
  117. // 其次从装饰器绑定的节点获取奖励数量
  118. try {
  119. if (this.addCoinRewardNode) {
  120. const label = this.addCoinRewardNode.getComponent(Label);
  121. if (label) {
  122. const reward = parseInt(label.string);
  123. return isNaN(reward) ? this.DEFAULT_ADD_COIN_BASE_REWARD : reward;
  124. }
  125. } else {
  126. // 回退到find方法(兼容性)
  127. const rewardNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann002/db01/addCoin');
  128. if (rewardNode) {
  129. const label = rewardNode.getComponent(Label);
  130. if (label) {
  131. const reward = parseInt(label.string);
  132. return isNaN(reward) ? this.DEFAULT_ADD_COIN_BASE_REWARD : reward;
  133. }
  134. }
  135. }
  136. } catch (error) {
  137. console.warn('[GameBlockSelection] 获取增加金币奖励失败:', error);
  138. }
  139. return this.DEFAULT_ADD_COIN_BASE_REWARD; // 默认奖励
  140. }
  141. // 价格获取方法
  142. private getAddBallCost(): number {
  143. // 优先从JSON配置中获取价格
  144. if (this.ballPriceConfigData && this.ballPriceConfigData.addBallPricing) {
  145. const config = this.ballPriceConfigData.addBallPricing;
  146. const basePrice = config.initialPrice ?? this.DEFAULT_ADD_BALL_BASE_PRICE;
  147. const increment = config.priceIncrement ?? this.DEFAULT_ADD_BALL_INCREMENT;
  148. const maxPrice = config.maxPrice ?? this.DEFAULT_ADD_BALL_MAX_PRICE;
  149. // 获取当前使用次数
  150. const session = this.session || LevelSessionManager.inst;
  151. const usageCount = session ? session.getAddBallUsageCount() : 0;
  152. // 计算当前价格
  153. const currentPrice = Math.min(basePrice + (usageCount * increment), maxPrice);
  154. return currentPrice;
  155. }
  156. // 其次从装饰器绑定的节点获取价格
  157. try {
  158. if (this.addBallPriceNode) {
  159. const label = this.addBallPriceNode.getComponent(Label);
  160. if (label) {
  161. const price = parseInt(label.string);
  162. return isNaN(price) ? this.DEFAULT_ADD_BALL_BASE_PRICE : price;
  163. }
  164. } else {
  165. // 回退到find方法(兼容性)
  166. const priceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann001/Ball/db01/Price');
  167. if (priceNode) {
  168. const label = priceNode.getComponent(Label);
  169. if (label) {
  170. const price = parseInt(label.string);
  171. return isNaN(price) ? this.DEFAULT_ADD_BALL_BASE_PRICE : price;
  172. }
  173. }
  174. }
  175. } catch (error) {
  176. console.warn('[GameBlockSelection] 获取新增小球价格失败:', error);
  177. }
  178. return this.DEFAULT_ADD_BALL_BASE_PRICE; // 默认价格
  179. }
  180. public getRefreshCost(): number {
  181. // 优先从JSON配置中获取价格
  182. console.log('[GameBlockSelection] 刷新方块价格配置:', this.ballPriceConfigData?.refreshBlockPricing);
  183. if (this.ballPriceConfigData && this.ballPriceConfigData.refreshBlockPricing) {
  184. const config = this.ballPriceConfigData.refreshBlockPricing;
  185. const basePrice = config.initialPrice ?? this.DEFAULT_REFRESH_BASE_PRICE;
  186. const increment = config.priceIncrement ?? this.DEFAULT_REFRESH_INCREMENT;
  187. const maxPrice = config.maxPrice ?? this.DEFAULT_REFRESH_MAX_PRICE;
  188. // 获取当前使用次数
  189. const session = this.session || LevelSessionManager.inst;
  190. const usageCount = session ? session.getRefreshUsageCount() : 0;
  191. // 计算当前价格
  192. const currentPrice = Math.min(basePrice + (usageCount * increment), maxPrice);
  193. return currentPrice;
  194. }
  195. // 其次从装饰器绑定的节点获取价格
  196. try {
  197. if (this.refreshBlockPriceNode) {
  198. console.log('[GameBlockSelection] 刷新方块价格节点:', this.refreshBlockPriceNode);
  199. const label = this.refreshBlockPriceNode.getComponent(Label);
  200. if (label) {
  201. const price = parseInt(label.string);
  202. return isNaN(price) ? this.DEFAULT_REFRESH_BASE_PRICE : price;
  203. }
  204. } else {
  205. // 回退到find方法(兼容性)
  206. const priceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann003/Ball/db01/Price');
  207. if (priceNode) {
  208. const label = priceNode.getComponent(Label);
  209. if (label) {
  210. const price = parseInt(label.string);
  211. return isNaN(price) ? this.DEFAULT_REFRESH_BASE_PRICE : price;
  212. }
  213. }
  214. }
  215. } catch (error) {
  216. console.warn('[GameBlockSelection] 获取刷新方块价格失败:', error);
  217. }
  218. return this.DEFAULT_REFRESH_BASE_PRICE; // 默认价格
  219. }
  220. private session: LevelSessionManager = null;
  221. private ballController: BallController = null;
  222. private blockManager: BlockManager = null;
  223. // 回调函数,用于通知GameManager
  224. public onConfirmCallback: () => void = null;
  225. // 标记是否已初始化
  226. private isInitialized: boolean = false;
  227. // 标记是否应该生成方块(只有在onBattle触发后才为true)
  228. private shouldGenerateBlocks: boolean = false;
  229. // 用户操作方块相关属性
  230. private currentDragBlock: Node | null = null;
  231. private startPos = new Vec2();
  232. private blockStartPos: Vec3 = new Vec3();
  233. // 调试绘制相关属性
  234. @property({
  235. tooltip: '是否启用吸附检测范围调试绘制'
  236. })
  237. public debugDrawSnapRange: boolean = false;
  238. private debugDrawNode: Node = null;
  239. private debugGraphics: Graphics = null;
  240. // 引导期间按钮原始颜色缓存
  241. private originalButtonColors: Map<Node, Color> = new Map();
  242. // 引导期禁用颜色置灰(HEX: 4D4545)
  243. private readonly GUIDE_DISABLED_COLOR: Color = new Color(0x4D, 0x45, 0x45, 255);
  244. onEnable() {
  245. // 如果还未初始化,则进行初始化
  246. if (!this.isInitialized) {
  247. this.initializeComponent();
  248. } else {
  249. // 如果已经初始化,重新设置事件监听器(因为onDisable时会移除)
  250. this.setupEventListeners();
  251. }
  252. // this.initDebugDraw();
  253. }
  254. start() {
  255. // 如果还未初始化,则进行初始化
  256. if (!this.isInitialized) {
  257. this.initializeComponent();
  258. }
  259. }
  260. private async initializeComponent() {
  261. // 异步加载小球价格配置
  262. try {
  263. this.ballPriceConfigData = await JsonConfigLoader.getInstance().loadConfig('ballPrice');
  264. console.log('[GameBlockSelection] 小球价格配置加载成功:', this.ballPriceConfigData);
  265. } catch (error) {
  266. console.warn('[GameBlockSelection] 小球价格配置加载失败:', error);
  267. this.ballPriceConfigData = null;
  268. }
  269. // 异步加载武器配置
  270. try {
  271. this.weaponsConfigData = await JsonConfigLoader.getInstance().loadConfig('weapons');
  272. console.log('[GameBlockSelection] 武器配置加载成功:', this.weaponsConfigData);
  273. } catch (error) {
  274. console.warn('[GameBlockSelection] 武器配置加载失败:', error);
  275. this.weaponsConfigData = null;
  276. }
  277. // 获取管理器实例
  278. this.session = LevelSessionManager.inst;
  279. // 获取BallController
  280. if (this.ballControllerNode) {
  281. this.ballController = this.ballControllerNode.getComponent(BallController);
  282. } else {
  283. console.warn('BallController节点未绑定,请在Inspector中拖拽Canvas/GameLevelUI/BallController节点');
  284. }
  285. // 获取BlockManager
  286. if (this.blockManagerNode) {
  287. this.blockManager = this.blockManagerNode.getComponent(BlockManager);
  288. // 如果武器配置已通过 BundleLoader 加载,传递给BlockManager
  289. if (this.weaponsConfigData) {
  290. // 通过公共方法将加载的配置传递给BlockManager
  291. if (this.blockManager && typeof this.blockManager.setPreloadedWeaponsConfig === 'function') {
  292. this.blockManager.setPreloadedWeaponsConfig(this.weaponsConfigData);
  293. console.log('[GameBlockSelection] 武器配置已传递给BlockManager');
  294. } else {
  295. console.warn('[GameBlockSelection] BlockManager不支持setPreloadedWeaponsConfig方法');
  296. }
  297. } else {
  298. console.warn('[GameBlockSelection] 武器配置加载失败,BlockManager将使用默认配置');
  299. }
  300. } else {
  301. console.warn('BlockManager节点未绑定,请在Inspector中拖拽Canvas/GameLevelUI/BlockController节点');
  302. }
  303. // 如果没有指定coinLabelNode,尝试找到它
  304. if (!this.coinLabelNode) {
  305. this.coinLabelNode = find('Canvas-001/TopArea/CoinNode/CoinLabel');
  306. }
  307. // 初始化金币显示
  308. this.updateCoinDisplay();
  309. // 绑定按钮事件
  310. this.bindButtonEvents();
  311. // 设置事件监听器
  312. this.setupEventListeners();
  313. // 更新价格显示
  314. this.updatePriceDisplay();
  315. // 更新奖励显示
  316. this.updateRewardDisplay();
  317. // 标记为已初始化
  318. this.isInitialized = true;
  319. // 初始化完成
  320. }
  321. // 设置事件监听器
  322. private setupEventListeners() {
  323. const eventBus = EventBus.getInstance();
  324. // 监听重置方块选择事件
  325. eventBus.on(GameEvents.RESET_BLOCK_SELECTION, this.onResetBlockSelectionEvent, this);
  326. // 监听游戏开始事件,用于标记可以开始生成方块
  327. eventBus.on(GameEvents.GAME_START, this.onGameStartEvent, this);
  328. // 监听方块拖拽事件设置请求
  329. eventBus.on(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.onSetupBlockDragEventsEvent, this);
  330. // 监听进入游玩状态与敌人开始生成以更新引导按钮状态(波次变化时)
  331. eventBus.on(GameEvents.ENTER_PLAYING_STATE, this.updateGuideButtonStates, this);
  332. eventBus.on(GameEvents.ENEMY_START_GAME, this.updateGuideButtonStates, this);
  333. eventBus.on(GameEvents.GAME_START, this.updateGuideButtonStates, this);
  334. // 监听敌人数量更新与新波次开始,精确在第二波结束时解禁按钮
  335. eventBus.on(GameEvents.ENEMY_UPDATE_COUNT, this.updateGuideButtonStates, this);
  336. eventBus.on(GameEvents.ENEMY_START_WAVE, this.updateGuideButtonStates, this);
  337. // 监听:全局强制结束所有拖拽(用于教程自动放置期间收敛拖拽状态)
  338. eventBus.on(GameEvents.FORCE_END_ALL_DRAGS, this.onForceEndAllDrags, this);
  339. }
  340. // 处理重置方块选择事件
  341. private onResetBlockSelectionEvent() {
  342. this.resetSelection();
  343. }
  344. // 处理游戏开始事件
  345. private onGameStartEvent() {
  346. // 接收到游戏开始事件,允许生成方块
  347. this.shouldGenerateBlocks = true;
  348. }
  349. // 处理方块拖拽事件设置请求
  350. private onSetupBlockDragEventsEvent(blocks: Node[]) {
  351. // 确保组件仍然有效
  352. if (!this.node || !this.node.isValid) {
  353. console.warn('[GameBlockSelection] 组件节点无效,跳过拖拽事件设置');
  354. return;
  355. }
  356. for (const block of blocks) {
  357. if (block && block.isValid) {
  358. // 先移除可能存在的旧事件监听器
  359. block.off(Node.EventType.TOUCH_START);
  360. block.off(Node.EventType.TOUCH_MOVE);
  361. block.off(Node.EventType.TOUCH_END);
  362. block.off(Node.EventType.TOUCH_CANCEL);
  363. // 重新设置拖拽事件
  364. this.setupBlockDragEvents(block);
  365. } else {
  366. // 跳过无效方块的拖拽事件设置
  367. }
  368. }
  369. }
  370. // 绑定按钮事件
  371. private bindButtonEvents() {
  372. // 绑定新增小球按钮
  373. if (this.addBallButton) {
  374. const btn = this.addBallButton.getComponent(Button);
  375. if (btn) {
  376. this.addBallButton.on(Button.EventType.CLICK, this.onAddBallClicked, this);
  377. } else {
  378. this.addBallButton.on(Node.EventType.TOUCH_END, this.onAddBallClicked, this);
  379. }
  380. }
  381. // 绑定增加金币按钮
  382. if (this.addCoinButton) {
  383. const btn = this.addCoinButton.getComponent(Button);
  384. if (btn) {
  385. this.addCoinButton.on(Button.EventType.CLICK, this.onAddCoinClicked, this);
  386. } else {
  387. this.addCoinButton.on(Node.EventType.TOUCH_END, this.onAddCoinClicked, this);
  388. }
  389. }
  390. // 绑定刷新方块按钮
  391. if (this.refreshButton) {
  392. const btn = this.refreshButton.getComponent(Button);
  393. if (btn) {
  394. this.refreshButton.on(Button.EventType.CLICK, this.onRefreshClicked, this);
  395. } else {
  396. this.refreshButton.on(Node.EventType.TOUCH_END, this.onRefreshClicked, this);
  397. }
  398. }
  399. // 绑定确认按钮
  400. if (this.confirmButton) {
  401. const btn = this.confirmButton.getComponent(Button);
  402. if (btn) {
  403. this.confirmButton.on(Button.EventType.CLICK, this.onConfirmButtonClicked, this);
  404. } else {
  405. this.confirmButton.on(Node.EventType.TOUCH_END, this.onConfirmButtonClicked, this);
  406. }
  407. }
  408. // 初始更新引导期间按钮状态
  409. this.updateGuideButtonStates();
  410. }
  411. // 新增小球按钮点击
  412. private onAddBallClicked() {
  413. // 播放UI点击音效
  414. Audio.playUISound('data/弹球音效/ui play');
  415. // 从UI节点获取价格并应用便宜技能效果计算实际费用
  416. const baseCost = this.getAddBallCost();
  417. const actualCost = this.getActualCost(baseCost);
  418. // 检查是否有足够金币
  419. const canAfford = this.canSpendCoins(actualCost);
  420. let success = false;
  421. let failureReason: string | undefined;
  422. if (!canAfford) {
  423. failureReason = 'insufficient_coins';
  424. this.showInsufficientCoinsUI();
  425. } else {
  426. // 扣除金币
  427. if (this.session.spendCoins(actualCost)) {
  428. success = true;
  429. // 增加使用次数
  430. this.session.incrementAddBallUsageCount();
  431. this.updateCoinDisplay();
  432. // 更新价格显示
  433. this.updatePriceDisplay();
  434. // 通过事件系统创建新的小球
  435. const eventBus = EventBus.getInstance();
  436. eventBus.emit(GameEvents.BALL_CREATE_ADDITIONAL);
  437. // 新增小球成功
  438. } else {
  439. failureReason = 'spend_coins_failed';
  440. }
  441. }
  442. // 数据分析追踪
  443. const properties: BlockSelectionClickProperties = {
  444. button_type: 'add_ball',
  445. button_cost: actualCost,
  446. user_money: this.session.getCoins(),
  447. usage_count: this.session.getAddBallUsageCount(),
  448. success: success,
  449. failure_reason: failureReason
  450. };
  451. AnalyticsManager.getInstance().trackBlockSelectionClick(properties);
  452. }
  453. // 增加金币按钮点击
  454. private onAddCoinClicked() {
  455. // 引导第2波结束前禁用此按钮
  456. if (this.isGuideRestrictActive()) {
  457. this.applyGuideDisabledVisual(this.addCoinButton, true);
  458. return;
  459. }
  460. // 播放UI点击音效
  461. Audio.playUISound('data/弹球音效/ui play');
  462. let success = false;
  463. let failureReason: string | undefined;
  464. // 显示激励视频广告
  465. AdManager.getInstance().showRewardedVideoAd(
  466. () => {
  467. // 广告观看完成,增加金币
  468. const coinsToAdd = this.getAddCoinReward(); // 从配置中获取广告奖励的金币数量
  469. this.session.addCoins(coinsToAdd);
  470. // 增加使用次数
  471. this.session.incrementAddCoinUsageCount();
  472. // 更新显示
  473. this.updateCoinDisplay();
  474. this.updateRewardDisplay();
  475. success = true;
  476. // 数据分析追踪 - 成功情况
  477. const properties: BlockSelectionClickProperties = {
  478. button_type: 'add_coin',
  479. user_money: this.session.getCoins(),
  480. usage_count: this.session.getAddCoinUsageCount(),
  481. success: success
  482. };
  483. AnalyticsManager.getInstance().trackBlockSelectionClick(properties);
  484. },
  485. (error) => {
  486. console.error('[GameBlockSelection] 广告显示失败:', error);
  487. // 广告失败时不给予奖励
  488. failureReason = 'ad_failed';
  489. // 数据分析追踪 - 失败情况
  490. const properties: BlockSelectionClickProperties = {
  491. button_type: 'add_coin',
  492. user_money: this.session.getCoins(),
  493. usage_count: this.session.getAddCoinUsageCount(),
  494. success: false,
  495. failure_reason: failureReason
  496. };
  497. AnalyticsManager.getInstance().trackBlockSelectionClick(properties);
  498. }
  499. );
  500. }
  501. // 刷新方块按钮点击
  502. private onRefreshClicked() {
  503. // 引导第2波结束前禁用此按钮
  504. if (this.isGuideRestrictActive()) {
  505. this.applyGuideDisabledVisual(this.refreshButton, true);
  506. return;
  507. }
  508. // 播放UI点击音效
  509. Audio.playUISound('data/弹球音效/ui play');
  510. // 从UI节点获取价格并应用便宜技能效果计算实际费用
  511. const baseCost = this.getRefreshCost();
  512. const actualCost = this.getActualCost(baseCost);
  513. // 检查是否有足够金币
  514. const canAfford = this.canSpendCoins(actualCost);
  515. let success = false;
  516. let failureReason: string | undefined;
  517. if (!canAfford) {
  518. failureReason = 'insufficient_coins';
  519. this.showInsufficientCoinsUI();
  520. } else {
  521. // 扣除金币
  522. if (this.session.spendCoins(actualCost)) {
  523. success = true;
  524. // 增加使用次数
  525. this.session.incrementRefreshUsageCount();
  526. // 成功扣除金币
  527. this.updateCoinDisplay();
  528. // 更新价格显示
  529. this.updatePriceDisplay();
  530. // 刷新方块
  531. if (this.blockManager) {
  532. console.log('[GameBlockSelection] 开始刷新方块流程');
  533. // 找到PlacedBlocks容器
  534. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  535. if (placedBlocksContainer) {
  536. // 移除已放置方块的标签
  537. // 移除已放置方块的标签
  538. BlockTag.removeTagsInContainer(placedBlocksContainer);
  539. }
  540. // 刷新方块
  541. // 调用 blockManager.refreshBlocks()
  542. this.blockManager.refreshBlocks();
  543. // 等待一帧确保方块生成完成
  544. this.scheduleOnce(() => {
  545. }, 0.1);
  546. } else {
  547. console.error('[GameBlockSelection] 找不到BlockManager,无法刷新方块');
  548. success = false;
  549. failureReason = 'block_manager_not_found';
  550. }
  551. } else {
  552. console.error('[GameBlockSelection] 扣除金币失败');
  553. failureReason = 'spend_coins_failed';
  554. }
  555. }
  556. // 数据分析追踪
  557. const properties: BlockSelectionClickProperties = {
  558. button_type: 'refresh_blocks',
  559. button_cost: actualCost,
  560. user_money: this.session.getCoins(),
  561. usage_count: this.session.getRefreshUsageCount(),
  562. success: success,
  563. failure_reason: failureReason
  564. };
  565. AnalyticsManager.getInstance().trackBlockSelectionClick(properties);
  566. }
  567. // 确认按钮点击
  568. public onConfirmButtonClicked() {
  569. // 检查是否有上阵方块
  570. const hasBlocks = this.hasPlacedBlocks();
  571. if (!hasBlocks) {
  572. this.showNoPlacedBlocksToast();
  573. return;
  574. }
  575. // 播放UI音效
  576. Audio.playUISound('data/弹球音效/ui play');
  577. // 保存已放置的方块
  578. this.preservePlacedBlocks();
  579. // 清理kuang区域的方块(用户期望的行为)
  580. if (this.blockManager) {
  581. this.blockManager.clearBlocks();
  582. console.log('[GameBlockSelection] 已清理kuang区域的方块');
  583. }
  584. // 先回调通知GameManager,让它处理波次逻辑
  585. if (this.onConfirmCallback) {
  586. this.onConfirmCallback();
  587. }
  588. // 发出方块选择确认事件(用于新手引导第三步结束)
  589. EventBus.getInstance().emit(GameEvents.BLOCK_SELECTION_CONFIRMED);
  590. // 播放下滑diban动画,结束备战进入playing状态
  591. this.playDibanSlideDownAnimation();
  592. // 确认后更新一次(可能进入下一波)
  593. this.updateGuideButtonStates();
  594. }
  595. // 播放diban下滑动画
  596. private playDibanSlideDownAnimation() {
  597. // 开始播放diban下滑动画
  598. // 使用装饰器属性获取Camera节点上的GameStartMove组件
  599. if (!this.cameraNode) {
  600. console.warn('[GameBlockSelection] Camera节点未设置,请在Inspector中拖拽Canvas/Camera节点');
  601. return;
  602. }
  603. const gameStartMove = this.cameraNode.getComponent('GameStartMove');
  604. if (!gameStartMove) {
  605. console.warn('[GameBlockSelection] GameStartMove组件未找到');
  606. return;
  607. }
  608. // 调用GameStartMove的下滑动画方法
  609. (gameStartMove as any).slideDibanDownAndHide(0.3);
  610. // 已调用GameStartMove的diban下滑动画
  611. }
  612. // 保存已放置的方块(从GameManager迁移)
  613. private preservePlacedBlocks() {
  614. if (this.blockManager) {
  615. this.blockManager.onGameStart();
  616. }
  617. }
  618. // 检查是否有足够金币
  619. private canSpendCoins(amount: number): boolean {
  620. return this.session.getCoins() >= amount;
  621. }
  622. // 计算应用便宜技能效果后的实际费用
  623. private getActualCost(baseCost: number): number {
  624. const skillManager = SkillManager.getInstance();
  625. if (skillManager) {
  626. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  627. return Math.ceil(SkillManager.calculateCheaperUnitsPrice(baseCost, cheaperSkillLevel));
  628. }
  629. return baseCost;
  630. }
  631. // 更新金币显示
  632. private updateCoinDisplay() {
  633. if (this.coinLabelNode) {
  634. const label = this.coinLabelNode.getComponent(Label);
  635. if (label) {
  636. const coins = this.session.getCoins();
  637. label.string = coins.toString();
  638. // 更新金币显示
  639. } else {
  640. console.warn('[GameBlockSelection] coinLabelNode缺少Label组件');
  641. }
  642. } else {
  643. console.warn('[GameBlockSelection] coinLabelNode未找到');
  644. }
  645. }
  646. // ——— 引导期间按钮禁用与颜色处理 ———
  647. private isGuideRestrictActive(): boolean {
  648. try {
  649. // 仅在第1关启用引导期限制;进入其他关卡一律不限制
  650. const sdm = SaveDataManager.getInstance();
  651. const currentLevel = sdm ? sdm.getCurrentLevel() : 1;
  652. if (currentLevel !== 1) return false;
  653. const guideMgr = NewbieGuideManager.getInstance();
  654. const isGuide = guideMgr && guideMgr.isNewbieGuideInProgress();
  655. if (!isGuide) return false;
  656. const inGameMgr = this.inGameManagerNode ? this.inGameManagerNode.getComponent(InGameManager) : null;
  657. const currentWave = inGameMgr ? inGameMgr.getCurrentWave() : 1;
  658. // 第1波:禁用
  659. if (currentWave < 2) return true;
  660. // 第3波及以后:解禁
  661. if (currentWave > 2) return false;
  662. // 第2波:直到所有敌人被击败前禁用
  663. const total = inGameMgr ? inGameMgr.getCurrentWaveTotalEnemies() : 0;
  664. const killed = inGameMgr ? inGameMgr.getCurrentWaveEnemyCount() : 0;
  665. if (total <= 0) {
  666. // 无法获取总数时保守禁用
  667. return true;
  668. }
  669. return killed < total;
  670. } catch (e) {
  671. return false;
  672. }
  673. }
  674. private applyGuideDisabledVisual(targetButtonNode: Node | null, disabled: boolean) {
  675. if (!targetButtonNode) return;
  676. const btn = targetButtonNode.getComponent(Button);
  677. if (btn) btn.interactable = !disabled;
  678. // 设置按钮节点及其子节点的Sprite颜色
  679. const applyColorRecursively = (node: Node, color: Color) => {
  680. const sp = node.getComponent(Sprite);
  681. if (sp) {
  682. // 缓存原始颜色
  683. if (!this.originalButtonColors.has(node)) {
  684. this.originalButtonColors.set(node, sp.color?.clone?.() || new Color(255, 255, 255, 255));
  685. }
  686. sp.color = color;
  687. }
  688. node.children?.forEach(child => applyColorRecursively(child, color));
  689. };
  690. if (disabled) {
  691. applyColorRecursively(targetButtonNode, this.GUIDE_DISABLED_COLOR);
  692. } else {
  693. // 恢复至原始颜色(若无缓存则使用白色)
  694. const restoreColorRecursively = (node: Node) => {
  695. const sp = node.getComponent(Sprite);
  696. if (sp) {
  697. const orig = this.originalButtonColors.get(node) || new Color(255, 255, 255, 255);
  698. sp.color = orig;
  699. }
  700. node.children?.forEach(child => restoreColorRecursively(child));
  701. };
  702. restoreColorRecursively(targetButtonNode);
  703. }
  704. }
  705. private updateGuideButtonStates = () => {
  706. // 根据引导期与波次实时计算禁用状态(仅第1关的第1/2波禁用)
  707. const restrict = this.isGuideRestrictActive();
  708. this.applyGuideDisabledVisual(this.addCoinButton, restrict);
  709. this.applyGuideDisabledVisual(this.refreshButton, restrict);
  710. };
  711. // 显示金币不足UI
  712. private showInsufficientCoinsUI() {
  713. // 使用事件机制显示资源不足Toast
  714. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  715. message: '金币不足!',
  716. duration: 3.0
  717. });
  718. // 金币不足
  719. }
  720. // === 公共方法:供GameManager调用 ===
  721. // 生成方块选择(不再控制UI显示,只负责生成方块)
  722. public generateBlockSelection() {
  723. // 尝试确保拿到 BlockManager(兼容场景切换后生命周期先后顺序)
  724. if (!this.blockManager) {
  725. // 1) 通过已绑定的节点拿组件
  726. if (this.blockManagerNode && this.blockManagerNode.isValid) {
  727. this.blockManager = this.blockManagerNode.getComponent(BlockManager);
  728. }
  729. // 2) 回退到路径查找(确保场景加载后也能获取到)
  730. if (!this.blockManager) {
  731. const bmNode = find('Canvas/GameLevelUI/BlockController');
  732. if (bmNode) {
  733. this.blockManager = bmNode.getComponent(BlockManager) as any;
  734. if (!this.blockManager) {
  735. // 兼容字符串组件名(某些环境下主动通过字符串拿组件)
  736. this.blockManager = bmNode.getComponent('BlockManager') as any;
  737. }
  738. }
  739. }
  740. // 3) 如果武器配置已预加载,补传一次给 BlockManager
  741. if (this.blockManager && this.weaponsConfigData && typeof (this.blockManager as any).setPreloadedWeaponsConfig === 'function') {
  742. (this.blockManager as any).setPreloadedWeaponsConfig(this.weaponsConfigData);
  743. console.log('[GameBlockSelection] 懒加载后已向BlockManager传递武器配置');
  744. }
  745. }
  746. // 直接生成方块,不再依赖shouldGenerateBlocks标志
  747. if (this.blockManager) {
  748. this.blockManager.refreshBlocks();
  749. } else {
  750. console.warn('[GameBlockSelection] BlockManager未找到,无法生成随机方块');
  751. }
  752. // 触发进入备战状态事件
  753. EventBus.getInstance().emit(GameEvents.ENTER_BATTLE_PREPARATION);
  754. }
  755. // 设置确认回调
  756. public setConfirmCallback(callback: () => void) {
  757. this.onConfirmCallback = callback;
  758. }
  759. // 统一的方块占用情况刷新方法
  760. public refreshGridOccupation() {
  761. if (this.blockManager) {
  762. this.blockManager.resetGridOccupation();
  763. // 重新计算所有已放置方块的占用情况
  764. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  765. if (placedBlocksContainer) {
  766. for (let i = 0; i < placedBlocksContainer.children.length; i++) {
  767. const block = placedBlocksContainer.children[i];
  768. // 按照BlockManager.tryPlaceBlockToGrid的正确方法获取位置
  769. let b1Node = block;
  770. if (block.name !== 'B1') {
  771. b1Node = block.getChildByName('B1');
  772. if (!b1Node) {
  773. console.warn(`[GameBlockSelection] 方块 ${block.name} 没有B1子节点`);
  774. continue;
  775. }
  776. }
  777. // 获取B1节点的世界坐标,然后转换为网格本地坐标
  778. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  779. const gridPos = this.blockManager.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  780. // 重新标记方块占用的网格位置
  781. const gridNode = this.blockManager.findNearestGridNode(gridPos);
  782. if (gridNode) {
  783. this.blockManager.markOccupiedPositions(block, gridNode);
  784. } else {
  785. console.warn(`[GameBlockSelection] 方块 ${block.name} 未找到对应的网格节点`);
  786. }
  787. }
  788. }
  789. } else {
  790. console.warn('[GameBlockSelection] BlockManager未找到,无法刷新占用情况');
  791. }
  792. this.blockManager.printGridOccupationMatrix();
  793. }
  794. // 重置方块选择状态
  795. public resetSelection() {
  796. // 重置方块生成标志,等待下次onBattle触发
  797. this.shouldGenerateBlocks = false;
  798. // 注意:不再直接调用blockManager.onGameReset(),因为StartGame.clearGameStates()
  799. // 已经通过RESET_BLOCK_MANAGER事件触发了BlockManager的重置,避免重复生成方块
  800. // 清理所有方块标签
  801. BlockTag.clearAllTags();
  802. // 更新价格显示(使用次数已在session中重置)
  803. this.updatePriceDisplay();
  804. // 更新金币显示
  805. this.updateCoinDisplay();
  806. }
  807. // 检查是否有上阵方块
  808. private hasPlacedBlocks(): boolean {
  809. // 优先使用BlockManager的方法检查
  810. if (this.blockManager) {
  811. return this.blockManager.hasPlacedBlocks();
  812. }
  813. // 备用方案:直接检查PlacedBlocks容器
  814. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  815. if (!placedBlocksContainer) {
  816. console.warn('找不到PlacedBlocks容器');
  817. return false;
  818. }
  819. // 检查容器中是否有子节点(方块)
  820. return placedBlocksContainer.children.length > 0;
  821. }
  822. // 显示没有上阵方块的Toast提示
  823. private showNoPlacedBlocksToast() {
  824. // 使用事件机制显示Toast
  825. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  826. message: '请至少上阵一个植物!',
  827. duration: 3.0
  828. });
  829. }
  830. // 设置方块拖拽事件
  831. public setupBlockDragEvents(block: Node) {
  832. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  833. // 检查游戏是否已开始
  834. if (!this.blockManager.gameStarted) {
  835. return;
  836. }
  837. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  838. const blockLocation = this.blockManager.blockLocations.get(block);
  839. // 金币不足时禁止从kuang区域拖拽,并在点击时提示
  840. if (blockLocation !== 'grid') {
  841. const price = this.blockManager.getBlockPrice(block);
  842. if (!this.canSpendCoins(price)) {
  843. this.blockManager.showInsufficientCoinsEffect(block);
  844. return; // 不进入拖拽流程
  845. }
  846. }
  847. // grid区域的方块目前允许自由移动
  848. this.currentDragBlock = block;
  849. this.startPos = event.getUILocation();
  850. this.blockStartPos.set(block.position);
  851. this.currentDragBlock['startLocation'] = blockLocation;
  852. // 如果方块在grid区域,拿起时清除其占用状态
  853. if (blockLocation === 'grid') {
  854. this.blockManager.clearOccupiedPositions(block);
  855. // 输出更新后的占用情况
  856. this.blockManager.printGridOccupationMatrix();
  857. }
  858. // 设置拖动状态,隐藏价格标签
  859. block['isDragging'] = true;
  860. block.setSiblingIndex(block.parent.children.length - 1);
  861. // 拖拽开始时禁用碰撞体
  862. const collider = block.getComponent(Collider2D);
  863. if (collider) collider.enabled = false;
  864. // 通知BallController有方块开始拖拽
  865. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_START, { block: block });
  866. }, this);
  867. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  868. // 检查游戏是否已开始
  869. if (!this.blockManager.gameStarted) {
  870. return;
  871. }
  872. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  873. const blockLocation = this.blockManager.blockLocations.get(block);
  874. // 教程阶段:第6步结束前禁止移动已上阵方块(第4步除外)
  875. if (blockLocation === 'grid' && !this.blockManager.canMovePlacedBlocks()) {
  876. return;
  877. }
  878. if (!this.currentDragBlock) return;
  879. const location = event.getUILocation();
  880. const deltaX = location.x - this.startPos.x;
  881. const deltaY = location.y - this.startPos.y;
  882. this.currentDragBlock.position = new Vec3(
  883. this.blockStartPos.x + deltaX,
  884. this.blockStartPos.y + deltaY,
  885. this.blockStartPos.z
  886. );
  887. }, this);
  888. block.on(Node.EventType.TOUCH_END, async (event: EventTouch) => {
  889. // 检查游戏是否已开始
  890. if (!this.blockManager.gameStarted) {
  891. return;
  892. }
  893. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  894. const blockLocation = this.blockManager.blockLocations.get(block);
  895. // 教程阶段:第6步结束前禁止移动已上阵方块(第4步除外)
  896. if (blockLocation === 'grid' && !this.blockManager.canMovePlacedBlocks()) {
  897. return;
  898. }
  899. if (this.currentDragBlock) {
  900. try {
  901. await this.handleBlockDrop(event);
  902. } catch (error) {
  903. console.error('[GameBlockSelection] 处理方块拖拽放置时发生错误:', error);
  904. // 发生错误时,将方块返回原位置
  905. this.returnBlockToOriginalPosition();
  906. }
  907. // 清除拖动状态,恢复价格标签显示
  908. block['isDragging'] = false;
  909. this.currentDragBlock = null;
  910. // 拖拽结束时恢复碰撞体
  911. const collider = block.getComponent(Collider2D);
  912. if (collider) collider.enabled = true;
  913. // 通知BallController方块拖拽结束
  914. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: block });
  915. }
  916. }, this);
  917. block.on(Node.EventType.TOUCH_CANCEL, () => {
  918. if (this.currentDragBlock) {
  919. this.returnBlockToOriginalPosition();
  920. // 清除拖动状态,恢复价格标签显示
  921. block['isDragging'] = false;
  922. this.currentDragBlock = null;
  923. // 拖拽取消时恢复碰撞体
  924. const collider = block.getComponent(Collider2D);
  925. if (collider) collider.enabled = true;
  926. // 通知BallController方块拖拽结束
  927. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: block });
  928. }
  929. }, this);
  930. }
  931. // 处理方块放下
  932. private async handleBlockDrop(event: EventTouch) {
  933. try {
  934. const touchPos = event.getLocation();
  935. const startLocation = this.currentDragBlock['startLocation'];
  936. if (this.isInKuangArea(touchPos)) {
  937. // 检查是否有标签,只有有标签的方块才能放回kuang
  938. if (BlockTag.hasTag(this.currentDragBlock)) {
  939. this.returnBlockToKuang(startLocation);
  940. } else {
  941. // 没有标签的方块不能放回kuang,返回原位置
  942. this.returnBlockToOriginalPosition();
  943. }
  944. } else if (this.blockManager.tryPlaceBlockToGrid(this.currentDragBlock)) {
  945. await this.handleSuccessfulPlacement(startLocation);
  946. } else {
  947. // 放置失败,尝试直接与重叠方块合成
  948. // 先检查金币是否充足(如果来自kuang区域)
  949. if (startLocation !== 'grid') {
  950. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  951. if (!this.canSpendCoins(price)) {
  952. this.returnBlockToOriginalPosition();
  953. return;
  954. }
  955. }
  956. if (this.blockManager.tryMergeOnOverlap(this.currentDragBlock)) {
  957. // 合成成功时,若来自 kuang 则扣费
  958. if (startLocation !== 'grid') {
  959. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  960. this.blockManager.deductPlayerCoins(price);
  961. }
  962. // 当前拖拽块已被销毁(合并时),无需复位
  963. } else {
  964. this.returnBlockToOriginalPosition();
  965. }
  966. }
  967. } catch (error) {
  968. console.error('[GameBlockSelection] handleBlockDrop 发生错误:', error);
  969. // 发生错误时,将方块返回原位置
  970. this.returnBlockToOriginalPosition();
  971. throw error; // 重新抛出错误,让上层处理
  972. } finally {
  973. // 无论成功还是失败,都要清理拖拽状态
  974. if (this.currentDragBlock && this.currentDragBlock.isValid) {
  975. // 重新启用碰撞器
  976. const collider = this.currentDragBlock.getComponent(Collider2D);
  977. if (collider) {
  978. collider.enabled = true;
  979. console.log('[GameBlockSelection] 拖拽结束,重新启用碰撞器:', this.currentDragBlock.name);
  980. }
  981. // 发射拖拽结束事件
  982. console.log('[GameBlockSelection] 发射 BLOCK_DRAG_END 事件:', this.currentDragBlock.name);
  983. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: this.currentDragBlock });
  984. }
  985. // 清理拖拽状态
  986. this.currentDragBlock = null;
  987. }
  988. // 刷新方块占用情况
  989. this.refreshGridOccupation();
  990. }
  991. // 检查是否在kuang区域内
  992. private isInKuangArea(touchPos: Vec2): boolean {
  993. // 检查是否在任何一个Block容器区域内
  994. const blockContainers = [
  995. this.blockManager.block1Container,
  996. this.blockManager.block2Container,
  997. this.blockManager.block3Container
  998. ];
  999. for (const container of blockContainers) {
  1000. if (container) {
  1001. const transform = container.getComponent(UITransform);
  1002. if (transform) {
  1003. const boundingBox = new Rect(
  1004. container.worldPosition.x - transform.width * transform.anchorX,
  1005. container.worldPosition.y - transform.height * transform.anchorY,
  1006. transform.width,
  1007. transform.height
  1008. );
  1009. if (boundingBox.contains(new Vec2(touchPos.x, touchPos.y))) {
  1010. return true;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. // 如果Block容器都不可用,回退到检查kuang容器
  1016. if (this.blockManager.kuangContainer) {
  1017. const kuangTransform = this.blockManager.kuangContainer.getComponent(UITransform);
  1018. if (kuangTransform) {
  1019. const kuangBoundingBox = new Rect(
  1020. this.blockManager.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  1021. this.blockManager.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  1022. kuangTransform.width,
  1023. kuangTransform.height
  1024. );
  1025. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  1026. }
  1027. }
  1028. return false;
  1029. }
  1030. // 返回方块到对应的Block容器区域
  1031. private returnBlockToKuang(startLocation: string) {
  1032. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  1033. const blockLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  1034. if (originalPos) {
  1035. // 根据方块的原始位置确定应该返回到哪个Block容器
  1036. let targetContainer: Node = null;
  1037. let targetLocation = 'kuang'; // 默认位置
  1038. if (blockLocation && blockLocation.startsWith('block')) {
  1039. // 如果方块原本在Block容器中,返回到对应的容器
  1040. if (blockLocation === 'block1') {
  1041. targetContainer = this.blockManager.block1Container;
  1042. targetLocation = 'block1';
  1043. } else if (blockLocation === 'block2') {
  1044. targetContainer = this.blockManager.block2Container;
  1045. targetLocation = 'block2';
  1046. } else if (blockLocation === 'block3') {
  1047. targetContainer = this.blockManager.block3Container;
  1048. targetLocation = 'block3';
  1049. }
  1050. }
  1051. // 如果没有找到对应的Block容器,回退到kuang容器
  1052. if (!targetContainer) {
  1053. targetContainer = this.blockManager.kuangContainer;
  1054. targetLocation = 'kuang';
  1055. }
  1056. if (targetContainer && this.currentDragBlock.parent !== targetContainer) {
  1057. this.currentDragBlock.removeFromParent();
  1058. targetContainer.addChild(this.currentDragBlock);
  1059. }
  1060. this.currentDragBlock.position = originalPos.clone();
  1061. this.blockManager.blockLocations.set(this.currentDragBlock, targetLocation);
  1062. }
  1063. // 当方块返回kuang区域时,重新设置植物图标缩放至0.4倍
  1064. const weaponNode = this.findWeaponNodeInBlock(this.currentDragBlock);
  1065. if (weaponNode) {
  1066. weaponNode.setScale(0.4, 0.4, 1);
  1067. // 方块返回kuang区域,设置植物图标缩放: 0.4倍
  1068. }
  1069. if (startLocation === 'grid') {
  1070. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  1071. this.blockManager.refundPlayerCoins(price);
  1072. this.currentDragBlock['placedBefore'] = false;
  1073. }
  1074. // 显示对应的db标签节点
  1075. this.showDbNodeByBlockLocation(this.currentDragBlock);
  1076. }
  1077. /**
  1078. * 为方块的武器节点添加武器信息组件
  1079. * @param block 方块节点
  1080. */
  1081. private attachWeaponInfoToBlock(block: Node): void {
  1082. try {
  1083. // 查找方块中的Weapon节点
  1084. const weaponNode = this.findWeaponNodeInBlock(block);
  1085. if (!weaponNode) {
  1086. console.warn(`[GameBlockSelection] 方块 ${block.name} 中未找到Weapon节点,无法添加武器信息组件`);
  1087. return;
  1088. }
  1089. // 检查是否已经有WeaponInfo组件
  1090. let weaponInfo = weaponNode.getComponent(WeaponInfo);
  1091. if (weaponInfo) {
  1092. return;
  1093. }
  1094. // 添加WeaponInfo组件
  1095. weaponInfo = weaponNode.addComponent(WeaponInfo);
  1096. // 获取方块的武器配置
  1097. const weaponConfig = this.blockManager.getBlockWeaponConfig(block);
  1098. if (weaponConfig) {
  1099. // 设置武器配置到WeaponInfo组件
  1100. weaponInfo.setWeaponConfig(weaponConfig);
  1101. } else {
  1102. console.warn(`[GameBlockSelection] 方块 ${block.name} 没有武器配置,无法设置武器信息`);
  1103. // 移除刚添加的组件
  1104. weaponNode.removeComponent(WeaponInfo);
  1105. }
  1106. } catch (error) {
  1107. console.error(`[GameBlockSelection] 为方块 ${block.name} 添加武器信息组件时发生错误:`, error);
  1108. }
  1109. }
  1110. /**
  1111. * 在方块中查找Weapon节点
  1112. * @param block 方块节点
  1113. * @returns Weapon节点,如果未找到返回null
  1114. */
  1115. private findWeaponNodeInBlock(block: Node): Node | null {
  1116. if (!block || !block.isValid) {
  1117. return null;
  1118. }
  1119. // 根据新的预制体结构,武器节点直接位于方块根节点下
  1120. const weaponNode = block.getChildByName('Weapon');
  1121. if (weaponNode) {
  1122. return weaponNode;
  1123. }
  1124. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  1125. const b1Node = block.getChildByName('B1');
  1126. if (b1Node) {
  1127. const b1WeaponNode = b1Node.getChildByName('Weapon');
  1128. if (b1WeaponNode) {
  1129. return b1WeaponNode;
  1130. }
  1131. }
  1132. // 最后使用递归方式查找(兼容其他可能的结构)
  1133. const findWeaponRecursive = (node: Node): Node | null => {
  1134. if (node.name === 'Weapon') {
  1135. return node;
  1136. }
  1137. for (let i = 0; i < node.children.length; i++) {
  1138. const result = findWeaponRecursive(node.children[i]);
  1139. if (result) {
  1140. return result;
  1141. }
  1142. }
  1143. return null;
  1144. };
  1145. return findWeaponRecursive(block);
  1146. }
  1147. // 根据方块位置隐藏对应的db标签节点
  1148. private hideDbNodeByBlockLocation(block: Node) {
  1149. const originalLocation = this.getBlockOriginalLocation(block);
  1150. if (originalLocation === 'block1') {
  1151. console.log(`[GameBlockSelection] 隐藏block1的db标签节点`);
  1152. const blockInContainer = this.getBlockInContainer(this.blockManager.block1Container);
  1153. if (blockInContainer) {
  1154. this.blockManager.hideDbLabel(blockInContainer);
  1155. }
  1156. } else if (originalLocation === 'block2') {
  1157. console.log(`[GameBlockSelection] 隐藏block2的db标签节点`);
  1158. const blockInContainer = this.getBlockInContainer(this.blockManager.block2Container);
  1159. if (blockInContainer) {
  1160. this.blockManager.hideDbLabel(blockInContainer);
  1161. }
  1162. } else if (originalLocation === 'block3') {
  1163. console.log(`[GameBlockSelection] 隐藏block3的db标签节点`);
  1164. const blockInContainer = this.getBlockInContainer(this.blockManager.block3Container);
  1165. if (blockInContainer) {
  1166. this.blockManager.hideDbLabel(blockInContainer);
  1167. }
  1168. }
  1169. }
  1170. // 根据方块位置显示对应的db标签节点
  1171. private showDbNodeByBlockLocation(block: Node) {
  1172. const originalLocation = this.getBlockOriginalLocation(block);
  1173. if (originalLocation === 'block1') {
  1174. const blockInContainer = this.getBlockInContainer(this.blockManager.block1Container);
  1175. if (blockInContainer) {
  1176. this.blockManager.showDbLabel(blockInContainer);
  1177. }
  1178. } else if (originalLocation === 'block2') {
  1179. const blockInContainer = this.getBlockInContainer(this.blockManager.block2Container);
  1180. if (blockInContainer) {
  1181. this.blockManager.showDbLabel(blockInContainer);
  1182. }
  1183. } else if (originalLocation === 'block3') {
  1184. const blockInContainer = this.getBlockInContainer(this.blockManager.block3Container);
  1185. if (blockInContainer) {
  1186. this.blockManager.showDbLabel(blockInContainer);
  1187. }
  1188. }
  1189. }
  1190. // 获取容器中的方块节点
  1191. private getBlockInContainer(container: Node): Node | null {
  1192. if (!container) {
  1193. return null;
  1194. }
  1195. // 查找容器中的方块节点(通常以Block命名或有B1子节点)
  1196. for (let i = 0; i < container.children.length; i++) {
  1197. const child = container.children[i];
  1198. if (child.name.includes('Block') || child.getChildByName('B1')) {
  1199. return child;
  1200. }
  1201. }
  1202. return null;
  1203. }
  1204. // 处理成功放置
  1205. private async handleSuccessfulPlacement(startLocation: string) {
  1206. try {
  1207. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  1208. if (startLocation === 'grid') {
  1209. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  1210. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  1211. // 隐藏对应的db标签节点
  1212. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  1213. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  1214. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  1215. // 为武器节点添加武器信息组件
  1216. this.attachWeaponInfoToBlock(this.currentDragBlock);
  1217. // 如果游戏已开始,添加锁定视觉提示
  1218. if (this.blockManager.gameStarted) {
  1219. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  1220. BlockTag.removeTag(this.currentDragBlock);
  1221. }
  1222. // 检查并执行合成
  1223. try {
  1224. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  1225. } catch (mergeError) {
  1226. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  1227. }
  1228. } else {
  1229. if (this.blockManager.deductPlayerCoins(price)) {
  1230. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  1231. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  1232. // 隐藏对应的db标签节点
  1233. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  1234. this.currentDragBlock['placedBefore'] = true;
  1235. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  1236. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  1237. // 为武器节点添加武器信息组件
  1238. this.attachWeaponInfoToBlock(this.currentDragBlock);
  1239. // 如果游戏已开始,添加锁定视觉提示
  1240. if (this.blockManager.gameStarted) {
  1241. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  1242. // 游戏开始后放置的方块移除标签,不能再放回kuang
  1243. BlockTag.removeTag(this.currentDragBlock);
  1244. }
  1245. // 检查并执行合成
  1246. try {
  1247. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  1248. } catch (mergeError) {
  1249. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  1250. // 合成失败不影响方块放置,只记录错误
  1251. }
  1252. } else {
  1253. // 金币不足时显示价格标签闪烁效果和Toast提示
  1254. this.blockManager.showInsufficientCoinsEffect(this.currentDragBlock);
  1255. this.returnBlockToOriginalPosition();
  1256. }
  1257. }
  1258. } catch (error) {
  1259. console.error('[GameBlockSelection] handleSuccessfulPlacement 发生错误:', error);
  1260. // 发生错误时,将方块返回原位置
  1261. this.returnBlockToOriginalPosition();
  1262. throw error; // 重新抛出错误,让上层处理
  1263. }
  1264. }
  1265. // 返回方块到原位置
  1266. private returnBlockToOriginalPosition() {
  1267. const currentLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  1268. const startLocation = this.currentDragBlock['startLocation'];
  1269. if (currentLocation === 'kuang') {
  1270. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  1271. if (originalPos) {
  1272. this.currentDragBlock.position = originalPos.clone();
  1273. }
  1274. } else {
  1275. this.currentDragBlock.position = this.blockStartPos.clone();
  1276. // 如果方块原本在grid区域,返回原位置后需要重新标记占用状态
  1277. if (startLocation === 'grid') {
  1278. // 获取方块当前位置对应的网格节点
  1279. let b1Node = this.currentDragBlock;
  1280. if (this.currentDragBlock.name !== 'B1') {
  1281. b1Node = this.currentDragBlock.getChildByName('B1');
  1282. }
  1283. if (b1Node) {
  1284. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  1285. const gridPos = this.blockManager.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  1286. const gridNode = this.blockManager.findNearestGridNode(gridPos);
  1287. if (gridNode) {
  1288. this.blockManager.markOccupiedPositions(this.currentDragBlock, gridNode);
  1289. // 输出更新后的占用情况
  1290. this.blockManager.printGridOccupationMatrix();
  1291. }
  1292. }
  1293. }
  1294. }
  1295. // 清除拖动状态,恢复db节点显示
  1296. this.currentDragBlock['isDragging'] = false;
  1297. this.showDbNodeByBlockLocation(this.currentDragBlock);
  1298. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  1299. }
  1300. // === 调试绘制相关方法 ===
  1301. private initDebugDraw() {
  1302. // 调试绘制功能已禁用
  1303. }
  1304. private drawGridSnapRanges() {
  1305. // 调试绘制功能已禁用
  1306. }
  1307. private drawBlockSnapRange(block: Node) {
  1308. // 调试绘制功能已禁用
  1309. }
  1310. private updateDebugDraw() {
  1311. // 调试绘制功能已禁用
  1312. }
  1313. // 清理调试绘制
  1314. private cleanupDebugDraw() {
  1315. if (this.debugDrawNode && this.debugDrawNode.isValid) {
  1316. this.debugDrawNode.destroy();
  1317. this.debugDrawNode = null;
  1318. this.debugGraphics = null;
  1319. }
  1320. }
  1321. public setDebugDrawSnapRange(enabled: boolean) {
  1322. this.debugDrawSnapRange = enabled;
  1323. // 调试绘制功能已禁用
  1324. }
  1325. onDisable() {
  1326. this.removeEventListeners();
  1327. this.cleanupDebugDraw();
  1328. }
  1329. onDestroy() {
  1330. this.removeEventListeners();
  1331. this.cleanupDebugDraw();
  1332. }
  1333. // 移除事件监听器
  1334. private removeEventListeners() {
  1335. const eventBus = EventBus.getInstance();
  1336. eventBus.off(GameEvents.RESET_BLOCK_SELECTION, this.onResetBlockSelectionEvent, this);
  1337. eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1338. eventBus.off(GameEvents.GAME_START, this.updateGuideButtonStates, this);
  1339. eventBus.off(GameEvents.ENTER_PLAYING_STATE, this.updateGuideButtonStates, this);
  1340. eventBus.off(GameEvents.ENEMY_START_GAME, this.updateGuideButtonStates, this);
  1341. eventBus.off(GameEvents.ENEMY_UPDATE_COUNT, this.updateGuideButtonStates, this);
  1342. eventBus.off(GameEvents.ENEMY_START_WAVE, this.updateGuideButtonStates, this);
  1343. eventBus.off(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.onSetupBlockDragEventsEvent, this);
  1344. eventBus.off(GameEvents.FORCE_END_ALL_DRAGS, this.onForceEndAllDrags, this);
  1345. }
  1346. // 强制结束当前拖拽:用于教程自动放置发生时,立即清空拖拽上下文
  1347. private onForceEndAllDrags() {
  1348. if (!this.currentDragBlock || !this.currentDragBlock.isValid) {
  1349. return;
  1350. }
  1351. try {
  1352. // 清除拖拽标记并恢复碰撞
  1353. (this.currentDragBlock as any)['isDragging'] = false;
  1354. const rootCol = this.currentDragBlock.getComponent(Collider2D);
  1355. if (rootCol && !rootCol.enabled) rootCol.enabled = true;
  1356. const b1 = this.currentDragBlock.getChildByName('B1');
  1357. if (b1) {
  1358. const b1Col = b1.getComponent(Collider2D);
  1359. if (b1Col && !b1Col.enabled) b1Col.enabled = true;
  1360. }
  1361. // 根据方块原始位置决定是否需要回到kuang容器
  1362. const startLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  1363. if (startLocation && startLocation !== 'grid') {
  1364. this.returnBlockToKuang(startLocation);
  1365. }
  1366. // 统一抛出拖拽结束事件,维持各模块状态一致
  1367. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: this.currentDragBlock });
  1368. } catch (e) {
  1369. console.warn('[GameBlockSelection] 强制结束拖拽失败:', e);
  1370. } finally {
  1371. this.currentDragBlock = null;
  1372. }
  1373. }
  1374. /**
  1375. * 获取方块的原始位置
  1376. * @param block 方块节点
  1377. * @returns 原始位置标识符
  1378. */
  1379. private getBlockOriginalLocation(block: Node): string | null {
  1380. // 检查方块是否在block1Container中
  1381. if (this.blockManager.block1Container && this.isBlockInContainer(block, this.blockManager.block1Container)) {
  1382. return 'block1';
  1383. }
  1384. // 检查方块是否在block2Container中
  1385. if (this.blockManager.block2Container && this.isBlockInContainer(block, this.blockManager.block2Container)) {
  1386. return 'block2';
  1387. }
  1388. // 检查方块是否在block3Container中
  1389. if (this.blockManager.block3Container && this.isBlockInContainer(block, this.blockManager.block3Container)) {
  1390. return 'block3';
  1391. }
  1392. return null;
  1393. }
  1394. /**
  1395. * 检查方块是否在指定容器中
  1396. * @param block 方块节点
  1397. * @param container 容器节点
  1398. * @returns 是否在容器中
  1399. */
  1400. private isBlockInContainer(block: Node, container: Node): boolean {
  1401. let parent = block.parent;
  1402. while (parent) {
  1403. if (parent === container) {
  1404. return true;
  1405. }
  1406. parent = parent.parent;
  1407. }
  1408. return false;
  1409. }
  1410. // === 价格配置管理方法 ===
  1411. // 更新价格显示
  1412. private updatePriceDisplay() {
  1413. // 更新新增小球价格显示 - 使用装饰器绑定的节点
  1414. if (this.addBallPriceNode) {
  1415. console.log(`[GameBlockSelection] 更新新增小球价格显示: ${this.getAddBallCost()}`);
  1416. const label = this.addBallPriceNode.getComponent(Label);
  1417. if (label) {
  1418. label.string = this.getAddBallCost().toString();
  1419. }
  1420. } else {
  1421. // 回退到find方法(兼容性)
  1422. const addBallPriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann001/Ball/db01/Price');
  1423. if (addBallPriceNode) {
  1424. const label = addBallPriceNode.getComponent(Label);
  1425. if (label) {
  1426. label.string = this.getAddBallCost().toString();
  1427. }
  1428. }
  1429. }
  1430. // 更新刷新方块价格显示 - 使用装饰器绑定的节点
  1431. if (this.refreshBlockPriceNode) {
  1432. console.log(`[GameBlockSelection] 更新刷新方块价格显示: ${this.getRefreshCost()}`);
  1433. const label = this.refreshBlockPriceNode.getComponent(Label);
  1434. if (label) {
  1435. label.string = this.getRefreshCost().toString();
  1436. }
  1437. } else {
  1438. // 回退到find方法(兼容性)
  1439. const refreshPriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann003/Ball/db01/Price');
  1440. if (refreshPriceNode) {
  1441. const label = refreshPriceNode.getComponent(Label);
  1442. if (label) {
  1443. label.string = this.getRefreshCost().toString();
  1444. }
  1445. }
  1446. }
  1447. }
  1448. // 更新奖励显示
  1449. private updateRewardDisplay() {
  1450. // 更新增加金币奖励显示 - 使用装饰器绑定的节点
  1451. if (this.addCoinRewardNode) {
  1452. const label = this.addCoinRewardNode.getComponent(Label);
  1453. if (label) {
  1454. label.string = this.getAddCoinReward().toString();
  1455. }
  1456. } else {
  1457. // 回退到find方法(兼容性)
  1458. try {
  1459. const rewardNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann002/db01/addCoin');
  1460. if (rewardNode) {
  1461. const label = rewardNode.getComponent(Label);
  1462. if (label) {
  1463. label.string = this.getAddCoinReward().toString();
  1464. }
  1465. }
  1466. } catch (error) {
  1467. console.warn('[GameBlockSelection] 更新增加金币奖励显示失败:', error);
  1468. }
  1469. }
  1470. }
  1471. }