GameBlockSelection.ts 45 KB

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