GameBlockSelection.ts 43 KB

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