LevelAction.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 } 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. const { ccclass, property } = _decorator;
  17. @ccclass('LevelAction')
  18. export class LevelAction extends Component {
  19. @property(OutArea)
  20. outArea: OutArea = null!; // 直接引用OutArea组件
  21. @property(WaitArea)
  22. waitArea: WaitArea = null!; // 直接引用WaitArea组件
  23. @property(Node)
  24. tempCups: Node = null!; //临时杯
  25. @property(Node)
  26. originArea: Node = null!; //原浆区
  27. private originCupPositions = new Map<string, Vec3>(); // 改用唯一ID记录
  28. private isProcessing = false; // 添加状态锁
  29. static instance: LevelAction; // 添加静态实例
  30. onLoad() {
  31. LevelAction.instance = this;
  32. }
  33. start() {
  34. this.generateInitialCups();
  35. this.registerListener();
  36. }
  37. onDestroy() {
  38. this.unregisterListener();
  39. }
  40. registerListener() {
  41. EventDispatcher.instance.on(GameEvent.EVENT_REFRESH_COLOR, this.generateOriginCups, this);
  42. EventDispatcher.instance.on(GameEvent.EVENT_CLICK_ORIGIN_CUP, this.handlePourOriginCup, this);
  43. EventDispatcher.instance.on(GameEvent.EVENT_ORIGIN_CUP_DESTROYED, (uuid: string) => {
  44. if (!this.originCupPositions) return
  45. const targetPos = this.originCupPositions.get(uuid);
  46. if (targetPos) {
  47. this.spawnNewOriginCup(targetPos);
  48. }
  49. }, this);
  50. EventDispatcher.instance.on(GameEvent.EVENT_COCKTAIL_CUP_DESTROYED, this.handleCupDestroyed, this);
  51. }
  52. unregisterListener() {
  53. EventDispatcher.instance.off(GameEvent.EVENT_REFRESH_COLOR, this.generateOriginCups, this);
  54. EventDispatcher.instance.off(GameEvent.EVENT_CLICK_ORIGIN_CUP, this.handlePourOriginCup, this);
  55. EventDispatcher.instance.off(GameEvent.EVENT_ORIGIN_CUP_DESTROYED, this.spawnNewOriginCup, this);
  56. EventDispatcher.instance.off(GameEvent.EVENT_COCKTAIL_CUP_DESTROYED, this.handleCupDestroyed, this);
  57. }
  58. private async generateInitialCups() {
  59. const instance = TakeGobletGlobalInstance.instance;
  60. const configs = instance.getInitialCupsConfig();
  61. const allCups: Node[] = [];
  62. for (const config of configs) {
  63. for (let i = 0; i < config.count; i++) {
  64. const prefab = await instance.loadAsyncCocktail(config.height);
  65. const cupNode = instantiate(prefab);
  66. const cup = cupNode.getComponent(CocktailCup)!;
  67. cup.reset();
  68. allCups.push(cupNode);
  69. }
  70. }
  71. const levelColors = LevelManager.instance.levelModel.levelColors;
  72. const rule = instance.cocktailCupRule();
  73. const [x, y] = rule;
  74. const colorPool = levelColors.slice(0, y);
  75. // 为所有杯子分配颜色,并控制颜色种类不超过y种
  76. allCups.forEach(cup => {
  77. const cupComp = cup.getComponent(CocktailCup)!;
  78. // 从颜色池随机选择一个颜色
  79. const randomColor = colorPool[Math.floor(Math.random() * colorPool.length)];
  80. cupComp.cupColor = randomColor;
  81. });
  82. console.log('allCups: ', allCups.length);
  83. // 分配初始位置
  84. allCups.slice(0, 2).forEach(cup => this.outArea.addCup(cup));
  85. allCups.slice(2).forEach(cup => this.waitArea.addCup(cup));
  86. // 在分配完调酒杯后添加
  87. this.generateOriginCups();
  88. // 初始化暂存区
  89. this.tempCups.children.forEach(tempCupNode => {
  90. const tempCup = tempCupNode.getComponent(TempCup)!;
  91. tempCup.reset(); // 重置所有暂存杯
  92. });
  93. }
  94. // 当调酒区杯子被消除时调用
  95. public async handleCupsRemoved(count: number) {
  96. for (let i = 0; i < count; i++) {
  97. const cup = this.waitArea.takeCup();
  98. if (cup) {
  99. this.outArea.addCup(cup);
  100. }
  101. }
  102. }
  103. private async generateOriginCups() {
  104. if (this.isProcessing) {
  105. tgxUITips.show('我知道你很急,但你先别急!');
  106. return;
  107. }
  108. const levelModel = LevelManager.instance.levelModel;
  109. const outCups = this.outArea.getCups() as Node[];
  110. const waitCups = this.waitArea.getCups() as Node[];
  111. const measuringcup_number = levelModel.levelConfig.measuringcup_number;
  112. const allCups = [...outCups, ...waitCups].slice(0, measuringcup_number);
  113. const colors = allCups.map(cup => {
  114. const comp = cup.getComponent(CocktailCup);
  115. return comp ? comp.cupColor : WaterColors.Blue;
  116. });
  117. this.originArea.children.forEach(originCupNode => {
  118. const originCup = originCupNode.getComponent(OriginCup)!;
  119. const waters = originCup.waters.children;
  120. for (let i = 0; i < originCup.cupHeight; i++) {
  121. const waterNode = waters[i];
  122. const water = waterNode.getComponent(Water);
  123. if (water) {
  124. water.initColor(colors[Math.floor(Math.random() * colors.length)]);
  125. waterNode.active = true;
  126. }
  127. }
  128. // 在生成初始原浆杯时记录位置
  129. const id = originCupNode.uuid; // 使用节点唯一ID
  130. this.originCupPositions.set(id, originCupNode.position.clone());
  131. // console.log('在生成初始原浆杯时记录id : ', id, originCupNode.position);
  132. });
  133. }
  134. private findTargetCupInOutArea(color: WaterColors): { node: Node, comp: CocktailCup } | null {
  135. const validCups = this.outArea.getCups()
  136. .map(node => ({
  137. node,
  138. comp: node.getComponent(CocktailCup)!
  139. }))
  140. .filter(({ comp }) =>
  141. comp &&
  142. comp.cupColor === color &&
  143. !comp.isFull
  144. );
  145. if (validCups.length === 0) return null;
  146. const sorted = validCups.sort((a, b) => (a.comp.remainingCapacity ?? 0) - (b.comp.remainingCapacity ?? 0));
  147. return sorted[0];
  148. }
  149. public async handlePourOriginCup(originCup: OriginCup) {
  150. if (this.isProcessing) {
  151. tgxUITips.show('我知道你很急,但你先别急!');
  152. return;
  153. }
  154. this.isProcessing = true;
  155. try {
  156. // 如果子节点0是底层,需要反转顺序
  157. const watersNode: Node[] = [];
  158. for (let i = originCup.waters.children.length - 1; i >= 0; i--) {
  159. const waterNode = originCup.waters.children[i];
  160. if (waterNode.active) {
  161. watersNode.push(waterNode);
  162. }
  163. }
  164. let hasUnprocessed = false; // 标记是否有未处理的水层
  165. for (const waterNode of watersNode) {
  166. const color = waterNode.getComponent(Water)!.color;
  167. let targetNode: Node | null = this.findTargetCupInOutArea(color)?.node || null;
  168. let targetIsTemp = false;
  169. if (waterNode.getComponent(Water).markActive) {
  170. waterNode.getComponent(Water)!.setMark(false);
  171. }
  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. // 更新目标杯
  198. if (targetIsTemp) {
  199. const tempCupComp = targetNode.getComponent(TempCup)!;
  200. tempCupComp.fill(color);
  201. } else {
  202. const cocktailCup = targetNode.getComponent(CocktailCup)!;
  203. await cocktailCup.addLayer(color); // 等待添加水层流程完成
  204. }
  205. this.hideCurrentWaterLayer(originCup);
  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.y += 80; // 暂存杯偏移
  321. } else {
  322. localPos.y += 150; // 调酒杯偏移
  323. }
  324. // 移动动画到目标位置
  325. await new Promise<void>(resolve => {
  326. tween(origin)
  327. .to(0.5, { position: localPos })
  328. .call(resolve)
  329. .start();
  330. });
  331. // 返回到暂存区初始位置
  332. if (isTempCup && originalPos) {
  333. await new Promise(resolve => {
  334. tween(origin)
  335. .to(0.3, { position: originalPos })
  336. .call(resolve)
  337. .start();
  338. });
  339. }
  340. }
  341. //隐藏原浆杯当前水层
  342. private hideCurrentWaterLayer(originCup: OriginCup) {
  343. const activeWaters = originCup.waters.children.filter(n => n.active);
  344. if (activeWaters.length >= 0) {
  345. const topIndex = activeWaters.length - 1;
  346. activeWaters[topIndex].active = false;
  347. }
  348. }
  349. private async spawnNewOriginCup(targetPos: Vec3) {
  350. const levelModel = LevelManager.instance.levelModel;
  351. const measuringcup_number = levelModel.levelConfig.measuringcup_number;//获取调酒和等待区前面数量
  352. const colors = this.getAvailableColors(measuringcup_number);
  353. if (colors.length <= 0) return;
  354. // 创建新原浆杯
  355. const height = TakeGobletGlobalInstance.instance.generateOriginCupHeight();
  356. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncOriginCup(height);
  357. const newCup = instantiate(prefab);
  358. // 设置初始位置(屏幕左侧)
  359. const uiTransform = this.node.getComponent(UITransform)!;
  360. newCup.setPosition(-uiTransform.width / 2, 0, 0);
  361. newCup.getComponent(OriginCup)!.cupHeight = height;
  362. this.originArea.addChild(newCup);
  363. this.setupOriginCupColors(newCup, colors);
  364. // 记录新杯子的初始位置
  365. this.originCupPositions.set(newCup.uuid, targetPos);
  366. // 移动动画到原位置
  367. tween(newCup)
  368. .to(0.5, { position: targetPos })
  369. .start();
  370. const markCount = this.originArea.getComponent(OriginArea)?.getTotalMarkCount();
  371. LevelManager.instance.levelModel.createQuestionCount = markCount;
  372. }
  373. // 获取可用颜色
  374. private getAvailableColors(count: number): WaterColors[] {
  375. const outCups = this.outArea.getCups();
  376. const waitCups = this.waitArea.getCups();
  377. const allCups = [...outCups, ...waitCups].slice(0, count);
  378. return allCups.map(cup => {
  379. const comp = cup.getComponent(CocktailCup);
  380. return comp ? comp.cupColor : WaterColors.Blue;
  381. });
  382. }
  383. // 设置原浆杯颜色
  384. private setupOriginCupColors(cupNode: Node, colors: WaterColors[]) {
  385. const originCup = cupNode.getComponent(OriginCup)!;
  386. const waters = originCup.waters.children;
  387. // console.log(`新创建原浆杯,高度: ${originCup.cupHeight}`);
  388. const markCount = this.originArea.getComponent(OriginArea)?.getTotalMarkCount();
  389. const waterCount = originCup.cupHeight;
  390. for (let i = 0; i < waterCount; i++) {
  391. const waterNode = waters[i];
  392. if (!waterNode) continue;
  393. const water = waterNode.getComponent(Water)!;
  394. const mark = TakeGobletGlobalInstance.instance.refreshQuestionWater(markCount);
  395. water.color = colors[Math.floor(Math.random() * colors.length)];
  396. waterNode.active = true;
  397. // console.log('mark: ', mark);
  398. water.setMark(mark);
  399. }
  400. }
  401. private handleCupDestroyed(destroyedCup: Node) {
  402. // 从outArea移除被销毁的杯子
  403. this.outArea.removeCup(destroyedCup);
  404. }
  405. }