Overhaul Rummikub with Aunt Rivka's Kitchen theme and match rules

- New baked-canvas art: kitchen room, tiles atlas (incl. colour-blind
  glyphs), teapot, cat, clock, bag, and opponent racks
- Multi-round match system with house rules (opening meld 30/50,
  turn timer + penalty, 1/3/5 rounds or first-to-200)
- AI skill ladder 1–5: greedy sets → table attachment → run splitting →
  local re-solve → whole-table solve + joker holding
- Coach: playable-tile glow, one-liner hints, and "show me" staging
- Undo (Z), save/resume (plain JSON), timeout forfeiture
- Table layout reworked: flow-based set placement, hit-testing,
  self-check in verify harness
- Table talk (Rivka + opponent), round tally, end-of-match score race
- Solver rewritten: planPlay, bestRackSets, attachToTable, localResolve,
  canonicalOrder, setProblem
- verifyRummikub expanded: skill ladder duels, solver time budget,
  layout overlap checks, 789/777 sort, coach assertions
This commit is contained in:
Brian Fertig 2026-12-01 12:41:48 -07:00
parent ad9c58528b
commit e61ec5e363
12 changed files with 3941 additions and 1170 deletions

View File

@ -1,47 +1,109 @@
// Rummikub — heuristic AI. No Phaser, no state mutation. `planTurn` inspects an
// (already-current) engine state and returns a plain plan describing what tiles
// to lay down (and the resulting table arrangement) or a decision to draw. The
// scene applies & animates the plan; the engine validates the commit.
// Rummikub — opponents and the Coach. No Phaser, no state mutation.
// `planTurn` inspects the current engine state and returns a plain plan: the
// tiles to lay down and the resulting table, or a decision to draw. The scene
// animates the plan; the engine validates the commit.
//
// The skill ladder (1–5):
// 1 spots sets on its rack the quick way · often sits on a small play
// 2 finds the best sets its rack can make, and adds tiles to set ends
// 3 … also splits long runs to slip a tile into the middle
// 4 … re-solves nearby sets to fit a tile (the rearrange)
// 5 … wider rearranges, whole-table solves near the end, holds its jokers
// back for when they matter, and never sits on a play when someone is
// about to go out
import { INITIAL_MELD_MIN } from './RummikubData.js';
import { bestMeldDecomposition } from './RummikubSolver.js';
import { planPlay, isValidSet } from './RummikubSolver.js';
import { shortName } from './RummikubData.js';
// Skill 1–5: lower skill is slower, less likely to manipulate the table, and
// adds "noise" (sometimes declines an available meld to draw instead).
const PROFILE = {
1: { delay: [780, 1250], manipulate: false, declineChance: 0.30 },
2: { delay: [680, 1100], manipulate: false, declineChance: 0.18 },
3: { delay: [600, 980], manipulate: false, declineChance: 0.08 },
4: { delay: [500, 860], manipulate: true, declineChance: 0.03 },
5: { delay: [430, 740], manipulate: true, declineChance: 0.0 },
1: { level: 1, decline: 0.3, hold: false },
2: { level: 2, decline: 0.15, hold: false },
3: { level: 3, decline: 0.06, hold: false },
4: { level: 4, decline: 0.02, hold: false },
5: { level: 5, decline: 0, hold: true },
};
function profile(skill) { return PROFILE[Math.max(1, Math.min(5, skill | 0))] || PROFILE[3]; }
export function profile(skill) { return PROFILE[Math.max(1, Math.min(5, Math.round(skill ?? 3)))] ?? PROFILE[3]; }
/** Back-compat: ms of "thinking" (the scene now uses the kit's AITiming). */
export function thinkDelay(skill) {
const [lo, hi] = profile(skill).delay;
return lo + Math.floor(Math.random() * (hi - lo));
const k = Math.max(1, Math.min(5, skill | 0));
return 400 + (5 - k) * 120 + Math.floor(Math.random() * 300);
}
// Returns { type:'commit', tilesPlayed, newTable, firstMeld } or { type:'draw' }.
export function planTurn(state, seat, skill) {
/**
* Returns { type:'commit', tilesPlayed, newTable, firstMeld, points } or { type:'draw' }.
* rand: optional PRNG (the verify harness passes a seeded one).
*/
export function planTurn(state, seat, skill, rand = Math.random) {
const p = profile(skill);
const player = state.players[seat];
const rack = player.rack;
const table = state.table.map((s) => s.slice());
const plan = bestMeldDecomposition(rack, table, {
mustReach: player.hasMelded ? 0 : INITIAL_MELD_MIN,
alreadyMelded: player.hasMelded,
manipulate: p.manipulate,
const threat = state.players.some((q, i) => i !== seat && q.rack.length <= 3);
const plan = planPlay(rack, state.table, {
melded: player.hasMelded, openMin: state.rules?.openMin ?? 30, level: p.level,
holdJokers: p.hold && !threat && state.pool.length > 12,
});
if (!plan || plan.tilesPlayed.length === 0) return { type: 'draw' };
// Low-skill players sometimes sit on a small play and draw instead — but never
// decline a chance to go out.
// Low-skill players sometimes sit on a small play and draw instead — but
// never pass up going out, and never with an empty pool.
const goesOut = plan.tilesPlayed.length === rack.length;
if (!goesOut && Math.random() < p.declineChance) return { type: 'draw' };
return { type: 'commit', tilesPlayed: plan.tilesPlayed, newTable: plan.newTable, firstMeld: plan.firstMeld };
if (!goesOut && state.pool.length > 0 && !threat && rand() < p.decline) return { type: 'draw' };
return { type: 'commit', tilesPlayed: plan.tilesPlayed, newTable: plan.newTable, firstMeld: plan.firstMeld, points: plan.points };
}
// ── The Coach ─────────────────────────────────────────────────────────────────
/**
* The strongest play from the start of the current player's turn (what Aunt
* Rivka would see). Returns null when there's nothing to lay down.
* { tilesPlayed, newTable, firstMeld, points, newSets, attached, rearranged }
*/
export function coachPlan(state) {
const seat = state.currentPlayer;
const ts = state.turnStart;
const plan = planPlay(ts.rack, ts.table, { melded: ts.hasMelded, openMin: state.rules?.openMin ?? 30, level: 5 });
if (!plan || !plan.tilesPlayed.length) return null;
const played = new Set(plan.tilesPlayed);
const origIds = new Set(ts.table.flat().map((t) => t.id));
const newSets = plan.newTable.filter((s) => s.every((t) => played.has(t.id)));
const touched = plan.newTable.filter((s) => s.some((t) => played.has(t.id)) && s.some((t) => origIds.has(t.id)));
const rearranged = ts.table.some((s) => !plan.newTable.some((t) => s.every((x) => t.some((y) => y.id === x.id))));
return { ...plan, seat, newSets, attached: touched, rearranged };
}
const listTiles = (tiles) => tiles.map((t) => shortName(t)).join(' ');
/** A friendly one-liner for the Coach's first nudge. */
export function describePlan(plan, rackSize) {
if (!plan) return null;
const n = plan.tilesPlayed.length;
const out = n === rackSize;
if (plan.firstMeld) {
const parts = plan.newSets.map((s) => (isValidSet(s).kind === 'group' ? `a group of ${s.find((t) => !t.isJoker)?.number}s` : `a ${s.find((t) => !t.isJoker)?.color} run`));
return `You can open with ${plan.points}: ${joinWords(parts)}${out ? ' — and go out!' : '.'}`;
}
const bits = [];
if (plan.newSets.length) bits.push(`${plan.newSets.length === 1 ? 'a new set' : `${plan.newSets.length} new sets`}`);
if (plan.attached.length) bits.push(plan.rearranged ? 'a rearrange on the table' : `tiles onto ${plan.attached.length === 1 ? 'a set' : 'sets'} already down`);
return `There's a play of ${n} tile${n === 1 ? '' : 's'} here — ${joinWords(bits)}${out ? '. That takes you out!' : '.'}`;
}
/** Short tile lists per set ("R4 R5 R6") for the hint panel. */
export function planLines(plan) {
if (!plan) return [];
const played = new Set(plan.tilesPlayed);
return plan.newTable.filter((s) => s.some((t) => played.has(t.id))).map((s) => listTiles(s));
}
function joinWords(parts) {
if (parts.length <= 1) return parts[0] ?? '';
return `${parts.slice(0, -1).join(', ')} and ${parts[parts.length - 1]}`;
}
/**
* Rack tiles that have somewhere to go this turn (the "playable" glow): tiles
* in the Coach's plan. Returns a Set of ids.
*/
export function playableIds(plan) {
return new Set(plan?.tilesPlayed ?? []);
}

View File

@ -0,0 +1,559 @@
// Rummikub art — "Aunt Rivka's Kitchen", Sunday tile night. Everything is
// baked once per page load into canvas textures (no image files).
//
// rk-room butter-yellow kitchen wallpaper with little blue sprigs, a
// window onto the evening street (the cat sits on the sill — its
// tail is a live sprite), a kitchen clock (live hands), a shelf of
// canisters, a fringed pendant lamp over the table; the table
// itself in navy gingham oilcloth with a maple rim, and your
// two-tier walnut rack along the near edge
// rk-tiles atlas: ivory tile faces `${color}-${n}`, colour-blind faces
// `cb-${color}-${n}` (a glyph under the number), 'joker',
// 'cb-joker', 'back'
// rk-shadow soft tile shadow · rk-glow tile outline glow (tinted)
// rk-opprack an opponent's rack ledge (rotated per seat)
// rk-bag the tile pool: a drawstring bag with tiles spilling out
// rk-teapot Rivka's teapot (steam is live)
// rk-tail the cat's tail · rk-clock the clock face
import {
bakeRoom, canvas, rr, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, checks,
} from '../../ui/cardtable/TableArt.js';
import { makeTable, W, H } from '../../ui/cardtable/TableGeometry.js';
import { TILE, TILE_RES, RACK_BOARD, RACK, TABLE } from './RummikubTable.js';
import { COLORS_ORDER, COLOR_HEX } from './RummikubData.js';
export const VIEW = { cx: 960, yFar: 74, yNear: 1024, sFar: 0.8, halfW: 1000, squash: 0.9 };
export const T = makeTable(VIEW, { shape: 'rect', corner: 0.1, feltK: 0.965, faceH: 40 });
export const WINDOW = { x0: 456, x1: 742, y1: 70 };
export const CAT = { x: 690, y: 66 }; // where the cat sits on the sill
export const CLOCK = { x: 826, y: 36, r: 27 };
export const LAMP = { x: 960, y: 30 };
export const TEAPOT = { x: 1712, y: 318 };
export const CUP = { x: 1668, y: 470 };
const SERIF = 'Georgia, "Times New Roman", serif';
const TW = TILE.w * TILE_RES, TH = TILE.h * TILE_RES;
function seeded(seed) {
let s = seed;
return () => { s = (s * 16807) % 2147483647; return s / 2147483647; };
}
// ── The room ─────────────────────────────────────────────────────────────────
function wallpaper(ctx) {
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, '#e9cf86');
g.addColorStop(1, '#b8954e');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
// little blue sprigs, in a half-drop repeat
const rnd = seeded(41);
for (let y = 10; y < H; y += 46) {
for (let x = (Math.floor(y / 46) % 2) * 34; x < W + 40; x += 68) {
const cx = x + rnd() * 4, cy = y + rnd() * 4;
ctx.strokeStyle = 'rgba(70,110,80,0.35)';
ctx.lineWidth = 1.4;
ctx.beginPath(); ctx.moveTo(cx, cy + 9); ctx.quadraticCurveTo(cx + 3, cy + 3, cx, cy - 4); ctx.stroke();
for (const [dx, dy] of [[-4, -5], [4, -4], [0, -9]]) {
ctx.beginPath(); ctx.arc(cx + dx, cy + dy, 2.6, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(60,100,170,0.38)'; ctx.fill();
}
}
}
// a painted dado rail low on the wall
ctx.fillStyle = 'rgba(255,255,255,0.18)';
ctx.fillRect(0, 300, W, 4);
ctx.fillStyle = noisePattern(ctx, 128, 12);
ctx.fillRect(0, 0, W, H);
}
function windowAtNight(ctx) {
const { x0, x1, y1 } = WINDOW;
const sky = ctx.createLinearGradient(0, 0, 0, y1);
sky.addColorStop(0, '#161a3a'); sky.addColorStop(1, '#3a3a6a');
ctx.fillStyle = sky;
ctx.fillRect(x0, 0, x1 - x0, y1);
// the building across the street, a few lit windows
ctx.fillStyle = '#20202e';
ctx.fillRect(x0, 22, 120, y1 - 22);
ctx.fillRect(x0 + 170, 34, 116, y1 - 34);
const lit = [[x0 + 14, 30], [x0 + 52, 30], [x0 + 90, 46], [x0 + 186, 44], [x0 + 248, 44]];
for (const [x, y] of lit) {
ctx.fillStyle = 'rgba(255,214,120,0.85)';
ctx.fillRect(x, y, 12, 9);
}
// the moon
ctx.fillStyle = 'rgba(255,248,220,0.92)';
ctx.beginPath(); ctx.arc(x0 + 150, 16, 8, 0, Math.PI * 2); ctx.fill();
// mullions & frame (cream paint)
ctx.fillStyle = '#f2ead6';
ctx.fillRect(x0 - 9, 0, 9, y1 + 6); ctx.fillRect(x1, 0, 9, y1 + 6);
ctx.fillRect((x0 + x1) / 2 - 3, 0, 6, y1);
ctx.fillRect(x0, 34, x1 - x0, 4);
// the sill
ctx.fillStyle = '#e6dcc4';
ctx.fillRect(x0 - 20, y1 - 2, x1 - x0 + 40, 8);
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.fillRect(x0 - 20, y1 + 6, x1 - x0 + 40, 3);
// café curtains, gathered at the sides, a gingham trim
for (const side of [-1, 1]) {
const cx = side < 0 ? x0 + 30 : x1 - 30;
for (let i = 0; i < 5; i++) {
const g = ctx.createLinearGradient(cx - 26, 0, cx + 26, 0);
g.addColorStop(0, 'rgba(250,246,236,0.25)'); g.addColorStop(0.5, 'rgba(250,246,236,0.85)'); g.addColorStop(1, 'rgba(250,246,236,0.25)');
ctx.fillStyle = g;
ctx.fillRect(cx - 30 + i * 8 * side, 0, 18, y1 - 4);
}
}
ctx.fillStyle = 'rgba(46,82,120,0.85)';
for (let x = x0; x < x1; x += 12) ctx.fillRect(x, 0, 6, 5);
// the cat on the sill (a silhouette; its tail is live)
const { x, y } = CAT;
ctx.fillStyle = '#1a1612';
ctx.beginPath(); ctx.ellipse(x, y - 14, 15, 14, 0, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(x + 2, y - 33, 9, 0, Math.PI * 2); ctx.fill();
poly(ctx, [{ x: x - 5, y: y - 38 }, { x: x - 3, y: y - 48 }, { x: x + 2, y: y - 40 }]); ctx.fill();
poly(ctx, [{ x: x + 4, y: y - 40 }, { x: x + 9, y: y - 48 }, { x: x + 10, y: y - 37 }]); ctx.fill();
ctx.fillStyle = 'rgba(240,210,90,0.9)';
ctx.beginPath(); ctx.arc(x - 1, y - 34, 1.4, 0, Math.PI * 2); ctx.arc(x + 5, y - 34, 1.4, 0, Math.PI * 2); ctx.fill();
}
function shelf(ctx) {
// a painted shelf with canisters and a sprig in a jar (top right)
const x0 = 1592, x1 = 1904, y = 92;
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.fillRect(x0 + 4, y + 8, x1 - x0, 6);
ctx.fillStyle = '#f0e6cc';
ctx.fillRect(x0, y, x1 - x0, 9);
const cans = [[1612, 52, '#c8302a', 'FLOUR'], [1660, 40, '#1f62b0', 'SUGAR'], [1706, 30, '#e07a10', 'TEA']];
for (const [x, h, c, label] of cans) {
ctx.fillStyle = c;
rr(ctx, x, y - h, 40, h, 5); ctx.fill();
ctx.fillStyle = '#f6efdb';
ctx.fillRect(x + 4, y - h * 0.62, 32, 12);
ctx.font = 'bold 9px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = c; ctx.fillText(label, x + 20, y - h * 0.62 + 6);
ctx.fillStyle = 'rgba(255,255,255,0.25)'; ctx.fillRect(x + 5, y - h + 4, 5, h - 8);
}
// a jar of dill and a little framed photo
ctx.fillStyle = 'rgba(210,230,220,0.55)';
rr(ctx, 1770, y - 34, 26, 34, 4); ctx.fill();
ctx.strokeStyle = '#5a8a3a'; ctx.lineWidth = 1.6;
for (let i = 0; i < 6; i++) { ctx.beginPath(); ctx.moveTo(1783, y - 20); ctx.lineTo(1772 + i * 5, y - 52 - (i % 2) * 6); ctx.stroke(); }
ctx.fillStyle = '#7a5a30'; rr(ctx, 1820, y - 46, 46, 46, 3); ctx.fill();
ctx.fillStyle = '#d8c8a0'; ctx.fillRect(1826, y - 40, 34, 34);
ctx.fillStyle = '#8a7a60';
ctx.beginPath(); ctx.arc(1843, y - 28, 7, 0, Math.PI * 2); ctx.fill();
ctx.fillRect(1832, y - 18, 22, 12);
}
function pendantCord(ctx) {
ctx.strokeStyle = '#2a2018';
ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(LAMP.x, 0); ctx.lineTo(LAMP.x, LAMP.y - 18); ctx.stroke();
}
function wall(ctx) {
wallpaper(ctx);
windowAtNight(ctx);
shelf(ctx);
// the clock's wooden surround (face + hands are live)
ctx.fillStyle = '#7a4a22';
ctx.beginPath(); ctx.arc(CLOCK.x, CLOCK.y, CLOCK.r + 6, 0, Math.PI * 2); ctx.fill();
pendantCord(ctx);
// evening: dim the walls a touch
ctx.fillStyle = 'rgba(20,12,4,0.28)';
ctx.fillRect(0, 0, W, H);
// the linoleum floor at the very bottom
const f = ctx.createLinearGradient(0, 1000, 0, H);
f.addColorStop(0, '#5a4a3a'); f.addColorStop(1, '#2a2018');
ctx.fillStyle = f;
ctx.fillRect(0, 1000, W, H - 1000);
}
function front(ctx, Tb) {
frontBands(ctx, Tb, ['#c08a50', '#a87440', '#8c5e32', '#6e4824', '#4e3218'], { grooves: [0.45] });
}
function rim(ctx, Tb) {
rimBand(ctx, Tb, { base: '#b07a44', dark: '#4a2c10', light: '#f0c88a', grain: ['#5a3412', '#f6d4a0'], gloss: 1.4 });
}
function oilcloth(ctx, Tb) {
ctx.fillStyle = '#284a68';
ctx.fillRect(0, 0, W, H);
// navy gingham: a soft, low-contrast check so the tiles pop
checks(ctx, Tb, { cell: 0.05, colors: ['#1d3a56', '#27496a', '#33597c'], aspect: 0.6 });
// a faint printed sprig in the light squares
ctx.fillStyle = noisePattern(ctx, 200, 20);
ctx.fillRect(0, 0, W, H);
// oilcloth sheen
const sheen = ctx.createLinearGradient(0, 0, W, H);
sheen.addColorStop(0, 'rgba(255,255,255,0.05)'); sheen.addColorStop(0.5, 'rgba(255,255,255,0)'); sheen.addColorStop(1, 'rgba(255,255,255,0.04)');
ctx.fillStyle = sheen;
ctx.fillRect(0, 0, W, H);
lampPool(ctx, Tb, { color: '255,220,160', alpha: 0.34, vignette: 0.55, at: { u: 0, v: 0.42 } });
rimShadow(ctx, Tb, 0.4);
}
function onTop(ctx) {
// a faint chalk-line frame where the sets go
ctx.save();
ctx.setLineDash([10, 8]);
ctx.strokeStyle = 'rgba(230,220,190,0.14)';
ctx.lineWidth = 2;
rr(ctx, TABLE.x0 - 16, TABLE.y0 - 16, TABLE.x1 - TABLE.x0 + 32, TABLE.y1 - TABLE.y0 + 24, 18);
ctx.stroke();
ctx.restore();
// a saucer under where the cup sits
ctx.save();
ctx.translate(CUP.x, CUP.y + 8);
ctx.scale(1, 0.55);
ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = 10; ctx.shadowOffsetY = 6;
ctx.beginPath(); ctx.arc(0, 0, 40, 0, Math.PI * 2); ctx.fillStyle = '#f4efe2'; ctx.fill();
ctx.shadowColor = 'transparent';
ctx.strokeStyle = '#2f6fb0'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(0, 0, 34, 0, Math.PI * 2); ctx.stroke();
ctx.restore();
// the cup
ctx.save();
ctx.translate(CUP.x, CUP.y);
ctx.fillStyle = '#f4efe2';
ctx.beginPath(); ctx.moveTo(-22, -16); ctx.lineTo(22, -16); ctx.quadraticCurveTo(20, 14, 0, 16); ctx.quadraticCurveTo(-20, 14, -22, -16); ctx.fill();
ctx.strokeStyle = '#f4efe2'; ctx.lineWidth = 5; ctx.beginPath(); ctx.arc(26, -4, 8, -1.2, 1.2); ctx.stroke();
ctx.fillStyle = '#7a3e18'; ctx.beginPath(); ctx.ellipse(0, -16, 20, 6, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#2f6fb0'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(-18, -6); ctx.lineTo(18, -6); ctx.stroke();
ctx.restore();
}
/** Your two-tier walnut rack along the near edge. */
function humanRack(ctx) {
const { x0, x1, y0, y1 } = RACK_BOARD;
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 22; ctx.shadowOffsetY = 10;
rr(ctx, x0, y0, x1 - x0, y1 - y0, 16);
const g = ctx.createLinearGradient(0, y0, 0, y1);
g.addColorStop(0, '#6a4424'); g.addColorStop(1, '#3a2210');
ctx.fillStyle = g; ctx.fill();
ctx.restore();
// wood grain
ctx.save();
rr(ctx, x0, y0, x1 - x0, y1 - y0, 16); ctx.clip();
const rnd = seeded(7);
ctx.globalAlpha = 0.18;
for (let i = 0; i < 40; i++) {
const y = y0 + rnd() * (y1 - y0);
ctx.strokeStyle = rnd() < 0.5 ? '#2a1606' : '#a07040';
ctx.lineWidth = 1 + rnd() * 1.5;
ctx.beginPath(); ctx.moveTo(x0, y);
for (let x = x0; x <= x1; x += 60) ctx.lineTo(x, y + Math.sin(x * 0.01 + i) * 3);
ctx.stroke();
}
ctx.globalAlpha = 1;
ctx.restore();
// the two ledges the tiles stand on
for (const ry of RACK.rows) {
const ly = ry + TILE.h / 2 + 2;
const lg = ctx.createLinearGradient(0, ly - 4, 0, ly + 12);
lg.addColorStop(0, '#c08a50'); lg.addColorStop(0.4, '#8a5a2c'); lg.addColorStop(1, '#3a2210');
ctx.fillStyle = lg;
rr(ctx, x0 + 10, ly - 4, x1 - x0 - 20, 14, 6); ctx.fill();
ctx.fillStyle = 'rgba(0,0,0,0.35)';
ctx.fillRect(x0 + 14, ly - 6 - TILE.h, x1 - x0 - 28, 3);
}
ctx.strokeStyle = 'rgba(240,200,140,0.5)';
ctx.lineWidth = 2;
rr(ctx, x0 + 3, y0 + 3, x1 - x0 - 6, y1 - y0 - 6, 14); ctx.stroke();
}
function after(ctx) {
humanRack(ctx);
}
// ── Tiles ────────────────────────────────────────────────────────────────────
const EDGE = 10; // the tile's visible side (bottom), in texture px
function tileBody(ctx, x, y, { face = '#f8f1dc', hi = '#fffaf0', side = '#c9b98e' } = {}) {
const w = TW, h = TH, r = 14;
// side (thickness)
rr(ctx, x + 1, y + EDGE, w - 2, h - EDGE, r);
ctx.fillStyle = side; ctx.fill();
// face
rr(ctx, x + 1, y + 1, w - 2, h - EDGE - 2, r);
const g = ctx.createLinearGradient(x, y, x + w * 0.4, y + h);
g.addColorStop(0, hi); g.addColorStop(0.5, face); g.addColorStop(1, mix(face, '#b8a880', 0.35));
ctx.fillStyle = g; ctx.fill();
ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(110,90,50,0.55)'; ctx.stroke();
// bevel highlight
rr(ctx, x + 6, y + 5, w - 12, h - EDGE - 12, r - 4);
ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(255,255,255,0.65)'; ctx.stroke();
}
function glyph(ctx, kind, x, y, s, color) {
ctx.save();
ctx.translate(x, y);
ctx.fillStyle = color;
ctx.strokeStyle = color;
if (kind === 'heart') {
ctx.beginPath();
ctx.moveTo(0, s * 0.8);
ctx.bezierCurveTo(-s * 1.4, -s * 0.2, -s * 0.6, -s * 1.1, 0, -s * 0.35);
ctx.bezierCurveTo(s * 0.6, -s * 1.1, s * 1.4, -s * 0.2, 0, s * 0.8);
ctx.fill();
} else if (kind === 'drop') {
ctx.beginPath();
ctx.moveTo(0, -s);
ctx.quadraticCurveTo(s * 0.9, s * 0.1, 0, s * 0.85);
ctx.quadraticCurveTo(-s * 0.9, s * 0.1, 0, -s);
ctx.fill();
} else if (kind === 'square') {
ctx.fillRect(-s * 0.72, -s * 0.72, s * 1.44, s * 1.44);
} else {
ctx.beginPath(); ctx.arc(0, 0, s * 0.45, 0, Math.PI * 2); ctx.fill();
ctx.lineWidth = s * 0.22;
for (let i = 0; i < 8; i++) {
const a = (i / 8) * Math.PI * 2;
ctx.beginPath(); ctx.moveTo(Math.cos(a) * s * 0.62, Math.sin(a) * s * 0.62); ctx.lineTo(Math.cos(a) * s, Math.sin(a) * s); ctx.stroke();
}
}
ctx.restore();
}
const GLYPHS = { red: 'heart', blue: 'drop', black: 'square', orange: 'sun' };
function numberFace(ctx, x, y, color, n, cb) {
tileBody(ctx, x, y);
const hex = COLOR_HEX[color];
const cx = x + TW / 2;
const faceH = TH - EDGE;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = `bold ${n >= 10 ? 62 : 70}px ${SERIF}`;
// a pressed-in look: light below, colour on top
ctx.fillStyle = 'rgba(255,255,255,0.8)';
ctx.fillText(String(n), cx + 1, y + faceH * (cb ? 0.4 : 0.46) + 2);
ctx.fillStyle = hex;
ctx.fillText(String(n), cx, y + faceH * (cb ? 0.4 : 0.46));
if (cb) glyph(ctx, GLYPHS[color], cx, y + faceH * 0.8, 13, hex);
else {
// the little dot under the number
ctx.beginPath(); ctx.arc(cx, y + faceH * 0.8, 6, 0, Math.PI * 2); ctx.fillStyle = hex; ctx.fill();
}
}
function jokerFace(ctx, x, y, cb) {
tileBody(ctx, x, y);
const cx = x + TW / 2, cy = y + (TH - EDGE) * 0.42;
// a jester's smiling face, four-coloured cap
const cols = [COLOR_HEX.red, COLOR_HEX.blue, COLOR_HEX.orange];
for (let i = 0; i < 3; i++) {
const a = -Math.PI / 2 + (i - 1) * 0.9;
ctx.beginPath();
ctx.moveTo(cx - 20, cy - 12); ctx.quadraticCurveTo(cx + Math.cos(a) * 30, cy - 30 + Math.sin(a) * 10, cx + Math.cos(a) * 34, cy - 18 + Math.sin(a) * 28);
ctx.quadraticCurveTo(cx + Math.cos(a) * 14, cy - 16, cx + 20, cy - 12);
ctx.fillStyle = cols[i]; ctx.fill();
ctx.beginPath(); ctx.arc(cx + Math.cos(a) * 34, cy - 18 + Math.sin(a) * 28, 5, 0, Math.PI * 2); ctx.fillStyle = '#e8b020'; ctx.fill();
}
ctx.beginPath(); ctx.arc(cx, cy + 6, 22, 0, Math.PI * 2); ctx.fillStyle = '#fbe6c8'; ctx.fill();
ctx.lineWidth = 2.5; ctx.strokeStyle = COLOR_HEX.black; ctx.stroke();
ctx.fillStyle = COLOR_HEX.black;
ctx.beginPath(); ctx.arc(cx - 8, cy + 1, 2.8, 0, Math.PI * 2); ctx.arc(cx + 8, cy + 1, 2.8, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(cx, cy + 9, 10, 0.15 * Math.PI, 0.85 * Math.PI); ctx.lineWidth = 2.6; ctx.strokeStyle = COLOR_HEX.red; ctx.stroke();
ctx.font = `bold 17px ${SERIF}`;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = cb ? COLOR_HEX.black : '#8a5a20';
ctx.fillText('JOKER', cx, y + (TH - EDGE) * 0.86);
}
function backFace(ctx, x, y) {
tileBody(ctx, x, y, { face: '#ead8b0', hi: '#f6ead0', side: '#b89a68' });
const cx = x + TW / 2, cy = y + (TH - EDGE) / 2;
// an embossed rosette
ctx.strokeStyle = 'rgba(140,100,50,0.45)';
ctx.lineWidth = 2;
for (let i = 0; i < 8; i++) {
const a = (i / 8) * Math.PI * 2;
ctx.beginPath(); ctx.ellipse(cx + Math.cos(a) * 14, cy + Math.sin(a) * 14, 12, 6, a, 0, Math.PI * 2); ctx.stroke();
}
ctx.beginPath(); ctx.arc(cx, cy, 6, 0, Math.PI * 2); ctx.fillStyle = 'rgba(140,100,50,0.4)'; ctx.fill();
}
function bakeTiles(scene) {
const cols = 14, rows = 9;
const c = canvas(cols * TW, rows * TH);
const ctx = c.getContext('2d');
const frames = [];
COLORS_ORDER.forEach((color, ci) => {
for (let n = 1; n <= 13; n++) {
numberFace(ctx, (n - 1) * TW, ci * TH, color, n, false);
frames.push([`${color}-${n}`, (n - 1) * TW, ci * TH]);
numberFace(ctx, (n - 1) * TW, (ci + 4) * TH, color, n, true);
frames.push([`cb-${color}-${n}`, (n - 1) * TW, (ci + 4) * TH]);
}
});
jokerFace(ctx, 13 * TW, 0, false); frames.push(['joker', 13 * TW, 0]);
jokerFace(ctx, 13 * TW, TH, true); frames.push(['cb-joker', 13 * TW, TH]);
backFace(ctx, 13 * TW, 2 * TH); frames.push(['back', 13 * TW, 2 * TH]);
const tex = scene.textures.addCanvas('rk-tiles', c);
for (const [name, x, y] of frames) tex.add(name, 0, x, y, TW, TH);
}
function bakeShadow(scene) {
const pad = 24;
const c = canvas(TW + pad * 2, TH + pad * 2);
const ctx = c.getContext('2d');
ctx.shadowColor = 'rgba(0,0,0,0.7)';
ctx.shadowBlur = 16;
rr(ctx, pad, pad, TW, TH, 14);
ctx.fillStyle = 'rgba(0,0,0,0.6)';
ctx.fill();
scene.textures.addCanvas('rk-shadow', c);
}
function bakeGlow(scene) {
const pad = 22;
const c = canvas(TW + pad * 2, TH + pad * 2);
const ctx = c.getContext('2d');
ctx.shadowColor = '#ffffff';
ctx.shadowBlur = 16;
rr(ctx, pad, pad, TW, TH - EDGE / 2, 16);
ctx.lineWidth = 7;
ctx.strokeStyle = '#ffffff';
ctx.stroke(); ctx.stroke();
scene.textures.addCanvas('rk-glow', c);
}
function bakeOppRack(scene) {
const w = 640, h = 34;
const c = canvas(w, h);
const ctx = c.getContext('2d');
rr(ctx, 1, 1, w - 2, h - 2, 10);
const g = ctx.createLinearGradient(0, 0, 0, h);
g.addColorStop(0, '#9a6a38'); g.addColorStop(0.5, '#6a4424'); g.addColorStop(1, '#3a2210');
ctx.fillStyle = g; ctx.fill();
ctx.strokeStyle = 'rgba(240,200,140,0.45)'; ctx.lineWidth = 2; ctx.stroke();
scene.textures.addCanvas('rk-opprack', c);
}
function bakeBag(scene) {
const w = 190, h = 190;
const c = canvas(w, h);
const ctx = c.getContext('2d');
const cx = w / 2;
// shadow
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.beginPath(); ctx.ellipse(cx + 6, 158, 78, 22, 0, 0, Math.PI * 2); ctx.fill();
// a velvet drawstring bag, slumped open
ctx.beginPath();
ctx.moveTo(cx - 56, 70);
ctx.bezierCurveTo(cx - 92, 110, cx - 80, 160, cx, 162);
ctx.bezierCurveTo(cx + 80, 160, cx + 92, 110, cx + 56, 70);
ctx.quadraticCurveTo(cx, 54, cx - 56, 70);
const g = ctx.createRadialGradient(cx - 20, 100, 10, cx, 120, 100);
g.addColorStop(0, '#a03048'); g.addColorStop(1, '#4a0c1c');
ctx.fillStyle = g; ctx.fill();
// the opening, tiles inside
ctx.beginPath(); ctx.ellipse(cx, 70, 56, 16, 0, 0, Math.PI * 2);
ctx.fillStyle = '#2a0610'; ctx.fill();
const rnd = seeded(3);
for (let i = 0; i < 7; i++) {
ctx.save();
ctx.translate(cx - 36 + i * 12 + rnd() * 4, 62 + rnd() * 6);
ctx.rotate((rnd() - 0.5) * 0.8);
rr(ctx, -9, -12, 18, 24, 4);
ctx.fillStyle = '#ead8b0'; ctx.fill();
ctx.strokeStyle = 'rgba(120,90,40,0.6)'; ctx.lineWidth = 1; ctx.stroke();
ctx.restore();
}
// gold drawstring
ctx.strokeStyle = '#e8c060'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.ellipse(cx, 78, 58, 15, 0, 0.1, Math.PI - 0.1); ctx.stroke();
ctx.beginPath(); ctx.moveTo(cx + 40, 90); ctx.quadraticCurveTo(cx + 70, 120, cx + 62, 146); ctx.stroke();
ctx.fillStyle = '#e8c060'; ctx.beginPath(); ctx.arc(cx + 62, 148, 5, 0, Math.PI * 2); ctx.fill();
// a few spilled tiles
for (const [dx, dy, a] of [[-70, 150, -0.5], [58, 162, 0.35]]) {
ctx.save(); ctx.translate(cx + dx, dy); ctx.rotate(a);
rr(ctx, -14, -19, 28, 38, 5); ctx.fillStyle = '#ead8b0'; ctx.fill();
ctx.strokeStyle = 'rgba(120,90,40,0.6)'; ctx.lineWidth = 1.2; ctx.stroke();
ctx.restore();
}
scene.textures.addCanvas('rk-bag', c);
}
function bakeTeapot(scene) {
const w = 170, h = 150;
const c = canvas(w, h);
const ctx = c.getContext('2d');
const cx = 82, cy = 92;
ctx.fillStyle = 'rgba(0,0,0,0.38)';
ctx.beginPath(); ctx.ellipse(cx + 6, 138, 66, 12, 0, 0, Math.PI * 2); ctx.fill();
// spout & handle
ctx.strokeStyle = '#2f6fb0'; ctx.lineWidth = 14; ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(cx + 40, cy + 10); ctx.quadraticCurveTo(cx + 70, cy, cx + 76, cy - 30); ctx.stroke();
ctx.lineWidth = 9;
ctx.beginPath(); ctx.arc(cx - 50, cy, 24, Math.PI * 0.55, Math.PI * 1.45); ctx.stroke();
// body
ctx.beginPath(); ctx.ellipse(cx, cy, 52, 44, 0, 0, Math.PI * 2);
const g = ctx.createRadialGradient(cx - 18, cy - 16, 6, cx, cy, 60);
g.addColorStop(0, '#6aa8e0'); g.addColorStop(1, '#1d4a80');
ctx.fillStyle = g; ctx.fill();
// white polka dots
ctx.fillStyle = 'rgba(255,255,255,0.85)';
for (const [dx, dy] of [[-24, -8], [0, -22], [22, -6], [-10, 14], [16, 20], [34, 8], [-34, 16]]) {
ctx.beginPath(); ctx.arc(cx + dx, cy + dy, 4.5, 0, Math.PI * 2); ctx.fill();
}
// lid
ctx.fillStyle = '#1d4a80';
ctx.beginPath(); ctx.ellipse(cx, cy - 42, 30, 9, 0, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(cx, cy - 52, 7, 0, Math.PI * 2); ctx.fillStyle = '#6aa8e0'; ctx.fill();
scene.textures.addCanvas('rk-teapot', c);
}
function bakeTail(scene) {
const c = canvas(40, 60);
const ctx = c.getContext('2d');
ctx.strokeStyle = '#1a1612';
ctx.lineWidth = 6;
ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(6, 4); ctx.quadraticCurveTo(34, 20, 18, 54); ctx.stroke();
scene.textures.addCanvas('rk-tail', c);
}
function bakeClock(scene) {
const r = CLOCK.r;
const c = canvas(r * 2 + 4, r * 2 + 4);
const ctx = c.getContext('2d');
const cx = r + 2;
ctx.beginPath(); ctx.arc(cx, cx, r, 0, Math.PI * 2);
ctx.fillStyle = '#f6efdc'; ctx.fill();
ctx.lineWidth = 2; ctx.strokeStyle = '#3a2410'; ctx.stroke();
ctx.fillStyle = '#3a2410';
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
ctx.beginPath(); ctx.arc(cx + Math.cos(a) * (r - 5), cx + Math.sin(a) * (r - 5), i % 3 ? 1.2 : 2.2, 0, Math.PI * 2); ctx.fill();
}
scene.textures.addCanvas('rk-clock', c);
}
/** Bake everything (once per page load). Returns the room key. */
export function prepareRummikubArt(scene) {
if (!scene.textures.exists('rk-tiles')) bakeTiles(scene);
if (!scene.textures.exists('rk-shadow')) bakeShadow(scene);
if (!scene.textures.exists('rk-glow')) bakeGlow(scene);
if (!scene.textures.exists('rk-opprack')) bakeOppRack(scene);
if (!scene.textures.exists('rk-bag')) bakeBag(scene);
if (!scene.textures.exists('rk-teapot')) bakeTeapot(scene);
if (!scene.textures.exists('rk-tail')) bakeTail(scene);
if (!scene.textures.exists('rk-clock')) bakeClock(scene);
return bakeRoom(scene, 'rk-room', T, { wall, front, rim, top: oilcloth, onTop, after });
}
/** Atlas frame for a tile face. */
export function tileFrame(tile, cb = false) {
if (!tile) return 'back';
if (tile.isJoker) return cb ? 'cb-joker' : 'joker';
return `${cb ? 'cb-' : ''}${tile.color}-${tile.number}`;
}
export { W, H, rr, poly };

View File

@ -1,10 +1,11 @@
// Rummikub — static data, theme and table geometry. No Phaser, no game state:
// imported by the solver, the logic engine, the AI, the Phaser scene and the
// headless verify harness alike.
// Rummikub — static data, rules defaults and tile helpers. No Phaser, no game
// state: imported by the solver, the logic engine, the AI, the table layout,
// the Phaser scene and the headless verify harness alike.
//
// Classic Rummikub: 106 tiles (numbers 1–13 in four colours, two copies each =
// 104, plus two jokers). 2–4 players, 14 tiles per rack, race to empty your rack
// by laying down valid sets (groups & runs). First table play must total ≥30.
// Classic tile rummy: 106 tiles (numbers 1–13 in four colours, two copies each
// = 104, plus two jokers). 2–4 players, 14 tiles per rack, race to empty your
// rack by laying down valid sets (groups & runs). A player's first table play
// must total at least 30 (house rule: 50) from their own rack.
export const ICON_FRAME = 68;
@ -16,98 +17,99 @@ export const COPIES = 2; // two copies of every numbered tile
export const JOKER_COUNT = 2; // two jokers
export const TILE_COUNT = 106; // 13 × 4 × 2 + 2
export const RACK_START = 14; // tiles dealt to each player
export const INITIAL_MELD_MIN = 30; // a player's first table play must total ≥30
export const JOKER_PENALTY = 30; // a joker left on the rack at game end
export const INITIAL_MELD_MIN = 30; // default opening-meld minimum
export const JOKER_PENALTY = 30; // a joker left on the rack at round end
export const MIN_SET = 3; // a valid group/run is at least three tiles
export const MAX_PLAYERS = 4;
/**
* House rules (Settings → start with the next game).
* openMin opening meld minimum (30 classic, 50 house)
* match 'r1' one round · 'r3' / 'r5' rounds · 't200' first to +200
* timer 0 = off, else seconds per turn for you
* penalty tiles drawn when your timer runs out with an unfinished table
*/
export const DEFAULT_RULES = { openMin: 30, match: 'r1', timer: 0, penalty: 3 };
/** { rounds } or { target } for a match setting. */
export function matchSpec(match) {
if (typeof match === 'string' && match[0] === 't') return { rounds: null, target: Number(match.slice(1)) || 200 };
const n = typeof match === 'string' ? Number(match.slice(1)) : Number(match);
return { rounds: n > 0 ? n : 1, target: null };
}
export function matchLabel(match) {
const m = matchSpec(match);
if (m.target) return `first to +${m.target}`;
return m.rounds === 1 ? 'one round' : `${m.rounds} rounds`;
}
// ── Tiles ────────────────────────────────────────────────────────────────────
// A tile is a plain descriptor: { id, color, number, isJoker }. A joker carries
// color:null / number:null until it is "represented" inside a committed set; the
// solver attaches a transient { rcolor, rnumber } assignment for display only.
// color:null / number:null; what it stands for inside a set is worked out by
// the solver (isValidSet → assignment) whenever it's needed, never stored.
/** Numeric value of a tile for scoring / the initial-meld minimum. Jokers are
* contextual and must be valued via the solver's set assignment. */
/** Numeric value of a tile on a rack (jokers are valued in context). */
export function tileValue(tile) {
if (tile.isJoker) return 0;
return tile.number;
}
export const COLOR_HEX = {
red: '#c8302a', blue: '#1f62b0', black: '#24201a', orange: '#e07a10',
};
export const COLOR_INT = {
red: 0xc8302a, blue: 0x1f62b0, black: 0x24201a, orange: 0xe07a10,
};
export const COLOR_WORD = { red: 'red', blue: 'blue', black: 'black', orange: 'orange' };
/** Colour-blind glyphs (Settings → Tile glyphs). */
export const COLOR_GLYPH = { red: 'heart', blue: 'drop', black: 'square', orange: 'sun' };
/** Display hex for a tile's number, by colour. */
export function colorHex(color) {
switch (color) {
case 'red': return '#d23b32';
case 'blue': return '#2f6fb0';
case 'black': return '#222018';
case 'orange': return '#e08a1e';
default: return '#222018';
}
return COLOR_HEX[color] ?? '#24201a';
}
/** Stable rack sort: by colour order, then number; jokers last. */
export function sortRackTiles(tiles) {
const ci = (c) => { const i = COLORS_ORDER.indexOf(c); return i < 0 ? 99 : i; };
export function tileName(t, rep = null) {
if (t.isJoker) return rep ? `joker (as ${COLOR_WORD[rep.color]} ${rep.number})` : 'joker';
return `${COLOR_WORD[t.color]} ${t.number}`;
}
export function shortName(t) {
if (t.isJoker) return '★';
return `${t.color[0].toUpperCase()}${t.number}`;
}
const CI = (c) => { const i = COLORS_ORDER.indexOf(c); return i < 0 ? 99 : i; };
/** Rack sort "789": by colour, then number; jokers last. */
export function sortByRun(tiles) {
return tiles.slice().sort((a, b) => {
if (a.isJoker !== b.isJoker) return a.isJoker ? 1 : -1;
if (a.isJoker && b.isJoker) return 0;
return ci(a.color) - ci(b.color) || a.number - b.number;
if (a.isJoker && b.isJoker) return a.id - b.id;
return CI(a.color) - CI(b.color) || a.number - b.number || a.id - b.id;
});
}
// ── Theme (classic ivory tiles, warm wood rack, green felt) ───────────────────
export const THEME = {
feltTop: 0x1c6b3a, // lit centre of the felt
feltMid: 0x125230, // mid green
feltEdge: 0x07351c, // deep green at the edge
rail: 0x5a3a1c, // walnut wood rack
railHi: 0x7a5230, // lit wood grain
railDark: 0x32200f, // wood shadow
brass: 0xc9a227, // brass trim
brassHi: 0xf0d77a, // brass highlight
gold: 0xd4a017,
tileFace: 0xf6efdb, // cream ivory tile face
tileFaceHi:0xfffaf0, // tile sheen
tileSide: 0xb9ae90, // extruded side / shadow
tileEdge: 0x9c8f6a, // tile border
tileSel: 0xfff4cf, // lifted/selected tile tint
validGlow: 0x55d96a, // a complete, valid set
invalidGlow: 0xe0556a, // an incomplete / illegal set
trayFill: 0x0c3f22, // table set backing tray
trayEdge: 0x1f6b3c,
text: 0xf2ead8,
jokerHex: '#8e44ad',
};
// ── Table geometry ────────────────────────────────────────────────────────────
// Seat 0 is always the human (full face-up rack along the bottom). The AI seats
// fill the top, then left, then right depending on the player count. Returns the
// anchor each seat's face-down stack + count label is drawn at, plus the central
// table band and the human rack strip.
export function buildTableLayout(playerCount, { width, height }) {
const cx = width / 2;
const seats = {
0: { x: cx, y: height - 150, dir: 'h', side: 'bottom' },
};
// AI seats by count: 2p → top; 3p → top + left; 4p → top + left + right.
const order = [];
if (playerCount >= 2) order.push({ seat: 1, x: cx, y: 200, dir: 'h', side: 'top' });
if (playerCount >= 3) order.push({ seat: 2, x: 150, y: 470, dir: 'v', side: 'left' });
if (playerCount >= 4) order.push({ seat: 3, x: width - 150, y: 470, dir: 'v', side: 'right' });
for (const o of order) seats[o.seat] = o;
// Side opponents at x≈150 (left) and x≈1770 (right) need clear space.
// Portrait ring + name text extends ~180px inward from each side opponent.
const lm = playerCount >= 3 ? 350 : 120; // left margin
const rm = playerCount >= 4 ? 350 : 120; // right margin
const tableX = lm, tableY = 300, tableW = width - lm - rm, tableH = 430;
return {
cx,
seats,
// Pool sits just outside the table band to the right, near the bottom edge.
pool: { x: tableX + tableW + 70, y: tableY + tableH - 20 },
table: { x: tableX, y: tableY, w: tableW, h: tableH },
rack: { x: 120, y: height - 168, w: width - 240, h: 150 },
};
/** Rack sort "777": by number, then colour; jokers last. */
export function sortByGroup(tiles) {
return tiles.slice().sort((a, b) => {
if (a.isJoker !== b.isJoker) return a.isJoker ? 1 : -1;
if (a.isJoker && b.isJoker) return a.id - b.id;
return a.number - b.number || CI(a.color) - CI(b.color) || a.id - b.id;
});
}
/** Back-compat alias (older callers). */
export const sortRackTiles = sortByRun;
export function sortRack(tiles, mode) {
if (mode === 'group') return sortByGroup(tiles);
if (mode === 'run') return sortByRun(tiles);
return tiles.slice();
}
/** Penalty value of tiles left on a rack. */
export function rackPenalty(rack) {
return rack.reduce((sum, t) => sum + (t.isJoker ? JOKER_PENALTY : t.number), 0);
}

View File

@ -0,0 +1,112 @@
// Rummikub dialogs — How to play, Settings (table + house rules), and your
// lifetime record at Aunt Rivka's table. Each takes the scene (a CardTableScene).
import { COLORS } from '../../config.js';
import { DEPTH as D, CX, CY } from '../../ui/cardtable/CardTableScene.js';
import { DEFAULT_RULES, matchLabel } from './RummikubData.js';
export const STATS_KEY = 'rummikub-stats';
const emptyLifetime = () => ({
games: 0, wins: 0, rounds: 0, roundsWon: 0, outs: 0, tiles: 0, biggest: 0, jokers: 0, rearranges: 0,
bestRound: null, fastest: null, bestDate: null,
});
export function loadLifetime() {
try { return { ...emptyLifetime(), ...JSON.parse(localStorage.getItem(STATS_KEY) || '{}') }; } catch (_) { return emptyLifetime(); }
}
/** Fold a finished match (you are seat 0) into the lifetime record. */
export function recordLifetime(gs) {
const L = loadLifetime();
const st = gs.stats[0];
const won = gs.match.winner === 0;
L.games++;
if (won) L.wins++;
L.rounds += gs.match.history.length;
L.roundsWon += st.roundsWon;
L.outs += st.outs;
L.tiles += st.tiles;
L.jokers += st.jokers;
L.rearranges += st.rearranges;
L.biggest = Math.max(L.biggest, st.biggest);
const best = Math.max(...gs.match.history.map((h) => h.deltas[0]));
const newBest = L.bestRound == null || best > L.bestRound;
if (newBest) { L.bestRound = best; L.bestDate = new Date().toISOString().slice(0, 10); }
// fastest round won by going out, in your own turns
for (const h of gs.match.history) {
if (h.outSeat === 0 && h.yourTurns && (L.fastest == null || h.yourTurns < L.fastest)) L.fastest = h.yourTurns;
}
try { localStorage.setItem(STATS_KEY, JSON.stringify(L)); } catch (_) { /* private mode */ }
return { lifetime: L, newBest: newBest && best > 0, best };
}
export function openRules(scene) {
const h = 880;
scene.openModal({ w: 1140, h, onEscape: () => scene.closeModal() });
const top = CY - h / 2;
scene.modalText(CX, top + 46, 'How to play — Sunday tile night', { fontFamily: 'Righteous', fontSize: '36px', color: COLORS.goldHex });
const r = scene.gs?.rules ?? { ...DEFAULT_RULES, ...scene.settings.rules };
const lines = [
['Goal', 'Be the first to empty your rack. Everyone else pays you what\'s left on theirs.'],
['Tiles', '106: numbers 1–13 in red, blue, black and orange, two of each, plus two jokers.'],
['Group', 'Three or four of the same number, every one a different colour. 7 7 7'],
['Run', 'Three or more of one colour in a row. 13 is the end — no wrapping to 1. 4 5 6 7'],
['Jokers', 'Stand in for any tile. In a run, a joker takes the spot you drop it in (front or back).'],
['Opening', `Your first play must be new sets from your own rack worth at least ${r.openMin}. Until then, hands off the table.`],
['Rearrange', 'After that, the table is yours: split runs, borrow from groups, swap out jokers — as long as every set is valid when you press Play.'],
['Your turn', 'Drag tiles (or click several, then click a set). Play when every tray is green — or Draw one tile to end your turn.'],
['Undo', 'Undo takes back your last move; Reset puts everything back where the turn began. Drawing with tiles out resets them first.'],
['Splitting', 'Pull a tile from the middle of a long run and it breaks into two runs when both halves still stand.'],
['Timer', r.timer ? `You have ${r.timer / 60} minute${r.timer > 60 ? 's' : ''} a turn. Run out with a broken table and it all goes back, plus ${r.penalty} tile${r.penalty === 1 ? '' : 's'} from the bag.` : 'Off (Settings → Turn timer). With it on, an unfinished table at the bell costs you tiles from the bag.'],
['Round end', 'Someone goes out — or the bag is empty and nobody can move, and the lowest rack wins.'],
['Scoring', `Losers pay the difference between their rack and the winner's (a joker left on the rack costs 30). This game: ${matchLabel(r.match)}.`],
];
lines.forEach(([k, v], i) => {
const y = top + 108 + i * 54;
scene.addToModal(scene.add.text(CX - 510, y, k, { fontFamily: 'Righteous', fontSize: '18px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 1));
scene.addToModal(scene.add.text(CX - 360, y, v, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, wordWrap: { width: 870 } }).setOrigin(0, 0.5).setDepth(D.modal + 1));
});
scene.modalButton(CX, top + h - 42, 'Back to the table', () => scene.closeModal(), { width: 280, height: 46, fontSize: 18 });
}
export function openSettings(scene, onDone = null) {
const s = scene.settings;
const R = s.rules;
scene.openSettingsModal([
{ label: 'Opponent pace', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.pace, set: (v) => { s.pace = v; } },
{ label: 'Coach (playable glow · missed plays)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; scene.onSettingsChanged?.(); } },
{ label: 'Table talk', options: [[false, 'Off'], [true, 'On']], get: () => s.talk, set: (v) => { s.talk = v; } },
{ label: 'Colour glyphs on tiles (♥ ● ■ ☀)', options: [[false, 'Off'], [true, 'On']], get: () => s.glyphs, set: (v) => { s.glyphs = v; scene.onSettingsChanged?.(); } },
{ label: 'Big tiles', options: [[false, 'Off'], [true, 'On']], get: () => s.big, set: (v) => { s.big = v; scene.onSettingsChanged?.(); } },
{ label: 'Opening meld', options: [[30, '30'], [50, '50']], get: () => R.openMin, set: (v) => { R.openMin = v; } },
{ label: 'Match length', options: [['r1', '1 round'], ['r3', '3 rounds'], ['r5', '5 rounds'], ['t200', 'To 200']], get: () => R.match, set: (v) => { R.match = v; } },
{ label: 'Turn timer', options: [[0, 'Off'], [60, '1 min'], [120, '2 min']], get: () => R.timer, set: (v) => { R.timer = v; } },
{ label: 'Timeout penalty', options: [[1, '1 tile'], [3, '3 tiles']], get: () => R.penalty, set: (v) => { R.penalty = v; } },
], { note: 'House rules (opening meld, match length, timer) start with the next game — Menu → New game.', onDone });
}
export function openLifetime(scene, onBack = null) {
const L = loadLifetime();
const h = 620;
const back = () => { scene.closeModal(); onBack?.(); };
scene.openModal({ w: 920, h, onEscape: back });
const top = CY - h / 2;
scene.modalText(CX, top + 48, 'Your record at Aunt Rivka\'s table', { fontFamily: 'Righteous', fontSize: '32px', color: COLORS.goldHex });
const rows = [
['Games', L.games ? `${L.wins} won of ${L.games} (${Math.round((L.wins / L.games) * 100)}%)` : 'none yet'],
['Rounds', L.rounds ? `${L.roundsWon} of ${L.rounds} won · went out ${L.outs} time${L.outs === 1 ? '' : 's'}` : '—'],
['Tiles laid', `${L.tiles}${L.games ? ` · ${(L.tiles / L.games).toFixed(1)} a game` : ''}`],
['Biggest play', L.biggest ? `${L.biggest} tiles in one turn` : '—'],
['Rearranges', `${L.rearranges}`],
['Jokers played', `${L.jokers}`],
['Best round', L.bestRound != null ? `${L.bestRound > 0 ? '+' : ''}${L.bestRound}${L.bestDate ? ` (${L.bestDate})` : ''}` : '—'],
['Fastest out', L.fastest != null ? `${L.fastest} of your turns` : '—'],
];
rows.forEach(([k, v], i) => {
const y = top + 116 + i * 48;
scene.addToModal(scene.add.text(CX - 370, y, k, { fontFamily: 'Righteous', fontSize: '19px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 1));
scene.addToModal(scene.add.text(CX - 120, y, v, { fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex }).setOrigin(0, 0.5).setDepth(D.modal + 1));
});
scene.modalButton(CX, top + h - 44, 'Back', back, { width: 220, height: 46, fontSize: 18 });
}

View File

@ -0,0 +1,210 @@
// Rummikub — the round tally (every rack turned face up, the penalties counted
// off tile by tile, the winner's take) and the end-of-match card (who won, the
// score race round by round, everyone's plays, your record).
import { COLORS } from '../../config.js';
import { DEPTH as D, CX, CY, playSoundEx, SFX } from '../../ui/cardtable/CardTableScene.js';
import { rackPenalty, sortByRun, matchLabel } from './RummikubData.js';
import { SEAT_COLORS, SEAT_HEX, TILE } from './RummikubTable.js';
import { tileFrame } from './RummikubArt.js';
const INK = '#f2ead8';
const MUTED = '#b9a98a';
const GOLD = '#f0d77a';
const signed = (n) => (n > 0 ? `+${n}` : n < 0 ? `−${Math.abs(n)}` : '0');
/**
* opts: { gs, instant?, onNext, onScores?, onLeave? }
* gs.phase is 'roundOver' (more rounds to come) or 'gameOver'.
*/
export function openRoundTally(scene, { gs, instant = false, onNext, onScores = null, onLeave = null, names }) {
const n = gs.playerCount;
const h = 300 + n * 104;
const w = 1180;
scene.openModal({ w, h, onEscape: null, freeze: false });
const top = CY - h / 2, left = CX - w / 2;
const last = gs.match.history[gs.match.history.length - 1];
const r = gs.result;
const who = (s) => (s === 0 ? 'You' : names[s]);
const head = r.stalled
? `The bag ran dry — ${who(r.winner)} ${r.winner === 0 ? 'have' : 'has'} the lowest rack`
: `${who(r.winner)} ${r.winner === 0 ? 'go' : 'goes'} out!`;
const roundWord = gs.match.spec.rounds === 1 && !gs.match.spec.target ? '' : `Round ${last.round}: `;
scene.modalText(CX, top + 48, `${roundWord}${head}`, { fontFamily: 'Righteous', fontSize: '34px', color: r.winner === 0 ? GOLD : COLORS.textHex });
scene.modalText(CX, top + 88, 'Tiles left on each rack are counted against it (a joker costs 30)', { fontFamily: '"Julius Sans One"', fontSize: '14px', color: MUTED });
const per = instant ? 0 : 55;
const rowY = (i) => top + 150 + i * 104;
const counters = [];
let delay = 300;
for (let seat = 0; seat < n; seat++) {
const y = rowY(seat);
scene.modalPortrait(seat, left + 70, y, 30, SEAT_COLORS[seat]);
scene.addToModal(scene.add.text(left + 116, y - 14, who(seat), { fontFamily: 'Righteous', fontSize: '22px', color: SEAT_HEX[seat] }).setOrigin(0, 0.5).setDepth(D.modal + 1));
const rackIds = last.racks[seat];
const tiles = sortByRun(rackIds.map((id) => scene.tileById(id)).filter(Boolean));
const k = tiles.length > 20 ? 0.36 : 0.44;
const tw = TILE.w * k + 3;
const x0 = left + 250;
const maxW = 560;
const step = tiles.length > 1 ? Math.min(tw, maxW / (tiles.length - 1)) : tw;
if (!tiles.length) {
scene.addToModal(scene.add.text(x0, y, seat === r.winner && !r.stalled ? 'went out — rack empty!' : 'empty', { fontFamily: '"Julius Sans One"', fontSize: '17px', color: '#8ce99a' }).setOrigin(0, 0.5).setDepth(D.modal + 1));
}
const pen = scene.addToModal(scene.add.text(left + 880, y, '0', { fontFamily: 'Righteous', fontSize: '24px', color: tiles.length ? '#ff8a7a' : MUTED }).setOrigin(1, 0.5).setDepth(D.modal + 1));
let running = 0;
tiles.forEach((t, i) => {
const img = scene.addToModal(scene.add.image(x0 + i * step + (TILE.w * k) / 2, y, 'rk-tiles', tileFrame(t, scene.settings.glyphs))
.setScale(k / 2).setDepth(D.modal + 1 + i * 0.001));
running += t.isJoker ? 30 : t.number;
const val = running;
if (per) {
img.setAlpha(0).setY(y - 10);
scene.time.delayedCall(delay + i * per, () => {
if (!img.active) return;
scene.tweens.add({ targets: img, alpha: 1, y, duration: 140 });
if (pen.active) pen.setText(`−${val}`);
if (i % 2 === 0) playSoundEx(scene, SFX.PIECE_CLICK, { volume: 0.25, rate: 1.2 + Math.random() * 0.2 });
});
}
});
if (!per && tiles.length) pen.setText(`−${rackPenalty(tiles)}`);
delay += Math.min(tiles.length, 14) * per * 0.6 + 120;
// this round & match columns
const d = last.deltas[seat];
const dt = scene.addToModal(scene.add.text(left + 1010, y, signed(d), { fontFamily: 'Righteous', fontSize: '28px', color: d > 0 ? '#8ce99a' : d < 0 ? '#ff8a7a' : MUTED }).setOrigin(1, 0.5).setDepth(D.modal + 1));
const mt = scene.addToModal(scene.add.text(left + 1130, y, signed(last.after[seat] - d), { fontFamily: 'Righteous', fontSize: '24px', color: INK }).setOrigin(1, 0.5).setDepth(D.modal + 1));
counters.push({ dt, mt, d, from: last.after[seat] - d, to: last.after[seat] });
}
scene.modalText(left + 880 - 34, top + 118, 'rack', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: MUTED });
scene.modalText(left + 1010 - 36, top + 118, 'round', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: MUTED });
scene.modalText(left + 1130 - 40, top + 118, 'match', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: MUTED });
// tick the match totals over once the racks are counted
for (const c of counters) {
if (!per) { c.mt.setText(signed(c.to)); continue; }
c.dt.setAlpha(0);
const box = { v: c.from };
scene.time.delayedCall(delay + 200, () => {
if (!c.dt.active) return;
c.dt.setAlpha(1);
scene.tweens.add({
targets: box, v: c.to, duration: 700, ease: 'Cubic.easeOut',
onUpdate: () => { if (c.mt.active) c.mt.setText(signed(Math.round(box.v))); },
});
});
}
if (per) scene.time.delayedCall(delay + 200, () => scene.modal && playSoundEx(scene, SFX.PENCIL_WRITE, { volume: 0.5 }));
const fy = top + h - 50;
if (gs.phase === 'gameOver') {
scene.modalButton(CX, fy, 'See the result', onNext, { width: 260, bg: COLORS.accent, textColor: COLORS.textDarkHex });
} else {
const spec = gs.match.spec;
const more = spec.target ? `first to +${spec.target}` : `round ${last.round + 1} of ${spec.rounds}`;
scene.modalText(CX, fy - 48, `Next: ${more}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: MUTED });
scene.modalButton(CX - 250, fy, 'Next round', onNext, { width: 220, bg: COLORS.accent, textColor: COLORS.textDarkHex });
if (onScores) scene.modalButton(CX, fy, 'Score sheet', onScores, { width: 220, variant: 'ghost' });
if (onLeave) scene.modalButton(CX + 250, fy, 'Leave', onLeave, { width: 220, variant: 'ghost' });
}
scene.modal.onEnter = onNext;
scene.modal.objs[0].setAlpha(0.45);
}
/**
* The end-of-match card.
* buttons: [{ label, act, hot?, ghost? }] · note: { newBest, lifetime }
*/
export function openEndScreen(scene, { gs, names, buttons, note = null }) {
const w = 1220, h = 800;
scene.openModal({ w, h, onEscape: null, freeze: false });
const top = CY - h / 2, left = CX - w / 2;
const n = gs.playerCount;
const m = gs.match;
const won = m.winner === 0;
const multi = m.history.length > 1;
scene.modalText(CX, top + 54, won ? (multi ? 'You win the match!' : 'You win!') : `${names[m.winner]} wins${multi ? ' the match' : ''}`, {
fontFamily: 'Righteous', fontSize: '50px', color: won ? GOLD : COLORS.textHex,
});
scene.modalText(CX, top + 104, `${matchLabel(gs.rules.match)} · opening meld ${gs.rules.openMin}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: MUTED });
// ── the score race (or the single round's take) ──
const gx = left + 80, gy = top + 160, gw = 520, gh = 300;
const g = scene.addToModal(scene.add.graphics().setDepth(D.modal + 1));
g.fillStyle(0x0c0806, 0.55);
g.fillRoundedRect(gx - 16, gy - 14, gw + 60, gh + 48, 10);
const pts = [Array(n).fill(0), ...m.history.map((hh) => hh.after)];
if (multi) {
const all = pts.flat();
const hi = Math.max(10, ...all), lo = Math.min(-10, ...all);
const X = (i) => gx + (i / (pts.length - 1)) * gw;
const Y = (v) => gy + gh - ((v - lo) / (hi - lo)) * gh;
g.lineStyle(1, 0x9e9080, 0.35);
g.lineBetween(gx, Y(0), gx + gw, Y(0));
if (m.spec.target) {
g.lineStyle(2, 0xf0d77a, 0.8);
g.lineBetween(gx, Y(m.spec.target), gx + gw, Y(m.spec.target));
}
for (let seat = n - 1; seat >= 0; seat--) {
g.lineStyle(4, SEAT_COLORS[seat], 1);
g.beginPath();
pts.forEach((p, i) => (i ? g.lineTo(X(i), Y(p[seat])) : g.moveTo(X(i), Y(p[seat]))));
g.strokePath();
g.fillStyle(SEAT_COLORS[seat], 1);
pts.forEach((p, i) => g.fillCircle(X(i), Y(p[seat]), i === pts.length - 1 ? 6 : 3.5));
}
scene.addToModal(scene.add.text(gx, gy + gh + 18, `the race, round by round (${m.history.length} rounds)`, { fontFamily: '"Julius Sans One"', fontSize: '13px', color: MUTED }).setOrigin(0, 0.5).setDepth(D.modal + 2));
} else {
// one round: bars of the take
const last = m.history[0];
const max = Math.max(1, ...last.deltas.map(Math.abs));
const bw = gw / n;
const mid = gy + gh / 2;
g.lineStyle(1, 0x9e9080, 0.4);
g.lineBetween(gx, mid, gx + gw, mid);
last.deltas.forEach((d, seat) => {
const bh = (Math.abs(d) / max) * (gh / 2 - 30);
const x = gx + seat * bw + bw * 0.2;
g.fillStyle(SEAT_COLORS[seat], 0.9);
if (d >= 0) g.fillRect(x, mid - bh, bw * 0.6, bh); else g.fillRect(x, mid, bw * 0.6, bh);
scene.modalText(x + bw * 0.3, d >= 0 ? mid - bh - 16 : mid + bh + 16, signed(d), { fontFamily: 'Righteous', fontSize: '20px', color: SEAT_HEX[seat] });
scene.modalText(x + bw * 0.3, gy + gh + 18, seat === 0 ? 'You' : names[seat], { fontFamily: '"Julius Sans One"', fontSize: '14px', color: SEAT_HEX[seat] });
});
}
// ── the table, by the numbers ──
const tx = left + 650, ty = top + 160;
const colW = Math.min(110, 400 / n);
const cols = Array.from({ length: n }, (_, s) => tx + 170 + s * colW);
for (let s = 0; s < n; s++) scene.modalText(cols[s], ty, s === 0 ? 'You' : names[s].slice(0, 9), { fontFamily: 'Righteous', fontSize: '18px', color: SEAT_HEX[s] });
const st = gs.stats;
const rows = [
['Score', (s) => signed(m.scores[s])],
['Rounds won', (s) => st[s].roundsWon],
['Plays', (s) => st[s].plays],
['Tiles laid', (s) => st[s].tiles],
['Biggest play', (s) => st[s].biggest],
['Rearranges', (s) => st[s].rearranges],
['Jokers laid', (s) => st[s].jokers],
['Tiles drawn', (s) => st[s].draws],
];
rows.forEach(([k, fn], i) => {
const y = ty + 44 + i * 36;
scene.addToModal(scene.add.text(tx, y, k, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: MUTED }).setOrigin(0, 0.5).setDepth(D.modal + 1));
for (let s = 0; s < n; s++) scene.modalText(cols[s], y, String(fn(s)), { fontFamily: 'Righteous', fontSize: i === 0 ? '22px' : '19px', color: i === 0 ? SEAT_HEX[s] : INK });
});
if (note?.lifetime) {
const L = note.lifetime;
const line = `Your record: ${L.wins} of ${L.games} games · biggest play ${L.biggest} tiles · best round ${signed(L.bestRound ?? 0)}${note.newBest ? ' (NEW!)' : ''}`;
scene.modalText(CX, top + h - 128, line, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: note.newBest ? '#8ce99a' : MUTED });
}
const nb = buttons.length;
buttons.forEach((b, i) => {
const x = CX + (i - (nb - 1) / 2) * 250;
const opts = b.ghost ? { variant: 'ghost' } : b.hot ? { bg: COLORS.accent, textColor: COLORS.textDarkHex } : {};
scene.modalButton(x, top + h - 56, b.label, b.act, { width: 230, ...opts });
});
const hot = buttons.find((b) => b.hot);
if (hot) scene.modal.onEnter = hot.act;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,19 @@
// Rummikub — immutable game engine. No Phaser. Every mutating helper returns a
// NEW state object (mirrors HeartsLogic / CanastaLogic style). The Phaser scene,
// the AI and the verify harness all drive the game through these functions.
// Rummikub — immutable game engine. No Phaser. Every helper returns a NEW
// plain-JSON state (safe to save to localStorage). The scene, the AI and the
// verify harness all drive the game through these functions.
//
// A turn is edited on a working copy (workingTable / workingRack) so the player
// can freely rearrange tiles and then Commit (validated) or Reset (snapshot).
// A match is one or more rounds (house rule). A turn is edited on working
// copies (workingTable / workingRack) so the player can freely rearrange and
// then Commit (validated), Undo a move, or Reset to the turn's start.
import {
COLORS_ORDER, MIN_NUM, MAX_NUM, COPIES, JOKER_COUNT, RACK_START,
INITIAL_MELD_MIN, JOKER_PENALTY,
COLORS_ORDER, MIN_NUM, MAX_NUM, COPIES, JOKER_COUNT, RACK_START, TILE_COUNT,
DEFAULT_RULES, matchSpec, rackPenalty,
} from './RummikubData.js';
import { isValidSet } from './RummikubSolver.js';
import { isValidSet, canonicalOrder } from './RummikubSolver.js';
export const VERSION = 2;
const UNDO_CAP = 80;
// ── RNG ───────────────────────────────────────────────────────────────────────
function mulberry32(seed) {
@ -44,36 +48,77 @@ export function buildTiles() {
return tiles;
}
export { rackPenalty };
const emptyStats = () => ({ plays: 0, tiles: 0, biggest: 0, jokers: 0, draws: 0, rearranges: 0, outs: 0, roundsWon: 0 });
// ── Setup ───────────────────────────────────────────────────────────────────--
export function createInitialState({ seed = (Math.random() * 1e9) | 0, playerCount = 4 } = {}) {
const rand = mulberry32(seed);
/**
* A new match. opts: { playerCount, rules, seed }. Round 1 is dealt at once.
*/
export function createGame({ playerCount = 4, rules = {}, seed = (Math.random() * 2 ** 32) >>> 0 } = {}) {
const r = { ...DEFAULT_RULES, ...rules };
const match = {
spec: matchSpec(r.match),
roundNo: 0,
scores: Array(playerCount).fill(0),
history: [], // [{ round, winner, outSeat, penalties, deltas, after }]
winner: null,
};
const base = {
version: VERSION, playerCount, rules: r, seed, match,
stats: Array.from({ length: playerCount }, emptyStats),
};
return dealRound(base);
}
/** Back-compat: a single-round game (verify harness / older callers). */
export function createInitialState({ seed = (Math.random() * 1e9) | 0, playerCount = 4, rules = {} } = {}) {
return createGame({ playerCount, seed, rules: { ...rules, match: 'r1' } });
}
function dealRound(prev) {
const roundNo = prev.match.roundNo + 1;
const rand = mulberry32((prev.seed + roundNo * 7919) >>> 0);
const deck = shuffle(buildTiles(), rand);
const n = prev.playerCount;
const players = [];
for (let seat = 0; seat < playerCount; seat++) {
players.push({ seat, rack: deck.splice(0, RACK_START), hasMelded: false });
}
for (let seat = 0; seat < n; seat++) players.push({ seat, rack: deck.splice(0, RACK_START), hasMelded: false });
const state = {
playerCount,
version: VERSION,
playerCount: n,
rules: prev.rules,
seed: prev.seed,
match: { ...prev.match, roundNo },
stats: prev.stats,
players,
table: [], // committed sets: array of arrays of tiles
pool: deck, // remaining face-down draw tiles
currentPlayer: 0,
phase: 'play', // 'play' | 'gameOver'
consecutivePasses: 0, // turns in a row that emptied the pool with no play
winner: null,
finalScores: null,
currentPlayer: (roundNo - 1) % n,
phase: 'play', // 'play' | 'roundOver' | 'gameOver'
turnNo: 1,
consecutivePasses: 0,
winner: null, // this round's winner
finalScores: null, // this round's deltas
result: null,
commitError: null,
seed,
log: [],
// per-turn working copies (filled by beginTurn):
lastPlay: null, // { seat, ids } — the most recent table play
turnStart: null,
workingTable: [],
workingRack: [],
undo: [],
drewThisTurn: false,
};
return beginTurn(state);
}
/** Deal the next round of a match (after 'roundOver'). */
export function nextRound(state) {
if (state.phase !== 'roundOver') return state;
return dealRound(state);
}
// Snapshot the table + current rack so the turn can be Reset, and open editable
// working copies.
export function beginTurn(state) {
@ -91,41 +136,131 @@ export function beginTurn(state) {
},
workingTable: table,
workingRack: rack,
undo: [],
};
}
// ── Working-area editing ───────────────────────────────────────────────────────
// Move a tile (identified by id) from wherever it currently sits in the working
// area to `dest`: { type:'set', index } | { type:'newSet' } | { type:'rack' }.
// Empty working sets are pruned. Returns a new state.
export function applyDrag(state, tileId, dest) {
let tile = null;
const workingRack = state.workingRack.filter((t) => {
if (t.id === tileId) { tile = t; return false; }
return true;
});
const workingTable = state.workingTable.map((set) => set.filter((t) => {
if (t.id === tileId) { tile = t; return false; }
return true;
}));
if (!tile) return state; // unknown tile
const snap = (state) => ({ table: state.workingTable.map((s) => s.slice()), rack: state.workingRack.slice() });
const pushUndo = (state) => [...state.undo, snap(state)].slice(-UNDO_CAP);
if (dest.type === 'rack') {
const idx = (dest.insertIndex !== undefined && dest.insertIndex >= 0)
? Math.min(dest.insertIndex, workingRack.length) : workingRack.length;
workingRack.splice(idx, 0, tile);
} else if (dest.type === 'newSet') {
workingTable.push([tile]);
} else if (dest.type === 'set') {
if (workingTable[dest.index]) workingTable[dest.index].push(tile);
else workingTable.push([tile]);
}
const pruned = workingTable.filter((s) => s.length > 0);
return { ...state, workingTable: pruned, workingRack, commitError: null };
/** Ids of tiles that were on the table when the turn began (they can't go to a rack). */
export function tableIdsAtStart(state) {
return new Set(state.turnStart.table.flat().map((t) => t.id));
}
// Load an AI plan (newTable + the rack tiles it played) into the working copies,
// ready for commitTurn. Returns a new state.
/**
* Pick tiles up (ids, in the order given) out of the working area. A valid run
* that loses tiles from its middle splits into its pieces when every piece is
* still a valid run; otherwise it stays together so the gap shows ("gap at 6").
* Returns { table, rack, moving } or null if an id is unknown.
*/
export function liftTiles(state, ids) {
const idSet = new Set(ids);
const byId = new Map();
for (const t of state.workingRack) byId.set(t.id, t);
for (const s of state.workingTable) for (const t of s) byId.set(t.id, t);
const moving = ids.map((id) => byId.get(id));
if (moving.some((t) => !t)) return null;
const rack = state.workingRack.filter((t) => !idSet.has(t.id));
const table = [];
for (const s of state.workingTable) {
if (!s.some((t) => idSet.has(t.id))) { table.push(s.slice()); continue; }
const kept = s.filter((t) => !idSet.has(t.id));
if (!kept.length) continue;
if (isValidSet(s).kind === 'run') {
const segs = [];
let seg = [];
for (const t of s) {
if (idSet.has(t.id)) { if (seg.length) { segs.push(seg); seg = []; } continue; }
seg.push(t);
}
if (seg.length) segs.push(seg);
if (segs.length > 1 && segs.every((x) => isValidSet(x).valid)) { table.push(...segs); continue; }
}
table.push(kept);
}
return { table, rack, moving };
}
/**
* Put lifted tiles down. `dest` indexes the LIFTED table/rack:
* { type: 'set', index, at? } into set `index` at position `at` (default end)
* { type: 'newSet', at? } a new set, at table position `at` (default last)
* { type: 'rack', at? } back onto the rack at `at`
* A set that turns valid is laid out in order. Returns { table, rack }.
*/
export function placeTiles(lifted, dest) {
const table = lifted.table.map((s) => s.slice());
let rack = lifted.rack.slice();
const moving = lifted.moving;
let target = null;
if (dest.type === 'rack') {
const at = dest.at == null ? rack.length : Math.max(0, Math.min(rack.length, dest.at));
rack = [...rack.slice(0, at), ...moving, ...rack.slice(at)];
} else if (dest.type === 'set' && table[dest.index]) {
target = table[dest.index];
const at = dest.at == null ? target.length : Math.max(0, Math.min(target.length, dest.at));
target.splice(at, 0, ...moving);
} else {
const at = dest.at == null ? table.length : Math.max(0, Math.min(table.length, dest.at));
target = moving.slice();
table.splice(at, 0, target);
}
if (target && isValidSet(target).valid) {
const ordered = canonicalOrder(target);
target.splice(0, target.length, ...ordered);
}
return { table, rack };
}
/**
* Move tiles to `dest` (indices into the table/rack as they are once the
* tiles are picked up — see liftTiles; moving rack tiles never changes the
* table, so for those it's the same as the current table). Tiles that were on
* the table at the turn's start can't go back to a rack. Pass { undo: false }
* for previews. Returns a new state (unchanged, with commitError, if illegal).
*/
export function moveTiles(state, ids, dest, { undo = true } = {}) {
const idList = Array.isArray(ids) ? ids : [ids];
if (!idList.length) return state;
if (dest.type === 'rack') {
const fromTable = tableIdsAtStart(state);
if (idList.some((id) => fromTable.has(id))) {
return { ...state, commitError: 'Tiles that were already on the table have to stay there' };
}
}
const lifted = liftTiles(state, idList);
if (!lifted) return state;
const { table, rack } = placeTiles(lifted, dest);
return {
...state,
workingTable: table,
workingRack: rack,
commitError: null,
undo: undo ? pushUndo(state) : state.undo,
};
}
/** Older single-tile API: dest { type:'set', index } | { type:'newSet' } | { type:'rack', insertIndex }. */
export function applyDrag(state, tileId, dest) {
const d = dest.type === 'rack' ? { type: 'rack', at: dest.insertIndex } : dest;
return moveTiles(state, [tileId], d);
}
/** Replace the whole working layout (AI plans, the Coach's "show me"). */
export function stageLayout(state, table, rackIds = null, { undo = true } = {}) {
const onTable = new Set(table.flat().map((t) => t.id));
const all = [...state.workingRack, ...state.workingTable.flat()];
const rack = rackIds
? rackIds.map((id) => all.find((t) => t.id === id)).filter(Boolean)
: state.workingRack.filter((t) => !onTable.has(t.id));
// any working-table tile the plan forgot goes nowhere — refuse such plans
if (table.flat().length + rack.length !== all.length) return { ...state, commitError: 'That layout loses tiles' };
return { ...state, workingTable: table.map((s) => s.slice()), workingRack: rack, commitError: null, undo: undo ? pushUndo(state) : state.undo };
}
// Load an AI plan (newTable + the rack tiles it played) into the working copies.
export function stageAiPlan(state, plan) {
const playedIds = new Set(plan.tilesPlayed);
const workingRack = state.workingRack.filter((t) => !playedIds.has(t.id));
@ -133,11 +268,45 @@ export function stageAiPlan(state, plan) {
return { ...state, workingTable, workingRack, commitError: null };
}
/** Set the rack order (sorting — not an undoable move). ids must be the same tiles. */
export function reorderRack(state, ids) {
const byId = new Map(state.workingRack.map((t) => [t.id, t]));
if (ids.length !== byId.size || !ids.every((id) => byId.has(id))) return state;
return { ...state, workingRack: ids.map((id) => byId.get(id)) };
}
/** Reorder the working table's sets (Tidy). */
export function tidyTable(state) {
const key = (s) => {
const v = isValidSet(s);
if (!v.valid) return [2, 0, 0];
const first = s.find((t) => !t.isJoker);
if (v.kind === 'group') return [0, first.number, 0];
const lo = Math.min(...s.map((t) => (t.isJoker ? v.assignment[t.id].number : t.number)));
return [1, COLORS_ORDER.indexOf(first.color), lo];
};
const sorted = state.workingTable.slice().sort((a, b) => {
const ka = key(a), kb = key(b);
return ka[0] - kb[0] || ka[1] - kb[1] || ka[2] - kb[2];
});
return { ...state, workingTable: sorted };
}
export function undoMove(state) {
if (!state.undo.length) return state;
const prev = state.undo[state.undo.length - 1];
// keep the player's current rack order for tiles that stay on the rack
const order = new Map(state.workingRack.map((t, i) => [t.id, i]));
const rack = prev.rack.slice().sort((a, b) => (order.get(a.id) ?? 999) - (order.get(b.id) ?? 999));
return { ...state, workingTable: prev.table, workingRack: rack, undo: state.undo.slice(0, -1), commitError: null };
}
export function canUndo(state) { return state.undo.length > 0; }
export function resetTurn(state) {
const ts = state.turnStart;
// Preserve manual rack ordering: tiles already in workingRack keep their
// current positions; tiles being returned from the table append at the end
// in their original turnStart order.
// Keep the manual rack order: tiles already on the rack stay put; tiles
// coming back from the table go on the end in their original order.
const rankInWorking = new Map(state.workingRack.map((t, i) => [t.id, i]));
const origRank = new Map(ts.rack.map((t, i) => [t.id, i]));
const n = ts.rack.length;
@ -152,6 +321,7 @@ export function resetTurn(state) {
workingRack: resetRack,
drewThisTurn: false,
commitError: null,
undo: hasStagedChanges(state) || state.workingTable.length !== ts.table.length ? pushUndo(state) : state.undo,
};
}
@ -169,23 +339,41 @@ function multisetContains(haystackKeys, needleKeys) {
return true;
}
/** Points laid this turn in brand-new sets (the opening-meld count) + whether old sets are intact. */
export function openingCount(state) {
const ts = state.turnStart;
const origKeys = ts.table.map(setKey);
const working = state.workingTable;
const workKeys = working.map(setKey);
const intact = multisetContains(workKeys, origKeys);
const remaining = workKeys.slice();
for (const k of origKeys) { const i = remaining.indexOf(k); if (i >= 0) remaining.splice(i, 1); }
let points = 0, pending = 0;
const origIds = tableIdsAtStart(state);
for (const s of working) {
if (!remaining.includes(setKey(s))) continue;
if (s.some((t) => origIds.has(t.id))) continue;
const v = isValidSet(s);
if (v.valid) points += v.points; else pending++;
}
return { points, intact, pending };
}
// Returns { ok, reason, played, firstMeldPoints }.
export function validateCommit(state) {
const ts = state.turnStart;
const working = state.workingTable;
const openMin = state.rules?.openMin ?? 30;
// 1. every working set is a legal group/run.
for (const set of working) {
if (!isValidSet(set).valid) {
return { ok: false, reason: 'Every set on the table must be a valid run or group' };
}
}
// 2. tile bookkeeping.
const origTableIds = new Set(ts.table.flat().map((t) => t.id));
const origTableIds = tableIdsAtStart(state);
const workTableIds = working.flat().map((t) => t.id);
const workTableSet = new Set(workTableIds);
for (const id of origTableIds) {
if (!workTableSet.has(id)) return { ok: false, reason: 'Tiles already on the table must stay on the table' };
}
@ -194,23 +382,16 @@ export function validateCommit(state) {
return { ok: false, reason: 'Play at least one tile to the table, or draw instead' };
}
// 3. first meld must total ≥30 from brand-new sets only (no manipulation yet).
// the opening meld: brand-new sets only, worth openMin, no touching the table
if (!ts.hasMelded) {
const origKeys = ts.table.map(setKey);
const workKeys = working.map(setKey);
if (!multisetContains(workKeys, origKeys)) {
return { ok: false, reason: `Your opening meld must be at least ${INITIAL_MELD_MIN} points and can't rearrange the table yet` };
const oc = openingCount(state);
if (!oc.intact) {
return { ok: false, reason: `Your opening meld must be new sets from your own rack — you can't change the table until you're in` };
}
// New sets = working sets minus the (intact) original sets.
const remaining = workKeys.slice();
for (const k of origKeys) remaining.splice(remaining.indexOf(k), 1);
const newSets = working.filter((s) => remaining.includes(setKey(s)));
let points = 0;
for (const s of newSets) points += isValidSet(s).points;
if (points < INITIAL_MELD_MIN) {
return { ok: false, reason: `Your opening meld must total at least ${INITIAL_MELD_MIN} (currently ${points})`, firstMeldPoints: points };
if (oc.points < openMin) {
return { ok: false, reason: `Your opening meld must total at least ${openMin} (you have ${oc.points})`, firstMeldPoints: oc.points };
}
return { ok: true, played, firstMeldPoints: points };
return { ok: true, played, firstMeldPoints: oc.points };
}
return { ok: true, played };
}
@ -227,76 +408,133 @@ export function commitTurn(state) {
const players = state.players.map((p, i) =>
i === seat ? { ...p, rack: state.workingRack.slice(), hasMelded: true } : p);
const table = state.workingTable.map((s) => s.slice());
let next = { ...state, players, table, consecutivePasses: 0, commitError: null, drewThisTurn: false };
if (players[seat].rack.length === 0) {
return finishGame({ ...next }, seat);
}
// a rearrange: some set that was on the table isn't still whole inside one set
const rearranged = state.turnStart.table.some((s) => !table.some((t) => s.every((x) => t.some((y) => y.id === x.id))));
const jokers = v.played.filter((id) => state.turnStart.rack.find((t) => t.id === id)?.isJoker).length;
const points = table.reduce((a, s) => a + (isValidSet(s).points || 0), 0)
- state.turnStart.table.reduce((a, s) => a + (isValidSet(s).points || 0), 0);
const stats = state.stats.map((st, i) => (i !== seat ? st : {
...st, plays: st.plays + 1, tiles: st.tiles + v.played.length, biggest: Math.max(st.biggest, v.played.length),
jokers: st.jokers + jokers, rearranges: st.rearranges + (rearranged ? 1 : 0),
}));
const out = players[seat].rack.length === 0;
const entry = {
kind: 'play', seat, ids: v.played, n: v.played.length, points, first: !state.turnStart.hasMelded,
rearranged, jokers, out, turn: state.turnNo,
};
const next = {
...state, players, table, stats, consecutivePasses: 0, commitError: null, drewThisTurn: false,
log: [...state.log, entry], lastPlay: { seat, ids: v.played },
};
if (out) return finishRound(next, seat);
return advanceTurn(next);
}
// ── Drawing & passing ──────────────────────────────────────────────────────────
export function drawTile(state) {
/** Draw `n` tiles (1 normally; the timeout penalty draws more). Resets any staged play first. */
export function drawTile(state, n = 1, { penalty = false } = {}) {
const seat = state.currentPlayer;
if (state.pool.length === 0) return passTurn(state); // nothing to draw → pass
const pool = state.pool.slice();
const tile = pool.shift();
// Use workingRack so any manual reordering done before drawing is preserved;
// draw is only allowed when no tiles have been moved to the table, so
// workingRack has the same tile set as players[seat].rack.
const players = state.players.map((p, i) =>
i === seat ? { ...p, rack: [...state.workingRack, tile] } : p);
const next = { ...state, pool, players, consecutivePasses: 0, drewThisTurn: true, commitError: null };
const base = hasStagedChanges(state) || state.workingTable.length !== state.turnStart.table.length ? resetTurn(state) : state;
if (base.pool.length === 0) return passTurn(base);
const pool = base.pool.slice();
const drawn = pool.splice(0, Math.min(n, pool.length));
// keep the rack order the player arranged
const players = base.players.map((p, i) => (i === seat ? { ...p, rack: [...base.workingRack, ...drawn] } : p));
const stats = base.stats.map((st, i) => (i === seat ? { ...st, draws: st.draws + drawn.length } : st));
const next = {
...base, pool, players, stats, consecutivePasses: 0, drewThisTurn: true, commitError: null,
workingTable: base.turnStart.table.map((s) => s.slice()),
log: [...base.log, { kind: 'draw', seat, n: drawn.length, ids: drawn.map((t) => t.id), penalty, turn: base.turnNo }],
};
return advanceTurn(next);
}
/** The turn timer ran out: put everything back and draw the penalty. */
export function forfeitTurn(state) {
const n = canCommit(state) ? 0 : (state.rules?.penalty ?? 3);
if (n === 0) return commitTurn(state);
return drawTile(state, n, { penalty: true });
}
// Pool exhausted and the player has nothing to play: pass. When everyone passes
// in a row the hand is scored.
// in a row the round is scored.
export function passTurn(state) {
const passes = state.consecutivePasses + 1;
if (passes >= state.playerCount) return finishGame({ ...state }, null);
return advanceTurn({ ...state, consecutivePasses: passes, commitError: null });
const logged = { ...state, log: [...state.log, { kind: 'pass', seat: state.currentPlayer, turn: state.turnNo }] };
if (passes >= state.playerCount) return finishRound({ ...logged, consecutivePasses: passes }, null);
return advanceTurn({ ...logged, consecutivePasses: passes, commitError: null });
}
export function advanceTurn(state) {
const currentPlayer = (state.currentPlayer + 1) % state.playerCount;
return beginTurn({ ...state, currentPlayer });
}
// ── Game end ───────────────────────────────────────────────────────────────────
export function rackPenalty(rack) {
return rack.reduce((sum, t) => sum + (t.isJoker ? JOKER_PENALTY : t.number), 0);
return beginTurn({ ...state, currentPlayer, turnNo: state.turnNo + 1 });
}
// ── Round & match end ──────────────────────────────────────────────────────────
// winnerSeat given (someone went out) or null (pool stalled → lowest rack wins).
function finishGame(state, winnerSeat) {
function finishRound(state, outSeat) {
const penalties = state.players.map((p) => rackPenalty(p.rack));
let winner = winnerSeat;
let winner = outSeat;
if (winner == null) {
// lowest remaining rack points wins; ties broken by lowest seat.
let best = Infinity;
// lowest rack wins; ties go to the earliest seat after the last player
state.players.forEach((p, i) => { if (penalties[i] < best) { best = penalties[i]; winner = i; } });
}
// Classic scoring: the winner gains the sum of everyone else's rack penalties;
// each loser scores minus their own rack.
const finalScores = state.players.map((p, i) => (i === winner
? penalties.reduce((a, b, j) => a + (j === winner ? 0 : b), 0)
: -penalties[i]));
return { ...state, phase: 'gameOver', winner, finalScores };
// Zero-sum: everyone pays the winner the difference between racks.
const pw = penalties[winner];
const deltas = penalties.map((p, i) => (i === winner ? 0 : -(p - pw)));
deltas[winner] = -deltas.reduce((a, b) => a + b, 0);
const scores = state.match.scores.map((s, i) => s + deltas[i]);
const history = [...state.match.history, {
round: state.match.roundNo, winner, outSeat, penalties, deltas, after: scores.slice(),
racks: state.players.map((p) => p.rack.map((t) => t.id)),
yourTurns: state.log.filter((e) => e.seat === 0 && (e.kind === 'play' || e.kind === 'draw' || e.kind === 'pass')).length,
}];
const stats = state.stats.map((st, i) => (i !== winner ? st : { ...st, roundsWon: st.roundsWon + 1, outs: st.outs + (outSeat === i ? 1 : 0) }));
const spec = state.match.spec;
let matchWinner = null;
if (spec.target) {
const top = Math.max(...scores);
if (top >= spec.target) matchWinner = scores.indexOf(top);
} else if (history.length >= spec.rounds) {
const top = Math.max(...scores);
matchWinner = scores.indexOf(top);
}
const match = { ...state.match, scores, history, winner: matchWinner };
const result = { winner, outSeat, penalties, deltas, stalled: outSeat == null };
return {
...state, stats, match, result, winner, finalScores: deltas,
phase: matchWinner != null ? 'gameOver' : 'roundOver',
log: [...state.log, { kind: 'roundOver', seat: winner, out: outSeat != null, turn: state.turnNo }],
};
}
export function isOver(state) { return state.phase === 'roundOver' || state.phase === 'gameOver'; }
// ── Read helpers (for the scene / AI) ──────────────────────────────────────────
// Tiles played from the rack so far this working turn.
/** Tiles played from the rack so far this working turn. */
export function stagedPlayedIds(state) {
const origTableIds = new Set(state.turnStart.table.flat().map((t) => t.id));
const origTableIds = tableIdsAtStart(state);
return state.workingTable.flat().map((t) => t.id).filter((id) => !origTableIds.has(id));
}
export function hasStagedChanges(state) {
const ts = state.turnStart;
const a = state.workingRack.map((t) => t.id).sort().join(',');
const b = ts.rack.map((t) => t.id).sort().join(',');
return a !== b;
if (state.workingRack.length !== ts.rack.length) return true;
const a = state.workingRack.map((t) => t.id).sort((x, y) => x - y).join(',');
const b = ts.rack.map((t) => t.id).sort((x, y) => x - y).join(',');
if (a !== b) return true;
// a pure rearrangement of the table (no rack tiles) still counts
const ka = state.workingTable.map(setKey).sort().join('|');
const kb = ts.table.map(setKey).sort().join('|');
return ka !== kb;
}
/** Every tile in the game is somewhere exactly once (verify / save sanity). */
export function tileCount(state) {
const rackN = state.players.reduce((a, p) => a + p.rack.length, 0);
const tableN = state.table.reduce((a, s) => a + s.length, 0);
return rackN + tableN + state.pool.length;
}
export { TILE_COUNT };

View File

@ -1,15 +1,19 @@
// Rummikub — the rules "brain". Pure functions, no Phaser, no engine state.
// Imported by the logic engine, the AI and the headless verify harness.
// Imported by the logic engine, the AI, the scene and the verify harness.
//
// isValidSet(tiles) — validate one group/run, assigning jokers.
// solvePartition(tiles) — constructively partition a multiset of tiles into
// valid sets (returns the actual sets, or null). This
// powers the AI's "what can I lay down" search and the
// feasibility checks.
// partitionable(tiles) — boolean wrapper around solvePartition.
// findSetsFromPool(...) — pull disjoint valid sets out of a loose pool (used
// for the 30-point initial meld and laying new sets).
// bestMeldDecomposition — the AI's turn planner.
// isValidSet(tiles) validate one group/run (order-aware for jokers)
// setProblem(tiles) why a set isn't valid yet, in a few words
// canonicalOrder(tiles) a valid set laid out neatly (runs ascending)
// solvePartition(tiles) partition a multiset of tiles into valid sets
// bestRackSets(rack, …) best disjoint sets made from a rack alone
// attachToTable(table, …) lay single rack tiles onto table sets (ends,
// groups, splitting a long run in two)
// localResolve(table, …) re-solve the few table sets near a rack tile so it
// fits (the "big rearrange", bounded so it's fast)
// planPlay(rack, table, …) the turn planner every AI skill and the Coach use
//
// Tiles are plain { id, color, number, isJoker } descriptors and are never
// mutated here; a joker's meaning lives in isValidSet's `assignment`.
import { COLORS_ORDER, MIN_NUM, MAX_NUM } from './RummikubData.js';
@ -17,12 +21,14 @@ const CI = (c) => COLORS_ORDER.indexOf(c);
// ── Single-set validation ─────────────────────────────────────────────────────
// Returns { valid, kind, points, assignment } where assignment maps each joker
// tile id → { color, number } it represents (for display & scoring).
// tile id → { color, number } it represents. Jokers in a run take the slot they
// sit in when the tiles read as an ascending run in the order given; otherwise
// any legal placement is found (lowest start first).
export function isValidSet(tiles) {
if (!tiles || tiles.length < 3 || tiles.length > 13) return { valid: false };
const reals = tiles.filter((t) => !t.isJoker);
const jokers = tiles.filter((t) => t.isJoker);
if (reals.length === 0) return { valid: false }; // all-joker set never legal
if (reals.length === 0) return { valid: false }; // an all-joker set is never legal
// GROUP: same number, distinct colours, 3–4 tiles.
if (tiles.length <= 4) {
@ -41,36 +47,109 @@ export function isValidSet(tiles) {
// RUN: same colour, consecutive numbers, jokers fill gaps/ends.
const color = reals[0].color;
if (reals.every((t) => t.color === color)) {
const nums = reals.map((t) => t.number);
if (new Set(nums).size === nums.length) { // no duplicate numbers
const lo = Math.min(...nums), hi = Math.max(...nums);
const spanReals = hi - lo + 1;
const size = tiles.length;
if (spanReals <= size) {
const jLeft = size - reals.length; // jokers to place
// Place the run window so it contains [lo,hi]; extend with leftover jokers.
// Try every start position that keeps [lo,hi] inside a length-`size` window.
for (let start = Math.max(MIN_NUM, hi - size + 1); start <= lo; start++) {
const end = start + size - 1;
if (end > MAX_NUM) continue;
const haveReal = new Set(nums);
const gaps = [];
for (let v = start; v <= end; v++) if (!haveReal.has(v)) gaps.push(v);
if (gaps.length === jLeft) {
const assignment = {};
jokers.forEach((j, i) => { assignment[j.id] = { color, number: gaps[i] }; });
let points = 0;
for (let v = start; v <= end; v++) points += v;
return { valid: true, kind: 'run', points, assignment };
}
}
}
if (!reals.every((t) => t.color === color)) return { valid: false };
const nums = reals.map((t) => t.number);
if (new Set(nums).size !== nums.length) return { valid: false };
const size = tiles.length;
const runResult = (start) => {
const assignment = {};
let points = 0;
for (let v = start; v < start + size; v++) points += v;
return { start, assignment, points };
};
// 1) As ordered: the i-th tile is start + i.
const firstReal = tiles.findIndex((t) => !t.isJoker);
const start0 = tiles[firstReal].number - firstReal;
if (start0 >= MIN_NUM && start0 + size - 1 <= MAX_NUM
&& tiles.every((t, i) => t.isJoker || t.number === start0 + i)) {
const r = runResult(start0);
tiles.forEach((t, i) => { if (t.isJoker) r.assignment[t.id] = { color, number: start0 + i }; });
return { valid: true, kind: 'run', points: r.points, assignment: r.assignment };
}
// 2) Any placement that contains every real.
const lo = Math.min(...nums), hi = Math.max(...nums);
if (hi - lo + 1 > size) return { valid: false };
for (let start = Math.max(MIN_NUM, hi - size + 1); start <= lo; start++) {
const end = start + size - 1;
if (end > MAX_NUM) continue;
const have = new Set(nums);
const gaps = [];
for (let v = start; v <= end; v++) if (!have.has(v)) gaps.push(v);
if (gaps.length === jokers.length) {
const r = runResult(start);
jokers.forEach((j, i) => { r.assignment[j.id] = { color, number: gaps[i] }; });
return { valid: true, kind: 'run', points: r.points, assignment: r.assignment };
}
}
return { valid: false };
}
/** Points a set is worth (0 if invalid). */
export function setPoints(tiles) {
const v = isValidSet(tiles);
return v.valid ? v.points : 0;
}
/**
* Why a set isn't valid, in a few words for the label under its tray —
* "needs 1 more", "two reds", "gap at 8", "past 13"… or null when valid.
*/
export function setProblem(tiles) {
if (!tiles || !tiles.length) return null;
if (isValidSet(tiles).valid) return null;
const reals = tiles.filter((t) => !t.isJoker);
const jokers = tiles.length - reals.length;
if (!reals.length) return 'jokers need a real tile';
const sameNum = reals.every((t) => t.number === reals[0].number);
const sameCol = reals.every((t) => t.color === reals[0].color);
const colorCount = (c) => reals.filter((t) => t.color === c).length;
const dupColor = COLORS_ORDER.find((c) => colorCount(c) > 1);
const nums = reals.map((t) => t.number);
const dupNum = nums.find((n, i) => nums.indexOf(n) !== i);
const more = (n) => `needs ${n} more`;
if (sameNum && (!sameCol || reals.length === 1)) {
// a group in the making
if (dupColor) return `two ${dupColor}s`;
if (tiles.length > 4) return 'groups stop at 4';
return more(3 - tiles.length);
}
if (sameCol) {
if (dupNum != null) return `two ${dupNum}s`;
const lo = Math.min(...nums), hi = Math.max(...nums);
const span = hi - lo + 1;
if (span > reals.length + jokers) {
const have = new Set(nums);
for (let v = lo; v <= hi; v++) if (!have.has(v)) return `gap at ${v}`;
}
if (tiles.length < 3) return more(3 - tiles.length);
if (tiles.length > MAX_NUM - MIN_NUM + 1) return 'too long';
return 'past 13';
}
if (sameNum) return dupColor ? `two ${dupColor}s` : 'mixed up';
return 'mixed colours';
}
/** A valid set in display order: runs ascending, groups in colour order. Invalid sets are returned as-is. */
export function canonicalOrder(tiles) {
const v = isValidSet(tiles);
if (!v.valid) return tiles.slice();
const rep = (t) => (t.isJoker ? v.assignment[t.id] : t);
if (v.kind === 'run') return tiles.slice().sort((a, b) => rep(a).number - rep(b).number);
return tiles.slice().sort((a, b) => CI(rep(a).color) - CI(rep(b).color));
}
/** Represented { color, number } for every tile of a valid set (jokers resolved). */
export function representations(tiles) {
const v = isValidSet(tiles);
if (!v.valid) return null;
const out = {};
for (const t of tiles) out[t.id] = t.isJoker ? v.assignment[t.id] : { color: t.color, number: t.number };
return out;
}
// ── Pool helpers (counts + concrete tile objects) ─────────────────────────────
function buildPools(tiles) {
const byKey = new Map(); // 'color-num' → array of concrete tile objects
@ -104,15 +183,25 @@ function smallestRealKey(byKey) {
return best;
}
// Constructively partition `tiles` into valid sets. Returns an array of sets
// (each an array of concrete tile objects, jokers carrying a `_rep` assignment)
// or null if impossible. Bounded by a node budget so the AI can never hang.
const SOLVE_BUDGET = 12000; // node cap so the AI can never hang
function subsets(arr) {
const out = [[]];
for (const x of arr) {
const len = out.length;
for (let i = 0; i < len; i++) out.push([...out[i], x]);
}
return out;
}
export function solvePartition(tiles) {
// ── Whole-multiset partition ──────────────────────────────────────────────────
// Constructively partition `tiles` into valid sets. Returns an array of sets
// (each an array of tile objects in display order) or null if impossible.
// Bounded by a node budget so nothing can ever hang.
export const SOLVE_BUDGET = 12000;
export function solvePartition(tiles, budgetN = SOLVE_BUDGET) {
const { byKey, jokers } = buildPools(tiles);
const fails = new Set();
const budget = { n: SOLVE_BUDGET };
const budget = { n: budgetN };
const take = (key) => byKey.get(key).pop();
const give = (key, t) => byKey.get(key).push(t);
@ -127,49 +216,59 @@ export function solvePartition(tiles) {
const { color, num } = pick;
const candidates = [];
// Runs of `color` starting at `num` (num is the run minimum by construction).
// jokersNeeded only grows with L, so once it exceeds the pool we can stop.
for (let L = 3; num + L - 1 <= MAX_NUM; L++) {
const need = []; // concrete real keys to pull
let jokersNeeded = 0;
for (let v = num; v < num + L; v++) {
const k = `${color}-${v}`;
if (byKey.get(k)?.length) need.push(k);
else jokersNeeded++;
// Runs of `color` whose lowest REAL tile is `num`. Jokers may sit below it
// too (a run 1-joker-3 starts at a joker), so try a few leading jokers.
for (let lead = 0; lead <= Math.min(jokers.length, num - MIN_NUM); lead++) {
for (let L = 3; num - lead + L - 1 <= MAX_NUM; L++) {
if (L <= lead) continue;
const need = [];
let jokersNeeded = lead;
for (let v = num; v < num - lead + L; v++) {
const k = `${color}-${v}`;
if (byKey.get(k)?.length) need.push(k);
else jokersNeeded++;
}
if (jokersNeeded > jokers.length) break;
candidates.push({ need, jokersNeeded, lead, start: num - lead });
}
if (jokersNeeded > jokers.length) break;
candidates.push({ type: 'run', need, jokersNeeded, color, start: num, len: L });
}
// Groups at value `num` including `color`.
const present = COLORS_ORDER.filter((c) => c !== color && byKey.get(`${c}-${num}`)?.length);
const subs = subsets(present);
for (const R of subs) {
for (const R of subsets(present)) {
const baseColors = 1 + R.length;
for (let j = Math.max(0, 3 - baseColors); j <= Math.min(jokers.length, 4 - baseColors); j++) {
const size = baseColors + j;
if (size < 3 || size > 4) continue;
const need = [`${color}-${num}`, ...R.map((c) => `${c}-${num}`)];
candidates.push({ type: 'group', need, jokersNeeded: j, color, num });
candidates.push({ need: [`${color}-${num}`, ...R.map((c) => `${c}-${num}`)], jokersNeeded: j, group: true });
}
}
// Prefer candidates that use fewer jokers (keeps the search shallow).
candidates.sort((a, b) => a.jokersNeeded - b.jokersNeeded || b.need.length - a.need.length);
for (const cand of candidates) {
const pulledReal = cand.need.map((k) => ({ k, t: take(k) }));
const pulledJok = [];
for (let i = 0; i < cand.jokersNeeded; i++) pulledJok.push(jokers.pop());
const set = pulledReal.map((p) => p.t);
for (const j of pulledJok) set.push(j);
// attach representation for display/scoring
let set;
if (cand.group) set = [...pulledReal.map((p) => p.t), ...pulledJok];
else {
// lay the run out in order, jokers in the gaps / leading slots
set = [];
const reals = new Map(pulledReal.map((p) => [p.t.number, p.t]));
const jq = pulledJok.slice();
const len = cand.need.length + cand.jokersNeeded;
for (let v = cand.start; v < cand.start + len; v++) set.push(reals.get(v) ?? jq.pop());
}
const v = isValidSet(set);
if (v.valid) {
for (const j of pulledJok) j._rep = v.assignment[j.id];
set._meta = { kind: v.kind, points: v.points };
const ordered = canonicalOrder(set);
ordered._meta = { kind: v.kind, points: v.points };
const rest = rec();
if (rest) return [set, ...rest];
if (rest) return [ordered, ...rest];
}
// backtrack
for (const j of pulledJok) { delete j._rep; jokers.push(j); }
for (const j of pulledJok) jokers.push(j);
for (const p of pulledReal) give(p.k, p.t);
}
@ -180,155 +279,363 @@ export function solvePartition(tiles) {
return rec();
}
function subsets(arr) {
const out = [[]];
for (const x of arr) {
const len = out.length;
for (let i = 0; i < len; i++) out.push([...out[i], x]);
}
return out;
}
export function partitionable(tiles) {
if (!tiles.length) return true;
return solvePartition(tiles) !== null;
}
// ── Loose-pool set finding (for laying new sets / the initial meld) ───────────
// Greedily pull disjoint valid sets out of `poolTiles`, maximising tile count.
// Returns { sets: [[tile,...]], tilesUsed, points }.
export function findSetsFromPool(poolTiles) {
// For small pools, a full partition (laying everything down) is worth trying —
// this is how an AI goes out. Large pools rarely fully partition, so skip the
// expensive solve and go straight to greedy extraction.
if (poolTiles.length <= 15) {
const whole = solvePartition(poolTiles);
if (whole) {
let points = 0, used = 0;
for (const s of whole) { points += s._meta.points; used += s.length; }
return { sets: whole, tilesUsed: used, points };
// ── Sets from a rack ──────────────────────────────────────────────────────────
/**
* Every valid set that could be made from `tiles` (by value; concrete tiles are
* chosen when a selection is built). Runs up to 13 long, groups of 3–4,
* jokers filling at most `maxJokers` slots.
*/
function candidateSets(tiles, maxJokers) {
const { byKey, jokers } = buildPools(tiles);
const J = Math.min(maxJokers, jokers.length);
const has = (c, n) => (byKey.get(`${c}-${n}`)?.length ?? 0) > 0;
const out = [];
for (const color of COLORS_ORDER) {
for (let start = MIN_NUM; start <= MAX_NUM - 2; start++) {
let jk = 0;
const keys = [];
for (let v = start; v <= MAX_NUM; v++) {
if (has(color, v)) keys.push(`${color}-${v}`);
else jk++;
if (jk > J) break;
if (v - start + 1 >= 3 && keys.length) out.push({ keys: keys.slice(), jokers: jk, run: { color, start, len: v - start + 1 } });
}
}
}
// Otherwise repeatedly extract the best single set from what remains.
for (let num = MIN_NUM; num <= MAX_NUM; num++) {
const present = COLORS_ORDER.filter((c) => has(c, num));
for (const R of subsets(present)) {
if (!R.length) continue;
for (let j = 0; j <= J; j++) {
const size = R.length + j;
if (size < 3 || size > 4) continue;
out.push({ keys: R.map((c) => `${c}-${num}`), jokers: j, group: { num } });
}
}
}
// values for scoring
for (const c of out) {
if (c.run) c.points = (c.run.start * 2 + c.run.len - 1) * c.run.len / 2;
else c.points = c.group.num * (c.keys.length + c.jokers);
c.size = c.keys.length + c.jokers;
}
return { cands: out, byKey, jokers };
}
/** Build concrete tile arrays for a chosen list of candidate sets. */
function materialize(chosen, byKey, jokers) {
const avail = new Map([...byKey].map(([k, arr]) => [k, arr.slice()]));
const jq = jokers.slice();
return chosen.map((c) => {
if (c.group) {
const set = c.keys.map((k) => avail.get(k).pop());
for (let i = 0; i < c.jokers; i++) set.push(jq.pop());
return canonicalOrder(set);
}
const { color, start, len } = c.run;
const set = [];
for (let v = start; v < start + len; v++) {
const arr = avail.get(`${color}-${v}`);
set.push(arr && arr.length ? arr.pop() : jq.pop());
}
return set;
});
}
/**
* The best selection of disjoint sets from a rack.
* minPoints only selections worth at least this count (the opening meld)
* maxJokers jokers the sets may use (0 = keep them on the rack)
* budget search nodes
* Score: tiles laid first, then points. Returns { sets, tiles, points } or null.
*/
export function bestRackSets(rack, { minPoints = 0, maxJokers = 2, budget = 30000, preferPoints = false } = {}) {
const { cands, byKey, jokers } = candidateSets(rack, maxJokers);
if (!cands.length) return null;
// big sets first so good answers turn up early
cands.sort((a, b) => b.size - a.size || b.points - a.points);
const count = new Map([...byKey].map(([k, arr]) => [k, arr.length]));
let jokersLeft = Math.min(maxJokers, jokers.length);
const realTotal = rack.filter((t) => !t.isJoker).length;
let freeReal = realTotal;
let best = null;
const chosen = [];
let tiles = 0, points = 0, nodes = 0;
const score = (t, p) => (preferPoints ? p * 100 + t : t * 1000 + p);
function consider() {
if (points < minPoints || !chosen.length) return;
const s = score(tiles, points);
if (!best || s > best.score) best = { score: s, chosen: chosen.slice(), tiles, points };
}
function rec(i) {
if (++nodes > budget) return;
consider();
// bound: even laying every remaining tile can't beat the best
if (best && !preferPoints && (tiles + freeReal + jokersLeft) * 1000 + 999 < best.score) return;
for (let k = i; k < cands.length; k++) {
const c = cands[k];
if (c.jokers > jokersLeft) continue;
let ok = true;
for (const key of c.keys) if (!(count.get(key) > 0)) { ok = false; break; }
if (!ok) continue;
for (const key of c.keys) count.set(key, count.get(key) - 1);
jokersLeft -= c.jokers;
freeReal -= c.keys.length;
chosen.push(c); tiles += c.size; points += c.points;
rec(k + 1);
chosen.pop(); tiles -= c.size; points -= c.points;
freeReal += c.keys.length;
jokersLeft += c.jokers;
for (const key of c.keys) count.set(key, count.get(key) + 1);
if (nodes > budget) return;
}
}
rec(0);
if (!best) return null;
return { sets: materialize(best.chosen, byKey, jokers), tiles: best.tiles, points: best.points };
}
// ── Loose-pool greedy (the beginner's eye) ────────────────────────────────────
/** Greedily pull disjoint valid sets out of a rack, biggest first. */
export function findSetsFromPool(poolTiles) {
let remaining = poolTiles.slice();
const sets = [];
let guard = 0;
while (guard++ < 60) {
const best = extractOneSet(remaining);
if (!best) break;
sets.push(best.set);
const usedIds = new Set(best.set.map((t) => t.id));
remaining = remaining.filter((t) => !usedIds.has(t.id));
for (let guard = 0; guard < 40; guard++) {
const { cands, byKey, jokers } = candidateSets(remaining, 2);
if (!cands.length) break;
cands.sort((a, b) => b.size - a.size || b.points - a.points);
const set = materialize([cands[0]], byKey, jokers)[0];
sets.push(set);
const used = new Set(set.map((t) => t.id));
remaining = remaining.filter((t) => !used.has(t.id));
}
let points = 0, used = 0;
for (const s of sets) { const v = isValidSet(s); points += v.points; used += s.length; }
for (const s of sets) { points += setPoints(s); used += s.length; }
return { sets, tilesUsed: used, points };
}
// Find one valid set inside a loose pool (prefers larger / higher-scoring sets).
function extractOneSet(pool) {
const { byKey, jokers } = buildPools(pool);
let best = null;
// Try runs by colour.
for (const color of COLORS_ORDER) {
for (let start = MIN_NUM; start <= MAX_NUM - 2; start++) {
for (let L = 3; start + L - 1 <= MAX_NUM; L++) {
const set = [];
let jUsed = 0, ok = true;
const jpool = jokers.slice();
const usedByKey = new Map();
for (let v = start; v < start + L; v++) {
const k = `${color}-${v}`;
const avail = (byKey.get(k)?.length || 0) - (usedByKey.get(k) || 0);
if (avail > 0) { usedByKey.set(k, (usedByKey.get(k) || 0) + 1); set.push(findTile(pool, color, v, set)); }
else if (jpool.length) { set.push(jpool.pop()); jUsed++; }
else { ok = false; break; }
// ── Laying single tiles onto the table ────────────────────────────────────────
/**
* Lay rack tiles onto existing table sets one at a time: run ends, the
* missing colour of a group, swapping a real tile for a table joker (the
* joker then has to be placed too), and — with `split` — dropping a
* duplicate into the middle of a long run to break it into two runs.
* Returns { table, played: [ids] } (table is a new array of new sets).
*/
export function attachToTable(table, rack, { split = false, jokers = false } = {}) {
let sets = table.map((s) => s.slice());
const played = [];
let left = rack.filter((t) => jokers || !t.isJoker);
let changed = true;
for (let guard = 0; changed && guard < 60; guard++) {
changed = false;
for (const t of left) {
let placed = false;
for (let si = 0; si < sets.length && !placed; si++) {
const s = sets[si];
for (const trial of [[...s, t], [t, ...s]]) {
if (isValidSet(trial).valid) { sets[si] = canonicalOrder(trial); placed = true; break; }
}
if (ok) { const v = isValidSet(set); if (v.valid) best = better(best, set, v); }
if (placed) break;
if (split && !t.isJoker && s.length >= 5) {
const parts = splitWith(s, t);
if (parts) { sets.splice(si, 1, ...parts); placed = true; }
}
}
if (placed) {
played.push(t.id);
left = left.filter((x) => x.id !== t.id);
changed = true;
break;
}
}
}
// Try groups by value.
for (let num = MIN_NUM; num <= MAX_NUM; num++) {
const colorsHere = COLORS_ORDER.filter((c) => byKey.get(`${c}-${num}`)?.length);
for (const R of subsets(colorsHere)) {
if (R.length < 1) continue;
for (let j = 0; j <= jokers.length; j++) {
const size = R.length + j;
if (size < 3 || size > 4) continue;
const set = R.map((c) => findTile(pool, c, num, [])).filter(Boolean);
for (let i = 0; i < j; i++) set.push(jokers[i]);
// ensure distinct concrete ids
if (new Set(set.map((t) => t.id)).size !== set.length) continue;
const v = isValidSet(set);
if (v.valid) best = better(best, set, v);
return { table: sets, played };
}
/** Put tile `t` into the middle of a valid run so it becomes two valid runs. */
function splitWith(set, t) {
const v = isValidSet(set);
if (!v.valid || v.kind !== 'run') return null;
const ordered = canonicalOrder(set);
const rep = (x) => (x.isJoker ? v.assignment[x.id] : x);
if (rep(ordered[0]).color !== t.color) return null;
const i = ordered.findIndex((x) => rep(x).number === t.number);
if (i < 2 || i > ordered.length - 3) return null;
const a = [...ordered.slice(0, i), t];
const b = ordered.slice(i);
if (isValidSet(a).valid && isValidSet(b).valid) return [a, b];
return null;
}
// ── Local re-solve (the big rearrange, bounded) ──────────────────────────────
const near = (a, b) => {
if (a.isJoker || b.isJoker) return false;
return a.number === b.number || (a.color === b.color && Math.abs(a.number - b.number) <= 2);
};
/**
* For each rack tile, gather the table sets it could interact with (same
* number, or same colour within two), and re-solve just those sets with the
* tile added (plus any other rack tiles that fit the same neighbourhood).
* Returns { table, played }.
*/
export function localResolve(table, rack, { budget = 4000, maxPool = 26, combos = true, timeLimit = 400 } = {}) {
let sets = table.map((s) => s.slice());
const played = [];
let left = rack.filter((t) => !t.isJoker);
const t0 = Date.now();
for (let pass = 0; pass < 3; pass++) {
let progress = false;
for (const t of left.slice()) {
if (Date.now() - t0 > timeLimit) break;
if (!left.includes(t)) continue;
const idx = [];
sets.forEach((s, i) => { if (s.some((x) => near(x, t))) idx.push(i); });
if (!idx.length) continue;
let pool = idx.flatMap((i) => sets[i]);
if (pool.length + 1 > maxPool) {
// keep the closest sets only
idx.sort((a, b) => dist(sets[a], t) - dist(sets[b], t));
while (idx.length > 1 && idx.flatMap((i) => sets[i]).length + 1 > maxPool) idx.pop();
pool = idx.flatMap((i) => sets[i]);
}
let sol = solvePartition([...pool, t], budget);
let extra = [];
if (!sol && combos) {
const friends = left.filter((x) => x !== t && near(x, t));
if (friends.length && pool.length + 1 + friends.length <= maxPool + 4) {
sol = solvePartition([...pool, t, ...friends], budget);
if (sol) extra = friends;
}
}
if (!sol) continue;
// greedily fold in any other neighbourhood rack tiles
let cur = [...pool, t, ...extra];
for (const f of left) {
if (f === t || extra.includes(f) || !near(f, t)) continue;
const s2 = solvePartition([...cur, f], budget);
if (s2) { sol = s2; cur = [...cur, f]; extra = [...extra, f]; }
}
const keep = sets.filter((_, i) => !idx.includes(i));
sets = [...keep, ...sol];
for (const x of [t, ...extra]) { played.push(x.id); }
const gone = new Set([t, ...extra].map((x) => x.id));
left = left.filter((x) => !gone.has(x.id));
progress = true;
}
if (!progress) break;
}
return { table: sets, played };
}
function dist(set, t) {
let d = 99;
for (const x of set) {
if (x.isJoker) continue;
if (x.number === t.number) d = Math.min(d, 0);
if (x.color === t.color) d = Math.min(d, Math.abs(x.number - t.number));
}
return d;
}
// ── The turn planner ──────────────────────────────────────────────────────────
/**
* What to lay down this turn.
* rack, table the player's rack and the committed table (array of sets)
* opts.melded has this player made their opening meld?
* opts.openMin the opening-meld minimum
* opts.level 1 greedy rack sets · 2 best rack sets + single tiles
* onto set ends · 3 + splitting long runs ·
* 4 + local re-solves · 5 + wider re-solves and a
* whole-table solve when it's small
* opts.holdJokers keep rack jokers back unless they matter
* Returns { tilesPlayed: [ids], newTable, firstMeld, points } or null (→ draw).
*/
export function planPlay(rack, table, { melded = false, openMin = 30, level = 5, holdJokers = false } = {}) {
const base = table.map((s) => s.slice());
const rackSets = (tiles, minPoints, maxJ) => {
if (level <= 1) {
const g = findSetsFromPool(tiles.filter((t) => maxJ > 0 || !t.isJoker));
if (!g.tilesUsed || g.points < minPoints) return null;
return { sets: g.sets, tiles: g.tilesUsed, points: g.points };
}
return bestRackSets(tiles, { minPoints, maxJokers: maxJ, preferPoints: minPoints > 0 && !melded });
};
if (!melded) {
// Opening meld: sets purely from the rack worth ≥ openMin.
let r = rackSets(rack, openMin, holdJokers ? 0 : 2);
if (!r && holdJokers) r = rackSets(rack, openMin, 2);
if (!r) return null;
// with the opening made, lay as many tiles as possible among the passing selections
if (level >= 2) {
const more = bestRackSets(rack, { minPoints: openMin, maxJokers: holdJokers && !r.sets.flat().some((t) => t.isJoker) ? 0 : 2 });
if (more && more.tiles > r.tiles) r = more;
}
const ids = r.sets.flat().map((t) => t.id);
return { tilesPlayed: ids, newTable: [...base, ...r.sets], firstMeld: true, points: r.points };
}
const tryPlan = (maxJ) => {
let tableNow = base;
let rackLeft = rack.slice();
const played = [];
const take = (ids) => {
const s = new Set(ids);
played.push(...ids);
rackLeft = rackLeft.filter((t) => !s.has(t.id));
};
const allowedJ = (tiles) => tiles.filter((t) => maxJ > 0 || !t.isJoker);
// 1) whole new sets from the rack
const r = rackSets(allowedJ(rackLeft), 0, maxJ);
if (r && r.tiles) { tableNow = [...tableNow, ...r.sets]; take(r.sets.flat().map((t) => t.id)); }
// 2) single tiles onto table sets
if (level >= 2) {
const a = attachToTable(tableNow, rackLeft, { split: level >= 3, jokers: level >= 3 && maxJ > 0 && rackLeft.length <= 2 });
if (a.played.length) { tableNow = a.table; take(a.played); }
}
// 3) the rearrange
if (level >= 4 && rackLeft.some((t) => !t.isJoker)) {
const lr = localResolve(tableNow, rackLeft, { combos: level >= 5, budget: level >= 5 ? 5000 : 2500 });
if (lr.played.length) { tableNow = lr.table; take(lr.played); }
if (level >= 5 && rackLeft.length) {
// and anything that now lands on the reshaped table
const a2 = attachToTable(tableNow, rackLeft, { split: true, jokers: maxJ > 0 && rackLeft.length <= 2 });
if (a2.played.length) { tableNow = a2.table; take(a2.played); }
}
}
}
return best;
// 4) whole-table solve for the last few tiles (strong players, small tables)
if (level >= 5 && rackLeft.length && rackLeft.length <= 4) {
const flat = tableNow.flat();
if (flat.length + rackLeft.length <= 40) {
const all = solvePartition([...flat, ...rackLeft], 8000);
if (all) { tableNow = all; take(rackLeft.map((t) => t.id)); }
}
}
if (!played.length) return null;
const points = tableNow.reduce((a, s) => a + setPoints(s), 0) - base.reduce((a, s) => a + setPoints(s), 0);
return { tilesPlayed: played, newTable: tableNow, firstMeld: false, points, rackLeft: rackLeft.length };
};
const full = tryPlan(2);
if (!holdJokers || !full) return full;
const usesJoker = full.tilesPlayed.some((id) => rack.find((t) => t.id === id)?.isJoker);
if (!usesJoker || full.rackLeft === 0) return full; // going out: spend it
const lean = tryPlan(0);
if (lean && full.tilesPlayed.length - lean.tilesPlayed.length <= 2) return lean;
return full;
}
function findTile(pool, color, num, exclude) {
const ex = new Set(exclude.map((t) => t.id));
return pool.find((t) => !t.isJoker && t.color === color && t.number === num && !ex.has(t.id));
}
function better(best, set, v) {
const score = set.length * 100 + v.points;
if (!best || score > best.score) return { set: set.slice(), points: v.points, score };
return best;
}
// ── AI turn planner ───────────────────────────────────────────────────────────
// Given the player's rack and the current table, decide what to lay down.
// Returns { tilesPlayed: [ids], newTable: [[tile,...]] } or null (→ draw).
/** Back-compat wrapper for older callers/tests. */
export function bestMeldDecomposition(rackTiles, tableTiles, { mustReach = 0, alreadyMelded = false, manipulate = false } = {}) {
if (!alreadyMelded) {
// First meld: form sets purely from the rack worth ≥ mustReach.
const found = findSetsFromPool(rackTiles);
if (found.points >= mustReach && found.tilesUsed > 0) {
const playedIds = found.sets.flat().map((t) => t.id);
return { tilesPlayed: playedIds, newTable: [...cloneSets(tableTiles), ...found.sets], firstMeld: true };
}
return null;
}
// Already melded. 1) Always-safe: lay any complete new sets made from the rack.
const newSets = findSetsFromPool(rackTiles);
let table = cloneSets(tableTiles);
let played = [];
if (newSets.tilesUsed > 0) {
table = [...table, ...newSets.sets];
played = newSets.sets.flat().map((t) => t.id);
}
const playedSet = new Set(played);
let rackLeft = rackTiles.filter((t) => !playedSet.has(t.id));
// 2) Manipulation (higher skill): try to attach more rack tiles by re-solving
// the whole table. Single capped pass — add any rack tile that keeps the
// table partitionable. Skipped when the table is large (solver too costly).
if (manipulate && rackLeft.length && table.flat().length <= 26) {
let pool = table.flat();
let solves = 0;
for (let i = 0; i < rackLeft.length && solves < 24; i++) {
solves++;
const trial = solvePartition([...pool, rackLeft[i]]);
if (trial) {
pool = trial.flat();
played.push(rackLeft[i].id);
table = trial;
}
}
}
if (played.length === 0) return null;
return { tilesPlayed: played, newTable: table, firstMeld: false };
}
// Deep-ish clone of table sets (new arrays; tile objects shared by reference are
// fine — callers treat tiles as immutable descriptors).
function cloneSets(tableTiles) {
// tableTiles may be a flat tile array OR an array of sets. Normalise to sets is
// the caller's job; here we expect an array of sets.
return (tableTiles || []).map((s) => s.slice());
return planPlay(rackTiles, tableTiles, { melded: alreadyMelded, openMin: mustReach, level: manipulate ? 5 : 2 });
}

View File

@ -0,0 +1,251 @@
// Rummikub table layout — Phaser-free so tools/verifyRummikub.js can test it.
//
// "Aunt Rivka's Kitchen": her oilcloth-covered kitchen table seen from your
// chair. Tiles lie flat and upright in screen space (no perspective squash —
// you need to read a lot of small numbers at once); the room art supplies the
// depth. You sit at the bottom with a two-tier wooden rack; opponents' racks
// stand at the far edge (top) and the two ends (left / right), backs to you.
//
// Screen bands, top to bottom:
// top opponent rack + plates · the table (sets flow in rows) · the readout
// strip (opening-meter, status, timer, Hint/Tidy) · your rack.
import {
W, H, PLATE, HUMAN_PLATE, DOCK, plateRect, hudFurniture, rectsOverlap, onScreen, centreRect, unionRect,
} from '../../ui/cardtable/TableGeometry.js';
export { W, H, PLATE };
// ── Tiles ────────────────────────────────────────────────────────────────────
export const TILE = { w: 56, h: 76 }; // a tile at scale 1 (textures are baked at 2×)
export const TILE_RES = 2;
// you · then the opponents clockwise
export const SEAT_COLORS = [0xf2c46a, 0xe8806a, 0x7ab8e0, 0x9ad08a];
export const SEAT_HEX = ['#f2c46a', '#e8806a', '#7ab8e0', '#9ad08a'];
// ── Regions ──────────────────────────────────────────────────────────────────
export const TABLE = { x0: 150, x1: 1600, y0: 214, y1: 834 };
export const READOUT = { y: 868, x0: 470, x1: 1560 };
export const METER = { x: 470, y: 868, w: 250 };
export const STATUS = { x: 1010, y: 868 };
export const TIMER = { x: 1180, y: 868 };
export const MINI_BTNS = [{ key: 'hint', x: 1404, y: 868, w: 96, h: 34 }, { key: 'tidy', x: 1508, y: 868, w: 96, h: 34 }];
export const POOL = { x: 1716, y: 660 };
export const RIVKA = { x: 300, y: 790 }; // Aunt Rivka's note (her advice)
export const RACK = { x0: 470, x1: 1560, rows: [941, 1027] };
export const RACK_BOARD = { x0: 440, x1: 1590, y0: 892, y1: 1076 };
const SIDES = { 2: ['top'], 3: ['left', 'right'], 4: ['left', 'top', 'right'] };
/** 'bottom' for you, else where opponent `seat` sits. */
export function sideOf(playerCount, seat) {
if (seat === 0) return 'bottom';
return SIDES[playerCount]?.[seat - 1] ?? 'top';
}
const OPP = {
top: { x: 900, y: 82, rot: 0, s: 0.52, maxSpan: 560, plate: { x: 1400, y: 76 }, bubble: { x: 1400, y: 168 }, spot: { x: 900, y: 120, w: 780, h: 260 } },
left: { x: 64, y: 520, rot: Math.PI / 2, s: 0.52, maxSpan: 470, plate: { x: 190, y: 150 }, bubble: { x: 250, y: 244 }, spot: { x: 90, y: 520, w: 300, h: 640 } },
right: { x: 1856, y: 520, rot: -Math.PI / 2, s: 0.52, maxSpan: 470, plate: { x: 1730, y: 150 }, bubble: { x: 1670, y: 244 }, spot: { x: 1830, y: 520, w: 300, h: 640 } },
};
export function seatGeom(playerCount, seat) {
const side = sideOf(playerCount, seat);
if (side === 'bottom') return { side, plate: HUMAN_PLATE, spot: { x: 1015, y: 960, w: 1300, h: 340 }, bubble: { x: 300, y: 790 } };
return { side, ...OPP[side] };
}
// ── Opponent racks (backs toward you) ────────────────────────────────────────
export function oppTilePose(playerCount, seat, i, n) {
const g = seatGeom(playerCount, seat);
const step = Math.min(TILE.w * g.s + 2, n > 1 ? g.maxSpan / (n - 1) : 0);
const d = (i - (n - 1) / 2) * step;
const along = { x: Math.cos(g.rot), y: Math.sin(g.rot) };
// two rows when it gets crowded, like a real rack's second tier
return { x: g.x + along.x * d, y: g.y + along.y * d, rot: g.rot, s: g.s, q: 1 };
}
/** Where an opponent's hand rests (ghost hand) and where their tiles leave from. */
export function oppHome(playerCount, seat) {
const g = seatGeom(playerCount, seat);
const inward = g.side === 'top' ? { x: 0, y: 70 } : g.side === 'left' ? { x: 80, y: 0 } : { x: -80, y: 0 };
return { x: g.x + inward.x, y: g.y + inward.y, rot: g.side === 'top' ? Math.PI : g.side === 'left' ? Math.PI / 2 : -Math.PI / 2, k: 0.5 };
}
// ── Your rack ────────────────────────────────────────────────────────────────
export function rackScale(big) { return big ? 1.1 : 1; }
/** Tiles per row before the rack compresses. */
export function rackPerRow(big) {
const s = rackScale(big);
return Math.floor((RACK.x1 - RACK.x0) / (TILE.w * s + 4));
}
/** Pose of rack tile i of n. The top tier fills first; past two full tiers the spacing tightens. */
export function rackPose(i, n, big = false, lift = 0) {
const s = rackScale(big);
const width = RACK.x1 - RACK.x0;
const full = rackPerRow(big);
let perRow = full, step = TILE.w * s + 4;
if (n > full * 2) { perRow = Math.ceil(n / 2); step = width / perRow; }
const row = i < perRow ? 0 : 1;
const inRow = row === 0 ? Math.min(n, perRow) : n - perRow;
const col = row === 0 ? i : i - perRow;
const rowW = (inRow - 1) * step;
const cx = (RACK.x0 + RACK.x1) / 2;
return { x: cx - rowW / 2 + col * step, y: RACK.rows[row] - lift * 10, rot: 0, s, q: 1 };
}
/** Rack insertion slot nearest a point, for n tiles already on the rack. */
export function rackInsertAt(pt, n, big = false) {
let best = n, bestD = Infinity;
for (let k = 0; k <= n; k++) {
const p = rackPose(k, n + 1, big);
const d = (pt.x - p.x) ** 2 + ((pt.y - p.y) * 1.6) ** 2;
if (d < bestD) { bestD = d; best = k; }
}
return best;
}
export function inRack(pt) {
return pt.x >= RACK_BOARD.x0 && pt.x <= RACK_BOARD.x1 && pt.y >= RACK_BOARD.y0 - 20 && pt.y <= H;
}
// ── The table: sets flow in rows ─────────────────────────────────────────────
const SCALES = [0.84, 0.76, 0.68, 0.61, 0.55, 0.5];
const BIG_SCALES = [0.94, 0.84, 0.76, 0.68, 0.61, 0.55, 0.5];
const PAD = 9; // tray padding around tiles
const GAP = 4; // between tiles in a set
const SET_GAP = 22; // between sets
const LABEL = 26; // room under a tray for its label
function flow(lengths, s, ghostLen) {
const tw = TILE.w * s, th = TILE.h * s;
const step = tw + GAP;
const rowH = th + PAD * 2 + LABEL;
let x = TABLE.x0, y = TABLE.y0;
const boxes = [];
const place = (len) => {
const w = len * step - GAP + PAD * 2;
if (x + w > TABLE.x1 && x > TABLE.x0) { x = TABLE.x0; y += rowH; }
const box = { x0: x, x1: x + w, y0: y, y1: y + th + PAD * 2 };
box.cx = (box.x0 + box.x1) / 2;
box.cy = (box.y0 + box.y1) / 2;
box.tiles = Array.from({ length: len }, (_, i) => ({ x: x + PAD + tw / 2 + i * step, y: box.cy }));
x += w + SET_GAP;
return box;
};
for (const len of lengths) boxes.push(place(len));
const ghost = ghostLen ? place(ghostLen) : null;
const bottom = (ghost ?? boxes[boxes.length - 1])?.y1 ?? TABLE.y0;
return { s, tw, th, step, rowH, boxes, ghost, fits: bottom + LABEL - 6 <= TABLE.y1 };
}
/**
* Lay out the table's sets (array of lengths). opts: { ghost: true → a
* trailing "new set" slot, big }. Shrinks the tiles until everything fits.
*/
export function layoutTable(lengths, { ghost = true, big = false } = {}) {
const scales = big ? BIG_SCALES : SCALES;
let out = null;
for (const s of scales) {
out = flow(lengths, s, ghost ? 3 : 0);
if (out.fits) return out;
}
return out;
}
/**
* What a point is over on a laid-out table:
* { type: 'set', index, at } — over set `index`, inserting at `at`
* { type: 'newSet' } — the ghost slot or open table
* null — off the table
*/
export function tableTargetAt(lay, pt) {
const padX = 14, padY = 16;
for (let i = 0; i < lay.boxes.length; i++) {
const b = lay.boxes[i];
if (pt.x < b.x0 - padX || pt.x > b.x1 + padX || pt.y < b.y0 - padY || pt.y > b.y1 + padY) continue;
const at = b.tiles.filter((t) => t.x < pt.x).length;
return { type: 'set', index: i, at };
}
if (pt.x >= TABLE.x0 - 30 && pt.x <= TABLE.x1 + 30 && pt.y >= TABLE.y0 - 30 && pt.y <= TABLE.y1 + 10) return { type: 'newSet' };
return null;
}
/** The tile (by box & index) under a point. */
export function tableTileAt(lay, pt) {
const hw = lay.tw / 2 + 1, hh = lay.th / 2 + 1;
for (let i = 0; i < lay.boxes.length; i++) {
const b = lay.boxes[i];
if (pt.y < b.y0 || pt.y > b.y1) continue;
for (let k = 0; k < b.tiles.length; k++) {
const t = b.tiles[k];
if (Math.abs(pt.x - t.x) <= hw && Math.abs(pt.y - t.y) <= hh) return { set: i, k };
}
}
return null;
}
// ── Layout self-check (tools/verifyRummikub.js) ──────────────────────────────
export function verifyLayout() {
const problems = [];
const tileRect = (p) => {
const c = Math.abs(Math.cos(p.rot)), sn = Math.abs(Math.sin(p.rot));
const w = TILE.w * p.s, h = TILE.h * p.s;
const hw = (w * c + h * sn) / 2, hh = (w * sn + h * c) / 2;
return { x0: p.x - hw, x1: p.x + hw, y0: p.y - hh, y1: p.y + hh };
};
// the table at worst: ~95 tiles in 28 sets of 3–4 (plus the ghost)
for (const big of [false, true]) {
const lengths = Array.from({ length: 28 }, (_, i) => (i % 3 === 0 ? 4 : 3));
lengths.push(13, 12);
const lay = layoutTable(lengths, { big });
if (!lay.fits) problems.push(`table${big ? ' (big tiles)' : ''}: ${lengths.length} sets don't fit even at scale ${lay.s}`);
const lay2 = layoutTable([3, 4, 5, 3], { big });
if (lay2.s < (big ? 0.9 : 0.8)) problems.push('a small table should not shrink');
}
// the rack at worst: 40 tiles
let rackR = null;
for (const big of [false, true]) {
for (const n of [1, 14, 19, 30, 40]) {
for (let i = 0; i < n; i++) {
const r = tileRect(rackPose(i, n, big, 1));
rackR = unionRect(rackR, r);
if (r.x0 < RACK_BOARD.x0 || r.x1 > RACK_BOARD.x1) problems.push(`rack (${n}${big ? ' big' : ''}) tile ${i} leaves the rack board`);
}
// no two tiles of the same row overlap
for (let i = 1; i < n; i++) {
const a = rackPose(i - 1, n, big), b = rackPose(i, n, big);
if (a.y === b.y && b.x - a.x < TILE.w * a.s * 0.82) problems.push(`rack (${n}${big ? ' big' : ''}) tiles ${i - 1}/${i} overlap too much`);
}
}
}
const tableR = { x0: TABLE.x0, x1: TABLE.x1, y0: TABLE.y0, y1: TABLE.y1 };
const named = [['your rack', rackR], ['the table', tableR], ['pool', { x0: POOL.x - 70, x1: POOL.x + 70, y0: POOL.y - 70, y1: POOL.y + 80 }]];
for (const pc of [2, 3, 4]) {
for (let seat = 1; seat < pc; seat++) {
const g = seatGeom(pc, seat);
let r = null;
for (let i = 0; i < 40; i++) r = unionRect(r, tileRect(oppTilePose(pc, seat, i, 40)));
named.push([`${g.side} rack (${pc}p)`, r], [`${g.side} plate (${pc}p)`, plateRect(g.plate)]);
}
}
for (const [name, r] of named) if (!onScreen(r, 2)) problems.push(`${name} off screen`);
for (let i = 0; i < named.length; i++) {
for (let j = i + 1; j < named.length; j++) {
const [a, ra] = named[i], [b, rb] = named[j];
if (a.split(' ')[0] === b.split(' ')[0] && a.includes('(') && b.includes('(')) continue; // same seat
if (rectsOverlap(ra, rb)) problems.push(`${a} overlaps ${b}`);
}
}
for (const f of hudFurniture()) {
for (const [name, r] of named) {
if (rectsOverlap(f.r, r)) problems.push(`${name} overlaps ${f.name}`);
}
}
for (const b of MINI_BTNS) if (rectsOverlap(centreRect(b), rackR) || rectsOverlap(centreRect(b), DOCK)) problems.push(`${b.key} button overlaps`);
return [...new Set(problems)];
}

View File

@ -0,0 +1,107 @@
// Rummikub — table talk at Aunt Rivka's. Two voices:
// rivkaLine(kind, ctx) your hostess (and Coach): warm, a little bossy,
// always on your side
// opponentLine(kind, ctx) whoever you're playing: friendly needling
// Each returns a line or null (some moments only get a remark now and then,
// so nobody nags).
const RIVKA = {
welcome: [
'Sit, sit. Fourteen tiles each — and nobody leaves until the kettle\'s empty.',
'Push the cat off the chair, dear. Let\'s play.',
'Sunday tile night! I\'ve got rugelach in the oven.',
],
welcomeBack: [
'There you are! Your tiles are right where you left them.',
'I kept your seat warm. Let\'s finish this.',
],
open: [
'You\'re in! Now the whole table is yours to play with.',
'Lovely opening. Now we can have some fun.',
'That\'s {points} — you\'re in the game, dear.',
],
bigPlay: [
'{n} tiles in one go! Look at you.',
'Now THAT is how we play on Sundays.',
'Ooh, the whole table glows green. Beautiful.',
],
rearrange: [
'A rearrange! I taught you that.',
'Clever — you moved their tiles to make room for yours.',
],
missed: [
'You could have laid down {n} there, dear. Next time ask me — press Hint.',
'Mm. There was a play there. {lines}',
'Don\'t be shy with your tiles — {n} could have gone down.',
],
stuckOpen: [
'Still waiting on that opening {min}? Keep collecting — runs add up fast.',
'Patience. A run of high tiles and you\'re in.',
],
oneLeft: [
'{name} has one tile left — lay down your big ones!',
'Careful, {name} is nearly out. Get your high tiles down.',
],
joker: [
'A joker! Hold it for the big play if you can.',
'Ooh, the jester. Don\'t waste him on something small.',
],
youWin: [
'Out! That\'s my clever one.',
'You emptied your rack! Have a cookie.',
'Mazel tov! Not a tile left.',
],
theyWin: [
'Well. They had the tiles tonight.',
'Never mind, dear. Shuffle them up and we go again.',
],
stalled: [
'Nobody can move and the bag is empty — lowest rack wins.',
],
timeout: [
'Time\'s up, dear! Back they go — and {n} from the bag.',
],
invalid: [
'Not yet — look for the red trays.',
'Something on the table isn\'t a set yet. Check the red ones.',
],
hintNone: [
'Nothing to lay down this turn, dear. Draw a tile.',
'I don\'t see a play. Take one from the bag.',
],
};
const OPP = {
open: ['Finally, I\'m in!', 'There — {points} on the table.', 'That\'s my opening.'],
bigPlay: ['Did you see that? {n} tiles!', 'Ha! Try to beat that.', 'That\'s how it\'s done.'],
rearrange: ['Don\'t mind me, just tidying your sets.', 'I\'ll borrow this one…', 'A little shuffle here, a little there.'],
draw: ['Hmm. I\'ll draw.', 'Nothing for me.', 'Come on, bag…'],
oneLeft: ['One tile left!', 'Almost there…', 'Watch out — one to go.'],
win: ['Out! Read \'em and weep.', 'Not a tile left on my rack!', 'Sorry, Rivka — I win this one.'],
lose: ['Next round is mine.', 'Rematch!', 'I had such good tiles, too.'],
youBig: ['Show-off.', 'Where did THAT come from?', 'Hey, those were my sets!'],
};
const CHANCE = {
open: 0.7, bigPlay: 0.8, rearrange: 0.6, draw: 0.12, oneLeft: 1, win: 1, lose: 0.7, youBig: 0.6,
missed: 0.8, stuckOpen: 0.5, joker: 0.6,
};
function pick(pool, ctx) {
const line = pool[Math.floor(Math.random() * pool.length)];
return line.replace(/\{(\w+)\}/g, (_, k) => (ctx[k] ?? ''));
}
export function rivkaLine(kind, ctx = {}) {
const pool = RIVKA[kind];
if (!pool) return null;
if (!ctx.force && Math.random() > (CHANCE[kind] ?? 1)) return null;
return pick(pool, ctx);
}
export function opponentLine(kind, ctx = {}) {
const pool = OPP[kind];
if (!pool) return null;
if (!ctx.force && Math.random() > (CHANCE[kind] ?? 1)) return null;
return pick(pool, ctx);
}

View File

@ -1,55 +1,74 @@
# Rummikub — Racks, Runs, and the Joy of the Big Rearrange
*By Aunt Rivka, who has hosted Sunday tile night for thirty-one years and has never once let anyone leave early*
*By Aunt Rivka, who has hosted Sunday tile night at her kitchen table for thirty-one years and has never once let anyone leave early*
---
Sit, sit. Push the cat off the chair. You see these little numbered tiles all face-down in the middle? We call that the **pool**. Everyone gets a rack of fourteen, and the whole game is a race to be the first to lay every last one of them down on the table. Simple to learn, and then it gets its claws in you. Let me show you.
Sit, sit. Push the cat off the chair — he'll go back to the windowsill, he always does. You see that velvet bag by the teapot? That's the **pool**. Everyone gets a rack of fourteen tiles, and the whole game is a race to be the first to lay every last one of them down on the table. Simple to learn, and then it gets its claws in you. Let me show you.
## The Goal
Be the **first to empty your rack**. That's it. When your rack is bare, you've won the round and everyone else groans and totals up the tiles they got stuck with.
Be the **first to empty your rack**. When your rack is bare, you've won the round, and everyone else pays you what's left on theirs.
## The Tiles
There are **106** of them: the numbers **1 through 13** in **four colours** — red, blue, black and orange — two of each. And **two jokers**, the wild rascals that can stand in for any tile you like.
There are **106** of them: the numbers **1 through 13** in **four colours** — red, blue, black and orange — two of each. And **two jokers**, the grinning rascals that can stand in for any tile you like. (If the colours are hard to tell apart, turn on **Colour glyphs** in Settings and every tile gets a little ♥, drop, square or sun.)
## What Counts as a Set
Everything you lay on the table must belong to a valid **set**, and there are only two kinds:
Everything on the table must belong to a valid **set**, and there are only two kinds:
- **A Group** — three or four tiles of the **same number**, each a **different colour**. (Red 7, blue 7, black 7. Lovely.)
- **A Run** — three or more tiles of the **same colour** in a **consecutive row**. (Blue 4, blue 5, blue 6.) Runs don't wrap around — 13 is the end of the line, no looping back to 1.
- **A Run** — three or more tiles of the **same colour** in a **row**. (Blue 4, blue 5, blue 6.) Runs don't wrap — 13 is the end of the line.
A **joker** fills any gap. Pop it between red 5 and red 7 and it's a red 6. In a group it becomes whatever colour is missing. It's worth the tile it pretends to be.
A **joker** fills any gap. In a run it takes the spot **you drop it in**: put it in front of blue 5-6-7 and it's the 4, behind and it's the 8. A little number on the joker tells you what it's playing as.
## Your Turn
When the gold ring is around your portrait, it's you. **Drag tiles** from your rack up to the table to build sets. Each set sits in its own little tray that glows **green when it's valid** and **red when it isn't** — so you always know where you stand. When you're happy, hit **Play**.
When your nameplate glows, it's you.
Don't like how it's going? **Reset** snaps everything back to the start of your turn, no harm done. And **Sort** tidies your rack by colour and number when your eyes are tired.
- **Drag tiles** from your rack onto the table. Drop one **on a set** to slip it in exactly where you let go, or on the open table (or the dotted **+ new set** slot) to start a new one.
- Or **click** a few tiles to pick them up, then **click a set** (or the empty table) to put them all down at once. **Double-click** a set to pick up the whole thing. **Shift-drag** a tile in a run to take it and everything after it.
- Every set sits in a tray that glows **green when it's good** and **red when it isn't** — and a red tray tells you why: *needs 1 more*, *two reds*, *gap at 8*.
- While you're dragging, the tray you're over lights up and the line above your rack says what the drop would make — "Makes a run worth 24".
- When every tray is green, press **Play** (or Enter).
If you can't (or don't want to) play anything, hit **Draw** to take one tile from the pool — and that ends your turn.
Made a mess? **Undo** (Z) takes back your last move, one at a time. **Reset** (R) puts everything back the way the turn started. And if you can't — or don't want to — play, press **Draw** to take one tile from the bag; that ends your turn. (If you've got tiles out, Draw puts them back first.)
Your rack sorts itself: **789** keeps colours together for spotting runs, **777** lines up numbers for spotting groups, and **Free** leaves it however you arrange it by hand. You can tidy your rack even while the others are thinking.
## The One Big Rule: Your Opening Meld
Here's the catch that trips up every newcomer. Your **very first** play of the game must be sets, made **entirely from your own rack**, worth **at least 30 points** all together (add up the tile numbers). Until you've made that opening meld, you can't touch the tiles already on the table. Once you're in, though — oh, then the fun begins.
Here's the catch that trips up every newcomer. Your **very first** play must be sets made **entirely from your own rack**, worth **at least 30 points** all together (add up the numbers; a joker counts as the tile it plays). The brass gauge over your rack fills up as you go. Until you're in, you can't touch the tiles already on the table. (Some houses play 50 — that's in Settings.)
## The Beautiful Part: Manipulation
## The Beautiful Part: Rearranging
After you've made your opening meld, the whole table is fair game. You may **rearrange anything** out there — break up runs, borrow from groups, shuffle it all about — **as long as every set is still valid when you hit Play**. Take the blue 6 off the end of one run to start another. Split a group to slot in your spare. This is where a stuck rack suddenly comes loose and you lay down six tiles in one glorious move. The table glows green, you press Play, and you feel like a genius.
Once you're in, the whole table is fair game. **Rearrange anything** — split a run, borrow from a group of four, swap a real tile in for a joker and use the joker somewhere else — **as long as every set is valid when you press Play**.
Just remember: when your turn ends, **no leftovers**. Every tile on the table must sit in a complete, valid set, and any tile you pulled down has to stay down.
Pull a tile out of the middle of a long run and, if both halves still stand on their own, it breaks neatly into two runs. If they don't, the gap stays put so you can see it.
## When It Ends
Just remember: **tiles that were on the table stay on the table.** You can move them around all you like, but they can't go back to your rack.
The moment someone empties their rack, the round is over. Everyone else adds up the tiles still on their rack as penalty points (a joker stings for **30**), and the winner is crowned. If the pool runs dry and nobody can move, we settle it on the lowest rack instead.
## Ask Me for Help
Press **Hint** (H) and I'll tell you what I see — "You can open with 34: a red run and a group of 9s." Press it again and I'll lay it out on the table for you; Play it, or Undo if you'd rather not. With the **Coach** on, a little green dot marks the tiles on your rack that have somewhere to go, and I'll mention it if you draw when there was a play.
## When a Round Ends
The moment someone empties their rack, the round is over. Every rack is turned face up and counted: each player pays the winner the difference between their rack and the winner's (a joker left on your rack stings for **30**). If the bag runs dry and nobody can play, the lowest rack wins.
In Settings you can play **one round**, **three** or **five**, or **first to +200** — the score sheet keeps track.
## House Rules
- **Opening meld** — 30 or 50.
- **Turn timer** — off, one minute or two. When the bell goes with a broken table, everything goes back and you draw a penalty (1 or 3 tiles). If your table was good, it's played for you.
## Aunt Rivka's Advice
- **Hold a joker for the big play.** It's tempting to spend it early, but a joker saved is a rearrange waiting to happen.
- **Watch the table, not just your rack.** Half your moves live in tiles other people laid down.
- **Make your opening 30 and get in the game** — you can't manipulate a thing until you do.
- **Count before you commit.** A red tray means a set is short or broken; tidy it before you press Play.
- **Watch the table, not just your rack.** Half your moves live in tiles other people laid down. Their latest plays are outlined in their colour, so you can see what changed.
- **Make your opening and get in the game** — you can't rearrange a thing until you do.
- **When someone's down to one tile, lay down your high ones.** Whatever's left on your rack is what you'll pay.
Now then. Fourteen tiles, a clear head, and a little nerve. Drag something up to the table and let's see what you've got.
Now then. Fourteen tiles, a cup of tea, and a little nerve. Drag something up to the table and let's see what you've got.

View File

@ -1,22 +1,26 @@
// Headless verification for Rummikub.
// node server/scripts/verifyRummikub.js [--games=N]
// Headless verification for Rummikub ("Aunt Rivka's Kitchen").
// node tools/verifyRummikub.js [--games=N] [--ladder=N]
// Exits non-zero on any failure.
//
// 1. Fixture tests: set validation (runs/groups/jokers), table partitioning, the
// 30-point initial meld, and core engine transitions.
// 2. Self-play: full 2–4 player games driven by the heuristic AI in every seat,
// asserting invariants (no exceptions, strict tile conservation = 106 every
// turn, legal sets, the opening-meld rule, termination with a winner).
// 1. Set validation, joker placement by position, why-invalid reasons,
// canonical order, partitioning.
// 2. The rack-set search, table attachment, run splitting, local re-solve.
// 3. Engine: deal, positional moves, auto-split, undo/reset, the opening meld
// (30 and the 50 house rule), draw/penalty, rounds & match scoring, save
// round-trip (plain JSON).
// 4. Self-play soak: 2–4 players × skills 1–5, tile conservation every turn,
// every AI plan commits legally, games end.
// 5. Skill ladder: skill 5 beats skill 1 head-to-head on paired deals.
// 6. Solver time budget on crowded tables.
// 7. Table layout: nothing overlaps the HUD or leaves the screen at worst case.
import {
isValidSet, partitionable, solvePartition, bestMeldDecomposition,
isValidSet, setProblem, canonicalOrder, partitionable, solvePartition, bestRackSets,
attachToTable, localResolve, planPlay, bestMeldDecomposition,
} from '../src/games/rummikub/RummikubSolver.js';
import {
createInitialState, commitTurn, drawTile, stageAiPlan, validateCommit,
buildTiles, rackPenalty, beginTurn,
} from '../src/games/rummikub/RummikubLogic.js';
import { planTurn } from '../src/games/rummikub/RummikubAI.js';
import { INITIAL_MELD_MIN } from '../src/games/rummikub/RummikubData.js';
import * as G from '../src/games/rummikub/RummikubLogic.js';
import { planTurn, coachPlan, describePlan } from '../src/games/rummikub/RummikubAI.js';
import { INITIAL_MELD_MIN, TILE_COUNT, sortByGroup, sortByRun } from '../src/games/rummikub/RummikubData.js';
let failures = 0;
function check(name, cond, detail = '') {
@ -24,13 +28,26 @@ function check(name, cond, detail = '') {
failures++;
console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`);
}
const arg = (k, d) => Number((process.argv.find((a) => a.startsWith(`--${k}=`)) || '').split('=')[1]) || d;
// Fixture tiles use ids well above the engine's 0..105 so they never collide.
let _id = 100000;
const T = (color, number) => ({ id: _id++, color, number, isJoker: false });
const J = () => ({ id: _id++, color: null, number: null, isJoker: true });
const show = (s) => s.map((t) => (t.isJoker ? 'J' : `${t.color[0]}${t.number}`)).join(' ');
// ── 1. Single-set validation ────────────────────────────────────────────────────
function rng(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// ── 1. Sets ─────────────────────────────────────────────────────────────────────
console.log('Set validation:');
check('run 4-5-6 red', isValidSet([T('red', 4), T('red', 5), T('red', 6)]).valid);
check('group 7 r/b/k', isValidSet([T('red', 7), T('blue', 7), T('black', 7)]).valid);
@ -48,152 +65,326 @@ check('two tiles too short', !isValidSet([T('red', 4), T('red', 5)]).valid);
const g = isValidSet([T('red', 7), T('blue', 7), J()]);
check('joker fills group, scored at 7', g.valid && g.points === 21, `points ${g.points}`);
}
{
const j = J();
const front = isValidSet([j, T('blue', 5), T('blue', 6), T('blue', 7)]);
const back = isValidSet([T('blue', 5), T('blue', 6), T('blue', 7), j]);
check('joker in front of a run stands for the 4', front.assignment?.[j.id]?.number === 4);
check('joker behind a run stands for the 8', back.assignment?.[j.id]?.number === 8);
const j2 = J();
const edge = isValidSet([T('blue', 12), T('blue', 13), j2]);
check('joker after 13 falls back to the 11', edge.valid && edge.assignment[j2.id].number === 11);
}
check('non-adjacent reals + joker invalid', !isValidSet([T('red', 2), T('red', 9), J()]).valid);
check('13 reals + joker too long', !isValidSet(
Array.from({ length: 13 }, (_, i) => T('blue', i + 1)).concat(J())).valid);
check('13 reals + joker too long', !isValidSet(Array.from({ length: 13 }, (_, i) => T('blue', i + 1)).concat(J())).valid);
check('all-joker set invalid', !isValidSet([J(), J(), J()]).valid);
// ── 2. Table partitioning ───────────────────────────────────────────────────────
console.log('Why-invalid reasons:');
check('short run → needs 1 more', setProblem([T('red', 5), T('red', 6)]) === 'needs 1 more');
check('gap named', setProblem([T('red', 5), T('red', 7), T('red', 8)]) === 'gap at 6', setProblem([T('red', 5), T('red', 7), T('red', 8)]));
check('duplicate colour named', setProblem([T('red', 5), T('red', 5), T('blue', 5)]) === 'two reds');
check('duplicate number in a run', setProblem([T('red', 5), T('red', 5), T('red', 6)]) === 'two 5s');
check('mixed colours', setProblem([T('red', 5), T('blue', 6), T('black', 9)]) === 'mixed colours');
check('valid set has no problem', setProblem([T('red', 5), T('red', 6), T('red', 7)]) === null);
check('lone tile → needs 2 more', setProblem([T('red', 5)]) === 'needs 2 more');
console.log('Canonical order:');
check('run sorts ascending', show(canonicalOrder([T('red', 7), T('red', 5), T('red', 6)])) === 'r5 r6 r7');
check('group sorts by colour', show(canonicalOrder([T('orange', 7), T('red', 7), T('blue', 7)])) === 'r7 b7 o7');
check('invalid set left alone', show(canonicalOrder([T('red', 9), T('red', 2)])) === 'r9 r2');
console.log('Partitioning:');
check('two clean sets partition', partitionable([
T('red', 1), T('red', 2), T('red', 3), T('blue', 7), T('black', 7), T('orange', 7),
]));
check('two clean sets partition', partitionable([T('red', 1), T('red', 2), T('red', 3), T('blue', 7), T('black', 7), T('orange', 7)]));
check('missing tile fails', !partitionable([T('red', 1), T('red', 2), T('blue', 7), T('black', 7)]));
check('empty table partitions', partitionable([]));
{
// A shared-tile rearrangement: red 1..5 (two copies of 3) = run 1-2-3 + run 3-4-5.
const tiles = [T('red', 1), T('red', 2), T('red', 3), T('red', 3), T('red', 4), T('red', 5)];
check('overlapping runs partition', partitionable(tiles));
}
check('overlapping runs partition', partitionable([T('red', 1), T('red', 2), T('red', 3), T('red', 3), T('red', 4), T('red', 5)]));
{
const sol = solvePartition([T('red', 3), T('red', 4), T('red', 5), T('blue', 9), T('black', 9), J()]);
check('joker-in-table partition reconstructs', !!sol && sol.length === 2);
}
check('joker before 12-13 partitions', partitionable([T('red', 12), T('red', 13), J()]));
check('stranded tile fails', !partitionable([T('red', 1), T('red', 2), T('red', 3), T('blue', 7), T('black', 7), T('orange', 7), T('orange', 1)]));
{
// odd count that cannot fully partition (7 tiles, one stranded)
check('stranded tile fails', !partitionable([
T('red', 1), T('red', 2), T('red', 3), T('blue', 7), T('black', 7), T('orange', 7), T('orange', 1),
]));
const tiles = [T('red', 3), T('red', 4), J(), T('red', 6)];
const sol = solvePartition(tiles);
check('solver output is in display order', !!sol && show(sol[0]) === 'r3 r4 J r6', sol && show(sol[0]));
}
// ── 3. Initial-meld rule ────────────────────────────────────────────────────────
console.log('Initial meld:');
// ── 2. Search ───────────────────────────────────────────────────────────────────
console.log('Rack sets & table play:');
{
// 29 points from one run → rejected; 30 → accepted (via bestMeldDecomposition).
const rack29 = [T('blue', 9), T('blue', 10), T('blue', 11)]; // 30 actually; craft 29:
const r29 = [T('red', 4), T('red', 5), T('red', 6), T('black', 9)]; // 4+5+6=15 only set; <30
const dec29 = bestMeldDecomposition(r29, [], { mustReach: INITIAL_MELD_MIN, alreadyMelded: false });
check('sub-30 opening rejected', dec29 === null);
const dec30 = bestMeldDecomposition(rack29, [], { mustReach: INITIAL_MELD_MIN, alreadyMelded: false });
check('30 opening accepted', !!dec30 && dec30.tilesPlayed.length === 3);
const rack = [T('red', 1), T('red', 2), T('red', 3), T('blue', 10), T('black', 10), T('orange', 10), T('red', 10),
T('blue', 11), T('blue', 12), J(), T('black', 4)];
const b = bestRackSets(rack, { minPoints: 30 });
check('best rack sets lays 10 of 11', b && b.tiles === 10, b && `${b.tiles}`);
const noJ = bestRackSets(rack, { maxJokers: 0 });
check('maxJokers 0 keeps the joker', noJ && !noJ.sets.flat().some((t) => t.isJoker));
}
{
// joker counted at represented value toward the 30.
const rack = [T('orange', 10), T('orange', 11), J()]; // 10+11+12 = 33
const dec = bestMeldDecomposition(rack, [], { mustReach: INITIAL_MELD_MIN, alreadyMelded: false });
check('joker counts toward opening meld', !!dec);
// tile-count beats greed: r5-r8 run vs. the 5s group
const rack = [T('red', 5), T('red', 6), T('red', 7), T('red', 8), T('blue', 5), T('black', 5), T('blue', 6), T('black', 6)];
const b = bestRackSets(rack);
check('search finds 6-tile layout (two groups)', b && b.tiles >= 6, b && `${b.tiles}: ${b.sets.map(show).join(' | ')}`);
}
{
const table = [[T('blue', 3), T('blue', 4), T('blue', 5), T('blue', 6), T('blue', 7)], [T('red', 9), T('blue', 9), T('black', 9)]];
const a = attachToTable(table, [T('blue', 8), T('orange', 9)]);
check('attach to run end and group', a.played.length === 2);
const sp = attachToTable(table, [T('blue', 5)], { split: true });
check('split a long run with a duplicate', sp.played.length === 1 && sp.table.length === 3, sp.table.map(show).join(' | '));
const nosp = attachToTable(table, [T('blue', 5)], { split: false });
check('no split without the split option', nosp.played.length === 0);
}
{
// red 7 only fits by breaking the 7s group and the run: r5 r6 [r7] + 7s group of four → needs re-solve
const table = [[T('red', 5), T('red', 6), T('red', 7), T('red', 8)], [T('blue', 7), T('black', 7), T('orange', 7)]];
const lr = localResolve(table, [T('red', 9)]);
check('local re-solve places a tile', lr.played.length === 1 && lr.table.every((s) => isValidSet(s).valid), lr.table.map(show).join(' | '));
const table2 = [[T('red', 4), T('red', 5), T('red', 6)], [T('red', 7), T('blue', 7), T('black', 7), T('orange', 7)]];
const lr2 = localResolve(table2, [T('red', 8)]);
check('rearrange: borrow r7 from a group of four for r4–r8', lr2.played.length === 1 && lr2.table.every((s) => isValidSet(s).valid), lr2.table.map(show).join(' | '));
}
{
const r29 = [T('red', 4), T('red', 5), T('red', 6), T('black', 9)];
check('sub-30 opening rejected', bestMeldDecomposition(r29, [], { mustReach: INITIAL_MELD_MIN }) === null);
const r30 = [T('blue', 9), T('blue', 10), T('blue', 11)];
const d = bestMeldDecomposition(r30, [], { mustReach: INITIAL_MELD_MIN });
check('30 opening accepted', !!d && d.tilesPlayed.length === 3);
check('joker counts toward opening meld', !!bestMeldDecomposition([T('orange', 10), T('orange', 11), J()], [], { mustReach: 30 }));
const p50 = planPlay([T('blue', 9), T('blue', 10), T('blue', 11)], [], { melded: false, openMin: 50 });
check('50 house rule rejects a 30 opening', p50 === null);
}
// ── 4. Engine transitions ───────────────────────────────────────────────────────
// ── 3. Engine ───────────────────────────────────────────────────────────────────
console.log('Engine:');
for (const pc of [2, 3, 4]) {
const s = createInitialState({ seed: 123, playerCount: pc });
const s = G.createGame({ seed: 123, playerCount: pc });
const dealt = s.players.reduce((a, p) => a + p.rack.length, 0);
check(`${pc}p deal: 14 each + pool = 106`, dealt === 14 * pc && s.pool.length === 106 - 14 * pc,
`dealt ${dealt}, pool ${s.pool.length}`);
check(`${pc}p deal: 14 each + pool = 106`, dealt === 14 * pc && s.pool.length === 106 - 14 * pc);
}
check('tile factory builds 106', G.buildTiles().length === TILE_COUNT);
check('rack penalty: joker=30', G.rackPenalty([J()]) === 30);
{
let s = createInitialState({ seed: 5, playerCount: 4 });
const before = s.currentPlayer;
let s = G.createGame({ seed: 5, playerCount: 4 });
const poolBefore = s.pool.length;
s = drawTile(s);
check('draw advances turn', s.currentPlayer === (before + 1) % 4);
s = G.drawTile(s);
check('draw advances turn', s.currentPlayer === 1);
check('draw removes one pool tile', s.pool.length === poolBefore - 1);
check('draw is logged', s.log.at(-1)?.kind === 'draw' && s.log.at(-1).n === 1);
}
// Build a controlled position for move tests.
function fixture({ rack, table = [], melded = true, openMin = 30 }) {
let s = G.createGame({ seed: 9, playerCount: 2, rules: { openMin } });
s.players = s.players.map((p, i) => (i === 0 ? { ...p, rack, hasMelded: melded } : p));
s.table = table;
s.currentPlayer = 0;
return G.beginTurn(s);
}
{
// Reject an invalid working board (a 2-tile "set").
let s = createInitialState({ seed: 6, playerCount: 2 });
s = { ...s, workingTable: [[s.workingRack[0], s.workingRack[1]]], workingRack: s.workingRack.slice(2) };
const v = validateCommit(s);
check('invalid board rejected', !v.ok);
const after = commitTurn(s);
check('rejected commit leaves an error', !!after.commitError && after.currentPlayer === s.currentPlayer);
const r5 = T('red', 5), r6 = T('red', 6), r7 = T('red', 7), r8 = T('red', 8), r4 = T('red', 4), r3 = T('red', 3), r9 = T('red', 9);
let s = fixture({ rack: [r4, r8, r3, r9], table: [[r5, r6, r7]] });
s = G.moveTiles(s, [r4.id], { type: 'set', index: 0, at: 0 });
check('positional insert at the front', show(s.workingTable[0]) === 'r4 r5 r6 r7');
s = G.moveTiles(s, [r8.id], { type: 'set', index: 0, at: 0 });
check('valid set reorders itself (r8 dropped at front)', show(s.workingTable[0]) === 'r4 r5 r6 r7 r8');
const gap = G.moveTiles(s, [r6.id], { type: 'newSet' });
check('a gap that leaves short pieces stays together', gap.workingTable.length === 2 && show(gap.workingTable[0]) === 'r4 r5 r7 r8',
gap.workingTable.map(show).join(' | '));
s = G.moveTiles(s, [r3.id, r9.id], { type: 'set', index: 0 });
check('two tiles at once', show(s.workingTable[0]) === 'r3 r4 r5 r6 r7 r8 r9');
s = G.moveTiles(s, [r6.id], { type: 'newSet' });
check('pulling from the middle splits into two valid runs', s.workingTable.length === 3 && show(s.workingTable[0]) === 'r3 r4 r5' && show(s.workingTable[1]) === 'r7 r8 r9',
s.workingTable.map(show).join(' | '));
const lifted = G.liftTiles(s, [r6.id]);
check('lift without placing', lifted.table.length === 2 && lifted.moving[0] === r6);
s = G.undoMove(s);
check('undo restores the previous move', s.workingTable.length === 1 && show(s.workingTable[0]) === 'r3 r4 r5 r6 r7 r8 r9');
s = G.undoMove(G.undoMove(G.undoMove(s)));
check('undo back to the start', show(s.workingTable[0]) === 'r5 r6 r7' && s.workingRack.length === 4);
check('nothing left to undo', !G.canUndo(s));
const bad = G.moveTiles(s, [r5.id], { type: 'rack' });
check('table tiles cannot go to the rack', !!bad.commitError && bad.workingTable[0].length === 3);
}
check('tile factory builds 106', buildTiles().length === 106);
check('rack penalty: joker=30', rackPenalty([J()]) === 30);
// ── 5. Self-play ────────────────────────────────────────────────────────────────
const games = Number((process.argv.find((a) => a.startsWith('--games=')) || '').split('=')[1]) || 300;
console.log(`Self-play (${games} games):`);
function tileTotal(s) {
const rack = s.players.reduce((a, p) => a + p.rack.length, 0);
const table = s.table.reduce((a, set) => a + set.length, 0);
return rack + table + s.pool.length;
{
const j = J();
const b5 = T('blue', 5), b6 = T('blue', 6), b7 = T('blue', 7);
let s = fixture({ rack: [j, b5, b6, b7] });
s = G.moveTiles(s, [b5.id], { type: 'newSet' });
s = G.moveTiles(s, [b6.id], { type: 'set', index: 0 });
s = G.moveTiles(s, [b7.id], { type: 'set', index: 0 });
s = G.moveTiles(s, [j.id], { type: 'set', index: 0, at: 0 });
const v = isValidSet(s.workingTable[0]);
check('joker dropped at the front plays as the 4', v.valid && v.assignment[j.id].number === 4, show(s.workingTable[0]));
}
{
// opening meld bookkeeping and the 30/50 rule
const tiles = [T('blue', 9), T('blue', 10), T('blue', 11)];
let s = fixture({ rack: tiles.slice(), melded: false });
s = G.moveTiles(s, tiles.map((t) => t.id), { type: 'newSet' });
check('opening of 30 commits', G.validateCommit(s).ok);
let h = fixture({ rack: tiles.slice(), melded: false, openMin: 50 });
h = G.moveTiles(h, tiles.map((t) => t.id), { type: 'newSet' });
const v = G.validateCommit(h);
check('opening of 30 fails the 50 rule', !v.ok && /50/.test(v.reason));
const tbl = [[T('red', 1), T('red', 2), T('red', 3)]];
let m = fixture({ rack: [T('red', 4), ...tiles], table: tbl, melded: false });
m = G.moveTiles(m, [m.workingRack[0].id], { type: 'set', index: 0 });
m = G.moveTiles(m, tiles.map((t) => t.id), { type: 'newSet' });
check('no touching the table before opening', !G.validateCommit(m).ok);
}
{
// reset & draw with tiles staged
const tiles = [T('blue', 9), T('blue', 10), T('orange', 2)];
let s = fixture({ rack: tiles.slice() });
s = G.moveTiles(s, [tiles[0].id, tiles[1].id], { type: 'newSet' });
check('staged changes seen', G.hasStagedChanges(s));
const d = G.drawTile(s);
check('draw with staged tiles resets them first', d.players[0].rack.length === 4 && d.table.length === 0);
const r = G.resetTurn(s);
check('reset returns staged tiles', r.workingRack.length === 3 && r.workingTable.length === 0);
check('reset is undoable', G.canUndo(r) && G.undoMove(r).workingTable.length === 1);
}
{
// timeout penalty
const tiles = [T('blue', 9), T('blue', 10), T('orange', 2)];
let s = fixture({ rack: tiles.slice() });
s = G.moveTiles(s, [tiles[0].id], { type: 'newSet' });
const f = G.forfeitTurn(s);
check('timeout draws the 3-tile penalty', f.players[0].rack.length === 6 && f.log.at(-1).penalty);
}
{
// round & match scoring: zero-sum, history, match end
let s = G.createGame({ seed: 77, playerCount: 3, rules: { match: 'r3' } });
let rounds = 0;
for (let guard = 0; guard < 20000 && s.phase !== 'gameOver'; guard++) {
if (s.phase === 'roundOver') { rounds++; s = G.nextRound(s); continue; }
const plan = planTurn(s, s.currentPlayer, 4, rng(guard));
if (plan.type === 'commit') s = G.commitTurn(G.stageAiPlan(s, plan)); else s = G.drawTile(s);
}
check('3-round match ends after 3 rounds', s.phase === 'gameOver' && s.match.history.length === 3, `${s.match.history.length} rounds`);
check('every round is zero-sum', s.match.history.every((h) => h.deltas.reduce((a, b) => a + b, 0) === 0));
check('match totals add up', s.match.scores.every((v, i) => v === s.match.history.reduce((a, h) => a + h.deltas[i], 0)));
check('match winner has the top score', s.match.scores[s.match.winner] === Math.max(...s.match.scores));
check('rounds rotate the first player', rounds === 2);
const json = JSON.parse(JSON.stringify(s));
check('state survives a JSON round-trip', G.tileCount(json) === TILE_COUNT && json.match.history.length === 3);
}
{
let s = G.createGame({ seed: 4, playerCount: 2, rules: { match: 't100' } });
check('points-target match parsed', s.match.spec.target === 100 && s.match.spec.rounds === null);
}
{
const r = [T('red', 9), T('blue', 3), T('red', 1), J(), T('black', 9)];
check('777 sort', show(sortByGroup(r)) === 'r1 b3 r9 b9 J');
check('789 sort', show(sortByRun(r)) === 'r1 r9 b3 b9 J');
}
{
// the Coach
const tiles = [T('blue', 9), T('blue', 10), T('blue', 11), T('red', 2)];
const s = fixture({ rack: tiles, melded: false });
const cp = coachPlan(s);
check('coach finds the opening', cp && cp.firstMeld && cp.points === 30);
check('coach describes it', /open with 30/.test(describePlan(cp, 4) ?? ''), describePlan(cp, 4));
}
let exceptions = 0, conserveBad = 0, illegalSet = 0, badRack = 0, noWinner = 0, firstMeldBad = 0;
// ── 4. Self-play soak ───────────────────────────────────────────────────────────
const games = arg('games', 240);
console.log(`Self-play (${games} games, skills 1–5):`);
let exceptions = 0, conserveBad = 0, illegal = 0, firstMeldBad = 0, noEnd = 0;
let slowest = 0;
const winsBySeat = {};
let meldedGames = 0;
for (let g = 1; g <= games; g++) {
try {
const playerCount = 2 + (g % 3); // cycles 2,3,4
let s = createInitialState({ seed: g * 2654435761, playerCount });
let turns = 0, sawMeld = false;
while (s.phase !== 'gameOver') {
if (++turns > 100000) throw new Error('turn loop did not terminate');
if (tileTotal(s) !== 106) { conserveBad++; throw new Error(`tile total ${tileTotal(s)}`); }
const playerCount = 2 + (g % 3);
let s = G.createGame({ seed: (g * 2654435761) >>> 0, playerCount, rules: { openMin: g % 4 === 0 ? 50 : 30 } });
const rand = rng(g);
let turns = 0;
while (s.phase === 'play') {
if (++turns > 5000) { noEnd++; break; }
if (G.tileCount(s) !== TILE_COUNT) { conserveBad++; throw new Error(`tile total ${G.tileCount(s)}`); }
const seat = s.currentPlayer;
const meldedBefore = s.players[seat].hasMelded;
const melded = s.players[seat].hasMelded;
const skill = 1 + ((g + seat) % 5);
const plan = planTurn(s, seat, skill);
const t0 = Date.now();
const plan = planTurn(s, seat, skill, rand);
slowest = Math.max(slowest, Date.now() - t0);
if (plan.type === 'commit') {
// Opening-meld rule must hold.
if (!meldedBefore && plan.firstMeld) {
let pts = 0;
for (const set of plan.newTable) {
const ids = set.map((t) => t.id);
const fresh = ids.some((id) => plan.tilesPlayed.includes(id));
if (fresh && set.every((t) => plan.tilesPlayed.includes(t.id))) pts += isValidSet(set).points;
}
if (pts < INITIAL_MELD_MIN) firstMeldBad++;
}
s = stageAiPlan(s, plan);
const v = validateCommit(s);
if (!v.ok) { illegalSet++; throw new Error(`AI proposed illegal commit: ${v.reason}`); }
s = commitTurn(s);
sawMeld = true;
} else {
s = drawTile(s);
}
// Every committed table set is legal.
for (const set of s.table) if (!isValidSet(set).valid) illegalSet++;
for (const p of s.players) if (p.rack.length < 0 || p.rack.length > 60) badRack++;
const st = G.stageAiPlan(s, plan);
const v = G.validateCommit(st);
if (!v.ok) { illegal++; throw new Error(`skill ${skill} illegal commit: ${v.reason}`); }
if (!melded && (v.firstMeldPoints ?? 0) < s.rules.openMin) firstMeldBad++;
s = G.commitTurn(st);
} else s = G.drawTile(s);
for (const set of s.table) if (!isValidSet(set).valid) illegal++;
}
if (s.winner == null) noWinner++; else winsBySeat[s.winner] = (winsBySeat[s.winner] || 0) + 1;
if (sawMeld) meldedGames++;
if (s.winner != null) winsBySeat[s.winner] = (winsBySeat[s.winner] || 0) + 1;
} catch (e) {
exceptions++;
if (exceptions <= 5) console.error(` game ${g}: ${e.message}`);
}
}
check('no exceptions during self-play', exceptions === 0, `${exceptions} games threw`);
check('tile conservation holds (106 every turn)', conserveBad === 0, `${conserveBad} violations`);
check('all committed sets legal', illegalSet === 0, `${illegalSet} illegal`);
check('rack sizes stay sane', badRack === 0, `${badRack} bad`);
check('every AI plan commits legally', illegal === 0, `${illegal} illegal`);
check('opening-meld rule never broken', firstMeldBad === 0, `${firstMeldBad} bad`);
check('most games see a meld', meldedGames >= games * 0.8, `${meldedGames}/${games}`);
check('games terminate with a winner', noWinner <= games * 0.05, `${noWinner} without winner`);
const seatList = Object.entries(winsBySeat).map(([k, v]) => `seat${k}:${v}`).join(' ');
check('wins spread across seats', Object.keys(winsBySeat).length >= 2, seatList);
console.log(` results: ${seatList}, no-winner ${noWinner}, melded ${meldedGames}/${games}`);
check('games end', noEnd === 0, `${noEnd} ran away`);
check('AI turn under 1.5s worst case', slowest < 1500, `${slowest}ms`);
console.log(` wins by seat ${JSON.stringify(winsBySeat)} · slowest AI turn ${slowest}ms`);
// ── 5. Skill ladder ─────────────────────────────────────────────────────────────
const ladder = arg('ladder', 120);
console.log(`Skill ladder (${ladder} paired 2-player deals):`);
function duel(seed, skills) {
let s = G.createGame({ seed, playerCount: 2 });
const rand = rng(seed);
for (let i = 0; i < 4000 && s.phase === 'play'; i++) {
const plan = planTurn(s, s.currentPlayer, skills[s.currentPlayer], rand);
s = plan.type === 'commit' ? G.commitTurn(G.stageAiPlan(s, plan)) : G.drawTile(s);
}
return s.winner;
}
for (const [hi, lo] of [[5, 1], [3, 1], [4, 2], [5, 3]]) {
let w = 0;
for (let i = 0; i < ladder; i++) {
const seed = (i * 97 + 13) >>> 0;
if (duel(seed, [hi, lo]) === 0) w++;
if (duel(seed, [lo, hi]) === 1) w++;
}
const rate = w / (ladder * 2);
check(`skill ${hi} beats skill ${lo} (${Math.round(rate * 100)}%)`, rate > 0.55, `${Math.round(rate * 100)}%`);
}
// ── 6. Solver time on a crowded table ──────────────────────────────────────────
console.log('Solver budget:');
{
let worst = 0;
for (let k = 0; k < 20; k++) {
// grow a crowded table by self-play, then time a full plan from a big rack
let s = G.createGame({ seed: 5000 + k, playerCount: 4 });
const rand = rng(k);
for (let i = 0; i < 40 && s.phase === 'play'; i++) {
const plan = planTurn(s, s.currentPlayer, 2, rand);
s = plan.type === 'commit' ? G.commitTurn(G.stageAiPlan(s, plan)) : G.drawTile(s);
}
if (s.phase !== 'play') continue;
const bigRack = [...s.players[0].rack, ...s.pool.slice(0, 16)];
const t0 = Date.now();
planPlay(bigRack, s.table, { melded: true, level: 5 });
worst = Math.max(worst, Date.now() - t0);
}
check('level-5 plan on a crowded table under 1.5s', worst < 1500, `${worst}ms`);
console.log(` worst ${worst}ms`);
}
// ── 7. Layout ───────────────────────────────────────────────────────────────────
console.log('Layout:');
{
const Tb = await import('../src/games/rummikub/RummikubTable.js').catch(() => null);
if (Tb?.verifyLayout) {
const problems = Tb.verifyLayout();
check('table layout fits (worst cases)', problems.length === 0, problems.slice(0, 6).join('; '));
} else console.log(' (no layout module yet)');
}
console.log(failures ? `\n${failures} check(s) FAILED` : '\nAll checks passed.');
process.exit(failures ? 1 : 0);