LevelAction.ts 19 KB

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