GameBlockSelection.ts 61 KB

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