LevelAction.ts 17 KB

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