GameBlockSelection.ts 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  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. // 发出方块选择确认事件(用于新手引导第三步结束)
  502. EventBus.getInstance().emit(GameEvents.BLOCK_SELECTION_CONFIRMED);
  503. // 播放下滑diban动画,结束备战进入playing状态
  504. this.playDibanSlideDownAnimation();
  505. }
  506. // 播放diban下滑动画
  507. private playDibanSlideDownAnimation() {
  508. // 开始播放diban下滑动画
  509. // 使用装饰器属性获取Camera节点上的GameStartMove组件
  510. if (!this.cameraNode) {
  511. console.warn('[GameBlockSelection] Camera节点未设置,请在Inspector中拖拽Canvas/Camera节点');
  512. return;
  513. }
  514. const gameStartMove = this.cameraNode.getComponent('GameStartMove');
  515. if (!gameStartMove) {
  516. console.warn('[GameBlockSelection] GameStartMove组件未找到');
  517. return;
  518. }
  519. // 调用GameStartMove的下滑动画方法
  520. (gameStartMove as any).slideDibanDownAndHide(0.3);
  521. // 已调用GameStartMove的diban下滑动画
  522. }
  523. // 保存已放置的方块(从GameManager迁移)
  524. private preservePlacedBlocks() {
  525. if (this.blockManager) {
  526. this.blockManager.onGameStart();
  527. }
  528. }
  529. // 检查是否有足够金币
  530. private canSpendCoins(amount: number): boolean {
  531. return this.session.getCoins() >= amount;
  532. }
  533. // 计算应用便宜技能效果后的实际费用
  534. private getActualCost(baseCost: number): number {
  535. const skillManager = SkillManager.getInstance();
  536. if (skillManager) {
  537. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  538. return Math.ceil(SkillManager.calculateCheaperUnitsPrice(baseCost, cheaperSkillLevel));
  539. }
  540. return baseCost;
  541. }
  542. // 更新金币显示
  543. private updateCoinDisplay() {
  544. if (this.coinLabelNode) {
  545. const label = this.coinLabelNode.getComponent(Label);
  546. if (label) {
  547. const coins = this.session.getCoins();
  548. label.string = coins.toString();
  549. // 更新金币显示
  550. } else {
  551. console.warn('[GameBlockSelection] coinLabelNode缺少Label组件');
  552. }
  553. } else {
  554. console.warn('[GameBlockSelection] coinLabelNode未找到');
  555. }
  556. }
  557. // 显示金币不足UI
  558. private showInsufficientCoinsUI() {
  559. // 使用事件机制显示资源不足Toast
  560. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  561. message: '金币不足!',
  562. duration: 3.0
  563. });
  564. // 金币不足
  565. }
  566. // === 公共方法:供GameManager调用 ===
  567. // 生成方块选择(不再控制UI显示,只负责生成方块)
  568. public generateBlockSelection() {
  569. // 直接生成方块,不再依赖shouldGenerateBlocks标志
  570. if (this.blockManager) {
  571. this.blockManager.refreshBlocks();
  572. } else {
  573. console.warn('[GameBlockSelection] BlockManager未找到,无法生成随机方块');
  574. }
  575. // 触发进入备战状态事件
  576. EventBus.getInstance().emit(GameEvents.ENTER_BATTLE_PREPARATION);
  577. }
  578. // 设置确认回调
  579. public setConfirmCallback(callback: () => void) {
  580. this.onConfirmCallback = callback;
  581. }
  582. // 统一的方块占用情况刷新方法
  583. public refreshGridOccupation() {
  584. if (this.blockManager) {
  585. this.blockManager.resetGridOccupation();
  586. // 重新计算所有已放置方块的占用情况
  587. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  588. if (placedBlocksContainer) {
  589. for (let i = 0; i < placedBlocksContainer.children.length; i++) {
  590. const block = placedBlocksContainer.children[i];
  591. // 按照BlockManager.tryPlaceBlockToGrid的正确方法获取位置
  592. let b1Node = block;
  593. if (block.name !== 'B1') {
  594. b1Node = block.getChildByName('B1');
  595. if (!b1Node) {
  596. console.warn(`[GameBlockSelection] 方块 ${block.name} 没有B1子节点`);
  597. continue;
  598. }
  599. }
  600. // 获取B1节点的世界坐标,然后转换为网格本地坐标
  601. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  602. const gridPos = this.blockManager.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  603. // 重新标记方块占用的网格位置
  604. const gridNode = this.blockManager.findNearestGridNode(gridPos);
  605. if (gridNode) {
  606. this.blockManager.markOccupiedPositions(block, gridNode);
  607. } else {
  608. console.warn(`[GameBlockSelection] 方块 ${block.name} 未找到对应的网格节点`);
  609. }
  610. }
  611. }
  612. } else {
  613. console.warn('[GameBlockSelection] BlockManager未找到,无法刷新占用情况');
  614. }
  615. this.blockManager.printGridOccupationMatrix();
  616. }
  617. // 重置方块选择状态
  618. public resetSelection() {
  619. // 重置方块生成标志,等待下次onBattle触发
  620. this.shouldGenerateBlocks = false;
  621. // 注意:不再直接调用blockManager.onGameReset(),因为StartGame.clearGameStates()
  622. // 已经通过RESET_BLOCK_MANAGER事件触发了BlockManager的重置,避免重复生成方块
  623. // 清理所有方块标签
  624. BlockTag.clearAllTags();
  625. // 更新价格显示(使用次数已在session中重置)
  626. this.updatePriceDisplay();
  627. // 更新金币显示
  628. this.updateCoinDisplay();
  629. }
  630. // 检查是否有上阵方块
  631. private hasPlacedBlocks(): boolean {
  632. // 优先使用BlockManager的方法检查
  633. if (this.blockManager) {
  634. return this.blockManager.hasPlacedBlocks();
  635. }
  636. // 备用方案:直接检查PlacedBlocks容器
  637. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  638. if (!placedBlocksContainer) {
  639. console.warn('找不到PlacedBlocks容器');
  640. return false;
  641. }
  642. // 检查容器中是否有子节点(方块)
  643. return placedBlocksContainer.children.length > 0;
  644. }
  645. // 显示没有上阵方块的Toast提示
  646. private showNoPlacedBlocksToast() {
  647. // 使用事件机制显示Toast
  648. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  649. message: '请至少上阵一个植物!',
  650. duration: 3.0
  651. });
  652. }
  653. // 设置方块拖拽事件
  654. public setupBlockDragEvents(block: Node) {
  655. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  656. // 检查游戏是否已开始
  657. if (!this.blockManager.gameStarted) {
  658. return;
  659. }
  660. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  661. const blockLocation = this.blockManager.blockLocations.get(block);
  662. // grid区域的方块目前允许自由移动
  663. this.currentDragBlock = block;
  664. this.startPos = event.getUILocation();
  665. this.blockStartPos.set(block.position);
  666. this.currentDragBlock['startLocation'] = blockLocation;
  667. // 如果方块在grid区域,拿起时清除其占用状态
  668. if (blockLocation === 'grid') {
  669. this.blockManager.clearOccupiedPositions(block);
  670. // 输出更新后的占用情况
  671. this.blockManager.printGridOccupationMatrix();
  672. }
  673. // 设置拖动状态,隐藏价格标签
  674. block['isDragging'] = true;
  675. block.setSiblingIndex(block.parent.children.length - 1);
  676. // 拖拽开始时禁用碰撞体
  677. const collider = block.getComponent(Collider2D);
  678. if (collider) collider.enabled = false;
  679. // 通知BallController有方块开始拖拽
  680. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_START, { block: block });
  681. }, this);
  682. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  683. // 检查游戏是否已开始
  684. if (!this.blockManager.gameStarted) {
  685. return;
  686. }
  687. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  688. const blockLocation = this.blockManager.blockLocations.get(block);
  689. // 教程阶段:第6步结束前禁止移动已上阵方块(第4步除外)
  690. if (blockLocation === 'grid' && !this.blockManager.canMovePlacedBlocks()) {
  691. return;
  692. }
  693. if (!this.currentDragBlock) return;
  694. const location = event.getUILocation();
  695. const deltaX = location.x - this.startPos.x;
  696. const deltaY = location.y - this.startPos.y;
  697. this.currentDragBlock.position = new Vec3(
  698. this.blockStartPos.x + deltaX,
  699. this.blockStartPos.y + deltaY,
  700. this.blockStartPos.z
  701. );
  702. }, this);
  703. block.on(Node.EventType.TOUCH_END, async (event: EventTouch) => {
  704. // 检查游戏是否已开始
  705. if (!this.blockManager.gameStarted) {
  706. return;
  707. }
  708. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  709. const blockLocation = this.blockManager.blockLocations.get(block);
  710. // 教程阶段:第6步结束前禁止移动已上阵方块(第4步除外)
  711. if (blockLocation === 'grid' && !this.blockManager.canMovePlacedBlocks()) {
  712. return;
  713. }
  714. if (this.currentDragBlock) {
  715. try {
  716. await this.handleBlockDrop(event);
  717. } catch (error) {
  718. console.error('[GameBlockSelection] 处理方块拖拽放置时发生错误:', error);
  719. // 发生错误时,将方块返回原位置
  720. this.returnBlockToOriginalPosition();
  721. }
  722. // 清除拖动状态,恢复价格标签显示
  723. block['isDragging'] = false;
  724. this.currentDragBlock = null;
  725. // 拖拽结束时恢复碰撞体
  726. const collider = block.getComponent(Collider2D);
  727. if (collider) collider.enabled = true;
  728. // 通知BallController方块拖拽结束
  729. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: block });
  730. }
  731. }, this);
  732. block.on(Node.EventType.TOUCH_CANCEL, () => {
  733. if (this.currentDragBlock) {
  734. this.returnBlockToOriginalPosition();
  735. // 清除拖动状态,恢复价格标签显示
  736. block['isDragging'] = false;
  737. this.currentDragBlock = null;
  738. // 拖拽取消时恢复碰撞体
  739. const collider = block.getComponent(Collider2D);
  740. if (collider) collider.enabled = true;
  741. // 通知BallController方块拖拽结束
  742. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: block });
  743. }
  744. }, this);
  745. }
  746. // 处理方块放下
  747. private async handleBlockDrop(event: EventTouch) {
  748. try {
  749. const touchPos = event.getLocation();
  750. const startLocation = this.currentDragBlock['startLocation'];
  751. if (this.isInKuangArea(touchPos)) {
  752. // 检查是否有标签,只有有标签的方块才能放回kuang
  753. if (BlockTag.hasTag(this.currentDragBlock)) {
  754. this.returnBlockToKuang(startLocation);
  755. } else {
  756. // 没有标签的方块不能放回kuang,返回原位置
  757. this.returnBlockToOriginalPosition();
  758. }
  759. } else if (this.blockManager.tryPlaceBlockToGrid(this.currentDragBlock)) {
  760. await this.handleSuccessfulPlacement(startLocation);
  761. } else {
  762. // 放置失败,尝试直接与重叠方块合成
  763. // 先检查金币是否充足(如果来自kuang区域)
  764. if (startLocation !== 'grid') {
  765. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  766. if (!this.canSpendCoins(price)) {
  767. // 金币不足时显示价格标签闪烁效果和Toast提示
  768. this.blockManager.showInsufficientCoinsEffect(this.currentDragBlock);
  769. this.returnBlockToOriginalPosition();
  770. return;
  771. }
  772. }
  773. if (this.blockManager.tryMergeOnOverlap(this.currentDragBlock)) {
  774. // 合成成功时,若来自 kuang 则扣费
  775. if (startLocation !== 'grid') {
  776. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  777. this.blockManager.deductPlayerCoins(price);
  778. }
  779. // 当前拖拽块已被销毁(合并时),无需复位
  780. } else {
  781. this.returnBlockToOriginalPosition();
  782. }
  783. }
  784. } catch (error) {
  785. console.error('[GameBlockSelection] handleBlockDrop 发生错误:', error);
  786. // 发生错误时,将方块返回原位置
  787. this.returnBlockToOriginalPosition();
  788. throw error; // 重新抛出错误,让上层处理
  789. } finally {
  790. // 无论成功还是失败,都要清理拖拽状态
  791. if (this.currentDragBlock && this.currentDragBlock.isValid) {
  792. // 重新启用碰撞器
  793. const collider = this.currentDragBlock.getComponent(Collider2D);
  794. if (collider) {
  795. collider.enabled = true;
  796. console.log('[GameBlockSelection] 拖拽结束,重新启用碰撞器:', this.currentDragBlock.name);
  797. }
  798. // 发射拖拽结束事件
  799. console.log('[GameBlockSelection] 发射 BLOCK_DRAG_END 事件:', this.currentDragBlock.name);
  800. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: this.currentDragBlock });
  801. }
  802. // 清理拖拽状态
  803. this.currentDragBlock = null;
  804. }
  805. // 刷新方块占用情况
  806. this.refreshGridOccupation();
  807. }
  808. // 检查是否在kuang区域内
  809. private isInKuangArea(touchPos: Vec2): boolean {
  810. // 检查是否在任何一个Block容器区域内
  811. const blockContainers = [
  812. this.blockManager.block1Container,
  813. this.blockManager.block2Container,
  814. this.blockManager.block3Container
  815. ];
  816. for (const container of blockContainers) {
  817. if (container) {
  818. const transform = container.getComponent(UITransform);
  819. if (transform) {
  820. const boundingBox = new Rect(
  821. container.worldPosition.x - transform.width * transform.anchorX,
  822. container.worldPosition.y - transform.height * transform.anchorY,
  823. transform.width,
  824. transform.height
  825. );
  826. if (boundingBox.contains(new Vec2(touchPos.x, touchPos.y))) {
  827. return true;
  828. }
  829. }
  830. }
  831. }
  832. // 如果Block容器都不可用,回退到检查kuang容器
  833. if (this.blockManager.kuangContainer) {
  834. const kuangTransform = this.blockManager.kuangContainer.getComponent(UITransform);
  835. if (kuangTransform) {
  836. const kuangBoundingBox = new Rect(
  837. this.blockManager.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  838. this.blockManager.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  839. kuangTransform.width,
  840. kuangTransform.height
  841. );
  842. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  843. }
  844. }
  845. return false;
  846. }
  847. // 返回方块到对应的Block容器区域
  848. private returnBlockToKuang(startLocation: string) {
  849. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  850. const blockLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  851. if (originalPos) {
  852. // 根据方块的原始位置确定应该返回到哪个Block容器
  853. let targetContainer: Node = null;
  854. let targetLocation = 'kuang'; // 默认位置
  855. if (blockLocation && blockLocation.startsWith('block')) {
  856. // 如果方块原本在Block容器中,返回到对应的容器
  857. if (blockLocation === 'block1') {
  858. targetContainer = this.blockManager.block1Container;
  859. targetLocation = 'block1';
  860. } else if (blockLocation === 'block2') {
  861. targetContainer = this.blockManager.block2Container;
  862. targetLocation = 'block2';
  863. } else if (blockLocation === 'block3') {
  864. targetContainer = this.blockManager.block3Container;
  865. targetLocation = 'block3';
  866. }
  867. }
  868. // 如果没有找到对应的Block容器,回退到kuang容器
  869. if (!targetContainer) {
  870. targetContainer = this.blockManager.kuangContainer;
  871. targetLocation = 'kuang';
  872. }
  873. if (targetContainer && this.currentDragBlock.parent !== targetContainer) {
  874. this.currentDragBlock.removeFromParent();
  875. targetContainer.addChild(this.currentDragBlock);
  876. }
  877. this.currentDragBlock.position = originalPos.clone();
  878. this.blockManager.blockLocations.set(this.currentDragBlock, targetLocation);
  879. }
  880. // 当方块返回kuang区域时,重新设置植物图标缩放至0.4倍
  881. const weaponNode = this.findWeaponNodeInBlock(this.currentDragBlock);
  882. if (weaponNode) {
  883. weaponNode.setScale(0.4, 0.4, 1);
  884. // 方块返回kuang区域,设置植物图标缩放: 0.4倍
  885. }
  886. if (startLocation === 'grid') {
  887. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  888. this.blockManager.refundPlayerCoins(price);
  889. this.currentDragBlock['placedBefore'] = false;
  890. }
  891. // 显示对应的db标签节点
  892. this.showDbNodeByBlockLocation(this.currentDragBlock);
  893. }
  894. /**
  895. * 为方块的武器节点添加武器信息组件
  896. * @param block 方块节点
  897. */
  898. private attachWeaponInfoToBlock(block: Node): void {
  899. try {
  900. // 查找方块中的Weapon节点
  901. const weaponNode = this.findWeaponNodeInBlock(block);
  902. if (!weaponNode) {
  903. console.warn(`[GameBlockSelection] 方块 ${block.name} 中未找到Weapon节点,无法添加武器信息组件`);
  904. return;
  905. }
  906. // 检查是否已经有WeaponInfo组件
  907. let weaponInfo = weaponNode.getComponent(WeaponInfo);
  908. if (weaponInfo) {
  909. return;
  910. }
  911. // 添加WeaponInfo组件
  912. weaponInfo = weaponNode.addComponent(WeaponInfo);
  913. // 获取方块的武器配置
  914. const weaponConfig = this.blockManager.getBlockWeaponConfig(block);
  915. if (weaponConfig) {
  916. // 设置武器配置到WeaponInfo组件
  917. weaponInfo.setWeaponConfig(weaponConfig);
  918. } else {
  919. console.warn(`[GameBlockSelection] 方块 ${block.name} 没有武器配置,无法设置武器信息`);
  920. // 移除刚添加的组件
  921. weaponNode.removeComponent(WeaponInfo);
  922. }
  923. } catch (error) {
  924. console.error(`[GameBlockSelection] 为方块 ${block.name} 添加武器信息组件时发生错误:`, error);
  925. }
  926. }
  927. /**
  928. * 在方块中查找Weapon节点
  929. * @param block 方块节点
  930. * @returns Weapon节点,如果未找到返回null
  931. */
  932. private findWeaponNodeInBlock(block: Node): Node | null {
  933. if (!block || !block.isValid) {
  934. return null;
  935. }
  936. // 根据新的预制体结构,武器节点直接位于方块根节点下
  937. const weaponNode = block.getChildByName('Weapon');
  938. if (weaponNode) {
  939. return weaponNode;
  940. }
  941. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  942. const b1Node = block.getChildByName('B1');
  943. if (b1Node) {
  944. const b1WeaponNode = b1Node.getChildByName('Weapon');
  945. if (b1WeaponNode) {
  946. return b1WeaponNode;
  947. }
  948. }
  949. // 最后使用递归方式查找(兼容其他可能的结构)
  950. const findWeaponRecursive = (node: Node): Node | null => {
  951. if (node.name === 'Weapon') {
  952. return node;
  953. }
  954. for (let i = 0; i < node.children.length; i++) {
  955. const result = findWeaponRecursive(node.children[i]);
  956. if (result) {
  957. return result;
  958. }
  959. }
  960. return null;
  961. };
  962. return findWeaponRecursive(block);
  963. }
  964. // 根据方块位置隐藏对应的db标签节点
  965. private hideDbNodeByBlockLocation(block: Node) {
  966. const originalLocation = this.getBlockOriginalLocation(block);
  967. if (originalLocation === 'block1') {
  968. console.log(`[GameBlockSelection] 隐藏block1的db标签节点`);
  969. const blockInContainer = this.getBlockInContainer(this.blockManager.block1Container);
  970. if (blockInContainer) {
  971. this.blockManager.hideDbLabel(blockInContainer);
  972. }
  973. } else if (originalLocation === 'block2') {
  974. console.log(`[GameBlockSelection] 隐藏block2的db标签节点`);
  975. const blockInContainer = this.getBlockInContainer(this.blockManager.block2Container);
  976. if (blockInContainer) {
  977. this.blockManager.hideDbLabel(blockInContainer);
  978. }
  979. } else if (originalLocation === 'block3') {
  980. console.log(`[GameBlockSelection] 隐藏block3的db标签节点`);
  981. const blockInContainer = this.getBlockInContainer(this.blockManager.block3Container);
  982. if (blockInContainer) {
  983. this.blockManager.hideDbLabel(blockInContainer);
  984. }
  985. }
  986. }
  987. // 根据方块位置显示对应的db标签节点
  988. private showDbNodeByBlockLocation(block: Node) {
  989. const originalLocation = this.getBlockOriginalLocation(block);
  990. if (originalLocation === 'block1') {
  991. const blockInContainer = this.getBlockInContainer(this.blockManager.block1Container);
  992. if (blockInContainer) {
  993. this.blockManager.showDbLabel(blockInContainer);
  994. }
  995. } else if (originalLocation === 'block2') {
  996. const blockInContainer = this.getBlockInContainer(this.blockManager.block2Container);
  997. if (blockInContainer) {
  998. this.blockManager.showDbLabel(blockInContainer);
  999. }
  1000. } else if (originalLocation === 'block3') {
  1001. const blockInContainer = this.getBlockInContainer(this.blockManager.block3Container);
  1002. if (blockInContainer) {
  1003. this.blockManager.showDbLabel(blockInContainer);
  1004. }
  1005. }
  1006. }
  1007. // 获取容器中的方块节点
  1008. private getBlockInContainer(container: Node): Node | null {
  1009. if (!container) {
  1010. return null;
  1011. }
  1012. // 查找容器中的方块节点(通常以Block命名或有B1子节点)
  1013. for (let i = 0; i < container.children.length; i++) {
  1014. const child = container.children[i];
  1015. if (child.name.includes('Block') || child.getChildByName('B1')) {
  1016. return child;
  1017. }
  1018. }
  1019. return null;
  1020. }
  1021. // 处理成功放置
  1022. private async handleSuccessfulPlacement(startLocation: string) {
  1023. try {
  1024. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  1025. if (startLocation === 'grid') {
  1026. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  1027. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  1028. // 隐藏对应的db标签节点
  1029. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  1030. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  1031. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  1032. // 为武器节点添加武器信息组件
  1033. this.attachWeaponInfoToBlock(this.currentDragBlock);
  1034. // 如果游戏已开始,添加锁定视觉提示
  1035. if (this.blockManager.gameStarted) {
  1036. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  1037. BlockTag.removeTag(this.currentDragBlock);
  1038. }
  1039. // 检查并执行合成
  1040. try {
  1041. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  1042. } catch (mergeError) {
  1043. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  1044. }
  1045. } else {
  1046. if (this.blockManager.deductPlayerCoins(price)) {
  1047. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  1048. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  1049. // 隐藏对应的db标签节点
  1050. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  1051. this.currentDragBlock['placedBefore'] = true;
  1052. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  1053. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  1054. // 为武器节点添加武器信息组件
  1055. this.attachWeaponInfoToBlock(this.currentDragBlock);
  1056. // 如果游戏已开始,添加锁定视觉提示
  1057. if (this.blockManager.gameStarted) {
  1058. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  1059. // 游戏开始后放置的方块移除标签,不能再放回kuang
  1060. BlockTag.removeTag(this.currentDragBlock);
  1061. }
  1062. // 检查并执行合成
  1063. try {
  1064. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  1065. } catch (mergeError) {
  1066. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  1067. // 合成失败不影响方块放置,只记录错误
  1068. }
  1069. } else {
  1070. // 金币不足时显示价格标签闪烁效果和Toast提示
  1071. this.blockManager.showInsufficientCoinsEffect(this.currentDragBlock);
  1072. this.returnBlockToOriginalPosition();
  1073. }
  1074. }
  1075. } catch (error) {
  1076. console.error('[GameBlockSelection] handleSuccessfulPlacement 发生错误:', error);
  1077. // 发生错误时,将方块返回原位置
  1078. this.returnBlockToOriginalPosition();
  1079. throw error; // 重新抛出错误,让上层处理
  1080. }
  1081. }
  1082. // 返回方块到原位置
  1083. private returnBlockToOriginalPosition() {
  1084. const currentLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  1085. const startLocation = this.currentDragBlock['startLocation'];
  1086. if (currentLocation === 'kuang') {
  1087. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  1088. if (originalPos) {
  1089. this.currentDragBlock.position = originalPos.clone();
  1090. }
  1091. } else {
  1092. this.currentDragBlock.position = this.blockStartPos.clone();
  1093. // 如果方块原本在grid区域,返回原位置后需要重新标记占用状态
  1094. if (startLocation === 'grid') {
  1095. // 获取方块当前位置对应的网格节点
  1096. let b1Node = this.currentDragBlock;
  1097. if (this.currentDragBlock.name !== 'B1') {
  1098. b1Node = this.currentDragBlock.getChildByName('B1');
  1099. }
  1100. if (b1Node) {
  1101. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  1102. const gridPos = this.blockManager.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  1103. const gridNode = this.blockManager.findNearestGridNode(gridPos);
  1104. if (gridNode) {
  1105. this.blockManager.markOccupiedPositions(this.currentDragBlock, gridNode);
  1106. // 输出更新后的占用情况
  1107. this.blockManager.printGridOccupationMatrix();
  1108. }
  1109. }
  1110. }
  1111. }
  1112. // 清除拖动状态,恢复db节点显示
  1113. this.currentDragBlock['isDragging'] = false;
  1114. this.showDbNodeByBlockLocation(this.currentDragBlock);
  1115. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  1116. }
  1117. // === 调试绘制相关方法 ===
  1118. private initDebugDraw() {
  1119. // 调试绘制功能已禁用
  1120. }
  1121. private drawGridSnapRanges() {
  1122. // 调试绘制功能已禁用
  1123. }
  1124. private drawBlockSnapRange(block: Node) {
  1125. // 调试绘制功能已禁用
  1126. }
  1127. private updateDebugDraw() {
  1128. // 调试绘制功能已禁用
  1129. }
  1130. // 清理调试绘制
  1131. private cleanupDebugDraw() {
  1132. if (this.debugDrawNode && this.debugDrawNode.isValid) {
  1133. this.debugDrawNode.destroy();
  1134. this.debugDrawNode = null;
  1135. this.debugGraphics = null;
  1136. }
  1137. }
  1138. public setDebugDrawSnapRange(enabled: boolean) {
  1139. this.debugDrawSnapRange = enabled;
  1140. // 调试绘制功能已禁用
  1141. }
  1142. onDisable() {
  1143. this.removeEventListeners();
  1144. this.cleanupDebugDraw();
  1145. }
  1146. onDestroy() {
  1147. this.removeEventListeners();
  1148. this.cleanupDebugDraw();
  1149. }
  1150. // 移除事件监听器
  1151. private removeEventListeners() {
  1152. const eventBus = EventBus.getInstance();
  1153. eventBus.off(GameEvents.RESET_BLOCK_SELECTION, this.onResetBlockSelectionEvent, this);
  1154. eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1155. eventBus.off(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.onSetupBlockDragEventsEvent, this);
  1156. }
  1157. /**
  1158. * 获取方块的原始位置
  1159. * @param block 方块节点
  1160. * @returns 原始位置标识符
  1161. */
  1162. private getBlockOriginalLocation(block: Node): string | null {
  1163. // 检查方块是否在block1Container中
  1164. if (this.blockManager.block1Container && this.isBlockInContainer(block, this.blockManager.block1Container)) {
  1165. return 'block1';
  1166. }
  1167. // 检查方块是否在block2Container中
  1168. if (this.blockManager.block2Container && this.isBlockInContainer(block, this.blockManager.block2Container)) {
  1169. return 'block2';
  1170. }
  1171. // 检查方块是否在block3Container中
  1172. if (this.blockManager.block3Container && this.isBlockInContainer(block, this.blockManager.block3Container)) {
  1173. return 'block3';
  1174. }
  1175. return null;
  1176. }
  1177. /**
  1178. * 检查方块是否在指定容器中
  1179. * @param block 方块节点
  1180. * @param container 容器节点
  1181. * @returns 是否在容器中
  1182. */
  1183. private isBlockInContainer(block: Node, container: Node): boolean {
  1184. let parent = block.parent;
  1185. while (parent) {
  1186. if (parent === container) {
  1187. return true;
  1188. }
  1189. parent = parent.parent;
  1190. }
  1191. return false;
  1192. }
  1193. // === 价格配置管理方法 ===
  1194. // 更新价格显示
  1195. private updatePriceDisplay() {
  1196. // 更新新增小球价格显示 - 使用装饰器绑定的节点
  1197. if (this.addBallPriceNode) {
  1198. console.log(`[GameBlockSelection] 更新新增小球价格显示: ${this.getAddBallCost()}`);
  1199. const label = this.addBallPriceNode.getComponent(Label);
  1200. if (label) {
  1201. label.string = this.getAddBallCost().toString();
  1202. }
  1203. } else {
  1204. // 回退到find方法(兼容性)
  1205. const addBallPriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann001/Ball/db01/Price');
  1206. if (addBallPriceNode) {
  1207. const label = addBallPriceNode.getComponent(Label);
  1208. if (label) {
  1209. label.string = this.getAddBallCost().toString();
  1210. }
  1211. }
  1212. }
  1213. // 更新刷新方块价格显示 - 使用装饰器绑定的节点
  1214. if (this.refreshBlockPriceNode) {
  1215. console.log(`[GameBlockSelection] 更新刷新方块价格显示: ${this.getRefreshCost()}`);
  1216. const label = this.refreshBlockPriceNode.getComponent(Label);
  1217. if (label) {
  1218. label.string = this.getRefreshCost().toString();
  1219. }
  1220. } else {
  1221. // 回退到find方法(兼容性)
  1222. const refreshPriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann003/Ball/db01/Price');
  1223. if (refreshPriceNode) {
  1224. const label = refreshPriceNode.getComponent(Label);
  1225. if (label) {
  1226. label.string = this.getRefreshCost().toString();
  1227. }
  1228. }
  1229. }
  1230. }
  1231. // 更新奖励显示
  1232. private updateRewardDisplay() {
  1233. // 更新增加金币奖励显示 - 使用装饰器绑定的节点
  1234. if (this.addCoinRewardNode) {
  1235. const label = this.addCoinRewardNode.getComponent(Label);
  1236. if (label) {
  1237. label.string = this.getAddCoinReward().toString();
  1238. }
  1239. } else {
  1240. // 回退到find方法(兼容性)
  1241. try {
  1242. const rewardNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann002/db01/addCoin');
  1243. if (rewardNode) {
  1244. const label = rewardNode.getComponent(Label);
  1245. if (label) {
  1246. label.string = this.getAddCoinReward().toString();
  1247. }
  1248. }
  1249. } catch (error) {
  1250. console.warn('[GameBlockSelection] 更新增加金币奖励显示失败:', error);
  1251. }
  1252. }
  1253. }
  1254. }