392 lines
15 KiB
JavaScript
392 lines
15 KiB
JavaScript
// Farkel — pure game engine. No Phaser, no timers, JSON-serialisable state (the
|
||
// scene autosaves it). Every random draw comes from an injected rng.
|
||
//
|
||
// Standard rules: each throw is scored ON ITS OWN — dice set aside from an
|
||
// earlier throw never combine with a later one. Single 1 = 100, single 5 = 50;
|
||
// three-of-a-kind = face×100 (three 1s = 1,000); four / five / six of a kind =
|
||
// 1,000 / 2,000 / 3,000; straight 1–6 = 1,500; three pairs (incl. four of a kind
|
||
// + a pair) = 1,500. Hot dice: once all six are set aside, roll all six again
|
||
// and keep the turn total. A turn must reach `entry` (default 500) before a
|
||
// player's first bank. First to `target` triggers one final round.
|
||
//
|
||
// House rules (state.rules): threeFarkle (−1,000 on a third Farkle in a row),
|
||
// twoTriplets (2,500), doubling (N-of-a-kind = triple ×2/×4/×8), piggyback
|
||
// (the next player may take over the leftover dice and turn total).
|
||
|
||
import { DICE, DEFAULT_RULES, THREE_FARKLE_PENALTY, normalizeRules } from './FarkelData.js';
|
||
|
||
const LOG_CAP = 400;
|
||
const NUM = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six'];
|
||
|
||
// ── scoring ──────────────────────────────────────────────────────────────────
|
||
export function countsOf(dice) {
|
||
const c = [0, 0, 0, 0, 0, 0, 0];
|
||
for (const v of dice) c[v]++;
|
||
return c;
|
||
}
|
||
|
||
export function tripleValue(v) { return v === 1 ? 1000 : v * 100; }
|
||
|
||
// Value of N (≥3) of a kind of face v.
|
||
export function nKindValue(v, n, rules = DEFAULT_RULES) {
|
||
if (n === 3) return tripleValue(v);
|
||
if (rules.doubling) return tripleValue(v) * 2 ** (n - 3);
|
||
return n === 4 ? 1000 : n === 5 ? 2000 : 3000;
|
||
}
|
||
|
||
function kindPart(v, n, rules) {
|
||
const key = n === 3 ? `three${v}` : n === 4 ? 'four' : n === 5 ? 'five' : 'six';
|
||
return { key, label: `${NUM[n]} ${v}s`, points: nKindValue(v, n, rules), count: n, face: v };
|
||
}
|
||
function singlesPart(v, n) {
|
||
return { key: `single${v}`, label: n === 1 ? `Single ${v}` : `${NUM[n]} ${v}s`, points: n * (v === 1 ? 100 : 50), count: n, face: v };
|
||
}
|
||
|
||
// Score one throw's chosen dice. Every die must belong to a combo.
|
||
// Returns { valid, points, parts: [{ key, label, points, count, face? }] }.
|
||
export function scoreParts(dice, rules = DEFAULT_RULES) {
|
||
if (!dice || dice.length === 0) return { valid: false, points: 0, parts: [] };
|
||
const counts = countsOf(dice);
|
||
const cands = [];
|
||
|
||
if (dice.length === 6) {
|
||
if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] === 1)) {
|
||
cands.push([{ key: 'straight', label: 'Straight 1–6', points: 1500, count: 6 }]);
|
||
}
|
||
if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] % 2 === 0)) {
|
||
cands.push([{ key: 'pairs', label: 'Three Pairs', points: 1500, count: 6 }]);
|
||
}
|
||
if (rules.twoTriplets && counts.filter((c) => c === 3).length === 2) {
|
||
cands.push([{ key: 'triplets', label: 'Two Triplets', points: 2500, count: 6 }]);
|
||
}
|
||
}
|
||
|
||
// Combos face by face (the only other way every die can score).
|
||
const parts = [];
|
||
let ok = true;
|
||
for (let v = 1; v <= 6 && ok; v++) {
|
||
const c = counts[v];
|
||
if (c === 0) continue;
|
||
if (c >= 3) {
|
||
const flat = kindPart(v, c, rules);
|
||
// three of a kind plus the extras as singles (only ever an option for 1s/5s)
|
||
if ((v === 1 || v === 5) && c > 3) {
|
||
const alt = [kindPart(v, 3, rules), singlesPart(v, c - 3)];
|
||
if (alt[0].points + alt[1].points > flat.points) { parts.push(...alt); continue; }
|
||
}
|
||
parts.push(flat);
|
||
} else if (v === 1 || v === 5) {
|
||
parts.push(singlesPart(v, c));
|
||
} else ok = false;
|
||
}
|
||
if (ok) cands.push(parts);
|
||
|
||
if (!cands.length) return { valid: false, points: 0, parts: [] };
|
||
let best = null, bestPts = -1;
|
||
for (const p of cands) {
|
||
const pts = p.reduce((s, x) => s + x.points, 0);
|
||
if (pts > bestPts) { best = p; bestPts = pts; }
|
||
}
|
||
return { valid: true, points: bestPts, parts: best };
|
||
}
|
||
|
||
export function scoreSelection(dice, rules = DEFAULT_RULES) {
|
||
const r = scoreParts(dice, rules);
|
||
return { valid: r.valid, points: r.points };
|
||
}
|
||
export function breakdownScoring(dice, rules = DEFAULT_RULES) {
|
||
return scoreParts(dice, rules).parts.map(({ label, points, key }) => ({ label, points, key }));
|
||
}
|
||
|
||
function subsets(n) {
|
||
const out = [];
|
||
for (let mask = 1; mask < (1 << n); mask++) {
|
||
const idx = [];
|
||
for (let i = 0; i < n; i++) if (mask & (1 << i)) idx.push(i);
|
||
out.push(idx);
|
||
}
|
||
return out;
|
||
}
|
||
const SUBSETS = Array.from({ length: DICE + 1 }, (_, n) => subsets(n));
|
||
|
||
// The best set of dice to keep from one throw. Ties prefer using every die (hot
|
||
// dice), then keeping fewer dice. Returns { indices, points } (points 0 = none).
|
||
export function bestScoring(rolled, rules = DEFAULT_RULES) {
|
||
let best = { indices: [], points: 0 };
|
||
for (const idx of SUBSETS[rolled.length]) {
|
||
const r = scoreSelection(idx.map((i) => rolled[i]), rules);
|
||
if (!r.valid) continue;
|
||
const allUsed = idx.length === rolled.length;
|
||
const bestAll = best.indices.length === rolled.length;
|
||
const better = r.points > best.points
|
||
|| (r.points === best.points && ((allUsed && !bestAll) || (allUsed === bestAll && idx.length < best.indices.length)));
|
||
if (better) best = { indices: idx, points: r.points };
|
||
}
|
||
return best;
|
||
}
|
||
|
||
// Does this throw score at all? (Earlier set-aside dice never count.)
|
||
export function hasScoring(rolled, rules = DEFAULT_RULES) {
|
||
const c = countsOf(rolled);
|
||
if (c[1] || c[5]) return true;
|
||
for (let v = 2; v <= 6; v++) if (c[v] >= 3) return true;
|
||
if (rolled.length === 6) return scoreSelection(rolled, rules).valid;
|
||
return false;
|
||
}
|
||
|
||
// Which dice can take part in some scoring keep (for the hint glow).
|
||
export function scoringMask(rolled, rules = DEFAULT_RULES) {
|
||
const mask = rolled.map(() => false);
|
||
for (const idx of SUBSETS[rolled.length]) {
|
||
if (!scoreSelection(idx.map((i) => rolled[i]), rules).valid) continue;
|
||
for (const i of idx) mask[i] = true;
|
||
}
|
||
return mask;
|
||
}
|
||
|
||
// Smart pick: the natural combo a click on die i belongs to.
|
||
export function smartGroup(rolled, i, rules = DEFAULT_RULES) {
|
||
const v = rolled[i];
|
||
if (rolled.length === 6) {
|
||
const whole = scoreParts(rolled, rules);
|
||
if (whole.valid && whole.parts.length === 1 && whole.parts[0].count === 6) return rolled.map((_, k) => k);
|
||
}
|
||
const same = rolled.map((x, k) => (x === v ? k : -1)).filter((k) => k >= 0);
|
||
if (same.length >= 3) return same;
|
||
return [i];
|
||
}
|
||
|
||
// ── state ────────────────────────────────────────────────────────────────────
|
||
function freshStats() {
|
||
return { turns: 0, banks: 0, bankTotal: 0, bestTurn: 0, farkles: 0, hotDice: 0, penalties: 0, piggybacks: 0, history: [0] };
|
||
}
|
||
|
||
export function createInitialState({ playerCount = 4, names = [], skills = {}, rules = {} } = {}) {
|
||
const players = [];
|
||
for (let seat = 0; seat < playerCount; seat++) {
|
||
players.push({
|
||
name: names[seat] ?? `Player ${seat + 1}`,
|
||
seat,
|
||
score: 0,
|
||
onBoard: false,
|
||
skill: skills[seat] ?? 3,
|
||
isAI: seat !== 0,
|
||
farkleStreak: 0,
|
||
stats: freshStats(),
|
||
});
|
||
}
|
||
const state = {
|
||
version: 2,
|
||
rules: normalizeRules(rules),
|
||
players,
|
||
current: 0,
|
||
turnNo: 1,
|
||
phase: 'awaitRoll', // awaitRoll | awaitPick | awaitDecision | farkled | gameover
|
||
winners: [],
|
||
winner: null,
|
||
finalRound: false,
|
||
finalFrom: null,
|
||
piggyOffer: null, // { kept, available, from } when the piggyback rule offers one
|
||
log: [],
|
||
turn: null,
|
||
};
|
||
resetTurn(state);
|
||
return state;
|
||
}
|
||
|
||
function resetTurn(state) {
|
||
state.turn = { rolled: [], available: DICE, kept: 0, groups: [], cycle: 0, rolls: 0, hotDice: false, piggy: false, lastKeep: null };
|
||
state.phase = 'awaitRoll';
|
||
}
|
||
|
||
export function cloneState(s) { return JSON.parse(JSON.stringify(s)); }
|
||
|
||
function log(state, entry) {
|
||
state.log.push({ turn: state.turnNo, seat: state.current, ...entry });
|
||
if (state.log.length > LOG_CAP) state.log.splice(0, state.log.length - LOG_CAP);
|
||
}
|
||
|
||
export const currentPlayer = (s) => s.players[s.current];
|
||
|
||
// Can the current player legally bank `total` this turn?
|
||
export function bankAllowed(state, total = state.turn.kept) {
|
||
const p = currentPlayer(state);
|
||
return total > 0 && (p.onBoard || total >= state.rules.entry);
|
||
}
|
||
export function canBank(state) {
|
||
return state.phase === 'awaitDecision' && bankAllowed(state);
|
||
}
|
||
|
||
// Points the current player still needs this turn to beat the leader in the
|
||
// final round (0 when not chasing).
|
||
export function finalRoundNeed(state) {
|
||
if (!state.finalRound) return 0;
|
||
const me = currentPlayer(state);
|
||
let lead = -Infinity;
|
||
state.players.forEach((p) => { if (p.seat !== me.seat) lead = Math.max(lead, p.score); });
|
||
return me.score > lead ? 0 : lead - me.score + 50;
|
||
}
|
||
|
||
// ── actions ──────────────────────────────────────────────────────────────────
|
||
export function canRoll(state) {
|
||
return state.phase === 'awaitRoll' || state.phase === 'awaitDecision';
|
||
}
|
||
|
||
// Throw the available dice. Phase → awaitPick, or farkled if nothing scores.
|
||
export function rollDice(state, rng = Math.random) {
|
||
if (!canRoll(state)) return state;
|
||
const t = state.turn;
|
||
if (state.piggyOffer && t.rolls === 0 && !t.piggy) state.piggyOffer = null; // declined
|
||
const out = [];
|
||
for (let i = 0; i < t.available; i++) out.push(1 + Math.floor(rng() * 6));
|
||
t.rolled = out;
|
||
t.rolls++;
|
||
t.hotDice = false;
|
||
state.phase = hasScoring(out, state.rules) ? 'awaitPick' : 'farkled';
|
||
log(state, { kind: 'roll', dice: out.slice(), farkle: state.phase === 'farkled' });
|
||
return state;
|
||
}
|
||
|
||
// Take the piggyback offer (before the first roll of the turn).
|
||
export function takePiggyback(state) {
|
||
const o = state.piggyOffer;
|
||
const t = state.turn;
|
||
if (!o || state.phase !== 'awaitRoll' || t.rolls > 0) return false;
|
||
t.kept = o.kept;
|
||
t.available = o.available;
|
||
t.piggy = true;
|
||
state.piggyOffer = null;
|
||
currentPlayer(state).stats.piggybacks++;
|
||
log(state, { kind: 'piggy', points: o.kept, available: o.available, from: o.from });
|
||
return true;
|
||
}
|
||
|
||
// Set aside the dice at `indices` (into turn.rolled). They must all score as
|
||
// one throw's combo. Hot dice when no dice remain. Returns the scored result
|
||
// or null on an invalid selection.
|
||
export function applySetAside(state, indices) {
|
||
if (state.phase !== 'awaitPick') return null;
|
||
const t = state.turn;
|
||
const uniq = [...new Set(indices)].filter((i) => i >= 0 && i < t.rolled.length);
|
||
if (!uniq.length) return null;
|
||
const values = uniq.map((i) => t.rolled[i]);
|
||
const res = scoreParts(values, state.rules);
|
||
if (!res.valid) return null;
|
||
|
||
t.kept += res.points;
|
||
t.groups.push({ dice: values, points: res.points, parts: res.parts, cycle: t.cycle });
|
||
t.available -= values.length;
|
||
t.rolled = [];
|
||
t.lastKeep = { dice: values, points: res.points };
|
||
let hot = false;
|
||
if (t.available === 0) {
|
||
hot = true;
|
||
t.available = DICE;
|
||
t.cycle++;
|
||
t.hotDice = true;
|
||
currentPlayer(state).stats.hotDice++;
|
||
}
|
||
state.phase = 'awaitDecision';
|
||
log(state, { kind: 'keep', dice: values, points: res.points, total: t.kept, hot, label: res.parts.map((p) => p.label).join(' + ') });
|
||
return { points: res.points, parts: res.parts, hot, total: t.kept };
|
||
}
|
||
|
||
// Bank the turn total and pass play. Returns { banked, total } or null.
|
||
export function bank(state) {
|
||
if (!canBank(state)) return null;
|
||
const p = currentPlayer(state);
|
||
const t = state.turn;
|
||
const banked = t.kept;
|
||
p.score += banked;
|
||
p.onBoard = true;
|
||
p.farkleStreak = 0;
|
||
p.stats.banks++;
|
||
p.stats.bankTotal += banked;
|
||
p.stats.bestTurn = Math.max(p.stats.bestTurn, banked);
|
||
log(state, { kind: 'bank', points: banked, score: p.score });
|
||
const offer = state.rules.piggyback ? { kept: t.kept, available: t.available, from: p.seat } : null;
|
||
endTurn(state, offer);
|
||
return { banked, total: p.score };
|
||
}
|
||
|
||
// Lose the turn total after a Farkle. Returns { penalty }.
|
||
export function farkleTurn(state) {
|
||
if (state.phase !== 'farkled') return { penalty: 0 };
|
||
const p = currentPlayer(state);
|
||
p.stats.farkles++;
|
||
p.farkleStreak++;
|
||
let penalty = 0;
|
||
if (state.rules.threeFarkle && p.farkleStreak >= 3) {
|
||
penalty = Math.min(THREE_FARKLE_PENALTY, p.score);
|
||
p.score -= penalty;
|
||
p.farkleStreak = 0;
|
||
p.stats.penalties++;
|
||
}
|
||
log(state, { kind: 'farkle', lost: state.turn.kept, penalty, score: p.score });
|
||
endTurn(state, null);
|
||
return { penalty };
|
||
}
|
||
|
||
function endTurn(state, offer) {
|
||
const N = state.players.length;
|
||
const p = currentPlayer(state);
|
||
p.stats.turns++;
|
||
p.stats.history.push(p.score);
|
||
|
||
if (!state.finalRound && p.score >= state.rules.target) {
|
||
state.finalRound = true;
|
||
state.finalFrom = state.current;
|
||
log(state, { kind: 'final', score: p.score });
|
||
}
|
||
state.current = (state.current + 1) % N;
|
||
if (state.current === 0) state.turnNo++;
|
||
|
||
if (state.finalRound && state.current === state.finalFrom) {
|
||
state.phase = 'gameover';
|
||
state.piggyOffer = null;
|
||
state.turn.rolled = [];
|
||
state.winners = computeWinners(state);
|
||
state.winner = state.winners[0] ?? null;
|
||
return;
|
||
}
|
||
resetTurn(state);
|
||
state.piggyOffer = offer && offer.kept > 0 ? offer : null;
|
||
}
|
||
|
||
function computeWinners(state) {
|
||
let max = -Infinity;
|
||
state.players.forEach((p) => { if (p.score > max) max = p.score; });
|
||
return state.players.filter((p) => p.score === max).map((p) => p.seat);
|
||
}
|
||
|
||
export function isGameOver(state) { return state.phase === 'gameover'; }
|
||
export function getWinners(state) { return state.winners; }
|
||
|
||
// 1-based standing per seat (ties share a rank).
|
||
export function rankings(state) {
|
||
return state.players.map((p) => 1 + state.players.filter((q) => q.score > p.score).length);
|
||
}
|
||
|
||
export function leaderSeat(state) {
|
||
let best = null;
|
||
for (const p of state.players) if (p.score > 0 && (!best || p.score > best.score)) best = p;
|
||
if (!best) return null;
|
||
return state.players.filter((p) => p.score === best.score).length > 1 ? null : best.seat;
|
||
}
|
||
|
||
export function fmtPts(n) { return Math.round(n).toLocaleString('en-US'); }
|
||
|
||
// One human-readable line per log entry.
|
||
export function describeLog(state, e) {
|
||
const name = state.players[e.seat]?.name ?? '?';
|
||
switch (e.kind) {
|
||
case 'roll': return e.farkle ? `${name} threw ${e.dice.join(' ')} — FARKLE` : `${name} threw ${e.dice.join(' ')}`;
|
||
case 'keep': return `${name} kept ${e.dice.join(' ')} (${e.label}) +${fmtPts(e.points)} → ${fmtPts(e.total)}${e.hot ? ' · HOT DICE' : ''}`;
|
||
case 'bank': return `${name} banked ${fmtPts(e.points)} → ${fmtPts(e.score)}`;
|
||
case 'farkle': return `${name} lost ${fmtPts(e.lost)}${e.penalty ? ` and paid the ${fmtPts(e.penalty)} three-Farkle penalty` : ''}`;
|
||
case 'piggy': return `${name} piggybacked ${fmtPts(e.points)} with ${e.available} dice`;
|
||
case 'final': return `${name} reached ${fmtPts(e.score)} — final round!`;
|
||
default: return '';
|
||
}
|
||
}
|