// Pure slot-machine engine — no Phaser imports. All randomness flows through // the injected rng so seeded runs replay identically (verifySlots.js relies // on this). Documented rng draw order per spin: // 1. reel stops, left to right (held reels skipped) // 2. coin values for landed coins, column-major // 3. cascade refills, per cascade: column-major, top-down // (rainbow roll first, then strip draw) // 4. feature rolls: hold offer, then nudge award // Hold-and-spin respins draw in holdSpinRespin(): cells column-major, // presence roll then value roll. // // The engine returns a complete ordered steps[] script for every spin; the // renderer only animates it and never invents a symbol or payout. export function randInt(rng, n) { return Math.floor(rng() * n); } export function weightedDraw(rng, pairs) { let total = 0; for (const [, w] of pairs) total += w; let roll = rng() * total; for (const [value, w] of pairs) { roll -= w; if (roll <= 0) return value; } return pairs[pairs.length - 1][0]; } // Largest numeric key in table that is <= count (pay tables are monotonic). function lookupTier(table, count) { let best = null; for (const k of Object.keys(table)) { const n = Number(k); if (n <= count && (best === null || n > best)) best = n; } return best === null ? null : { count: best, pay: table[best] }; } const key = (c, r) => `${c},${r}`; // ── Session ─────────────────────────────────────────────────────────────────── export function createSession(machine, rng = Math.random) { return { machine, rng, mode: 'base', // 'base' | 'freespins' | 'holdspin' stops: machine.strips.map(() => 0), grid: null, freeSpins: null, // { remaining, total } stickyWilds: [], // [{ c, r, spinsLeft }] holds: { offered: false, held: machine.strips.map(() => false) }, nudgesLeft: 0, holdSpin: null, // { locked: [{c,r,value|tier}], respinsLeft } coinValues: {}, // 'c,r' → { value } | { tier } rainbowValues: {}, // 'c,r' → multiplier value }; } export function spinIsFree(state) { return state.mode === 'freespins'; } // ── Grid construction ───────────────────────────────────────────────────────── // grid[col][row] = symbol id. stop = strip index of the TOP visible row. export function gridFromStops(machine, stops, overrides = {}) { const { rows } = machine.layout; const grid = []; for (let c = 0; c < machine.strips.length; c++) { const strip = machine.strips[c]; grid[c] = []; for (let r = 0; r < rows; r++) { grid[c][r] = overrides[key(c, r)] ?? strip[(stops[c] + r) % strip.length]; } } return grid; } // ── Line evaluation ─────────────────────────────────────────────────────────── // Returns { wins: [{ line, symbol, count, cells, credits, wildMult }], total }. // Pay values are per LINE bet; credits = round(pay * wildMult * bet / nLines). export function evaluateLines(machine, grid, bet) { const wildSym = machine.wild?.symbol ?? null; const wildMults = machine.wild?.multipliers ?? null; const groups = machine.symbolGroups ?? {}; const nLines = machine.paylines.length; const wins = []; let total = 0; machine.paylines.forEach((line, li) => { let best = null; for (const target of Object.keys(machine.paytable)) { const members = groups[target] ?? null; const isWildTarget = target === wildSym; let count = 0; let wildsInWin = 0; for (let c = 0; c < line.length; c++) { const sym = grid[c][line[c]]; const isWild = wildSym !== null && sym === wildSym; let match; if (isWildTarget) match = isWild; else if (members) match = members.includes(sym) || isWild; else match = sym === target || isWild; if (!match) break; count++; if (isWild && !isWildTarget) wildsInWin++; } if (count === 0) continue; const tier = lookupTier(machine.paytable[target], count); if (!tier) continue; // A group/symbol win made of nothing but wilds belongs to the wild's own // paytable entry (or a better symbol) — still valid, just scored here too; // best-pick keeps the highest. const wildMult = (wildMults && !isWildTarget && wildsInWin > 0) ? (wildMults[wildsInWin] ?? 1) : 1; const credits = Math.round(tier.pay * wildMult * bet / nLines); if (credits > 0 && (!best || credits > best.credits)) { best = { line: li, symbol: target, count: tier.count, cells: line.slice(0, tier.count).map((row, c) => ({ c, r: row })), credits, wildMult, }; } } if (best) { wins.push(best); total += best.credits; } }); return { wins, total }; } // ── Scatter-pays evaluation (Sugar Spin) ────────────────────────────────────── // paytable[symbol] = [{ min, pay }] sorted by min desc; pay is ×total-bet. export function evaluateScatterPays(machine, grid, bet) { const counts = {}; const cellsBySym = {}; for (let c = 0; c < grid.length; c++) { for (let r = 0; r < grid[c].length; r++) { const sym = grid[c][r]; counts[sym] = (counts[sym] ?? 0) + 1; (cellsBySym[sym] ??= []).push({ c, r }); } } const wins = []; let total = 0; for (const [sym, tiers] of Object.entries(machine.paytable)) { const n = counts[sym] ?? 0; const tier = tiers.find((t) => n >= t.min); if (!tier) continue; const credits = Math.round(tier.pay * bet); if (credits <= 0) continue; wins.push({ symbol: sym, count: n, cells: cellsBySym[sym], credits }); total += credits; } return { wins, total }; } export function evaluateGrid(machine, grid, bet) { return machine.evaluation === 'scatterPays' ? evaluateScatterPays(machine, grid, bet) : evaluateLines(machine, grid, bet); } // ── Scatter symbol (anywhere) counting ──────────────────────────────────────── function findScatters(machine, grid) { if (!machine.scatter) return { count: 0, cells: [] }; const cells = []; for (let c = 0; c < grid.length; c++) { for (let r = 0; r < grid[c].length; r++) { if (grid[c][r] === machine.scatter.symbol) cells.push({ c, r }); } } return { count: cells.length, cells }; } // ── Cascades / tumbles ──────────────────────────────────────────────────────── // Mutates grid in place; returns steps + total. Used by Abyssal (lines with // multiplier ladder) and Sugar Spin (scatter pays + rainbow multipliers). export function resolveCascades(state, grid, bet) { const { machine, rng } = state; const ladder = machine.features.cascade?.multipliers ?? null; const rainbowCfg = machine.features.rainbow ?? null; const steps = []; let total = 0; let cascadeIndex = 0; for (;;) { const mult = ladder ? ladder[Math.min(cascadeIndex, ladder.length - 1)] : 1; const ev = evaluateGrid(machine, grid, bet); if (ev.total <= 0) break; const winCredits = ev.total * mult; total += winCredits; steps.push({ type: machine.evaluation === 'scatterPays' ? 'scatterPay' : 'lineWins', wins: ev.wins, multiplier: mult, credits: winCredits, }); // Union of winning cells to remove. const removeSet = new Set(); for (const w of ev.wins) for (const cell of w.cells) removeSet.add(key(cell.c, cell.r)); // Tumble each column: survivors fall, refills drop in from the strip. const rows = machine.layout.rows; const removed = [...removeSet].map((k) => { const [c, r] = k.split(',').map(Number); return { c, r }; }); const falls = []; const refills = []; for (let c = 0; c < grid.length; c++) { const survivors = []; for (let r = 0; r < rows; r++) { if (!removeSet.has(key(c, r))) survivors.push({ fromR: r, sym: grid[c][r] }); } const missing = rows - survivors.length; if (missing === 0) continue; // Slide survivors to the bottom of the column. for (let i = survivors.length - 1; i >= 0; i--) { const toR = rows - (survivors.length - i); const { fromR, sym } = survivors[i]; if (state.rainbowValues[key(c, fromR)] !== undefined && fromR !== toR) { state.rainbowValues[key(c, toR)] = state.rainbowValues[key(c, fromR)]; delete state.rainbowValues[key(c, fromR)]; } if (fromR !== toR) falls.push({ c, fromR, toR }); grid[c][toR] = sym; } // Refill the vacated top cells, top-down. const strip = machine.strips[c]; for (let r = 0; r < missing; r++) { let sym; if (rainbowCfg && rng() < rainbowCfg.chance) { sym = rainbowCfg.symbol; state.rainbowValues[key(c, r)] = weightedDraw(rng, rainbowCfg.values); } else { sym = strip[randInt(rng, strip.length)]; } grid[c][r] = sym; refills.push({ c, r, symbol: sym }); } } steps.push({ type: 'tumble', removed, falls, refills, grid: grid.map((col) => col.slice()), cascadeIndex, }); cascadeIndex++; } // Rainbow multipliers apply to the whole tumble sequence at the end. if (rainbowCfg && total > 0) { const cells = []; for (const [k, v] of Object.entries(state.rainbowValues)) { const [c, r] = k.split(',').map(Number); cells.push({ c, r, value: v }); } if (cells.length > 0) { const factor = cells.reduce((s, cell) => s + cell.value, 0); const boosted = total * factor; steps.push({ type: 'rainbow', cells, factor, credits: boosted - total }); total = boosted; } } return { steps, total }; } // ── Core spin ───────────────────────────────────────────────────────────────── // The caller owns the money: charge `bet` before calling unless spinIsFree(). export function spin(state, bet) { const { machine, rng } = state; if (state.mode === 'holdspin') throw new Error('resolve hold-and-spin respins first'); const freeSpin = state.mode === 'freespins'; if (freeSpin) state.freeSpins.remaining--; // 1. Stops (held reels keep their previous stop). const heldAny = state.holds.held.some(Boolean); const stops = machine.strips.map((strip, i) => (state.holds.held[i] ? state.stops[i] : randInt(rng, strip.length))); state.stops = stops; state.holds = { offered: false, held: machine.strips.map(() => false) }; state.nudgesLeft = 0; state.rainbowValues = {}; // Sticky wild overrides (placed on previous spins). const overrides = {}; const stickyCfg = machine.features.stickyWilds ?? null; for (const s of state.stickyWilds) overrides[key(s.c, s.r)] = stickyCfg.symbol; let grid = gridFromStops(machine, stops, overrides); const steps = []; // 2. Coin values (Dragon's Hoard) — column-major draw order. const holdSpinCfg = machine.features.holdSpin ?? null; state.coinValues = {}; const coinCells = []; if (holdSpinCfg) { for (let c = 0; c < grid.length; c++) { for (let r = 0; r < grid[c].length; r++) { if (grid[c][r] !== holdSpinCfg.coinSymbol) continue; const drawn = weightedDraw(rng, holdSpinCfg.coinValues); state.coinValues[key(c, r)] = typeof drawn === 'number' ? { value: drawn } : { tier: drawn }; coinCells.push({ c, r, ...state.coinValues[key(c, r)] }); } } } // Expanding wild on the configured reel during free spins (Pharaoh). if (freeSpin && machine.scatter?.expandingWildReel !== undefined) { const col = machine.scatter.expandingWildReel; if (grid[col].some((s) => s === machine.wild.symbol)) { grid[col] = grid[col].map(() => machine.wild.symbol); steps.push({ type: 'expandWild', col, cells: grid[col].map((_, r) => ({ c: col, r })), }); } } // 3. Evaluation (+ cascades where configured). let totalWin = 0; if (machine.features.cascade || machine.features.tumble) { const res = resolveCascades(state, grid, bet); steps.push(...res.steps); totalWin += res.total; } else { const ev = evaluateGrid(machine, grid, bet); if (ev.total > 0) { steps.push({ type: machine.evaluation === 'scatterPays' ? 'scatterPay' : 'lineWins', wins: ev.wins, multiplier: 1, credits: ev.total, }); totalWin += ev.total; } } // Scatter pays + free spin awards. let freeSpinsAwarded = 0; const sc = findScatters(machine, grid); if (sc.count > 0 && machine.scatter) { let credits = 0; if (machine.scatter.pays) { const tier = lookupTier(machine.scatter.pays, sc.count); if (tier) credits = Math.round(tier.pay * bet); } if (machine.scatter.freeSpins && (!freeSpin || machine.scatter.retrigger)) { const fsTier = lookupTier(machine.scatter.freeSpins, sc.count); if (fsTier) freeSpinsAwarded = fsTier.pay; } if (credits > 0 || freeSpinsAwarded > 0) { steps.push({ type: 'scatterAward', symbol: machine.scatter.symbol, cells: sc.cells, credits, freeSpins: freeSpinsAwarded, }); totalWin += credits; } } if (freeSpinsAwarded > 0) { if (state.freeSpins) { state.freeSpins.remaining += freeSpinsAwarded; state.freeSpins.total += freeSpinsAwarded; } else { state.freeSpins = { remaining: freeSpinsAwarded, total: freeSpinsAwarded }; } state.mode = 'freespins'; } else if (freeSpin && state.freeSpins.remaining <= 0) { state.mode = 'base'; state.freeSpins = null; } // Hold-and-spin trigger (Dragon's Hoard). let holdSpinTriggered = false; if (holdSpinCfg && coinCells.length >= holdSpinCfg.trigger) { holdSpinTriggered = true; state.mode = 'holdspin'; state.holdSpin = { locked: coinCells.map(({ c, r, value, tier }) => ({ c, r, value, tier })), respinsLeft: holdSpinCfg.respins, }; } // Sticky wilds: age the existing ones, then add this spin's natural landings. // Placement/refresh must read the NATURAL strip symbol — the override grid // always shows a wild at a sticky cell, which would refresh stickies forever. let pickBonusTriggered = false; if (stickyCfg) { const expiring = []; state.stickyWilds = state.stickyWilds.filter((s) => { s.spinsLeft--; if (s.spinsLeft <= 0) { expiring.push({ c: s.c, r: s.r }); return false; } return true; }); const placed = []; for (let c = 0; c < grid.length; c++) { const strip = machine.strips[c]; for (let r = 0; r < grid[c].length; r++) { if (strip[(stops[c] + r) % strip.length] !== stickyCfg.symbol) continue; const existing = state.stickyWilds.find((s) => s.c === c && s.r === r); if (existing) existing.spinsLeft = stickyCfg.spins; else { state.stickyWilds.push({ c, r, spinsLeft: stickyCfg.spins }); placed.push({ c, r }); } } } if (placed.length > 0 || expiring.length > 0) { steps.push({ type: 'stickyWilds', placed, expiring }); } } if (machine.features.pickBonus && sc.count >= machine.features.pickBonus.min) { pickBonusTriggered = true; } // 4. Feature rolls (Fruit Frenzy): only on losing base spins. Holds are not // offered on the spin right after holds were used. let holdsOffered = false; let nudgesAwarded = 0; const hn = machine.features.holdNudge ?? null; if (hn && state.mode === 'base' && totalWin === 0) { if (!heldAny && rng() < hn.holdChance) { holdsOffered = true; state.holds.offered = true; } else if (rng() < hn.nudgeChance) { nudgesAwarded = weightedDraw(rng, hn.nudgeWeights); state.nudgesLeft = nudgesAwarded; } } const sliver = holdSpinCfg?.grand?.sliver ?? 0; state.grid = grid; return { stops, grid, steps, totalWin, coinCells, freeSpinsAwarded, freeSpinsRemaining: state.freeSpins?.remaining ?? 0, holdSpinTriggered, pickBonusTriggered, scatterCount: sc.count, holdsOffered, nudgesAwarded, progressiveContribution: sliver > 0 && !freeSpin ? bet * sliver : 0, }; } // ── Fruit Frenzy: holds & nudges ────────────────────────────────────────────── export function setHold(state, reelIdx, held) { if (!state.holds.offered) return false; state.holds.held[reelIdx] = held; return true; } // Nudge one reel down a single strip step and re-evaluate the grid. The caller // settles the LAST evaluation when the player stops nudging. export function applyNudge(state, reelIdx, bet) { if (state.nudgesLeft <= 0) return null; const { machine } = state; const strip = machine.strips[reelIdx]; state.nudgesLeft--; state.stops[reelIdx] = (state.stops[reelIdx] + 1) % strip.length; const grid = gridFromStops(machine, state.stops); state.grid = grid; const ev = evaluateGrid(machine, grid, bet); return { grid, wins: ev.wins, totalWin: ev.total, nudgesLeft: state.nudgesLeft }; } // Peek at what a nudge on reelIdx would produce, without committing. export function peekNudge(state, reelIdx, bet) { const { machine } = state; const strip = machine.strips[reelIdx]; const stops = state.stops.slice(); stops[reelIdx] = (stops[reelIdx] + 1) % strip.length; const grid = gridFromStops(machine, stops); return evaluateGrid(machine, grid, bet); } // ── Dragon's Hoard: hold-and-spin ───────────────────────────────────────────── export function holdSpinRespin(state, bet) { const cfg = state.machine.features.holdSpin; const hs = state.holdSpin; const { reels, rows } = state.machine.layout; const lockedSet = new Set(hs.locked.map((l) => key(l.c, l.r))); const newCoins = []; for (let c = 0; c < reels; c++) { for (let r = 0; r < rows; r++) { if (lockedSet.has(key(c, r))) continue; if (state.rng() < cfg.coinChance) { const drawn = weightedDraw(state.rng, cfg.coinValues); const coin = typeof drawn === 'number' ? { c, r, value: drawn } : { c, r, tier: drawn }; hs.locked.push(coin); newCoins.push(coin); } } } if (newCoins.length > 0) hs.respinsLeft = cfg.respins; else hs.respinsLeft--; const full = hs.locked.length >= reels * rows; const finished = full || hs.respinsLeft <= 0; let award = null; if (finished) { let credits = 0; const jackpots = []; for (const coin of hs.locked) { if (coin.value !== undefined) credits += coin.value * bet; else { const amount = cfg.jackpots[coin.tier] * bet; credits += amount; jackpots.push({ tier: coin.tier, amount }); } } award = { credits, jackpots, grandHit: full }; state.mode = 'base'; state.holdSpin = null; } return { newCoins, respinsLeft: finished ? 0 : hs.respinsLeft, finished, award }; } export function grandSliver(machine, bet) { return (machine.features.holdSpin?.grand?.sliver ?? 0) * bet; } // ── Gold Rush: pick-a-cart bonus ────────────────────────────────────────────── export function createPickBonus(machine, bet, rng) { const cfg = machine.features.pickBonus; const prizes = []; for (let i = 0; i < cfg.carts; i++) { prizes.push(Math.round(weightedDraw(rng, cfg.prizes) * bet)); } return { prizes, picksLeft: cfg.picks, picked: [], total: 0 }; } export function pick(bonus, idx) { if (bonus.picksLeft <= 0 || bonus.picked.includes(idx)) return null; bonus.picked.push(idx); bonus.picksLeft--; const prize = bonus.prizes[idx]; bonus.total += prize; return { prize, done: bonus.picksLeft <= 0, totalSoFar: bonus.total }; }