LevelAction.ts 18 KB

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