GameBlockSelection.ts 60 KB

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