LevelAction.ts 19 KB

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