GameBlockSelection.ts 56 KB

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