GameBlockSelection.ts 39 KB

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