GameBlockSelection.ts 76 KB

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