GameBlockSelection.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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(300, 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. // 不重置网格占用状态,只重新计算已放置方块的占用情况
  403. // 这样可以保留refreshBlocks中恢复的占用信息
  404. // 重新计算所有已放置方块的占用情况
  405. const placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  406. if (placedBlocksContainer) {
  407. for (let i = 0; i < placedBlocksContainer.children.length; i++) {
  408. const block = placedBlocksContainer.children[i];
  409. // 重新标记方块占用的网格位置
  410. const gridNode = this.blockManager.findNearestGridNode(block.worldPosition);
  411. if (gridNode) {
  412. this.blockManager.markOccupiedPositions(block, gridNode);
  413. }
  414. }
  415. }
  416. console.log('[GameBlockSelection] 方块占用情况刷新完成');
  417. } else {
  418. console.warn('[GameBlockSelection] BlockManager未找到,无法刷新占用情况');
  419. }
  420. }
  421. // 重置方块选择状态
  422. public resetSelection() {
  423. console.log('[GameBlockSelection] 重置方块选择状态');
  424. // 重置方块生成标志,等待下次onBattle触发
  425. this.shouldGenerateBlocks = false;
  426. console.log('[GameBlockSelection] 重置方块生成标志');
  427. // 注意:不再直接调用blockManager.onGameReset(),因为StartGame.clearGameStates()
  428. // 已经通过RESET_BLOCK_MANAGER事件触发了BlockManager的重置,避免重复生成方块
  429. console.log('[GameBlockSelection] BlockManager将通过事件系统自动重置');
  430. // 清理所有方块标签
  431. BlockTag.clearAllTags();
  432. console.log('[GameBlockSelection] 方块标签已清理');
  433. // 刷新方块占用情况
  434. this.refreshGridOccupation();
  435. // 更新金币显示
  436. this.updateCoinDisplay();
  437. console.log('[GameBlockSelection] 金币显示已更新');
  438. }
  439. // 检查是否有上阵方块
  440. private hasPlacedBlocks(): boolean {
  441. // 优先使用BlockManager的方法检查
  442. if (this.blockManager) {
  443. return this.blockManager.hasPlacedBlocks();
  444. }
  445. // 备用方案:直接检查PlacedBlocks容器
  446. const placedBlocksContainer = find('Canvas/GameLevelUI/PlacedBlocks');
  447. if (!placedBlocksContainer) {
  448. console.warn('找不到PlacedBlocks容器');
  449. return false;
  450. }
  451. // 检查容器中是否有子节点(方块)
  452. return placedBlocksContainer.children.length > 0;
  453. }
  454. // 显示没有上阵方块的Toast提示
  455. private showNoPlacedBlocksToast() {
  456. console.log('[GameBlockSelection] 显示未上阵植物提示');
  457. // 使用事件机制显示Toast
  458. EventBus.getInstance().emit(GameEvents.SHOW_TOAST, {
  459. message: '请至少上阵一个植物!',
  460. duration: 3.0
  461. });
  462. console.log('[GameBlockSelection] 请至少上阵一个植物!');
  463. }
  464. // 设置方块拖拽事件
  465. public setupBlockDragEvents(block: Node) {
  466. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  467. if (this.blockManager.gameStarted && this.blockManager.blockLocations.get(block) === 'grid') {
  468. if (!this.canMoveBlock(block)) {
  469. return;
  470. }
  471. }
  472. this.currentDragBlock = block;
  473. this.startPos = event.getUILocation();
  474. this.blockStartPos.set(block.position);
  475. this.currentDragBlock['startLocation'] = this.blockManager.blockLocations.get(block);
  476. block.setSiblingIndex(block.parent.children.length - 1);
  477. this.blockManager.tempStoreBlockOccupiedGrids(block);
  478. // 拖拽开始时禁用碰撞体
  479. const collider = block.getComponent(Collider2D);
  480. if (collider) collider.enabled = false;
  481. }, this);
  482. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  483. if (this.blockManager.gameStarted && this.blockManager.blockLocations.get(block) === 'grid') {
  484. if (!this.canMoveBlock(block)) {
  485. return;
  486. }
  487. }
  488. if (!this.currentDragBlock) return;
  489. const location = event.getUILocation();
  490. const deltaX = location.x - this.startPos.x;
  491. const deltaY = location.y - this.startPos.y;
  492. this.currentDragBlock.position = new Vec3(
  493. this.blockStartPos.x + deltaX,
  494. this.blockStartPos.y + deltaY,
  495. this.blockStartPos.z
  496. );
  497. // 更新调试绘制
  498. this.updateDebugDraw();
  499. }, this);
  500. block.on(Node.EventType.TOUCH_END, async (event: EventTouch) => {
  501. if (this.blockManager.gameStarted && this.blockManager.blockLocations.get(block) === 'grid') {
  502. if (!this.canMoveBlock(block)) {
  503. return;
  504. }
  505. }
  506. if (this.currentDragBlock) {
  507. try {
  508. await this.handleBlockDrop(event);
  509. } catch (error) {
  510. console.error('[GameBlockSelection] 处理方块拖拽放置时发生错误:', error);
  511. // 发生错误时,将方块返回原位置
  512. this.returnBlockToOriginalPosition();
  513. }
  514. this.currentDragBlock = null;
  515. // 拖拽结束时恢复碰撞体
  516. const collider = block.getComponent(Collider2D);
  517. if (collider) collider.enabled = true;
  518. // 更新调试绘制
  519. this.updateDebugDraw();
  520. }
  521. }, this);
  522. block.on(Node.EventType.TOUCH_CANCEL, () => {
  523. if (this.currentDragBlock) {
  524. this.returnBlockToOriginalPosition();
  525. this.currentDragBlock = null;
  526. // 拖拽取消时恢复碰撞体
  527. const collider = block.getComponent(Collider2D);
  528. if (collider) collider.enabled = true;
  529. // 更新调试绘制
  530. this.updateDebugDraw();
  531. }
  532. }, this);
  533. }
  534. // 检查方块是否可以移动
  535. private canMoveBlock(block: Node): boolean {
  536. return true;
  537. }
  538. // 处理方块放下
  539. private async handleBlockDrop(event: EventTouch) {
  540. try {
  541. const touchPos = event.getLocation();
  542. const startLocation = this.currentDragBlock['startLocation'];
  543. if (this.isInKuangArea(touchPos)) {
  544. // 检查是否有标签,只有有标签的方块才能放回kuang
  545. if (BlockTag.hasTag(this.currentDragBlock)) {
  546. this.returnBlockToKuang(startLocation);
  547. // 返回kuang后输出格子占用情况
  548. this.blockManager.printGridOccupationMatrix();
  549. // 刷新方块占用情况
  550. this.refreshGridOccupation();
  551. } else {
  552. // 没有标签的方块不能放回kuang,返回原位置
  553. console.log(`[GameBlockSelection] 方块 ${this.currentDragBlock.name} 没有标签,不能放回kuang区域`);
  554. this.returnBlockToOriginalPosition();
  555. // 返回原位置后输出格子占用情况
  556. this.blockManager.printGridOccupationMatrix();
  557. // 刷新方块占用情况
  558. this.refreshGridOccupation();
  559. }
  560. } else if (this.blockManager.tryPlaceBlockToGrid(this.currentDragBlock)) {
  561. await this.handleSuccessfulPlacement(startLocation);
  562. // 放置成功后输出格子占用情况
  563. this.blockManager.printGridOccupationMatrix();
  564. // 刷新方块占用情况
  565. this.refreshGridOccupation();
  566. } else {
  567. console.log(`[GameBlockSelection] 方块 ${this.currentDragBlock.name} 放置到网格失败`);
  568. console.log(`[GameBlockSelection] 方块标签状态:`, BlockTag.hasTag(this.currentDragBlock));
  569. console.log(`[GameBlockSelection] 方块UUID:`, this.currentDragBlock.uuid);
  570. // 放置失败,尝试直接与重叠方块合成
  571. if (this.blockManager.tryMergeOnOverlap(this.currentDragBlock)) {
  572. // 合成成功时,若来自 kuang 则扣费
  573. if (startLocation !== 'grid') {
  574. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  575. this.blockManager.deductPlayerCoins(price);
  576. }
  577. // 当前拖拽块已被销毁(合并时),无需复位
  578. // 合成成功后输出格子占用情况
  579. this.blockManager.printGridOccupationMatrix();
  580. // 刷新方块占用情况
  581. this.refreshGridOccupation();
  582. } else {
  583. console.log(`[GameBlockSelection] 方块 ${this.currentDragBlock.name} 合成也失败,返回原位置`);
  584. this.returnBlockToOriginalPosition();
  585. // 放置失败后输出格子占用情况
  586. this.blockManager.printGridOccupationMatrix();
  587. // 刷新方块占用情况
  588. this.refreshGridOccupation();
  589. }
  590. }
  591. } catch (error) {
  592. console.error('[GameBlockSelection] handleBlockDrop 发生错误:', error);
  593. // 发生错误时,将方块返回原位置
  594. this.returnBlockToOriginalPosition();
  595. throw error; // 重新抛出错误,让上层处理
  596. }
  597. }
  598. // 检查是否在kuang区域内
  599. private isInKuangArea(touchPos: Vec2): boolean {
  600. if (!this.blockManager.kuangContainer) return false;
  601. const kuangTransform = this.blockManager.kuangContainer.getComponent(UITransform);
  602. if (!kuangTransform) return false;
  603. const kuangBoundingBox = new Rect(
  604. this.blockManager.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
  605. this.blockManager.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
  606. kuangTransform.width,
  607. kuangTransform.height
  608. );
  609. return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
  610. }
  611. // 返回方块到kuang区域
  612. private returnBlockToKuang(startLocation: string) {
  613. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  614. if (originalPos) {
  615. const kuangNode = this.blockManager.kuangContainer;
  616. if (kuangNode && this.currentDragBlock.parent !== kuangNode) {
  617. this.currentDragBlock.removeFromParent();
  618. kuangNode.addChild(this.currentDragBlock);
  619. }
  620. this.currentDragBlock.position = originalPos.clone();
  621. }
  622. this.blockManager.restoreBlockOccupiedGrids(this.currentDragBlock);
  623. this.blockManager.blockLocations.set(this.currentDragBlock, 'kuang');
  624. this.blockManager.showPriceLabel(this.currentDragBlock);
  625. if (startLocation === 'grid') {
  626. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  627. this.blockManager.refundPlayerCoins(price);
  628. this.currentDragBlock['placedBefore'] = false;
  629. }
  630. const dbNode = this.currentDragBlock['dbNode'];
  631. if (dbNode) {
  632. dbNode.active = true;
  633. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  634. }
  635. }
  636. // 处理成功放置
  637. private async handleSuccessfulPlacement(startLocation: string) {
  638. try {
  639. const price = this.blockManager.getBlockPrice(this.currentDragBlock);
  640. if (startLocation === 'grid') {
  641. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  642. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  643. this.blockManager.hidePriceLabel(this.currentDragBlock);
  644. const dbNode = this.currentDragBlock['dbNode'];
  645. if (dbNode) {
  646. dbNode.active = false;
  647. }
  648. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  649. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  650. // 如果游戏已开始,添加锁定视觉提示
  651. if (this.blockManager.gameStarted) {
  652. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  653. // 游戏开始后放置的方块移除标签,不能再放回kuang
  654. BlockTag.removeTag(this.currentDragBlock);
  655. }
  656. // 检查并执行合成
  657. try {
  658. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  659. } catch (mergeError) {
  660. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  661. // 合成失败不影响方块放置,只记录错误
  662. }
  663. } else {
  664. if (this.blockManager.deductPlayerCoins(price)) {
  665. this.blockManager.clearTempStoredOccupiedGrids(this.currentDragBlock);
  666. this.blockManager.blockLocations.set(this.currentDragBlock, 'grid');
  667. this.blockManager.hidePriceLabel(this.currentDragBlock);
  668. const dbNode = this.currentDragBlock['dbNode'];
  669. if (dbNode) {
  670. dbNode.active = false;
  671. }
  672. this.currentDragBlock['placedBefore'] = true;
  673. // 立即将方块移动到PlacedBlocks节点下,不等游戏开始
  674. this.blockManager.moveBlockToPlacedBlocks(this.currentDragBlock);
  675. // 如果游戏已开始,添加锁定视觉提示
  676. if (this.blockManager.gameStarted) {
  677. this.blockManager.addLockedVisualHint(this.currentDragBlock);
  678. // 游戏开始后放置的方块移除标签,不能再放回kuang
  679. BlockTag.removeTag(this.currentDragBlock);
  680. }
  681. // 检查并执行合成
  682. try {
  683. await this.blockManager.tryMergeBlock(this.currentDragBlock);
  684. } catch (mergeError) {
  685. console.error('[GameBlockSelection] 方块合成时发生错误:', mergeError);
  686. // 合成失败不影响方块放置,只记录错误
  687. }
  688. } else {
  689. this.returnBlockToOriginalPosition();
  690. }
  691. }
  692. } catch (error) {
  693. console.error('[GameBlockSelection] handleSuccessfulPlacement 发生错误:', error);
  694. // 发生错误时,将方块返回原位置
  695. this.returnBlockToOriginalPosition();
  696. throw error; // 重新抛出错误,让上层处理
  697. }
  698. }
  699. // 返回方块到原位置
  700. private returnBlockToOriginalPosition() {
  701. const currentLocation = this.blockManager.blockLocations.get(this.currentDragBlock);
  702. if (currentLocation === 'kuang') {
  703. const originalPos = this.blockManager.originalPositions.get(this.currentDragBlock);
  704. if (originalPos) {
  705. this.currentDragBlock.position = originalPos.clone();
  706. }
  707. } else {
  708. this.currentDragBlock.position = this.blockStartPos.clone();
  709. }
  710. this.blockManager.restoreBlockOccupiedGrids(this.currentDragBlock);
  711. this.blockManager.showPriceLabel(this.currentDragBlock);
  712. const dbNode = this.currentDragBlock['dbNode'];
  713. if (dbNode) {
  714. dbNode.active = true;
  715. this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
  716. }
  717. // 刷新方块占用情况
  718. this.refreshGridOccupation();
  719. }
  720. // === 调试绘制相关方法 ===
  721. // 初始化调试绘制
  722. private initDebugDraw() {
  723. if (!this.debugDrawSnapRange) return;
  724. // 创建调试绘制节点
  725. this.debugDrawNode = new Node('DebugDraw');
  726. this.debugGraphics = this.debugDrawNode.addComponent(Graphics);
  727. // 将调试绘制节点添加到场景中
  728. if (this.gridContainer && this.gridContainer.parent) {
  729. this.gridContainer.parent.addChild(this.debugDrawNode);
  730. }
  731. console.log('[GameBlockSelection] 调试绘制初始化完成');
  732. }
  733. // 绘制网格吸附范围
  734. private drawGridSnapRanges() {
  735. if (!this.debugDrawSnapRange || !this.debugGraphics || !this.blockManager) return;
  736. this.debugGraphics.strokeColor = Color.GREEN;
  737. this.debugGraphics.lineWidth = 2;
  738. // 通过BlockManager获取网格信息来绘制吸附范围
  739. const gridSpacing = 54; // 网格间距
  740. const snapRange = gridSpacing * 0.8; // 吸附范围
  741. // 遍历所有网格位置,绘制吸附范围
  742. for (let row = 0; row < 6; row++) {
  743. for (let col = 0; col < 11; col++) {
  744. // 计算网格世界坐标
  745. const gridWorldPos = this.blockManager.getGridWorldPosition(row, col);
  746. if (!gridWorldPos) continue;
  747. // 转换为调试绘制节点的本地坐标
  748. const localPos = new Vec3();
  749. this.debugDrawNode.getComponent(UITransform).convertToNodeSpaceAR(gridWorldPos, localPos);
  750. // 绘制网格吸附范围圆圈
  751. this.debugGraphics.circle(localPos.x, localPos.y, snapRange);
  752. this.debugGraphics.stroke();
  753. }
  754. }
  755. }
  756. // 绘制方块吸附范围
  757. private drawBlockSnapRange(block: Node) {
  758. if (!this.debugDrawSnapRange || !this.debugGraphics || !block || !this.blockManager) return;
  759. // 绘制方块吸附点
  760. this.debugGraphics.strokeColor = Color.RED;
  761. this.debugGraphics.fillColor = Color.RED;
  762. this.debugGraphics.lineWidth = 3;
  763. const blockParts = this.blockManager.getBlockParts(block);
  764. const gridSpacing = 54; // 网格间距
  765. const snapRange = gridSpacing * 0.6; // 吸附范围
  766. blockParts.forEach(part => {
  767. const worldPos = part.node.getWorldPosition();
  768. const localPos = new Vec3();
  769. this.debugDrawNode.getComponent(UITransform).convertToNodeSpaceAR(worldPos, localPos);
  770. // 绘制红色十字标记吸附点
  771. const crossSize = 10;
  772. this.debugGraphics.moveTo(localPos.x - crossSize, localPos.y);
  773. this.debugGraphics.lineTo(localPos.x + crossSize, localPos.y);
  774. this.debugGraphics.moveTo(localPos.x, localPos.y - crossSize);
  775. this.debugGraphics.lineTo(localPos.x, localPos.y + crossSize);
  776. this.debugGraphics.stroke();
  777. // 绘制吸附范围圆圈
  778. this.debugGraphics.circle(localPos.x, localPos.y, snapRange);
  779. this.debugGraphics.stroke();
  780. });
  781. }
  782. // 更新调试绘制
  783. private updateDebugDraw() {
  784. if (!this.debugDrawSnapRange || !this.debugGraphics) return;
  785. this.debugGraphics.clear();
  786. // 绘制网格吸附范围
  787. this.drawGridSnapRanges();
  788. // 如果有正在拖拽的方块,绘制其吸附范围
  789. if (this.currentDragBlock) {
  790. this.drawBlockSnapRange(this.currentDragBlock);
  791. }
  792. }
  793. // 清理调试绘制
  794. private cleanupDebugDraw() {
  795. if (this.debugDrawNode && this.debugDrawNode.isValid) {
  796. this.debugDrawNode.destroy();
  797. this.debugDrawNode = null;
  798. this.debugGraphics = null;
  799. }
  800. }
  801. // 设置调试绘制开关
  802. public setDebugDrawSnapRange(enabled: boolean) {
  803. this.debugDrawSnapRange = enabled;
  804. if (enabled) {
  805. this.initDebugDraw();
  806. } else {
  807. this.cleanupDebugDraw();
  808. }
  809. console.log(`[GameBlockSelection] 调试绘制已${enabled ? '开启' : '关闭'}`);
  810. }
  811. onDisable() {
  812. this.removeEventListeners();
  813. this.cleanupDebugDraw();
  814. }
  815. onDestroy() {
  816. this.removeEventListeners();
  817. this.cleanupDebugDraw();
  818. }
  819. // 移除事件监听器
  820. private removeEventListeners() {
  821. const eventBus = EventBus.getInstance();
  822. eventBus.off(GameEvents.RESET_BLOCK_SELECTION, this.onResetBlockSelectionEvent, this);
  823. eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
  824. eventBus.off(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.onSetupBlockDragEventsEvent, this);
  825. }
  826. }