// Back Porch Games: code behind https://backporchgames.com/cribbage/hand-odds/ // File 1: scripts/studies/cribbage-hand-odds.test.ts (run with vitest; writes the JSON the page reads) // File 2: src/games/cribbage/score.ts (the scorer our cribbage game uses; the study calls handTotal) // Free to use with a link to the page above. // ===== File 1: scripts/studies/cribbage-hand-odds.test.ts ===== // Data study: cribbage hand odds, October 2026. Page: /cribbage/hand-odds/ // Rerun (6 to 9 minutes on one core): // npx vitest run --config scripts/studies/vitest.config.ts --silent=false // Writes scripts/studies/cribbage-hand-odds.json. No random numbers anywhere: every count is exact. // // Part 1. Every 4-card hand with every starter: C(52,4) x 48 = 12,994,800 cases, scored as a hand // and as a crib (a crib flush needs all five cards). // Part 2. Every 6-card deal with every starter: C(52,6) x 46 = 936,491,920 cases. For each deal we // try all 15 ways to keep four cards and record // (a) the keep with the best average hand score over the 46 possible starters (crib ignored; // ties go to the first keep in a fixed order), and the score it actually makes, and // (b) the most points any keep would have made once the starter is known (hindsight). // To save time, deals that are the same apart from swapping suits around are scored once and // weighted by how many deals they stand for. Every score comes from handTotal in // src/games/cribbage/score.ts, the scoring file shared by the game and the hand calculator. import { it, expect } from 'vitest'; import { writeFileSync } from 'node:fs'; import { makeDecks, type Card } from '../../src/engine/cards'; import { handTotal } from '../../src/games/cribbage/score'; const deck = makeDecks(1); // index = suitIndex * 13 + (rank - 1) const out: Record = { date: new Date().toISOString().slice(0, 10) }; // the day this run happened const MAX = 30; it('part 1: every 4-card hand and starter', () => { const hand = new Array(MAX).fill(0); const crib = new Array(MAX).fill(0); let n = 0; for (let a = 0; a < 52; a++) for (let b = a + 1; b < 52; b++) for (let c = b + 1; c < 52; c++) for (let d = c + 1; d < 52; d++) { const h = [deck[a], deck[b], deck[c], deck[d]]; for (let s = 0; s < 52; s++) { if (s === a || s === b || s === c || s === d) continue; hand[handTotal(h, deck[s])]++; crib[handTotal(h, deck[s], true)]++; n++; } } expect(n).toBe(12994800); out.part1 = { cases: n, hand, crib }; console.log('part 1', n, JSON.stringify(hand)); }, 3_600_000); // Six cards as four 13-bit rank masks, one per suit. Sorting the masks gives the same key for // every deal that differs only by which suit is which. function key6(idx: number[]): string { const m = [0, 0, 0, 0]; for (const i of idx) m[Math.floor(i / 13)] |= 1 << i % 13; m.sort((x, y) => y - x); return m.join(','); } const KEEPS: number[][] = []; for (let a = 0; a < 6; a++) for (let b = a + 1; b < 6; b++) for (let c = b + 1; c < 6; c++) for (let d = c + 1; d < 6; d++) KEEPS.push([a, b, c, d]); it('part 2: every 6-card deal and starter', () => { // Pass 1: group the 20,358,520 deals. const groups = new Map(); let deals = 0; const idx = [0, 0, 0, 0, 0, 0]; for (idx[0] = 0; idx[0] < 52; idx[0]++) for (idx[1] = idx[0] + 1; idx[1] < 52; idx[1]++) for (idx[2] = idx[1] + 1; idx[2] < 52; idx[2]++) for (idx[3] = idx[2] + 1; idx[3] < 52; idx[3]++) for (idx[4] = idx[3] + 1; idx[4] < 52; idx[4]++) for (idx[5] = idx[4] + 1; idx[5] < 52; idx[5]++) { const k = key6(idx); groups.set(k, (groups.get(k) ?? 0) + 1); deals++; } expect(deals).toBe(20358520); console.log('deals', deals, 'groups', groups.size); const best = new Array(MAX).fill(0); // score of the best-average keep, per (deal, starter) const hind = new Array(MAX).fill(0); // hindsight best score, per (deal, starter) let bestAvgSum = 0; // sum over deals of the best keep's average (x46 later) let cases = 0; const scores = new Int32Array(15 * 46); let done = 0; for (const [k, weight] of groups) { // Rebuild one deal from the key: suit j gets mask j. const masks = k.split(',').map(Number); const cards: Card[] = []; const used = new Set(); masks.forEach((mask, suit) => { for (let r = 0; r < 13; r++) if (mask & (1 << r)) (cards.push(deck[suit * 13 + r]), used.add(suit * 13 + r)); }); const starters = deck.filter((_, i) => !used.has(i)); const keeps = KEEPS.map((kp) => kp.map((i) => cards[i])); for (let q = 0; q < 15; q++) for (let s = 0; s < 46; s++) scores[q * 46 + s] = handTotal(keeps[q], starters[s]); let bq = 0; let bsum = -1; for (let q = 0; q < 15; q++) { let t = 0; for (let s = 0; s < 46; s++) t += scores[q * 46 + s]; if (t > bsum) (bsum = t), (bq = q); } bestAvgSum += weight * bsum; for (let s = 0; s < 46; s++) { best[scores[bq * 46 + s]] += weight; let h = 0; for (let q = 0; q < 15; q++) if (scores[q * 46 + s] > h) h = scores[q * 46 + s]; hind[h] += weight; cases += weight; } if (++done % 100000 === 0) console.log('groups done', done); } expect(cases).toBe(936491920); out.part2 = { deals, groups: groups.size, cases, bestKeep: best, hindsight: hind, bestKeepAverage: bestAvgSum / cases }; console.log('part 2 best', JSON.stringify(best), 'hind', JSON.stringify(hind)); }, 7_200_000); // Part 3. A check behind one sentence on the page: whenever a 29 is possible, is the keep that makes // it among the keeps with the best average? (Brute force over every deal holding three 5s and a jack.) it('part 3: the 29 keep always has the best average', () => { let possible = 0; let notBest = 0; let tied = 0; const idx = [0, 0, 0, 0, 0, 0]; for (idx[0] = 0; idx[0] < 52; idx[0]++) for (idx[1] = idx[0] + 1; idx[1] < 52; idx[1]++) for (idx[2] = idx[1] + 1; idx[2] < 52; idx[2]++) for (idx[3] = idx[2] + 1; idx[3] < 52; idx[3]++) for (idx[4] = idx[3] + 1; idx[4] < 52; idx[4]++) for (idx[5] = idx[4] + 1; idx[5] < 52; idx[5]++) { const cards = idx.map((i) => deck[i]); if (cards.filter((c) => c.rank === 5).length < 3 || !cards.some((c) => c.rank === 11)) continue; const starters = deck.filter((_, i) => !idx.includes(i)); const keeps = KEEPS.map((kp) => kp.map((i) => cards[i])); const sums = keeps.map((kp) => starters.reduce((t, s) => t + handTotal(kp, s), 0)); const top = Math.max(...sums); for (const s of starters) { const sc = keeps.map((kp) => handTotal(kp, s)); if (!sc.includes(29)) continue; possible++; if (!sc.some((x, q) => x === 29 && sums[q] === top)) notBest++; else if (sc.some((x, q) => x !== 29 && sums[q] === top)) tied++; } } expect(possible).toBe(4324); expect(notBest).toBe(0); expect(tied).toBe(132); out.part3 = { possible29: possible, keep29NotBestAverage: notBest, keep29TiedWithAnotherKeep: tied }; console.log('part 3', JSON.stringify(out.part3)); }, 3_600_000); it('write', () => writeFileSync('scripts/studies/cribbage-hand-odds.json', JSON.stringify(out, null, 1) + '\n')); // ===== File 2: src/games/cribbage/score.ts ===== // Cribbage scoring: counting a hand or crib in the show, and the points for each card in the play. // Pure functions, shared by the game, the hand calculator page, the computer player and the tests. // Rules follow the American Cribbage Congress rulebook and pagat.com's six-card cribbage. import type { Card } from '../../engine/cards'; /** A card's count value: ace 1, 2 to 10 as marked, jack, queen and king 10. */ export const value = (c: Card) => Math.min(c.rank, 10); export type ItemKind = 'fifteen' | 'pair' | 'run' | 'flush' | 'nobs'; export interface ScoreItem { kind: ItemKind; cards: Card[]; points: number; } export interface HandScore { total: number; items: ScoreItem[]; } /** * Counts a hand of 4 cards (or a crib) with the starter. * Fifteens: 2 for every different set of cards adding to 15. * Pairs: 2 for every pair (so three of a kind is 6 and four of a kind 12). * Runs: 1 per card for every run of 3 or more (double runs count twice). * Flush: 4 for four hand cards of one suit, 5 if the starter matches too. A crib needs all 5. * Nobs: 1 for the jack of the starter's suit in the hand or crib. */ export function scoreHand(hand: Card[], starter: Card | null, isCrib = false): HandScore { const all = starter ? [...hand, starter] : [...hand]; const items: ScoreItem[] = []; // Fifteens: every subset of two or more cards. const n = all.length; for (let mask = 1; mask < 1 << n; mask++) { let sum = 0; let size = 0; for (let i = 0; i < n; i++) if (mask & (1 << i)) (sum += value(all[i])), size++; if (size >= 2 && sum === 15) items.push({ kind: 'fifteen', cards: all.filter((_, i) => mask & (1 << i)), points: 2 }); } // Pairs. for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (all[i].rank === all[j].rank) items.push({ kind: 'pair', cards: [all[i], all[j]], points: 2 }); // Runs: find the longest stretches of consecutive ranks, then every way to pick one card per rank. const byRank: Card[][] = Array.from({ length: 14 }, () => []); for (const c of all) byRank[c.rank].push(c); let r = 1; while (r <= 13) { if (!byRank[r].length) { r++; continue; } let end = r; while (end + 1 <= 13 && byRank[end + 1].length) end++; const len = end - r + 1; if (len >= 3) { let combos: Card[][] = [[]]; for (let k = r; k <= end; k++) combos = combos.flatMap((pre) => byRank[k].map((c) => [...pre, c])); for (const cards of combos) items.push({ kind: 'run', cards, points: len }); } r = end + 1; } // Flush. if (hand.length === 4 && hand.every((c) => c.suit === hand[0].suit)) { const withStarter = !!starter && starter.suit === hand[0].suit; if (withStarter) items.push({ kind: 'flush', cards: all, points: 5 }); else if (!isCrib) items.push({ kind: 'flush', cards: [...hand], points: 4 }); } // Nobs. if (starter) { const nob = hand.find((c) => c.rank === 11 && c.suit === starter.suit); if (nob) items.push({ kind: 'nobs', cards: [nob], points: 1 }); } return { total: items.reduce((t, i) => t + i.points, 0), items }; } /** Same as scoreHand(...).total but without building the breakdown. Used in tight loops. */ export function handTotal(hand: Card[], starter: Card | null, isCrib = false): number { const all = starter ? [...hand, starter] : hand; const n = all.length; let pts = 0; const vals = all.map(value); for (let mask = 3; mask < 1 << n; mask++) { if ((mask & (mask - 1)) === 0) continue; let sum = 0; for (let i = 0; i < n; i++) if (mask & (1 << i)) sum += vals[i]; if (sum === 15) pts += 2; } const counts = new Array(15).fill(0); for (const c of all) counts[c.rank]++; for (let k = 1; k <= 13; k++) pts += counts[k] * (counts[k] - 1); // n choose 2, times 2 let k = 1; while (k <= 13) { if (!counts[k]) { k++; continue; } let end = k; let mult = counts[k]; while (end + 1 <= 13 && counts[end + 1]) mult *= counts[++end]; const len = end - k + 1; if (len >= 3) pts += len * mult; k = end + 1; } if (hand.length === 4 && hand[1].suit === hand[0].suit && hand[2].suit === hand[0].suit && hand[3].suit === hand[0].suit) { if (starter && starter.suit === hand[0].suit) pts += 5; else if (!isCrib) pts += 4; } if (starter) for (const c of hand) if (c.rank === 11 && c.suit === starter.suit) pts += 1; return pts; } // ---------- the play ---------- export type PegReason = | { kind: 'fifteen' } | { kind: 'thirty-one' } | { kind: 'pair'; n: 2 | 3 | 4 } | { kind: 'run'; n: number }; export interface PegScore { points: number; reasons: PegReason[]; } const PAIR_POINTS = { 2: 2, 3: 6, 4: 12 } as const; /** * Points for the card just played, given every card played since the count last went back to zero * (the last item is the new card) and the new count. */ export function pegScore(series: Card[], count: number): PegScore { const reasons: PegReason[] = []; let points = 0; if (count === 15) { reasons.push({ kind: 'fifteen' }); points += 2; } if (count === 31) { reasons.push({ kind: 'thirty-one' }); points += 2; } const last = series[series.length - 1]; let same = 1; for (let i = series.length - 2; i >= 0 && series[i].rank === last.rank; i--) same++; if (same >= 2) { const n = Math.min(same, 4) as 2 | 3 | 4; reasons.push({ kind: 'pair', n }); points += PAIR_POINTS[n]; } // A run: the last k cards, in any order, are k different consecutive ranks. Take the longest. for (let k = series.length; k >= 3; k--) { const ranks = series.slice(-k).map((c) => c.rank); const lo = Math.min(...ranks); const hi = Math.max(...ranks); if (hi - lo === k - 1 && new Set(ranks).size === k) { reasons.push({ kind: 'run', n: k }); points += k; break; } } return { points, reasons }; }