GameBlockSelection.ts 42 KB

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