GameBlockSelection.ts 69 KB

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