LevelAction.ts 20 KB

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