LevelAction.ts 16 KB

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