/** * r24labs engines: a reference build. * * A second implementation of the engines, in another language than the * original, following their descriptions (rain-engines.json, `spec`). It is * the proof that the descriptions are enough: from the same seed, settings, * dial and actions it makes the same draws in the same order and pays the * same amount as every round in rain-engine-vectors.json, and a test holds it * to that. * * It needs nothing but Node's crypto and the tables in rain-engines.json: * * import engines from "./rain-engines.json"; * const round = play(engines.engines, "mines", { mines: 3 }, 9900, seedHex, [["pick", 0], ["cashout"]]); * round.payX10k // what the round pays for a stake of 1, times 10,000 * round.draws // every draw, as [m, value]: int_below(m) gave value * * No engine fixes anything hidden at the start of a round: a card or a mine is * drawn at the step that shows it. So a round can also be played with a seed * of its own for every step. Give a list of seeds in place of the one: the * first starts the round, the next is the generator for the first action, and * so on, each started afresh. `round.steps` then holds the draws step by step. * * Where a table is data (slots, scratch, plinko, wheel, keno, the baccarat * pays) it is read from the file at the dial point asked for; where it is a * formula (dice, limbo, crash, tower, mines, ...) it is worked out here. * Whole-number arithmetic only, in BigInt, rounded down. * * The played-out slots and scratch cards pick one round out of a file of * rounds (rain-engines.json names the file and its sha256 under `books`). * Load that file and hand its list over before playing: * * import { gunzipSync } from "node:zlib"; * engines.engines["scratch (books)"].rounds = JSON.parse(gunzipSync(readFileSync("rain-books-scratch-v2.json.gz")).toString()); */ import { createHmac } from "node:crypto"; // ── The generator ──────────────────────────────────────────────────────────── const TWO_64 = BigInt(1) << BigInt(64); /** Storm's generator. word_j = HMAC-SHA256(key = seed, "STORM-DRBG|" || u64be(j)); * the words, in order, are cut into big-endian 64-bit values. */ export class Drbg { readonly draws: [number, number][] = []; private j = 0; private buffer: Buffer = Buffer.alloc(0); constructor(private readonly seed: Uint8Array) {} private u64(): bigint { if (this.buffer.length < 8) { const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(this.j)); this.j += 1; this.buffer = Buffer.concat([this.buffer, createHmac("sha256", this.seed).update(Buffer.concat([Buffer.from("STORM-DRBG|"), counter])).digest()]); } const value = this.buffer.readBigUInt64BE(0); this.buffer = this.buffer.subarray(8); return value; } /** A whole number from 0 to m-1, every one equally likely: values at or * above the largest multiple of m are thrown away. m is at most 2^53. */ intBelow(m: number | bigint): number { const size = BigInt(m); const limit = TWO_64 - (TWO_64 % size); for (;;) { const value = this.u64(); if (value < limit) { const out = Number(value % size); this.draws.push([Number(size), out]); return out; } } } /** Fisher-Yates from the end: for i from the last place down to 1, swap * place i with place int_below(i + 1). */ shuffle(list: T[]): T[] { for (let i = list.length - 1; i > 0; i--) { const j = this.intBelow(i + 1); [list[i], list[j]] = [list[j], list[i]]; } return list; } } // ── The file's tables ──────────────────────────────────────────────────────── export type Action = [string, number?]; type Params = Record; type Tables = Record< string, { tables: Record>> | null; insideBets?: Record; red?: number[]; /** blackjack: what a blackjack pays (x100) at each dial point. */ dialPoints?: Record; /** The played-out engines: the list in the books file, set by the caller. */ rounds?: { pay: number }[]; } >; export interface Round { payX10k: bigint; draws: [number, number][]; /** The same draws, step by step: the start of the round, then each action. One list when the round ran on one seed. */ steps: [number, number][][]; } /** Where a round's draws come from: one generator for the whole round, or one * for the start and a fresh one for each action after it. */ class Source { readonly draws: [number, number][] = []; readonly steps: [number, number][][] = [[]]; private at = 0; private generator: Drbg; constructor(private readonly seeds: string[]) { this.generator = new Drbg(Buffer.from(seeds[0], "hex")); } /** The player acts. With a seed for each step, the next seed's generator takes over. */ step(): void { if (this.seeds.length === 1) return; this.at += 1; if (this.at >= this.seeds.length) throw new Error("more actions than seeds"); this.generator = new Drbg(Buffer.from(this.seeds[this.at], "hex")); this.steps.push([]); } intBelow(m: number | bigint): number { const value = this.generator.intBelow(m); const drawn: [number, number] = [Number(m), value]; this.draws.push(drawn); this.steps[this.steps.length - 1].push(drawn); return value; } shuffle(list: T[]): T[] { for (let i = list.length - 1; i > 0; i--) { const j = this.intBelow(i + 1); [list[i], list[j]] = [list[j], list[i]]; } return list; } } const big = (value: unknown) => BigInt(value as number | string); const range = (n: number, from = 0) => Array.from({ length: n }, (_, i) => i + from); function tableAt(engines: Tables, engine: string, rtp: number, name: string): Record { const table = engines[engine]?.tables?.[String(rtp)]?.[name]; if (!table) throw new Error(`${engine} has no table "${name}" at ${rtp} in the file: it carries 9600, 9750 and 9900`); return table; } const x10k = (engines: Tables, engine: string, rtp: number, name: string) => (tableAt(engines, engine, rtp, name).tableX10k as (number | string)[]).map(big); function choose(n: number, k: number): bigint { let out = BigInt(1); for (let i = 1; i <= k; i++) out = (out * BigInt(n - k + i)) / BigInt(i); return out; } // ── The played-out engines: a round's weight, and the round a draw picks ───── /** The weight of a round that pays `pay` hundredths of the stake, for a feel. */ function bookWeight(pay: number, feel: string): number { let weight = pay < 20_000 ? 1000 : pay < 100_000 ? 200 : 40; if (feel === "small wins often") weight = pay <= 500 ? Math.floor((weight * 13) / 10) : pay >= 2000 ? Math.floor((weight * 6) / 10) : weight; else if (feel === "rare big wins") weight = pay <= 200 ? Math.floor((weight * 7) / 10) : pay >= 2000 ? Math.floor((weight * 16) / 10) : weight; return weight * 1000; } /** The weights of a table: the winning rounds' sum, the one weight every * losing round has (set for the dial and rounded up, so the return is never * above the dial) and the total. */ function bookTable(rounds: { pay: number }[], feel: string, rtp: number): { winning: bigint; each: bigint; total: bigint } { let winning = BigInt(0); let paid = BigInt(0); let losing = 0; for (const round of rounds) { if (round.pay > 0) { const weight = BigInt(bookWeight(round.pay, feel)); winning += weight; paid += weight * BigInt(round.pay); } else losing += 1; } // (paid / 100) / (rtp / 10000) - winning, over the losing rounds: one fraction, rounded up once. const num = paid * BigInt(100) - winning * BigInt(rtp); const den = BigInt(rtp) * BigInt(losing); let each = num / den; if (each * den < num) each += BigInt(1); if (each < BigInt(1)) each = BigInt(1); return { winning, each, total: winning + each * BigInt(losing) }; } // ── The card market: the exact chance that the player hand beats the dealer ── const CARD_VALUE = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]; /** A hand of the card market: its total, how many aces still count 11, and its cards (2 stands for two or more). */ type Dealt = { total: number; soft: number; cards: number }; function dealt(hand: Dealt, rank: number): Dealt { let total = hand.total + CARD_VALUE[rank]; let soft = hand.soft + (rank === 12 ? 1 : 0); while (total > 21 && soft) { total -= 10; soft -= 1; } return { total, soft, cards: Math.min(hand.cards + 1, 2) }; } /** Who gets the next card, or null when the hand is over. */ function nextCard(player: Dealt, dealer: Dealt): "player" | "dealer" | null { if (player.cards < 1) return "player"; if (dealer.cards < 1) return "dealer"; if (player.cards < 2 || player.total < 17) return "player"; if (player.total > 21) return null; if (dealer.cards < 2 || dealer.total < 17) return "dealer"; return null; } const playerBeats = (player: Dealt, dealer: Dealt) => player.total <= 21 && (dealer.total > 21 || player.total > dealer.total); const THIRTEEN = BigInt(13); const yesMemo = new Map(); /** The chance of YES from here, exact, as [n, k]: n over 13 to the power k. */ function yesChance(player: Dealt, dealer: Dealt): [bigint, number] { const key = `${player.total},${player.soft},${player.cards},${dealer.total},${dealer.soft},${dealer.cards}`; const known = yesMemo.get(key); if (known) return known; const who = nextCard(player, dealer); let out: [bigint, number]; if (!who) out = [BigInt(playerBeats(player, dealer) ? 1 : 0), 0]; else { const parts = range(13).map((rank) => (who === "player" ? yesChance(dealt(player, rank), dealer) : yesChance(player, dealt(dealer, rank)))); const power = Math.max(...parts.map(([, k]) => k)); out = [parts.reduce((sum, [n, k]) => sum + n * THIRTEEN ** BigInt(power - k), BigInt(0)), power + 1]; } yesMemo.set(key, out); return out; } // ── The poker markets: a hand's value, and on how many boards each outcome happens ── function straightHigh(ranks: number): number { for (let high = 12; high >= 4; high--) if (((ranks >> (high - 4)) & 0x1f) === 0x1f) return high; return (ranks & 0x100f) === 0x100f ? 3 : -1; } /** The n highest ranks of a set, four bits each, the highest first. */ function topRanks(ranks: number, n: number): number { let value = 0; let left = n; for (let rank = 12; rank >= 0 && left > 0; rank--) if (ranks & (1 << rank)) { value = (value << 4) | rank; left -= 1; } return value << (4 * left); } /** The value of the best five of some cards (five or seven): a higher number is a better hand, equal numbers tie. */ function handValue(cards: number[]): number { const bySuit = [0, 0, 0, 0]; const suited = [0, 0, 0, 0]; const count = new Array(13).fill(0); let all = 0; for (const card of cards) { const rank = card % 13; const suit = Math.floor(card / 13); bySuit[suit] |= 1 << rank; suited[suit] += 1; count[rank] += 1; all |= 1 << rank; } for (let suit = 0; suit < 4; suit++) if (suited[suit] >= 5) { const high = straightHigh(bySuit[suit]); if (high >= 0) return (8 << 20) | high; } let four = -1; let three = -1; let three2 = -1; let pair = -1; let pair2 = -1; for (let rank = 12; rank >= 0; rank--) { if (count[rank] === 4) four = rank; else if (count[rank] === 3) { if (three < 0) three = rank; else if (three2 < 0) three2 = rank; } else if (count[rank] === 2) { if (pair < 0) pair = rank; else if (pair2 < 0) pair2 = rank; } } if (four >= 0) return (7 << 20) | (four << 4) | topRanks(all & ~(1 << four), 1); if (three >= 0 && (three2 >= 0 || pair >= 0)) return (6 << 20) | (three << 4) | Math.max(three2, pair); for (let suit = 0; suit < 4; suit++) if (suited[suit] >= 5) return (5 << 20) | topRanks(bySuit[suit], 5); const high = straightHigh(all); if (high >= 0) return (4 << 20) | high; if (three >= 0) return (3 << 20) | (three << 8) | topRanks(all & ~(1 << three), 2); if (pair >= 0 && pair2 >= 0) return (2 << 20) | (pair << 8) | (pair2 << 4) | topRanks(all & ~(1 << pair) & ~(1 << pair2), 1); if (pair >= 0) return (1 << 20) | (pair << 12) | topRanks(all & ~(1 << pair), 3); return topRanks(all, 5); } /** A hand's best five on a full board: any five of seven in hold'em; in Omaha exactly two of its own four and three of the board. */ function bestOn(hand: number[], board: number[]): number { if (hand.length === 2) return handValue([hand[0], hand[1], ...board]); let best = 0; for (let i = 0; i < hand.length; i++) for (let j = i + 1; j < hand.length; j++) for (let x = 0; x < 5; x++) for (let y = x + 1; y < 5; y++) for (let z = y + 1; z < 5; z++) { const value = handValue([hand[i], hand[j], board[x], board[y], board[z]]); if (value > best) best = value; } return best; } /** Over every way the board can still be completed: on how many each hand alone is best, on how many there is a tie for best, and how many there are. */ function boardCounts(hands: number[][], board: number[]): number[] { const out = [0, 0, 0, 0, 0]; const used = new Set([...hands.flat(), ...board]); const deck = range(52).filter((card) => !used.has(card)); const full = [...board]; const walk = (from: number) => { if (full.length === 5) { const values = hands.map((hand) => bestOn(hand, full)); const top = Math.max(...values); const best = values.filter((value) => value === top).length; out[best === 1 ? values.indexOf(top) : 3] += 1; out[4] += 1; return; } for (let i = from; i < deck.length; i++) { full.push(deck[i]); walk(i + 1); full.pop(); } }; walk(0); return out; } const POKER_SIDES = ["p1", "p2", "p3", "push"]; // ── Counter Attack's chances, in ten-thousandths ───────────────────────────── const SHOT = [3000, 3600, 4200, 5000, 5800, 6700, 7700, 8800]; const DRIBBLE: Record = { open: [7500, 7200, 7000, 6700, 6400, 6000, 5500], high: [6500, 6200, 5800, 5400, 5000, 4600, 4200], low: [5000, 4700, 4400, 4000, 3600, 3200, 2800] }; // ── One round ──────────────────────────────────────────────────────────────── /** * Plays one whole round and returns what it pays and every draw it made. * `engines` is the `engines` object of rain-engines.json. `rtp` is the dial in * basis points (roulette ignores it). `actions` are the player's choices in * order, for the engines that take any. `seed` is one seed in hex for the * whole round, or a list: one for the start and one for each action. */ export function play(engines: Tables, engine: string, params: Params, rtp: number, seed: string | string[], actions: Action[] = []): Round { const draw = new Source(typeof seed === "string" ? [seed] : seed); const R = BigInt(rtp); const done = (payX10k: bigint | number): Round => ({ payX10k: BigInt(payX10k), draws: draw.draws, steps: draw.steps }); switch (engine) { case "dice": { const target = Number(params.target ?? 5000); const roll = draw.intBelow(10_000); const win = params.over ? roll >= 10_000 - target : roll < target; return done(win ? (R * BigInt(10_000)) / BigInt(target) : 0); } case "limbo": { const target = BigInt(Number(params.targetX100 ?? 200)); const r = draw.intBelow(1_000_000_000); const top = BigInt(100_000_000); const reached = (R * BigInt(10_000_000)) / BigInt(r + 1); const result = reached < top ? reached : top; return done(result >= target ? target * BigInt(100) : 0); } case "coin": { return done(draw.intBelow(2) === Number(params.side ?? 0) ? R * BigInt(2) : 0); } case "roulette": { const inside = engines.roulette.insideBets ?? {}; const red = new Set(engines.roulette.red ?? []); const one = (bet: string, sel: number, n: number): number => { if (bet === "straight") return n === sel ? 360_000 : 0; if (bet === "red") return red.has(n) ? 20_000 : 0; if (bet === "black") return n !== 0 && !red.has(n) ? 20_000 : 0; if (bet === "odd") return n % 2 === 1 ? 20_000 : 0; if (bet === "even") return n !== 0 && n % 2 === 0 ? 20_000 : 0; if (bet === "low") return n >= 1 && n <= 18 ? 20_000 : 0; if (bet === "high") return n >= 19 ? 20_000 : 0; if (bet === "dozen") return n !== 0 && Math.floor((n - 1) / 12) === sel ? 30_000 : 0; if (bet === "column") return n !== 0 && (n - 1) % 3 === sel ? 30_000 : 0; const numbers = inside[bet]?.[sel]; if (!numbers) throw new Error(`roulette has no bet ${bet} ${sel}`); return numbers.includes(n) ? Math.floor(360_000 / numbers.length) : 0; }; const n = draw.intBelow(37); const bets = params.bets as [string, number, number][] | undefined; if (!bets) return done(one(String(params.bet ?? "red"), Number(params.sel ?? 0), n)); const units = bets.reduce((sum, bet) => sum + bet[2], 0); return done(Math.floor(bets.reduce((sum, [bet, sel, share]) => sum + share * one(bet, sel, n), 0) / units)); } case "slots": case "scratch": { const rows = tableAt(engines, engine, rtp, String(params.feel ?? "balanced")).rows as { pays: number; weight: number }[]; const r = draw.intBelow(10_000_000); let running = 0; for (const row of rows) { running += row.weight; if (r < running) return done(row.pays * 10_000); } return done(0); } case "slots (books)": case "scratch (books)": { const rounds = engines[engine]?.rounds; if (!rounds) throw new Error(`${engine} needs its rounds: load the file named under "books" and set engines["${engine}"].rounds to its list`); const feel = String(params.feel ?? "balanced"); const weights = bookTable(rounds, feel, rtp); const stated = tableAt(engines, engine, rtp, feel); if (big(stated.weightTotal) !== weights.total || big(stated.losingWeightEach) !== weights.each) throw new Error(`${engine}: the weights worked out from the rounds are not the table's`); const r = BigInt(draw.intBelow(weights.total)); // The winning rounds in file order, then the losing rounds in file order. if (r < weights.winning) { let running = BigInt(0); for (const round of rounds) { if (round.pay <= 0) continue; running += BigInt(bookWeight(round.pay, feel)); if (r < running) return done(round.pay * 100); } } return done(0); } case "blackjack": { const points = engines.blackjack.dialPoints ?? {}; const point = Math.max(...Object.keys(points).map(Number).filter((bps) => bps <= rtp)); const blackjackPays = points[String(point)].blackjackPaysX100; const value = (cards: number[]): number => { let total = 0; let aces = 0; for (const card of cards) { const rank = card % 13; if (rank === 12) { total += 11; aces += 1; } else total += rank >= 8 ? 10 : rank + 2; } while (total > 21 && aces) { total -= 10; aces -= 1; } return total; }; // The shoe: six copies of each card. A card is drawn when it is shown, from the cards left, listed in rising // order of card number with copies side by side. const left = range(52).map(() => 6); const count = (weight: (card: number) => number) => range(52).reduce((sum, card) => sum + weight(card), 0); const at = (r: number, weight: (card: number) => number): number => { for (let card = 0; card < 52; card++) { const w = weight(card); if (r < w) return card; r -= w; } throw new Error("no card left"); }; const plain = () => { const card = at(draw.intBelow(count((c) => left[c])), (c) => left[c]); left[card] -= 1; return card; }; const first = plain(); const up = plain(); let hands = [{ cards: [first, plain()], bet: 1, done: false }]; // What the hidden card cannot be once the dealer has looked and play went on: ten-valued under an ace, an ace under a ten-valued card. let looked = false; let turned = false; const barred = (card: number) => looked && !turned && (up % 13 === 12 ? card % 13 >= 8 && card % 13 <= 11 : card % 13 === 12); // A card to the player or the dealer. While a looked-at hidden card lies on the table, card x weighs // (copies of x left) x (the cards the hidden one could still be if x is dealt). const take = () => { if (!looked || turned) return plain(); const n = count((c) => left[c]); const b = n - count((c) => (barred(c) ? left[c] : 0)); const weight = (c: number) => left[c] * (b - (barred(c) ? 0 : 1)); const card = at(draw.intBelow(b * (n - 1)), weight); left[card] -= 1; return card; }; // The hidden card, drawn when it is turned, from the cards left that agree with the look. const hole = () => { const weight = (c: number) => (barred(c) ? 0 : left[c]); const card = at(draw.intBelow(count(weight)), weight); left[card] -= 1; turned = true; return card; }; // The look: the dealer shows a ten or an ace. One draw; a card that makes blackjack is the hidden card and ends the round, any other stays in the shoe. if (up % 13 >= 8) { const seen = at(draw.intBelow(count((c) => left[c])), (c) => left[c]); if (value([up, seen]) === 21) return done(value(hands[0].cards) === 21 ? 10_000 : 0); looked = true; } if (value(hands[0].cards) === 21) { hole(); return done(10_000 + blackjackPays * 100); } let active = 0; for (const [action] of actions) { draw.step(); const hand = hands[active]; if (action === "hit") { hand.cards.push(take()); if (value(hand.cards) >= 21) hand.done = true; } else if (action === "stand") hand.done = true; else if (action === "double") { hand.bet = 2; hand.cards.push(take()); hand.done = true; } else if (action === "split") { const [first, second] = hand.cards; const aces = first % 13 === 12; const one = { cards: [first, take()], bet: 1, done: aces }; const two = { cards: [second, take()], bet: 1, done: aces }; hands = [one, two]; for (const split of hands) if (value(split.cards) === 21) split.done = true; } else throw new Error(`blackjack has no action ${action}`); while (active < hands.length && hands[active].done) active += 1; if (active < hands.length) continue; // Every hand is done: the hidden card is turned, the dealer draws to 17 if any hand is still in, and each hand is settled. const dealer = [up, hole()]; if (hands.some((one) => value(one.cards) <= 21)) while (value(dealer) < 17) dealer.push(take()); const against = value(dealer); let units = 0; for (const one of hands) { const mine = value(one.cards); if (mine > 21) continue; if (against > 21 || mine > against) units += 2 * one.bet; else if (mine === against) units += one.bet; } return done(units * 10_000); } throw new Error("the round did not end"); } case "card_market": { const million = BigInt(1_000_000); let player: Dealt = { total: 0, soft: 0, cards: 0 }; let dealer: Dealt = { total: 0, soft: 0, cards: 0 }; let position: { yes: boolean; ppm: bigint } | null = null; // The price of a side now, as a fraction: n over d. const price = (yes: boolean): [bigint, bigint] => { const [n, k] = yesChance(player, dealer); const d = THIRTEEN ** BigInt(k); return [yes ? n : d - n, d]; }; for (const [action] of actions) { draw.step(); if (action === "buy_yes" || action === "buy_no") { const [n, d] = price(action === "buy_yes"); position = { yes: action === "buy_yes", ppm: (n * million) / d }; } else if (action === "sell") { if (!position) throw new Error("nothing to sell"); const [n, d] = price(position.yes); return done((R * n * million) / (d * position.ppm)); } else if (action === "next") { const who = nextCard(player, dealer); const rank = draw.intBelow(13); if (who === "player") player = dealt(player, rank); else dealer = dealt(dealer, rank); if (nextCard(player, dealer)) continue; if (!position) return done(10_000); return done(position.yes === playerBeats(player, dealer) ? (R * million) / position.ppm : 0); } else throw new Error(`the card market has no action ${action}`); } throw new Error("the round did not end"); } case "holdem_market": case "omaha_market": { const size = engine === "holdem_market" ? 2 : 4; // The cards left, in rising order; one is taken at the place drawn. The hands are dealt and shown at the start; no board card is drawn before its street. const left = range(52); const take = () => left.splice(draw.intBelow(left.length), 1)[0]; const hands = range(3).map(() => range(size).map(() => take())); const board: number[] = []; // The position: the outcome, and the n boards of d it won on when it was bought. let position: { side: number; n: bigint; d: bigint } | null = null; for (const [action] of actions) { draw.step(); if (action.startsWith("buy_")) { const side = POKER_SIDES.indexOf(action.slice(4)); if (side < 0) throw new Error(`no outcome ${action.slice(4)}`); const counts = boardCounts(hands, board); position = { side, n: BigInt(counts[side]), d: BigInt(counts[4]) }; } else if (action === "sell") { if (!position) throw new Error("nothing to sell"); const counts = boardCounts(hands, board); return done((R * BigInt(counts[position.side]) * position.d) / (BigInt(counts[4]) * position.n)); } else if (action === "next") { const more = board.length ? 1 : 3; for (let i = 0; i < more; i++) board.push(take()); if (board.length < 5) continue; if (!position) return done(10_000); return done(boardCounts(hands, board)[position.side] === 1 ? (R * position.d) / position.n : 0); } else throw new Error(`the market has no action ${action}`); } throw new Error("the round did not end"); } case "plinko": { const rows = Number(params.rows ?? 12); const table = x10k(engines, "plinko", rtp, `${String(params.risk ?? "medium")}/${rows}`); const bits = draw.intBelow(BigInt(1) << BigInt(rows)); const slot = range(rows).filter((i) => Math.floor(bits / 2 ** i) % 2 === 1).length; return done(table[slot]); } case "spin": { const segments = Number(params.segments ?? 10); const table = x10k(engines, "spin", rtp, `${String(params.risk ?? "medium")}/${segments}`); return done(table[draw.intBelow(segments)]); } case "keno": { const picks = params.picks as number[]; const table = x10k(engines, "keno", rtp, `${String(params.risk ?? "classic")}/${picks.length}`); const drawn = new Set(draw.shuffle(range(40, 1)).slice(0, 10)); return done(table[picks.filter((pick) => drawn.has(pick)).length]); } case "baccarat": { const bet = String(params.bet ?? "player"); const value = (rank: number) => (rank <= 7 ? rank + 2 : rank === 12 ? 1 : 0); const card = () => draw.intBelow(13); const player = [card()]; const banker = [card()]; player.push(card()); banker.push(card()); const total = (hand: number[]) => hand.reduce((sum, rank) => sum + value(rank), 0) % 10; if (total(player) < 8 && total(banker) < 8) { let third: number | null = null; if (total(player) <= 5) { const rank = card(); player.push(rank); third = value(rank); } const b = total(banker); const draws = third === null ? b <= 5 : b <= 2 || (b === 3 && third !== 8) || (b === 4 && third >= 2 && third <= 7) || (b === 5 && third >= 4 && third <= 7) || (b === 6 && (third === 6 || third === 7)); if (draws) banker.push(card()); } const pays = big(tableAt(engines, "baccarat", rtp, bet).paysX10k); if (bet === "player_pair") return done(player[0] === player[1] ? pays : 0); if (bet === "banker_pair") return done(banker[0] === banker[1] ? pays : 0); const outcome = total(player) > total(banker) ? "player" : total(banker) > total(player) ? "banker" : "tie"; return done(outcome === bet ? pays : outcome === "tie" ? 10_000 : 0); } case "tower": case "coinstreak": { const steps = Number(params.steps ?? (engine === "tower" ? 8 : 10)); const tiles = engine === "tower" && params.tiles != null ? Number(params.tiles) : 0; const safe = tiles ? Number(params.safe ?? tiles - 1) : 0; const ppm = engine === "coinstreak" ? 500_000 : Number(params.p_ppm ?? 666_667); // What k steps won are worth: the dial over the chance of getting there. const prize = (k: number): bigint => { if (engine === "coinstreak") return R * BigInt(2) ** BigInt(k); if (tiles) return (R * BigInt(tiles) ** BigInt(k)) / BigInt(safe) ** BigInt(k); return (R * BigInt(10) ** BigInt(6 * k)) / BigInt(ppm) ** BigInt(k); }; let k = 0; for (const [action, tile] of actions) { draw.step(); if (action === "cashout") return done(prize(k)); const won = tiles ? draw.shuffle(range(tiles)).slice(0, safe).includes(tile ?? 0) : draw.intBelow(1_000_000) < ppm; if (!won) return done(0); k += 1; if (k >= steps) return done(prize(k)); } throw new Error("the round did not end"); } case "mines": { const mines = Number(params.mines ?? 3); const prize = (k: number) => (R * choose(25, k)) / choose(25 - mines, k); const opened: number[] = []; // Where the mines not found lie, drawn for the picture when the round ends: it changes no pay. const rest = () => draw.shuffle(range(25).filter((tile) => !opened.includes(tile))); let k = 0; for (const [action, tile] of actions) { draw.step(); if (action === "cashout") { rest(); return done(prize(k)); } // No tile holds anything until it is opened: this one is a mine with chance mines / tiles not opened yet. const mine = draw.intBelow(25 - opened.length) < mines; opened.push(tile as number); if (mine) { rest(); return done(0); } k += 1; if (k >= 25 - mines) return done(prize(k)); } throw new Error("the round did not end"); } case "hilo": { // The cards not shown yet, in rising order; one is taken at the place drawn. const left = range(52); const take = () => left.splice(draw.intBelow(left.length), 1)[0]; let shown = take(); // The prize multiple as a fraction: each right guess multiplies it by one over the guess's chance. let num = BigInt(1); let den = BigInt(1); const wins = (guess: string, next: number, rank: number) => (guess === "hi" ? (rank === 0 ? next > rank : next >= rank) : guess === "lo" ? (rank === 12 ? next < rank : next <= rank) : next === rank); for (const [action] of actions) { draw.step(); if (action === "cashout") return done((num * R) / den); if (action === "skip") { shown = take(); continue; } const rank = shown % 13; const cards = left.length; const good = left.filter((card) => wins(action, card % 13, rank)).length; const next = take(); if (!wins(action, next % 13, rank)) return done(0); num *= BigInt(cards); den *= BigInt(good); shown = next; if (left.length < 2) return done((num * R) / den); } throw new Error("the round did not end"); } case "crash": { const two52 = BigInt(1) << BigInt(52); const r = BigInt(draw.intBelow(two52)); const raw = (R * two52 * BigInt(100)) / (BigInt(10_000) * (two52 - r)); const crash = raw < BigInt(100) ? BigInt(100) : raw > BigInt(1_000_000) ? BigInt(1_000_000) : raw; if (actions.length) draw.step(); const [action, at] = actions[0] ?? ["crashed"]; const m = BigInt(at ?? 0); return done(action === "cashout" && m > BigInt(100) && m <= crash ? m * BigInt(100) : 0); } case "counter_attack": { const dribble = DRIBBLE[String(params.mode ?? "open")]; // A goal from a spot pays the dial over (the chance of reaching it x the chance of scoring from it). const prize = (spot: number) => (R * BigInt(10_000) ** BigInt(spot + 1)) / (dribble.slice(0, spot).reduce((product, chance) => product * BigInt(chance), BigInt(1)) * BigInt(SHOT[spot])); let spot = 0; for (const [action] of actions) { draw.step(); const r = draw.intBelow(10_000); if (action === "shoot") return done(r < SHOT[spot] ? prize(spot) : 0); if (r >= dribble[spot]) return done(0); spot += 1; } throw new Error("the round did not end"); } default: throw new Error(`no reference build for ${engine}`); } }