GameBlockSelection.ts 57 KB

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