SlotGame.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. // =============================================================
  2. // SlotGame.ts —— 《果冻消消乐 · Jelly Pop》消除式老虎机(可玩原型)
  3. // by anim_studio
  4. // v4:先预加载全部 UI 美术,再搭界面——HUD 胶囊用 hud_pill、
  5. // 圆按钮用 btn_round、SPIN 用 btn_spin;隐藏预览性能面板;
  6. // 4×5 大符号 + 每格圆角卡片。
  7. // =============================================================
  8. import {
  9. _decorator, Component, Node, sp, resources, JsonAsset, SpriteFrame, Sprite,
  10. ParticleSystem2D, UITransform, Label, Graphics, Button, Color, Vec3,
  11. view, EventTouch, tween, UIOpacity,
  12. } from 'cc';
  13. import * as cc from 'cc';
  14. import { applyParticleConfig } from './ParticleConfig';
  15. const { ccclass } = _decorator;
  16. const SYMBOLS = __SYMBOLS__;
  17. const GENERATED_CONFIG = __GAME_CONFIG__;
  18. // ============ 画面结构(先定区域,再往里填元素)============
  19. // 所有数值都是相对屏幕的比例;cy = 区域中心相对屏幕中心的 Y(向上为正)。
  20. const LAYOUT = (GENERATED_CONFIG.layout || {
  21. logo: { cy: 0.41, maxW: 0.82, maxH: 0.15 }, // 顶部 Logo
  22. reel: { cy: 0.02, h: 0.60, aspect: 0.652, // 卷轴框(按新图:霓虹边+白板)
  23. holeW: 0.86, holeH: 0.92, cols: 4, rows: 6 }, // 白板内孔 + 网格行列
  24. hud: { cy: -0.33, pillH: 0.40 }, // 三个 HUD 胶囊(按图比例)
  25. controls: { cy: -0.405, spinR: 0.13, smallR: 0.075, // 控制按钮(按宽度定标、做大)
  26. xMinus: 0.24, xTurbo: 0.40 },
  27. });
  28. const ECONOMY = GENERATED_CONFIG.economy || { startingBalance: 5000, defaultBet: 50 };
  29. const WIN_RULES = GENERATED_CONFIG.winRules || { minMatch: 4 };
  30. const FEATURE_RULES = GENERATED_CONFIG.features || {};
  31. const FEEDBACK_CONFIG = GENERATED_CONFIG.feedback || {};
  32. const PAYTABLE = GENERATED_CONFIG.paytable || {};
  33. const SYMBOL_RULES = GENERATED_CONFIG.symbols || [];
  34. const MATH_MODEL = GENERATED_CONFIG.mathModel || {};
  35. const PAYOUT_SCALE = MATH_MODEL.payoutScale ?? 1;
  36. const REEL_STRIPS = MATH_MODEL.reelStrips || [];
  37. // ============ 文字样式表(统一定义,按角色取用)============
  38. // size<=1 表示相对所在容器高度的比例;否则按像素。ow=描边宽。
  39. const STYLE = {
  40. hudTitle: { size: 0.30, color: [205, 222, 255], bold: false, outline: [40, 28, 78], ow: 0, letter: 0.04 },
  41. hudValue: { size: 0.52, color: [255, 255, 255], bold: true, outline: [54, 30, 96], ow: 3 },
  42. mult: { size: 66, color: [255, 214, 70], bold: true, outline: [188, 70, 24], ow: 6 },
  43. floatWin: { size: 46, color: [255, 244, 130], bold: true, outline: [196, 92, 24], ow: 5 },
  44. bigWin: { size: 0.16, color: [255, 224, 70], bold: true, outline: [180, 50, 16], ow: 9 }, // 报幕(相对屏宽)
  45. };
  46. // ============ 每个符号的"按内容定标"参数(s=缩放/格, oyf=居中下移/格)============
  47. // 由素材实际内容包围盒算出,保证果冻填满格子、垂直居中——这就是"按规格画/摆"。
  48. const SYMFIT: Record<string, {s: number; oyf: number}> = __SYMBOL_FIT__;
  49. const SYMFIT_DEFAULT = __SYMBOL_FIT_DEFAULT__;
  50. // ============ 交互/动效反馈(统一定义)============
  51. const FEEDBACK = {
  52. btnPress: 0.86,
  53. btnBack: 0.16,
  54. idleBob: 0.016,
  55. dropFrom: 1.05,
  56. dropTime: FEEDBACK_CONFIG.dropTimeSec ?? 0.30,
  57. clearPop: FEEDBACK_CONFIG.clearPopScale ?? 1.30,
  58. spinDuration: FEEDBACK_CONFIG.spinDurationSec ?? 0.45,
  59. bigWinThresholdBet: FEEDBACK_CONFIG.bigWinThresholdBet ?? 25,
  60. screenShake: FEEDBACK_CONFIG.screenShake ?? false,
  61. };
  62. const COLS = LAYOUT.reel.cols, ROWS = LAYOUT.reel.rows;
  63. const MIN_MATCH = WIN_RULES.minMatch ?? 4;
  64. const CASCADE_RULES = FEATURE_RULES.cascades || {};
  65. const MAX_CASCADE = CASCADE_RULES.maxCascades ?? 6;
  66. const CASCADE_MULT_STEP = CASCADE_RULES.multiplierStep ?? 1;
  67. const CASCADE_MULT_MAX = CASCADE_RULES.maxMultiplier ?? 6;
  68. const START_BALANCE = ECONOMY.startingBalance ?? 5000;
  69. const DEFAULT_BET = ECONOMY.defaultBet ?? 50;
  70. const SCATTER_RULES = FEATURE_RULES.scatterFreeSpins || {};
  71. const HOLD_RULES = FEATURE_RULES.holdAndWin || {};
  72. const IS_CLUSTER = WIN_RULES.evaluation === 'cluster_count';
  73. const FREE_SPIN_TRIGGER = SCATTER_RULES.triggerCount ?? 3;
  74. const FREE_SPIN_AWARD = SCATTER_RULES.awardSpins ?? 8;
  75. const HOLD_TRIGGER = HOLD_RULES.triggerCount ?? 6;
  76. const HOLD_RESPINS = HOLD_RULES.respins ?? 3;
  77. const SYMBOL_ROLE: Record<string, string> = {};
  78. SYMBOL_RULES.forEach((s: any) => { SYMBOL_ROLE[s.id] = s.role; });
  79. @ccclass('SlotGame')
  80. export class SlotGame extends Component {
  81. private dataMap: Record<string, sp.SkeletonData> = {};
  82. private art: Record<string, SpriteFrame | null> = {};
  83. private cells: sp.Skeleton[][] = [];
  84. private ids: string[][] = [];
  85. private cell = 90;
  86. private gridX0 = 0;
  87. private gridY0 = 0;
  88. private spinning = false;
  89. private balance = START_BALANCE;
  90. private displayBalance = START_BALANCE;
  91. private bet = DEFAULT_BET;
  92. private multiplier = 1;
  93. private roundWin = 0;
  94. private cascade = 0;
  95. private freeSpins = 0;
  96. private holdActive = false;
  97. private holdRespinsLeft = 0;
  98. private holdHeld: boolean[][] = [];
  99. private holdWinTotal = 0;
  100. private balanceLabel!: Label;
  101. private betLabel!: Label;
  102. private winLabel!: Label;
  103. private multLabel!: Label;
  104. private spinBtn!: Node;
  105. private particleTex: SpriteFrame | null = null;
  106. private frameCY = 0; private frameW = 0; private frameH = 0;
  107. private W = 0; private H = 0;
  108. private symBaseY: number[][] = [];
  109. private t = 0;
  110. private turbo = false; private auto = false;
  111. private turboBtn!: Node; private autoBtn!: Node;
  112. onLoad() {
  113. try { (cc as any).profiler?.hideStats?.(); } catch (e) {}
  114. this.node.setPosition(0, 0, 0);
  115. const ut = this.node.getComponent(UITransform) || this.node.addComponent(UITransform);
  116. ut.setAnchorPoint(0.5, 0.5);
  117. const s = view.getVisibleSize();
  118. this.W = s.width; this.H = s.height;
  119. ut.setContentSize(s.width, s.height);
  120. this.computeLayout(s.width, s.height);
  121. this.buildBackground(s.width, s.height); // 渐变兜底
  122. resources.load('vfx/particle/spriteFrame', SpriteFrame, (_e, sf) => { if (sf) this.particleTex = sf; });
  123. const artIds = ['bg_main', 'reel_frame', 'logo', 'hud_pill', 'btn_round', 'btn_spin', 'btn_plus', 'btn_minus', 'btn_turbo', 'btn_auto', 'coin'];
  124. let toLoad = artIds.length;
  125. artIds.forEach((id) => {
  126. resources.load(`ui_art/${id}/spriteFrame`, SpriteFrame, (err, sf) => {
  127. this.art[id] = err ? null : sf;
  128. if (--toLoad === 0) this.afterArt();
  129. });
  130. });
  131. }
  132. private afterArt() {
  133. const W = this.W, H = this.H;
  134. this.buildArt(W, H);
  135. this.buildHud(W, H);
  136. this.buildControls(W, H);
  137. let left = SYMBOLS.length;
  138. SYMBOLS.forEach((id) => {
  139. resources.load(`characters/${id}`, sp.SkeletonData, (err, data) => {
  140. if (!err) this.dataMap[id] = data;
  141. if (--left === 0) this.buildGrid();
  142. });
  143. });
  144. }
  145. private computeLayout(W: number, H: number) {
  146. const R = LAYOUT.reel;
  147. let fh = H * R.h;
  148. let fw = fh * R.aspect;
  149. if (fw > W * 0.96) { fw = W * 0.96; fh = fw / R.aspect; }
  150. this.frameW = fw; this.frameH = fh;
  151. this.frameCY = H * R.cy;
  152. const innerW = fw * R.holeW, innerH = fh * R.holeH;
  153. this.cell = Math.min(innerW / COLS, innerH / ROWS);
  154. this.gridX0 = -((COLS - 1) * this.cell) / 2;
  155. this.gridY0 = this.frameCY + ((ROWS - 1) * this.cell) / 2;
  156. }
  157. private cellPos(c: number, r: number): [number, number] {
  158. return [this.gridX0 + c * this.cell, this.gridY0 - r * this.cell];
  159. }
  160. private buildBackground(W: number, H: number) {
  161. const n = new Node('bg'); n.parent = this.node; n.setSiblingIndex(0);
  162. const g = n.addComponent(Graphics);
  163. g.fillColor = new Color(120, 200, 255, 255); g.rect(-W / 2, 0, W, H / 2); g.fill();
  164. g.fillColor = new Color(255, 150, 175, 255); g.rect(-W / 2, -H / 2, W, H / 2); g.fill();
  165. }
  166. // ---- 背景大图 / 卷轴框 / Logo(有图用图,没图兜底)----
  167. private buildArt(W: number, H: number) {
  168. if (this.art['bg_main']) {
  169. const [w, h] = this.coverSize(this.art['bg_main']!, W, H);
  170. this.spriteNode(this.art['bg_main']!, w, h, 0, 0, 1);
  171. }
  172. if (this.art['reel_frame']) {
  173. this.spriteNode(this.art['reel_frame']!, this.frameW, this.frameH, 0, this.frameCY, 3);
  174. } else {
  175. const n = new Node('frame'); n.parent = this.node; n.setPosition(0, this.frameCY, 0); n.setSiblingIndex(3);
  176. const g = n.addComponent(Graphics);
  177. g.lineWidth = 10; g.strokeColor = new Color(120, 180, 255, 255);
  178. this.roundRect(g, -this.frameW / 2, -this.frameH / 2, this.frameW, this.frameH, 26); g.stroke();
  179. }
  180. const logoCy = H * LAYOUT.logo.cy;
  181. if (this.art['logo']) {
  182. const [w, h] = this.fitSize(this.art['logo']!, W * LAYOUT.logo.maxW, H * LAYOUT.logo.maxH);
  183. this.spriteNode(this.art['logo']!, w, h, 0, logoCy, 21);
  184. } else {
  185. const t = new Node('logo'); t.parent = this.node; t.setPosition(0, logoCy, 0); t.setSiblingIndex(21);
  186. const lab = t.addComponent(Label); lab.string = '🍬 JELLY POP'; lab.fontSize = 42; lab.color = new Color(255, 90, 70, 255);
  187. }
  188. }
  189. // ---------------- HUD:用 hud_pill 美术 ----------------
  190. private buildHud(W: number, H: number) {
  191. const y = H * LAYOUT.hud.cy;
  192. const pw = (W - 36) / 3 - 8, gap = 8;
  193. const ps = this.art['hud_pill'];
  194. const ph = ps ? pw * (ps.rect.height / ps.rect.width) : pw * LAYOUT.hud.pillH; // 按图比例,不拉伸
  195. this.balanceLabel = this.makePill(-(pw + gap), y, pw, ph, '余额', `${START_BALANCE}`);
  196. this.betLabel = this.makePill(0, y, pw, ph, '下注', `${this.bet}`);
  197. this.winLabel = this.makePill(pw + gap, y, pw, ph, '本局赢', '0');
  198. const m = new Node('mult'); m.parent = this.node; m.setPosition(0, this.frameCY, 0); m.setSiblingIndex(25);
  199. this.multLabel = m.addComponent(Label); this.applyStyle(this.multLabel, STYLE.mult, 0); this.multLabel.string = '';
  200. }
  201. private makePill(x: number, y: number, w: number, h: number, title: string, val: string): Label {
  202. const n = new Node('pill'); n.parent = this.node; n.setPosition(x, y, 0); n.setSiblingIndex(16);
  203. if (this.art['hud_pill']) {
  204. const s = n.addComponent(Sprite); s.sizeMode = Sprite.SizeMode.CUSTOM; s.spriteFrame = this.art['hud_pill']!;
  205. } else {
  206. const g = n.addComponent(Graphics); g.fillColor = new Color(70, 50, 120, 235);
  207. this.roundRect(g, -w / 2, -h / 2, w, h, h / 2); g.fill();
  208. }
  209. const ut = n.getComponent(UITransform) || n.addComponent(UITransform); ut.setContentSize(w, h);
  210. // 标题(小字,靠左)
  211. const tl = new Node('t'); tl.parent = n; tl.setPosition(-w * 0.30, 0, 0);
  212. const tlab = tl.addComponent(Label); tlab.string = title; this.applyStyle(tlab, STYLE.hudTitle, h);
  213. // 数值(大字带描边,靠右)
  214. const vl = new Node('v'); vl.parent = n; vl.setPosition(w * 0.12, 0, 0);
  215. const lab = vl.addComponent(Label); lab.string = val; this.applyStyle(lab, STYLE.hudValue, h);
  216. return lab;
  217. }
  218. // 统一文字样式
  219. private applyStyle(lab: Label, st: any, base: number) {
  220. lab.fontSize = st.size <= 1 ? Math.round(base * st.size) : st.size;
  221. lab.lineHeight = lab.fontSize;
  222. lab.color = new Color(st.color[0], st.color[1], st.color[2], 255);
  223. if (st.bold) lab.isBold = true;
  224. if (st.ow && st.ow > 0) {
  225. lab.enableOutline = true;
  226. lab.outlineColor = new Color(st.outline[0], st.outline[1], st.outline[2], 255);
  227. lab.outlineWidth = st.ow;
  228. }
  229. }
  230. // 数字变化时弹一下
  231. private pop(node: Node, s = 1.22) {
  232. node.setScale(s, s, 1);
  233. tween(node).to(0.22, { scale: new Vec3(1, 1, 1) }, { easing: 'backOut' }).start();
  234. }
  235. // 中奖时在网格中央飘一个 +N 上升淡出
  236. private floatWin(amount: number) {
  237. const n = new Node('fw'); n.parent = this.node; n.setPosition(0, this.frameCY + this.cell, 0); n.setSiblingIndex(27);
  238. const lab = n.addComponent(Label); lab.string = '+' + amount; this.applyStyle(lab, STYLE.floatWin, 0);
  239. const op = n.addComponent(UIOpacity);
  240. n.setScale(0.5, 0.5, 1);
  241. tween(n).to(0.16, { scale: new Vec3(1.15, 1.15, 1) }, { easing: 'backOut' })
  242. .to(0.12, { scale: new Vec3(1, 1, 1) }).start();
  243. tween(n).by(0.85, { position: new Vec3(0, this.cell * 1.6, 0) }, { easing: 'cubicOut' }).start();
  244. tween(op).delay(0.35).to(0.5, { opacity: 0 }).call(() => n.destroy()).start();
  245. }
  246. // ---------------- 控制区:btn_round / btn_spin 美术 ----------------
  247. private buildControls(W: number, H: number) {
  248. const C = LAYOUT.controls;
  249. const y = H * C.cy;
  250. const big = W * C.spinR; // SPIN 按屏宽定标,最突出
  251. const sr = W * C.smallR;
  252. this.spinBtn = this.makeBtn(0, y, big, 'btn_spin', '⟳', big * 0.6, () => this.spin());
  253. this.turboBtn = this.makeBtn(-W * C.xTurbo, y, sr, 'btn_turbo', '⚡', sr * 0.8, () => this.toggleTurbo());
  254. this.makeBtn(-W * C.xMinus, y, sr, 'btn_minus', '−', sr, () => this.changeBet(-10));
  255. this.makeBtn(W * C.xMinus, y, sr, 'btn_plus', '+', sr, () => this.changeBet(10));
  256. this.autoBtn = this.makeBtn(W * C.xTurbo, y, sr, 'btn_auto', '▶', sr * 0.8, () => this.toggleAuto());
  257. }
  258. private makeBtn(x: number, y: number, r: number, artId: string, glyph: string, fs: number, onClick: () => void): Node {
  259. const node = new Node('btn'); node.parent = this.node; node.setPosition(x, y, 0); node.setSiblingIndex(17);
  260. let hasArt = false;
  261. if (this.art[artId]) {
  262. const s = node.addComponent(Sprite); s.sizeMode = Sprite.SizeMode.CUSTOM; s.spriteFrame = this.art[artId]!; hasArt = true;
  263. } else {
  264. const g = node.addComponent(Graphics); g.fillColor = new Color(90, 70, 140, 255); g.circle(0, 0, r); g.fill();
  265. g.lineWidth = 4; g.strokeColor = new Color(255, 255, 255, 235); g.circle(0, 0, r); g.stroke();
  266. }
  267. const ut = node.getComponent(UITransform) || node.addComponent(UITransform); ut.setContentSize(r * 2, r * 2);
  268. // 有美术(图标已烤进图里)就不叠字;没有才用文字兜底
  269. if (!hasArt) {
  270. const gl = new Node('g'); gl.parent = node;
  271. const lab = gl.addComponent(Label); lab.string = glyph; lab.fontSize = fs; lab.color = new Color(255, 255, 255, 255);
  272. }
  273. const btn = node.addComponent(Button);
  274. btn.transition = Button.Transition.NONE; // 自己控制反馈,更跟手
  275. const press = () => { tween(node).to(0.07, { scale: new Vec3(FEEDBACK.btnPress, FEEDBACK.btnPress, 1) }).start(); };
  276. const release = () => { tween(node).to(FEEDBACK.btnBack, { scale: new Vec3(1, 1, 1) }, { easing: 'backOut' }).start(); };
  277. node.on(Node.EventType.TOUCH_START, press);
  278. node.on(Node.EventType.TOUCH_END, (_e: EventTouch) => { release(); onClick(); });
  279. node.on(Node.EventType.TOUCH_CANCEL, release);
  280. return node;
  281. }
  282. private makeTextLabel(x: number, y: number, text: string, fs: number) {
  283. const n = new Node('tl'); n.parent = this.node; n.setPosition(x, y, 0); n.setSiblingIndex(17);
  284. const lab = n.addComponent(Label); lab.string = text; lab.fontSize = fs; lab.color = new Color(255, 255, 255, 235);
  285. }
  286. private changeBet(d: number) {
  287. if (this.spinning) return;
  288. this.bet = Math.max(10, Math.min(500, this.bet + d));
  289. this.betLabel.string = `${this.bet}`;
  290. this.pop(this.betLabel.node);
  291. }
  292. // TURBO:加速;AUTO:自动连转。带高亮状态。
  293. private td(v: number) { return this.turbo ? v * 0.4 : v; }
  294. private toggleTurbo() {
  295. this.turbo = !this.turbo; this.tintBtn(this.turboBtn, this.turbo);
  296. }
  297. private toggleAuto() {
  298. this.auto = !this.auto; this.tintBtn(this.autoBtn, this.auto);
  299. if (this.auto && !this.spinning) this.spin();
  300. }
  301. private tintBtn(node: Node, on: boolean) {
  302. const s = node.getComponent(Sprite);
  303. if (s) s.color = on ? new Color(255, 224, 90, 255) : new Color(255, 255, 255, 255);
  304. tween(node).to(0.12, { scale: new Vec3(on ? 1.12 : 1, on ? 1.12 : 1, 1) }, { easing: 'backOut' }).start();
  305. }
  306. // 大额报幕 + 金币雨
  307. private celebrate(amount: number) {
  308. const n = new Node('bigwin'); n.parent = this.node; n.setPosition(0, this.frameCY, 0);
  309. n.setSiblingIndex(this.node.children.length); // 强制置顶
  310. const lab = n.addComponent(Label); lab.string = '+' + amount; this.applyStyle(lab, STYLE.bigWin, this.W);
  311. const op = n.addComponent(UIOpacity);
  312. n.setScale(0.2, 0.2, 1);
  313. tween(n).to(0.28, { scale: new Vec3(1.18, 1.18, 1) }, { easing: 'backOut' })
  314. .to(0.12, { scale: new Vec3(1, 1, 1) })
  315. .delay(0.6).to(0.25, { scale: new Vec3(1.25, 1.25, 1) }).start();
  316. tween(op).delay(0.95).to(0.35, { opacity: 0 }).call(() => n.destroy()).start();
  317. this.coinShower(Math.max(12, Math.min(40, Math.floor(amount / 15))));
  318. }
  319. private coinShower(count: number) {
  320. const sf = this.art['coin']; if (!sf) return;
  321. const sz = this.cell * 0.6;
  322. for (let i = 0; i < count; i++) {
  323. const x0 = (Math.random() * 2 - 1) * this.frameW * 0.42;
  324. const c = this.spriteNode(sf, sz, sz, x0, this.H * 0.5 + this.cell, this.node.children.length + 1);
  325. const op = c.addComponent(UIOpacity);
  326. const dur = 0.9 + Math.random() * 0.7;
  327. const dx = (Math.random() * 2 - 1) * this.W * 0.12;
  328. tween(c).delay(Math.random() * 0.35)
  329. .by(dur, { position: new Vec3(dx, -this.H - this.cell * 2, 0), angle: (Math.random() * 2 - 1) * 720 }, { easing: 'sineIn' })
  330. .call(() => c.destroy()).start();
  331. tween(op).delay(dur * 0.7).to(dur * 0.3, { opacity: 0 }).start();
  332. }
  333. }
  334. private fitSize(sf: SpriteFrame, boxW: number, boxH: number): [number, number] {
  335. const r = sf.rect; const aw = r.width || 1, ah = r.height || 1;
  336. const s = Math.min(boxW / aw, boxH / ah); return [aw * s, ah * s];
  337. }
  338. private coverSize(sf: SpriteFrame, boxW: number, boxH: number): [number, number] {
  339. const r = sf.rect; const aw = r.width || 1, ah = r.height || 1;
  340. const s = Math.max(boxW / aw, boxH / ah); return [aw * s, ah * s];
  341. }
  342. private spriteNode(sf: SpriteFrame, w: number, h: number, x: number, y: number, sib: number): Node {
  343. const n = new Node('art'); n.parent = this.node; n.setPosition(x, y, 0); n.setSiblingIndex(sib);
  344. const s = n.addComponent(Sprite); s.sizeMode = Sprite.SizeMode.CUSTOM; s.spriteFrame = sf;
  345. const ut = n.getComponent(UITransform) || n.addComponent(UITransform); ut.setContentSize(w, h);
  346. return n;
  347. }
  348. // ---------------- 网格:圆角卡片 + 大符号 ----------------
  349. private fit(id: string) { return SYMFIT[id] || SYMFIT_DEFAULT; }
  350. private buildGrid() {
  351. const cardSize = this.cell * 0.92;
  352. for (let c = 0; c < COLS; c++) {
  353. this.cells[c] = []; this.ids[c] = []; this.symBaseY[c] = [];
  354. for (let r = 0; r < ROWS; r++) {
  355. const id = this.reelRand(c);
  356. const [x, y] = this.cellPos(c, r);
  357. const card = new Node(`card_${c}_${r}`); card.parent = this.node; card.setPosition(x, y, 0); card.setSiblingIndex(5);
  358. const cg = card.addComponent(Graphics);
  359. cg.fillColor = new Color(255, 255, 255, 215);
  360. this.roundRect(cg, -cardSize / 2, -cardSize / 2, cardSize, cardSize, cardSize * 0.24); cg.fill();
  361. cg.lineWidth = 3; cg.strokeColor = new Color(120, 175, 255, 240);
  362. this.roundRect(cg, -cardSize / 2, -cardSize / 2, cardSize, cardSize, cardSize * 0.24); cg.stroke();
  363. const f = this.fit(id);
  364. const scale = this.cell * f.s;
  365. const baseY = y - this.cell * f.oyf;
  366. this.symBaseY[c][r] = baseY;
  367. const node = new Node(`cell_${c}_${r}`); node.parent = this.node; node.setSiblingIndex(6);
  368. node.setPosition(x, baseY, 0); node.setScale(scale, scale, 1);
  369. const sk = node.addComponent(sp.Skeleton);
  370. sk.skeletonData = this.dataMap[id]; sk.premultipliedAlpha = false;
  371. sk.setAnimation(0, 'idle', true);
  372. this.cells[c][r] = sk; this.ids[c][r] = id;
  373. }
  374. }
  375. }
  376. private setSym(c: number, r: number, id: string) {
  377. const sk = this.cells[c][r];
  378. sk.skeletonData = this.dataMap[id]; sk.premultipliedAlpha = false;
  379. sk.setAnimation(0, 'idle', true);
  380. this.ids[c][r] = id;
  381. const [x, y] = this.cellPos(c, r);
  382. const f = this.fit(id);
  383. const scale = this.cell * f.s;
  384. const baseY = y - this.cell * f.oyf;
  385. this.symBaseY[c][r] = baseY;
  386. const nd = sk.node;
  387. nd.setScale(scale, scale, 1);
  388. nd.setPosition(x, baseY + this.cell * FEEDBACK.dropFrom, 0); // 从上方落入
  389. tween(nd).to(FEEDBACK.dropTime, { position: new Vec3(x, baseY, 0) }, { easing: 'backOut' }).start();
  390. }
  391. private spin() {
  392. if (this.spinning) return;
  393. if (this.holdActive) { this.holdRespin(); return; }
  394. const freeSpin = this.freeSpins > 0;
  395. if (!freeSpin && this.balance < this.bet) { this.flashMult('余额不足'); return; }
  396. if (freeSpin) {
  397. this.freeSpins -= 1;
  398. this.flashMult(`免费旋转 ${this.freeSpins}`);
  399. } else {
  400. this.balance -= this.bet; this.displayBalance = this.balance;
  401. this.balanceLabel.string = `${Math.floor(this.displayBalance)}`;
  402. this.pop(this.balanceLabel.node);
  403. }
  404. this.multiplier = 1; this.roundWin = 0; this.cascade = 0;
  405. this.winLabel.string = '0'; this.multLabel.string = '';
  406. this.spinning = true; this.setSpinEnabled(false);
  407. tween(this.spinBtn).by(FEEDBACK.spinDuration, { angle: -360 }, { easing: 'cubicOut' }).start(); // 联动旋转
  408. for (let c = 0; c < COLS; c++) {
  409. const strip = this.reel(c);
  410. const start = Math.floor(Math.random() * strip.length);
  411. for (let r = 0; r < ROWS; r++) this.setSym(c, r, strip[(start + r) % strip.length]);
  412. }
  413. this.scheduleOnce(() => this.resolve(), this.td(0.45));
  414. }
  415. private resolve() {
  416. if (this.cascade === 0) this.resolveFeatureTriggers();
  417. const count: Record<string, number> = {};
  418. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) count[this.ids[c][r]] = (count[this.ids[c][r]] || 0) + 1;
  419. const result = IS_CLUSTER ? this.findClusterWins() : this.findCountWins(count);
  420. if (result.groups.length === 0) { this.endRound(); return; }
  421. let cleared = 0; const winners: sp.Skeleton[] = [];
  422. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) {
  423. if (result.mask[c] && result.mask[c][r]) { winners.push(this.cells[c][r]); cleared++; }
  424. }
  425. const pay = this.calcPay(result.groups);
  426. this.roundWin += pay; this.balance += pay; this.winLabel.string = `${this.roundWin}`;
  427. this.pop(this.winLabel.node, 1.3); this.floatWin(pay);
  428. this.flashMult(`x${this.multiplier} +${pay}`);
  429. winners.forEach((sk) => {
  430. sk.setAnimation(0, 'win', false); sk.addAnimation(0, 'idle', true, 0);
  431. const nd = sk.node; const sc = nd.scale.x;
  432. tween(nd).to(0.1, { scale: new Vec3(sc * FEEDBACK.clearPop, sc * FEEDBACK.clearPop, 1) })
  433. .to(0.14, { scale: new Vec3(sc, sc, 1) }, { easing: 'backOut' }).start();
  434. });
  435. this.playParticle('coin_rain');
  436. this.cascade += 1;
  437. this.scheduleOnce(() => {
  438. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++)
  439. if (result.mask[c] && result.mask[c][r]) this.setSym(c, r, this.reelRand(c));
  440. this.multiplier = Math.min(CASCADE_MULT_MAX, this.multiplier + CASCADE_MULT_STEP);
  441. if (this.cascade >= MAX_CASCADE) { this.endRound(); return; }
  442. this.scheduleOnce(() => this.resolve(), this.td(0.4));
  443. }, this.td(0.6));
  444. }
  445. private calcPay(groups: {id: string; n: number}[]) {
  446. let total = 0;
  447. groups.forEach(({id, n}) => {
  448. const table = PAYTABLE[id] || {};
  449. const capped = Math.min(6, Math.max(MIN_MATCH, n));
  450. const mult = Number(table[String(capped)] ?? table[String(MIN_MATCH)] ?? capped);
  451. total += mult * this.bet;
  452. });
  453. return Math.max(1, Math.floor(total * this.multiplier * PAYOUT_SCALE));
  454. }
  455. private resolveFeatureTriggers() {
  456. if (SCATTER_RULES.enabled) {
  457. const scatterCount = this.countRole('scatter');
  458. if (scatterCount >= FREE_SPIN_TRIGGER) {
  459. const scatterPay = this.featurePay('scatter', scatterCount);
  460. this.freeSpins += FREE_SPIN_AWARD;
  461. if (scatterPay > 0) { this.roundWin += scatterPay; this.balance += scatterPay; this.winLabel.string = `${this.roundWin}`; }
  462. this.flashMult(`FREE SPINS +${FREE_SPIN_AWARD}`);
  463. this.playParticle('bigwin_glow');
  464. }
  465. }
  466. if (HOLD_RULES.enabled && !this.holdActive && this.countRole('bonus') >= HOLD_TRIGGER) {
  467. this.startHoldAndWin();
  468. }
  469. }
  470. private findCountWins(count: Record<string, number>) {
  471. const wildCount = this.countRole('wild');
  472. const mask = this.emptyMask();
  473. const groups = Object.keys(count).filter((id) => {
  474. if (this.isWild(id) || this.isScatter(id) || this.isBonus(id)) return false;
  475. return (count[id] || 0) + wildCount >= MIN_MATCH;
  476. }).map((id) => ({id, n: (count[id] || 0) + wildCount}));
  477. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) {
  478. const id = this.ids[c][r];
  479. if (groups.some((g) => g.id === id) || (this.isWild(id) && groups.length > 0)) mask[c][r] = true;
  480. }
  481. return {groups, mask};
  482. }
  483. private findClusterWins() {
  484. const groups: {id: string; n: number}[] = [];
  485. const mask = this.emptyMask();
  486. const regular = SYMBOLS.filter((id: string) => !this.isWild(id) && !this.isScatter(id) && !this.isBonus(id));
  487. regular.forEach((sid: string) => {
  488. const seen = this.emptyMask();
  489. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) {
  490. if (seen[c][r] || (this.ids[c][r] !== sid && !this.isWild(this.ids[c][r]))) continue;
  491. const stack: [number, number][] = [[c, r]];
  492. const cells: [number, number][] = [];
  493. seen[c][r] = true;
  494. while (stack.length) {
  495. const [x, y] = stack.pop()!;
  496. cells.push([x, y]);
  497. [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]].forEach(([nx, ny]) => {
  498. if (nx < 0 || nx >= COLS || ny < 0 || ny >= ROWS || seen[nx][ny]) return;
  499. const nid = this.ids[nx][ny];
  500. if (nid === sid || this.isWild(nid)) { seen[nx][ny] = true; stack.push([nx, ny]); }
  501. });
  502. }
  503. if (cells.length >= MIN_MATCH) {
  504. groups.push({id: sid, n: cells.length});
  505. cells.forEach(([x, y]) => { mask[x][y] = true; });
  506. }
  507. }
  508. });
  509. return {groups, mask};
  510. }
  511. private emptyMask() {
  512. const mask: boolean[][] = [];
  513. for (let c = 0; c < COLS; c++) {
  514. mask[c] = [];
  515. for (let r = 0; r < ROWS; r++) mask[c][r] = false;
  516. }
  517. return mask;
  518. }
  519. private featurePay(id: string, count: number) {
  520. const table = PAYTABLE[id] || {};
  521. const n = Math.min(6, Math.max(3, count));
  522. return Math.floor(Number(table[String(n)] ?? 0) * this.bet * PAYOUT_SCALE);
  523. }
  524. private role(id: string) { return SYMBOL_ROLE[id] || ''; }
  525. private isWild(id: string) { return this.role(id) === 'wild' || id === 'wild'; }
  526. private isScatter(id: string) { return this.role(id) === 'scatter' || id.indexOf('scatter') >= 0; }
  527. private isBonus(id: string) { return this.role(id) === 'bonus' || id.indexOf('coin') >= 0 || id === 'collect'; }
  528. private countRole(role: string) {
  529. let n = 0;
  530. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) {
  531. const id = this.ids[c][r];
  532. if ((role === 'wild' && this.isWild(id)) || (role === 'scatter' && this.isScatter(id)) || (role === 'bonus' && this.isBonus(id))) n++;
  533. }
  534. return n;
  535. }
  536. private startHoldAndWin() {
  537. this.holdActive = true;
  538. this.holdRespinsLeft = HOLD_RESPINS;
  539. this.holdWinTotal = 0;
  540. this.holdHeld = [];
  541. for (let c = 0; c < COLS; c++) {
  542. this.holdHeld[c] = [];
  543. for (let r = 0; r < ROWS; r++) {
  544. const held = this.isBonus(this.ids[c][r]);
  545. this.holdHeld[c][r] = held;
  546. if (held) this.holdWinTotal += this.coinValue(c, r);
  547. }
  548. }
  549. this.flashMult(`HOLD & WIN ${this.holdRespinsLeft}`);
  550. this.playParticle('bigwin_glow');
  551. }
  552. private holdRespin() {
  553. this.spinning = true; this.setSpinEnabled(false);
  554. let newCoin = false;
  555. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) {
  556. if (this.holdHeld[c] && this.holdHeld[c][r]) continue;
  557. const id = Math.random() < 0.18 ? this.randomBonusSymbol() : this.randRegular();
  558. this.setSym(c, r, id);
  559. if (this.isBonus(id)) {
  560. this.holdHeld[c][r] = true;
  561. this.holdWinTotal += this.coinValue(c, r);
  562. newCoin = true;
  563. }
  564. }
  565. this.holdRespinsLeft = newCoin ? HOLD_RESPINS : this.holdRespinsLeft - 1;
  566. this.flashMult(`HOLD & WIN ${this.holdRespinsLeft}`);
  567. this.scheduleOnce(() => {
  568. if (this.holdRespinsLeft <= 0 || this.allHoldFilled()) {
  569. this.balance += this.holdWinTotal; this.roundWin += this.holdWinTotal; this.winLabel.string = `${this.roundWin}`;
  570. this.holdActive = false; this.holdHeld = [];
  571. this.floatWin(this.holdWinTotal); this.playParticle('coin_rain');
  572. this.endRound();
  573. } else {
  574. this.spinning = false; this.setSpinEnabled(true);
  575. }
  576. }, this.td(0.6));
  577. }
  578. private allHoldFilled() {
  579. for (let c = 0; c < COLS; c++) for (let r = 0; r < ROWS; r++) if (!this.holdHeld[c][r]) return false;
  580. return true;
  581. }
  582. private coinValue(c: number, r: number) { return Math.floor(this.bet * (1 + ((c + r) % 5)) * PAYOUT_SCALE); }
  583. private randomBonusSymbol() {
  584. const bonus = SYMBOLS.filter((id: string) => this.isBonus(id));
  585. return bonus.length ? bonus[Math.floor(Math.random() * bonus.length)] : this.rand();
  586. }
  587. private randRegular() {
  588. const regular = SYMBOLS.filter((id: string) => !this.isWild(id) && !this.isScatter(id) && !this.isBonus(id));
  589. return regular.length ? regular[Math.floor(Math.random() * regular.length)] : this.rand();
  590. }
  591. private endRound() {
  592. if (this.roundWin > 0) { this.multLabel.string = ''; this.celebrate(this.roundWin); }
  593. else this.multLabel.string = '';
  594. this.spinning = false; this.setSpinEnabled(true);
  595. if (this.holdActive) return;
  596. if (this.freeSpins > 0) this.scheduleOnce(() => this.spin(), this.td(0.9));
  597. else if (this.auto && this.balance >= this.bet) this.scheduleOnce(() => this.spin(), this.td(0.9));
  598. }
  599. private flashMult(text: string) {
  600. this.multLabel.string = text;
  601. const n = this.multLabel.node; n.setScale(0.6, 0.6, 1);
  602. tween(n).to(0.3, { scale: new Vec3(1, 1, 1) }, { easing: 'elasticOut' }).start();
  603. }
  604. private playParticle(id: string) {
  605. resources.load(`vfx/${id}`, JsonAsset, (err, asset) => {
  606. if (err) return;
  607. const n = new Node('p'); n.parent = this.node; n.setPosition(0, this.frameCY + this.frameH / 2, 0); n.setSiblingIndex(26);
  608. const ps = n.addComponent(ParticleSystem2D);
  609. applyParticleConfig(ps, asset.json, this.particleTex as SpriteFrame);
  610. this.scheduleOnce(() => ps.stopSystem(), 1.2);
  611. this.scheduleOnce(() => n.destroy(), 4);
  612. });
  613. }
  614. update(dt: number) {
  615. this.t += dt;
  616. if (Math.abs(this.displayBalance - this.balance) > 0.5) {
  617. this.displayBalance += (this.balance - this.displayBalance) * Math.min(1, dt * 6);
  618. this.balanceLabel.string = `${Math.floor(this.displayBalance)}`;
  619. }
  620. // 待机时每个果冻轻微上下呼吸,画面更"活"
  621. if (!this.spinning && this.cells.length) {
  622. for (let c = 0; c < COLS; c++) {
  623. for (let r = 0; r < ROWS; r++) {
  624. const sk = this.cells[c] && this.cells[c][r]; if (!sk) continue;
  625. const by = this.symBaseY[c] && this.symBaseY[c][r]; if (by === undefined) continue;
  626. const px = sk.node.position.x;
  627. sk.node.setPosition(px, by + Math.sin(this.t * 2.2 + c * 0.8 + r * 0.6) * this.cell * FEEDBACK.idleBob, 0);
  628. }
  629. }
  630. }
  631. }
  632. private rand() { return SYMBOLS[Math.floor(Math.random() * SYMBOLS.length)]; }
  633. private reel(c: number) {
  634. const strip = REEL_STRIPS[c % Math.max(1, REEL_STRIPS.length)];
  635. return strip && strip.length ? strip : SYMBOLS;
  636. }
  637. private reelRand(c: number) {
  638. const strip = this.reel(c);
  639. return strip[Math.floor(Math.random() * strip.length)];
  640. }
  641. private setSpinEnabled(on: boolean) {
  642. const btn = this.spinBtn.getComponent(Button); if (btn) btn.interactable = on;
  643. }
  644. private roundRect(g: Graphics, x: number, y: number, w: number, h: number, r: number) {
  645. g.moveTo(x + r, y); g.lineTo(x + w - r, y);
  646. g.arc(x + w - r, y + r, r, -Math.PI / 2, 0, false);
  647. g.lineTo(x + w, y + h - r); g.arc(x + w - r, y + h - r, r, 0, Math.PI / 2, false);
  648. g.lineTo(x + r, y + h); g.arc(x + r, y + h - r, r, Math.PI / 2, Math.PI, false);
  649. g.lineTo(x, y + r); g.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5, false); g.close();
  650. }
  651. }