LevelAction.ts 17 KB

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