GameBlockSelection.ts 43 KB

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