GameBlockSelection.ts 42 KB

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