LevelAction.ts 21 KB

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