LevelAction.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. import { _decorator, BoxCollider2D, Button, CircleCollider2D, Collider2D, Component, find, instantiate, Node, NodeEventType, tween, view, Vec3, mat4, UITransform } from 'cc';
  2. import { CupHeight, TakeGobletGlobalInstance, WaterColorLog, WaterColors } from './TakeGobletGlobalInstance';
  3. import { OutArea } from './Component/OutArea';
  4. import { WaitArea } from './Component/WaitArea';
  5. import { CocktailCup } from './Component/CocktailCup';
  6. import { OriginCup, OriginCupState } from './Component/OriginCup';
  7. import { Water } from './Component/Water';
  8. import { EventDispatcher } from '../../core_tgx/easy_ui_framework/EventDispatcher';
  9. import { GameEvent } from './Enum/GameEvent';
  10. import { TempCup } from './Component/TempCup';
  11. import { TempCups } from './Component/TempCups';
  12. import { tgxUIMgr, tgxUITips } from '../../core_tgx/tgx';
  13. import { LevelManager } from './Manager/LevelMgr';
  14. import { UI_BattleResult } from '../../scripts/UIDef';
  15. import { OriginArea } from './Component/OriginArea';
  16. import { GameUtil } from './GameUtil';
  17. const { ccclass, property } = _decorator;
  18. @ccclass('LevelAction')
  19. export class LevelAction extends Component {
  20. @property(OutArea)
  21. outArea: OutArea = null!; // 直接引用OutArea组件
  22. @property(WaitArea)
  23. waitArea: WaitArea = null!; // 直接引用WaitArea组件
  24. @property(Node)
  25. tempCups: Node = null!; //临时杯
  26. @property(Node)
  27. originArea: Node = null!; //原浆区
  28. private originCupPositions = new Map<string, Vec3>(); // 改用唯一ID记录
  29. private isProcessing = false; // 添加状态锁
  30. static instance: LevelAction; // 添加静态实例
  31. onLoad() {
  32. LevelAction.instance = this;
  33. }
  34. start() {
  35. this.generateInitialCups();
  36. this.registerListener();
  37. }
  38. onDestroy() {
  39. this.unregisterListener();
  40. }
  41. registerListener() {
  42. EventDispatcher.instance.on(GameEvent.EVENT_REFRESH_COLOR, this.generateOriginCups, this);
  43. EventDispatcher.instance.on(GameEvent.EVENT_CLICK_ORIGIN_CUP, this.handlePourOriginCup, this);
  44. EventDispatcher.instance.on(GameEvent.EVENT_ORIGIN_CUP_DESTROYED, (uuid: string) => {
  45. if (!this.originCupPositions) return
  46. const targetPos = this.originCupPositions.get(uuid);
  47. if (targetPos) {
  48. this.spawnNewOriginCup(targetPos);
  49. }
  50. }, this);
  51. EventDispatcher.instance.on(GameEvent.EVENT_COCKTAIL_CUP_DESTROYED, this.handleCupDestroyed, this);
  52. }
  53. unregisterListener() {
  54. EventDispatcher.instance.off(GameEvent.EVENT_REFRESH_COLOR, this.generateOriginCups, this);
  55. EventDispatcher.instance.off(GameEvent.EVENT_CLICK_ORIGIN_CUP, this.handlePourOriginCup, this);
  56. EventDispatcher.instance.off(GameEvent.EVENT_ORIGIN_CUP_DESTROYED, this.spawnNewOriginCup, this);
  57. EventDispatcher.instance.off(GameEvent.EVENT_COCKTAIL_CUP_DESTROYED, this.handleCupDestroyed, this);
  58. }
  59. private async generateInitialCups() {
  60. const instance = TakeGobletGlobalInstance.instance;
  61. const configs = instance.getInitialCupsConfig();
  62. const allCups: Node[] = [];
  63. for (const config of configs) {
  64. for (let i = 0; i < config.count; i++) {
  65. const prefab = await instance.loadAsyncCocktail(config.height);
  66. const cupNode = instantiate(prefab);
  67. const cup = cupNode.getComponent(CocktailCup)!;
  68. cup.reset();
  69. allCups.push(cupNode);
  70. }
  71. }
  72. const levelColors = LevelManager.instance.levelModel.levelColors;
  73. const rule = instance.cocktailCupRule();
  74. const [x, y] = rule;
  75. const colorPool = levelColors.slice(0, y);
  76. // 为所有杯子分配颜色,并控制颜色种类不超过y种
  77. allCups.forEach(cup => {
  78. const cupComp = cup.getComponent(CocktailCup)!;
  79. // 从颜色池随机选择一个颜色
  80. const randomColor = colorPool[Math.floor(Math.random() * colorPool.length)];
  81. cupComp.cupColor = randomColor;
  82. });
  83. console.log('allCups: ', allCups.length);
  84. // 分配初始位置
  85. allCups.slice(0, 2).forEach(cup => this.outArea.addCup(cup));
  86. allCups.slice(2).forEach(cup => this.waitArea.addCup(cup));
  87. // 在分配完调酒杯后添加
  88. this.generateOriginCups();
  89. // 初始化暂存区
  90. this.tempCups.children.forEach(tempCupNode => {
  91. const tempCup = tempCupNode.getComponent(TempCup)!;
  92. tempCup.reset(); // 重置所有暂存杯
  93. });
  94. }
  95. // 当调酒区杯子被消除时调用
  96. public async handleCupsRemoved(count: number) {
  97. for (let i = 0; i < count; i++) {
  98. const cup = this.waitArea.takeCup();
  99. if (cup) {
  100. this.outArea.addCup(cup);
  101. }
  102. }
  103. }
  104. private async generateOriginCups() {
  105. if (this.isProcessing) {
  106. tgxUITips.show('我知道你很急,但你先别急!');
  107. return;
  108. }
  109. const levelModel = LevelManager.instance.levelModel;
  110. const outCups = this.outArea.getCups() as Node[];
  111. const waitCups = this.waitArea.getCups() as Node[];
  112. const measuringcup_number = levelModel.levelConfig.measuringcup_number;
  113. const allCups = [...outCups, ...waitCups].slice(0, measuringcup_number);
  114. const colors = allCups.map(cup => {
  115. const comp = cup.getComponent(CocktailCup);
  116. return comp ? comp.cupColor : WaterColors.Blue;
  117. });
  118. this.originArea.children.forEach(originCupNode => {
  119. const originCup = originCupNode.getComponent(OriginCup)!;
  120. const waters = originCup.waters.children;
  121. for (let i = 0; i < originCup.cupHeight; i++) {
  122. const waterNode = waters[i];
  123. const water = waterNode.getComponent(Water);
  124. if (water) {
  125. water.initColor(colors[Math.floor(Math.random() * colors.length)]);
  126. waterNode.active = true;
  127. }
  128. }
  129. // 在生成初始原浆杯时记录位置
  130. const id = originCupNode.uuid; // 使用节点唯一ID
  131. this.originCupPositions.set(id, originCupNode.position.clone());
  132. // console.log('在生成初始原浆杯时记录id : ', id, originCupNode.position);
  133. });
  134. }
  135. private findTargetCupInOutArea(color: WaterColors): { node: Node, comp: CocktailCup } | null {
  136. const validCups = this.outArea.getCups()
  137. .map(node => ({
  138. node,
  139. comp: node.getComponent(CocktailCup)!
  140. }))
  141. .filter(({ comp }) =>
  142. comp &&
  143. comp.cupColor === color &&
  144. !comp.isFull
  145. );
  146. if (validCups.length === 0) return null;
  147. const sorted = validCups.sort((a, b) => (a.comp.remainingCapacity ?? 0) - (b.comp.remainingCapacity ?? 0));
  148. return sorted[0];
  149. }
  150. public async handlePourOriginCup(originCup: OriginCup) {
  151. if (this.isProcessing) {
  152. tgxUITips.show('我知道你很急,但你先别急!');
  153. return;
  154. }
  155. this.isProcessing = true;
  156. try {
  157. // 如果子节点0是底层,需要反转顺序
  158. const watersNode: Node[] = [];
  159. for (let i = originCup.waters.children.length - 1; i >= 0; i--) {
  160. const waterNode = originCup.waters.children[i];
  161. if (waterNode.active) {
  162. watersNode.push(waterNode);
  163. }
  164. }
  165. let hasUnprocessed = false; // 标记是否有未处理的水层
  166. for (const waterNode of watersNode) {
  167. const color = waterNode.getComponent(Water)!.color;
  168. console.log(`当前处理的颜色:${WaterColorLog[color]}}`);
  169. let targetNode: Node | null = this.findTargetCupInOutArea(color)?.node || null;
  170. let targetIsTemp = false;
  171. //DOTO 处理mark问号图标
  172. // if (waterNode.getComponent(Water).markActive) {
  173. // waterNode.getComponent(Water)!.setMark(false);
  174. // }
  175. // 调酒区未找到,查找暂存区
  176. if (!targetNode) {
  177. const tempCupsComp = this.tempCups.getComponent(TempCups);
  178. if (!tempCupsComp) {
  179. console.error('TempCups component not found!');
  180. continue;
  181. }
  182. const tempCup = tempCupsComp.findAvailableTempCup();
  183. if (tempCup) {
  184. targetNode = tempCup.node;
  185. targetIsTemp = true;
  186. }
  187. }
  188. if (!targetNode) {
  189. hasUnprocessed = true;
  190. console.log(`颜色${WaterColors[color]}未找到可用杯子`);
  191. continue; // 继续尝试处理后续颜色
  192. }
  193. await this.pourAnimation(
  194. originCup.node,
  195. targetNode,
  196. color,
  197. undefined,
  198. targetIsTemp
  199. );
  200. await this.hideCurrentWaterLayer(originCup);
  201. // 更新目标杯
  202. if (targetIsTemp) {
  203. const tempCupComp = targetNode.getComponent(TempCup)!;
  204. tempCupComp.fill(color);
  205. } else {
  206. const cocktailCup = targetNode.getComponent(CocktailCup)!;
  207. await cocktailCup.addLayer(color); // 等待添加水层流程完成
  208. }
  209. }
  210. // 处理完所有颜色后检查剩余水层
  211. const remaining = originCup.waters.children.filter(n => n.active).length;
  212. if (hasUnprocessed || remaining > 0) {
  213. // console.log("游戏结束:仍有未处理的水层");
  214. this.isProcessing = true;
  215. LevelManager.instance.levelModel.isWin = false;
  216. tgxUIMgr.inst.showUI(UI_BattleResult);
  217. } else {
  218. // 所有水层处理完毕,销毁原浆杯
  219. originCup.destroyOriginCup();
  220. this.addWaitCupToOutArea();
  221. }
  222. } finally {
  223. this.isProcessing = false;
  224. }
  225. }
  226. //处理暂存区倒水到调酒区
  227. private async handlePourTempCupToOutArea() {
  228. if (this.isProcessing) return;
  229. this.isProcessing = true;
  230. try {
  231. const tempCupsComp = this.tempCups.getComponent(TempCups)!;
  232. const filledCups = tempCupsComp.getFilledCups();
  233. for (const tempCup of filledCups) {
  234. const originalPos = tempCup.node.position.clone();
  235. const colors = tempCup.getColors();
  236. let hasProcessed = false; // 标记是否有处理过颜色
  237. for (const color of colors) {
  238. const targetCup = this.findTargetCupInOutArea(color);
  239. if (!targetCup) {
  240. console.log(`颜色${WaterColors[color]}未找到可用调酒杯`);
  241. continue;
  242. }
  243. await this.pourAnimation(
  244. tempCup.node,
  245. targetCup.node,
  246. color,
  247. originalPos,
  248. true
  249. );
  250. const cocktailCup = targetCup.comp;
  251. await cocktailCup.addLayer(color);
  252. hasProcessed = true; // 标记已处理
  253. }
  254. // 仅当有处理过颜色时才重置暂存杯
  255. if (hasProcessed) {
  256. tempCup.reset();
  257. }
  258. }
  259. } finally {
  260. this.isProcessing = false;
  261. }
  262. }
  263. // 添加新杯子后触发暂存区倒水
  264. private async addWaitCupToOutArea() {
  265. // 原有添加逻辑保持不变
  266. const waitCups = this.waitArea.cups;
  267. const outCups = this.outArea.getCups();
  268. const needAddCount = outCups.length === 0 ? 2 : 1;
  269. const byX = outCups.length === 0 ? 160 : 80;
  270. const movingCups: Node[] = [];
  271. for (let i = 0; i < needAddCount; i++) {
  272. if (waitCups.length === 0) break;
  273. movingCups.push(waitCups.pop()!);
  274. }
  275. const newCups: Node[] = [];
  276. for (const cup of movingCups) {
  277. const comp = cup.getComponent(CocktailCup)!;
  278. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncCocktail(comp.cupHeight);
  279. const newCup = instantiate(prefab);
  280. const newComp = newCup.getComponent(CocktailCup)!;
  281. newComp.cupColor = comp.cupColor;
  282. newComp.reset();
  283. const targetX = outCups.length === 0 ?
  284. (newCups.length === 0 ? -120 : -40) :
  285. -40;
  286. newCup.setPosition(new Vec3(targetX, 0, 0));
  287. newCups.push(newCup);
  288. cup.destroy();
  289. }
  290. const outNodes = this.outArea.node.getChildByName('OutNodes')!;
  291. newCups.forEach(cup => cup.setParent(outNodes));
  292. // 执行统一平移
  293. if (this.waitArea.getCups().length > 0) {
  294. this.outArea.getCups().concat(this.waitArea.getCups()).forEach(cup => {
  295. tween(cup)
  296. .by(0.3, { position: new Vec3(byX, 0, 0) }, { easing: 'sineOut' })
  297. .start();
  298. });
  299. }
  300. // 在添加完成后处理暂存区倒水
  301. await this.handlePourTempCupToOutArea();
  302. // 胜利条件检测:当两个区域都没有杯子时触发胜利
  303. if (this.outArea.getCups().length === 0 && this.waitArea.cups.length === 0) {
  304. this.isProcessing = true;
  305. LevelManager.instance.levelModel.isWin = true;
  306. tgxUIMgr.inst.showUI(UI_BattleResult);
  307. }
  308. }
  309. //倒水移动动画
  310. private async pourAnimation(
  311. origin: Node,
  312. target: Node,
  313. color: WaterColors,
  314. originalPos?: Vec3,
  315. isTempCup: boolean = false
  316. ) {
  317. // 使用正确的坐标转换
  318. const originParent = origin.parent!;
  319. const targetWorldPos = target.worldPosition;
  320. const localPos = originParent.getComponent(UITransform)!.convertToNodeSpaceAR(targetWorldPos);
  321. // 调整Y轴偏移量
  322. if (isTempCup) {
  323. localPos.x -= 50; // 暂存杯偏移
  324. localPos.y += 80;
  325. } else {
  326. localPos.x -= 50; // 调酒杯偏移
  327. localPos.y += 100;
  328. }
  329. //播放动画
  330. origin.getComponent(OriginCup)?.playAnimation(OriginCupState.Up);
  331. // 移动动画到目标位置
  332. await new Promise<void>(resolve => {
  333. tween(origin)
  334. .to(0.5, { position: localPos })
  335. .call(resolve)
  336. .start();
  337. });
  338. // 返回到暂存区初始位置
  339. if (isTempCup && originalPos) {
  340. await new Promise(resolve => {
  341. tween(origin)
  342. .to(0.3, { position: originalPos })
  343. .call(resolve)
  344. .start();
  345. });
  346. }
  347. }
  348. //隐藏原浆杯当前水层 等待倒水动画
  349. private async hideCurrentWaterLayer(originCup: OriginCup) {
  350. const activeWaters = originCup.waters.children.filter(n => n.active);
  351. const topIndex = originCup.waters.children.length - activeWaters.length;
  352. if (activeWaters.length >= 0) {
  353. originCup.getComponent(OriginCup)?.playAnimation(OriginCupState.PourWater, topIndex + 1);
  354. await GameUtil.delay(0.6);
  355. activeWaters[activeWaters.length - 1].active = false;
  356. }
  357. }
  358. private async spawnNewOriginCup(targetPos: Vec3) {
  359. const levelModel = LevelManager.instance.levelModel;
  360. const measuringcup_number = levelModel.levelConfig.measuringcup_number;//获取调酒和等待区前面数量
  361. const colors = this.getAvailableColors(measuringcup_number);
  362. if (colors.length <= 0) return;
  363. // 创建新原浆杯
  364. const height = TakeGobletGlobalInstance.instance.generateOriginCupHeight();
  365. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncOriginCup(height);
  366. const newCup = instantiate(prefab);
  367. // 设置初始位置(屏幕左侧)
  368. const uiTransform = this.node.getComponent(UITransform)!;
  369. newCup.setPosition(-uiTransform.width / 2, 0, 0);
  370. newCup.getComponent(OriginCup)!.cupHeight = height;
  371. this.originArea.addChild(newCup);
  372. this.setupOriginCupColors(newCup, colors);
  373. // 记录新杯子的初始位置
  374. this.originCupPositions.set(newCup.uuid, targetPos);
  375. // 移动动画到原位置
  376. tween(newCup)
  377. .to(0.5, { position: targetPos })
  378. .start();
  379. const markCount = this.originArea.getComponent(OriginArea)?.getTotalMarkCount();
  380. console.log(`mark总数:${markCount}`);
  381. LevelManager.instance.levelModel.createQuestionCount = markCount;
  382. }
  383. // 获取可用颜色
  384. private getAvailableColors(count: number): WaterColors[] {
  385. const outCups = this.outArea.getCups();
  386. const waitCups = this.waitArea.getCups();
  387. const allCups = [...outCups, ...waitCups].slice(0, count);
  388. return allCups.map(cup => {
  389. const comp = cup.getComponent(CocktailCup);
  390. return comp ? comp.cupColor : WaterColors.Blue;
  391. });
  392. }
  393. // 设置原浆杯颜色
  394. private setupOriginCupColors(cupNode: Node, colors: WaterColors[]) {
  395. const originCup = cupNode.getComponent(OriginCup)!;
  396. const marks = cupNode.getChildByName('Marks')!;
  397. const waters = originCup.waters.children;
  398. // console.log(`新创建原浆杯,高度: ${originCup.cupHeight}`);
  399. const markCount = this.originArea.getComponent(OriginArea)?.getTotalMarkCount();
  400. const waterCount = originCup.cupHeight;
  401. for (let i = 0; i < waterCount; i++) {
  402. const waterNode = waters[i];
  403. if (!waterNode) continue;
  404. const water = waterNode.getComponent(Water)!;
  405. const mark = TakeGobletGlobalInstance.instance.refreshQuestionWater(markCount);
  406. water.color = colors[Math.floor(Math.random() * colors.length)];
  407. waterNode.active = true;
  408. console.log(`i:${i} -- marks.children[i].name:${marks.children[i].name}`);
  409. if (mark) {
  410. marks.children[i].active = true;
  411. marks.children[i].getComponent(Water)!.color = WaterColors.Black;
  412. }
  413. }
  414. }
  415. private handleCupDestroyed(destroyedCup: Node) {
  416. // 从outArea移除被销毁的杯子
  417. this.outArea.removeCup(destroyedCup);
  418. }
  419. }