LevelAction.ts 15 KB

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