GameBlockSelection.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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/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_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/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/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_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. // 设置拖动状态,隐藏价格标签
  479. block['isDragging'] = true;
  480. block.setSiblingIndex(block.parent.children.length - 1);
  481. // 拖拽开始时禁用碰撞体
  482. const collider = block.getComponent(Collider2D);
  483. if (collider) collider.enabled = false;
  484. }, this);
  485. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  486. // 检查游戏是否已开始
  487. if (!this.blockManager.gameStarted) {
  488. return;
  489. }
  490. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  491. const blockLocation = this.blockManager.blockLocations.get(block);
  492. // grid区域的方块目前允许自由移动
  493. if (!this.currentDragBlock) return;
  494. const location = event.getUILocation();
  495. const deltaX = location.x - this.startPos.x;
  496. const deltaY = location.y - this.startPos.y;
  497. this.currentDragBlock.position = new Vec3(
  498. this.blockStartPos.x + deltaX,
  499. this.blockStartPos.y + deltaY,
  500. this.blockStartPos.z
  501. );
  502. }, this);
  503. block.on(Node.EventType.TOUCH_END, async (event: EventTouch) => {
  504. // 检查游戏是否已开始
  505. if (!this.blockManager.gameStarted) {
  506. return;
  507. }
  508. // 只对grid区域的方块检查移动限制,kuang区域的方块可以自由拖拽
  509. const blockLocation = this.blockManager.blockLocations.get(block);
  510. // grid区域的方块目前允许自由移动
  511. if (this.currentDragBlock) {
  512. try {
  513. await this.handleBlockDrop(event);
  514. } catch (error) {
  515. console.error('[GameBlockSelection] 处理方块拖拽放置时发生错误:', error);
  516. // 发生错误时,将方块返回原位置
  517. this.returnBlockToOriginalPosition();
  518. }
  519. // 清除拖动状态,恢复价格标签显示
  520. block['isDragging'] = false;
  521. this.currentDragBlock = null;
  522. // 拖拽结束时恢复碰撞体
  523. const collider = block.getComponent(Collider2D);
  524. if (collider) collider.enabled = true;
  525. }
  526. }, this);
  527. block.on(Node.EventType.TOUCH_CANCEL, () => {
  528. if (this.currentDragBlock) {
  529. this.returnBlockToOriginalPosition();
  530. // 清除拖动状态,恢复价格标签显示
  531. block['isDragging'] = false;
  532. this.currentDragBlock = null;
  533. // 拖拽取消时恢复碰撞体
  534. const collider = block.getComponent(Collider2D);
  535. if (collider) collider.enabled = true;
  536. }
  537. }, this);
  538. }
  539. // 处理方块放下
  540. private async handleBlockDrop(event: EventTouch) {
  541. try {
  542. const touchPos = event.getLocation();
  543. const startLocation = this.currentDragBlock['startLocation'];
  544. if (this.isInKuangArea(touchPos)) {
  545. // 检查是否有标签,只有有标签的方块才能放回kuang
  546. if (BlockTag.hasTag(this.currentDragBlock)) {
  547. this.returnBlockToKuang(startLocation);
  548. } else {
  549. // 没有标签的方块不能放回kuang,返回原位置
  550. this.returnBlockToOriginalPosition();
  551. }
  552. } else if (this.blockManager.tryPlaceBlockToGrid(this.currentDragBlock)) {
  553. await this.handleSuccessfulPlacement(startLocation);
  554. } else {
  555. // 放置失败,尝试直接与重叠方块合成
  556. if (this.blockManager.tryMergeOnOverlap(this.currentDragBlock)) {
  557. // 合成成功时,若来自 kuang 则扣费
  558. if (startLocation !== 'grid') {
  559. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  560. this.blockManager.deductPlayerCoins(price);
  561. }
  562. // 当前拖拽块已被销毁(合并时),无需复位
  563. } else {
  564. this.returnBlockToOriginalPosition();
  565. }
  566. }
  567. } catch (error) {
  568. console.error('[GameBlockSelection] handleBlockDrop 发生错误:', error);
  569. // 发生错误时,将方块返回原位置
  570. this.returnBlockToOriginalPosition();
  571. throw error; // 重新抛出错误,让上层处理
  572. }
  573. // 刷新方块占用情况
  574. this.refreshGridOccupation();
  575. }
  576. // 检查是否在kuang区域内
  577. private isInKuangArea(touchPos: Vec2): boolean {
  578. // 检查是否在任何一个Block容器区域内
  579. const blockContainers = [
  580. this.blockManager.block1Container,
  581. this.blockManager.block2Container,
  582. this.blockManager.block3Container
  583. ];
  584. for (const container of blockContainers) {
  585. if (container) {
  586. const transform = container.getComponent(UITransform);
  587. if (transform) {
  588. const boundingBox = new Rect(
  589. container.worldPosition.x - transform.width * transform.anchorX,
  590. container.worldPosition.y - transform.height * transform.anchorY,
  591. transform.width,
  592. transform.height
  593. );
  594. if (boundingBox.contains(new Vec2(touchPos.x, touchPos.y))) {
  595. return true;
  596. }
  597. }
  598. }
  599. }
  600. // 如果Block容器都不可用,回退到检查kuang容器
  601. if (this.blockManager.kuangContainer) {
  602. const kuangTransform = this.blockManager.kuangContainer.getComponent(UITransform);
  603. if (kuangTransform) {
  604. const kuangBoundingBox = new Rect(
  605. this.blockManager.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  606. this.blockManager.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  607. kuangTransform.width,
  608. kuangTransform.height
  609. );
  610. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  611. }
  612. }
  613. return false;
  614. }
  615. // 返回方块到对应的Block容器区域
  616. private returnBlockToKuang(startLocation: string) {
  617. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  618. const blockLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  619. if (originalPos) {
  620. // 根据方块的原始位置确定应该返回到哪个Block容器
  621. let targetContainer: Node = null;
  622. let targetLocation = 'kuang'; // 默认位置
  623. if (blockLocation && blockLocation.startsWith('block')) {
  624. // 如果方块原本在Block容器中,返回到对应的容器
  625. if (blockLocation === 'block1') {
  626. targetContainer = this.blockManager.block1Container;
  627. targetLocation = 'block1';
  628. } else if (blockLocation === 'block2') {
  629. targetContainer = this.blockManager.block2Container;
  630. targetLocation = 'block2';
  631. } else if (blockLocation === 'block3') {
  632. targetContainer = this.blockManager.block3Container;
  633. targetLocation = 'block3';
  634. }
  635. }
  636. // 如果没有找到对应的Block容器,回退到kuang容器
  637. if (!targetContainer) {
  638. targetContainer = this.blockManager.kuangContainer;
  639. targetLocation = 'kuang';
  640. }
  641. if (targetContainer && this.currentDragBlock.parent !== targetContainer) {
  642. this.currentDragBlock.removeFromParent();
  643. targetContainer.addChild(this.currentDragBlock);
  644. }
  645. this.currentDragBlock.position = originalPos.clone();
  646. this.blockManager.blockLocations.set(this.currentDragBlock, targetLocation);
  647. }
  648. this.blockManager.showPriceLabel(this.currentDragBlock);
  649. // 当方块返回kuang区域时,重新设置植物图标缩放至0.45倍
  650. const b1Node = this.currentDragBlock.getChildByName('B1');
  651. if (b1Node) {
  652. const weaponNode = b1Node.getChildByName('Weapon');
  653. if (weaponNode) {
  654. weaponNode.setScale(0.45, 0.45, 1);
  655. // 方块返回kuang区域,设置植物图标缩放: 0.45倍
  656. }
  657. }
  658. if (startLocation === 'grid') {
  659. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  660. this.blockManager.refundPlayerCoins(price);
  661. this.currentDragBlock['placedBefore'] = false;
  662. }
  663. // 显示对应的db标签节点
  664. this.showDbNodeByBlockLocation(this.currentDragBlock);
  665. }
  666. /**
  667. * 为方块的武器节点添加武器信息组件
  668. * @param block 方块节点
  669. */
  670. private attachWeaponInfoToBlock(block: Node): void {
  671. try {
  672. // 查找方块中的Weapon节点
  673. const weaponNode = this.findWeaponNodeInBlock(block);
  674. if (!weaponNode) {
  675. console.warn(`[GameBlockSelection] 方块 ${block.name} 中未找到Weapon节点,无法添加武器信息组件`);
  676. return;
  677. }
  678. // 检查是否已经有WeaponInfo组件
  679. let weaponInfo = weaponNode.getComponent(WeaponInfo);
  680. if (weaponInfo) {
  681. return;
  682. }
  683. // 添加WeaponInfo组件
  684. weaponInfo = weaponNode.addComponent(WeaponInfo);
  685. // 获取方块的武器配置
  686. const weaponConfig = this.blockManager.getBlockWeaponConfig(block);
  687. if (weaponConfig) {
  688. // 设置武器配置到WeaponInfo组件
  689. weaponInfo.setWeaponConfig(weaponConfig);
  690. } else {
  691. console.warn(`[GameBlockSelection] 方块 ${block.name} 没有武器配置,无法设置武器信息`);
  692. // 移除刚添加的组件
  693. weaponNode.removeComponent(WeaponInfo);
  694. }
  695. } catch (error) {
  696. console.error(`[GameBlockSelection] 为方块 ${block.name} 添加武器信息组件时发生错误:`, error);
  697. }
  698. }
  699. /**
  700. * 在方块中查找Weapon节点
  701. * @param block 方块节点
  702. * @returns Weapon节点,如果未找到返回null
  703. */
  704. private findWeaponNodeInBlock(block: Node): Node | null {
  705. if (!block || !block.isValid) {
  706. return null;
  707. }
  708. // 递归查找名为"Weapon"的子节点
  709. const findWeaponRecursive = (node: Node): Node | null => {
  710. if (node.name === 'Weapon') {
  711. return node;
  712. }
  713. for (let i = 0; i < node.children.length; i++) {
  714. const result = findWeaponRecursive(node.children[i]);
  715. if (result) {
  716. return result;
  717. }
  718. }
  719. return null;
  720. };
  721. return findWeaponRecursive(block);
  722. }
  723. // 根据方块位置隐藏对应的db标签节点
  724. private hideDbNodeByBlockLocation(block: Node) {
  725. const originalLocation = this.getBlockOriginalLocation(block);
  726. if (originalLocation === 'block1' && this.blockManager.block1DbNode) {
  727. this.blockManager.block1DbNode.active = false;
  728. } else if (originalLocation === 'block2' && this.blockManager.block2DbNode) {
  729. this.blockManager.block2DbNode.active = false;
  730. } else if (originalLocation === 'block3' && this.blockManager.block3DbNode) {
  731. this.blockManager.block3DbNode.active = false;
  732. }
  733. }
  734. // 根据方块位置显示对应的db标签节点
  735. private showDbNodeByBlockLocation(block: Node) {
  736. const originalLocation = this.getBlockOriginalLocation(block);
  737. if (originalLocation === 'block1' && this.blockManager.block1DbNode) {
  738. this.blockManager.block1DbNode.active = true;
  739. } else if (originalLocation === 'block2' && this.blockManager.block2DbNode) {
  740. this.blockManager.block2DbNode.active = true;
  741. } else if (originalLocation === 'block3' && this.blockManager.block3DbNode) {
  742. this.blockManager.block3DbNode.active = true;
  743. }
  744. }
  745. // 处理成功放置
  746. private async handleSuccessfulPlacement(startLocation: string) {
  747. try {
  748. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  749. if (startLocation === 'grid') {
  750. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  751. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  752. // 隐藏对应的db标签节点
  753. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  754. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  755. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  756. // 为武器节点添加武器信息组件
  757. this.attachWeaponInfoToBlock(this.currentDragBlock);
  758. // 如果游戏已开始,添加锁定视觉提示
  759. if (this.blockManager.gameStarted) {
  760. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  761. BlockTag.removeTag(this.currentDragBlock);
  762. }
  763. // 检查并执行合成
  764. try {
  765. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  766. } catch (mergeError) {
  767. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  768. }
  769. } else {
  770. if (this.blockManager.deductPlayerCoins(price)) {
  771. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  772. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  773. // 隐藏对应的db标签节点
  774. this.hideDbNodeByBlockLocation(this.currentDragBlock);
  775. this.currentDragBlock['placedBefore'] = true;
  776. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  777. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  778. // 为武器节点添加武器信息组件
  779. this.attachWeaponInfoToBlock(this.currentDragBlock);
  780. // 如果游戏已开始,添加锁定视觉提示
  781. if (this.blockManager.gameStarted) {
  782. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  783. // 游戏开始后放置的方块移除标签,不能再放回kuang
  784. BlockTag.removeTag(this.currentDragBlock);
  785. }
  786. // 检查并执行合成
  787. try {
  788. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  789. } catch (mergeError) {
  790. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  791. // 合成失败不影响方块放置,只记录错误
  792. }
  793. } else {
  794. // 金币不足时显示价格标签闪烁效果和Toast提示
  795. this.blockManager.showInsufficientCoinsEffect(this.currentDragBlock);
  796. this.returnBlockToOriginalPosition();
  797. }
  798. }
  799. } catch (error) {
  800. console.error('[GameBlockSelection] handleSuccessfulPlacement 发生错误:', error);
  801. // 发生错误时,将方块返回原位置
  802. this.returnBlockToOriginalPosition();
  803. throw error; // 重新抛出错误,让上层处理
  804. }
  805. }
  806. // 返回方块到原位置
  807. private returnBlockToOriginalPosition() {
  808. const currentLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  809. if (currentLocation === 'kuang') {
  810. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  811. if (originalPos) {
  812. this.currentDragBlock.position = originalPos.clone();
  813. }
  814. } else {
  815. this.currentDragBlock.position = this.blockStartPos.clone();
  816. }
  817. // 清除拖动状态,恢复db节点显示
  818. this.currentDragBlock['isDragging'] = false;
  819. this.showDbNodeByBlockLocation(this.currentDragBlock);
  820. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  821. }
  822. // === 调试绘制相关方法 ===
  823. private initDebugDraw() {
  824. // 调试绘制功能已禁用
  825. }
  826. private drawGridSnapRanges() {
  827. // 调试绘制功能已禁用
  828. }
  829. private drawBlockSnapRange(block: Node) {
  830. // 调试绘制功能已禁用
  831. }
  832. private updateDebugDraw() {
  833. // 调试绘制功能已禁用
  834. }
  835. // 清理调试绘制
  836. private cleanupDebugDraw() {
  837. if (this.debugDrawNode && this.debugDrawNode.isValid) {
  838. this.debugDrawNode.destroy();
  839. this.debugDrawNode = null;
  840. this.debugGraphics = null;
  841. }
  842. }
  843. public setDebugDrawSnapRange(enabled: boolean) {
  844. this.debugDrawSnapRange = enabled;
  845. // 调试绘制功能已禁用
  846. }
  847. onDisable() {
  848. this.removeEventListeners();
  849. this.cleanupDebugDraw();
  850. }
  851. onDestroy() {
  852. this.removeEventListeners();
  853. this.cleanupDebugDraw();
  854. }
  855. // 移除事件监听器
  856. private removeEventListeners() {
  857. const eventBus = EventBus.getInstance();
  858. eventBus.off(GameEvents.RESET_BLOCK_SELECTION, this.onResetBlockSelectionEvent, this);
  859. eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  860. eventBus.off(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.onSetupBlockDragEventsEvent, this);
  861. }
  862. /**
  863. * 获取方块的原始位置
  864. * @param block 方块节点
  865. * @returns 原始位置标识符
  866. */
  867. private getBlockOriginalLocation(block: Node): string | null {
  868. // 检查方块是否在block1Container中
  869. if (this.blockManager.block1Container && this.isBlockInContainer(block, this.blockManager.block1Container)) {
  870. return 'block1';
  871. }
  872. // 检查方块是否在block2Container中
  873. if (this.blockManager.block2Container && this.isBlockInContainer(block, this.blockManager.block2Container)) {
  874. return 'block2';
  875. }
  876. // 检查方块是否在block3Container中
  877. if (this.blockManager.block3Container && this.isBlockInContainer(block, this.blockManager.block3Container)) {
  878. return 'block3';
  879. }
  880. return null;
  881. }
  882. /**
  883. * 检查方块是否在指定容器中
  884. * @param block 方块节点
  885. * @param container 容器节点
  886. * @returns 是否在容器中
  887. */
  888. private isBlockInContainer(block: Node, container: Node): boolean {
  889. let parent = block.parent;
  890. while (parent) {
  891. if (parent === container) {
  892. return true;
  893. }
  894. parent = parent.parent;
  895. }
  896. return false;
  897. }
  898. }