GameBlockSelection.ts 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. import { _decorator, Component, Node, Button, Label, find, EventTouch, Vec2, Vec3, UITransform, Rect, Collider2D, Graphics, Color, JsonAsset } 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 EventBus, { GameEvents } from '../../Core/EventBus';
  12. const { ccclass, property } = _decorator;
  13. @ccclass('GameBlockSelection')
  14. export class GameBlockSelection extends Component {
  15. @property({
  16. type: Node,
  17. tooltip: '拖拽diban/ann001按钮节点到这里'
  18. })
  19. public addBallButton: Node = null;
  20. @property({
  21. type: Node,
  22. tooltip: '拖拽diban/ann002按钮节点到这里'
  23. })
  24. public addCoinButton: Node = null;
  25. @property({
  26. type: Node,
  27. tooltip: '拖拽diban/ann003按钮节点到这里'
  28. })
  29. public refreshButton: Node = null;
  30. @property({
  31. type: Node,
  32. tooltip: '拖拽Canvas-001/TopArea/CoinNode/CoinLabel节点到这里'
  33. })
  34. public coinLabelNode: Node = null;
  35. @property({
  36. type: Node,
  37. tooltip: '拖拽Canvas/GameLevelUI/BallController节点到这里'
  38. })
  39. public ballControllerNode: Node = null;
  40. @property({
  41. type: Node,
  42. tooltip: '拖拽Canvas/GameLevelUI/BlockController节点到这里'
  43. })
  44. public blockManagerNode: Node = null;
  45. @property({
  46. type: Node,
  47. tooltip: '拖拽Canvas/GameLevelUI/GameArea/GridContainer节点到这里'
  48. })
  49. public gridContainer: Node = null;
  50. @property({
  51. type: Node,
  52. tooltip: '拖拽confirm按钮节点到这里'
  53. })
  54. public confirmButton: Node = null;
  55. @property({
  56. type: Node,
  57. tooltip: '拖拽Canvas/GameLevelUI/InGameManager节点到这里'
  58. })
  59. public inGameManagerNode: Node = null;
  60. @property({
  61. type: Node,
  62. tooltip: '拖拽Canvas/Camera节点到这里'
  63. })
  64. public cameraNode: Node = null;
  65. // 武器配置JsonAsset - 通过装饰器预加载
  66. @property({
  67. type: JsonAsset,
  68. tooltip: '拖拽weapons.json文件到这里,实现配置预加载'
  69. })
  70. public weaponsConfig: JsonAsset = null;
  71. // 小球价格配置JsonAsset - 通过装饰器预加载
  72. @property({
  73. type: JsonAsset,
  74. tooltip: '拖拽ball_price_config.json文件到这里,实现价格配置预加载'
  75. })
  76. public ballPriceConfig: JsonAsset = null;
  77. // 常量定义
  78. private readonly ADD_COIN_AMOUNT = 80;
  79. // 价格配置默认值
  80. private readonly DEFAULT_ADD_BALL_BASE_PRICE = 80;
  81. private readonly DEFAULT_ADD_BALL_INCREMENT = 10;
  82. private readonly DEFAULT_ADD_BALL_MAX_PRICE = 500;
  83. private readonly DEFAULT_REFRESH_BASE_PRICE = 5;
  84. private readonly DEFAULT_REFRESH_INCREMENT = 2;
  85. private readonly DEFAULT_REFRESH_MAX_PRICE = 50;
  86. // 价格获取方法
  87. private getAddBallCost(): number {
  88. if (this.ballPriceConfig && this.ballPriceConfig.json && this.ballPriceConfig.json.priceHistory) {
  89. return this.ballPriceConfig.json.priceHistory.addBallCurrentPrice || this.DEFAULT_ADD_BALL_BASE_PRICE;
  90. }
  91. try {
  92. const priceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann001/Ball/db01/Price');
  93. if (priceNode) {
  94. const label = priceNode.getComponent(Label);
  95. if (label) {
  96. const price = parseInt(label.string);
  97. return isNaN(price) ? this.DEFAULT_ADD_BALL_BASE_PRICE : price;
  98. }
  99. }
  100. } catch (error) {
  101. console.warn('[GameBlockSelection] 获取新增小球价格失败:', error);
  102. }
  103. return this.DEFAULT_ADD_BALL_BASE_PRICE; // 默认价格
  104. }
  105. private getRefreshCost(): number {
  106. if (this.ballPriceConfig && this.ballPriceConfig.json && this.ballPriceConfig.json.priceHistory) {
  107. return this.ballPriceConfig.json.priceHistory.refreshBlockCurrentPrice || this.DEFAULT_REFRESH_BASE_PRICE;
  108. }
  109. try {
  110. const priceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann003/Ball/db01/Price');
  111. if (priceNode) {
  112. const label = priceNode.getComponent(Label);
  113. if (label) {
  114. const price = parseInt(label.string);
  115. return isNaN(price) ? this.DEFAULT_REFRESH_BASE_PRICE : price;
  116. }
  117. }
  118. } catch (error) {
  119. console.warn('[GameBlockSelection] 获取刷新方块价格失败:', error);
  120. }
  121. return this.DEFAULT_REFRESH_BASE_PRICE; // 默认价格
  122. }
  123. private session: LevelSessionManager = null;
  124. private ballController: BallController = null;
  125. private blockManager: BlockManager = null;
  126. // 回调函数,用于通知GameManager
  127. public onConfirmCallback: () => void = null;
  128. // 标记是否已初始化
  129. private isInitialized: boolean = false;
  130. // 标记是否应该生成方块(只有在onBattle触发后才为true)
  131. private shouldGenerateBlocks: boolean = false;
  132. // 用户操作方块相关属性
  133. private currentDragBlock: Node | null = null;
  134. private startPos = new Vec2();
  135. private blockStartPos: Vec3 = new Vec3();
  136. // 调试绘制相关属性
  137. @property({
  138. tooltip: '是否启用吸附检测范围调试绘制'
  139. })
  140. public debugDrawSnapRange: boolean = false;
  141. private debugDrawNode: Node = null;
  142. private debugGraphics: Graphics = null;
  143. onEnable() {
  144. // 如果还未初始化,则进行初始化
  145. if (!this.isInitialized) {
  146. this.initializeComponent();
  147. } else {
  148. // 如果已经初始化,重新设置事件监听器(因为onDisable时会移除)
  149. this.setupEventListeners();
  150. }
  151. // this.initDebugDraw();
  152. }
  153. start() {
  154. // 如果还未初始化,则进行初始化
  155. if (!this.isInitialized) {
  156. this.initializeComponent();
  157. }
  158. }
  159. private initializeComponent() {
  160. // 获取管理器实例
  161. this.session = LevelSessionManager.inst;
  162. // 获取BallController
  163. if (this.ballControllerNode) {
  164. this.ballController = this.ballControllerNode.getComponent(BallController);
  165. } else {
  166. console.warn('BallController节点未绑定,请在Inspector中拖拽Canvas/GameLevelUI/BallController节点');
  167. }
  168. // 获取BlockManager
  169. if (this.blockManagerNode) {
  170. this.blockManager = this.blockManagerNode.getComponent(BlockManager);
  171. // 如果武器配置已通过装饰器预加载,直接传递给BlockManager
  172. if (this.weaponsConfig && this.weaponsConfig.json) {
  173. // 通过公共方法将预加载的配置传递给BlockManager
  174. if (this.blockManager && typeof this.blockManager.setPreloadedWeaponsConfig === 'function') {
  175. this.blockManager.setPreloadedWeaponsConfig(this.weaponsConfig.json);
  176. } else {
  177. console.warn('[GameBlockSelection] BlockManager不支持setPreloadedWeaponsConfig方法');
  178. }
  179. } else {
  180. console.warn('[GameBlockSelection] 武器配置未预加载,请在Inspector中拖拽weapons.json文件到weaponsConfig属性');
  181. }
  182. } else {
  183. console.warn('BlockManager节点未绑定,请在Inspector中拖拽Canvas/GameLevelUI/BlockController节点');
  184. }
  185. // 如果没有指定coinLabelNode,尝试找到它
  186. if (!this.coinLabelNode) {
  187. this.coinLabelNode = find('Canvas-001/TopArea/CoinNode/CoinLabel');
  188. }
  189. // 初始化金币显示
  190. this.updateCoinDisplay();
  191. // 绑定按钮事件
  192. this.bindButtonEvents();
  193. // 设置事件监听器
  194. this.setupEventListeners();
  195. // 更新价格显示
  196. this.updatePriceDisplay();
  197. // 标记为已初始化
  198. this.isInitialized = true;
  199. // 初始化完成
  200. }
  201. // 设置事件监听器
  202. private setupEventListeners() {
  203. const eventBus = EventBus.getInstance();
  204. // 监听重置方块选择事件
  205. eventBus.on(GameEvents.RESET_BLOCK_SELECTION, this.onResetBlockSelectionEvent, this);
  206. // 监听游戏开始事件,用于标记可以开始生成方块
  207. eventBus.on(GameEvents.GAME_START, this.onGameStartEvent, this);
  208. // 监听方块拖拽事件设置请求
  209. eventBus.on(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.onSetupBlockDragEventsEvent, this);
  210. }
  211. // 处理重置方块选择事件
  212. private onResetBlockSelectionEvent() {
  213. this.resetSelection();
  214. }
  215. // 处理游戏开始事件
  216. private onGameStartEvent() {
  217. // 接收到游戏开始事件,允许生成方块
  218. this.shouldGenerateBlocks = true;
  219. }
  220. // 处理方块拖拽事件设置请求
  221. private onSetupBlockDragEventsEvent(blocks: Node[]) {
  222. // 确保组件仍然有效
  223. if (!this.node || !this.node.isValid) {
  224. console.warn('[GameBlockSelection] 组件节点无效,跳过拖拽事件设置');
  225. return;
  226. }
  227. for (const block of blocks) {
  228. if (block && block.isValid) {
  229. // 先移除可能存在的旧事件监听器
  230. block.off(Node.EventType.TOUCH_START);
  231. block.off(Node.EventType.TOUCH_MOVE);
  232. block.off(Node.EventType.TOUCH_END);
  233. block.off(Node.EventType.TOUCH_CANCEL);
  234. // 重新设置拖拽事件
  235. this.setupBlockDragEvents(block);
  236. } else {
  237. // 跳过无效方块的拖拽事件设置
  238. }
  239. }
  240. }
  241. // 绑定按钮事件
  242. private bindButtonEvents() {
  243. // 绑定新增小球按钮
  244. if (this.addBallButton) {
  245. const btn = this.addBallButton.getComponent(Button);
  246. if (btn) {
  247. this.addBallButton.on(Button.EventType.CLICK, this.onAddBallClicked, this);
  248. } else {
  249. this.addBallButton.on(Node.EventType.TOUCH_END, this.onAddBallClicked, this);
  250. }
  251. }
  252. // 绑定增加金币按钮
  253. if (this.addCoinButton) {
  254. const btn = this.addCoinButton.getComponent(Button);
  255. if (btn) {
  256. this.addCoinButton.on(Button.EventType.CLICK, this.onAddCoinClicked, this);
  257. } else {
  258. this.addCoinButton.on(Node.EventType.TOUCH_END, this.onAddCoinClicked, this);
  259. }
  260. }
  261. // 绑定刷新方块按钮
  262. if (this.refreshButton) {
  263. const btn = this.refreshButton.getComponent(Button);
  264. if (btn) {
  265. this.refreshButton.on(Button.EventType.CLICK, this.onRefreshClicked, this);
  266. } else {
  267. this.refreshButton.on(Node.EventType.TOUCH_END, this.onRefreshClicked, this);
  268. }
  269. }
  270. // 绑定确认按钮
  271. if (this.confirmButton) {
  272. const btn = this.confirmButton.getComponent(Button);
  273. if (btn) {
  274. this.confirmButton.on(Button.EventType.CLICK, this.onConfirmButtonClicked, this);
  275. } else {
  276. this.confirmButton.on(Node.EventType.TOUCH_END, this.onConfirmButtonClicked, this);
  277. }
  278. }
  279. }
  280. // 新增小球按钮点击
  281. private onAddBallClicked() {
  282. // 播放UI点击音效
  283. Audio.playUISound('data/弹球音效/ui play');
  284. // 从UI节点获取价格并应用便宜技能效果计算实际费用
  285. const baseCost = this.getAddBallCost();
  286. const actualCost = this.getActualCost(baseCost);
  287. if (!this.canSpendCoins(actualCost)) {
  288. this.showInsufficientCoinsUI();
  289. return;
  290. }
  291. // 扣除金币
  292. if (this.session.spendCoins(actualCost)) {
  293. this.updateCoinDisplay();
  294. // 更新价格配置(增加购买次数和价格)
  295. this.updateAddBallPrice();
  296. // 通过事件系统创建新的小球
  297. const eventBus = EventBus.getInstance();
  298. eventBus.emit(GameEvents.BALL_CREATE_ADDITIONAL);
  299. // 新增小球成功
  300. }
  301. }
  302. // 增加金币按钮点击
  303. private onAddCoinClicked() {
  304. // 播放UI点击音效
  305. Audio.playUISound('data/弹球音效/ui play');
  306. // 显示激励视频广告
  307. AdManager.getInstance().showRewardedVideoAd(
  308. () => {
  309. // 广告观看完成,增加金币
  310. const coinsToAdd = 80; // 广告奖励的金币数量
  311. this.session.addCoins(coinsToAdd);
  312. // 更新显示
  313. this.updateCoinDisplay();
  314. },
  315. (error) => {
  316. console.error('[GameBlockSelection] 广告显示失败:', error);
  317. // 广告失败时不给予奖励
  318. }
  319. );
  320. }
  321. // 刷新方块按钮点击
  322. private onRefreshClicked() {
  323. // 播放UI点击音效
  324. Audio.playUISound('data/弹球音效/ui play');
  325. // 从UI节点获取价格并应用便宜技能效果计算实际费用
  326. const baseCost = this.getRefreshCost();
  327. const actualCost = this.getActualCost(baseCost);
  328. if (!this.canSpendCoins(actualCost)) {
  329. this.showInsufficientCoinsUI();
  330. return;
  331. }
  332. // 扣除金币
  333. if (this.session.spendCoins(actualCost)) {
  334. // 成功扣除金币
  335. this.updateCoinDisplay();
  336. // 更新价格配置(增加购买次数和价格)
  337. this.updateRefreshPrice();
  338. // 刷新方块
  339. if (this.blockManager) {
  340. console.log('[GameBlockSelection] 开始刷新方块流程');
  341. // 找到PlacedBlocks容器
  342. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  343. if (placedBlocksContainer) {
  344. // 移除已放置方块的标签
  345. // 移除已放置方块的标签
  346. BlockTag.removeTagsInContainer(placedBlocksContainer);
  347. }
  348. // 刷新方块
  349. // 调用 blockManager.refreshBlocks()
  350. this.blockManager.refreshBlocks();
  351. // 等待一帧确保方块生成完成
  352. this.scheduleOnce(() => {
  353. }, 0.1);
  354. } else {
  355. console.error('[GameBlockSelection] 找不到BlockManager,无法刷新方块');
  356. }
  357. } else {
  358. console.error('[GameBlockSelection] 扣除金币失败');
  359. }
  360. }
  361. // 确认按钮点击
  362. public onConfirmButtonClicked() {
  363. // 检查是否有上阵方块
  364. const hasBlocks = this.hasPlacedBlocks();
  365. if (!hasBlocks) {
  366. this.showNoPlacedBlocksToast();
  367. return;
  368. }
  369. // 播放UI音效
  370. Audio.playUISound('data/弹球音效/ui play');
  371. // 保存已放置的方块
  372. this.preservePlacedBlocks();
  373. // 清理kuang区域的方块(用户期望的行为)
  374. if (this.blockManager) {
  375. this.blockManager.clearBlocks();
  376. console.log('[GameBlockSelection] 已清理kuang区域的方块');
  377. }
  378. // 先回调通知GameManager,让它处理波次逻辑
  379. if (this.onConfirmCallback) {
  380. this.onConfirmCallback();
  381. }
  382. // 播放下滑diban动画,结束备战进入playing状态
  383. this.playDibanSlideDownAnimation();
  384. }
  385. // 播放diban下滑动画
  386. private playDibanSlideDownAnimation() {
  387. // 开始播放diban下滑动画
  388. // 使用装饰器属性获取Camera节点上的GameStartMove组件
  389. if (!this.cameraNode) {
  390. console.warn('[GameBlockSelection] Camera节点未设置,请在Inspector中拖拽Canvas/Camera节点');
  391. return;
  392. }
  393. const gameStartMove = this.cameraNode.getComponent('GameStartMove');
  394. if (!gameStartMove) {
  395. console.warn('[GameBlockSelection] GameStartMove组件未找到');
  396. return;
  397. }
  398. // 调用GameStartMove的下滑动画方法
  399. (gameStartMove as any).slideDibanDownAndHide(0.3);
  400. // 已调用GameStartMove的diban下滑动画
  401. }
  402. // 保存已放置的方块(从GameManager迁移)
  403. private preservePlacedBlocks() {
  404. if (this.blockManager) {
  405. this.blockManager.onGameStart();
  406. }
  407. }
  408. // 检查是否有足够金币
  409. private canSpendCoins(amount: number): boolean {
  410. return this.session.getCoins() >= amount;
  411. }
  412. // 计算应用便宜技能效果后的实际费用
  413. private getActualCost(baseCost: number): number {
  414. const skillManager = SkillManager.getInstance();
  415. if (skillManager) {
  416. const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
  417. return Math.ceil(SkillManager.calculateCheaperUnitsPrice(baseCost, cheaperSkillLevel));
  418. }
  419. return baseCost;
  420. }
  421. // 更新金币显示
  422. private updateCoinDisplay() {
  423. if (this.coinLabelNode) {
  424. const label = this.coinLabelNode.getComponent(Label);
  425. if (label) {
  426. const coins = this.session.getCoins();
  427. label.string = coins.toString();
  428. // 更新金币显示
  429. } else {
  430. console.warn('[GameBlockSelection] coinLabelNode缺少Label组件');
  431. }
  432. } else {
  433. console.warn('[GameBlockSelection] coinLabelNode未找到');
  434. }
  435. }
  436. // 显示金币不足UI
  437. private showInsufficientCoinsUI() {
  438. // 使用事件机制显示资源不足Toast
  439. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  440. message: '金币不足!',
  441. duration: 3.0
  442. });
  443. // 金币不足
  444. }
  445. // === 公共方法:供GameManager调用 ===
  446. // 生成方块选择(不再控制UI显示,只负责生成方块)
  447. public generateBlockSelection() {
  448. // 直接生成方块,不再依赖shouldGenerateBlocks标志
  449. if (this.blockManager) {
  450. this.blockManager.refreshBlocks();
  451. } else {
  452. console.warn('[GameBlockSelection] BlockManager未找到,无法生成随机方块');
  453. }
  454. // 触发进入备战状态事件
  455. EventBus.getInstance().emit(GameEvents.ENTER_BATTLE_PREPARATION);
  456. }
  457. // 设置确认回调
  458. public setConfirmCallback(callback: () => void) {
  459. this.onConfirmCallback = callback;
  460. }
  461. // 统一的方块占用情况刷新方法
  462. public refreshGridOccupation() {
  463. if (this.blockManager) {
  464. this.blockManager.resetGridOccupation();
  465. // 重新计算所有已放置方块的占用情况
  466. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  467. if (placedBlocksContainer) {
  468. for (let i = 0; i < placedBlocksContainer.children.length; i++) {
  469. const block = placedBlocksContainer.children[i];
  470. // 按照BlockManager.tryPlaceBlockToGrid的正确方法获取位置
  471. let b1Node = block;
  472. if (block.name !== 'B1') {
  473. b1Node = block.getChildByName('B1');
  474. if (!b1Node) {
  475. console.warn(`[GameBlockSelection] 方块 ${block.name} 没有B1子节点`);
  476. continue;
  477. }
  478. }
  479. // 获取B1节点的世界坐标,然后转换为网格本地坐标
  480. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  481. const gridPos = this.blockManager.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  482. // 重新标记方块占用的网格位置
  483. const gridNode = this.blockManager.findNearestGridNode(gridPos);
  484. if (gridNode) {
  485. this.blockManager.markOccupiedPositions(block, gridNode);
  486. } else {
  487. console.warn(`[GameBlockSelection] 方块 ${block.name} 未找到对应的网格节点`);
  488. }
  489. }
  490. }
  491. } else {
  492. console.warn('[GameBlockSelection] BlockManager未找到,无法刷新占用情况');
  493. }
  494. this.blockManager.printGridOccupationMatrix();
  495. }
  496. // 重置方块选择状态
  497. public resetSelection() {
  498. // 重置方块生成标志,等待下次onBattle触发
  499. this.shouldGenerateBlocks = false;
  500. // 注意:不再直接调用blockManager.onGameReset(),因为StartGame.clearGameStates()
  501. // 已经通过RESET_BLOCK_MANAGER事件触发了BlockManager的重置,避免重复生成方块
  502. // 清理所有方块标签
  503. BlockTag.clearAllTags();
  504. // 更新金币显示
  505. this.updateCoinDisplay();
  506. }
  507. // 检查是否有上阵方块
  508. private hasPlacedBlocks(): boolean {
  509. // 优先使用BlockManager的方法检查
  510. if (this.blockManager) {
  511. return this.blockManager.hasPlacedBlocks();
  512. }
  513. // 备用方案:直接检查PlacedBlocks容器
  514. const placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
  515. if (!placedBlocksContainer) {
  516. console.warn('找不到PlacedBlocks容器');
  517. return false;
  518. }
  519. // 检查容器中是否有子节点(方块)
  520. return placedBlocksContainer.children.length > 0;
  521. }
  522. // 显示没有上阵方块的Toast提示
  523. private showNoPlacedBlocksToast() {
  524. // 使用事件机制显示Toast
  525. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  526. message: '请至少上阵一个植物!',
  527. duration: 3.0
  528. });
  529. }
  530. // 设置方块拖拽事件
  531. public setupBlockDragEvents(block: Node) {
  532. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  533. // 检查游戏是否已开始
  534. if (!this.blockManager.gameStarted) {
  535. return;
  536. }
  537. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  538. const blockLocation = this.blockManager.blockLocations.get(block);
  539. // grid区域的方块目前允许自由移动
  540. this.currentDragBlock = block;
  541. this.startPos = event.getUILocation();
  542. this.blockStartPos.set(block.position);
  543. this.currentDragBlock['startLocation'] = blockLocation;
  544. // 如果方块在grid区域,拿起时清除其占用状态
  545. if (blockLocation === 'grid') {
  546. this.blockManager.clearOccupiedPositions(block);
  547. // 输出更新后的占用情况
  548. this.blockManager.printGridOccupationMatrix();
  549. }
  550. // 设置拖动状态,隐藏价格标签
  551. block['isDragging'] = true;
  552. block.setSiblingIndex(block.parent.children.length - 1);
  553. // 拖拽开始时禁用碰撞体
  554. const collider = block.getComponent(Collider2D);
  555. if (collider) collider.enabled = false;
  556. // 通知BallController有方块开始拖拽
  557. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_START, { block: block });
  558. }, this);
  559. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  560. // 检查游戏是否已开始
  561. if (!this.blockManager.gameStarted) {
  562. return;
  563. }
  564. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  565. const blockLocation = this.blockManager.blockLocations.get(block);
  566. // grid区域的方块目前允许自由移动
  567. if (!this.currentDragBlock) return;
  568. const location = event.getUILocation();
  569. const deltaX = location.x - this.startPos.x;
  570. const deltaY = location.y - this.startPos.y;
  571. this.currentDragBlock.position = new Vec3(
  572. this.blockStartPos.x + deltaX,
  573. this.blockStartPos.y + deltaY,
  574. this.blockStartPos.z
  575. );
  576. }, this);
  577. block.on(Node.EventType.TOUCH_END, async (event: EventTouch) => {
  578. // 检查游戏是否已开始
  579. if (!this.blockManager.gameStarted) {
  580. return;
  581. }
  582. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  583. const blockLocation = this.blockManager.blockLocations.get(block);
  584. // grid区域的方块目前允许自由移动
  585. if (this.currentDragBlock) {
  586. try {
  587. await this.handleBlockDrop(event);
  588. } catch (error) {
  589. console.error('[GameBlockSelection] 处理方块拖拽放置时发生错误:', error);
  590. // 发生错误时,将方块返回原位置
  591. this.returnBlockToOriginalPosition();
  592. }
  593. // 清除拖动状态,恢复价格标签显示
  594. block['isDragging'] = false;
  595. this.currentDragBlock = null;
  596. // 拖拽结束时恢复碰撞体
  597. const collider = block.getComponent(Collider2D);
  598. if (collider) collider.enabled = true;
  599. // 通知BallController方块拖拽结束
  600. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: block });
  601. }
  602. }, this);
  603. block.on(Node.EventType.TOUCH_CANCEL, () => {
  604. if (this.currentDragBlock) {
  605. this.returnBlockToOriginalPosition();
  606. // 清除拖动状态,恢复价格标签显示
  607. block['isDragging'] = false;
  608. this.currentDragBlock = null;
  609. // 拖拽取消时恢复碰撞体
  610. const collider = block.getComponent(Collider2D);
  611. if (collider) collider.enabled = true;
  612. // 通知BallController方块拖拽结束
  613. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: block });
  614. }
  615. }, this);
  616. }
  617. // 处理方块放下
  618. private async handleBlockDrop(event: EventTouch) {
  619. try {
  620. const touchPos = event.getLocation();
  621. const startLocation = this.currentDragBlock['startLocation'];
  622. if (this.isInKuangArea(touchPos)) {
  623. // 检查是否有标签,只有有标签的方块才能放回kuang
  624. if (BlockTag.hasTag(this.currentDragBlock)) {
  625. this.returnBlockToKuang(startLocation);
  626. } else {
  627. // 没有标签的方块不能放回kuang,返回原位置
  628. this.returnBlockToOriginalPosition();
  629. }
  630. } else if (this.blockManager.tryPlaceBlockToGrid(this.currentDragBlock)) {
  631. await this.handleSuccessfulPlacement(startLocation);
  632. } else {
  633. // 放置失败,尝试直接与重叠方块合成
  634. if (this.blockManager.tryMergeOnOverlap(this.currentDragBlock)) {
  635. // 合成成功时,若来自 kuang 则扣费
  636. if (startLocation !== 'grid') {
  637. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  638. this.blockManager.deductPlayerCoins(price);
  639. }
  640. // 当前拖拽块已被销毁(合并时),无需复位
  641. } else {
  642. this.returnBlockToOriginalPosition();
  643. }
  644. }
  645. } catch (error) {
  646. console.error('[GameBlockSelection] handleBlockDrop 发生错误:', error);
  647. // 发生错误时,将方块返回原位置
  648. this.returnBlockToOriginalPosition();
  649. throw error; // 重新抛出错误,让上层处理
  650. } finally {
  651. // 无论成功还是失败,都要清理拖拽状态
  652. if (this.currentDragBlock && this.currentDragBlock.isValid) {
  653. // 重新启用碰撞器
  654. const collider = this.currentDragBlock.getComponent(Collider2D);
  655. if (collider) {
  656. collider.enabled = true;
  657. console.log('[GameBlockSelection] 拖拽结束,重新启用碰撞器:', this.currentDragBlock.name);
  658. }
  659. // 发射拖拽结束事件
  660. console.log('[GameBlockSelection] 发射 BLOCK_DRAG_END 事件:', this.currentDragBlock.name);
  661. EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block: this.currentDragBlock });
  662. }
  663. // 清理拖拽状态
  664. this.currentDragBlock = null;
  665. }
  666. // 刷新方块占用情况
  667. this.refreshGridOccupation();
  668. }
  669. // 检查是否在kuang区域内
  670. private isInKuangArea(touchPos: Vec2): boolean {
  671. // 检查是否在任何一个Block容器区域内
  672. const blockContainers = [
  673. this.blockManager.block1Container,
  674. this.blockManager.block2Container,
  675. this.blockManager.block3Container
  676. ];
  677. for (const container of blockContainers) {
  678. if (container) {
  679. const transform = container.getComponent(UITransform);
  680. if (transform) {
  681. const boundingBox = new Rect(
  682. container.worldPosition.x - transform.width * transform.anchorX,
  683. container.worldPosition.y - transform.height * transform.anchorY,
  684. transform.width,
  685. transform.height
  686. );
  687. if (boundingBox.contains(new Vec2(touchPos.x, touchPos.y))) {
  688. return true;
  689. }
  690. }
  691. }
  692. }
  693. // 如果Block容器都不可用,回退到检查kuang容器
  694. if (this.blockManager.kuangContainer) {
  695. const kuangTransform = this.blockManager.kuangContainer.getComponent(UITransform);
  696. if (kuangTransform) {
  697. const kuangBoundingBox = new Rect(
  698. this.blockManager.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  699. this.blockManager.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  700. kuangTransform.width,
  701. kuangTransform.height
  702. );
  703. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  704. }
  705. }
  706. return false;
  707. }
  708. // 返回方块到对应的Block容器区域
  709. private returnBlockToKuang(startLocation: string) {
  710. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  711. const blockLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  712. if (originalPos) {
  713. // 根据方块的原始位置确定应该返回到哪个Block容器
  714. let targetContainer: Node = null;
  715. let targetLocation = 'kuang'; // 默认位置
  716. if (blockLocation && blockLocation.startsWith('block')) {
  717. // 如果方块原本在Block容器中,返回到对应的容器
  718. if (blockLocation === 'block1') {
  719. targetContainer = this.blockManager.block1Container;
  720. targetLocation = 'block1';
  721. } else if (blockLocation === 'block2') {
  722. targetContainer = this.blockManager.block2Container;
  723. targetLocation = 'block2';
  724. } else if (blockLocation === 'block3') {
  725. targetContainer = this.blockManager.block3Container;
  726. targetLocation = 'block3';
  727. }
  728. }
  729. // 如果没有找到对应的Block容器,回退到kuang容器
  730. if (!targetContainer) {
  731. targetContainer = this.blockManager.kuangContainer;
  732. targetLocation = 'kuang';
  733. }
  734. if (targetContainer && this.currentDragBlock.parent !== targetContainer) {
  735. this.currentDragBlock.removeFromParent();
  736. targetContainer.addChild(this.currentDragBlock);
  737. }
  738. this.currentDragBlock.position = originalPos.clone();
  739. this.blockManager.blockLocations.set(this.currentDragBlock, targetLocation);
  740. }
  741. // 当方块返回kuang区域时,重新设置植物图标缩放至0.4倍
  742. const weaponNode = this.findWeaponNodeInBlock(this.currentDragBlock);
  743. if (weaponNode) {
  744. weaponNode.setScale(0.4, 0.4, 1);
  745. // 方块返回kuang区域,设置植物图标缩放: 0.4倍
  746. }
  747. if (startLocation === 'grid') {
  748. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  749. this.blockManager.refundPlayerCoins(price);
  750. this.currentDragBlock['placedBefore'] = false;
  751. }
  752. // 显示对应的db标签节点
  753. this.showDbNodeByBlockLocation(this.currentDragBlock);
  754. }
  755. /**
  756. * 为方块的武器节点添加武器信息组件
  757. * @param block 方块节点
  758. */
  759. private attachWeaponInfoToBlock(block: Node): void {
  760. try {
  761. // 查找方块中的Weapon节点
  762. const weaponNode = this.findWeaponNodeInBlock(block);
  763. if (!weaponNode) {
  764. console.warn(`[GameBlockSelection] 方块 ${block.name} 中未找到Weapon节点,无法添加武器信息组件`);
  765. return;
  766. }
  767. // 检查是否已经有WeaponInfo组件
  768. let weaponInfo = weaponNode.getComponent(WeaponInfo);
  769. if (weaponInfo) {
  770. return;
  771. }
  772. // 添加WeaponInfo组件
  773. weaponInfo = weaponNode.addComponent(WeaponInfo);
  774. // 获取方块的武器配置
  775. const weaponConfig = this.blockManager.getBlockWeaponConfig(block);
  776. if (weaponConfig) {
  777. // 设置武器配置到WeaponInfo组件
  778. weaponInfo.setWeaponConfig(weaponConfig);
  779. } else {
  780. console.warn(`[GameBlockSelection] 方块 ${block.name} 没有武器配置,无法设置武器信息`);
  781. // 移除刚添加的组件
  782. weaponNode.removeComponent(WeaponInfo);
  783. }
  784. } catch (error) {
  785. console.error(`[GameBlockSelection] 为方块 ${block.name} 添加武器信息组件时发生错误:`, error);
  786. }
  787. }
  788. /**
  789. * 在方块中查找Weapon节点
  790. * @param block 方块节点
  791. * @returns Weapon节点,如果未找到返回null
  792. */
  793. private findWeaponNodeInBlock(block: Node): Node | null {
  794. if (!block || !block.isValid) {
  795. return null;
  796. }
  797. // 根据新的预制体结构,武器节点直接位于方块根节点下
  798. const weaponNode = block.getChildByName('Weapon');
  799. if (weaponNode) {
  800. return weaponNode;
  801. }
  802. // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
  803. const b1Node = block.getChildByName('B1');
  804. if (b1Node) {
  805. const b1WeaponNode = b1Node.getChildByName('Weapon');
  806. if (b1WeaponNode) {
  807. return b1WeaponNode;
  808. }
  809. }
  810. // 最后使用递归方式查找(兼容其他可能的结构)
  811. const findWeaponRecursive = (node: Node): Node | null => {
  812. if (node.name === 'Weapon') {
  813. return node;
  814. }
  815. for (let i = 0; i < node.children.length; i++) {
  816. const result = findWeaponRecursive(node.children[i]);
  817. if (result) {
  818. return result;
  819. }
  820. }
  821. return null;
  822. };
  823. return findWeaponRecursive(block);
  824. }
  825. // 根据方块位置隐藏对应的db标签节点
  826. private hideDbNodeByBlockLocation(block: Node) {
  827. const originalLocation = this.getBlockOriginalLocation(block);
  828. if (originalLocation === 'block1') {
  829. console.log(`[GameBlockSelection] 隐藏block1的db标签节点`);
  830. const blockInContainer = this.getBlockInContainer(this.blockManager.block1Container);
  831. if (blockInContainer) {
  832. this.blockManager.hideDbLabel(blockInContainer);
  833. }
  834. } else if (originalLocation === 'block2') {
  835. console.log(`[GameBlockSelection] 隐藏block2的db标签节点`);
  836. const blockInContainer = this.getBlockInContainer(this.blockManager.block2Container);
  837. if (blockInContainer) {
  838. this.blockManager.hideDbLabel(blockInContainer);
  839. }
  840. } else if (originalLocation === 'block3') {
  841. console.log(`[GameBlockSelection] 隐藏block3的db标签节点`);
  842. const blockInContainer = this.getBlockInContainer(this.blockManager.block3Container);
  843. if (blockInContainer) {
  844. this.blockManager.hideDbLabel(blockInContainer);
  845. }
  846. }
  847. }
  848. // 根据方块位置显示对应的db标签节点
  849. private showDbNodeByBlockLocation(block: Node) {
  850. const originalLocation = this.getBlockOriginalLocation(block);
  851. if (originalLocation === 'block1') {
  852. const blockInContainer = this.getBlockInContainer(this.blockManager.block1Container);
  853. if (blockInContainer) {
  854. this.blockManager.showDbLabel(blockInContainer);
  855. }
  856. } else if (originalLocation === 'block2') {
  857. const blockInContainer = this.getBlockInContainer(this.blockManager.block2Container);
  858. if (blockInContainer) {
  859. this.blockManager.showDbLabel(blockInContainer);
  860. }
  861. } else if (originalLocation === 'block3') {
  862. const blockInContainer = this.getBlockInContainer(this.blockManager.block3Container);
  863. if (blockInContainer) {
  864. this.blockManager.showDbLabel(blockInContainer);
  865. }
  866. }
  867. }
  868. // 获取容器中的方块节点
  869. private getBlockInContainer(container: Node): Node | null {
  870. if (!container) {
  871. return null;
  872. }
  873. // 查找容器中的方块节点(通常以Block命名或有B1子节点)
  874. for (let i = 0; i < container.children.length; i++) {
  875. const child = container.children[i];
  876. if (child.name.includes('Block') || child.getChildByName('B1')) {
  877. return child;
  878. }
  879. }
  880. return null;
  881. }
  882. // 处理成功放置
  883. private async handleSuccessfulPlacement(startLocation: string) {
  884. try {
  885. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  886. if (startLocation === 'grid') {
  887. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  888. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  889. // 隐藏对应的db标签节点
  890. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  891. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  892. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  893. // 为武器节点添加武器信息组件
  894. this.attachWeaponInfoToBlock(this.currentDragBlock);
  895. // 如果游戏已开始,添加锁定视觉提示
  896. if (this.blockManager.gameStarted) {
  897. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  898. BlockTag.removeTag(this.currentDragBlock);
  899. }
  900. // 检查并执行合成
  901. try {
  902. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  903. } catch (mergeError) {
  904. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  905. }
  906. } else {
  907. if (this.blockManager.deductPlayerCoins(price)) {
  908. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  909. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  910. // 隐藏对应的db标签节点
  911. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  912. this.currentDragBlock['placedBefore'] = true;
  913. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  914. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  915. // 为武器节点添加武器信息组件
  916. this.attachWeaponInfoToBlock(this.currentDragBlock);
  917. // 如果游戏已开始,添加锁定视觉提示
  918. if (this.blockManager.gameStarted) {
  919. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  920. // 游戏开始后放置的方块移除标签,不能再放回kuang
  921. BlockTag.removeTag(this.currentDragBlock);
  922. }
  923. // 检查并执行合成
  924. try {
  925. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  926. } catch (mergeError) {
  927. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  928. // 合成失败不影响方块放置,只记录错误
  929. }
  930. } else {
  931. // 金币不足时显示价格标签闪烁效果和Toast提示
  932. this.blockManager.showInsufficientCoinsEffect(this.currentDragBlock);
  933. this.returnBlockToOriginalPosition();
  934. }
  935. }
  936. } catch (error) {
  937. console.error('[GameBlockSelection] handleSuccessfulPlacement 发生错误:', error);
  938. // 发生错误时,将方块返回原位置
  939. this.returnBlockToOriginalPosition();
  940. throw error; // 重新抛出错误,让上层处理
  941. }
  942. }
  943. // 返回方块到原位置
  944. private returnBlockToOriginalPosition() {
  945. const currentLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  946. const startLocation = this.currentDragBlock['startLocation'];
  947. if (currentLocation === 'kuang') {
  948. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  949. if (originalPos) {
  950. this.currentDragBlock.position = originalPos.clone();
  951. }
  952. } else {
  953. this.currentDragBlock.position = this.blockStartPos.clone();
  954. // 如果方块原本在grid区域,返回原位置后需要重新标记占用状态
  955. if (startLocation === 'grid') {
  956. // 获取方块当前位置对应的网格节点
  957. let b1Node = this.currentDragBlock;
  958. if (this.currentDragBlock.name !== 'B1') {
  959. b1Node = this.currentDragBlock.getChildByName('B1');
  960. }
  961. if (b1Node) {
  962. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  963. const gridPos = this.blockManager.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  964. const gridNode = this.blockManager.findNearestGridNode(gridPos);
  965. if (gridNode) {
  966. this.blockManager.markOccupiedPositions(this.currentDragBlock, gridNode);
  967. // 输出更新后的占用情况
  968. this.blockManager.printGridOccupationMatrix();
  969. }
  970. }
  971. }
  972. }
  973. // 清除拖动状态,恢复db节点显示
  974. this.currentDragBlock['isDragging'] = false;
  975. this.showDbNodeByBlockLocation(this.currentDragBlock);
  976. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  977. }
  978. // === 调试绘制相关方法 ===
  979. private initDebugDraw() {
  980. // 调试绘制功能已禁用
  981. }
  982. private drawGridSnapRanges() {
  983. // 调试绘制功能已禁用
  984. }
  985. private drawBlockSnapRange(block: Node) {
  986. // 调试绘制功能已禁用
  987. }
  988. private updateDebugDraw() {
  989. // 调试绘制功能已禁用
  990. }
  991. // 清理调试绘制
  992. private cleanupDebugDraw() {
  993. if (this.debugDrawNode && this.debugDrawNode.isValid) {
  994. this.debugDrawNode.destroy();
  995. this.debugDrawNode = null;
  996. this.debugGraphics = null;
  997. }
  998. }
  999. public setDebugDrawSnapRange(enabled: boolean) {
  1000. this.debugDrawSnapRange = enabled;
  1001. // 调试绘制功能已禁用
  1002. }
  1003. onDisable() {
  1004. this.removeEventListeners();
  1005. this.cleanupDebugDraw();
  1006. }
  1007. onDestroy() {
  1008. this.removeEventListeners();
  1009. this.cleanupDebugDraw();
  1010. }
  1011. // 移除事件监听器
  1012. private removeEventListeners() {
  1013. const eventBus = EventBus.getInstance();
  1014. eventBus.off(GameEvents.RESET_BLOCK_SELECTION, this.onResetBlockSelectionEvent, this);
  1015. eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  1016. eventBus.off(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.onSetupBlockDragEventsEvent, this);
  1017. }
  1018. /**
  1019. * 获取方块的原始位置
  1020. * @param block 方块节点
  1021. * @returns 原始位置标识符
  1022. */
  1023. private getBlockOriginalLocation(block: Node): string | null {
  1024. // 检查方块是否在block1Container中
  1025. if (this.blockManager.block1Container && this.isBlockInContainer(block, this.blockManager.block1Container)) {
  1026. return 'block1';
  1027. }
  1028. // 检查方块是否在block2Container中
  1029. if (this.blockManager.block2Container && this.isBlockInContainer(block, this.blockManager.block2Container)) {
  1030. return 'block2';
  1031. }
  1032. // 检查方块是否在block3Container中
  1033. if (this.blockManager.block3Container && this.isBlockInContainer(block, this.blockManager.block3Container)) {
  1034. return 'block3';
  1035. }
  1036. return null;
  1037. }
  1038. /**
  1039. * 检查方块是否在指定容器中
  1040. * @param block 方块节点
  1041. * @param container 容器节点
  1042. * @returns 是否在容器中
  1043. */
  1044. private isBlockInContainer(block: Node, container: Node): boolean {
  1045. let parent = block.parent;
  1046. while (parent) {
  1047. if (parent === container) {
  1048. return true;
  1049. }
  1050. parent = parent.parent;
  1051. }
  1052. return false;
  1053. }
  1054. // === 价格配置管理方法 ===
  1055. // 获取价格配置数据(如果装饰器配置不存在则返回默认值)
  1056. private getPriceConfigData(): any {
  1057. if (this.ballPriceConfig && this.ballPriceConfig.json) {
  1058. return this.ballPriceConfig.json;
  1059. }
  1060. // 返回默认配置
  1061. return {
  1062. addBallPricing: {
  1063. initialPrice: this.DEFAULT_ADD_BALL_BASE_PRICE,
  1064. priceIncrement: this.DEFAULT_ADD_BALL_INCREMENT,
  1065. maxPrice: this.DEFAULT_ADD_BALL_MAX_PRICE
  1066. },
  1067. refreshBlockPricing: {
  1068. initialPrice: this.DEFAULT_REFRESH_BASE_PRICE,
  1069. priceIncrement: this.DEFAULT_REFRESH_INCREMENT,
  1070. maxPrice: this.DEFAULT_REFRESH_MAX_PRICE
  1071. },
  1072. priceHistory: {
  1073. addBallCurrentPrice: this.DEFAULT_ADD_BALL_BASE_PRICE,
  1074. refreshBlockCurrentPrice: this.DEFAULT_REFRESH_BASE_PRICE,
  1075. addBallPurchaseCount: 0,
  1076. refreshBlockPurchaseCount: 0
  1077. }
  1078. };
  1079. }
  1080. // 更新新增小球价格
  1081. private updateAddBallPrice() {
  1082. const configData = this.getPriceConfigData();
  1083. const config = configData.addBallPricing;
  1084. const history = configData.priceHistory;
  1085. // 增加购买次数
  1086. history.addBallPurchaseCount++;
  1087. // 计算新价格
  1088. const newPrice = Math.min(
  1089. config.initialPrice + (history.addBallPurchaseCount * config.priceIncrement),
  1090. config.maxPrice
  1091. );
  1092. history.addBallCurrentPrice = newPrice;
  1093. // 更新UI显示
  1094. this.updatePriceDisplay();
  1095. // 保存配置(注意:装饰器配置是只读的,这里只是打印日志)
  1096. this.saveBallPriceConfig();
  1097. console.log(`[GameBlockSelection] 新增小球价格更新: ${newPrice}, 购买次数: ${history.addBallPurchaseCount}`);
  1098. }
  1099. // 更新刷新方块价格
  1100. private updateRefreshPrice() {
  1101. const configData = this.getPriceConfigData();
  1102. const config = configData.refreshBlockPricing;
  1103. const history = configData.priceHistory;
  1104. // 增加购买次数
  1105. history.refreshBlockPurchaseCount++;
  1106. // 计算新价格
  1107. const newPrice = Math.min(
  1108. config.initialPrice + (history.refreshBlockPurchaseCount * config.priceIncrement),
  1109. config.maxPrice
  1110. );
  1111. history.refreshBlockCurrentPrice = newPrice;
  1112. // 更新UI显示
  1113. this.updatePriceDisplay();
  1114. // 保存配置(注意:装饰器配置是只读的,这里只是打印日志)
  1115. this.saveBallPriceConfig();
  1116. console.log(`[GameBlockSelection] 刷新方块价格更新: ${newPrice}, 购买次数: ${history.refreshBlockPurchaseCount}`);
  1117. }
  1118. // 更新价格显示
  1119. private updatePriceDisplay() {
  1120. // 更新新增小球价格显示
  1121. const addBallPriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann001/Ball/db01/Price');
  1122. if (addBallPriceNode) {
  1123. const label = addBallPriceNode.getComponent(Label);
  1124. if (label) {
  1125. label.string = this.getAddBallCost().toString();
  1126. }
  1127. }
  1128. // 更新刷新方块价格显示
  1129. const refreshPriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/ann003/Ball/db01/Price');
  1130. if (refreshPriceNode) {
  1131. const label = refreshPriceNode.getComponent(Label);
  1132. if (label) {
  1133. label.string = this.getRefreshCost().toString();
  1134. }
  1135. }
  1136. }
  1137. // 保存价格配置(装饰器配置是只读的,这里只是打印日志用于调试)
  1138. private saveBallPriceConfig() {
  1139. const configData = this.getPriceConfigData();
  1140. // 装饰器预加载的配置是只读的,无法直接修改
  1141. // 在实际项目中,价格变化应该保存到本地存储或服务器
  1142. console.log('[GameBlockSelection] 价格配置已更新:', JSON.stringify(configData, null, 2));
  1143. }
  1144. }