LevelAction.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import { _decorator, BoxCollider2D, Button, CircleCollider2D, Collider2D, Component, find, instantiate, Node, NodeEventType, tween, view, Vec3, mat4, UITransform, Label } 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. import { GtagMgr, GtagType } from '../../core_tgx/base/GtagMgr';
  18. import { GlobalConfig } from '../../start/Config/GlobalConfig';
  19. import { AdvertMgr } from '../../core_tgx/base/ad/AdvertMgr';
  20. const { ccclass, property } = _decorator;
  21. //动画时长
  22. export const ANIMATION_DURATION = 0.3;
  23. @ccclass('LevelAction')
  24. export class LevelAction extends Component {
  25. @property(OutArea)
  26. outArea: OutArea = null!; // 直接引用OutArea组件
  27. @property(WaitArea)
  28. waitArea: WaitArea = null!; // 直接引用WaitArea组件
  29. @property(Node)
  30. tempCups: Node = null!; //临时杯
  31. @property(Node)
  32. originArea: Node = null!; //原浆区
  33. originCupPositions = new Map<string, Vec3>(); // 改用唯一ID记录
  34. private isProcessing = false; // 添加状态锁
  35. static instance: LevelAction; // 添加静态实例
  36. onLoad() {
  37. LevelAction.instance = this;
  38. }
  39. start() {
  40. this.generateInitialCups();
  41. this.registerListener();
  42. this.reportInformation();
  43. }
  44. //上报信息
  45. reportInformation() {
  46. const { level } = LevelManager.instance.levelModel;
  47. console.log(`上报信息 level:${level}`);
  48. GtagMgr.inst.doGameDot(GtagType.level_start, { level });
  49. if (!GlobalConfig.isDebug) {
  50. AdvertMgr.instance.showInterstitial();
  51. }
  52. }
  53. onDestroy() {
  54. this.unregisterListener();
  55. }
  56. registerListener() {
  57. EventDispatcher.instance.on(GameEvent.EVENT_REFRESH_COLOR, this.generateOriginCups, this);
  58. EventDispatcher.instance.on(GameEvent.EVENT_CLICK_ORIGIN_CUP, this.handlePourOriginCup, this);
  59. EventDispatcher.instance.on(GameEvent.EVENT_ORIGIN_CUP_DESTROYED, (uuid: string) => {
  60. if (!this.originCupPositions) return
  61. const targetPos = this.originCupPositions.get(uuid);
  62. if (targetPos) {
  63. this.spawnNewOriginCup(targetPos);
  64. }
  65. }, this);
  66. EventDispatcher.instance.on(GameEvent.EVENT_COCKTAIL_CUP_DESTROYED, this.handleCupDestroyed, this);
  67. EventDispatcher.instance.on(GameEvent.EVENT_RIGHT_CUP_FULL, this.addWaitCupToOutArea, this);
  68. EventDispatcher.instance.on(GameEvent.EVENT_CHECK_GAME_OVER, this.checkGameOver, this);
  69. }
  70. unregisterListener() {
  71. EventDispatcher.instance.off(GameEvent.EVENT_REFRESH_COLOR, this.generateOriginCups, this);
  72. EventDispatcher.instance.off(GameEvent.EVENT_CLICK_ORIGIN_CUP, this.handlePourOriginCup, this);
  73. EventDispatcher.instance.off(GameEvent.EVENT_ORIGIN_CUP_DESTROYED, this.spawnNewOriginCup, this);
  74. EventDispatcher.instance.off(GameEvent.EVENT_COCKTAIL_CUP_DESTROYED, this.handleCupDestroyed, this);
  75. EventDispatcher.instance.off(GameEvent.EVENT_RIGHT_CUP_FULL, this.addWaitCupToOutArea, this);
  76. EventDispatcher.instance.off(GameEvent.EVENT_CHECK_GAME_OVER, this.checkGameOver, this);
  77. }
  78. private async generateInitialCups() {
  79. const instance = TakeGobletGlobalInstance.instance;
  80. const configs = instance.getInitialCupsConfig();
  81. const allCups: Node[] = [];
  82. for (const config of configs) {
  83. for (let i = 0; i < config.count; i++) {
  84. const prefab = await instance.loadAsyncCocktail(config.height);
  85. const cupNode = instantiate(prefab);
  86. const cup = cupNode.getComponent(CocktailCup)!;
  87. cup.reset();
  88. allCups.push(cupNode);
  89. }
  90. }
  91. const levelColors = LevelManager.instance.levelModel.levelColors;
  92. const rule = instance.cocktailCupRule();
  93. const [x, y] = rule;
  94. const colorPool = levelColors.slice(0, y);
  95. console.log(`colorPool:`, colorPool);
  96. // 为所有杯子分配颜色
  97. // 确保所有颜色至少出现一次
  98. const shuffledCups = [...allCups];
  99. const shuffledColors = [...levelColors];
  100. let currentIndex = 0;
  101. // 先为每个颜色分配一个杯子
  102. for (let i = 0; i < shuffledColors.length && i < shuffledCups.length; i++) {
  103. const cup = shuffledCups[i];
  104. const cupComp = cup.getComponent(CocktailCup)!;
  105. cupComp.cupColor = shuffledColors[i];
  106. currentIndex = i + 1;
  107. }
  108. // 为剩余杯子分配颜色,确保不超过x个相同颜色相邻
  109. for (let i = currentIndex; i < shuffledCups.length; i++) {
  110. const cup = shuffledCups[i];
  111. const cupComp = cup.getComponent(CocktailCup)!;
  112. // 获取前x-1个杯子的颜色
  113. const previousColors = new Set<WaterColors>();
  114. for (let j = Math.max(0, i - (x - 1)); j < i; j++) {
  115. const prevCup = shuffledCups[j].getComponent(CocktailCup)!;
  116. previousColors.add(prevCup.cupColor);
  117. }
  118. // 从可用颜色中筛选出合适的颜色
  119. const availableColors = shuffledColors.filter(color => !previousColors.has(color));
  120. // 如果没有合适的颜色,就从所有颜色中随机选择
  121. const colorPool = availableColors.length > 0 ? availableColors : shuffledColors;
  122. cupComp.cupColor = colorPool[Math.floor(Math.random() * colorPool.length)];
  123. }
  124. // 随机打乱杯子顺序
  125. for (let i = shuffledCups.length - 1; i > 0; i--) {
  126. const j = Math.floor(Math.random() * (i + 1));
  127. [shuffledCups[i], shuffledCups[j]] = [shuffledCups[j], shuffledCups[i]];
  128. }
  129. allCups.length = 0;
  130. allCups.push(...shuffledCups);
  131. // allCups.forEach(cup => {
  132. // const cupComp = cup.getComponent(CocktailCup)!;
  133. // // 从颜色池随机选择一个颜色
  134. // const randomColor = colorPool[Math.floor(Math.random() * colorPool.length)];
  135. // cupComp.cupColor = randomColor;
  136. // });
  137. console.log('allCups: ', allCups.length);
  138. // 分配初始位置
  139. allCups.slice(0, 2).forEach(cup => this.outArea.addCup(cup));
  140. allCups.slice(2).forEach(cup => this.waitArea.addCup(cup));
  141. // 在分配完调酒杯后添加
  142. this.generateOriginCups();
  143. // 初始化暂存区
  144. this.tempCups.children.forEach(tempCupNode => {
  145. const tempCup = tempCupNode.getComponent(TempCup)!;
  146. tempCup.reset(); // 重置所有暂存杯
  147. });
  148. EventDispatcher.instance.emit(GameEvent.EVENT_REFRESH_REMAIN_CUP);
  149. }
  150. // 当调酒区杯子被消除时调用
  151. public async handleCupsRemoved(count: number) {
  152. for (let i = 0; i < count; i++) {
  153. const cup = this.waitArea.takeCup();
  154. if (cup) {
  155. this.outArea.addCup(cup);
  156. }
  157. }
  158. }
  159. private async generateOriginCups() {
  160. if (this.isProcessing) {
  161. tgxUITips.show('Please wait for the \n current process to complete!');
  162. return;
  163. }
  164. const levelModel = LevelManager.instance.levelModel;
  165. const outCups = this.outArea.getCups() as Node[];
  166. const waitCups = this.waitArea.getCups() as Node[];
  167. const measuringcup_number = levelModel.levelConfig.measuringcup_number;
  168. const allCups = [...outCups, ...waitCups].slice(0, measuringcup_number);
  169. const colors = allCups.map(cup => {
  170. const comp = cup.getComponent(CocktailCup);
  171. return comp ? comp.cupColor : WaterColors.Blue;
  172. });
  173. this.originArea.children.forEach(originCupNode => {
  174. const originCup = originCupNode.getComponent(OriginCup)!;
  175. const waters = originCup.waters.children;
  176. for (let i = 0; i < originCup.cupHeight; i++) {
  177. const waterNode = waters[i];
  178. const water = waterNode.getComponent(Water);
  179. if (water) {
  180. water.initColor(colors[Math.floor(Math.random() * colors.length)]);
  181. waterNode.active = true;
  182. }
  183. }
  184. // 在生成初始原浆杯时记录位置
  185. const id = originCupNode.uuid; // 使用节点唯一ID
  186. this.originCupPositions.set(id, originCupNode.position.clone());
  187. // console.log('在生成初始原浆杯时记录id : ', id, originCupNode.position);
  188. });
  189. }
  190. private findTargetCupInOutArea(color: WaterColors): { node: Node, comp: CocktailCup } | null {
  191. const validCups = this.outArea.getCups()
  192. .map(node => ({
  193. node,
  194. comp: node.getComponent(CocktailCup)!
  195. }))
  196. .filter(({ comp }) =>
  197. comp &&
  198. comp.cupColor === color &&
  199. !comp.isFull
  200. );
  201. if (validCups.length === 0) return null;
  202. const sorted = validCups.sort((a, b) => (a.comp.remainingCapacity ?? 0) - (b.comp.remainingCapacity ?? 0));
  203. return sorted[0];
  204. }
  205. public async handlePourOriginCup(originCup: OriginCup) {
  206. if (this.isProcessing) {
  207. tgxUITips.show('Please wait for the \n current process to complete!');
  208. return;
  209. }
  210. this.isProcessing = true;
  211. try {
  212. // 如果子节点0是底层,需要反转顺序
  213. const watersNode: Node[] = [];
  214. for (let i = originCup.waters.children.length - 1; i >= 0; i--) {
  215. const waterNode = originCup.waters.children[i];
  216. if (waterNode.active) {
  217. watersNode.push(waterNode);
  218. }
  219. }
  220. let hasUnprocessed = false; // 标记是否有未处理的水层
  221. originCup.setMark(false);
  222. for (const waterNode of watersNode) {
  223. const color = waterNode.getComponent(Water)!.color;
  224. console.log(`当前处理的颜色:${WaterColorLog[color]}}`);
  225. let targetNode: Node | null = this.findTargetCupInOutArea(color)?.node || null;
  226. let targetIsTemp = false;
  227. // 调酒区未找到,查找暂存区
  228. if (!targetNode) {
  229. const tempCupsComp = this.tempCups.getComponent(TempCups);
  230. if (!tempCupsComp) {
  231. console.error('TempCups component not found!');
  232. continue;
  233. }
  234. const tempCup = tempCupsComp.findAvailableTempCup();
  235. if (tempCup) {
  236. targetNode = tempCup.node;
  237. targetIsTemp = true;
  238. }
  239. }
  240. if (!targetNode) {
  241. hasUnprocessed = true;
  242. console.log(`颜色${WaterColors[color]}未找到可用杯子`);
  243. continue; // 继续尝试处理后续颜色
  244. }
  245. await this.pourAnimation(
  246. originCup.node,
  247. targetNode,
  248. undefined,
  249. targetIsTemp
  250. );
  251. originCup.pourWater();
  252. // 更新目标杯
  253. if (targetIsTemp) {
  254. const tempCupComp = targetNode.getComponent(TempCup)!;
  255. await tempCupComp.fill(color);
  256. } else {
  257. const cocktailCup = targetNode.getComponent(CocktailCup)!;
  258. await cocktailCup.addLayer(); // 等待添加水层流程完成
  259. }
  260. originCup.hideCurrentWaterLayer();
  261. }
  262. // 处理完所有颜色后检查剩余水层
  263. if (!originCup.waters) return
  264. const remaining = originCup.waters.children.filter(n => n.active).length;
  265. if (hasUnprocessed || remaining > 0) {
  266. // console.log("游戏结束:仍有未处理的水层");
  267. this.loadResultPanel(false);
  268. } else {
  269. // 所有水层处理完毕,销毁原浆杯
  270. await originCup.destroyOriginCup();
  271. this.addWaitCupToOutArea();
  272. }
  273. } finally {
  274. this.isProcessing = false;
  275. }
  276. }
  277. //处理暂存区倒水到调酒区
  278. private async handlePourTempCupToOutArea() {
  279. if (this.isProcessing) return;
  280. this.isProcessing = true;
  281. try {
  282. const tempCupsComp = this.tempCups!.getComponent(TempCups)!;
  283. const filledCups = tempCupsComp.getFilledCups();
  284. for (const tempCup of filledCups) {
  285. const originalPos = tempCup.node.position.clone();
  286. const colors = tempCup.getColors();
  287. for (const color of colors) {
  288. const targetCup = this.findTargetCupInOutArea(color);
  289. if (!targetCup) {
  290. // console.log(`颜色${WaterColors[color]}未找到可用调酒杯`);
  291. continue;
  292. }
  293. await this.pourAnimation(
  294. tempCup.node,
  295. targetCup.node,
  296. originalPos,
  297. true
  298. );
  299. tempCup.pour();
  300. const cocktailCup = targetCup.comp;
  301. await cocktailCup.addLayer();
  302. await GameUtil.delay(0.2);
  303. // 返回到暂存区初始位置
  304. if (originalPos) {
  305. await new Promise(resolve => {
  306. tween(tempCup.node)
  307. .to(ANIMATION_DURATION, { position: originalPos })
  308. .call(() => {
  309. tempCup.reset();
  310. resolve(true);
  311. })
  312. .start();
  313. });
  314. }
  315. }
  316. }
  317. } finally {
  318. this.isProcessing = false;
  319. }
  320. }
  321. // 添加新杯子后触发暂存区倒水
  322. private async addWaitCupToOutArea() {
  323. const waitCups = this.waitArea.cups;
  324. const outCups = this.outArea.getCups();
  325. const needAddCount = outCups.length === 0 ? 2 : 1;
  326. const byX = outCups.length === 0 ? 220 : 110;
  327. const movingCups: Node[] = [];
  328. for (let i = 0; i < needAddCount; i++) {
  329. if (waitCups.length === 0) break;
  330. movingCups.push(waitCups.pop()!);
  331. }
  332. const newCups: Node[] = [];
  333. for (const cup of movingCups) {
  334. const comp = cup.getComponent(CocktailCup)!;
  335. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncCocktail(comp.cupHeight);
  336. const newCup = instantiate(prefab);
  337. const newComp = newCup.getComponent(CocktailCup)!;
  338. newComp.cupColor = comp.cupColor;
  339. newComp.reset();
  340. const targetX = outCups.length === 0 ?
  341. (newCups.length === 0 ? -160 : -50) :
  342. -50;
  343. newCup.setPosition(new Vec3(targetX, 0, 0));
  344. newCups.push(newCup);
  345. cup.destroy();
  346. }
  347. const outNodes = this.outArea.node.getChildByName('OutNodes')!;
  348. newCups.forEach(cup => cup.setParent(outNodes));
  349. // 执行统一平移
  350. if (this.waitArea.getCups().length > 0) {
  351. this.outArea.getCups().concat(this.waitArea.getCups()).forEach(cup => {
  352. tween(cup)
  353. .by(ANIMATION_DURATION, { position: new Vec3(byX, 0, 0) }, { easing: 'sineOut' })
  354. .start();
  355. });
  356. }
  357. await GameUtil.delay(0.2);
  358. // 在添加完成后处理暂存区倒水
  359. await this.handlePourTempCupToOutArea();
  360. this.checkGameOver();
  361. }
  362. //游戏检测胜利或失败
  363. checkGameOver() {
  364. if (this.isProcessing) return;
  365. // 胜利条件检测:当两个区域都没有杯子时触发胜利
  366. if (this.outArea.getCups().length === 0 && this.waitArea.cups.length === 0) {
  367. this.loadResultPanel(true);
  368. }
  369. //失败检查:制作区大于5个杯子就失败
  370. console.log('制作区水杯数量:', this.outArea.getCups().length);
  371. if (this.outArea.getCups().length > 5) {
  372. this.loadResultPanel(false);
  373. }
  374. }
  375. //加载结算面板
  376. loadResultPanel(win: boolean) {
  377. this.isProcessing = true;
  378. if (!win) {
  379. const waitLength = this.waitArea!.getCups().length;
  380. const outLength = this.outArea!.getCups().length;
  381. let remain = waitLength + outLength;
  382. console.log(`waitLength:${waitLength} + outLenght:${outLength} = remain:${remain}`);
  383. LevelManager.instance.levelModel.remainCupCount = remain;
  384. LevelManager.instance.levelModel.isWin = false;
  385. tgxUIMgr.inst.showUI(UI_BattleResult);
  386. } else {
  387. LevelManager.instance.levelModel.isWin = true;
  388. tgxUIMgr.inst.showUI(UI_BattleResult);
  389. }
  390. }
  391. /** 倒水移动动画
  392. * @param origin 原杯子
  393. * @param target 目标杯子
  394. * @param originalPos 原始位置
  395. * @param isTempCup 是否是暂存区杯子
  396. */
  397. private async pourAnimation(
  398. origin: Node,
  399. target: Node,
  400. originalPos?: Vec3,
  401. isTempCup: boolean = false
  402. ) {
  403. const targetWorldPos = target.getWorldPosition().clone();
  404. const tempRegex = /TempCup/.test(origin.name);
  405. let targetPosY: number = 135;
  406. if (origin.getComponent(OriginCup)) {
  407. const targetCup = origin.getComponent(OriginCup)!;
  408. if (targetCup.cupHeight == CupHeight.Two) {
  409. targetPosY = 165;
  410. } else if (targetCup.cupHeight == CupHeight.Four) {
  411. targetPosY = 105;
  412. }
  413. }
  414. // 调整偏移量
  415. targetWorldPos.x -= !tempRegex ? 55 : 40;
  416. targetWorldPos.y += !tempRegex ? targetPosY : 205;
  417. // 移动动画到目标位置
  418. await new Promise<void>(resolve => {
  419. tween(origin)
  420. .to(ANIMATION_DURATION, { worldPosition: targetWorldPos })
  421. .call(resolve)
  422. .start();
  423. });
  424. }
  425. private async spawnNewOriginCup(targetPos: Vec3) {
  426. const levelModel = LevelManager.instance.levelModel;
  427. const measuringcup_number = levelModel.levelConfig.measuringcup_number;//获取调酒和等待区前面数量
  428. const colors = this.getAvailableColors(measuringcup_number);
  429. if (colors.length <= 0) return;
  430. // 创建新原浆杯
  431. const height = TakeGobletGlobalInstance.instance.generateOriginCupHeight();
  432. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncOriginCup(height);
  433. const newCup = instantiate(prefab);
  434. this.originArea.addChild(newCup);
  435. await newCup.getComponent(OriginCup)?.spawnNewOriginCup(height, targetPos, colors);
  436. }
  437. // 获取可用颜色
  438. private getAvailableColors(count: number): WaterColors[] {
  439. const outCups = this.outArea.getCups();
  440. const waitCups = this.waitArea.getCups();
  441. const allCups = [...outCups, ...waitCups].slice(0, count);
  442. return allCups.map(cup => {
  443. const comp = cup.getComponent(CocktailCup);
  444. return comp ? comp.cupColor : WaterColors.Blue;
  445. });
  446. }
  447. private handleCupDestroyed(destroyedCup: Node) {
  448. // 从outArea移除被销毁的杯子
  449. this.outArea.removeCup(destroyedCup);
  450. }
  451. }