LevelAction.ts 17 KB

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