Rework Farkel as a ski-lodge table with exact-solver AI and house rules
- Replace the heuristic opponent with a skill ladder (1–5) built on an exact one-turn Markov solver; skills 4–5 pick keeps by expected value and handle final-round reach, catch-up pressure, and piggyback offers. - Add house rules (target, entry minimum, three-Farkle penalty, two triplets, doubling kinds, piggyback) with a settings dialog and normalized state; the engine now scores each throw independently instead of combining set-aside dice. - Rebuild the table art as Gerome's Ski Lodge: baked textures for room, tray, rail, cup, seats, clipboard score pad, chalkboard scoring card, risk gauge, frost and sprites, plus a 3D dice tray with shake-and-pour throws. - Add coach advice, turn log, pause menu, end screen with stats/chart and personal bests, autosave/resume, and keyboard controls. - Ship tools/verifyFarkel.js to check scoring, odds, solver, AI legality, skill ladder, and layout overlaps; update the tutorial accordingly.
This commit is contained in:
parent
9c72f9f215
commit
60021f197b
|
|
@ -1,55 +1,166 @@
|
|||
// Farkel — heuristic opponent. No Phaser, no timers, no state mutation. After a
|
||||
// roll the AI always takes the greedy best-scoring set (FarkelLogic.bestScoring);
|
||||
// the only real decision is reroll vs. bank, made with an expected-value model
|
||||
// over the standard Farkle odds, shaded by a 1-5 skill profile for human-like
|
||||
// pacing and the occasional greedy blunder.
|
||||
// Farkel — opponents and the Coach. No Phaser, no timers, no state mutation.
|
||||
//
|
||||
// skill 5 exact solver (FarkelSolver) for both the keep and bank/roll, plus
|
||||
// endgame awareness: the final-round chase maximises P(beat leader),
|
||||
// and it pushes harder when an opponent is about to close the game
|
||||
// skill 4 solver keeps (occasionally greedy) and solver banking with slips
|
||||
// on close calls
|
||||
// skill 3 greedy keeps, sensible bank thresholds by dice left
|
||||
// skill 2 greedy keeps, a timid or reckless personality with noise
|
||||
// skill 1 greedy keeps, banks as soon as it's nervous
|
||||
//
|
||||
// Every skill obeys the hard rules of the table: it never banks below the
|
||||
// entry minimum and never banks short of the leader in the final round.
|
||||
|
||||
import { WIN_TARGET, ON_BOARD_MIN } from './FarkelData.js';
|
||||
import { DICE } from './FarkelData.js';
|
||||
import { bestScoring, finalRoundNeed, bankAllowed, currentPlayer } from './FarkelLogic.js';
|
||||
import { pointsSolver, reachSolver, rankKeeps, farkleChance } from './FarkelSolver.js';
|
||||
|
||||
// Probability a roll of N dice scores nothing (standard Farkle figures).
|
||||
const FARKLE_PROB = { 1: 0.667, 2: 0.444, 3: 0.278, 4: 0.157, 5: 0.077, 6: 0.023 };
|
||||
// Rough expected points added by scoring dice in a roll of N.
|
||||
const AVG_GAIN = { 1: 25, 2: 50, 3: 75, 4: 113, 5: 150, 6: 200 };
|
||||
const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3)));
|
||||
|
||||
const SKILL_PROFILES = {
|
||||
1: { greed: 1.6, noise: 0.5, delay: [700, 1200] },
|
||||
2: { greed: 1.3, noise: 0.35, delay: [650, 1100] },
|
||||
3: { greed: 1.1, noise: 0.2, delay: [600, 1000] },
|
||||
4: { greed: 1.0, noise: 0.1, delay: [520, 900] },
|
||||
5: { greed: 1.0, noise: 0.0, delay: [440, 820] },
|
||||
const THRESH = {
|
||||
3: { 6: Infinity, 5: 3000, 4: 1050, 3: 450, 2: 250, 1: 350 },
|
||||
timid: { 6: Infinity, 5: 1000, 4: 500, 3: 300, 2: 250, 1: 200 },
|
||||
reckless: { 6: Infinity, 5: 3000, 4: 2000, 3: 1000, 2: 600, 1: 500 },
|
||||
};
|
||||
function profileFor(skill) {
|
||||
return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3];
|
||||
|
||||
// Reading of the scoreboard for the current player: which solver to use.
|
||||
export function situation(state) {
|
||||
const me = currentPlayer(state);
|
||||
const rules = state.rules;
|
||||
let need = finalRoundNeed(state);
|
||||
if (need > 0) {
|
||||
if (!me.onBoard) need = Math.max(need, rules.entry);
|
||||
return { mode: 'reach', need, solver: reachSolver(rules, need) };
|
||||
}
|
||||
const entry = me.onBoard ? 0 : rules.entry;
|
||||
return { mode: 'points', need: 0, minBank: entry, solver: pointsSolver(rules, entry) };
|
||||
}
|
||||
|
||||
// Expert endgame shading for skill 5: when an opponent is close to triggering
|
||||
// the final round and we're well behind, demand a bigger turn before banking.
|
||||
function catchUpMinBank(state) {
|
||||
const me = currentPlayer(state);
|
||||
const target = state.rules.target;
|
||||
let opp = 0;
|
||||
state.players.forEach((p) => { if (p.seat !== me.seat) opp = Math.max(opp, p.score); });
|
||||
if (opp < target * 0.8) return 0;
|
||||
const deficit = opp - me.score;
|
||||
if (deficit <= 1000) return 0;
|
||||
return Math.min(2000, Math.round((deficit * 0.3) / 50) * 50);
|
||||
}
|
||||
|
||||
function personality(state, seat) {
|
||||
// stable per seat and game: odd seats are reckless, even seats timid
|
||||
return (seat + state.players.length) % 2 ? 'reckless' : 'timid';
|
||||
}
|
||||
|
||||
// Decide what to keep from the current throw and whether to bank afterwards.
|
||||
// Returns { keep: indices into turn.rolled, bank: boolean }.
|
||||
export function planDecision(state, skill = 3, rng = Math.random) {
|
||||
const sk = clampSkill(skill);
|
||||
const me = currentPlayer(state);
|
||||
const t = state.turn;
|
||||
const rules = state.rules;
|
||||
const rolled = t.rolled;
|
||||
const sit = situation(state);
|
||||
|
||||
// ── which dice to keep ──
|
||||
let keep;
|
||||
if (sk >= 4 || (sk === 3 && sit.mode === 'reach')) {
|
||||
let solver = sit.solver;
|
||||
if (sk === 5 && sit.mode === 'points') {
|
||||
const mb = Math.max(sit.minBank, catchUpMinBank(state));
|
||||
if (mb > sit.minBank) solver = pointsSolver(rules, mb);
|
||||
}
|
||||
const ranked = rankKeeps(rolled, t.kept, rules, solver);
|
||||
keep = ranked[0];
|
||||
if (sk === 4 && rng() < 0.1) {
|
||||
const g = bestScoring(rolled, rules);
|
||||
keep = ranked.find((k) => k.indices.join() === g.indices.join()) ?? keep;
|
||||
}
|
||||
keep = { indices: keep.indices, points: keep.points, solver };
|
||||
} else {
|
||||
const g = bestScoring(rolled, rules);
|
||||
keep = { indices: g.indices, points: g.points, solver: sit.solver };
|
||||
}
|
||||
|
||||
const total = t.kept + keep.points;
|
||||
const left = rolled.length - keep.indices.length || DICE;
|
||||
const allowed = bankAllowed(state, total);
|
||||
|
||||
// ── hard rules every skill respects ──
|
||||
if (!allowed) return { keep: keep.indices, bank: false };
|
||||
if (sit.mode === 'reach') return { keep: keep.indices, bank: total >= sit.need };
|
||||
if (!state.finalRound && me.score + total >= rules.target) return { keep: keep.indices, bank: true };
|
||||
|
||||
// ── bank or roll ──
|
||||
let bank;
|
||||
if (sk >= 4) {
|
||||
const s = keep.solver;
|
||||
const bv = s.bankValue(total), rv = s.rollValue(total, left);
|
||||
bank = bv >= rv;
|
||||
if (sk === 4 && Math.abs(bv - rv) < Math.max(40, total * 0.06) && rng() < 0.35) bank = !bank;
|
||||
if (bv === -Infinity) bank = false;
|
||||
} else if (sk === 3) {
|
||||
bank = total >= THRESH[3][left];
|
||||
} else if (sk === 2) {
|
||||
const th = THRESH[personality(state, me.seat)][left];
|
||||
bank = total >= th * (0.55 + rng() * 0.9);
|
||||
} else {
|
||||
// skill 1: jittery — banks when few dice are left, sometimes on a whim
|
||||
bank = left <= 3 ? rng() < 0.75 : left <= 4 ? rng() < 0.3 : false;
|
||||
if (left <= 2 && total < 150) bank = rng() < 0.5;
|
||||
}
|
||||
return { keep: keep.indices, bank };
|
||||
}
|
||||
|
||||
// Should this player take the piggyback offer?
|
||||
export function wantsPiggyback(state, skill = 3) {
|
||||
const o = state.piggyOffer;
|
||||
if (!o) return false;
|
||||
const sk = clampSkill(skill);
|
||||
if (sk <= 2) return o.available >= 3 || o.kept >= 1000;
|
||||
const { solver } = situation(state);
|
||||
return solver.rollValue(o.kept, o.available) > solver.rollValue(0, DICE);
|
||||
}
|
||||
|
||||
// Human-like thinking time per skill.
|
||||
const DELAY = { 1: [700, 1200], 2: [650, 1100], 3: [600, 1000], 4: [520, 900], 5: [440, 820] };
|
||||
export function nextThinkDelay(skill) {
|
||||
const [lo, hi] = profileFor(skill).delay;
|
||||
const [lo, hi] = DELAY[clampSkill(skill)];
|
||||
return lo + Math.random() * (hi - lo);
|
||||
}
|
||||
|
||||
// Decide whether to reroll the remaining dice (true) or bank (false). Called
|
||||
// after the AI has already set aside its scoring dice for the current roll.
|
||||
export function decideReroll(state, skill = 3) {
|
||||
const prof = profileFor(skill);
|
||||
// ── Coach ────────────────────────────────────────────────────────────────────
|
||||
// Advice for the human on the current throw: the expert keep, plus what the
|
||||
// chosen (or expert) keep is worth if banked vs rolled on.
|
||||
export function coachAdvice(state, selection = null) {
|
||||
const t = state.turn;
|
||||
const me = state.players[state.current];
|
||||
|
||||
// Below the on-board minimum, banking would score nothing — so the kept total
|
||||
// is worthless until it reaches 500. Always push on (there's nothing to lose).
|
||||
if (!me.onBoard && t.kept < ON_BOARD_MIN) return true;
|
||||
|
||||
// If banking now wins the game, take it.
|
||||
if (me.score + t.kept >= WIN_TARGET) return false;
|
||||
|
||||
const prob = FARKLE_PROB[t.available] ?? 0.5;
|
||||
const gain = (AVG_GAIN[t.available] ?? 50) * prof.greed;
|
||||
let ev = (1 - prob) * gain - prob * t.kept;
|
||||
ev += (Math.random() * 2 - 1) * prof.noise * 100;
|
||||
|
||||
// If an opponent is on the brink, gamble harder to keep pace.
|
||||
let oppMax = 0;
|
||||
state.players.forEach((p) => { if (p.seat !== me.seat && p.score > oppMax) oppMax = p.score; });
|
||||
if (oppMax >= WIN_TARGET * 0.8 && me.score + t.kept < oppMax) ev += 150;
|
||||
|
||||
return ev > 0;
|
||||
const rules = state.rules;
|
||||
const sit = situation(state);
|
||||
const ranked = rankKeeps(t.rolled, t.kept, rules, sit.solver);
|
||||
if (!ranked.length) return null;
|
||||
const best = ranked[0];
|
||||
let mine = null;
|
||||
if (selection && selection.length) {
|
||||
const key = selection.map((i) => t.rolled[i]).sort().join('');
|
||||
mine = ranked.find((k) => k.indices.map((i) => t.rolled[i]).sort().join('') === key) ?? null;
|
||||
}
|
||||
const k = mine ?? best;
|
||||
const canBankK = bankAllowed(state, k.total) && (sit.mode !== 'reach' || k.total >= sit.need);
|
||||
return {
|
||||
mode: sit.mode,
|
||||
need: sit.need,
|
||||
best,
|
||||
mine,
|
||||
total: k.total,
|
||||
left: k.left,
|
||||
rollValue: k.roll,
|
||||
bankValue: canBankK ? (sit.mode === 'reach' ? 1 : k.total) : null,
|
||||
recommend: canBankK && k.bank >= k.roll ? 'bank' : 'roll',
|
||||
farkle: farkleChance(rules, k.left),
|
||||
// how much the selection gives up against the expert keep (points mode)
|
||||
regret: mine ? best.value - mine.value : 0,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,593 @@
|
|||
// FarkelArt.js — baked canvas textures for Gerome's Ski Lodge.
|
||||
//
|
||||
// farkel-room dark knotty-pine table, buffalo-plaid runner, fireside glow,
|
||||
// cold window light and frosted corners
|
||||
// farkel-vignette glow + vignette overlay for a chosen playfield "tablecloth"
|
||||
// farkel-tray pine dice tray with an evergreen felt well + snowflake crest
|
||||
// farkel-rail the "set aside" shelf under the tray
|
||||
// farkel-cup leather dice cup with a sheepskin cuff
|
||||
// farkel-seat an opponent's wooden place-card
|
||||
// farkel-pad-N clipboard + ruled score sheet for N players
|
||||
// farkel-card framed chalkboard for the scoring table
|
||||
// farkel-thermo wooden plaque + glass tube for the Farkle-risk gauge
|
||||
// farkel-frost frost sheet laid over the tray on a Farkle
|
||||
// farkel-hand a soft ghost hand (tinted per opponent)
|
||||
// farkel-spark / farkel-flake / farkel-ember small particles
|
||||
|
||||
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
|
||||
import {
|
||||
W, H, TRAY, TRAY_FELT, TRAY_WALL, RAIL, RAIL_TOP_H, RAIL_START_X, CUP, SEAT, BOARD, CLIP, PAPER,
|
||||
PAD_TITLE, PAD_HEAD, PAD_GRID, PAD_MARGIN, PAD_ROW_H, PAD_ROWS, padColX, CARD, CARD_INNER, THERMO,
|
||||
} from './FarkelLayout.js';
|
||||
|
||||
export const PAD_PX = 26; // shadow margin baked around tray / rail / board
|
||||
export const INK = ['#22304f', '#9c2121', '#1d6a3c', '#6a3591'];
|
||||
export const INK_HEX = [0x22304f, 0x9c2121, 0x1d6a3c, 0x6a3591];
|
||||
export const SEAT_TINT = [0x4f86c6, 0xd0533f, 0x3f9d66, 0x9364c9];
|
||||
export const HAND_FONT = 'YummyCupcakes, "Comic Sans MS", cursive';
|
||||
export const PRINT_FONT = '"Julius Sans One", Georgia, serif';
|
||||
export const DISPLAY_FONT = 'Righteous, Georgia, serif';
|
||||
export const SERIF = 'Georgia, "Times New Roman", serif';
|
||||
export const CHALK = '#f1eee2';
|
||||
export const ICE = 0x9fd8ff;
|
||||
export const EMBER = 0xff9a3c;
|
||||
|
||||
function addCanvas(scene, key, c) {
|
||||
if (scene.textures.exists(key)) scene.textures.remove(key);
|
||||
scene.textures.addCanvas(key, c);
|
||||
}
|
||||
|
||||
function shade(hex, k) {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
const c = [n >> 16, (n >> 8) & 255, n & 255].map((v) => Math.max(0, Math.min(255, Math.round(v * k))));
|
||||
return `rgb(${c[0]},${c[1]},${c[2]})`;
|
||||
}
|
||||
|
||||
function dropShadow(ctx, fn, { blur = 22, dy = 10, alpha = 0.55 } = {}) {
|
||||
ctx.save();
|
||||
ctx.shadowColor = `rgba(0,0,0,${alpha})`;
|
||||
ctx.shadowBlur = blur; ctx.shadowOffsetY = dy;
|
||||
fn();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// ── wood ─────────────────────────────────────────────────────────────────────
|
||||
function grain(ctx, x, y, w, h, { tone = 'rgba(40,20,8,0.22)', lines = 14, wave = 3, knots = 0.7 } = {}) {
|
||||
ctx.save();
|
||||
ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
|
||||
ctx.strokeStyle = tone;
|
||||
for (let i = 0; i < lines; i++) {
|
||||
const yy = y + Math.random() * h;
|
||||
const amp = wave * (0.4 + Math.random());
|
||||
const f = 0.004 + Math.random() * 0.01;
|
||||
const ph = Math.random() * 6;
|
||||
ctx.lineWidth = 0.6 + Math.random() * 1.4;
|
||||
ctx.beginPath();
|
||||
for (let xx = x; xx <= x + w; xx += 8) {
|
||||
const yv = yy + Math.sin(xx * f + ph) * amp + Math.sin(xx * f * 3.1 + ph) * amp * 0.3;
|
||||
if (xx === x) ctx.moveTo(xx, yv); else ctx.lineTo(xx, yv);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
// knotty pine: dark knots with rings
|
||||
const nk = w > 300 ? (Math.random() < knots ? 1 + Math.floor(Math.random() * 2) : 0) : 0;
|
||||
for (let k = 0; k < nk; k++) {
|
||||
const kx = x + Math.random() * w, ky = y + h * (0.25 + Math.random() * 0.5);
|
||||
const kg = ctx.createRadialGradient(kx, ky, 1, kx, ky, 12);
|
||||
kg.addColorStop(0, 'rgba(40,18,6,0.85)'); kg.addColorStop(1, 'rgba(40,18,6,0)');
|
||||
ctx.fillStyle = kg;
|
||||
ctx.beginPath(); ctx.ellipse(kx, ky, 14, 7, 0, 0, Math.PI * 2); ctx.fill();
|
||||
for (let r = 4; r < 22; r += 4) {
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath(); ctx.ellipse(kx, ky, r * 2.2, r * 0.7, 0, 0, Math.PI * 2); ctx.stroke();
|
||||
}
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function planks(ctx, x, y, w, h, { plankH = 120, tones = ['#5a3a20', '#4e321c', '#634024', '#553620'] } = {}) {
|
||||
let i = 0;
|
||||
for (let py = y; py < y + h; py += plankH, i++) {
|
||||
const ph = Math.min(plankH, y + h - py);
|
||||
const g = ctx.createLinearGradient(0, py, 0, py + ph);
|
||||
const base = tones[i % tones.length];
|
||||
g.addColorStop(0, base); g.addColorStop(0.5, shade(base, 1.08)); g.addColorStop(1, shade(base, 0.88));
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(x, py, w, ph);
|
||||
grain(ctx, x, py, w, ph, { lines: 20, knots: 0.9 });
|
||||
ctx.fillStyle = 'rgba(15,6,2,0.6)';
|
||||
ctx.fillRect(x, py + ph - 3, w, 3);
|
||||
ctx.fillStyle = 'rgba(255,220,170,0.07)';
|
||||
ctx.fillRect(x, py, w, 1.5);
|
||||
const jx = x + ((i * 617) % Math.max(1, w - 200)) + 100;
|
||||
ctx.fillStyle = 'rgba(15,6,2,0.45)';
|
||||
ctx.fillRect(jx, py, 2, ph);
|
||||
// square-head nails at the joint
|
||||
ctx.fillStyle = 'rgba(30,26,22,0.8)';
|
||||
ctx.fillRect(jx - 9, py + 14, 4, 4); ctx.fillRect(jx + 7, py + ph - 20, 4, 4);
|
||||
}
|
||||
}
|
||||
|
||||
// Red/black buffalo plaid with a fringe on the short ends.
|
||||
function plaid(ctx, x, y, w, h) {
|
||||
ctx.save();
|
||||
rr(ctx, x, y, w, h, 8); ctx.clip();
|
||||
ctx.fillStyle = '#8e1a1a'; ctx.fillRect(x, y, w, h);
|
||||
const S = 54;
|
||||
ctx.fillStyle = 'rgba(12,8,8,0.62)';
|
||||
for (let xx = x; xx < x + w; xx += S * 2) ctx.fillRect(xx, y, S, h);
|
||||
ctx.fillStyle = 'rgba(12,8,8,0.55)';
|
||||
for (let yy = y; yy < y + h; yy += S * 2) ctx.fillRect(x, yy, w, S);
|
||||
// woven texture: fine diagonal twill
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.12)'; ctx.lineWidth = 1;
|
||||
for (let d = -h; d < w; d += 5) { ctx.beginPath(); ctx.moveTo(x + d, y); ctx.lineTo(x + d + h, y + h); ctx.stroke(); }
|
||||
ctx.fillStyle = noisePattern(ctx, 96, 30); ctx.fillRect(x, y, w, h);
|
||||
// soft fold shadows
|
||||
const fg = ctx.createLinearGradient(0, y, 0, y + h);
|
||||
fg.addColorStop(0, 'rgba(0,0,0,0.25)'); fg.addColorStop(0.08, 'rgba(0,0,0,0)'); fg.addColorStop(0.92, 'rgba(0,0,0,0)'); fg.addColorStop(1, 'rgba(0,0,0,0.3)');
|
||||
ctx.fillStyle = fg; ctx.fillRect(x, y, w, h);
|
||||
ctx.restore();
|
||||
// fringe
|
||||
ctx.strokeStyle = 'rgba(120,24,24,0.9)'; ctx.lineWidth = 2;
|
||||
for (const ex of [x, x + w]) {
|
||||
const dir = ex === x ? -1 : 1;
|
||||
for (let yy = y + 6; yy < y + h - 4; yy += 7) {
|
||||
ctx.beginPath(); ctx.moveTo(ex, yy); ctx.lineTo(ex + dir * (10 + Math.random() * 6), yy + (Math.random() - 0.5) * 4); ctx.stroke();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function glow(ctx, cx, cy, r, rgb, alpha) {
|
||||
const g = ctx.createRadialGradient(cx, cy, 10, cx, cy, r);
|
||||
g.addColorStop(0, `rgba(${rgb},${alpha})`);
|
||||
g.addColorStop(0.6, `rgba(${rgb},${alpha * 0.35})`);
|
||||
g.addColorStop(1, `rgba(${rgb},0)`);
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
}
|
||||
function vignette(ctx, k = 0.6) {
|
||||
const g = ctx.createRadialGradient(W * 0.42, H * 0.48, H * 0.35, W * 0.5, H * 0.5, H * 1.05);
|
||||
g.addColorStop(0, 'rgba(0,0,0,0)');
|
||||
g.addColorStop(1, `rgba(0,0,0,${k})`);
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
}
|
||||
|
||||
// Frost crystals creeping in from a corner (cx, cy) towards (dx, dy).
|
||||
function frostCorner(ctx, cx, cy, dx, dy, reach = 260) {
|
||||
ctx.save();
|
||||
const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, reach);
|
||||
g.addColorStop(0, 'rgba(225,240,255,0.32)'); g.addColorStop(1, 'rgba(225,240,255,0)');
|
||||
ctx.fillStyle = g; ctx.fillRect(cx - reach, cy - reach, reach * 2, reach * 2);
|
||||
ctx.strokeStyle = 'rgba(235,246,255,0.35)';
|
||||
const branch = (x, y, ang, len, depth) => {
|
||||
if (depth <= 0 || len < 6) return;
|
||||
const x2 = x + Math.cos(ang) * len, y2 = y + Math.sin(ang) * len;
|
||||
ctx.lineWidth = Math.max(0.5, depth * 0.45);
|
||||
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x2, y2); ctx.stroke();
|
||||
const n = 2 + Math.floor(Math.random() * 2);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const t = 0.3 + Math.random() * 0.6;
|
||||
branch(x + (x2 - x) * t, y + (y2 - y) * t, ang + (Math.random() < 0.5 ? -1 : 1) * (0.5 + Math.random() * 0.5), len * 0.45, depth - 1);
|
||||
}
|
||||
branch(x2, y2, ang + (Math.random() - 0.5) * 0.4, len * 0.7, depth - 1);
|
||||
};
|
||||
const base = Math.atan2(dy, dx);
|
||||
for (let i = 0; i < 7; i++) branch(cx, cy, base + (i - 3) * 0.24, reach * (0.35 + Math.random() * 0.25), 5);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function bakeRoom(scene) {
|
||||
const c = canvas(W, H), ctx = c.getContext('2d');
|
||||
planks(ctx, 0, 0, W, H, { plankH: 128 });
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 26);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
// plaid runner under the tray, rail and the HUD
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#5a1010'; rr(ctx, 26, 166, 1168, 660, 8); ctx.fill(); }, { blur: 16, dy: 6, alpha: 0.5 });
|
||||
plaid(ctx, 26, 166, 1168, 660);
|
||||
// fireside: warm glow from the lower left; window: cold light from the upper right
|
||||
glow(ctx, -80, H + 60, 1100, '255,150,70', 0.42);
|
||||
glow(ctx, TRAY.x + TRAY.w / 2, TRAY.y + TRAY.h / 2, 820, '255,214,150', 0.2);
|
||||
glow(ctx, W + 80, -60, 900, '170,205,255', 0.22);
|
||||
vignette(ctx, 0.62);
|
||||
frostCorner(ctx, W, 0, -1, 1, 300);
|
||||
frostCorner(ctx, 0, 0, 1, 1, 220);
|
||||
addCanvas(scene, 'farkel-room', c);
|
||||
|
||||
const v = canvas(W, H), vx = v.getContext('2d');
|
||||
glow(vx, -80, H + 60, 1100, '255,150,70', 0.3);
|
||||
glow(vx, W + 80, -60, 900, '170,205,255', 0.16);
|
||||
vignette(vx, 0.55);
|
||||
frostCorner(vx, W, 0, -1, 1, 260);
|
||||
addCanvas(scene, 'farkel-vignette', v);
|
||||
}
|
||||
|
||||
// ── tray ─────────────────────────────────────────────────────────────────────
|
||||
function snowflake(ctx, cx, cy, r, { lw = 3, color = 'rgba(255,255,255,0.08)' } = {}) {
|
||||
ctx.save();
|
||||
ctx.translate(cx, cy);
|
||||
ctx.strokeStyle = color; ctx.lineWidth = lw; ctx.lineCap = 'round';
|
||||
for (let k = 0; k < 6; k++) {
|
||||
ctx.rotate(Math.PI / 3);
|
||||
ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(0, -r); ctx.stroke();
|
||||
for (const t of [0.45, 0.72]) {
|
||||
const b = r * (1 - t) * 0.6;
|
||||
ctx.beginPath(); ctx.moveTo(0, -r * t); ctx.lineTo(-b, -r * t - b); ctx.moveTo(0, -r * t); ctx.lineTo(b, -r * t - b); ctx.stroke();
|
||||
}
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function bakeTray(scene) {
|
||||
const P = PAD_PX;
|
||||
const c = canvas(TRAY.w + P * 2, TRAY.h + P * 2), ctx = c.getContext('2d');
|
||||
const x = P, y = P, w = TRAY.w, h = TRAY.h;
|
||||
dropShadow(ctx, () => { rr(ctx, x, y, w, h, 24); ctx.fillStyle = '#3a2412'; ctx.fill(); }, { blur: 30, dy: 16, alpha: 0.7 });
|
||||
// log-cabin frame: honey pine
|
||||
ctx.save(); rr(ctx, x, y, w, h, 24); ctx.clip();
|
||||
const g = ctx.createLinearGradient(0, y, 0, y + h);
|
||||
g.addColorStop(0, '#a8743e'); g.addColorStop(0.5, '#8a5a2c'); g.addColorStop(1, '#6e4520');
|
||||
ctx.fillStyle = g; ctx.fillRect(x, y, w, h);
|
||||
grain(ctx, x, y, w, h, { lines: 46, tone: 'rgba(60,30,10,0.32)', knots: 1 });
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(255,226,170,0.4)'; ctx.lineWidth = 2;
|
||||
rr(ctx, x + 2, y + 2, w - 4, h - 4, 22); ctx.stroke();
|
||||
// felt well — deep evergreen
|
||||
const fx = P + TRAY_WALL, fy = P + TRAY_WALL, fw = TRAY_FELT.w, fh = TRAY_FELT.h;
|
||||
ctx.save(); rr(ctx, fx, fy, fw, fh, 14); ctx.clip();
|
||||
const fg = ctx.createRadialGradient(fx + fw / 2, fy + fh * 0.45, 40, fx + fw / 2, fy + fh / 2, fw * 0.62);
|
||||
fg.addColorStop(0, '#2c6448'); fg.addColorStop(1, '#123726');
|
||||
ctx.fillStyle = fg; ctx.fillRect(fx, fy, fw, fh);
|
||||
ctx.fillStyle = noisePattern(ctx, 96, 40); ctx.fillRect(fx, fy, fw, fh);
|
||||
// crest: snowflake + lodge name, pressed into the felt
|
||||
snowflake(ctx, fx + fw / 2, fy + fh * 0.5, 120, { lw: 6, color: 'rgba(0,0,0,0.12)' });
|
||||
snowflake(ctx, fx + fw / 2 - 1, fy + fh * 0.5 - 2, 120, { lw: 4, color: 'rgba(220,255,235,0.07)' });
|
||||
ctx.font = `30px ${DISPLAY_FONT}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.16)'; ctx.fillText("GEROME'S LODGE", fx + fw / 2 + 1, fy + fh * 0.5 + 168);
|
||||
ctx.fillStyle = 'rgba(220,255,235,0.09)'; ctx.fillText("GEROME'S LODGE", fx + fw / 2, fy + fh * 0.5 + 166);
|
||||
ctx.font = `14px ${PRINT_FONT}`;
|
||||
ctx.fillStyle = 'rgba(220,255,235,0.08)'; ctx.fillText('· FARKLE · EST. ON A POWDER DAY ·', fx + fw / 2, fy + fh * 0.5 + 196);
|
||||
// the far wall's inner face and inner shadows
|
||||
const wallG = ctx.createLinearGradient(0, fy, 0, fy + 26);
|
||||
wallG.addColorStop(0, '#4a2c12'); wallG.addColorStop(1, 'rgba(74,44,18,0)');
|
||||
ctx.fillStyle = wallG; ctx.fillRect(fx, fy, fw, 26);
|
||||
for (const [x0, x1, a] of [[fx, fx + 22, 0.45], [fx + fw, fx + fw - 22, 0.35]]) {
|
||||
const s = ctx.createLinearGradient(x0, 0, x1, 0);
|
||||
s.addColorStop(0, `rgba(0,0,0,${a})`); s.addColorStop(1, 'rgba(0,0,0,0)');
|
||||
ctx.fillStyle = s; ctx.fillRect(Math.min(x0, x1), fy, 22, fh);
|
||||
}
|
||||
const bs = ctx.createLinearGradient(0, fy + fh, 0, fy + fh - 14);
|
||||
bs.addColorStop(0, 'rgba(0,0,0,0.3)'); bs.addColorStop(1, 'rgba(0,0,0,0)');
|
||||
ctx.fillStyle = bs; ctx.fillRect(fx, fy + fh - 14, fw, 14);
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 2;
|
||||
rr(ctx, fx, fy, fw, fh, 14); ctx.stroke();
|
||||
// iron corner brackets
|
||||
for (const [cx, cy, sx, sy] of [[x + 6, y + 6, 1, 1], [x + w - 6, y + 6, -1, 1], [x + 6, y + h - 6, 1, -1], [x + w - 6, y + h - 6, -1, -1]]) {
|
||||
ctx.fillStyle = '#2b2622';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(cx, cy); ctx.lineTo(cx + sx * 46, cy); ctx.lineTo(cx + sx * 46, cy + sy * 10);
|
||||
ctx.lineTo(cx + sx * 10, cy + sy * 10); ctx.lineTo(cx + sx * 10, cy + sy * 46); ctx.lineTo(cx, cy + sy * 46); ctx.closePath(); ctx.fill();
|
||||
ctx.fillStyle = '#8a8178';
|
||||
for (const [a, b] of [[30, 5], [5, 30]]) { ctx.beginPath(); ctx.arc(cx + sx * a, cy + sy * b, 2.5, 0, Math.PI * 2); ctx.fill(); }
|
||||
}
|
||||
addCanvas(scene, 'farkel-tray', c);
|
||||
}
|
||||
|
||||
// ── set-aside rail ───────────────────────────────────────────────────────────
|
||||
function bakeRail(scene) {
|
||||
const P = PAD_PX;
|
||||
const c = canvas(RAIL.w + P * 2, RAIL.h + P * 2), ctx = c.getContext('2d');
|
||||
const x = P, y = P, w = RAIL.w, h = RAIL.h;
|
||||
const topH = RAIL_TOP_H;
|
||||
dropShadow(ctx, () => { rr(ctx, x, y, w, h, 14); ctx.fillStyle = '#2e1a0b'; ctx.fill(); }, { blur: 22, dy: 12, alpha: 0.6 });
|
||||
ctx.save(); rr(ctx, x, y, w, h, 14); ctx.clip();
|
||||
const tg = ctx.createLinearGradient(0, y, 0, y + topH);
|
||||
tg.addColorStop(0, '#a26c38'); tg.addColorStop(1, '#84542a');
|
||||
ctx.fillStyle = tg; ctx.fillRect(x, y, w, topH);
|
||||
grain(ctx, x, y, w, topH, { lines: 16 });
|
||||
// felt groove where kept dice sit
|
||||
const gx = RAIL_START_X - RAIL.x + P - 10;
|
||||
ctx.save();
|
||||
rr(ctx, gx, y + 12, w - (gx - x) - 16, topH - 22, 12);
|
||||
const sg = ctx.createLinearGradient(0, y + 12, 0, y + topH - 10);
|
||||
sg.addColorStop(0, '#0f2c1d'); sg.addColorStop(1, '#1d5135');
|
||||
ctx.fillStyle = sg; ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 2; ctx.stroke();
|
||||
ctx.restore();
|
||||
// front face
|
||||
const fg = ctx.createLinearGradient(0, y + topH, 0, y + h);
|
||||
fg.addColorStop(0, '#5c3417'); fg.addColorStop(1, '#3a200d');
|
||||
ctx.fillStyle = fg; ctx.fillRect(x, y + topH, w, h - topH);
|
||||
grain(ctx, x, y + topH, w, h - topH, { lines: 10, tone: 'rgba(15,6,2,0.35)' });
|
||||
ctx.fillStyle = 'rgba(255,220,170,0.25)'; ctx.fillRect(x, y + topH, w, 2);
|
||||
ctx.restore();
|
||||
// engraved label at the left of the shelf top
|
||||
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
ctx.font = `20px ${DISPLAY_FONT}`;
|
||||
const lx = x + (RAIL_START_X - RAIL.x) / 2 - 6;
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.45)'; ctx.fillText('SET ASIDE', lx + 1, y + 22);
|
||||
ctx.fillStyle = '#f1d6a6'; ctx.fillText('SET ASIDE', lx, y + 21);
|
||||
ctx.font = `italic 13px ${SERIF}`;
|
||||
ctx.fillStyle = 'rgba(240,214,166,0.7)'; ctx.fillText('this turn, by throw', lx, y + 42);
|
||||
addCanvas(scene, 'farkel-rail', c);
|
||||
}
|
||||
|
||||
// ── dice cup ─────────────────────────────────────────────────────────────────
|
||||
function bakeCup(scene) {
|
||||
const P = 14;
|
||||
const cw = CUP.w, ch = CUP.h;
|
||||
const c = canvas(cw + P * 2, ch + P * 2), ctx = c.getContext('2d');
|
||||
const top = P + 18, bot = P + ch - 10;
|
||||
const lt = P + 6, rt = P + cw - 6;
|
||||
const lb = P + 16, rb = P + cw - 16;
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.45)';
|
||||
ctx.beginPath(); ctx.ellipse(P + cw / 2 + 8, bot + 2, cw * 0.42, 12, 0, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(lt, top); ctx.lineTo(rt, top); ctx.lineTo(rb, bot);
|
||||
ctx.ellipse(P + cw / 2, bot, (rb - lb) / 2, 10, 0, 0, Math.PI, false);
|
||||
ctx.lineTo(lt, top); ctx.closePath();
|
||||
const g = ctx.createLinearGradient(lt, 0, rt, 0);
|
||||
g.addColorStop(0, '#2a140a'); g.addColorStop(0.3, '#6b3a1e'); g.addColorStop(0.55, '#52290f'); g.addColorStop(1, '#1f0e06');
|
||||
ctx.fillStyle = g; ctx.fill();
|
||||
ctx.clip();
|
||||
ctx.fillStyle = noisePattern(ctx, 64, 50); ctx.fillRect(0, 0, c.width, c.height);
|
||||
// a red/black plaid band
|
||||
const by = bot - 46;
|
||||
ctx.fillStyle = '#8e1a1a'; ctx.fillRect(0, by, c.width, 22);
|
||||
ctx.fillStyle = 'rgba(10,6,6,0.6)';
|
||||
for (let xx = 0; xx < c.width; xx += 16) ctx.fillRect(xx, by, 8, 22);
|
||||
ctx.fillRect(0, by + 7, c.width, 8);
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.fillRect(0, by - 2, c.width, 2); ctx.fillRect(0, by + 22, c.width, 2);
|
||||
// embossed snowflake badge
|
||||
snowflake(ctx, P + cw / 2, (top + by) / 2 + 12, 20, { lw: 2.5, color: 'rgba(255,214,160,0.4)' });
|
||||
ctx.restore();
|
||||
// sheepskin cuff around the mouth
|
||||
ctx.save();
|
||||
for (let i = 0; i < 70; i++) {
|
||||
const a = (i / 70) * Math.PI * 2;
|
||||
const rx = (rt - lt) / 2 + 4, ry = 17;
|
||||
const px = P + cw / 2 + Math.cos(a) * rx, py = top + 4 + Math.sin(a) * ry;
|
||||
ctx.fillStyle = `rgba(${236 + Math.random() * 14},${228 + Math.random() * 14},${212 + Math.random() * 14},1)`;
|
||||
ctx.beginPath(); ctx.arc(px, py, 7 + Math.random() * 3, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
ctx.beginPath(); ctx.ellipse(P + cw / 2, top + 2, (rt - lt) / 2 - 8, 10, 0, 0, Math.PI * 2);
|
||||
const ig = ctx.createLinearGradient(0, top - 10, 0, top + 12);
|
||||
ig.addColorStop(0, '#0d0503'); ig.addColorStop(1, '#2a140a');
|
||||
ctx.fillStyle = ig; ctx.fill();
|
||||
addCanvas(scene, 'farkel-cup', c);
|
||||
}
|
||||
|
||||
// ── seat place-card ──────────────────────────────────────────────────────────
|
||||
function bakeSeat(scene) {
|
||||
const P = 16;
|
||||
const c = canvas(SEAT.w + P * 2, SEAT.h + P * 2), ctx = c.getContext('2d');
|
||||
dropShadow(ctx, () => { rr(ctx, P, P, SEAT.w, SEAT.h, 18); ctx.fillStyle = '#2b170b'; ctx.fill(); }, { blur: 18, dy: 8, alpha: 0.55 });
|
||||
ctx.save(); rr(ctx, P, P, SEAT.w, SEAT.h, 18); ctx.clip();
|
||||
const g = ctx.createLinearGradient(0, P, 0, P + SEAT.h);
|
||||
g.addColorStop(0, 'rgba(66,38,18,0.94)'); g.addColorStop(1, 'rgba(38,20,9,0.94)');
|
||||
ctx.fillStyle = g; ctx.fillRect(P, P, SEAT.w, SEAT.h);
|
||||
grain(ctx, P, P, SEAT.w, SEAT.h, { lines: 12, tone: 'rgba(0,0,0,0.25)' });
|
||||
// plaid strip along the bottom
|
||||
ctx.fillStyle = '#7a1717'; ctx.fillRect(P, P + SEAT.h - 10, SEAT.w, 10);
|
||||
ctx.fillStyle = 'rgba(10,6,6,0.6)';
|
||||
for (let xx = P; xx < P + SEAT.w; xx += 14) ctx.fillRect(xx, P + SEAT.h - 10, 7, 10);
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(214,170,96,0.55)'; ctx.lineWidth = 2;
|
||||
rr(ctx, P + 4, P + 4, SEAT.w - 8, SEAT.h - 8, 15); ctx.stroke();
|
||||
addCanvas(scene, 'farkel-seat', c);
|
||||
}
|
||||
|
||||
// ── score pad ────────────────────────────────────────────────────────────────
|
||||
export function padKey(n) { return `farkel-pad-${n}`; }
|
||||
|
||||
function bakePad(scene, n, target) {
|
||||
const key = `${padKey(n)}-${target}`;
|
||||
const P = PAD_PX;
|
||||
const ox = BOARD.x - P, oy = Math.min(BOARD.y, CLIP.y) - P;
|
||||
if (scene.textures.exists(key)) return { key, x: ox, y: oy };
|
||||
const c = canvas(BOARD.w + P * 2, BOARD.h + (BOARD.y - CLIP.y) + P * 2), ctx = c.getContext('2d');
|
||||
const X = (x) => x - ox, Y = (y) => y - oy;
|
||||
dropShadow(ctx, () => { rr(ctx, X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h, 22); ctx.fillStyle = '#6a4a2c'; ctx.fill(); }, { blur: 30, dy: 14, alpha: 0.6 });
|
||||
ctx.save(); rr(ctx, X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h, 22); ctx.clip();
|
||||
const bg = ctx.createLinearGradient(X(BOARD.x), 0, X(BOARD.x + BOARD.w), 0);
|
||||
bg.addColorStop(0, '#7e5634'); bg.addColorStop(0.5, '#966a42'); bg.addColorStop(1, '#74502e');
|
||||
ctx.fillStyle = bg; ctx.fillRect(X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h);
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 40); ctx.fillRect(X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h);
|
||||
ctx.restore();
|
||||
// paper
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#e9e1c8'; ctx.fillRect(X(PAPER.x) + 6, Y(PAPER.y) + 6, PAPER.w, PAPER.h); }, { blur: 6, dy: 2, alpha: 0.3 });
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#f8f3e2'; ctx.fillRect(X(PAPER.x), Y(PAPER.y), PAPER.w, PAPER.h); }, { blur: 10, dy: 3, alpha: 0.35 });
|
||||
ctx.save(); ctx.beginPath(); ctx.rect(X(PAPER.x), Y(PAPER.y), PAPER.w, PAPER.h); ctx.clip();
|
||||
ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(X(PAPER.x), Y(PAPER.y), PAPER.w, PAPER.h);
|
||||
// title
|
||||
ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
|
||||
ctx.font = `44px ${DISPLAY_FONT}`;
|
||||
ctx.fillStyle = '#8e1a1a';
|
||||
ctx.fillText('FARKLE', X(PAD_TITLE.x), Y(PAD_TITLE.y));
|
||||
ctx.font = `15px ${PRINT_FONT}`;
|
||||
ctx.fillStyle = '#6f5d45';
|
||||
ctx.fillText(`GEROME'S LODGE · FIRST TO ${target.toLocaleString('en-US')}`, X(PAD_TITLE.x) + 196, Y(PAD_TITLE.y) + 4);
|
||||
snowflake(ctx, X(PAPER.x + PAPER.w - 46), Y(PAD_TITLE.y), 20, { lw: 2.5, color: 'rgba(70,110,170,0.55)' });
|
||||
// header band + ruled lines
|
||||
const gx0 = X(PAD_GRID.x), gw = PAD_GRID.w;
|
||||
ctx.fillStyle = 'rgba(34,48,79,0.06)'; ctx.fillRect(gx0, Y(PAD_HEAD.y), gw, PAD_HEAD.h);
|
||||
ctx.fillStyle = '#22304f'; ctx.fillRect(gx0, Y(PAD_HEAD.y + PAD_HEAD.h) - 2, gw, 2);
|
||||
ctx.font = `13px ${PRINT_FONT}`; ctx.fillStyle = '#6f5d45'; ctx.textAlign = 'center';
|
||||
ctx.fillText('TURN', gx0 + PAD_MARGIN / 2, Y(PAD_HEAD.y + PAD_HEAD.h / 2));
|
||||
const rowsTop = PAD_HEAD.y + PAD_HEAD.h;
|
||||
ctx.fillStyle = 'rgba(70,95,150,0.35)';
|
||||
for (let r = 1; r <= PAD_ROWS; r++) ctx.fillRect(gx0, Y(rowsTop + r * PAD_ROW_H) - 1, gw, 1);
|
||||
// red margin + column rules
|
||||
const bottom = Y(rowsTop + PAD_ROWS * PAD_ROW_H);
|
||||
ctx.fillStyle = 'rgba(179,38,30,0.6)';
|
||||
ctx.fillRect(gx0 + PAD_MARGIN - 1, Y(PAD_HEAD.y), 2, bottom - Y(PAD_HEAD.y));
|
||||
ctx.fillStyle = 'rgba(70,95,150,0.35)';
|
||||
for (let p = 1; p < n; p++) ctx.fillRect(X(padColX(p, n)), Y(PAD_HEAD.y), 1, bottom - Y(PAD_HEAD.y));
|
||||
ctx.restore();
|
||||
// clip
|
||||
const cx = X(CLIP.x), cy = Y(CLIP.y);
|
||||
dropShadow(ctx, () => { rr(ctx, cx, cy, CLIP.w, CLIP.h, 16); ctx.fillStyle = '#9aa1a8'; ctx.fill(); }, { blur: 12, dy: 6, alpha: 0.5 });
|
||||
const mg = ctx.createLinearGradient(0, cy, 0, cy + CLIP.h);
|
||||
mg.addColorStop(0, '#eef1f3'); mg.addColorStop(0.45, '#a9b0b7'); mg.addColorStop(0.55, '#c9ced3'); mg.addColorStop(1, '#7c838a');
|
||||
rr(ctx, cx, cy, CLIP.w, CLIP.h, 16); ctx.fillStyle = mg; ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(40,44,48,0.6)'; ctx.lineWidth = 1.5; ctx.stroke();
|
||||
rr(ctx, cx + CLIP.w / 2 - 40, cy + 12, 80, 20, 10); ctx.fillStyle = 'rgba(60,64,70,0.55)'; ctx.fill();
|
||||
for (const rx of [cx + 24, cx + CLIP.w - 24]) {
|
||||
const rg = ctx.createRadialGradient(rx - 2, cy + CLIP.h - 22, 1, rx, cy + CLIP.h - 20, 8);
|
||||
rg.addColorStop(0, '#ffffff'); rg.addColorStop(1, '#6a7178');
|
||||
ctx.fillStyle = rg; ctx.beginPath(); ctx.arc(rx, cy + CLIP.h - 20, 7, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
addCanvas(scene, key, c);
|
||||
return { key, x: ox, y: oy };
|
||||
}
|
||||
|
||||
// ── scoring chalkboard ───────────────────────────────────────────────────────
|
||||
function bakeCard(scene) {
|
||||
const P = PAD_PX;
|
||||
const c = canvas(CARD.w + P * 2, CARD.h + P * 2), ctx = c.getContext('2d');
|
||||
const x = P, y = P, w = CARD.w, h = CARD.h;
|
||||
dropShadow(ctx, () => { rr(ctx, x, y, w, h, 16); ctx.fillStyle = '#3a2412'; ctx.fill(); }, { blur: 24, dy: 12, alpha: 0.6 });
|
||||
ctx.save(); rr(ctx, x, y, w, h, 16); ctx.clip();
|
||||
const fg = ctx.createLinearGradient(0, y, 0, y + h);
|
||||
fg.addColorStop(0, '#9a6a38'); fg.addColorStop(1, '#6e4520');
|
||||
ctx.fillStyle = fg; ctx.fillRect(x, y, w, h);
|
||||
grain(ctx, x, y, w, h, { lines: 30, tone: 'rgba(50,25,8,0.3)' });
|
||||
ctx.restore();
|
||||
const ix = CARD_INNER.x - CARD.x + P, iy = CARD_INNER.y - CARD.y + P, iw = CARD_INNER.w, ih = CARD_INNER.h;
|
||||
ctx.save(); rr(ctx, ix, iy, iw, ih, 6); ctx.clip();
|
||||
const bg = ctx.createRadialGradient(ix + iw / 2, iy + ih / 2, 40, ix + iw / 2, iy + ih / 2, iw * 0.7);
|
||||
bg.addColorStop(0, '#2f3a34'); bg.addColorStop(1, '#1c2420');
|
||||
ctx.fillStyle = bg; ctx.fillRect(ix, iy, iw, ih);
|
||||
ctx.fillStyle = noisePattern(ctx, 96, 22); ctx.fillRect(ix, iy, iw, ih);
|
||||
// old chalk smudges
|
||||
for (let i = 0; i < 14; i++) {
|
||||
const sx = ix + Math.random() * iw, sy = iy + Math.random() * ih;
|
||||
const sg = ctx.createRadialGradient(sx, sy, 2, sx, sy, 40 + Math.random() * 60);
|
||||
sg.addColorStop(0, 'rgba(255,255,255,0.05)'); sg.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = sg; ctx.fillRect(ix, iy, iw, ih);
|
||||
}
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.55)'; ctx.lineWidth = 3;
|
||||
rr(ctx, ix, iy, iw, ih, 6); ctx.stroke();
|
||||
// chalk ledge with a stub of chalk
|
||||
ctx.fillStyle = '#5a3818'; ctx.fillRect(ix + 20, iy + ih + 4, iw - 40, 10);
|
||||
ctx.fillStyle = '#f4f1e6'; rr(ctx, ix + iw - 110, iy + ih + 1, 34, 9, 4); ctx.fill();
|
||||
addCanvas(scene, 'farkel-card', c);
|
||||
}
|
||||
|
||||
// ── risk thermometer ─────────────────────────────────────────────────────────
|
||||
export const THERMO_TUBE = { x: THERMO.x + THERMO.w / 2, top: THERMO.y + 58, bottom: THERMO.y + THERMO.h - 46, w: 14, bulb: 17 };
|
||||
function bakeThermo(scene) {
|
||||
const P = 12;
|
||||
const c = canvas(THERMO.w + P * 2, THERMO.h + P * 2), ctx = c.getContext('2d');
|
||||
const x = P, y = P, w = THERMO.w, h = THERMO.h;
|
||||
dropShadow(ctx, () => { rr(ctx, x, y, w, h, 30); ctx.fillStyle = '#5a3818'; ctx.fill(); }, { blur: 14, dy: 6, alpha: 0.55 });
|
||||
ctx.save(); rr(ctx, x, y, w, h, 30); ctx.clip();
|
||||
const g = ctx.createLinearGradient(x, 0, x + w, 0);
|
||||
g.addColorStop(0, '#6e4520'); g.addColorStop(0.5, '#9a6a38'); g.addColorStop(1, '#6e4520');
|
||||
ctx.fillStyle = g; ctx.fillRect(x, y, w, h);
|
||||
grain(ctx, x, y, w, h, { lines: 8, tone: 'rgba(40,20,6,0.3)', knots: 0 });
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(255,226,170,0.35)'; ctx.lineWidth = 1.5; rr(ctx, x + 3, y + 3, w - 6, h - 6, 27); ctx.stroke();
|
||||
const tx = THERMO_TUBE.x - THERMO.x + P, tt = THERMO_TUBE.top - THERMO.y + P, tb = THERMO_TUBE.bottom - THERMO.y + P;
|
||||
// snowflake cap
|
||||
snowflake(ctx, tx, y + 24, 13, { lw: 2.5, color: 'rgba(230,244,255,0.85)' });
|
||||
// glass tube + bulb
|
||||
ctx.fillStyle = 'rgba(235,245,255,0.85)';
|
||||
rr(ctx, tx - THERMO_TUBE.w / 2 - 3, tt - 6, THERMO_TUBE.w + 6, tb - tt + 10, 10); ctx.fill();
|
||||
ctx.beginPath(); ctx.arc(tx, tb + 10, THERMO_TUBE.bulb + 3, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = 'rgba(40,30,30,0.85)';
|
||||
rr(ctx, tx - THERMO_TUBE.w / 2, tt - 3, THERMO_TUBE.w, tb - tt + 6, 7); ctx.fill();
|
||||
// tick marks (0–70 %)
|
||||
ctx.strokeStyle = '#f1d6a6'; ctx.fillStyle = '#f1d6a6';
|
||||
ctx.font = `10px ${PRINT_FONT}`; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
|
||||
for (let p = 0; p <= 70; p += 10) {
|
||||
const ty = tb - (p / 70) * (tb - tt);
|
||||
ctx.lineWidth = p % 20 === 0 ? 2 : 1;
|
||||
ctx.beginPath(); ctx.moveTo(tx + 11, ty); ctx.lineTo(tx + (p % 20 === 0 ? 20 : 16), ty); ctx.stroke();
|
||||
}
|
||||
addCanvas(scene, 'farkel-thermo', c);
|
||||
}
|
||||
|
||||
// ── frost sheet for a Farkle ─────────────────────────────────────────────────
|
||||
function bakeFrost(scene) {
|
||||
const c = canvas(TRAY_FELT.w, TRAY_FELT.h), ctx = c.getContext('2d');
|
||||
const w = TRAY_FELT.w, h = TRAY_FELT.h;
|
||||
ctx.save(); rr(ctx, 0, 0, w, h, 14); ctx.clip();
|
||||
const g = ctx.createRadialGradient(w / 2, h / 2, 40, w / 2, h / 2, w * 0.7);
|
||||
g.addColorStop(0, 'rgba(170,215,255,0.18)'); g.addColorStop(1, 'rgba(210,235,255,0.55)');
|
||||
ctx.fillStyle = g; ctx.fillRect(0, 0, w, h);
|
||||
frostCorner(ctx, 0, 0, 1, 1, 340);
|
||||
frostCorner(ctx, w, 0, -1, 1, 340);
|
||||
frostCorner(ctx, 0, h, 1, -1, 300);
|
||||
frostCorner(ctx, w, h, -1, -1, 300);
|
||||
ctx.restore();
|
||||
addCanvas(scene, 'farkel-frost', c);
|
||||
}
|
||||
|
||||
// ── small sprites ────────────────────────────────────────────────────────────
|
||||
function bakeSprites(scene) {
|
||||
const c = canvas(72, 84), ctx = c.getContext('2d');
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
rr(ctx, 14, 34, 44, 40, 16); ctx.fill(); ctx.stroke();
|
||||
for (const [hx, hy, hh] of [[14, 10, 34], [26, 4, 38], [38, 6, 36], [50, 14, 30]]) {
|
||||
rr(ctx, hx, hy, 11, hh, 5.5); ctx.fill(); ctx.stroke();
|
||||
}
|
||||
ctx.save(); ctx.translate(12, 56); ctx.rotate(-0.7);
|
||||
rr(ctx, -6, -18, 12, 26, 6); ctx.fill(); ctx.stroke();
|
||||
ctx.restore();
|
||||
addCanvas(scene, 'farkel-hand', c);
|
||||
|
||||
const s = canvas(32, 32), sx = s.getContext('2d');
|
||||
const g = sx.createRadialGradient(16, 16, 0, 16, 16, 16);
|
||||
g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.35, 'rgba(255,240,190,0.8)'); g.addColorStop(1, 'rgba(255,220,120,0)');
|
||||
sx.fillStyle = g; sx.fillRect(0, 0, 32, 32);
|
||||
addCanvas(scene, 'farkel-spark', s);
|
||||
|
||||
const e = canvas(20, 20), ex = e.getContext('2d');
|
||||
const eg = ex.createRadialGradient(10, 10, 0, 10, 10, 10);
|
||||
eg.addColorStop(0, 'rgba(255,250,220,1)'); eg.addColorStop(0.3, 'rgba(255,170,70,0.9)'); eg.addColorStop(1, 'rgba(255,90,20,0)');
|
||||
ex.fillStyle = eg; ex.fillRect(0, 0, 20, 20);
|
||||
addCanvas(scene, 'farkel-ember', e);
|
||||
|
||||
const f = canvas(40, 40), fx = f.getContext('2d');
|
||||
snowflake(fx, 20, 20, 17, { lw: 2.4, color: 'rgba(255,255,255,0.95)' });
|
||||
addCanvas(scene, 'farkel-flake', f);
|
||||
|
||||
// knit toque (leader's hat)
|
||||
const t = canvas(44, 44), tx = t.getContext('2d');
|
||||
tx.fillStyle = '#b3261e';
|
||||
tx.beginPath(); tx.moveTo(8, 34); tx.quadraticCurveTo(10, 10, 22, 10); tx.quadraticCurveTo(34, 10, 36, 34); tx.closePath(); tx.fill();
|
||||
tx.strokeStyle = 'rgba(255,255,255,0.35)'; tx.lineWidth = 1.5;
|
||||
for (let xx = 12; xx < 34; xx += 5) { tx.beginPath(); tx.moveTo(xx, 16); tx.lineTo(xx, 32); tx.stroke(); }
|
||||
tx.fillStyle = '#f4f1e6'; rr(tx, 5, 30, 34, 9, 4); tx.fill();
|
||||
tx.beginPath(); tx.arc(22, 8, 6, 0, Math.PI * 2); tx.fill();
|
||||
addCanvas(scene, 'farkel-hat', t);
|
||||
}
|
||||
|
||||
// ── entry point ──────────────────────────────────────────────────────────────
|
||||
let baked = false;
|
||||
export async function prepareFarkelArt(scene, nPlayers, target) {
|
||||
try {
|
||||
if (document.fonts?.load) {
|
||||
await Promise.race([
|
||||
Promise.all([
|
||||
document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"'),
|
||||
document.fonts.load('30px YummyCupcakes'),
|
||||
]),
|
||||
new Promise((res) => setTimeout(res, 1200)),
|
||||
]);
|
||||
}
|
||||
} catch (_) { /* fall back to Georgia */ }
|
||||
if (!baked || !scene.textures.exists('farkel-room')) {
|
||||
bakeRoom(scene); bakeTray(scene); bakeRail(scene); bakeCup(scene); bakeSeat(scene);
|
||||
bakeCard(scene); bakeThermo(scene); bakeFrost(scene); bakeSprites(scene);
|
||||
baked = true;
|
||||
}
|
||||
return bakePad(scene, nPlayers, target);
|
||||
}
|
||||
|
|
@ -1,38 +1,72 @@
|
|||
// Farkel — static catalog. No Phaser, no game state. Constants, the die-pip
|
||||
// layout (ported from Yatzi), player colours, and the scoring-reference rows
|
||||
// shown in the info panel.
|
||||
// Farkel — static catalog. No Phaser, no game state: dice count, the default
|
||||
// table rules, house-rule options and the scoring-reference rows.
|
||||
|
||||
export const DICE = 6;
|
||||
export const WIN_TARGET = 10000; // first to 10k triggers a final round
|
||||
export const ON_BOARD_MIN = 500; // single-turn total needed to start banking
|
||||
export const WIN_TARGET = 10000; // default: first to 10k triggers one final round
|
||||
export const ON_BOARD_MIN = 500; // default single-turn total needed to start banking
|
||||
export const THREE_FARKLE_PENALTY = 1000;
|
||||
|
||||
// 3x3 pip layout (col, row offsets in {-1, 0, 1}) per face. Mirrors Yatzi.
|
||||
export const PIP_POS = {
|
||||
1: [[0, 0]],
|
||||
2: [[-1, -1], [1, 1]],
|
||||
3: [[-1, -1], [0, 0], [1, 1]],
|
||||
4: [[-1, -1], [1, -1], [-1, 1], [1, 1]],
|
||||
5: [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]],
|
||||
6: [[-1, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [1, 1]],
|
||||
};
|
||||
// Every rule the engine understands. Saved settings are merged over this.
|
||||
export const DEFAULT_RULES = Object.freeze({
|
||||
target: WIN_TARGET, // 5000 | 10000 | 15000
|
||||
entry: ON_BOARD_MIN, // 0 | 350 | 500 | 1000
|
||||
threeFarkle: false, // three Farkles in a row costs 1,000
|
||||
twoTriplets: false, // two three-of-a-kinds in one roll = 2,500
|
||||
doubling: false, // 4/5/6 of a kind = triple ×2 / ×4 / ×8 (instead of 1k/2k/3k)
|
||||
piggyback: false, // the next player may take over the leftover dice + total
|
||||
});
|
||||
|
||||
// Seat colours (shared visual language with the other tabletop games).
|
||||
export const PLAYER_COLORS = [0xd0473a, 0x4a90d9, 0x49a25a, 0xe2b53c];
|
||||
export const PLAYER_COLOR_HEX = ['#d0473a', '#4a90d9', '#49a25a', '#e2b53c'];
|
||||
export const TARGET_OPTIONS = [5000, 10000, 15000];
|
||||
export const ENTRY_OPTIONS = [0, 350, 500, 1000];
|
||||
|
||||
// Ordered rows for the "Scoring" reference panel.
|
||||
export const SCORING_REFERENCE = [
|
||||
{ label: 'Single 1', value: '100' },
|
||||
{ label: 'Single 5', value: '50' },
|
||||
{ label: 'Three 1s', value: '1000' },
|
||||
{ label: 'Three 2s', value: '200' },
|
||||
{ label: 'Three 3s', value: '300' },
|
||||
{ label: 'Three 4s', value: '400' },
|
||||
{ label: 'Three 5s', value: '500' },
|
||||
{ label: 'Three 6s', value: '600' },
|
||||
{ label: 'Four of a kind', value: '1000' },
|
||||
{ label: 'Five of a kind', value: '2000' },
|
||||
{ label: 'Six of a kind', value: '3000' },
|
||||
{ label: 'Straight 1-6', value: '1500' },
|
||||
{ label: 'Three pairs', value: '1500' },
|
||||
];
|
||||
export function normalizeRules(r = {}) {
|
||||
const out = { ...DEFAULT_RULES, ...r };
|
||||
if (!TARGET_OPTIONS.includes(out.target)) out.target = WIN_TARGET;
|
||||
if (!ENTRY_OPTIONS.includes(out.entry)) out.entry = ON_BOARD_MIN;
|
||||
for (const k of ['threeFarkle', 'twoTriplets', 'doubling', 'piggyback']) out[k] = !!out[k];
|
||||
return out;
|
||||
}
|
||||
|
||||
// Exact chance that a throw of N dice scores nothing (standard combos). The
|
||||
// house rules only add combos inside rolls that already score, so these hold.
|
||||
// tools/verifyFarkel.js re-derives every entry by enumeration.
|
||||
export const FARKLE_ODDS = Object.freeze({
|
||||
1: 4 / 6, 2: 16 / 36, 3: 60 / 216, 4: 204 / 1296, 5: 600 / 7776, 6: 1080 / 46656,
|
||||
});
|
||||
|
||||
// Seat colours (pencil inks on the score pad, seat accents).
|
||||
export const PLAYER_COLORS = [0x22304f, 0x9c2121, 0x1d6a3c, 0x7a3fa0];
|
||||
export const PLAYER_COLOR_HEX = ['#22304f', '#9c2121', '#1d6a3c', '#7a3fa0'];
|
||||
|
||||
const fmt = (n) => n.toLocaleString('en-US');
|
||||
|
||||
// Rows for the scoring card. `key` matches the part keys from scoreParts().
|
||||
export function scoringReference(rules = DEFAULT_RULES) {
|
||||
const r = normalizeRules(rules);
|
||||
const rows = [
|
||||
{ key: 'single1', label: 'Each 1', value: '100' },
|
||||
{ key: 'single5', label: 'Each 5', value: '50' },
|
||||
{ key: 'three1', label: 'Three 1s', value: '1,000' },
|
||||
{ key: 'three2', label: 'Three 2s', value: '200' },
|
||||
{ key: 'three3', label: 'Three 3s', value: '300' },
|
||||
{ key: 'three4', label: 'Three 4s', value: '400' },
|
||||
{ key: 'three5', label: 'Three 5s', value: '500' },
|
||||
{ key: 'three6', label: 'Three 6s', value: '600' },
|
||||
];
|
||||
if (r.doubling) {
|
||||
rows.push({ key: 'four', label: 'Four of a kind', value: 'triple ×2' });
|
||||
rows.push({ key: 'five', label: 'Five of a kind', value: 'triple ×4' });
|
||||
rows.push({ key: 'six', label: 'Six of a kind', value: 'triple ×8' });
|
||||
} else {
|
||||
rows.push({ key: 'four', label: 'Four of a kind', value: fmt(1000) });
|
||||
rows.push({ key: 'five', label: 'Five of a kind', value: fmt(2000) });
|
||||
rows.push({ key: 'six', label: 'Six of a kind', value: fmt(3000) });
|
||||
}
|
||||
rows.push({ key: 'straight', label: 'Straight 1–6', value: fmt(1500) });
|
||||
rows.push({ key: 'pairs', label: 'Three pairs*', value: fmt(1500) });
|
||||
if (r.twoTriplets) rows.push({ key: 'triplets', label: 'Two triplets', value: fmt(2500) });
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Back-compat for anything that imported the old constant.
|
||||
export const SCORING_REFERENCE = scoringReference(DEFAULT_RULES);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,193 @@
|
|||
// FarkelDialogs.js — lodge pop-ups: a cream card in a pine frame with a plaid
|
||||
// band. Each opener returns { close() } and swallows clicks beneath it.
|
||||
//
|
||||
// openPauseMenu resume · table settings · house rules · log · rules · new · leave
|
||||
// openRulesDialog target / entry / house rules (take effect in a new game)
|
||||
// openLogDialog the turn-by-turn ledger
|
||||
// confirmBox yes / no (also used for resume-or-new)
|
||||
|
||||
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { DISPLAY_FONT, SERIF, PRINT_FONT, INK } from './FarkelArt.js';
|
||||
import { TARGET_OPTIONS, ENTRY_OPTIONS } from './FarkelData.js';
|
||||
import { describeLog, fmtPts } from './FarkelLogic.js';
|
||||
|
||||
export function frame(scene, x, y, w, h, depth) {
|
||||
const g = scene.add.graphics().setDepth(depth);
|
||||
g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 4, y + 8, w, h, 14);
|
||||
g.fillStyle(0x7a4e26, 1).fillRoundedRect(x, y, w, h, 14);
|
||||
g.lineStyle(2, 0xe6c088, 0.7).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 11);
|
||||
g.fillStyle(0xf8f3e2, 1).fillRoundedRect(x + 12, y + 12, w - 24, h - 24, 8);
|
||||
// plaid band under the title
|
||||
g.fillStyle(0x8e1a1a, 1).fillRect(x + 12, y + 70, w - 24, 8);
|
||||
g.fillStyle(0x140a0a, 0.6);
|
||||
for (let xx = x + 12; xx < x + w - 12; xx += 16) g.fillRect(xx, y + 70, 8, 8);
|
||||
return g;
|
||||
}
|
||||
|
||||
export function blocker(scene, depth, alpha = 0) {
|
||||
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, alpha)
|
||||
.setDepth(depth).setInteractive();
|
||||
}
|
||||
|
||||
export function title(scene, x, y, text, depth, size = 28) {
|
||||
return scene.add.text(x, y, text, { fontFamily: DISPLAY_FONT, fontSize: `${size}px`, color: '#8e1a1a', align: 'center' })
|
||||
.setOrigin(0.5).setDepth(depth);
|
||||
}
|
||||
|
||||
export function handle(objs, onClose) {
|
||||
let closed = false;
|
||||
return {
|
||||
objs,
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
objs.forEach((o) => o?.destroy?.());
|
||||
onClose?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const onOff = (v) => (v ? 'On' : 'Off');
|
||||
const PACE_LABEL = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' };
|
||||
|
||||
export function openPauseMenu(scene, { settings, depth, onChange, onHouseRules, onLog, onRules, onNewGame, onLeave, onClose }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.5)];
|
||||
const w = 540, h = 780;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, x + w / 2, y + 42, "Gerome's Lodge", depth + 1));
|
||||
const cx = x + w / 2;
|
||||
let hRef = null;
|
||||
const rows = [
|
||||
['Resume', () => hRef.close(), 0x22304f],
|
||||
[() => `Opponent speed: ${PACE_LABEL[settings.pace]}`, () => {
|
||||
const order = ['relaxed', 'normal', 'fast'];
|
||||
onChange('pace', order[(order.indexOf(settings.pace) + 1) % order.length]);
|
||||
}],
|
||||
[() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)],
|
||||
[() => `Scoring-dice hints: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)],
|
||||
[() => `Smart pick (whole combos): ${onOff(settings.smartPick)}`, () => onChange('smartPick', !settings.smartPick)],
|
||||
[() => `Coach (best keep + odds): ${onOff(settings.coach)}`, () => onChange('coach', !settings.coach)],
|
||||
['House Rules…', () => { hRef.close(); onHouseRules(); }],
|
||||
['Turn Log', () => { hRef.close(); onLog(); }],
|
||||
['How to Play', () => onRules()],
|
||||
['New Game', () => { hRef.close(); onNewGame(); }, 0x6a4a1a],
|
||||
['Leave Table', () => { hRef.close(); onLeave(); }, 0x7a2a1a],
|
||||
];
|
||||
rows.forEach(([label, fn, bg], i) => {
|
||||
const text = typeof label === 'function' ? label() : label;
|
||||
const btn = new Button(scene, cx, y + 116 + i * 54, text, () => {
|
||||
fn();
|
||||
if (typeof label === 'function') btn.setLabel(label());
|
||||
}, { width: 440, height: 46, fontSize: 17, bg: bg ?? 0x5a3820 }).setDepth(depth + 2);
|
||||
objs.push(btn);
|
||||
});
|
||||
objs.push(scene.add.text(cx, y + h - 40, 'Keys: Space shake & throw · 1–6 pick dice · R roll · B bank · A best keep · C clear · P piggyback · L log · Esc menu', {
|
||||
fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#5a4428', align: 'center', wordWrap: { width: w - 70 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
hRef = handle(objs, onClose);
|
||||
return hRef;
|
||||
}
|
||||
|
||||
// House rules. Edits a copy; onApply(rules) is called with the result.
|
||||
export function openRulesDialog(scene, { rules, depth, inGame, onApply, onClose }) {
|
||||
const r = { ...rules };
|
||||
const objs = [blocker(scene, depth - 1, 0.5)];
|
||||
const w = 600, h = 690;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, x + w / 2, y + 42, 'House Rules', depth + 1));
|
||||
const cx = x + w / 2;
|
||||
let hRef = null;
|
||||
const cycle = (list, v) => list[(list.indexOf(v) + 1) % list.length];
|
||||
const rows = [
|
||||
[() => `Play to: ${fmtPts(r.target)}`, () => { r.target = cycle(TARGET_OPTIONS, r.target); }, 'First to reach it triggers one final round.'],
|
||||
[() => `Get on the board: ${r.entry ? fmtPts(r.entry) : 'no minimum'}`, () => { r.entry = cycle(ENTRY_OPTIONS, r.entry); }, 'Points needed in one turn before your first bank.'],
|
||||
[() => `Three-Farkle penalty: ${onOff(r.threeFarkle)}`, () => { r.threeFarkle = !r.threeFarkle; }, 'A third Farkle in a row costs 1,000.'],
|
||||
[() => `Two triplets = 2,500: ${onOff(r.twoTriplets)}`, () => { r.twoTriplets = !r.twoTriplets; }, 'Two three-of-a-kinds in one throw.'],
|
||||
[() => `Doubling kinds: ${onOff(r.doubling)}`, () => { r.doubling = !r.doubling; }, '4/5/6 of a kind = the triple ×2 / ×4 / ×8.'],
|
||||
[() => `Piggyback: ${onOff(r.piggyback)}`, () => { r.piggyback = !r.piggyback; }, "Ride the last player's leftover dice and total."],
|
||||
];
|
||||
rows.forEach(([label, fn, hint], i) => {
|
||||
const by = y + 120 + i * 76;
|
||||
const btn = new Button(scene, cx, by, label(), () => { fn(); btn.setLabel(label()); }, {
|
||||
width: 470, height: 46, fontSize: 17, bg: 0x5a3820,
|
||||
}).setDepth(depth + 2);
|
||||
objs.push(btn);
|
||||
objs.push(scene.add.text(cx, by + 32, hint, {
|
||||
fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#6f5d45',
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
});
|
||||
const note = inGame ? 'Rule changes start a new game.' : '';
|
||||
if (note) {
|
||||
objs.push(scene.add.text(cx, y + h - 102, note, { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#8e1a1a' })
|
||||
.setOrigin(0.5).setDepth(depth + 1));
|
||||
}
|
||||
objs.push(new Button(scene, cx - 120, y + h - 54, inGame ? 'Apply & New Game' : 'Apply', () => { hRef.close(); onApply?.(r); }, {
|
||||
width: 220, height: 48, fontSize: 18, bg: 0x22304f,
|
||||
}).setDepth(depth + 2));
|
||||
objs.push(new Button(scene, cx + 120, y + h - 54, 'Cancel', () => hRef.close(), {
|
||||
width: 220, height: 48, fontSize: 18, bg: 0x5a3820,
|
||||
}).setDepth(depth + 2));
|
||||
hRef = handle(objs, onClose);
|
||||
return hRef;
|
||||
}
|
||||
|
||||
// The turn log, newest at the bottom; scrolls with the wheel or the arrows.
|
||||
export function openLogDialog(scene, { gs, depth, onClose }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.5)];
|
||||
const w = 900, h = 820;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, x + w / 2, y + 42, 'Turn Log', depth + 1));
|
||||
const entries = gs.log.filter((e) => e.kind !== 'roll' || e.farkle);
|
||||
const LINES = 24, LH = 25;
|
||||
let top = Math.max(0, entries.length - LINES);
|
||||
const texts = [];
|
||||
for (let i = 0; i < LINES; i++) {
|
||||
texts.push(scene.add.text(x + 44, y + 98 + i * LH, '', {
|
||||
fontFamily: SERIF, fontSize: '17px', color: '#2b2418',
|
||||
}).setDepth(depth + 1));
|
||||
}
|
||||
objs.push(...texts);
|
||||
const turnTag = scene.add.text(x + w - 40, y + 42, '', { fontFamily: PRINT_FONT, fontSize: '13px', color: '#6f5d45' }).setOrigin(1, 0.5).setDepth(depth + 1);
|
||||
objs.push(turnTag);
|
||||
const draw = () => {
|
||||
for (let i = 0; i < LINES; i++) {
|
||||
const e = entries[top + i];
|
||||
if (!e) { texts[i].setText(''); continue; }
|
||||
const bank = e.kind === 'bank', far = e.kind === 'farkle' || (e.kind === 'roll' && e.farkle);
|
||||
texts[i].setText(`${String(e.turn).padStart(3, ' ')} ${describeLog(gs, e)}`)
|
||||
.setColor(far ? '#9c2121' : bank ? INK[e.seat] ?? '#2b2418' : '#2b2418')
|
||||
.setFontStyle(bank ? 'bold' : 'normal');
|
||||
}
|
||||
turnTag.setText(entries.length ? `${top + 1}–${Math.min(entries.length, top + LINES)} of ${entries.length}` : 'Nothing yet');
|
||||
};
|
||||
draw();
|
||||
const scroll = (d) => { top = Math.max(0, Math.min(Math.max(0, entries.length - LINES), top + d)); draw(); };
|
||||
const wheel = (_p, _o, _dx, dy) => scroll(dy > 0 ? 3 : -3);
|
||||
scene.input.on('wheel', wheel);
|
||||
let hRef = null;
|
||||
objs.push(new Button(scene, x + w - 70, y + 120, '▲', () => scroll(-LINES + 2), { width: 60, height: 44, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2));
|
||||
objs.push(new Button(scene, x + w - 70, y + h - 140, '▼', () => scroll(LINES - 2), { width: 60, height: 44, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2));
|
||||
objs.push(new Button(scene, x + w / 2, y + h - 52, 'Close', () => hRef.close(), { width: 220, height: 48, fontSize: 18, bg: 0x22304f }).setDepth(depth + 2));
|
||||
hRef = handle(objs, () => { scene.input.off('wheel', wheel); onClose?.(); });
|
||||
return hRef;
|
||||
}
|
||||
|
||||
export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.5)];
|
||||
const w = 540, h = 270;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, x + w / 2, y + 42, heading, depth + 1, 24));
|
||||
objs.push(scene.add.text(x + w / 2, y + 134, text, {
|
||||
fontFamily: SERIF, fontSize: '17px', color: '#2b2418', align: 'center', wordWrap: { width: w - 70 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
let hRef = null;
|
||||
objs.push(new Button(scene, x + w / 2 - 122, y + h - 50, yes, () => { hRef.close(); onYes?.(); }, { width: 214, height: 46, fontSize: 18, bg: 0x7a2a1a }).setDepth(depth + 2));
|
||||
objs.push(new Button(scene, x + w / 2 + 122, y + h - 50, no, () => { hRef.close(); onNo?.(); }, { width: 214, height: 46, fontSize: 18, bg: 0x22304f }).setDepth(depth + 2));
|
||||
hRef = handle(objs);
|
||||
return hRef;
|
||||
}
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
// FarkelEndScreen.js — the after-game card over the dice tray: final standings,
|
||||
// per-player stats, a score-over-turns chart and the human's personal bests.
|
||||
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { fmtPts } from './FarkelLogic.js';
|
||||
import { INK, INK_HEX, DISPLAY_FONT, PRINT_FONT, SERIF, HAND_FONT } from './FarkelArt.js';
|
||||
import { frame } from './FarkelDialogs.js';
|
||||
|
||||
const BEST_KEY = 'farkel-best';
|
||||
|
||||
// Records the human's best final score and biggest single turn.
|
||||
export function recordPersonalBest(score, bestTurn) {
|
||||
let prev = null;
|
||||
try { prev = JSON.parse(localStorage.getItem(BEST_KEY) || 'null'); } catch (_) { prev = null; }
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const next = {
|
||||
score: Math.max(prev?.score ?? 0, score),
|
||||
scoreDate: score > (prev?.score ?? -1) ? today : prev?.scoreDate ?? today,
|
||||
turn: Math.max(prev?.turn ?? 0, bestTurn),
|
||||
turnDate: bestTurn > (prev?.turn ?? -1) ? today : prev?.turnDate ?? today,
|
||||
};
|
||||
try { localStorage.setItem(BEST_KEY, JSON.stringify(next)); } catch (_) { /* private mode */ }
|
||||
return { prev, next, newScore: !prev || score > prev.score, newTurn: !prev || bestTurn > (prev.turn ?? 0) };
|
||||
}
|
||||
|
||||
export function openEndScreen(scene, { gs, ranks, depth, best, onPlayAgain, onMenu }) {
|
||||
const objs = [];
|
||||
const n = gs.players.length;
|
||||
const w = 1060, rowsH = n * 58;
|
||||
const chartH = 190;
|
||||
const h = 150 + rowsH + chartH + 150;
|
||||
const x = 60 + (1100 - w) / 2, y = Math.max(16, 540 - h / 2);
|
||||
const shade = scene.add.rectangle(590, 540, 1180, 1080, 0x000000, 0.5).setDepth(depth - 1).setInteractive();
|
||||
objs.push(shade, frame(scene, x, y, w, h, depth));
|
||||
const order = gs.players.map((_, i) => i).sort((a, b) => ranks[a] - ranks[b]);
|
||||
const winner = order[0];
|
||||
const human = ranks[0] === 1;
|
||||
const tie = ranks.filter((r) => r === 1).length > 1;
|
||||
const head = tie ? (human ? 'A tie at the top!' : 'A shared win') : human ? 'You win the lodge!' : `${gs.players[winner].name} wins`;
|
||||
objs.push(scene.add.text(x + w / 2, y + 42, head, { fontFamily: DISPLAY_FONT, fontSize: '34px', color: '#8e1a1a' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
|
||||
const cols = [
|
||||
{ k: 'rank', x: x + 50, label: '', o: 0.5 },
|
||||
{ k: 'name', x: x + 96, label: 'PLAYER', o: 0 },
|
||||
{ k: 'total', x: x + 420, label: 'FINAL', o: 0.5 },
|
||||
{ k: 'best', x: x + 560, label: 'BEST TURN', o: 0.5 },
|
||||
{ k: 'avg', x: x + 690, label: 'AVG BANK', o: 0.5 },
|
||||
{ k: 'hot', x: x + 820, label: 'HOT DICE', o: 0.5 },
|
||||
{ k: 'far', x: x + 950, label: 'FARKLES', o: 0.5 },
|
||||
];
|
||||
const hy = y + 104;
|
||||
cols.forEach((c) => {
|
||||
if (!c.label) return;
|
||||
objs.push(scene.add.text(c.x, hy, c.label, { fontFamily: PRINT_FONT, fontSize: '13px', color: '#6f5d45' }).setOrigin(c.o, 0.5).setDepth(depth + 1));
|
||||
});
|
||||
order.forEach((p, row) => {
|
||||
const pl = gs.players[p];
|
||||
const st = pl.stats;
|
||||
const ry = hy + 40 + row * 58;
|
||||
const ink = INK[p];
|
||||
const txt = (c, s, opts = {}) => {
|
||||
const o = scene.add.text(c.x, ry, s, { fontFamily: HAND_FONT, fontSize: '27px', color: ink, ...opts }).setOrigin(c.o, 0.5).setDepth(depth + 1);
|
||||
objs.push(o);
|
||||
return o;
|
||||
};
|
||||
if (row > 0) {
|
||||
const g = scene.add.graphics().setDepth(depth + 1);
|
||||
g.fillStyle(0x465f96, 0.25).fillRect(x + 30, ry - 29, w - 60, 1);
|
||||
objs.push(g);
|
||||
}
|
||||
txt(cols[0], ['1st', '2nd', '3rd', '4th'][ranks[p] - 1], { color: ranks[p] === 1 ? '#8e1a1a' : '#6f5d45', fontSize: '23px' });
|
||||
txt(cols[1], pl.name.length > 16 ? pl.name.slice(0, 15) + '…' : pl.name);
|
||||
txt(cols[2], fmtPts(pl.score), { fontSize: '34px' });
|
||||
txt(cols[3], st.bestTurn ? fmtPts(st.bestTurn) : '—');
|
||||
txt(cols[4], st.banks ? fmtPts(Math.round(st.bankTotal / st.banks / 10) * 10) : '—');
|
||||
txt(cols[5], String(st.hotDice));
|
||||
txt(cols[6], `${st.farkles}${st.penalties ? ` (−${st.penalties})` : ''}`);
|
||||
});
|
||||
|
||||
// score-over-turns chart
|
||||
const cx0 = x + 90, cy0 = hy + 40 + rowsH, cw = w - 160, ch = chartH - 30;
|
||||
const g = scene.add.graphics().setDepth(depth + 1);
|
||||
objs.push(g);
|
||||
const maxTurns = Math.max(2, ...gs.players.map((p) => p.stats.history.length));
|
||||
const maxScore = Math.max(gs.rules.target, ...gs.players.map((p) => p.score)) * 1.05;
|
||||
const X = (k) => cx0 + (k / (maxTurns - 1)) * cw;
|
||||
const Y = (v) => cy0 + ch - (Math.max(0, v) / maxScore) * ch;
|
||||
g.lineStyle(1, 0x6f5d45, 0.5).strokeRect(cx0, cy0, cw, ch);
|
||||
// target line (dashed)
|
||||
const ty = Y(gs.rules.target);
|
||||
g.lineStyle(2, 0x8e1a1a, 0.6);
|
||||
for (let xx = cx0; xx < cx0 + cw; xx += 18) g.lineBetween(xx, ty, Math.min(cx0 + cw, xx + 10), ty);
|
||||
objs.push(scene.add.text(cx0 - 8, ty, fmtPts(gs.rules.target), { fontFamily: PRINT_FONT, fontSize: '12px', color: '#8e1a1a' }).setOrigin(1, 0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(cx0 - 8, cy0 + ch, '0', { fontFamily: PRINT_FONT, fontSize: '12px', color: '#6f5d45' }).setOrigin(1, 0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(cx0 + cw, cy0 + ch + 14, `turn ${maxTurns - 1}`, { fontFamily: PRINT_FONT, fontSize: '12px', color: '#6f5d45' }).setOrigin(1, 0.5).setDepth(depth + 1));
|
||||
gs.players.forEach((pl, p) => {
|
||||
const hist = pl.stats.history;
|
||||
g.lineStyle(3, INK_HEX[p], 0.9);
|
||||
g.beginPath();
|
||||
hist.forEach((v, k) => { if (k === 0) g.moveTo(X(k), Y(v)); else g.lineTo(X(k), Y(v)); });
|
||||
g.strokePath();
|
||||
g.fillStyle(INK_HEX[p], 1).fillCircle(X(hist.length - 1), Y(hist[hist.length - 1]), 4);
|
||||
});
|
||||
|
||||
const fy = y + h - 104;
|
||||
const me = gs.players[0];
|
||||
const bits = [];
|
||||
if (best.newScore && best.prev) bits.push(`New best score! ${fmtPts(me.score)} beats ${fmtPts(best.prev.score)}.`);
|
||||
else bits.push(`Best score: ${fmtPts(best.next.score)}.`);
|
||||
if (best.newTurn && best.prev && me.stats.bestTurn) bits.push(`New biggest turn: ${fmtPts(me.stats.bestTurn)}!`);
|
||||
else bits.push(`Biggest turn ever: ${fmtPts(best.next.turn)}.`);
|
||||
objs.push(scene.add.text(x + w / 2, fy, bits.join(' · '), {
|
||||
fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: (best.newScore || best.newTurn) && best.prev ? '#8e1a1a' : '#5a4428',
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
objs.push(new Button(scene, x + w / 2 - 140, y + h - 52, 'Rematch', onPlayAgain, { width: 240, height: 50, fontSize: 20, bg: 0x22304f }).setDepth(depth + 2));
|
||||
objs.push(new Button(scene, x + w / 2 + 140, y + h - 52, 'Back to Menu', onMenu, { width: 240, height: 50, fontSize: 20, bg: 0x5a3820 }).setDepth(depth + 2));
|
||||
|
||||
objs.forEach((o) => { if (o !== shade && o.y !== undefined) o.y -= 30; if (o.setAlpha) o.setAlpha(0); });
|
||||
scene.tweens.add({ targets: objs.filter((o) => o !== shade), y: '+=30', alpha: 1, duration: 380, ease: 'Back.Out' });
|
||||
shade.setAlpha(0);
|
||||
scene.tweens.add({ targets: shade, alpha: 1, duration: 300 });
|
||||
return { close: () => objs.forEach((o) => o.destroy()) };
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,161 @@
|
|||
// FarkelLayout.js — every screen rect for Gerome's Ski Lodge Farkle table, plus
|
||||
// the dice-tray projection. Phaser-free (tools/verifyFarkel.js checks overlaps).
|
||||
//
|
||||
// ┌ opponent seats (top) ─────────────────────┐ ┌ clipboard score pad ──┐
|
||||
// │ felt dice tray │ │ (one row per turn) │
|
||||
// │ "set aside" rail (kept dice, by throw) │ ├ chalkboard scoring ───┤
|
||||
// └ you · cup · risk gauge · status · buttons ┘ └───────────────────────┘
|
||||
|
||||
export const W = 1920;
|
||||
export const H = 1080;
|
||||
|
||||
// ── Seats ────────────────────────────────────────────────────────────────────
|
||||
export const SEAT = { w: 360, h: 150, y: 12, gap: 15, left: 40, span: 1120 };
|
||||
export function seatRect(k, nOpp) {
|
||||
const total = nOpp * SEAT.w + (nOpp - 1) * SEAT.gap;
|
||||
const x0 = SEAT.left + (SEAT.span - total) / 2;
|
||||
return { x: x0 + k * (SEAT.w + SEAT.gap), y: SEAT.y, w: SEAT.w, h: SEAT.h };
|
||||
}
|
||||
export function seatParts(k, nOpp) {
|
||||
const r = seatRect(k, nOpp);
|
||||
return {
|
||||
rect: r,
|
||||
portrait: { x: r.x + 70, y: r.y + 75, r: 52 },
|
||||
name: { x: r.x + 140, y: r.y + 32 },
|
||||
score: { x: r.x + 140, y: r.y + 70 },
|
||||
line: { x: r.x + 140, y: r.y + 108 },
|
||||
hat: { x: r.x + 112, y: r.y + 26 },
|
||||
bubble: { x: r.x + 138, y: r.y + 86, w: 214, h: 58 },
|
||||
};
|
||||
}
|
||||
|
||||
// ── Dice tray ────────────────────────────────────────────────────────────────
|
||||
export const TRAY = { x: 60, y: 176, w: 1100, h: 470 };
|
||||
export const TRAY_WALL = 26;
|
||||
export const TRAY_FELT = { x: TRAY.x + TRAY_WALL, y: TRAY.y + TRAY_WALL, w: TRAY.w - TRAY_WALL * 2, h: TRAY.h - TRAY_WALL * 2 };
|
||||
export const TRAY_CAM = { sin: 0.62, cos: 0.785 };
|
||||
export const TRAY_WORLD = { w: TRAY_FELT.w, h: TRAY_FELT.h / TRAY_CAM.sin };
|
||||
export const DIE_SIZE = 64;
|
||||
|
||||
// One shared ground plane for the tray, the rail and everything between.
|
||||
export function ground(u, v) {
|
||||
return { x: TRAY_FELT.x + u, y: TRAY_FELT.y + v * TRAY_CAM.sin, s: 1 };
|
||||
}
|
||||
export function toWorld(x, y) {
|
||||
return { u: x - TRAY_FELT.x, v: (y - TRAY_FELT.y) / TRAY_CAM.sin };
|
||||
}
|
||||
|
||||
// Where n dice rest after a throw (tidied into a row).
|
||||
const COL_GAP = 134;
|
||||
export function columnU(i, n) { return TRAY_FELT.w / 2 + (i - (n - 1) / 2) * COL_GAP; }
|
||||
export const REST_V = TRAY_WORLD.h * 0.56;
|
||||
|
||||
// ── Set-aside rail ───────────────────────────────────────────────────────────
|
||||
export const RAIL = { x: 60, y: 656, w: 1100, h: 150 };
|
||||
export const RAIL_TOP_H = 84; // the shelf top; the rest is the front face
|
||||
export const RAIL_GROUND_Y = 702; // where a kept die sits
|
||||
export const RAIL_V = toWorld(0, RAIL_GROUND_Y).v;
|
||||
export const RAIL_LABEL_Y = RAIL.y + RAIL_TOP_H + (RAIL.h - RAIL_TOP_H) / 2;
|
||||
export const RAIL_START_X = RAIL.x + 250; // left of this: the engraved "SET ASIDE"
|
||||
const RAIL_STEP = 86, RAIL_GROUP_GAP = 40;
|
||||
|
||||
// Slots for the kept dice of this cycle, grouped by throw. sizes = dice per
|
||||
// group. Returns { us: [u per die], labels: [{ x, w }] per group }.
|
||||
export function railSlots(sizes) {
|
||||
const us = [];
|
||||
const labels = [];
|
||||
let x = RAIL_START_X + RAIL_STEP / 2;
|
||||
sizes.forEach((n, g) => {
|
||||
if (g > 0) x += RAIL_GROUP_GAP;
|
||||
const x0 = x;
|
||||
for (let i = 0; i < n; i++) { us.push(x - TRAY_FELT.x); x += RAIL_STEP; }
|
||||
labels.push({ x: (x0 + x - RAIL_STEP) / 2, w: n * RAIL_STEP + RAIL_GROUP_GAP - 12 });
|
||||
});
|
||||
return { us, labels };
|
||||
}
|
||||
export function railU(k, groups = 6) {
|
||||
const sizes = Array.from({ length: groups }, () => 1);
|
||||
return railSlots(sizes).us[k];
|
||||
}
|
||||
export const RAIL_CHIP = { x: RAIL.x + 128, y: RAIL.y + RAIL_TOP_H / 2 + 2 }; // hot-dice carry chip
|
||||
|
||||
// ── Bottom rail (you) ────────────────────────────────────────────────────────
|
||||
export const HUMAN_PORTRAIT = { x: 92, y: 912, r: 56 };
|
||||
export const HUMAN_NAME = { x: 92, y: 994 };
|
||||
export const HUMAN_SCORE = { x: 92, y: 1034 };
|
||||
export const HUMAN_HAT = { x: 52, y: 860 };
|
||||
export const CUP = { x: 262, y: 940, w: 130, h: 160 }; // centre
|
||||
export const CUP_MOUTH = { x: CUP.x, y: CUP.y - CUP.h / 2 + 18 };
|
||||
export const THERMO = { x: 346, y: 826, w: 70, h: 236 };
|
||||
export const TURN_TOTAL = { x: 660, y: 852 };
|
||||
export const STATUS = { x: 660, y: 906, w: 430 };
|
||||
export const SUBLINE = { x: 660, y: 948 };
|
||||
export const TICKER = { x: 660, y: 1044 };
|
||||
export const BTN_BIG = { w: 236, h: 54 };
|
||||
export const BTN_SMALL = { w: 112, h: 42 };
|
||||
export const ROLL_BTN = { x: 1040, y: 852 };
|
||||
export const BANK_BTN = { x: 1040, y: 914 };
|
||||
export const BEST_BTN = { x: 978, y: 976 };
|
||||
export const CLEAR_BTN = { x: 1102, y: 976 };
|
||||
export const LOG_BTN = { x: 978, y: 1030 };
|
||||
export const MENU_BTN = { x: 1102, y: 1030 };
|
||||
export const BANNER = { x: TRAY.x + TRAY.w / 2, y: TRAY.y + TRAY.h * 0.44 };
|
||||
export const FINAL_RIBBON = { x: TRAY.x + TRAY.w / 2, y: TRAY.y + 8, w: 640, h: 40 };
|
||||
export const PIGGY = { x: TRAY.x + TRAY.w / 2, y: TRAY.y + TRAY.h * 0.5 };
|
||||
|
||||
// Throw origins in tray-world coordinates.
|
||||
export function humanOrigin() {
|
||||
return { u: CUP.x - TRAY_FELT.x + 40, v: TRAY_WORLD.h + 70, h: 130 };
|
||||
}
|
||||
export function seatOrigin(portraitX) {
|
||||
return { u: portraitX - TRAY_FELT.x, v: -90, h: 110 };
|
||||
}
|
||||
|
||||
// ── Score pad (clipboard) ────────────────────────────────────────────────────
|
||||
export const BOARD = { x: 1186, y: 12, w: 716, h: 640 };
|
||||
export const CLIP = { x: BOARD.x + BOARD.w / 2 - 110, y: 0, w: 220, h: 70 };
|
||||
export const PAPER = { x: BOARD.x + 22, y: 56, w: BOARD.w - 44, h: 580 };
|
||||
export const PAD_TITLE = { x: PAPER.x + 30, y: PAPER.y + 50 };
|
||||
export const PAD_HEAD = { y: PAPER.y + 98, h: 52 };
|
||||
export const PAD_MARGIN = 54; // turn numbers left of the red line
|
||||
export const PAD_ROW_H = 34;
|
||||
export const PAD_ROWS = Math.floor((PAPER.y + PAPER.h - 12 - (PAD_HEAD.y + PAD_HEAD.h)) / PAD_ROW_H);
|
||||
export const PAD_GRID = { x: PAPER.x + 12, y: PAD_HEAD.y, w: PAPER.w - 24 };
|
||||
export function padColW(n) { return (PAD_GRID.w - PAD_MARGIN) / n; }
|
||||
export function padColX(p, n) { return PAD_GRID.x + PAD_MARGIN + p * padColW(n); }
|
||||
export function padRowY(r) { return PAD_HEAD.y + PAD_HEAD.h + r * PAD_ROW_H; } // top of visible row r
|
||||
|
||||
// ── Scoring chalkboard ───────────────────────────────────────────────────────
|
||||
export const CARD = { x: 1186, y: 666, w: 716, h: 402 };
|
||||
export const CARD_INNER = { x: CARD.x + 26, y: CARD.y + 26, w: CARD.w - 52, h: CARD.h - 52 };
|
||||
export const CARD_ROW_H = 38;
|
||||
export const CARD_COLS = [
|
||||
{ x: CARD_INNER.x + 18, w: CARD_INNER.w / 2 - 30 },
|
||||
{ x: CARD_INNER.x + CARD_INNER.w / 2 + 12, w: CARD_INNER.w / 2 - 30 },
|
||||
];
|
||||
export const CARD_ROWS_TOP = CARD_INNER.y + 62;
|
||||
|
||||
// ── Checks ───────────────────────────────────────────────────────────────────
|
||||
export function hudFurniture(nOpp) {
|
||||
const f = [];
|
||||
for (let k = 0; k < nOpp; k++) f.push({ name: `seat${k}`, ...seatRect(k, nOpp) });
|
||||
f.push({ name: 'tray', ...TRAY });
|
||||
f.push({ name: 'rail', ...RAIL });
|
||||
const c = (name, o, w, h) => ({ name, x: o.x - w / 2, y: o.y - h / 2, w, h });
|
||||
f.push(c('portrait', HUMAN_PORTRAIT, HUMAN_PORTRAIT.r * 2, HUMAN_PORTRAIT.r * 2));
|
||||
f.push({ name: 'humanText', x: 20, y: HUMAN_NAME.y - 16, w: 150, h: HUMAN_SCORE.y + 18 - (HUMAN_NAME.y - 16) });
|
||||
f.push(c('cup', CUP, CUP.w, CUP.h));
|
||||
f.push({ name: 'thermo', x: THERMO.x, y: THERMO.y, w: THERMO.w, h: THERMO.h });
|
||||
f.push({ name: 'status', x: STATUS.x - STATUS.w / 2, y: TURN_TOTAL.y - 26, w: STATUS.w, h: TICKER.y + 30 - (TURN_TOTAL.y - 26) });
|
||||
f.push(c('roll', ROLL_BTN, BTN_BIG.w, BTN_BIG.h));
|
||||
f.push(c('bank', BANK_BTN, BTN_BIG.w, BTN_BIG.h));
|
||||
f.push(c('best', BEST_BTN, BTN_SMALL.w, BTN_SMALL.h));
|
||||
f.push(c('clear', CLEAR_BTN, BTN_SMALL.w, BTN_SMALL.h));
|
||||
f.push(c('log', LOG_BTN, BTN_SMALL.w, BTN_SMALL.h));
|
||||
f.push(c('menu', MENU_BTN, BTN_SMALL.w, BTN_SMALL.h));
|
||||
f.push({ name: 'board', ...BOARD });
|
||||
f.push({ name: 'card', ...CARD });
|
||||
return f;
|
||||
}
|
||||
export const rectsOverlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
||||
export const onScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= W && r.y + r.h <= H;
|
||||
|
|
@ -1,117 +1,167 @@
|
|||
// Farkel — pure game engine. No Phaser, no timers. Deterministic given a seed so
|
||||
// the AI self-play test is reproducible and lookahead is side-effect free.
|
||||
// Farkel — pure game engine. No Phaser, no timers, JSON-serialisable state (the
|
||||
// scene autosaves it). Every random draw comes from an injected rng.
|
||||
//
|
||||
// Scoring rules (confirmed): single 1 = 100, single 5 = 50; three-of-a-kind =
|
||||
// face×100 (three 1s = 1000); four = 1000, five = 2000, six = 3000; straight
|
||||
// 1-6 = 1500; three pairs = 1500. Hot dice: set aside all six and roll again,
|
||||
// keeping the turn total. Must bank 500+ in one turn before any points count.
|
||||
// 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, WIN_TARGET, ON_BOARD_MIN } from './FarkelData.js';
|
||||
import { DICE, DEFAULT_RULES, THREE_FARKLE_PENALTY, normalizeRules } from './FarkelData.js';
|
||||
|
||||
// ── seeded RNG (mulberry32) ──────────────────────────────────────────────────
|
||||
function mulberry32(seed) {
|
||||
let a = seed >>> 0;
|
||||
return function () {
|
||||
a |= 0; a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
const LOG_CAP = 400;
|
||||
const NUM = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six'];
|
||||
|
||||
// ── scoring helpers ──────────────────────────────────────────────────────────
|
||||
function countsOf(dice) {
|
||||
// ── scoring ──────────────────────────────────────────────────────────────────
|
||||
export function countsOf(dice) {
|
||||
const c = [0, 0, 0, 0, 0, 0, 0];
|
||||
for (const v of dice) c[v]++;
|
||||
return c;
|
||||
}
|
||||
|
||||
// Value of an N-of-a-kind (n >= 3) of face v.
|
||||
function nKindValue(v, n) {
|
||||
if (n === 3) return v === 1 ? 1000 : v * 100;
|
||||
if (n === 4) return 1000;
|
||||
if (n === 5) return 2000;
|
||||
return 3000; // n === 6
|
||||
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;
|
||||
}
|
||||
|
||||
// For c (>=3) dice of face v, the best of "flat N-of-a-kind" vs
|
||||
// "three-of-a-kind + the rest as singles" (only ever better for 1s/5s).
|
||||
function bestGroupValue(v, c) {
|
||||
const flat = nKindValue(v, c);
|
||||
let alt = -1;
|
||||
if (v === 1) alt = 1000 + (c - 3) * 100;
|
||||
else if (v === 5) alt = 500 + (c - 3) * 50;
|
||||
return Math.max(flat, alt);
|
||||
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 a chosen multiset of dice, requiring that EVERY die contributes to a
|
||||
// combo. Returns { valid, points }.
|
||||
export function scoreSelection(dice) {
|
||||
if (!dice || dice.length === 0) return { valid: false, points: 0 };
|
||||
// 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 total = dice.length;
|
||||
let best = null;
|
||||
const note = (p) => { best = best === null ? p : Math.max(best, p); };
|
||||
const cands = [];
|
||||
|
||||
// Whole-set six-dice patterns.
|
||||
if (total === 6) {
|
||||
if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] === 1)) note(1500); // straight
|
||||
if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] % 2 === 0)) note(1500); // three pairs
|
||||
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 }]);
|
||||
}
|
||||
}
|
||||
|
||||
// Greedy decomposition — valid only if no die is left non-scoring.
|
||||
let g = 0, ok = true;
|
||||
for (let v = 1; v <= 6; v++) {
|
||||
// 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) { g += bestGroupValue(v, c); }
|
||||
else if (v === 1) g += c * 100;
|
||||
else if (v === 5) g += c * 50;
|
||||
else { ok = false; }
|
||||
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) note(g);
|
||||
if (ok) cands.push(parts);
|
||||
|
||||
if (best === null) return { valid: false, points: 0 };
|
||||
return { valid: true, points: best };
|
||||
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 };
|
||||
}
|
||||
|
||||
// Find the best subset of `dice` (rolled) to set aside given already set-aside
|
||||
// dice from this turn. Brute-forces all 2^n subsets — feasible for n ≤ 6 (63
|
||||
// iterations). Returns the indices of rolled dice and the resulting combined score.
|
||||
export function bestScoring(dice, setAsideDice = []) {
|
||||
const n = dice.length;
|
||||
let bestPts = 0;
|
||||
let bestIndices = [];
|
||||
for (let mask = 1; mask < (1 << n); mask++) {
|
||||
const subset = [];
|
||||
const indices = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
if (mask & (1 << i)) { subset.push(dice[i]); indices.push(i); }
|
||||
}
|
||||
const res = scoreSelection([...setAsideDice, ...subset]);
|
||||
if (res.valid && res.points > bestPts) {
|
||||
bestPts = res.points;
|
||||
bestIndices = indices;
|
||||
}
|
||||
}
|
||||
return { indices: bestIndices, points: bestPts };
|
||||
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 }));
|
||||
}
|
||||
|
||||
// A roll is NOT a farkle if any subset of the rolled dice, when combined with
|
||||
// already set-aside dice from this turn, produces a valid scoring set.
|
||||
export function hasScoring(dice, setAsideDice = []) {
|
||||
const n = dice.length;
|
||||
function subsets(n) {
|
||||
const out = [];
|
||||
for (let mask = 1; mask < (1 << n); mask++) {
|
||||
const subset = [];
|
||||
for (let i = 0; i < n; i++) if (mask & (1 << i)) subset.push(dice[i]);
|
||||
if (scoreSelection([...setAsideDice, ...subset]).valid) return true;
|
||||
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 ────────────────────────────────────────────────────────────────────
|
||||
export function createInitialState({ playerCount = 4, names = [], skills = {}, seed } = {}) {
|
||||
const rng = mulberry32((seed ?? (Date.now() & 0x7fffffff)) | 0);
|
||||
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({
|
||||
|
|
@ -121,115 +171,186 @@ export function createInitialState({ playerCount = 4, names = [], skills = {}, s
|
|||
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
|
||||
winner: null,
|
||||
winners: [],
|
||||
winner: null,
|
||||
finalRound: false,
|
||||
finalFrom: null,
|
||||
_rng: rng,
|
||||
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, priorKept: 0, setAsideDice: [], hotDice: false };
|
||||
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) {
|
||||
const rngState = s._rng; // functions don't clone; lookahead must not roll dice
|
||||
const copy = JSON.parse(JSON.stringify({ ...s, _rng: undefined }));
|
||||
copy._rng = rngState;
|
||||
return copy;
|
||||
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);
|
||||
}
|
||||
|
||||
// Roll the available dice into turn.rolled. Sets phase to awaitPick, or farkled
|
||||
// when no subset of the rolled dice (combined with already set-aside dice) scores.
|
||||
export function rollDice(state) {
|
||||
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;
|
||||
const rng = state._rng;
|
||||
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, t.setAsideDice) ? 'awaitPick' : 'farkled';
|
||||
state.phase = hasScoring(out, state.rules) ? 'awaitPick' : 'farkled';
|
||||
log(state, { kind: 'roll', dice: out.slice(), farkle: state.phase === 'farkled' });
|
||||
return state;
|
||||
}
|
||||
|
||||
// Set aside the dice at the given indices (into turn.rolled). The turn score is
|
||||
// always the combined value of ALL set-aside dice this cycle (not a running sum),
|
||||
// so extending the set can unlock higher N-of-a-kind bonuses. Triggers hot dice
|
||||
// when all available dice have been used. Returns true on a valid selection.
|
||||
export function applySetAside(state, indices) {
|
||||
// Take the piggyback offer (before the first roll of the turn).
|
||||
export function takePiggyback(state) {
|
||||
const o = state.piggyOffer;
|
||||
const t = state.turn;
|
||||
const values = indices.map((i) => t.rolled[i]);
|
||||
const combined = [...t.setAsideDice, ...values];
|
||||
const res = scoreSelection(combined);
|
||||
if (!res.valid) return false;
|
||||
|
||||
t.setAsideDice.push(...values);
|
||||
t.available -= values.length;
|
||||
t.rolled = [];
|
||||
|
||||
if (t.available === 0) {
|
||||
// Hot dice — carry this cycle's score into priorKept, then reset for new cycle.
|
||||
t.priorKept += res.points;
|
||||
t.kept = t.priorKept;
|
||||
t.available = DICE;
|
||||
t.setAsideDice = [];
|
||||
t.hotDice = true;
|
||||
} else {
|
||||
t.kept = t.priorKept + res.points;
|
||||
}
|
||||
|
||||
state.phase = 'awaitDecision';
|
||||
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;
|
||||
}
|
||||
|
||||
// Bank the turn total (subject to the on-board minimum) and pass play.
|
||||
// Returns { bankable, scoreBefore, scoreAfter } so the caller can
|
||||
// handle score updates (e.g. for animations). Does NOT mutate state.score.
|
||||
export function bank(state) {
|
||||
const p = state.players[state.current];
|
||||
// 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 bankable = (p.onBoard || t.kept >= ON_BOARD_MIN) ? t.kept : 0;
|
||||
const scoreBefore = p.score;
|
||||
const scoreAfter = scoreBefore + bankable;
|
||||
if (bankable > 0) p.onBoard = true;
|
||||
advanceTurn(state);
|
||||
return { bankable, scoreBefore, scoreAfter };
|
||||
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 };
|
||||
}
|
||||
|
||||
// Forfeit the turn total and pass play.
|
||||
// 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) {
|
||||
advanceTurn(state);
|
||||
return 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 advanceTurn(state) {
|
||||
function endTurn(state, offer) {
|
||||
const N = state.players.length;
|
||||
const p = state.players[state.current];
|
||||
const p = currentPlayer(state);
|
||||
p.stats.turns++;
|
||||
p.stats.history.push(p.score);
|
||||
|
||||
if (!state.finalRound && p.score >= WIN_TARGET) {
|
||||
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) {
|
||||
|
|
@ -241,28 +362,30 @@ function computeWinners(state) {
|
|||
export function isGameOver(state) { return state.phase === 'gameover'; }
|
||||
export function getWinners(state) { return state.winners; }
|
||||
|
||||
// ── display helper ───────────────────────────────────────────────────────────
|
||||
// Returns an array of { label, points } describing the scoring groups in `dice`.
|
||||
export function breakdownScoring(dice) {
|
||||
if (!dice || dice.length === 0) return [];
|
||||
const total = dice.length;
|
||||
const counts = countsOf(dice);
|
||||
if (total === 6) {
|
||||
if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] === 1)) return [{ label: 'Straight 1–6', points: 1500 }];
|
||||
if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] % 2 === 0)) return [{ label: 'Three Pairs', points: 1500 }];
|
||||
}
|
||||
const K = ['', '', '', 'Three', 'Four', 'Five', 'Six'];
|
||||
const groups = [];
|
||||
for (let v = 1; v <= 6; v++) {
|
||||
const n = counts[v];
|
||||
if (n === 0) continue;
|
||||
if (n >= 3) {
|
||||
groups.push({ label: `${K[n]} ${v}s`, points: bestGroupValue(v, n) });
|
||||
} else if (v === 1) {
|
||||
groups.push({ label: n === 1 ? 'Single 1' : 'Two 1s', points: n * 100 });
|
||||
} else if (v === 5) {
|
||||
groups.push({ label: n === 1 ? 'Single 5' : 'Two 5s', points: n * 50 });
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
// 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 '';
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,185 @@
|
|||
// FarkelPad.js — the clipboard score sheet. One ruled row per turn, one column
|
||||
// per player. Each banked turn is pencilled as a new running total (with the
|
||||
// turn's points beside it) and the previous total gets struck through; a
|
||||
// Farkle is a red "F". The sheet scrolls once the game outgrows the paper.
|
||||
|
||||
import { playSoundEx, SFX } from '../../ui/Sounds.js';
|
||||
import {
|
||||
PAD_HEAD, PAD_MARGIN, PAD_ROW_H, PAD_ROWS, PAD_GRID, padColW, padColX, padRowY,
|
||||
} from './FarkelLayout.js';
|
||||
import { INK, INK_HEX, HAND_FONT, PRINT_FONT } from './FarkelArt.js';
|
||||
import { fmtPts } from './FarkelLogic.js';
|
||||
|
||||
const RED = '#b3261e';
|
||||
|
||||
export class FarkelPad {
|
||||
constructor(scene, { players, depth, origin }) {
|
||||
this.scene = scene;
|
||||
this.n = players.length;
|
||||
this.depth = depth;
|
||||
this.origin = origin;
|
||||
this.names = players.map((p) => p.name);
|
||||
this.cells = [];
|
||||
this.preview = null;
|
||||
this.active = null;
|
||||
}
|
||||
|
||||
build() {
|
||||
const s = this.scene;
|
||||
s.add.image(this.origin.x, this.origin.y, this.origin.key).setOrigin(0).setDepth(this.depth);
|
||||
this.hl = s.add.graphics().setDepth(this.depth + 1);
|
||||
this.head = [];
|
||||
for (let p = 0; p < this.n; p++) {
|
||||
const x = padColX(p, this.n), w = padColW(this.n);
|
||||
const max = Math.max(4, Math.floor(w / 15));
|
||||
const nm = this.names[p].length > max ? `${this.names[p].slice(0, max - 1)}…` : this.names[p];
|
||||
const name = s.add.text(x + w / 2, PAD_HEAD.y + PAD_HEAD.h / 2 - 2, nm, {
|
||||
fontFamily: HAND_FONT, fontSize: this.n > 3 ? '24px' : '28px', color: INK[p],
|
||||
}).setOrigin(0.5).setDepth(this.depth + 3);
|
||||
const check = s.add.text(x + w - 12, PAD_HEAD.y + 14, '✓', {
|
||||
fontFamily: HAND_FONT, fontSize: '22px', color: '#1d6a3c',
|
||||
}).setOrigin(0.5).setDepth(this.depth + 3).setVisible(false);
|
||||
const hat = s.add.image(x + 16, PAD_HEAD.y + 16, 'farkel-hat').setScale(0.6).setDepth(this.depth + 3).setVisible(false).setAngle(-12);
|
||||
this.head.push({ name, check, hat });
|
||||
}
|
||||
this.layer = s.add.container(0, 0).setDepth(this.depth + 2);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Highlighter band down the active player's column.
|
||||
setActive(seat) {
|
||||
this.active = seat;
|
||||
const g = this.hl;
|
||||
g.clear();
|
||||
if (seat === null || seat === undefined) return;
|
||||
const x = padColX(seat, this.n), w = padColW(this.n);
|
||||
g.fillStyle(0xfff07a, 0.28).fillRect(x + 3, PAD_HEAD.y + 4, w - 6, PAD_HEAD.h + PAD_ROWS * PAD_ROW_H - 8);
|
||||
g.lineStyle(2, INK_HEX[seat], 0.7).lineBetween(x + 14, PAD_HEAD.y + PAD_HEAD.h - 8, x + w - 14, PAD_HEAD.y + PAD_HEAD.h - 8);
|
||||
}
|
||||
|
||||
// Rebuild every visible row from the game state.
|
||||
syncFromState(gs, { leader = null } = {}) {
|
||||
this.gs = gs;
|
||||
this.layer.removeAll(true);
|
||||
this.cells = gs.players.map(() => ({}));
|
||||
const s = this.scene;
|
||||
const turnsDone = gs.players.map((p) => p.stats.history.length - 1);
|
||||
const rowsNeeded = Math.max(1, ...turnsDone.map((t, p) => t + (p === gs.current && gs.phase !== 'gameover' ? 1 : 0)));
|
||||
const start = Math.max(0, rowsNeeded - PAD_ROWS);
|
||||
this.start = start;
|
||||
|
||||
for (let r = 0; r < Math.min(PAD_ROWS, rowsNeeded); r++) {
|
||||
const turn = start + r + 1;
|
||||
const y = padRowY(r) + PAD_ROW_H / 2;
|
||||
this.layer.add(s.add.text(PAD_GRID.x + PAD_MARGIN / 2, y + 1, String(turn), {
|
||||
fontFamily: PRINT_FONT, fontSize: '13px', color: '#8a7a60',
|
||||
}).setOrigin(0.5));
|
||||
}
|
||||
if (start > 0) {
|
||||
this.layer.add(s.add.text(PAD_GRID.x + PAD_MARGIN / 2, PAD_HEAD.y + PAD_HEAD.h + 4, '⋮', {
|
||||
fontFamily: PRINT_FONT, fontSize: '12px', color: '#8a7a60',
|
||||
}).setOrigin(0.5, 0));
|
||||
}
|
||||
|
||||
gs.players.forEach((pl, p) => {
|
||||
const h = pl.stats.history;
|
||||
const x = padColX(p, this.n), w = padColW(this.n);
|
||||
// index of the latest turn that changed the total (that total stays unstruck)
|
||||
let latest = 0;
|
||||
for (let k = 1; k < h.length; k++) if (h[k] !== h[k - 1]) latest = k;
|
||||
for (let k = Math.max(1, start + 1); k < h.length; k++) {
|
||||
const r = k - 1 - start;
|
||||
if (r < 0 || r >= PAD_ROWS) continue;
|
||||
const y = padRowY(r) + PAD_ROW_H / 2;
|
||||
const delta = h[k] - h[k - 1];
|
||||
const objs = [];
|
||||
if (delta > 0) {
|
||||
const plus = s.add.text(x + 10, y + 3, `+${fmtPts(delta)}`, {
|
||||
fontFamily: HAND_FONT, fontSize: '16px', color: INK[p],
|
||||
}).setOrigin(0, 0.5).setAlpha(0.6);
|
||||
this.layer.add(plus);
|
||||
objs.push(plus);
|
||||
const tot = s.add.text(x + w - 10, y, fmtPts(h[k]), {
|
||||
fontFamily: HAND_FONT, fontSize: '27px', color: INK[p],
|
||||
}).setOrigin(1, 0.5);
|
||||
this.layer.add(tot);
|
||||
objs.push(tot);
|
||||
if (k !== latest) objs.push(this.strike(tot, p));
|
||||
} else {
|
||||
const f = s.add.text(x + 14, y, 'F', { fontFamily: HAND_FONT, fontSize: '26px', color: RED }).setOrigin(0, 0.5).setAngle(-6);
|
||||
this.layer.add(f);
|
||||
objs.push(f);
|
||||
if (delta < 0) {
|
||||
const pen = s.add.text(x + 36, y + 2, `−${fmtPts(-delta)}`, { fontFamily: HAND_FONT, fontSize: '17px', color: RED }).setOrigin(0, 0.5);
|
||||
const tot = s.add.text(x + w - 10, y, fmtPts(h[k]), { fontFamily: HAND_FONT, fontSize: '27px', color: INK[p] }).setOrigin(1, 0.5);
|
||||
this.layer.add([pen, tot]);
|
||||
objs.push(pen, tot);
|
||||
if (k !== latest) objs.push(this.strike(tot, p));
|
||||
}
|
||||
}
|
||||
this.cells[p][k] = objs;
|
||||
}
|
||||
// header marks
|
||||
this.head[p].check.setVisible(pl.onBoard);
|
||||
this.head[p].hat.setVisible(leader === p);
|
||||
});
|
||||
this.drawPreview();
|
||||
}
|
||||
|
||||
strike(textObj, p) {
|
||||
const g = this.scene.add.graphics();
|
||||
const b = textObj.getBounds();
|
||||
g.lineStyle(2, INK_HEX[p], 0.75);
|
||||
g.beginPath();
|
||||
g.moveTo(b.x - 3, b.centerY + 2);
|
||||
g.lineTo(b.right + 3, b.centerY - 1);
|
||||
g.strokePath();
|
||||
this.layer.add(g);
|
||||
return g;
|
||||
}
|
||||
|
||||
// Animate the newest cell of `seat` being pencilled in (call after syncFromState).
|
||||
async animateLatest(seat, { speed = 1 } = {}) {
|
||||
const h = this.gs.players[seat].stats.history;
|
||||
const objs = this.cells[seat][h.length - 1];
|
||||
if (!objs) return;
|
||||
const s = this.scene;
|
||||
playSoundEx(s, SFX.PENCIL_WRITE, { volume: 0.6 });
|
||||
objs.forEach((o) => { o.__a = o.alpha; o.setAlpha(0); });
|
||||
await new Promise((res) => {
|
||||
objs.forEach((o, i) => s.tweens.add({
|
||||
targets: o, alpha: o.__a ?? 1, duration: 260 * speed, delay: i * 90 * speed,
|
||||
onComplete: i === objs.length - 1 ? res : undefined,
|
||||
}));
|
||||
});
|
||||
// strike the previous total in the column, if it's visible
|
||||
let prev = null;
|
||||
for (let k = h.length - 2; k >= 1; k--) {
|
||||
if (h[k] !== h[k - 1]) { prev = this.cells[seat][k]; break; }
|
||||
}
|
||||
const line = prev?.find((o) => o.type === 'Graphics');
|
||||
if (line && h[h.length - 1] !== h[h.length - 2]) {
|
||||
line.setAlpha(0);
|
||||
await new Promise((res) => s.tweens.add({ targets: line, alpha: 1, duration: 200 * speed, onComplete: res }));
|
||||
}
|
||||
}
|
||||
|
||||
// Ghost pencil "+650" in the current row while a turn is running.
|
||||
setPreview(seat, points) {
|
||||
this.preview = points > 0 && seat !== null ? { seat, points } : null;
|
||||
this.drawPreview();
|
||||
}
|
||||
drawPreview() {
|
||||
this.previewText?.destroy();
|
||||
this.previewText = null;
|
||||
if (!this.preview || !this.gs) return;
|
||||
const { seat, points } = this.preview;
|
||||
const k = this.gs.players[seat].stats.history.length; // the row being played
|
||||
const r = k - 1 - (this.start ?? 0);
|
||||
if (r < 0 || r >= PAD_ROWS) return;
|
||||
const x = padColX(seat, this.n), w = padColW(this.n);
|
||||
this.previewText = this.scene.add.text(x + w / 2, padRowY(r) + PAD_ROW_H / 2, `+${fmtPts(points)}?`, {
|
||||
fontFamily: HAND_FONT, fontSize: '22px', color: '#7d7466',
|
||||
}).setOrigin(0.5).setAlpha(0.65).setDepth(this.depth + 3);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
// FarkelSolver.js — exact one-turn Farkle policy. Phaser-free, no state.
|
||||
//
|
||||
// A turn is a Markov decision process over (turn total t, dice left n). After a
|
||||
// scoring throw you choose which combo to keep (→ t + points, n − used, or six
|
||||
// fresh dice on hot dice), then bank or roll on. Because every keep strictly
|
||||
// raises t, values can be filled from the largest total downward in one sweep.
|
||||
//
|
||||
// pointsSolver(rules, minBank) maximise expected banked points; banking is
|
||||
// only allowed at t ≥ minBank (the entry rule)
|
||||
// reachSolver(rules, need) maximise P(turn total ≥ need) — the final
|
||||
// round chase, where anything less loses
|
||||
//
|
||||
// Totals are multiples of 50 up to T_MAX; beyond it the solver simply banks.
|
||||
|
||||
import { DICE } from './FarkelData.js';
|
||||
import { scoreSelection, countsOf } from './FarkelLogic.js';
|
||||
|
||||
export const STEP = 50;
|
||||
export const T_MAX = 20000;
|
||||
const TI = T_MAX / STEP;
|
||||
|
||||
const rulesKey = (r) => `${r.doubling ? 1 : 0}${r.twoTriplets ? 1 : 0}`;
|
||||
|
||||
// ── throw outcomes ───────────────────────────────────────────────────────────
|
||||
// For n dice: every multiset of faces with its probability and, per number of
|
||||
// dice used, the best points any valid keep of that size scores.
|
||||
function multisets(n) {
|
||||
const out = [];
|
||||
const rec = (start, left, acc) => {
|
||||
if (left === 0) { out.push(acc.slice()); return; }
|
||||
for (let v = start; v <= 6; v++) { acc.push(v); rec(v, left - 1, acc); acc.pop(); }
|
||||
};
|
||||
rec(1, n, []);
|
||||
return out;
|
||||
}
|
||||
const FACT = [1, 1, 2, 6, 24, 120, 720];
|
||||
function multisetProb(dice) {
|
||||
const c = countsOf(dice);
|
||||
let ways = FACT[dice.length];
|
||||
for (let v = 1; v <= 6; v++) ways /= FACT[c[v]];
|
||||
return ways / 6 ** dice.length;
|
||||
}
|
||||
// All sub-multisets of a multiset (as count vectors → dice arrays).
|
||||
function subMultisets(dice) {
|
||||
const c = countsOf(dice);
|
||||
const out = [];
|
||||
const rec = (v, acc) => {
|
||||
if (v > 6) { if (acc.length) out.push(acc.slice()); return; }
|
||||
for (let k = 0; k <= c[v]; k++) {
|
||||
for (let i = 0; i < k; i++) acc.push(v);
|
||||
rec(v + 1, acc);
|
||||
for (let i = 0; i < k; i++) acc.pop();
|
||||
}
|
||||
};
|
||||
rec(1, []);
|
||||
return out;
|
||||
}
|
||||
|
||||
const OUTCOME_CACHE = new Map();
|
||||
export function outcomes(rules) {
|
||||
const key = rulesKey(rules);
|
||||
if (OUTCOME_CACHE.has(key)) return OUTCOME_CACHE.get(key);
|
||||
const byN = [null];
|
||||
for (let n = 1; n <= DICE; n++) {
|
||||
const list = [];
|
||||
let pFarkle = 0;
|
||||
for (const ms of multisets(n)) {
|
||||
const p = multisetProb(ms);
|
||||
const best = new Map(); // used → points
|
||||
for (const sub of subMultisets(ms)) {
|
||||
const r = scoreSelection(sub, rules);
|
||||
if (!r.valid) continue;
|
||||
if ((best.get(sub.length) ?? -1) < r.points) best.set(sub.length, r.points);
|
||||
}
|
||||
if (!best.size) { pFarkle += p; continue; }
|
||||
const opts = [...best].map(([used, pts]) => ({ used, pts, ti: pts / STEP, next: n - used || DICE }));
|
||||
list.push({ p, opts });
|
||||
}
|
||||
byN.push({ list, pFarkle });
|
||||
}
|
||||
OUTCOME_CACHE.set(key, byN);
|
||||
return byN;
|
||||
}
|
||||
|
||||
// ── generic sweep ────────────────────────────────────────────────────────────
|
||||
// bankV(ti) → value of banking at total ti*STEP (−Infinity when not allowed).
|
||||
// stopAt(ti) → true if the state is terminal (value = bankV, no rolling).
|
||||
function sweep(rules, bankV, stopAt) {
|
||||
const outs = outcomes(rules);
|
||||
const R = Array.from({ length: DICE + 1 }, () => new Float64Array(TI + 1));
|
||||
const V = Array.from({ length: DICE + 1 }, () => new Float64Array(TI + 1));
|
||||
const val = (ti, n) => (ti > TI ? Math.max(0, bankV(ti)) : V[n][ti]);
|
||||
for (let ti = TI; ti >= 0; ti--) {
|
||||
for (let n = 1; n <= DICE; n++) {
|
||||
const b = bankV(ti);
|
||||
if (ti === TI || stopAt(ti)) { R[n][ti] = Math.max(0, b); V[n][ti] = Math.max(0, b); continue; }
|
||||
let r = 0;
|
||||
for (const o of outs[n].list) {
|
||||
let m = 0;
|
||||
for (const op of o.opts) { const x = val(ti + op.ti, op.next); if (x > m) m = x; }
|
||||
r += o.p * m;
|
||||
}
|
||||
R[n][ti] = r;
|
||||
V[n][ti] = Math.max(r, b);
|
||||
}
|
||||
}
|
||||
return { R, V };
|
||||
}
|
||||
|
||||
function wrap(rules, tables, bankV, kind, param) {
|
||||
const ti = (t) => Math.min(TI + 1, Math.round(t / STEP));
|
||||
return {
|
||||
kind, param,
|
||||
// value of rolling n dice holding total t
|
||||
rollValue(t, n) { const i = ti(t); return i > TI ? Math.max(0, bankV(i)) : tables.R[n][i]; },
|
||||
// value of banking at t (−Infinity when not allowed)
|
||||
bankValue(t) { return bankV(ti(t)); },
|
||||
// best of the two
|
||||
value(t, n) { const i = ti(t); return i > TI ? Math.max(0, bankV(i)) : tables.V[n][i]; },
|
||||
shouldBank(t, n) {
|
||||
const b = bankV(ti(t));
|
||||
return b > -Infinity && b >= this.rollValue(t, n);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const SOLVER_CACHE = new Map();
|
||||
function cached(key, make) {
|
||||
if (SOLVER_CACHE.has(key)) {
|
||||
const v = SOLVER_CACHE.get(key);
|
||||
SOLVER_CACHE.delete(key); SOLVER_CACHE.set(key, v); // LRU touch
|
||||
return v;
|
||||
}
|
||||
const v = make();
|
||||
SOLVER_CACHE.set(key, v);
|
||||
if (SOLVER_CACHE.size > 24) SOLVER_CACHE.delete(SOLVER_CACHE.keys().next().value);
|
||||
return v;
|
||||
}
|
||||
|
||||
export function pointsSolver(rules, minBank = 0) {
|
||||
const mb = Math.max(0, Math.ceil(minBank / STEP));
|
||||
return cached(`p:${rulesKey(rules)}:${mb}`, () => {
|
||||
const bankV = (ti) => (ti >= Math.max(1, mb) ? ti * STEP : -Infinity);
|
||||
const tables = sweep(rules, bankV, () => false);
|
||||
return wrap(rules, tables, bankV, 'points', mb * STEP);
|
||||
});
|
||||
}
|
||||
|
||||
export function reachSolver(rules, need) {
|
||||
const nd = Math.max(1, Math.ceil(need / STEP));
|
||||
return cached(`r:${rulesKey(rules)}:${nd}`, () => {
|
||||
const bankV = (ti) => (ti >= nd ? 1 : -Infinity);
|
||||
const tables = sweep(rules, bankV, (ti) => ti >= nd);
|
||||
return wrap(rules, tables, bankV, 'reach', nd * STEP);
|
||||
});
|
||||
}
|
||||
|
||||
// ── policy over a concrete throw ─────────────────────────────────────────────
|
||||
const SUBS = [];
|
||||
for (let n = 0; n <= DICE; n++) {
|
||||
const list = [];
|
||||
for (let mask = 1; mask < (1 << n); mask++) {
|
||||
const idx = [];
|
||||
for (let i = 0; i < n; i++) if (mask & (1 << i)) idx.push(i);
|
||||
list.push(idx);
|
||||
}
|
||||
SUBS.push(list);
|
||||
}
|
||||
|
||||
// Every distinct scoring keep of a throw, valued by `solver` from total t.
|
||||
export function rankKeeps(rolled, t, rules, solver) {
|
||||
const seen = new Map();
|
||||
for (const idx of SUBS[rolled.length]) {
|
||||
const dice = idx.map((i) => rolled[i]);
|
||||
const r = scoreSelection(dice, rules);
|
||||
if (!r.valid) continue;
|
||||
const key = dice.slice().sort().join('');
|
||||
if (seen.has(key)) continue;
|
||||
const t2 = t + r.points;
|
||||
const left = rolled.length - idx.length || DICE;
|
||||
const roll = solver.rollValue(t2, left);
|
||||
const bankV = solver.bankValue(t2);
|
||||
seen.set(key, { indices: idx, points: r.points, total: t2, left, roll, bank: bankV, value: Math.max(roll, bankV) });
|
||||
}
|
||||
return [...seen.values()].sort((a, b) => b.value - a.value || b.points - a.points);
|
||||
}
|
||||
|
||||
export function bestKeep(rolled, t, rules, solver) {
|
||||
return rankKeeps(rolled, t, rules, solver)[0] ?? null;
|
||||
}
|
||||
|
||||
// Chance a throw of n dice scores nothing (from the enumeration).
|
||||
export function farkleChance(rules, n) { return outcomes(rules)[n].pFarkle; }
|
||||
|
|
@ -0,0 +1,389 @@
|
|||
// FarkelTray.js — the felt dice tray, the "set aside" rail and the leather cup,
|
||||
// with six real 3D dice (src/ui/dice/Dice3D.js).
|
||||
//
|
||||
// Fairness: the engine rolls first (FarkelLogic.rollDice); throwDice() then
|
||||
// plays a planned boxed throw whose dice are relabelled to land on exactly
|
||||
// those faces. The animation never decides a result.
|
||||
//
|
||||
// The six Die3D objects are a pool. Dice kept this cycle sit on the rail in
|
||||
// throw order (grouped); every other die is "in the tray" — idle, or the
|
||||
// current throw, tidied into a centred row where rolled[i] is column i.
|
||||
|
||||
import { Die3D, planTrayThrow, poseFromPlan, restingQ, qslerp } from '../../ui/dice/Dice3D.js';
|
||||
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
|
||||
import { DICE } from './FarkelData.js';
|
||||
import {
|
||||
TRAY, RAIL, TRAY_WORLD, DIE_SIZE, REST_V, RAIL_V, CUP, columnU, railSlots, ground, toWorld,
|
||||
} from './FarkelLayout.js';
|
||||
import { PAD_PX } from './FarkelArt.js';
|
||||
|
||||
const BODY = [246, 240, 224];
|
||||
const PIP = 0x1b1410;
|
||||
const YAW = [0.1, -0.08, 0.05, -0.13, 0.09, -0.04];
|
||||
const lerp = (a, b, t) => a + (b - a) * t;
|
||||
const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
|
||||
const LIFT = 16;
|
||||
|
||||
export class FarkelTray {
|
||||
constructor(scene, depth, { onDieClick, onDieHover } = {}) {
|
||||
this.scene = scene;
|
||||
this.depth = depth;
|
||||
this.onDieClick = onDieClick;
|
||||
this.onDieHover = onDieHover;
|
||||
this.poses = [];
|
||||
this.enabled = false;
|
||||
this.railDice = []; // die indices on the rail, in order
|
||||
this.rollMap = []; // rolled index → die index
|
||||
this.decor = { selected: new Set(), hints: null, coach: null, hover: -1, dimAll: false };
|
||||
}
|
||||
|
||||
build() {
|
||||
const s = this.scene;
|
||||
s.add.image(TRAY.x - PAD_PX, TRAY.y - PAD_PX, 'farkel-tray').setOrigin(0).setDepth(this.depth);
|
||||
s.add.image(RAIL.x - PAD_PX, RAIL.y - PAD_PX, 'farkel-rail').setOrigin(0).setDepth(this.depth + 1);
|
||||
this.dice = Array.from({ length: DICE }, () => new Die3D(s, this.depth + 3, {
|
||||
size: DIE_SIZE, body: BODY, pip: PIP, sin: 0.62, cos: 0.785, ground, glowColor: 0xf5d020,
|
||||
}));
|
||||
this.zones = this.dice.map((_, d) => {
|
||||
const z = s.add.zone(0, 0, 92, 92).setDepth(this.depth + 8);
|
||||
z.on('pointerdown', (ptr) => {
|
||||
const i = this.rollMap.indexOf(d);
|
||||
if (this.enabled && i >= 0) this.onDieClick?.(i, ptr?.event);
|
||||
});
|
||||
z.on('pointerover', () => { const i = this.rollMap.indexOf(d); if (this.enabled && i >= 0) this.onDieHover?.(i, true); });
|
||||
z.on('pointerout', () => { const i = this.rollMap.indexOf(d); if (i >= 0) this.onDieHover?.(i, false); });
|
||||
return z;
|
||||
});
|
||||
for (let d = 0; d < DICE; d++) {
|
||||
this.poses[d] = { u: columnU(d, DICE), v: REST_V, h: 0, q: restingQ(d + 1, YAW[d]), face: d + 1, spot: 'tray', alpha: 1 };
|
||||
this.apply(d);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
// ── pose helpers ───────────────────────────────────────────────────────────
|
||||
apply(d) {
|
||||
const p = this.poses[d];
|
||||
const die = this.dice[d];
|
||||
die.g.setAlpha(p.alpha);
|
||||
die.shadow.setAlpha(p.alpha);
|
||||
die.set(p.u, p.v, p.h, p.q);
|
||||
}
|
||||
trayDice() { return this.dice.map((_, d) => d).filter((d) => !this.railDice.includes(d)); }
|
||||
|
||||
// Put everything at rest instantly from a turn: this cycle's kept groups on
|
||||
// the rail, the rest in the tray (showing `turn.rolled` when there is a throw).
|
||||
layoutState(turn) {
|
||||
const groups = (turn?.groups ?? []).filter((g) => g.cycle === turn.cycle);
|
||||
const faces = groups.flatMap((g) => g.dice);
|
||||
const { us } = railSlots(groups.map((g) => g.dice.length));
|
||||
this.railDice = faces.map((_, k) => k);
|
||||
faces.forEach((f, k) => {
|
||||
Object.assign(this.poses[k], { u: us[k], v: RAIL_V, h: 0, q: restingQ(f, YAW[k]), face: f, spot: 'rail', alpha: 1 });
|
||||
this.dice[k].setVisible(true);
|
||||
this.apply(k);
|
||||
});
|
||||
const tray = this.trayDice();
|
||||
const rolled = turn?.rolled ?? [];
|
||||
this.rollMap = rolled.length ? tray.slice(0, rolled.length) : [];
|
||||
tray.forEach((d, i) => {
|
||||
if (i >= rolled.length) {
|
||||
// not thrown yet: the dice are in the cup
|
||||
Object.assign(this.poses[d], { u: columnU(i, tray.length), v: REST_V, h: 0, spot: 'cup', alpha: 0 });
|
||||
this.dice[d].glow = 0;
|
||||
this.dice[d].setVisible(false);
|
||||
return;
|
||||
}
|
||||
const face = rolled[i];
|
||||
Object.assign(this.poses[d], { u: columnU(i, rolled.length), v: REST_V, h: 0, q: restingQ(face, YAW[d]), face, spot: 'tray', alpha: 1 });
|
||||
this.dice[d].setVisible(true);
|
||||
this.apply(d);
|
||||
});
|
||||
this.refreshDecor();
|
||||
this.syncZones();
|
||||
}
|
||||
|
||||
tweenDie(d, to, dur, { arc = 0, alphaTo = null, q = null } = {}) {
|
||||
const p = this.poses[d];
|
||||
const from = { u: p.u, v: p.v, h: p.h, q: p.q, alpha: p.alpha };
|
||||
const qTo = q ?? p.q;
|
||||
if (dur <= 0) {
|
||||
Object.assign(p, { u: to.u, v: to.v, h: to.h ?? 0, q: qTo });
|
||||
if (alphaTo !== null) p.alpha = alphaTo;
|
||||
this.apply(d);
|
||||
return Promise.resolve();
|
||||
}
|
||||
const prox = { t: 0 };
|
||||
return new Promise((resolve) => {
|
||||
this.scene.tweens.add({
|
||||
targets: prox, t: 1, duration: dur, ease: 'Linear',
|
||||
onUpdate: () => {
|
||||
const t = easeInOut(prox.t);
|
||||
p.u = lerp(from.u, to.u, t);
|
||||
p.v = lerp(from.v, to.v, t);
|
||||
p.h = lerp(from.h, to.h ?? 0, t) + arc * Math.sin(Math.PI * prox.t);
|
||||
p.q = qslerp(from.q, qTo, t);
|
||||
if (alphaTo !== null) p.alpha = lerp(from.alpha, alphaTo, t);
|
||||
this.apply(d);
|
||||
},
|
||||
onComplete: () => resolve(),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Gather dice into the cup (or towards a seat) and hide them.
|
||||
async scoop(dice, target, dur = 260) {
|
||||
if (!dice.length) return;
|
||||
const w = toWorld(target.x, target.y);
|
||||
await Promise.all(dice.map((d, k) => new Promise((res) => {
|
||||
this.scene.time.delayedCall(k * 30, async () => {
|
||||
this.poses[d].spot = 'cup';
|
||||
this.dice[d].glow = 0;
|
||||
await this.tweenDie(d, { u: w.u, v: w.v + 30, h: 90 }, dur, { arc: 30, alphaTo: 0 });
|
||||
this.dice[d].setVisible(false);
|
||||
res();
|
||||
});
|
||||
})));
|
||||
}
|
||||
async scoopTray(target, dur) {
|
||||
this.rollMap = [];
|
||||
await this.scoop(this.trayDice(), target, dur);
|
||||
}
|
||||
async scoopAll(target, dur) {
|
||||
this.rollMap = [];
|
||||
const all = this.dice.map((_, d) => d).filter((d) => this.dice[d].visible);
|
||||
this.railDice = [];
|
||||
await this.scoop(all, target, dur);
|
||||
}
|
||||
|
||||
// Throw the tray dice so they land on `faces`, then tidy them into a row.
|
||||
async throwDice(faces, origin, { speed = 1, fast = false } = {}) {
|
||||
const s = this.scene;
|
||||
const tray = this.trayDice();
|
||||
const dice = tray.slice(0, faces.length);
|
||||
this.rollMap = [];
|
||||
this.decor.selected = new Set();
|
||||
if (fast) {
|
||||
dice.forEach((d, i) => {
|
||||
Object.assign(this.poses[d], { u: columnU(i, faces.length), v: REST_V, h: 0, q: restingQ(faces[i], YAW[d]), face: faces[i], spot: 'tray', alpha: 1 });
|
||||
this.dice[d].setVisible(true);
|
||||
this.apply(d);
|
||||
});
|
||||
playSoundEx(s, SFX.DICE_ROLL, { volume: 0.5 });
|
||||
this.rollMap = dice.slice();
|
||||
this.refreshDecor();
|
||||
this.syncZones();
|
||||
return;
|
||||
}
|
||||
const plan = planTrayThrow(TRAY_WORLD, origin, faces, Math.random, DIE_SIZE, {
|
||||
spread: faces.length > 4 ? 1.9 : 1.5, sep: 1.4, aim: { u0: 0.22, u1: 0.78, v0: 0.28, v1: 0.72 },
|
||||
});
|
||||
playSound(s, SFX.DICE_ROLL);
|
||||
dice.forEach((d, i) => {
|
||||
Object.assign(this.poses[d], { face: faces[i], spot: 'tray', alpha: 1 });
|
||||
this.dice[d].glow = 0;
|
||||
this.dice[d].setVisible(true);
|
||||
});
|
||||
const step = (t) => dice.forEach((d, i) => {
|
||||
const p = poseFromPlan(plan, i, t);
|
||||
Object.assign(this.poses[d], { u: p.u, v: p.v, h: p.h, q: p.q });
|
||||
this.apply(d);
|
||||
});
|
||||
step(0);
|
||||
const prox = { t: 0 };
|
||||
let clacks = 0;
|
||||
await new Promise((resolve) => {
|
||||
s.tweens.add({
|
||||
targets: prox, t: 1, duration: Math.max(650, plan.duration * 1000) * speed, ease: 'Linear',
|
||||
onUpdate: () => {
|
||||
step(prox.t);
|
||||
// a couple of wooden clacks as dice hit the felt
|
||||
if (clacks < 3 && prox.t > 0.3 + clacks * 0.18) {
|
||||
clacks++;
|
||||
playSoundEx(s, SFX.PIECE_CLICK, { volume: 0.22, rate: 1.1 + Math.random() * 0.5 });
|
||||
}
|
||||
},
|
||||
onComplete: () => { step(1); resolve(); },
|
||||
});
|
||||
});
|
||||
await new Promise((resolve) => {
|
||||
const sq = { k: 1.1 };
|
||||
s.tweens.add({
|
||||
targets: sq, k: 1, duration: 150, ease: 'Back.Out',
|
||||
onUpdate: () => dice.forEach((d) => { this.dice[d].scale = sq.k; this.dice[d].draw(); }),
|
||||
onComplete: () => { dice.forEach((d) => { this.dice[d].scale = 1; this.dice[d].draw(); }); resolve(); },
|
||||
});
|
||||
});
|
||||
await this.wait(120 * speed);
|
||||
await Promise.all(dice.map((d, i) => this.tweenDie(d, { u: columnU(i, faces.length), v: REST_V, h: 0 }, 300 * speed, {
|
||||
q: restingQ(faces[i], YAW[d]),
|
||||
})));
|
||||
this.rollMap = dice.slice();
|
||||
this.refreshDecor();
|
||||
this.syncZones();
|
||||
}
|
||||
|
||||
// Slide the kept dice (indices into the current throw) onto the rail.
|
||||
// `sizes` = dice per group this cycle INCLUDING the new group.
|
||||
async keepToRail(indices, sizes, dur = 300) {
|
||||
const moving = indices.map((i) => this.rollMap[i]).filter((d) => d !== undefined);
|
||||
const { us } = railSlots(sizes);
|
||||
const base = this.railDice.length;
|
||||
this.railDice.push(...moving);
|
||||
this.rollMap = [];
|
||||
this.decor.selected = new Set();
|
||||
this.decor.hints = null;
|
||||
this.decor.coach = null;
|
||||
const jobs = moving.map((d, k) => new Promise((res) => {
|
||||
this.scene.time.delayedCall(dur > 0 ? k * 60 : 0, async () => {
|
||||
this.poses[d].spot = 'rail';
|
||||
this.dice[d].glow = 0;
|
||||
this.poses[d].alpha = 1;
|
||||
await this.tweenDie(d, { u: us[base + k], v: RAIL_V, h: 0 }, dur, { arc: dur > 0 ? 70 : 0, q: restingQ(this.poses[d].face, YAW[d]) });
|
||||
if (dur > 0) playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.32, rate: 1.15 + Math.random() * 0.3 });
|
||||
res();
|
||||
});
|
||||
}));
|
||||
await Promise.all(jobs);
|
||||
this.refreshDecor();
|
||||
this.syncZones();
|
||||
}
|
||||
|
||||
// Little celebratory hops (hot dice, a straight…).
|
||||
async hop(dice, height = 46, dur = 420) {
|
||||
await Promise.all(dice.map((d, k) => new Promise((res) => {
|
||||
this.scene.time.delayedCall(k * 60, async () => {
|
||||
const p = this.poses[d];
|
||||
await this.tweenDie(d, { u: p.u, v: p.v, h: 0 }, dur, { arc: height });
|
||||
res();
|
||||
});
|
||||
})));
|
||||
}
|
||||
railHop(height, dur) { return this.hop(this.railDice.slice(), height, dur); }
|
||||
rollHop(height, dur) { return this.hop(this.rollMap.slice(), height, dur); }
|
||||
|
||||
wait(ms) { return new Promise((r) => this.scene.time.delayedCall(Math.max(0, ms), r)); }
|
||||
|
||||
// ── decoration: selection lift, hint glow, coach glow, hover ───────────────
|
||||
setDecor(patch) { Object.assign(this.decor, patch); this.refreshDecor(); }
|
||||
clearDecor() { this.decor = { selected: new Set(), hints: null, coach: null, hover: -1, dimAll: false }; this.refreshDecor(); }
|
||||
|
||||
refreshDecor() {
|
||||
const { selected, hints, coach, hover, dimAll } = this.decor;
|
||||
for (let d = 0; d < DICE; d++) {
|
||||
const die = this.dice[d];
|
||||
const p = this.poses[d];
|
||||
if (p.spot === 'cup') continue;
|
||||
const i = this.rollMap.indexOf(d);
|
||||
let glow = 0, color = 0xf5d020, alpha = 1, lift = 0;
|
||||
if (i >= 0) {
|
||||
if (selected.has(i)) { glow = 1; color = 0xf5d020; lift = LIFT; }
|
||||
else if (coach && coach.includes(i)) { glow = 0.85; color = 0x7fd6ff; }
|
||||
else if (hover === i) { glow = 0.7; color = 0xffffff; }
|
||||
else if (hints) { glow = hints[i] ? 0.32 : 0; color = 0xfff3c0; alpha = hints[i] ? 1 : 0.62; }
|
||||
}
|
||||
if (dimAll && p.spot === 'tray') alpha = 0.45;
|
||||
die.glow = glow;
|
||||
die.opts.glowColor = color;
|
||||
if (p.alpha !== alpha) p.alpha = alpha;
|
||||
if (p.spot === 'tray' && p.h !== lift && !this.lifting?.has(d)) this.liftTo(d, lift);
|
||||
else this.apply(d);
|
||||
}
|
||||
}
|
||||
|
||||
liftTo(d, h) {
|
||||
this.lifting ??= new Set();
|
||||
this.lifting.add(d);
|
||||
const p = this.poses[d];
|
||||
this.tweenDie(d, { u: p.u, v: p.v, h }, 110).then(() => {
|
||||
this.lifting.delete(d);
|
||||
this.syncZones();
|
||||
});
|
||||
}
|
||||
|
||||
// ── input ──────────────────────────────────────────────────────────────────
|
||||
setEnabled(on) {
|
||||
this.enabled = !!on;
|
||||
this.zones.forEach((z) => (on ? z.setInteractive({ useHandCursor: true }) : z.disableInteractive()));
|
||||
if (!on && this.decor.hover >= 0) this.setDecor({ hover: -1 });
|
||||
}
|
||||
syncZones() {
|
||||
this.dice.forEach((die, d) => {
|
||||
const c = die.screenCenter();
|
||||
this.zones[d].setPosition(c.x, c.y);
|
||||
});
|
||||
}
|
||||
screenOfRoll(i) {
|
||||
const d = this.rollMap[i];
|
||||
return d === undefined ? null : this.dice[d].screenCenter();
|
||||
}
|
||||
}
|
||||
|
||||
// ── the leather cup ──────────────────────────────────────────────────────────
|
||||
export class FarkelCup {
|
||||
constructor(scene, depth, { onPress } = {}) {
|
||||
this.scene = scene;
|
||||
this.depth = depth;
|
||||
this.onPress = onPress;
|
||||
this.enabled = false;
|
||||
}
|
||||
|
||||
build() {
|
||||
const s = this.scene;
|
||||
this.glow = s.add.graphics().setDepth(this.depth - 1);
|
||||
this.glow.fillStyle(0xf5d020, 0.22).fillEllipse(CUP.x, CUP.y + CUP.h / 2 - 12, CUP.w * 1.25, 40);
|
||||
this.glow.lineStyle(3, 0xf5d020, 0.8).strokeEllipse(CUP.x, CUP.y + CUP.h / 2 - 12, CUP.w * 1.1, 32);
|
||||
this.glow.setAlpha(0);
|
||||
this.img = s.add.image(CUP.x, CUP.y + CUP.h / 2 - 4, 'farkel-cup').setOrigin(0.5, 1 - 18 / (CUP.h + 28)).setDepth(this.depth);
|
||||
this.home = { x: this.img.x, y: this.img.y };
|
||||
this.img.setInteractive({ useHandCursor: true });
|
||||
this.img.on('pointerdown', () => { if (this.enabled) this.onPress?.(); });
|
||||
this.img.on('pointerover', () => { if (this.enabled) this.img.setScale(1.04); });
|
||||
this.img.on('pointerout', () => this.img.setScale(1));
|
||||
this.pulse = s.tweens.add({ targets: this.glow, alpha: { from: 0.25, to: 0.95 }, duration: 750, yoyo: true, repeat: -1, paused: true });
|
||||
return this;
|
||||
}
|
||||
|
||||
setEnabled(on) {
|
||||
this.enabled = !!on;
|
||||
if (on) { if (this.pulse.isPaused()) this.pulse.resume(); }
|
||||
else { this.pulse.pause(); this.glow.setAlpha(0); this.img.setScale(1); }
|
||||
}
|
||||
|
||||
startShake() {
|
||||
const s = this.scene;
|
||||
this.stopShake();
|
||||
this.shakeT = 0;
|
||||
this.shakeTimer = s.time.addEvent({
|
||||
delay: 16, loop: true, callback: () => {
|
||||
this.shakeT += 16;
|
||||
const k = Math.min(1, this.shakeT / 400);
|
||||
this.img.rotation = Math.sin(this.shakeT / 38) * (0.12 + 0.1 * k);
|
||||
this.img.x = this.home.x + Math.sin(this.shakeT / 55) * 6 * k;
|
||||
this.img.y = this.home.y - 10 - Math.abs(Math.sin(this.shakeT / 45)) * 10 * k;
|
||||
},
|
||||
});
|
||||
this.rattle = s.time.addEvent({
|
||||
delay: 95, loop: true, callback: () => playSoundEx(s, SFX.PIECE_CLICK, { volume: 0.16 + Math.random() * 0.14, rate: 1.4 + Math.random() * 0.8 }),
|
||||
});
|
||||
}
|
||||
stopShake() {
|
||||
this.shakeTimer?.remove(); this.shakeTimer = null;
|
||||
this.rattle?.remove(); this.rattle = null;
|
||||
}
|
||||
shakeTime() { return this.shakeT ?? 0; }
|
||||
|
||||
// Tip the cup towards the tray, then set it back down.
|
||||
async pour() {
|
||||
this.stopShake();
|
||||
const s = this.scene;
|
||||
await new Promise((res) => s.tweens.add({
|
||||
targets: this.img, rotation: 0.5, x: this.home.x + 34, y: this.home.y - 52, duration: 140, ease: 'Quad.Out', onComplete: res,
|
||||
}));
|
||||
s.tweens.add({ targets: this.img, rotation: 0, x: this.home.x, y: this.home.y, duration: 380, delay: 160, ease: 'Back.Out' });
|
||||
}
|
||||
reset() {
|
||||
this.stopShake();
|
||||
this.img.setRotation(0).setPosition(this.home.x, this.home.y);
|
||||
}
|
||||
}
|
||||
|
|
@ -32,9 +32,11 @@ If there's NOTHING — no 1s, no 5s, no three-of-a-kinds, nothing — that's a *
|
|||
|
||||
### Step 2: Set Aside Your Scoring Dice
|
||||
|
||||
You MUST set aside at least one scoring die each roll. Click the dice you want to keep and they'll lock in. Check the scoring chart below — it tells you exactly what each combination is worth.
|
||||
You MUST set aside at least one scoring die each roll. Click the dice you want to keep — they pop up with a gold glow — and the chalkboard on the right lights up the combo you've made. Press **Best** if you just want the biggest score from the throw.
|
||||
|
||||
The dice you set aside are done for this turn. The ones you didn't pick? Those are still live. You can keep rolling them.
|
||||
The dice you set aside slide onto the **Set Aside** rail under the tray, grouped by throw, and they're done for this turn. The ones you didn't pick? Those are still live. You can keep rolling them.
|
||||
|
||||
**One throw at a time, my friend.** Every throw scores on its own. Dice you set aside earlier NEVER team up with dice from a later throw. Got three 2s last throw and a lone 2 this throw? That lone 2 is worth nothing — it's not four of a kind. A 1 and a 5 on the rail plus a 2-3-4-6 on the next throw? That's not a straight. That's a Farkle. Brutal. Fair. Mountain law.
|
||||
|
||||
### Step 3: Roll Again or Bank
|
||||
|
||||
|
|
@ -46,6 +48,17 @@ Now the real decision. The moment of truth. The top of the cliff.
|
|||
|
||||
More dice = more scoring combinations. Fewer dice = higher Farkle risk. When you're down to one or two dice, you're basically pointing your skis straight down a sheet of ice and hoping for the best. Thrilling? Yes. Recommended? Debatable.
|
||||
|
||||
Check the **thermometer** next to the cup — it shows the exact chance that your next throw scores nothing:
|
||||
|
||||
| Dice you'd roll | Farkle chance |
|
||||
|---|---|
|
||||
| 6 | 2% |
|
||||
| 5 | 8% |
|
||||
| 4 | 16% |
|
||||
| 3 | 28% |
|
||||
| 2 | 44% |
|
||||
| 1 | 67% |
|
||||
|
||||
### Hot Dice — The Mountain Calls!
|
||||
|
||||
Here's the best rule in the entire game: if you manage to set aside ALL SIX DICE in a single turn, you get **Hot Dice**. You pick up all six dice and roll again, keeping every point you've built up so far.
|
||||
|
|
@ -70,7 +83,7 @@ Hot Dice is like hitting a perfect powder stash, ripping through it top to botto
|
|||
| Straight (1-2-3-4-5-6) | 1,500 |
|
||||
| Three pairs | 1,500 |
|
||||
|
||||
Note: a straight and three pairs use all six dice at once — the game will recognize them automatically.
|
||||
Note: a straight and three pairs use all six dice from ONE throw — the game will recognize them automatically. Four of a kind plus a pair counts as three pairs (1,500).
|
||||
|
||||
## Gerome's Mountain Wisdom (Tips)
|
||||
|
||||
|
|
@ -86,15 +99,38 @@ Note: a straight and three pairs use all six dice at once — the game will reco
|
|||
|
||||
**6. Three 1s is the jackpot.** That's 1,000 points from three dice in one shot. It's like dropping off a cliff and landing in bottomless pow — it doesn't get better than that moment.
|
||||
|
||||
## House Rules
|
||||
|
||||
Every lodge has its own rules, and ours are in **Menu → House Rules**. Changing them starts a fresh game.
|
||||
|
||||
- **Play to** 5,000, 10,000 or 15,000.
|
||||
- **Get on the board** with 0, 350, 500 or 1,000 in one turn.
|
||||
- **Three-Farkle penalty** — Farkle three turns in a row and it costs you 1,000. Ouch.
|
||||
- **Two triplets = 2,500** — two three-of-a-kinds in one throw.
|
||||
- **Doubling kinds** — four of a kind is the triple ×2, five is ×4, six is ×8. Six 1s = 8,000. Gerome has seen it ONCE.
|
||||
- **Piggyback** — when the player before you banks, you can take over their leftover dice AND their turn total. Roll a score and it's all yours. Farkle and it's gone. Pure backcountry.
|
||||
|
||||
## Your Table at the Lodge
|
||||
|
||||
- **Shake the cup:** press and hold the cup (or hold Space), then let go to throw. Or just hit **Roll**.
|
||||
- **Score pad:** every banked turn gets pencilled in as your new total, the old one gets crossed out, and a Farkle is a big red **F**. The ✓ means that player is on the board; the red toque marks the leader.
|
||||
- **Hints:** dice that can score glow softly and the duds dim. Turn it off in the Menu if you like it raw.
|
||||
- **Smart pick:** clicking a die grabs its whole combo (all three 4s, the whole straight). Shift-click takes just that one die.
|
||||
- **Coach:** switch it on in the Menu and I'll glow the best keep in blue and tell you whether rolling on beats banking. Straight from the math. No ego.
|
||||
- **Turn Log:** press **Log** (or L) to see every throw, keep, bank and Farkle.
|
||||
- **Your game saves** at the start of every turn. Leave the lodge and you can pick it back up later.
|
||||
|
||||
**Keys:** Space shake & throw · 1–6 pick dice · R roll · B bank · A best keep · C clear · P piggyback · L log · Esc menu. During someone else's turn, click the tray (or tap Space) to hurry them along.
|
||||
|
||||
## When the Final Round Hits
|
||||
|
||||
The first player to cross 10,000 triggers the **final round** — everyone else gets one last turn to beat that score. No sudden death. Everyone gets their shot.
|
||||
|
||||
This is where Farkle turns into a chase scene. Trailing by 800 points with one turn left? That's your moment. Roll big. Bank nothing until you know you've got enough. This is Gerome's favorite part of the game, honestly. Pure mountain energy. All or nothing.
|
||||
This is where Farkle turns into a chase scene. Trailing by 800 points with one turn left? That's your moment. Roll big. Bank nothing until you know you've got enough — the red ribbon over the tray tells you exactly how much you need. This is Gerome's favorite part of the game, honestly. Pure mountain energy. All or nothing.
|
||||
|
||||
## A Note on the AI Opponents
|
||||
|
||||
The computer players are smart. They've read the odds. They know when to bank and when to push. I won't lie to you — they'll Farkle sometimes, and when they do, it's extremely satisfying. But they'll also rip off a 3,000-point turn right when you think you've got it locked up.
|
||||
The computer players range from first-day-on-skis (skill 1) to ski patrol (skill 5). The top ones have done the math on every single throw — which dice to keep, when to bank, and exactly how hard to chase in the final round. I won't lie to you — they'll Farkle sometimes, and when they do, it's extremely satisfying. But they'll also rip off a 3,000-point turn right when you think you've got it locked up.
|
||||
|
||||
Treat them like the locals at a powder day. Respectful. A little competitive. Always slightly better at reading the mountain than you'd like.
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,314 @@
|
|||
#!/usr/bin/env node
|
||||
// verifyFarkel.js — headless checks for Farkle:
|
||||
// • scoring table (standard + every house rule), parts/labels
|
||||
// • per-roll scoring: dice from different throws never combine (regressions)
|
||||
// • farkle odds by enumeration, hot dice, entry minimum, bank gating
|
||||
// • final round, three-Farkle penalty, piggyback, rankings, autosave JSON
|
||||
// • solver: odds, textbook keeps, monotone values, reach solver
|
||||
// • AI: never banks below entry or short of the final-round leader;
|
||||
// seeded self-play terminates; skill ladder 1 < 2 < 3 < 4 < 5
|
||||
// • screen layout: furniture on screen, no overlaps (when present)
|
||||
// Usage: node tools/verifyFarkel.js [--quick]
|
||||
|
||||
import * as L from '../src/games/farkel/FarkelLogic.js';
|
||||
import { DEFAULT_RULES, FARKLE_ODDS, normalizeRules, scoringReference } from '../src/games/farkel/FarkelData.js';
|
||||
import { pointsSolver, reachSolver, bestKeep, rankKeeps, farkleChance } from '../src/games/farkel/FarkelSolver.js';
|
||||
import { planDecision, wantsPiggyback, coachAdvice } from '../src/games/farkel/FarkelAI.js';
|
||||
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
|
||||
|
||||
const QUICK = process.argv.includes('--quick');
|
||||
let pass = 0, fail = 0;
|
||||
function ok(label, cond, detail = '') {
|
||||
if (cond) pass++;
|
||||
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
|
||||
}
|
||||
const section = (n) => console.log(`\n${n}`);
|
||||
const R = (o = {}) => normalizeRules(o);
|
||||
|
||||
// ── scoring ──────────────────────────────────────────────────────────────────
|
||||
section('Scoring');
|
||||
{
|
||||
const T = [
|
||||
[[1], 100], [[5], 50], [[1, 1], 200], [[5, 5], 100], [[1, 5], 150],
|
||||
[[1, 1, 1], 1000], [[2, 2, 2], 200], [[3, 3, 3], 300], [[4, 4, 4], 400], [[5, 5, 5], 500], [[6, 6, 6], 600],
|
||||
[[2, 2, 2, 2], 1000], [[3, 3, 3, 3, 3], 2000], [[4, 4, 4, 4, 4, 4], 3000],
|
||||
[[1, 1, 1, 1], 1100], [[5, 5, 5, 5], 1000], [[1, 1, 1, 1, 1, 1], 3000],
|
||||
[[1, 2, 3, 4, 5, 6], 1500], [[2, 2, 3, 3, 4, 4], 1500], [[2, 2, 2, 2, 3, 3], 1500],
|
||||
[[2, 2, 2, 3, 3, 3], 500], [[1, 1, 1, 5, 5, 5], 1500], [[2, 2, 2, 1], 300], [[3, 3, 3, 5, 5], 400],
|
||||
];
|
||||
for (const [d, pts] of T) {
|
||||
const r = L.scoreSelection(d);
|
||||
ok(`score ${d.join('')} = ${pts}`, r.valid && r.points === pts, JSON.stringify(r));
|
||||
}
|
||||
for (const d of [[2], [1, 2], [2, 2], [3, 4], [1, 1, 6], [2, 3, 4, 5, 6]]) {
|
||||
ok(`invalid ${d.join('')}`, !L.scoreSelection(d).valid);
|
||||
}
|
||||
// house rules
|
||||
ok('two triplets 2500', L.scoreSelection([2, 2, 2, 3, 3, 3], R({ twoTriplets: true })).points === 2500);
|
||||
ok('two triplets beats 1s+5s triples', L.scoreSelection([1, 1, 1, 5, 5, 5], R({ twoTriplets: true })).points === 2500);
|
||||
const dbl = R({ doubling: true });
|
||||
ok('doubling four 2s = 400', L.scoreSelection([2, 2, 2, 2], dbl).points === 400);
|
||||
ok('doubling five 3s = 1200', L.scoreSelection([3, 3, 3, 3, 3], dbl).points === 1200);
|
||||
ok('doubling six 1s = 8000', L.scoreSelection([1, 1, 1, 1, 1, 1], dbl).points === 8000);
|
||||
ok('doubling four 2s + pair = three pairs 1500', L.scoreSelection([2, 2, 2, 2, 3, 3], dbl).points === 1500);
|
||||
// parts + reference keys line up
|
||||
const keys = new Set(scoringReference(R({ twoTriplets: true })).map((r) => r.key));
|
||||
for (const d of [[1], [5, 5], [1, 1, 1], [6, 6, 6], [2, 2, 2, 2], [4, 4, 4, 4, 4], [3, 3, 3, 3, 3, 3], [1, 2, 3, 4, 5, 6], [2, 2, 4, 4, 6, 6], [2, 2, 2, 3, 3, 3]]) {
|
||||
const p = L.scoreParts(d, R({ twoTriplets: true }));
|
||||
ok(`parts of ${d.join('')} are reference rows`, p.parts.every((x) => keys.has(x.key)), p.parts.map((x) => x.key).join());
|
||||
ok(`parts of ${d.join('')} sum`, p.parts.reduce((s, x) => s + x.points, 0) === p.points);
|
||||
}
|
||||
ok('best keep 1,5,2,3,4,6 → straight', L.bestScoring([1, 5, 2, 3, 4, 6]).points === 1500);
|
||||
ok('best keep prefers hot dice on ties', L.bestScoring([5, 5, 5, 1, 1, 1]).indices.length === 6);
|
||||
ok('smart group triple', L.smartGroup([2, 4, 2, 6, 2, 3], 2).join() === '0,2,4');
|
||||
ok('smart group straight', L.smartGroup([1, 2, 3, 4, 5, 6], 3).length === 6);
|
||||
ok('smart group single 1', L.smartGroup([1, 2, 3, 4, 4, 6], 0).join() === '0');
|
||||
ok('scoring mask', L.scoringMask([1, 2, 3, 5, 6, 6]).join() === 'true,false,false,true,false,false');
|
||||
}
|
||||
|
||||
// ── per-roll scoring regressions (the old engine combined throws) ────────────
|
||||
section('Per-roll scoring');
|
||||
{
|
||||
const s = L.createInitialState({ playerCount: 2 });
|
||||
// set aside 1 and 5, then throw 2,3,4,6 — a Farkle, not a straight
|
||||
s.phase = 'awaitPick'; s.turn.rolled = [1, 5, 2, 2, 3, 6];
|
||||
L.applySetAside(s, [0, 1]);
|
||||
ok('kept 150', s.turn.kept === 150 && s.turn.available === 4);
|
||||
ok('2,3,4,6 after 1,5 is a Farkle', !L.hasScoring([2, 3, 4, 6]));
|
||||
// set aside 2,2,2 then throw a single 2 — no four of a kind
|
||||
const s2 = L.createInitialState({ playerCount: 2 });
|
||||
s2.phase = 'awaitPick'; s2.turn.rolled = [2, 2, 2, 3, 4, 6];
|
||||
L.applySetAside(s2, [0, 1, 2]);
|
||||
ok('three 2s = 200', s2.turn.kept === 200);
|
||||
ok('a lone 2 later does not score', !L.hasScoring([2, 3, 4]));
|
||||
s2.phase = 'awaitPick'; s2.turn.rolled = [2, 1, 3];
|
||||
ok('cannot add a 2 to an old triple', L.applySetAside(s2, [0]) === null);
|
||||
ok('the 1 still scores', L.applySetAside(s2, [1])?.points === 100 && s2.turn.kept === 300);
|
||||
// set aside 1,1 then 3,3,4,4 — not three pairs
|
||||
ok('3,3,4,4 alone does not score', !L.hasScoring([3, 3, 4, 4]));
|
||||
}
|
||||
|
||||
// ── odds ─────────────────────────────────────────────────────────────────────
|
||||
section('Farkle odds');
|
||||
{
|
||||
for (let n = 1; n <= 6; n++) {
|
||||
let farkles = 0, total = 6 ** n;
|
||||
for (let k = 0; k < total; k++) {
|
||||
const d = []; let x = k;
|
||||
for (let i = 0; i < n; i++) { d.push(1 + (x % 6)); x = Math.floor(x / 6); }
|
||||
if (!L.hasScoring(d)) farkles++;
|
||||
}
|
||||
ok(`${n}-die farkle odds`, Math.abs(farkles / total - FARKLE_ODDS[n]) < 1e-12, `${farkles}/${total}`);
|
||||
ok(`${n}-die solver odds`, Math.abs(farkleChance(DEFAULT_RULES, n) - FARKLE_ODDS[n]) < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
// ── turn flow ────────────────────────────────────────────────────────────────
|
||||
section('Turn flow');
|
||||
{
|
||||
const s = L.createInitialState({ playerCount: 3, names: ['A', 'B', 'C'] });
|
||||
ok('starts awaitRoll', s.phase === 'awaitRoll' && s.turn.available === 6);
|
||||
ok('cannot bank before rolling', L.bank(s) === null);
|
||||
s.phase = 'awaitPick'; s.turn.rolled = [1, 1, 1, 5, 5, 5];
|
||||
const hot = L.applySetAside(s, [0, 1, 2, 3, 4, 5]);
|
||||
ok('hot dice', hot.hot && s.turn.available === 6 && s.turn.kept === 1500 && s.players[0].stats.hotDice === 1);
|
||||
ok('hot dice groups keep cycle', s.turn.groups[0].cycle === 0 && s.turn.cycle === 1);
|
||||
ok('bank allowed ≥ entry', L.canBank(s));
|
||||
const b = L.bank(s);
|
||||
ok('banked 1500', b.banked === 1500 && s.players[0].score === 1500 && s.players[0].onBoard);
|
||||
ok('next player', s.current === 1 && s.phase === 'awaitRoll' && s.turn.kept === 0);
|
||||
// entry gating
|
||||
s.phase = 'awaitPick'; s.turn.rolled = [1, 5, 2, 3, 4, 4];
|
||||
L.applySetAside(s, [0, 1]);
|
||||
ok('150 < entry: bank blocked', !L.canBank(s) && L.bank(s) === null);
|
||||
ok('rolling on is allowed', L.canRoll(s));
|
||||
// farkle
|
||||
s.phase = 'farkled';
|
||||
L.farkleTurn(s);
|
||||
ok('farkle passes', s.current === 2 && s.players[1].stats.farkles === 1 && s.players[1].farkleStreak === 1);
|
||||
// entry 0
|
||||
const z = L.createInitialState({ playerCount: 2, rules: { entry: 0 } });
|
||||
z.phase = 'awaitPick'; z.turn.rolled = [5, 2, 3, 4, 6, 6];
|
||||
L.applySetAside(z, [0]);
|
||||
ok('entry 0 allows a 50 bank', L.canBank(z));
|
||||
// seeded rolls
|
||||
const a = L.createInitialState({ playerCount: 2 });
|
||||
const c = L.createInitialState({ playerCount: 2 });
|
||||
L.rollDice(a, mulberry32(7)); L.rollDice(c, mulberry32(7));
|
||||
ok('seeded roll repeatable', a.turn.rolled.join() === c.turn.rolled.join());
|
||||
ok('state is JSON-safe', JSON.stringify(L.cloneState(a)) === JSON.stringify(a));
|
||||
}
|
||||
|
||||
section('Final round');
|
||||
{
|
||||
const s = L.createInitialState({ playerCount: 3, names: ['A', 'B', 'C'] });
|
||||
s.players.forEach((p) => { p.onBoard = true; });
|
||||
s.players[0].score = 9800;
|
||||
s.phase = 'awaitPick'; s.turn.rolled = [1, 1, 1, 2, 3, 4];
|
||||
L.applySetAside(s, [0, 1, 2]);
|
||||
L.bank(s);
|
||||
ok('final round triggered', s.finalRound && s.finalFrom === 0 && s.players[0].score === 10800);
|
||||
ok('B needs 10,850 − score', L.finalRoundNeed(s) === 10800 - s.players[1].score + 50);
|
||||
s.phase = 'farkled'; L.farkleTurn(s);
|
||||
ok('C still to play', s.phase === 'awaitRoll' && s.current === 2);
|
||||
s.players[2].score = 11000;
|
||||
ok('C leads: needs nothing', L.finalRoundNeed(s) === 0);
|
||||
s.phase = 'farkled'; L.farkleTurn(s);
|
||||
ok('game over after the lap', L.isGameOver(s) && s.winners.join() === '2');
|
||||
ok('rankings', L.rankings(s).join() === '2,3,1');
|
||||
}
|
||||
|
||||
section('House rules');
|
||||
{
|
||||
const s = L.createInitialState({ playerCount: 2, rules: { threeFarkle: true } });
|
||||
s.players[0].score = 700; s.players[0].onBoard = true;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
s.current = 0; s.phase = 'farkled';
|
||||
const r = L.farkleTurn(s);
|
||||
if (k < 2) ok(`farkle ${k + 1}: no penalty`, r.penalty === 0);
|
||||
else ok('third farkle costs up to 1,000', r.penalty === 700 && s.players[0].score === 0 && s.players[0].farkleStreak === 0);
|
||||
}
|
||||
// piggyback
|
||||
const p = L.createInitialState({ playerCount: 2, rules: { piggyback: true } });
|
||||
p.phase = 'awaitPick'; p.turn.rolled = [1, 1, 1, 2, 3, 4];
|
||||
L.applySetAside(p, [0, 1, 2]);
|
||||
L.bank(p);
|
||||
ok('piggyback offered', p.piggyOffer && p.piggyOffer.kept === 1000 && p.piggyOffer.available === 3);
|
||||
ok('take piggyback', L.takePiggyback(p) && p.turn.kept === 1000 && p.turn.available === 3 && !L.canBank(p));
|
||||
const q = L.createInitialState({ playerCount: 2, rules: { piggyback: true } });
|
||||
q.phase = 'awaitPick'; q.turn.rolled = [1, 1, 1, 2, 3, 4];
|
||||
L.applySetAside(q, [0, 1, 2]); L.bank(q);
|
||||
L.rollDice(q, mulberry32(3));
|
||||
ok('rolling fresh declines the offer', q.piggyOffer === null && q.turn.kept === 0 && q.turn.rolls === 1);
|
||||
ok('piggy AI decision is boolean', typeof wantsPiggyback(p, 5) === 'boolean');
|
||||
ok('rules normalise', normalizeRules({ target: 123, entry: 7 }).target === 10000 && normalizeRules({ entry: 7 }).entry === 500);
|
||||
}
|
||||
|
||||
// ── solver ───────────────────────────────────────────────────────────────────
|
||||
section('Solver');
|
||||
{
|
||||
const s0 = pointsSolver(DEFAULT_RULES, 0);
|
||||
const e = s0.rollValue(0, 6);
|
||||
ok('expected turn ≈ 590', e > 560 && e < 620, e.toFixed(1));
|
||||
const s5 = pointsSolver(DEFAULT_RULES, 500);
|
||||
ok('entry rule lowers the value', s5.rollValue(0, 6) < e);
|
||||
ok('never bank with 6 dice at 1000', !s0.shouldBank(1000, 6));
|
||||
ok('bank 2 dice at 600', s0.shouldBank(600, 2));
|
||||
ok('roll 3 dice at 200', !s0.shouldBank(200, 3));
|
||||
ok('roll 4 dice at 500', !s0.shouldBank(500, 4));
|
||||
ok('bank below entry impossible', !s5.shouldBank(300, 1));
|
||||
let mono = true;
|
||||
for (let n = 1; n <= 6; n++) for (let t = 50; t <= 5000; t += 50) if (s0.value(t, n) + 1e-9 < s0.value(t - 50, n)) mono = false;
|
||||
ok('value monotone in total', mono);
|
||||
const k1 = bestKeep([1, 5, 2, 3, 4, 4], 0, DEFAULT_RULES, s0);
|
||||
ok('textbook: keep a lone 1 from 1,5,…', k1.indices.length === 1 && k1.points === 100);
|
||||
const k2 = bestKeep([1, 2, 3, 4, 5, 6], 0, DEFAULT_RULES, s0);
|
||||
ok('keep a straight', k2.points === 1500);
|
||||
const r = reachSolver(DEFAULT_RULES, 1000);
|
||||
const p = r.rollValue(0, 6);
|
||||
ok('reach 1000 probability sane', p > 0.25 && p < 0.6, p.toFixed(3));
|
||||
ok('reach is monotone in need', reachSolver(DEFAULT_RULES, 2000).rollValue(0, 6) < p);
|
||||
ok('ranked keeps sorted', rankKeeps([1, 1, 5, 2, 3, 6], 0, DEFAULT_RULES, s0).every((k, i, a) => !i || a[i - 1].value >= k.value));
|
||||
const st = L.createInitialState({ playerCount: 2 });
|
||||
st.phase = 'awaitPick'; st.turn.rolled = [1, 5, 2, 3, 4, 4];
|
||||
const adv = coachAdvice(st, [0, 1]);
|
||||
ok('coach flags a 1+5 keep as worse than the lone 1', adv && adv.regret > 0 && adv.best.points === 100);
|
||||
}
|
||||
|
||||
// ── AI play ──────────────────────────────────────────────────────────────────
|
||||
function playTurn(s, skill, rng, checks) {
|
||||
for (let guard = 0; guard < 200; guard++) {
|
||||
if (s.piggyOffer && s.turn.rolls === 0 && wantsPiggyback(s, skill)) L.takePiggyback(s);
|
||||
L.rollDice(s, rng);
|
||||
if (s.phase === 'farkled') { L.farkleTurn(s); return 0; }
|
||||
const me = s.players[s.current];
|
||||
const need = L.finalRoundNeed(s);
|
||||
const d = planDecision(s, skill, rng);
|
||||
const res = L.applySetAside(s, d.keep);
|
||||
if (!res) { checks.badKeep++; return 0; }
|
||||
if (d.bank) {
|
||||
const leadBefore = Math.max(...s.players.filter((p) => p !== me).map((p) => p.score));
|
||||
const wasFinal = s.finalRound;
|
||||
const b = L.bank(s);
|
||||
if (!b) { checks.badBank++; return 0; }
|
||||
if (wasFinal && need > 0 && me.score <= leadBefore) checks.finalShort++;
|
||||
return b.banked;
|
||||
}
|
||||
}
|
||||
checks.stuck++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
section('AI self-play');
|
||||
{
|
||||
const rng = mulberry32(12345);
|
||||
const checks = { badKeep: 0, badBank: 0, finalShort: 0, stuck: 0 };
|
||||
const GAMES = QUICK ? 120 : 600;
|
||||
let turns = 0, maxTurns = 0, belowTarget = 0;
|
||||
const ruleSets = [{}, { entry: 0 }, { entry: 1000, target: 5000 }, { threeFarkle: true, piggyback: true }, { doubling: true, twoTriplets: true, target: 15000 }];
|
||||
for (let g = 0; g < GAMES; g++) {
|
||||
const n = 2 + (g % 3);
|
||||
const skills = {};
|
||||
for (let i = 0; i < n; i++) skills[i] = 1 + Math.floor(rng() * 5);
|
||||
const s = L.createInitialState({ playerCount: n, skills, rules: ruleSets[g % ruleSets.length] });
|
||||
let k = 0;
|
||||
while (!L.isGameOver(s) && k < 3000) { playTurn(s, s.players[s.current].skill, rng, checks); k++; }
|
||||
turns += k; maxTurns = Math.max(maxTurns, k);
|
||||
ok(`game ${g} finished`, L.isGameOver(s), `${k} turns`);
|
||||
if (Math.max(...s.players.map((p) => p.score)) < s.rules.target) belowTarget++;
|
||||
ok(`game ${g} winners hold the max`, s.winners.every((w) => s.players[w].score === Math.max(...s.players.map((p) => p.score))));
|
||||
}
|
||||
ok('every keep was legal', checks.badKeep === 0, String(checks.badKeep));
|
||||
ok('never banked illegally (entry)', checks.badBank === 0, String(checks.badBank));
|
||||
ok('never banked short of the final-round leader', checks.finalShort === 0, String(checks.finalShort));
|
||||
ok('no stuck turns', checks.stuck === 0);
|
||||
ok('winner always reached the target', belowTarget === 0, String(belowTarget));
|
||||
console.log(` ${GAMES} games · avg ${(turns / GAMES).toFixed(1)} turns · max ${maxTurns}`);
|
||||
}
|
||||
|
||||
section('Skill ladder');
|
||||
{
|
||||
const N = QUICK ? 30000 : 120000;
|
||||
const avg = [];
|
||||
for (let sk = 1; sk <= 5; sk++) {
|
||||
const rng = mulberry32(900 + sk);
|
||||
const checks = { badKeep: 0, badBank: 0, finalShort: 0, stuck: 0 };
|
||||
let sum = 0;
|
||||
for (let i = 0; i < N; i++) {
|
||||
const s = L.createInitialState({ playerCount: 2, skills: { 0: sk } });
|
||||
s.players[0].onBoard = true;
|
||||
sum += playTurn(s, sk, rng, checks);
|
||||
}
|
||||
avg[sk] = sum / N;
|
||||
}
|
||||
console.log(` points/turn: ${avg.slice(1).map((a, i) => `${i + 1}:${a.toFixed(0)}`).join(' ')}`);
|
||||
for (let sk = 2; sk <= 5; sk++) ok(`skill ${sk} > skill ${sk - 1}`, avg[sk] > avg[sk - 1] + 5, `${avg[sk].toFixed(1)} vs ${avg[sk - 1].toFixed(1)}`);
|
||||
const opt = pointsSolver(DEFAULT_RULES, 0).rollValue(0, 6);
|
||||
ok('skill 5 matches the solver', Math.abs(avg[5] - opt) < opt * 0.03, `${avg[5].toFixed(1)} vs ${opt.toFixed(1)}`);
|
||||
}
|
||||
|
||||
// ── layout (optional until the scene modules exist) ─────────────────────────
|
||||
section('Layout');
|
||||
try {
|
||||
const Y = await import('../src/games/farkel/FarkelLayout.js');
|
||||
for (let nOpp = 1; nOpp <= 3; nOpp++) {
|
||||
const f = Y.hudFurniture(nOpp);
|
||||
for (const r of f) ok(`${r.name} on screen (${nOpp} opp)`, Y.onScreen(r), JSON.stringify(r));
|
||||
for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) {
|
||||
if (Y.ALLOWED_OVERLAPS?.has(`${f[i].name}|${f[j].name}`)) continue;
|
||||
ok(`${f[i].name} ∩ ${f[j].name} (${nOpp} opp)`, !Y.rectsOverlap(f[i], f[j]));
|
||||
}
|
||||
}
|
||||
// six dice fit across the tray and the rail
|
||||
for (let n = 1; n <= 6; n++) {
|
||||
const xs = Array.from({ length: n }, (_, i) => Y.columnU(i, n));
|
||||
ok(`${n} columns inside the felt`, xs.every((u) => u > Y.DIE_SIZE && u < Y.TRAY_FELT.w - Y.DIE_SIZE));
|
||||
}
|
||||
for (let k = 0; k < 6; k++) ok(`rail slot ${k} on the rail`, Y.railU(k, 6, 3) > 0 && Y.TRAY_FELT.x + Y.railU(k, 6, 3) < Y.RAIL.x + Y.RAIL.w);
|
||||
} catch (e) {
|
||||
if (e.code === 'ERR_MODULE_NOT_FOUND') console.log(' (layout module not present — skipped)');
|
||||
else { ok('layout module loads', false, e.message); }
|
||||
}
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
Loading…
Reference in New Issue