LevelAction.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 { GameUtil } from './GameUtil';
  16. import { OriginArea } from './Component/OriginArea';
  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. 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 freezeInit = TakeGobletGlobalInstance.instance.refreshFreezeWaterInit();
  131. const freezeCount = this.originArea.getComponent(OriginArea)!.getFrozenCupCount();
  132. const freezeOver = TakeGobletGlobalInstance.instance.isOverFreezeWaterCeiling(freezeCount);
  133. const freeze = freezeInit && !freezeOver;
  134. originCup.getComponent(OriginCup)!.freezeActive = freeze;
  135. // 在生成初始原浆杯时记录位置
  136. const id = originCupNode.uuid; // 使用节点唯一ID
  137. this.originCupPositions.set(id, originCupNode.position.clone());
  138. // console.log('在生成初始原浆杯时记录id : ', id, originCupNode.position);
  139. });
  140. }
  141. private findTargetCupInOutArea(color: WaterColors): { node: Node, comp: CocktailCup } | null {
  142. const validCups = this.outArea.getCups()
  143. .map(node => ({
  144. node,
  145. comp: node.getComponent(CocktailCup)!
  146. }))
  147. .filter(({ comp }) =>
  148. comp &&
  149. comp.cupColor === color &&
  150. !comp.isFull
  151. );
  152. if (validCups.length === 0) return null;
  153. const sorted = validCups.sort((a, b) => (a.comp.remainingCapacity ?? 0) - (b.comp.remainingCapacity ?? 0));
  154. return sorted[0];
  155. }
  156. public async handlePourOriginCup(originCup: OriginCup) {
  157. if (this.isProcessing) {
  158. tgxUITips.show('我知道你很急,但你先别急!');
  159. return;
  160. }
  161. this.isProcessing = true;
  162. try {
  163. // 如果子节点0是底层,需要反转顺序
  164. const watersNode: Node[] = [];
  165. for (let i = originCup.waters.children.length - 1; i >= 0; i--) {
  166. const waterNode = originCup.waters.children[i];
  167. if (waterNode.active) {
  168. watersNode.push(waterNode);
  169. }
  170. }
  171. let hasUnprocessed = false; // 标记是否有未处理的水层
  172. originCup.setMark(false);
  173. for (const waterNode of watersNode) {
  174. const color = waterNode.getComponent(Water)!.color;
  175. console.log(`当前处理的颜色:${WaterColorLog[color]}}`);
  176. let targetNode: Node | null = this.findTargetCupInOutArea(color)?.node || null;
  177. let targetIsTemp = false;
  178. // 调酒区未找到,查找暂存区
  179. if (!targetNode) {
  180. const tempCupsComp = this.tempCups.getComponent(TempCups);
  181. if (!tempCupsComp) {
  182. console.error('TempCups component not found!');
  183. continue;
  184. }
  185. const tempCup = tempCupsComp.findAvailableTempCup();
  186. if (tempCup) {
  187. targetNode = tempCup.node;
  188. targetIsTemp = true;
  189. }
  190. }
  191. if (!targetNode) {
  192. hasUnprocessed = true;
  193. console.log(`颜色${WaterColors[color]}未找到可用杯子`);
  194. continue; // 继续尝试处理后续颜色
  195. }
  196. await this.pourAnimation(
  197. originCup.node,
  198. targetNode,
  199. color,
  200. undefined,
  201. targetIsTemp
  202. );
  203. await this.hideCurrentWaterLayer(originCup);
  204. // 更新目标杯
  205. if (targetIsTemp) {
  206. const tempCupComp = targetNode.getComponent(TempCup)!;
  207. tempCupComp.fill(color);
  208. } else {
  209. const cocktailCup = targetNode.getComponent(CocktailCup)!;
  210. await cocktailCup.addLayer(color); // 等待添加水层流程完成
  211. }
  212. }
  213. // 处理完所有颜色后检查剩余水层
  214. const remaining = originCup.waters.children.filter(n => n.active).length;
  215. if (hasUnprocessed || remaining > 0) {
  216. // console.log("游戏结束:仍有未处理的水层");
  217. this.isProcessing = true;
  218. LevelManager.instance.levelModel.isWin = false;
  219. tgxUIMgr.inst.showUI(UI_BattleResult);
  220. } else {
  221. // 所有水层处理完毕,销毁原浆杯
  222. originCup.destroyOriginCup();
  223. this.addWaitCupToOutArea();
  224. }
  225. } finally {
  226. this.isProcessing = false;
  227. }
  228. }
  229. //处理暂存区倒水到调酒区
  230. private async handlePourTempCupToOutArea() {
  231. if (this.isProcessing) return;
  232. this.isProcessing = true;
  233. try {
  234. const tempCupsComp = this.tempCups.getComponent(TempCups)!;
  235. const filledCups = tempCupsComp.getFilledCups();
  236. for (const tempCup of filledCups) {
  237. const originalPos = tempCup.node.position.clone();
  238. const colors = tempCup.getColors();
  239. let hasProcessed = false; // 标记是否有处理过颜色
  240. for (const color of colors) {
  241. const targetCup = this.findTargetCupInOutArea(color);
  242. if (!targetCup) {
  243. console.log(`颜色${WaterColors[color]}未找到可用调酒杯`);
  244. continue;
  245. }
  246. await this.pourAnimation(
  247. tempCup.node,
  248. targetCup.node,
  249. color,
  250. originalPos,
  251. true
  252. );
  253. const cocktailCup = targetCup.comp;
  254. await cocktailCup.addLayer(color);
  255. hasProcessed = true; // 标记已处理
  256. }
  257. // 仅当有处理过颜色时才重置暂存杯
  258. if (hasProcessed) {
  259. tempCup.reset();
  260. }
  261. }
  262. } finally {
  263. this.isProcessing = false;
  264. }
  265. }
  266. // 添加新杯子后触发暂存区倒水
  267. private async addWaitCupToOutArea() {
  268. // 原有添加逻辑保持不变
  269. const waitCups = this.waitArea.cups;
  270. const outCups = this.outArea.getCups();
  271. const needAddCount = outCups.length === 0 ? 2 : 1;
  272. const byX = outCups.length === 0 ? 160 : 80;
  273. const movingCups: Node[] = [];
  274. for (let i = 0; i < needAddCount; i++) {
  275. if (waitCups.length === 0) break;
  276. movingCups.push(waitCups.pop()!);
  277. }
  278. const newCups: Node[] = [];
  279. for (const cup of movingCups) {
  280. const comp = cup.getComponent(CocktailCup)!;
  281. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncCocktail(comp.cupHeight);
  282. const newCup = instantiate(prefab);
  283. const newComp = newCup.getComponent(CocktailCup)!;
  284. newComp.cupColor = comp.cupColor;
  285. newComp.reset();
  286. const targetX = outCups.length === 0 ?
  287. (newCups.length === 0 ? -120 : -40) :
  288. -40;
  289. newCup.setPosition(new Vec3(targetX, 0, 0));
  290. newCups.push(newCup);
  291. cup.destroy();
  292. }
  293. const outNodes = this.outArea.node.getChildByName('OutNodes')!;
  294. newCups.forEach(cup => cup.setParent(outNodes));
  295. // 执行统一平移
  296. if (this.waitArea.getCups().length > 0) {
  297. this.outArea.getCups().concat(this.waitArea.getCups()).forEach(cup => {
  298. tween(cup)
  299. .by(0.3, { position: new Vec3(byX, 0, 0) }, { easing: 'sineOut' })
  300. .start();
  301. });
  302. }
  303. // 在添加完成后处理暂存区倒水
  304. await this.handlePourTempCupToOutArea();
  305. // 胜利条件检测:当两个区域都没有杯子时触发胜利
  306. if (this.outArea.getCups().length === 0 && this.waitArea.cups.length === 0) {
  307. this.isProcessing = true;
  308. LevelManager.instance.levelModel.isWin = true;
  309. tgxUIMgr.inst.showUI(UI_BattleResult);
  310. }
  311. }
  312. //倒水移动动画
  313. private async pourAnimation(
  314. origin: Node,
  315. target: Node,
  316. color: WaterColors,
  317. originalPos?: Vec3,
  318. isTempCup: boolean = false
  319. ) {
  320. // 使用正确的坐标转换
  321. const originParent = origin.parent!;
  322. const targetWorldPos = target.worldPosition;
  323. const localPos = originParent.getComponent(UITransform)!.convertToNodeSpaceAR(targetWorldPos);
  324. // 调整Y轴偏移量
  325. if (isTempCup) {
  326. localPos.x -= 50; // 暂存杯偏移
  327. localPos.y += 80;
  328. } else {
  329. localPos.x -= 50; // 调酒杯偏移
  330. localPos.y += 100;
  331. }
  332. //播放动画
  333. origin.getComponent(OriginCup)?.playAnimation(OriginCupState.Up);
  334. // 移动动画到目标位置
  335. await new Promise<void>(resolve => {
  336. tween(origin)
  337. .to(0.5, { position: localPos })
  338. .call(resolve)
  339. .start();
  340. });
  341. // 返回到暂存区初始位置
  342. if (isTempCup && originalPos) {
  343. await new Promise(resolve => {
  344. tween(origin)
  345. .to(0.3, { position: originalPos })
  346. .call(resolve)
  347. .start();
  348. });
  349. }
  350. }
  351. //隐藏原浆杯当前水层 等待倒水动画
  352. private async hideCurrentWaterLayer(originCup: OriginCup) {
  353. const activeWaters = originCup.waters.children.filter(n => n.active);
  354. const topIndex = originCup.waters.children.length - activeWaters.length;
  355. if (activeWaters.length >= 0) {
  356. originCup.getComponent(OriginCup)?.playAnimation(OriginCupState.PourWater, topIndex + 1);
  357. await GameUtil.delay(0.6);
  358. activeWaters[activeWaters.length - 1].active = false;
  359. }
  360. }
  361. private async spawnNewOriginCup(targetPos: Vec3) {
  362. const levelModel = LevelManager.instance.levelModel;
  363. const measuringcup_number = levelModel.levelConfig.measuringcup_number;//获取调酒和等待区前面数量
  364. const colors = this.getAvailableColors(measuringcup_number);
  365. if (colors.length <= 0) return;
  366. // 创建新原浆杯
  367. const height = TakeGobletGlobalInstance.instance.generateOriginCupHeight();
  368. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncOriginCup(height);
  369. const newCup = instantiate(prefab);
  370. this.originArea.addChild(newCup);
  371. await newCup.getComponent(OriginCup)?.spawnNewOriginCup(height, targetPos, colors);
  372. }
  373. // 获取可用颜色
  374. private getAvailableColors(count: number): WaterColors[] {
  375. const outCups = this.outArea.getCups();
  376. const waitCups = this.waitArea.getCups();
  377. const allCups = [...outCups, ...waitCups].slice(0, count);
  378. return allCups.map(cup => {
  379. const comp = cup.getComponent(CocktailCup);
  380. return comp ? comp.cupColor : WaterColors.Blue;
  381. });
  382. }
  383. private handleCupDestroyed(destroyedCup: Node) {
  384. // 从outArea移除被销毁的杯子
  385. this.outArea.removeCup(destroyedCup);
  386. }
  387. }