/** * 루미큐브 computer player. A turn is two decisions: first one `setDraft` with the whole plan (rack-only sets, then * single tiles laid off on table / new sets), then `commit` once the view says the draft is valid. If the draft is * not valid (should not happen) it draws, which also throws the draft away — it never leaves a half-built draft. * Table sets are never rearranged beyond adding tiles to their ends. */ import type { BotStrategy } from '../bots/types'; import { answerRequests } from '../bots/policy'; import { extendSet, isJoker, pickDisjoint, type JokerAs } from './rules'; import type { RummikubAction, RummikubView } from './index'; type Plan = { tileIds: string[]; kind: 'run' | 'group'; jokerAs: Record }; /** Lays rack tiles off on the given sets in place (repeating, so 5-6-7 + 8 + 9 works). */ function layOff(sets: Plan[], rack: string[], keepJokers: boolean): void { const used = new Set(); for (let changed = true; changed; ) { changed = false; for (const id of rack) { if (used.has(id) || (keepJokers && isJoker(id))) continue; for (let i = 0; i < sets.length; i++) { const ext = extendSet(sets[i]!, id); if (!ext) continue; sets[i] = ext; used.add(id); changed = true; break; } } } } export const rummikubBot: BotStrategy = ({ view, legal }) => { const req = answerRequests(legal); if (req) return req; if (legal.some((a) => a.type === 'ready')) return { type: 'ready' }; const my = view.my!; const endTurn: RummikubAction = legal.find((a) => a.type === 'pass') ?? { type: 'draw' }; // Second step of a turn: the plan is on the table — commit it, or give up cleanly (draw resets the draft). if (my.changed) return my.check?.ok ? { type: 'commit', turn: view.turnNo } : endTurn; const rack = my.rack; const table: Plan[] = view.table.map((t) => ({ tileIds: [...t.tileIds], kind: t.kind, jokerAs: t.jokerAs })); const disjoint = pickDisjoint(rack); const fresh = disjoint.sets.map((n): Plan => ({ tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs })); const rest = rack.filter((id) => !fresh.some((s) => s.tileIds.includes(id))); // A lone joker is only laid off near the end (it's the most flexible tile, but costs 30 if still on the rack). const keepJokers = rack.length > 4; let sets: Plan[]; if (!my.melded) { // First meld: every disjoint rack set at once, if together they reach the minimum. Table sets stay untouched. if (!fresh.length || disjoint.points < view.options.initialMeldPoints) return endTurn; layOff(fresh, rest, keepJokers); sets = [...table, ...fresh]; } else { sets = [...table, ...fresh]; layOff(sets, rest, keepJokers); } const before = new Set(view.table.flatMap((t) => t.tileIds)); if (!sets.some((s) => s.tileIds.some((id) => !before.has(id)))) return endTurn; return { type: 'setDraft', sets: sets.map((s) => ({ tileIds: s.tileIds, as: s.kind })), turn: view.turnNo }; };