GameBlockSelection.ts 42 KB

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