GameBlockSelection.ts 74 KB

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