LevelAction.ts 16 KB

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