GameBlockSelection.ts 68 KB

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