GameBlockSelection.ts 60 KB

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