LevelAction.ts 16 KB

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