LevelAction.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. targetIsTemp
  163. );
  164. // 更新目标杯
  165. if (targetIsTemp) {
  166. const tempCupComp = targetNode.getComponent(TempCup)!;
  167. tempCupComp.fill(color);
  168. } else {
  169. const cocktailCup = targetNode.getComponent(CocktailCup)!;
  170. await cocktailCup.addLayer(color); // 等待添加水层流程完成
  171. }
  172. this.hideCurrentWaterLayer(originCup);
  173. }
  174. // 处理完所有颜色后检查剩余水层
  175. const remaining = originCup.waters.children.filter(n => n.active).length;
  176. if (hasUnprocessed || remaining > 0) {
  177. console.log("游戏结束:仍有未处理的水层");
  178. // 触发游戏结束逻辑
  179. } else {
  180. // 所有水层处理完毕,销毁原浆杯
  181. originCup.destroyOriginCup();
  182. this.addWaitCupToOutArea();
  183. }
  184. }
  185. // 添加等待区杯子到调酒区
  186. private async addWaitCupToOutArea() {
  187. // 原有添加逻辑保持不变
  188. const waitCups = this.waitArea.cups;
  189. const outCups = this.outArea.getCups();
  190. const needAddCount = outCups.length === 0 ? 2 : 1;
  191. const movingCups: Node[] = [];
  192. for (let i = 0; i < needAddCount; i++) {
  193. if (waitCups.length === 0) break;
  194. movingCups.push(waitCups.pop()!);
  195. }
  196. const newCups: Node[] = [];
  197. for (const cup of movingCups) {
  198. const comp = cup.getComponent(CocktailCup)!;
  199. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncCocktail(comp.cupHeight);
  200. const newCup = instantiate(prefab);
  201. const newComp = newCup.getComponent(CocktailCup)!;
  202. newComp.cupColor = comp.cupColor;
  203. newComp.reset();
  204. const targetX = outCups.length === 0 ?
  205. (newCups.length === 0 ? -125 : -45) :
  206. -45;
  207. newCup.setPosition(new Vec3(targetX, 0, 0));
  208. newCups.push(newCup);
  209. cup.destroy();
  210. }
  211. const outNodes = this.outArea.node.getChildByName('OutNodes')!;
  212. newCups.forEach(cup => cup.setParent(outNodes));
  213. // 执行统一平移
  214. this.outArea.getCups().concat(this.waitArea.getCups()).forEach(cup => {
  215. tween(cup)
  216. .by(0.3, { position: new Vec3(80, 0, 0) }, { easing: 'sineOut' })
  217. .start();
  218. });
  219. }
  220. private async pourAnimation(
  221. origin: Node,
  222. target: Node,
  223. color: WaterColors,
  224. isTempCup: boolean = false
  225. ) {
  226. // 使用正确的坐标转换
  227. const originParent = origin.parent!;
  228. const targetWorldPos = target.worldPosition;
  229. const localPos = originParent.getComponent(UITransform)!.convertToNodeSpaceAR(targetWorldPos);
  230. // 调整Y轴偏移量
  231. if (isTempCup) {
  232. localPos.y += 80; // 暂存杯偏移
  233. } else {
  234. localPos.y += 150; // 调酒杯偏移
  235. }
  236. // 只做单程移动,保留在目标位置
  237. await new Promise<void>(resolve => {
  238. tween(origin)
  239. .to(0.5, { position: localPos }) // 延长动画时间到0.5秒
  240. .call(() => resolve())
  241. .start();
  242. });
  243. }
  244. // 新增辅助方法
  245. private hideCurrentWaterLayer(originCup: OriginCup) {
  246. const activeWaters = originCup.waters.children.filter(n => n.active);
  247. if (activeWaters.length > 0) {
  248. const topIndex = activeWaters.length - 1;
  249. activeWaters[topIndex].active = false;
  250. }
  251. }
  252. private async spawnNewOriginCup(targetPos: Vec3) {
  253. // 创建新原浆杯
  254. const height = TakeGobletGlobalInstance.instance.generateOriginCupHeight();
  255. const prefab = await TakeGobletGlobalInstance.instance.loadAsyncOriginCup(height);
  256. const newCup = instantiate(prefab);
  257. // 设置初始位置(屏幕左侧)
  258. const uiTransform = this.node.getComponent(UITransform)!;
  259. newCup.setPosition(-uiTransform.width / 2, 0, 0);
  260. this.goblets.addChild(newCup);
  261. // 记录新杯子的初始位置
  262. this.originCupPositions.set(newCup.uuid, targetPos);
  263. // 移动动画到原位置
  264. tween(newCup)
  265. .to(0.5, { position: targetPos })
  266. .start();
  267. // DOTO 获取颜色配置
  268. const colors = this.getAvailableColors(5); // 获取前5个颜色
  269. this.setupOriginCupColors(newCup, colors);
  270. }
  271. // 获取可用颜色
  272. private getAvailableColors(count: number): WaterColors[] {
  273. const outCups = this.outArea.getCups();
  274. const waitCups = this.waitArea.getCups();
  275. const allCups = [...outCups, ...waitCups].slice(0, count);
  276. return allCups.map(cup => {
  277. const comp = cup.getComponent(CocktailCup);
  278. return comp ? comp.cupColor : WaterColors.Blue;
  279. });
  280. }
  281. // 设置原浆杯颜色
  282. private setupOriginCupColors(cupNode: Node, colors: WaterColors[]) {
  283. const originCup = cupNode.getComponent(OriginCup)!;
  284. const waters = originCup.waters.children;
  285. // 暂时写死5层水
  286. const waterCount = 5;
  287. for (let i = 0; i < waterCount; i++) {
  288. const waterNode = waters[i];
  289. if (!waterNode) continue;
  290. const water = waterNode.getComponent(Water)!;
  291. water.color = colors[Math.floor(Math.random() * colors.length)];
  292. waterNode.active = true;
  293. }
  294. }
  295. private handleCupDestroyed(destroyedCup: Node) {
  296. // 从outArea移除被销毁的杯子
  297. this.outArea.removeCup(destroyedCup);
  298. }
  299. }