GameBlockSelection.ts 45 KB

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