Overhaul Mexican Train: full kitchen-table art, skill-based AI, and house rules
This commit is contained in:
parent
df725cb013
commit
c530bc5b30
Binary file not shown.
|
|
@ -287,6 +287,7 @@ export const MANIFEST = {
|
|||
// first-player(5). Frame order documented in AzulData.js. A placeholder
|
||||
// sheet ships; vectors draw when absent.
|
||||
azul: [sheet('azul-tiles', 'assets/images/azul-tiles.png', 96, 96)],
|
||||
mexicantrain: [{ type: 'audio', key: 'mt-dominoes-shuffle', path: 'assets/speech/dominoes-shuffle.mp3' }],
|
||||
tickettoride: [sheet('ttr-cards', 'assets/images/tickettoride-cards.png', 270, 390)],
|
||||
gofish: [sheet('gofish-cards', 'assets/images/gofish-cards.png', 270, 390)],
|
||||
oldmaid: [sheet('oldmaid-cards', 'assets/images/oldmaid-cards.png', 270, 390)],
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: tru
|
|||
registerGame({ slug: 'uno', name: 'Uno', category: 'cards', cardGame: false, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 9 });
|
||||
registerGame({ slug: 'craps', name: 'Craps', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 10 });
|
||||
registerGame({ slug: 'roulette', name: 'Roulette', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 11 });
|
||||
registerGame({ slug: 'mexicantrain', name: 'Mexican Train', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 12 });
|
||||
registerGame({ slug: 'mexicantrain', name: 'Mexican Train', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, defaultOpponents: 3, hasTutorial: true, iconFrame: 12 });
|
||||
registerGame({ slug: 'hearts', name: 'Hearts', category: 'cards', cardGame: true, minPlayers: 4, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, iconFrame: 13 });
|
||||
registerGame({ slug: 'catan', name: 'Settlers of Catan', category: 'tabletop', cardGame: true, minPlayers: 3, maxPlayers: 4, minOpponents: 2, maxOpponents: 3, hasTutorial: true, iconFrame: 14 });
|
||||
registerGame({ slug: 'tickettoride', name: 'Ticket to Ride', category: 'tabletop', cardGame: true, minPlayers: 2, maxPlayers: 5, minOpponents: 1, maxOpponents: 4, hasTutorial: true, iconFrame: 15 });
|
||||
|
|
|
|||
|
|
@ -1,45 +1,240 @@
|
|||
// Heuristic Mexican Train AI. Stateless; consumed by MexicanTrainGame.
|
||||
// MexicanTrainAI.js — skill 1–5 opponents (and the human's Hint). Pure.
|
||||
//
|
||||
// chooseMove(state, idx) -> { tileIndex, train } | null
|
||||
// Picks among the legal moves the engine reports. The scene handles the
|
||||
// draw/pass flow when no legal move exists.
|
||||
// chooseAction(state, seat, skill, rnd) → { type: 'play', tileId, train }
|
||||
// | { type: 'draw' } | { type: 'pass' } | { type: 'end' }
|
||||
// hint(state, seat) → { action, tags, text }
|
||||
// bestChain(hand, start) → { path: [{ id, left, right }], pips }
|
||||
//
|
||||
// Strategy (skill 3+): plan the longest chain your hand can build off your own
|
||||
// train's end — that's your "train" for the coming turns — and dump the tiles
|
||||
// that don't fit it ("orphans") on the Mexican Train / open trains first. Take
|
||||
// your marker back as soon as you can, lay out the whole chain on the opening
|
||||
// run, don't lay a double you can't cover, and shed heavy tiles once someone
|
||||
// is close to going out. Skill 4–5 also count the tiles they can't see to
|
||||
// starve opponents' open trains and to keep the Mexican end on a number they
|
||||
// hold. Lower skills add noise (skill 1 sometimes plays at random).
|
||||
|
||||
import { getLegalMoves, isDoubleTile, tilePips, MEXICAN } from './MexicanTrainLogic.js';
|
||||
import * as L from './MexicanTrainLogic.js';
|
||||
|
||||
export function chooseMove(state, idx) {
|
||||
const moves = getLegalMoves(state, idx);
|
||||
if (moves.length === 0) return null;
|
||||
export const TUNE = {
|
||||
pips: 0.32, // immediate pips shed (× urgency)
|
||||
orphan: 2.6, // each tile left that doesn't fit our chain
|
||||
orphanPip: 0.07, // … and its pips (× urgency)
|
||||
reclaim: 6, // taking our marker back
|
||||
ownSpend: 0.9, // playing our own train when we didn't need to
|
||||
runTile: 2.2, // opening run: per chain tile we'll get to lay out
|
||||
doubleCover: 2.4, // a double we can cover ourselves (two tiles this turn)
|
||||
doubleStuck: 6.5, // a double we can't cover (draw + marker + a gift)
|
||||
doubleRelaxed: 1.5, // relaxed doubles: the free extra play
|
||||
onOpen: 0.6, // using someone else's open train
|
||||
keepEnd: 1.1, // leaving a public end on a number we still hold
|
||||
feed: 3.2, // Δ chance the next players can use the end we leave
|
||||
ownerFeed: 2.0, // … extra when it's the owner's own (open) train
|
||||
};
|
||||
// Skill 5 (and the Hint): measured +9% wins over skill 4 in mirrored play —
|
||||
// leave opponents' open trains alone unless it pays, and starve the next seats.
|
||||
export const TUNE5 = { ...TUNE, onOpen: -1, feed: 6, ownerFeed: 3, pips: 0.22 };
|
||||
|
||||
const hand = state.players[idx].hand;
|
||||
const ownKey = String(idx);
|
||||
const ownMarked = state.trains[ownKey]?.marker;
|
||||
const NOISE = { 1: 4, 2: 2.4, 3: 1.2, 4: 0.5, 5: 0 };
|
||||
const RANDOM_PLAY = { 1: 0.15, 2: 0.04, 3: 0, 4: 0, 5: 0 };
|
||||
const KNOCK = { 1: 0.7, 2: 0.82, 3: 0.92, 4: 0.97, 5: 1 };
|
||||
const CATCH = { 1: 0.25, 2: 0.4, 3: 0.6, 4: 0.78, 5: 0.92 };
|
||||
|
||||
let best = null;
|
||||
let bestScore = -Infinity;
|
||||
for (const m of moves) {
|
||||
const score = scoreMove(state, m, hand[m.tileIndex], ownKey, ownMarked);
|
||||
if (score > bestScore) { bestScore = score; best = m; }
|
||||
export const willKnock = (skill, rnd = Math.random) => rnd() < (KNOCK[skill] ?? 0.9);
|
||||
export const willCatch = (skill, rnd = Math.random) => rnd() < (CATCH[skill] ?? 0.6);
|
||||
|
||||
// ── chain search ─────────────────────────────────────────────────────────────
|
||||
// Longest trail of hand tiles starting at `start`; ties → more pips (lay the
|
||||
// heavy ones in the chain, which is sure to be played). A double is always
|
||||
// taken the moment we stand on its number (never shortens a trail).
|
||||
export function bestChain(hand, start, budget = 12000) {
|
||||
const byVal = new Map();
|
||||
for (const t of hand) {
|
||||
if (!byVal.has(t.a)) byVal.set(t.a, []);
|
||||
byVal.get(t.a).push(t);
|
||||
if (t.b !== t.a) {
|
||||
if (!byVal.has(t.b)) byVal.set(t.b, []);
|
||||
byVal.get(t.b).push(t);
|
||||
}
|
||||
}
|
||||
for (const list of byVal.values()) list.sort((x, y) => (y.a === y.b) - (x.a === x.b) || (y.a + y.b) - (x.a + x.b));
|
||||
const used = new Set();
|
||||
const path = [];
|
||||
let best = { path: [], pips: 0 };
|
||||
let nodes = 0;
|
||||
const dfs = (v, pips) => {
|
||||
if (++nodes > budget) return;
|
||||
if (path.length > best.path.length || (path.length === best.path.length && pips > best.pips)) best = { path: path.slice(), pips };
|
||||
const list = byVal.get(v);
|
||||
if (!list) return;
|
||||
const dbl = list.find((t) => t.a === v && t.b === v && !used.has(t.id));
|
||||
const options = dbl ? [dbl] : list;
|
||||
for (const t of options) {
|
||||
if (used.has(t.id)) continue;
|
||||
used.add(t.id);
|
||||
const right = t.a === v ? t.b : t.a;
|
||||
path.push({ id: t.id, left: v, right });
|
||||
dfs(right, pips + t.a + t.b);
|
||||
path.pop();
|
||||
used.delete(t.id);
|
||||
if (nodes > budget) return;
|
||||
}
|
||||
};
|
||||
dfs(start, 0);
|
||||
return best;
|
||||
}
|
||||
|
||||
function scoreMove(state, move, tile, ownKey, ownMarked) {
|
||||
let score = tilePips(tile); // shed heavy tiles first to cut penalty risk
|
||||
|
||||
// Doubles are risky to hold and heavy — favor unloading them when we can.
|
||||
if (isDoubleTile(tile)) score += 6;
|
||||
|
||||
// Covering an open double is forced; prefer doing it with a non-double so we
|
||||
// don't immediately re-open another one we might not be able to cover.
|
||||
if (state.openDouble) {
|
||||
if (isDoubleTile(tile)) score -= 4;
|
||||
return score;
|
||||
// ── evaluation ───────────────────────────────────────────────────────────────
|
||||
function context(s, seat, skill, tune = null) {
|
||||
const opts = s.opts;
|
||||
const others = s.players.map((p, i) => i).filter((i) => i !== seat);
|
||||
const minOpp = Math.min(...others.map((i) => s.players[i].hand.length));
|
||||
const urgency = 1 + Math.max(0, 6 - minOpp) * 0.25;
|
||||
let has = null;
|
||||
if (skill >= 4) {
|
||||
// P(opponent o holds a tile with number v): unseen-tile odds, sharpened by
|
||||
// the numbers they publicly showed they lacked (and draws since).
|
||||
const unseen = L.unseenTiles(s, seat);
|
||||
const U = Math.max(1, unseen.length);
|
||||
const cnt = new Array(opts.set + 1).fill(0);
|
||||
for (const t of unseen) { cnt[t.a]++; if (t.b !== t.a) cnt[t.b]++; }
|
||||
const opp = [];
|
||||
for (let k = 1; k < s.n; k++) {
|
||||
const o = (seat + k) % s.n;
|
||||
const h = s.players[o].hand.length;
|
||||
opp.push({ o, h, w: [1, 0.55, 0.35][k - 1] * (1 + Math.max(0, 5 - h) * 0.3), voids: s.voids?.[o] ?? {} });
|
||||
}
|
||||
const pHas = (op, v) => {
|
||||
const q = 1 - Math.min(0.95, cnt[v] / U);
|
||||
const d = op.voids[v];
|
||||
return 1 - Math.pow(q, d != null ? d : op.h);
|
||||
};
|
||||
has = { opp, pHas, feedOf: (v) => opp.reduce((acc, op) => acc + op.w * pHas(op, v), 0) };
|
||||
}
|
||||
|
||||
// Reclaim our own train (clears the marker so opponents lose access).
|
||||
if (move.train === ownKey) score += ownMarked ? 8 : 3;
|
||||
else if (move.train === MEXICAN) score += 1;
|
||||
// else: playing on an opponent's open train — neutral.
|
||||
|
||||
return score;
|
||||
return { opts, own: String(seat), urgency, has, minOpp, T: tune ?? TUNE };
|
||||
}
|
||||
|
||||
function orphanCost(hand, ownEnd, ctx, skill) {
|
||||
const T = ctx.T;
|
||||
const ch = bestChain(hand, ownEnd);
|
||||
const inChain = new Set(ch.path.map((p) => p.id));
|
||||
let n = 0, pips = 0;
|
||||
for (const t of hand) if (!inChain.has(t.id)) { n++; pips += L.tilePips(t, ctx.opts); }
|
||||
return { cost: n * T.orphan + pips * T.orphanPip * ctx.urgency, chain: ch.path.length };
|
||||
}
|
||||
|
||||
function scoreMove(s, seat, m, ctx, skill, base) {
|
||||
const hand = s.players[seat].hand;
|
||||
const tile = hand.find((t) => t.id === m.tileId);
|
||||
const after = hand.filter((t) => t.id !== m.tileId);
|
||||
const tags = [];
|
||||
const T = ctx.T;
|
||||
let sc = L.tilePips(tile, ctx.opts) * T.pips * ctx.urgency;
|
||||
const own = m.train === ctx.own;
|
||||
const ownEndAfter = own ? m.right : L.trainOpenEnd(s, ctx.own);
|
||||
const oc = orphanCost(after, ownEndAfter, ctx, skill);
|
||||
sc -= oc.cost;
|
||||
sc += base.cost; // relative to standing still
|
||||
if (oc.cost < base.cost - 0.01 && !own) tags.push('orphan');
|
||||
if (own) {
|
||||
if (s.trains[ctx.own].marker) { sc += T.reclaim; tags.push('reclaim'); }
|
||||
else if (!s.turn.opening && !s.openDouble) sc -= T.ownSpend;
|
||||
if (s.turn.opening) { sc += T.runTile * oc.chain; tags.push('run'); }
|
||||
if (oc.chain > 0 || base.chain > 0) tags.push('chain');
|
||||
} else if (m.train !== L.MEXICAN) {
|
||||
sc += T.onOpen;
|
||||
tags.push('open');
|
||||
}
|
||||
if (m.left === m.right) {
|
||||
const canCover = after.some((t) => t.a === m.right || t.b === m.right);
|
||||
if (ctx.opts.doubles === 'cover') {
|
||||
if (canCover) { sc += T.doubleCover; tags.push('double'); }
|
||||
else { sc -= T.doubleStuck * (skill <= 1 ? 0.4 : 1); tags.push('stuck'); }
|
||||
} else sc += T.doubleRelaxed;
|
||||
}
|
||||
if (s.openDouble) tags.push('cover');
|
||||
if (ctx.has && !own) {
|
||||
// what the next players can do with the end we leave vs. the end that's there now
|
||||
const before = L.trainOpenEnd(s, m.train), e = m.right;
|
||||
let delta = ctx.has.feedOf(e) - ctx.has.feedOf(before);
|
||||
if (m.train !== L.MEXICAN) {
|
||||
const op = ctx.has.opp.find((q) => String(q.o) === m.train);
|
||||
if (op) delta += (T.ownerFeed / T.feed) * (ctx.has.pHas(op, e) - ctx.has.pHas(op, before));
|
||||
}
|
||||
sc -= T.feed * delta;
|
||||
if (delta < -0.25) tags.push('block');
|
||||
if (after.some((t) => t.a === e || t.b === e)) sc += T.keepEnd;
|
||||
}
|
||||
if (ctx.urgency > 1.6 && L.tilePips(tile, ctx.opts) >= ctx.opts.set) tags.push('heavy');
|
||||
return { sc, tags };
|
||||
}
|
||||
|
||||
function rankMoves(s, seat, skill, tune = null) {
|
||||
const moves = L.getLegalMoves(s, seat);
|
||||
const ctx = context(s, seat, skill, tune);
|
||||
const base = orphanCost(s.players[seat].hand, L.trainOpenEnd(s, ctx.own), ctx, skill);
|
||||
return moves.map((m) => ({ m, ...scoreMove(s, seat, m, ctx, skill, base) })).sort((a, b) => b.sc - a.sc);
|
||||
}
|
||||
|
||||
function gauss(rnd) {
|
||||
let u = 0, v = 0;
|
||||
while (u === 0) u = rnd();
|
||||
while (v === 0) v = rnd();
|
||||
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
|
||||
}
|
||||
|
||||
export function chooseAction(s, seat, skill = 3, rnd = Math.random, tune = null) {
|
||||
if (s.phase !== 'playing' || s.current !== seat) return null;
|
||||
const moves = L.getLegalMoves(s, seat);
|
||||
if (!moves.length) {
|
||||
if (L.canDraw(s)) return { type: 'draw' };
|
||||
if (L.canEndTurn(s)) return { type: 'end' };
|
||||
if (L.canPass(s)) return { type: 'pass' };
|
||||
return null;
|
||||
}
|
||||
// the opening run: weak players sometimes stop early
|
||||
if (L.canEndTurn(s) && skill <= 2 && rnd() < (skill === 1 ? 0.25 : 0.08)) return { type: 'end' };
|
||||
if (rnd() < (RANDOM_PLAY[skill] ?? 0)) {
|
||||
const m = moves[Math.floor(rnd() * moves.length)];
|
||||
return { type: 'play', tileId: m.tileId, train: m.train };
|
||||
}
|
||||
const ranked = rankMoves(s, seat, skill, tune ?? (skill >= 5 ? TUNE5 : null));
|
||||
const sigma = NOISE[skill] ?? 0;
|
||||
let best = ranked[0];
|
||||
if (sigma > 0) {
|
||||
let bv = -Infinity;
|
||||
for (const r of ranked) { const v = r.sc + gauss(rnd) * sigma; if (v > bv) { bv = v; best = r; } }
|
||||
}
|
||||
return { type: 'play', tileId: best.m.tileId, train: best.m.train };
|
||||
}
|
||||
|
||||
// ── hint for the human ───────────────────────────────────────────────────────
|
||||
export function hint(s, seat) {
|
||||
const moves = L.getLegalMoves(s, seat);
|
||||
if (!moves.length) {
|
||||
if (L.canDraw(s)) return { action: { type: 'draw' }, tags: [], text: 'Nothing fits anywhere you may play — draw from the boneyard.' };
|
||||
if (L.canEndTurn(s)) return { action: { type: 'end' }, tags: [], text: 'Your opening run is finished — end your turn.' };
|
||||
if (L.canPass(s)) return { action: { type: 'pass' }, tags: [], text: 'Still nothing playable — you have to pass (your train gets marked).' };
|
||||
return null;
|
||||
}
|
||||
const ranked = rankMoves(s, seat, 5, TUNE5);
|
||||
const top = ranked[0];
|
||||
const hand = s.players[seat].hand;
|
||||
const t = hand.find((x) => x.id === top.m.tileId);
|
||||
const name = L.tileName(t);
|
||||
const where = L.trainLabel(s, top.m.train, seat);
|
||||
const tg = new Set(top.tags);
|
||||
let why;
|
||||
if (tg.has('cover')) why = 'The double has to be covered first.';
|
||||
else if (tg.has('reclaim')) why = 'It takes your marker back, so nobody else can play on your train.';
|
||||
else if (tg.has('run')) {
|
||||
const ch = bestChain(hand, L.trainOpenEnd(s, String(seat)));
|
||||
why = ch.path.length > 1 ? `It starts a ${ch.path.length}-tile run on your own train — lay out as much as you can on your first turn.` : 'It gets your own train started.';
|
||||
} else if (tg.has('double')) why = `A double you can cover yourself — two tiles gone this turn.`;
|
||||
else if (tg.has('orphan')) why = `It doesn't fit the chain your hand can build, so dump it while you can and save your own train.`;
|
||||
else if (tg.has('block')) why = 'It also leaves their open train on a number that is nearly used up.';
|
||||
else if (tg.has('heavy')) why = 'Someone is nearly out — shed your heavy tiles.';
|
||||
else if (tg.has('chain')) why = 'It extends the chain your hand builds off your own train.';
|
||||
else why = 'It sheds the most pips for the least risk.';
|
||||
return { action: { type: 'play', tileId: top.m.tileId, train: top.m.train }, tags: [...tg], text: `Play ${name} on ${where}. ${why}` };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,752 @@
|
|||
// MexicanTrainArt.js — baked canvas textures for "Sunday afternoon at the
|
||||
// kitchen table". All procedural: no image files.
|
||||
//
|
||||
// mt-room honey-oak plank table (grain, knots, seams, wear, a coffee
|
||||
// ring), a crocheted doily under the hub, and the props: a
|
||||
// coffee mug, a bowl of pretzels, the lemonade pitcher and a
|
||||
// glass, a sleeping tabby, the open wooden domino box
|
||||
// mt-vignette the warm light + vignette alone (over a chosen playfield)
|
||||
// mt-props the props alone (over a chosen playfield)
|
||||
// mt-sun window light (four panes) — drifted slowly, ADD blend
|
||||
// mt-tail the cat's tail (flicks now and then)
|
||||
// mt-tc-<a>-<b> domino faces with coloured pips (mt-tk-… classic black)
|
||||
// mt-back, mt-tshadow, mt-glow, mt-slot
|
||||
// mt-hub the station hub (turned maple, brass ring, slot notches)
|
||||
// mt-engine-<c> toy locomotive markers (seat colours + 'm' Mexican)
|
||||
// mt-card / mt-seat / mt-pad / mt-rack / mt-mini paper + wood furniture
|
||||
// mt-mote, mt-steam, mt-spark, mt-badge
|
||||
|
||||
import { canvas, rr } from '../../ui/casino/CasinoArt.js';
|
||||
import {
|
||||
W, H, HUB, STATUS, TALK, SEAT_CARDS, RACK, SCORE_PAD, BONEYARD, RACK_TILE, TILE,
|
||||
} from './MexicanTrainLayout.js';
|
||||
|
||||
export const DISPLAY_FONT = 'Righteous, Georgia, serif';
|
||||
export const SERIF = 'Georgia, "Times New Roman", serif';
|
||||
export const HAND_FONT = 'YummyCupcakes, "Comic Sans MS", cursive';
|
||||
export const PRINT_FONT = '"Julius Sans One", Georgia, serif';
|
||||
|
||||
export const RES = 2; // texture px per screen px (rack size)
|
||||
export const TEX = { w: RACK_TILE.u * 2 * RES, h: RACK_TILE.u * RES }; // horizontal face texture
|
||||
export const TABLE_SCALE = TILE.u / RACK_TILE.u / RES; // texture → table tile at zoom 1
|
||||
export const RACK_SCALE = 1 / RES;
|
||||
|
||||
// Seat colours (seat 0 = you), and the Mexican Train's.
|
||||
export const SEAT = [
|
||||
{ name: 'cherry', base: '#c23b2e', light: '#ec6a52', dark: '#6e1810', hex: 0xc23b2e, ink: '#a1281c' },
|
||||
{ name: 'blue', base: '#2e64ad', light: '#5d93d8', dark: '#132f5c', hex: 0x2e64ad, ink: '#24508c' },
|
||||
{ name: 'green', base: '#3a8f47', light: '#6cc178', dark: '#173f1e', hex: 0x3a8f47, ink: '#2b6e35' },
|
||||
{ name: 'gold', base: '#d39a1e', light: '#f5c95a', dark: '#6e4c06', hex: 0xd39a1e, ink: '#8e6408' },
|
||||
];
|
||||
export const MEX = { name: 'mexican', base: '#7a4bb0', light: '#a985da', dark: '#3a1e5e', hex: 0x7a4bb0, ink: '#5e3590' };
|
||||
export const colorOf = (key) => (key === 'mexican' ? MEX : SEAT[Number(key)] ?? SEAT[0]);
|
||||
|
||||
// Pip colours by number, like a real Mexican Train set (index 0 unused).
|
||||
export const PIP_COLORS = [
|
||||
'#222', '#2f8fd8', '#2e9a45', '#d23c32', '#8a5a2b', '#23408f', '#d9a514',
|
||||
'#8a4fc0', '#138a86', '#c2367f', '#e0742a', '#6f7d1c', '#3a3a3a',
|
||||
];
|
||||
export const PIP_HEX = PIP_COLORS.map((c) => parseInt(c.length === 4 ? c.slice(1).split('').map((x) => x + x).join('') : c.slice(1), 16));
|
||||
|
||||
function addCanvas(scene, key, c) {
|
||||
if (scene.textures.exists(key)) scene.textures.remove(key);
|
||||
scene.textures.addCanvas(key, c);
|
||||
}
|
||||
|
||||
function seeded(seed) {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function shadowed(ctx, fn, { blur = 18, dx = 6, dy = 10, alpha = 0.45 } = {}) {
|
||||
ctx.save();
|
||||
ctx.shadowColor = `rgba(20,8,0,${alpha})`;
|
||||
ctx.shadowBlur = blur;
|
||||
ctx.shadowOffsetX = dx;
|
||||
ctx.shadowOffsetY = dy;
|
||||
fn();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// ── the table ────────────────────────────────────────────────────────────────
|
||||
const PLANK_H = 136;
|
||||
const PLANK_TONES = ['#c88f4e', '#c08646', '#cf985a', '#bd8445', '#c99352', '#c48b4b', '#d09b5d', '#c1884a', '#c68e4f'];
|
||||
|
||||
function paintPlanks(ctx, rnd) {
|
||||
for (let i = 0, y = -24; y < H; i++, y += PLANK_H) {
|
||||
const tone = PLANK_TONES[i % PLANK_TONES.length];
|
||||
const g = ctx.createLinearGradient(0, y, 0, y + PLANK_H);
|
||||
g.addColorStop(0, tone);
|
||||
g.addColorStop(0.5, shade(tone, 6));
|
||||
g.addColorStop(1, shade(tone, -10));
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, y, W, PLANK_H);
|
||||
// grain
|
||||
ctx.save();
|
||||
ctx.beginPath(); ctx.rect(0, y, W, PLANK_H); ctx.clip();
|
||||
for (let k = 0; k < 46; k++) {
|
||||
const oy = y + rnd() * PLANK_H, amp = 2 + rnd() * 6, f = 0.002 + rnd() * 0.006, ph = rnd() * 6;
|
||||
ctx.strokeStyle = `rgba(${rnd() < 0.5 ? '90,48,14' : '120,70,28'},${0.06 + rnd() * 0.12})`;
|
||||
ctx.lineWidth = 0.6 + rnd() * 1.8;
|
||||
ctx.beginPath();
|
||||
for (let x = -10; x <= W + 10; x += 8) {
|
||||
const yy = oy + Math.sin(x * f + ph) * amp + Math.sin(x * f * 3.7 + ph * 2) * amp * 0.25;
|
||||
if (x < 0) ctx.moveTo(x, yy); else ctx.lineTo(x, yy);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
// cathedral arches
|
||||
for (let k = 0; k < 2; k++) {
|
||||
const cx = rnd() * W, cy = y + PLANK_H * (0.35 + rnd() * 0.3);
|
||||
for (let r = 0; r < 7; r++) {
|
||||
ctx.strokeStyle = `rgba(100,54,18,${0.08 + rnd() * 0.06})`;
|
||||
ctx.lineWidth = 1.2;
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(cx, cy, 120 + r * 34, 16 + r * 7, 0, Math.PI * 1.05, Math.PI * 1.95);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
// a knot or two
|
||||
for (let k = 0; k < (rnd() < 0.6 ? 1 : 2); k++) {
|
||||
const kx = 80 + rnd() * (W - 160), ky = y + 30 + rnd() * (PLANK_H - 60);
|
||||
for (let r = 6; r >= 1; r--) {
|
||||
ctx.fillStyle = `rgba(${70 + r * 8},${38 + r * 4},${12 + r * 2},${0.12 + (6 - r) * 0.06})`;
|
||||
ctx.beginPath(); ctx.ellipse(kx, ky, 4 + r * 5, 2 + r * 2.2, 0, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
ctx.fillStyle = 'rgba(52,24,6,0.7)';
|
||||
ctx.beginPath(); ctx.ellipse(kx, ky, 5, 2.5, 0, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
// butt joint
|
||||
const jx = 200 + rnd() * (W - 400);
|
||||
ctx.fillStyle = 'rgba(50,22,4,0.55)';
|
||||
ctx.fillRect(jx, y + 2, 2, PLANK_H - 4);
|
||||
// seam with a worn highlight
|
||||
ctx.fillStyle = 'rgba(46,20,4,0.75)';
|
||||
ctx.fillRect(0, y + PLANK_H - 2, W, 3);
|
||||
ctx.fillStyle = 'rgba(255,228,180,0.18)';
|
||||
ctx.fillRect(0, y + PLANK_H + 1, W, 2);
|
||||
}
|
||||
// pores
|
||||
for (let i = 0; i < 9000; i++) {
|
||||
ctx.fillStyle = `rgba(70,34,8,${0.05 + rnd() * 0.1})`;
|
||||
ctx.fillRect(rnd() * W, rnd() * H, 1 + rnd() * 3, 1);
|
||||
}
|
||||
}
|
||||
|
||||
function shade(hex, amt) {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
const c = (v) => Math.max(0, Math.min(255, v + amt));
|
||||
return `rgb(${c((n >> 16) & 255)},${c((n >> 8) & 255)},${c(n & 255)})`;
|
||||
}
|
||||
|
||||
function paintWear(ctx, rnd) {
|
||||
// a lighter worn patch where hands rest, a few scratches, and a coffee ring
|
||||
const wp = ctx.createRadialGradient(960, 1000, 40, 960, 1000, 520);
|
||||
wp.addColorStop(0, 'rgba(255,226,170,0.16)'); wp.addColorStop(1, 'rgba(255,226,170,0)');
|
||||
ctx.fillStyle = wp; ctx.fillRect(0, 0, W, H);
|
||||
for (let i = 0; i < 70; i++) {
|
||||
const x = rnd() * W, y = rnd() * H, len = 10 + rnd() * 60, a = (rnd() - 0.5) * 0.8;
|
||||
ctx.strokeStyle = `rgba(255,236,200,${0.05 + rnd() * 0.08})`;
|
||||
ctx.lineWidth = 0.8;
|
||||
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(a) * len, y + Math.sin(a) * len); ctx.stroke();
|
||||
}
|
||||
const ring = (x, y, r, a) => {
|
||||
ctx.strokeStyle = `rgba(92,48,16,${a})`;
|
||||
ctx.lineWidth = 3.5;
|
||||
ctx.beginPath(); ctx.arc(x, y, r, 0.3, Math.PI * 1.75); ctx.stroke();
|
||||
ctx.lineWidth = 1.2;
|
||||
ctx.beginPath(); ctx.arc(x + 2, y + 1, r - 4, 0.5, Math.PI * 1.4); ctx.stroke();
|
||||
};
|
||||
ring(1240, 840, 40, 0.22);
|
||||
ring(430, 230, 34, 0.14);
|
||||
}
|
||||
|
||||
function paintDoily(ctx) {
|
||||
const c = canvas(420, 420), d = c.getContext('2d');
|
||||
const cx = 210, cy = 210, R = 176;
|
||||
d.fillStyle = 'rgba(252,248,238,0.92)';
|
||||
d.beginPath();
|
||||
for (let i = 0; i <= 360; i++) {
|
||||
const a = (i / 360) * Math.PI * 2;
|
||||
const r = R + Math.cos(a * 24) * 9;
|
||||
const x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r;
|
||||
if (i === 0) d.moveTo(x, y); else d.lineTo(x, y);
|
||||
}
|
||||
d.fill();
|
||||
// lace holes
|
||||
d.globalCompositeOperation = 'destination-out';
|
||||
const holeRing = (rad, count, size) => {
|
||||
for (let k = 0; k < count; k++) {
|
||||
const a = (k / count) * Math.PI * 2;
|
||||
d.beginPath(); d.arc(cx + Math.cos(a) * rad, cy + Math.sin(a) * rad, size, 0, Math.PI * 2); d.fill();
|
||||
}
|
||||
};
|
||||
holeRing(R - 12, 24, 5.5);
|
||||
holeRing(R - 34, 36, 4.2);
|
||||
holeRing(R - 56, 30, 6);
|
||||
holeRing(R - 80, 24, 4);
|
||||
holeRing(R - 100, 18, 5);
|
||||
for (let k = 0; k < 12; k++) {
|
||||
const a = (k / 12) * Math.PI * 2;
|
||||
d.beginPath(); d.ellipse(cx + Math.cos(a) * 40, cy + Math.sin(a) * 40, 14, 5, a, 0, Math.PI * 2); d.fill();
|
||||
}
|
||||
d.globalCompositeOperation = 'source-over';
|
||||
d.strokeStyle = 'rgba(200,190,170,0.6)';
|
||||
d.lineWidth = 1;
|
||||
for (const rad of [R - 24, R - 46, R - 68, R - 90, R - 112]) { d.beginPath(); d.arc(cx, cy, rad, 0, Math.PI * 2); d.stroke(); }
|
||||
shadowed(ctx, () => ctx.drawImage(c, HUB.x - 210, HUB.y - 210), { blur: 6, dx: 2, dy: 3, alpha: 0.3 });
|
||||
}
|
||||
|
||||
// ── props ────────────────────────────────────────────────────────────────────
|
||||
export const PROPS = {
|
||||
mug: { x: 150, y: 470, r: 46 },
|
||||
pretzels: { x: 592, y: 70, r: 56 },
|
||||
pitcher: { x: 1300, y: 70, r: 50 },
|
||||
glass: { x: 1392, y: 92, r: 27 },
|
||||
cat: { x: 1772, y: 486 },
|
||||
};
|
||||
|
||||
function paintMug(ctx) {
|
||||
const { x, y, r } = PROPS.mug;
|
||||
shadowed(ctx, () => {
|
||||
ctx.fillStyle = '#e9e2d2';
|
||||
ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
|
||||
}, { blur: 16, dx: 8, dy: 12 });
|
||||
// handle
|
||||
ctx.strokeStyle = '#d8cfbc'; ctx.lineWidth = 11;
|
||||
ctx.beginPath(); ctx.arc(x + r + 6, y + 14, 17, -1.2, 1.9); ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.12)'; ctx.lineWidth = 2;
|
||||
ctx.beginPath(); ctx.arc(x + r + 6, y + 14, 22, -0.9, 1.6); ctx.stroke();
|
||||
// rim + a blue band
|
||||
ctx.strokeStyle = '#3d6fa8'; ctx.lineWidth = 5;
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 4, 0, Math.PI * 2); ctx.stroke();
|
||||
// coffee
|
||||
const g = ctx.createRadialGradient(x - 8, y - 8, 4, x, y, r - 9);
|
||||
g.addColorStop(0, '#6a3c1c'); g.addColorStop(0.7, '#3e2010'); g.addColorStop(1, '#2a1408');
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 9, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(214,170,120,0.45)'; ctx.lineWidth = 2;
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 11, 0, Math.PI * 2); ctx.stroke();
|
||||
ctx.fillStyle = 'rgba(255,244,220,0.35)';
|
||||
ctx.beginPath(); ctx.ellipse(x - 12, y - 14, 12, 5, -0.6, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
|
||||
function paintPretzels(ctx, rnd) {
|
||||
const { x, y, r } = PROPS.pretzels;
|
||||
shadowed(ctx, () => {
|
||||
ctx.fillStyle = '#6b8fb3';
|
||||
ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
|
||||
}, { blur: 16, dx: 8, dy: 12 });
|
||||
const g = ctx.createRadialGradient(x - 10, y - 10, 6, x, y, r);
|
||||
g.addColorStop(0, '#f2f4f6'); g.addColorStop(0.85, '#c8d4e0'); g.addColorStop(1, '#6b8fb3');
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 5, 0, Math.PI * 2); ctx.fill();
|
||||
for (let i = 0; i < 9; i++) {
|
||||
const a = rnd() * Math.PI * 2, d = rnd() * (r - 26);
|
||||
pretzel(ctx, x + Math.cos(a) * d, y + Math.sin(a) * d, 12 + rnd() * 3, rnd() * 6);
|
||||
}
|
||||
}
|
||||
function pretzel(ctx, x, y, s, rot) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y); ctx.rotate(rot);
|
||||
ctx.strokeStyle = '#7a3e12'; ctx.lineWidth = 5.5; ctx.lineCap = 'round';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-s * 0.2, s * 0.8);
|
||||
ctx.bezierCurveTo(-s * 1.4, s * 0.2, -s * 1.1, -s * 1.0, -s * 0.1, -s * 0.4);
|
||||
ctx.bezierCurveTo(s * 1.1, -s * 1.0, s * 1.4, s * 0.2, s * 0.2, s * 0.8);
|
||||
ctx.moveTo(-s * 0.55, -s * 0.05); ctx.lineTo(s * 0.4, s * 0.75);
|
||||
ctx.moveTo(s * 0.55, -s * 0.05); ctx.lineTo(-s * 0.4, s * 0.75);
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(255,200,140,0.5)'; ctx.lineWidth = 1.6;
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.85)';
|
||||
for (let i = 0; i < 4; i++) ctx.fillRect((Math.sin(i * 7 + rot) * s * 0.8), (Math.cos(i * 5 + rot) * s * 0.5), 2, 1.5);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function paintPitcher(ctx, rnd) {
|
||||
const { x, y, r } = PROPS.pitcher;
|
||||
shadowed(ctx, () => {
|
||||
ctx.fillStyle = 'rgba(240,232,160,0.75)';
|
||||
ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
|
||||
}, { blur: 14, dx: 8, dy: 12, alpha: 0.32 });
|
||||
// handle + spout
|
||||
ctx.strokeStyle = 'rgba(230,240,240,0.8)'; ctx.lineWidth = 9;
|
||||
ctx.beginPath(); ctx.arc(x - r - 4, y + 4, 15, 1.4, 4.9); ctx.stroke();
|
||||
ctx.fillStyle = 'rgba(235,240,230,0.7)';
|
||||
ctx.beginPath(); ctx.moveTo(x + r - 6, y - 12); ctx.lineTo(x + r + 16, y); ctx.lineTo(x + r - 6, y + 12); ctx.fill();
|
||||
const g = ctx.createRadialGradient(x - 14, y - 14, 4, x, y, r);
|
||||
g.addColorStop(0, 'rgba(255,252,210,0.95)'); g.addColorStop(1, 'rgba(240,214,90,0.9)');
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 5, 0, Math.PI * 2); ctx.fill();
|
||||
lemon(ctx, x + 10, y - 8, 15);
|
||||
lemon(ctx, x - 16, y + 14, 13);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const a = rnd() * 6, d = 10 + rnd() * 20;
|
||||
ctx.save(); ctx.translate(x + Math.cos(a) * d, y + Math.sin(a) * d); ctx.rotate(rnd() * 2);
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.55)'; rr(ctx, -8, -8, 16, 16, 4); ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.8)'; ctx.lineWidth = 1; ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.lineWidth = 3;
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 3, 0, Math.PI * 2); ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 4;
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 12, -2.6, -1.6); ctx.stroke();
|
||||
// the glass beside it, with a wet ring
|
||||
const gl = PROPS.glass;
|
||||
ctx.strokeStyle = 'rgba(80,50,20,0.18)'; ctx.lineWidth = 3;
|
||||
ctx.beginPath(); ctx.arc(gl.x + 6, gl.y + 7, gl.r + 2, 0, Math.PI * 2); ctx.stroke();
|
||||
const g2 = ctx.createRadialGradient(gl.x - 6, gl.y - 6, 2, gl.x, gl.y, gl.r);
|
||||
g2.addColorStop(0, 'rgba(255,250,200,0.95)'); g2.addColorStop(1, 'rgba(236,210,90,0.85)');
|
||||
ctx.fillStyle = g2;
|
||||
ctx.beginPath(); ctx.arc(gl.x, gl.y, gl.r, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.9)'; ctx.lineWidth = 2.5; ctx.stroke();
|
||||
lemon(ctx, gl.x + 4, gl.y - 2, 9);
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const a = rnd() * 6.28;
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.7)';
|
||||
ctx.beginPath(); ctx.arc(gl.x + Math.cos(a) * (gl.r + 1), gl.y + Math.sin(a) * (gl.r + 1), 1.4, 0, 6.28); ctx.fill();
|
||||
}
|
||||
}
|
||||
function lemon(ctx, x, y, r) {
|
||||
ctx.fillStyle = '#f3d23a';
|
||||
ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = '#fff6b8';
|
||||
ctx.beginPath(); ctx.arc(x, y, r - 2.5, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.strokeStyle = '#f0c428'; ctx.lineWidth = 1.4;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
const a = (k / 8) * Math.PI * 2;
|
||||
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(a) * (r - 3), y + Math.sin(a) * (r - 3)); ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
function paintCat(ctx, rnd) {
|
||||
const { x, y } = PROPS.cat;
|
||||
shadowed(ctx, () => {
|
||||
ctx.fillStyle = '#d98a3c';
|
||||
ctx.beginPath(); ctx.ellipse(x, y, 92, 64, -0.18, 0, Math.PI * 2); ctx.fill();
|
||||
}, { blur: 20, dx: 8, dy: 12, alpha: 0.4 });
|
||||
const g = ctx.createRadialGradient(x - 20, y - 20, 10, x, y, 96);
|
||||
g.addColorStop(0, '#f2a858'); g.addColorStop(0.75, '#d6853a'); g.addColorStop(1, '#a85e22');
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath(); ctx.ellipse(x, y, 92, 64, -0.18, 0, Math.PI * 2); ctx.fill();
|
||||
// tabby stripes
|
||||
ctx.strokeStyle = 'rgba(140,70,20,0.55)'; ctx.lineWidth = 7; ctx.lineCap = 'round';
|
||||
for (let i = -3; i <= 3; i++) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x + i * 22 + 10, y - 70, 64, Math.PI * 0.35, Math.PI * 0.62);
|
||||
ctx.stroke();
|
||||
}
|
||||
// head tucked in, front left
|
||||
const hx = x - 64, hy = y + 22;
|
||||
ctx.fillStyle = '#e8984a';
|
||||
ctx.beginPath(); ctx.ellipse(hx, hy, 40, 34, 0.4, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = '#d6853a';
|
||||
ctx.beginPath(); ctx.moveTo(hx - 30, hy - 14); ctx.lineTo(hx - 42, hy - 46); ctx.lineTo(hx - 10, hy - 30); ctx.fill();
|
||||
ctx.beginPath(); ctx.moveTo(hx + 4, hy - 30); ctx.lineTo(hx + 18, hy - 58); ctx.lineTo(hx + 30, hy - 20); ctx.fill();
|
||||
ctx.fillStyle = '#f4b8a8';
|
||||
ctx.beginPath(); ctx.moveTo(hx - 28, hy - 18); ctx.lineTo(hx - 37, hy - 40); ctx.lineTo(hx - 15, hy - 29); ctx.fill();
|
||||
ctx.beginPath(); ctx.moveTo(hx + 7, hy - 30); ctx.lineTo(hx + 17, hy - 50); ctx.lineTo(hx + 25, hy - 22); ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(140,70,20,0.6)'; ctx.lineWidth = 4;
|
||||
for (let i = 0; i < 3; i++) { ctx.beginPath(); ctx.moveTo(hx - 12 + i * 10, hy - 28); ctx.lineTo(hx - 10 + i * 10, hy - 14); ctx.stroke(); }
|
||||
// closed eyes (sleeping)
|
||||
ctx.strokeStyle = '#4a2a10'; ctx.lineWidth = 2.5;
|
||||
ctx.beginPath(); ctx.arc(hx - 16, hy - 2, 7, 0.2, Math.PI - 0.2); ctx.stroke();
|
||||
ctx.beginPath(); ctx.arc(hx + 10, hy + 6, 7, 0.2, Math.PI - 0.2); ctx.stroke();
|
||||
ctx.fillStyle = '#e07a82';
|
||||
ctx.beginPath(); ctx.arc(hx - 6, hy + 14, 4, 0, Math.PI * 2); ctx.fill();
|
||||
// white paw peeking out
|
||||
ctx.fillStyle = '#fbefe0';
|
||||
ctx.beginPath(); ctx.ellipse(hx + 30, hy + 30, 16, 10, 0.3, 0, Math.PI * 2); ctx.fill();
|
||||
void rnd;
|
||||
}
|
||||
|
||||
function bakeTail(scene) {
|
||||
const c = canvas(150, 50), d = c.getContext('2d');
|
||||
d.lineCap = 'round';
|
||||
d.strokeStyle = '#c97a34'; d.lineWidth = 22;
|
||||
d.beginPath(); d.moveTo(12, 25); d.quadraticCurveTo(70, 4, 136, 26); d.stroke();
|
||||
d.strokeStyle = 'rgba(140,70,20,0.6)'; d.lineWidth = 6;
|
||||
for (let i = 0; i < 5; i++) { d.beginPath(); d.moveTo(28 + i * 22, 6); d.lineTo(30 + i * 22, 30); d.stroke(); }
|
||||
addCanvas(scene, 'mt-tail', c);
|
||||
}
|
||||
|
||||
function paintBox(ctx, rnd) {
|
||||
const { x, y } = BONEYARD.box;
|
||||
const w = 210, h = 74;
|
||||
shadowed(ctx, () => { ctx.fillStyle = '#7a4a22'; rr(ctx, x - w / 2, y - h / 2, w, h, 8); ctx.fill(); }, { blur: 16, dx: 6, dy: 10 });
|
||||
ctx.fillStyle = '#8c5528'; rr(ctx, x - w / 2, y - h / 2, w, h, 8); ctx.fill();
|
||||
ctx.fillStyle = '#3a200c'; rr(ctx, x - w / 2 + 10, y - h / 2 + 10, w - 20, h - 20, 4); ctx.fill();
|
||||
ctx.fillStyle = '#5a3216';
|
||||
for (let i = 1; i < 4; i++) ctx.fillRect(x - w / 2 + 10 + i * (w - 20) / 4, y - h / 2 + 10, 3, h - 20);
|
||||
for (let i = 0; i < 14; i++) {
|
||||
ctx.strokeStyle = `rgba(60,30,8,${0.2 + rnd() * 0.2})`; ctx.lineWidth = 1;
|
||||
const yy = y - h / 2 + 2 + rnd() * 8;
|
||||
ctx.beginPath(); ctx.moveTo(x - w / 2 + 4, yy); ctx.lineTo(x + w / 2 - 4, yy + rnd() * 2); ctx.stroke();
|
||||
}
|
||||
// the lid, slid off at an angle
|
||||
ctx.save();
|
||||
ctx.translate(x + 30, y - 52); ctx.rotate(-0.12);
|
||||
shadowed(ctx, () => { ctx.fillStyle = '#9a6030'; rr(ctx, -w / 2, -18, w, 30, 6); ctx.fill(); }, { blur: 10, dx: 4, dy: 7 });
|
||||
ctx.fillStyle = '#a5683a'; rr(ctx, -w / 2, -18, w, 30, 6); ctx.fill();
|
||||
ctx.fillStyle = 'rgba(255,230,190,0.7)';
|
||||
ctx.font = `bold 15px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
ctx.fillText('DOUBLE TWELVE', 0, -3);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// ── room ─────────────────────────────────────────────────────────────────────
|
||||
function paintVignette(ctx) {
|
||||
const v = ctx.createRadialGradient(W * 0.42, H * 0.38, 200, W / 2, H / 2, 1150);
|
||||
v.addColorStop(0, 'rgba(255,214,150,0.10)');
|
||||
v.addColorStop(0.55, 'rgba(0,0,0,0)');
|
||||
v.addColorStop(1, 'rgba(30,10,0,0.55)');
|
||||
ctx.fillStyle = v; ctx.fillRect(0, 0, W, H);
|
||||
}
|
||||
|
||||
function paintProps(ctx, rnd) {
|
||||
paintBox(ctx, rnd);
|
||||
paintMug(ctx);
|
||||
paintPretzels(ctx, rnd);
|
||||
paintPitcher(ctx, rnd);
|
||||
paintCat(ctx, rnd);
|
||||
}
|
||||
|
||||
function bakeRoom(scene) {
|
||||
const rnd = seeded(20261125);
|
||||
const c = canvas(W, H), ctx = c.getContext('2d');
|
||||
paintPlanks(ctx, rnd);
|
||||
paintWear(ctx, rnd);
|
||||
paintDoily(ctx);
|
||||
paintProps(ctx, rnd);
|
||||
paintVignette(ctx);
|
||||
addCanvas(scene, 'mt-room', c);
|
||||
const v = canvas(W, H);
|
||||
paintVignette(v.getContext('2d'));
|
||||
addCanvas(scene, 'mt-vignette', v);
|
||||
const p = canvas(W, H);
|
||||
paintProps(p.getContext('2d'), seeded(20261125));
|
||||
addCanvas(scene, 'mt-props', p);
|
||||
}
|
||||
|
||||
function bakeSun(scene) {
|
||||
// four window panes thrown across the table, soft edged
|
||||
const c = canvas(900, 700), d = c.getContext('2d');
|
||||
d.filter = 'blur(18px)';
|
||||
const pane = (x, y) => {
|
||||
d.beginPath();
|
||||
d.moveTo(x, y); d.lineTo(x + 260, y + 40); d.lineTo(x + 330, y + 300); d.lineTo(x + 70, y + 260); d.closePath();
|
||||
d.fill();
|
||||
};
|
||||
d.fillStyle = 'rgba(255,214,140,0.55)';
|
||||
pane(80, 40); pane(380, 86); pane(150, 340); pane(450, 386);
|
||||
d.filter = 'none';
|
||||
addCanvas(scene, 'mt-sun', c);
|
||||
}
|
||||
|
||||
// ── dominoes ─────────────────────────────────────────────────────────────────
|
||||
const G = 0.6;
|
||||
const PIPS = {
|
||||
0: [],
|
||||
1: [[0, 0]],
|
||||
2: [[-G, -G], [G, G]],
|
||||
3: [[-G, -G], [0, 0], [G, G]],
|
||||
4: [[-G, -G], [G, -G], [-G, G], [G, G]],
|
||||
5: [[-G, -G], [G, -G], [0, 0], [-G, G], [G, G]],
|
||||
6: [[-G, -G], [-G, 0], [-G, G], [G, -G], [G, 0], [G, G]],
|
||||
7: [[-G, -G], [-G, 0], [-G, G], [G, -G], [G, 0], [G, G], [0, 0]],
|
||||
8: [[-G, -G], [-G, 0], [-G, G], [G, -G], [G, 0], [G, G], [0, -G], [0, G]],
|
||||
9: [[-G, -G], [-G, 0], [-G, G], [G, -G], [G, 0], [G, G], [0, -G], [0, G], [0, 0]],
|
||||
};
|
||||
const R4 = [-0.68, -0.23, 0.23, 0.68];
|
||||
PIPS[10] = [...R4.map((y) => [-G, y]), ...R4.map((y) => [G, y]), [0, -0.35], [0, 0.35]];
|
||||
PIPS[11] = [...R4.map((y) => [-G, y]), ...R4.map((y) => [G, y]), [0, -0.5], [0, 0], [0, 0.5]];
|
||||
PIPS[12] = [...R4.map((y) => [-G, y]), ...R4.map((y) => [G, y]), ...R4.map((y) => [0, y])];
|
||||
|
||||
function tileBody(d, w, h, back = false) {
|
||||
const r = h * 0.14;
|
||||
// thickness (the side you see below / right)
|
||||
d.fillStyle = '#c4b28a';
|
||||
rr(d, 1.5, 3, w - 3, h - 4, r); d.fill();
|
||||
const g = d.createLinearGradient(0, 0, w * 0.3, h);
|
||||
g.addColorStop(0, back ? '#f7eedb' : '#fffaf0');
|
||||
g.addColorStop(1, back ? '#e4d5b4' : '#ede2c6');
|
||||
d.fillStyle = g;
|
||||
rr(d, 1, 1, w - 3, h - 5, r); d.fill();
|
||||
d.strokeStyle = 'rgba(255,255,255,0.8)'; d.lineWidth = 1.5;
|
||||
rr(d, 2.5, 2.5, w - 6, h - 8, r * 0.8); d.stroke();
|
||||
d.strokeStyle = 'rgba(120,96,56,0.55)'; d.lineWidth = 1;
|
||||
rr(d, 1, 1, w - 3, h - 5, r); d.stroke();
|
||||
}
|
||||
|
||||
function drawPips(d, cx, cy, s, v, colored) {
|
||||
const pts = PIPS[v] ?? [];
|
||||
const pr = v >= 10 ? s * 0.105 : s * 0.13;
|
||||
const spread = s * 0.33;
|
||||
for (const [px, py] of pts) {
|
||||
const x = cx + px * spread, y = cy + py * spread;
|
||||
d.fillStyle = 'rgba(80,60,30,0.35)';
|
||||
d.beginPath(); d.arc(x + 0.6, y + 0.9, pr + 0.9, 0, Math.PI * 2); d.fill();
|
||||
d.fillStyle = colored ? PIP_COLORS[v] : '#1d1a16';
|
||||
d.beginPath(); d.arc(x, y, pr, 0, Math.PI * 2); d.fill();
|
||||
d.fillStyle = 'rgba(255,255,255,0.35)';
|
||||
d.beginPath(); d.arc(x - pr * 0.3, y - pr * 0.35, pr * 0.35, 0, Math.PI * 2); d.fill();
|
||||
}
|
||||
}
|
||||
|
||||
export const tileKey = (a, b, colored) => `mt-t${colored ? 'c' : 'k'}-${Math.min(a, b)}-${Math.max(a, b)}`;
|
||||
|
||||
/** Bake every face of a set (idempotent per colour scheme). */
|
||||
export function bakeTiles(scene, set, colored) {
|
||||
const w = TEX.w, h = TEX.h;
|
||||
for (let a = 0; a <= set; a++) {
|
||||
for (let b = a; b <= set; b++) {
|
||||
const key = tileKey(a, b, colored);
|
||||
if (scene.textures.exists(key)) continue;
|
||||
const c = canvas(w, h), d = c.getContext('2d');
|
||||
tileBody(d, w, h);
|
||||
// divider groove + brass spinner
|
||||
d.strokeStyle = 'rgba(110,86,50,0.6)'; d.lineWidth = 2;
|
||||
d.beginPath(); d.moveTo(w / 2, h * 0.14); d.lineTo(w / 2, h * 0.8); d.stroke();
|
||||
d.strokeStyle = 'rgba(255,255,255,0.7)'; d.lineWidth = 1;
|
||||
d.beginPath(); d.moveTo(w / 2 + 1.5, h * 0.14); d.lineTo(w / 2 + 1.5, h * 0.8); d.stroke();
|
||||
const sg = d.createRadialGradient(w / 2 - 1, h * 0.47 - 1, 0.5, w / 2, h * 0.47, h * 0.07);
|
||||
sg.addColorStop(0, '#fff2b8'); sg.addColorStop(0.5, '#c89a3a'); sg.addColorStop(1, '#7a5418');
|
||||
d.fillStyle = sg;
|
||||
d.beginPath(); d.arc(w / 2, h * 0.47, h * 0.065, 0, Math.PI * 2); d.fill();
|
||||
const s = h - 6;
|
||||
drawPips(d, w * 0.25, h * 0.47, s, a, colored);
|
||||
drawPips(d, w * 0.75, h * 0.47, s, b, colored);
|
||||
addCanvas(scene, key, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bakeTileBits(scene) {
|
||||
const w = TEX.w, h = TEX.h;
|
||||
const c = canvas(w, h), d = c.getContext('2d');
|
||||
tileBody(d, w, h, true);
|
||||
// a little embossed locomotive
|
||||
d.fillStyle = 'rgba(150,120,70,0.35)';
|
||||
d.save(); d.translate(w / 2, h * 0.47);
|
||||
rr(d, -h * 0.5, -h * 0.16, h * 0.62, h * 0.3, 3); d.fill();
|
||||
rr(d, h * 0.12, -h * 0.26, h * 0.3, h * 0.4, 3); d.fill();
|
||||
d.fillRect(-h * 0.42, -h * 0.3, h * 0.1, h * 0.16);
|
||||
d.beginPath(); d.arc(-h * 0.34, h * 0.2, h * 0.07, 0, 6.28); d.arc(-h * 0.08, h * 0.2, h * 0.07, 0, 6.28); d.arc(h * 0.24, h * 0.2, h * 0.07, 0, 6.28); d.fill();
|
||||
d.restore();
|
||||
addCanvas(scene, 'mt-back', c);
|
||||
// soft shadow (drawn under every tile)
|
||||
const pad = 14;
|
||||
const s = canvas(w + pad * 2, h + pad * 2), sd = s.getContext('2d');
|
||||
sd.filter = 'blur(5px)';
|
||||
sd.fillStyle = 'rgba(40,18,0,0.55)';
|
||||
rr(sd, pad, pad, w - 2, h - 3, h * 0.14); sd.fill();
|
||||
addCanvas(scene, 'mt-tshadow', s);
|
||||
// glow outline
|
||||
const gl = canvas(w + 40, h + 40), gd = gl.getContext('2d');
|
||||
gd.filter = 'blur(6px)';
|
||||
gd.strokeStyle = '#ffffff'; gd.lineWidth = 10;
|
||||
rr(gd, 20, 20, w, h - 4, h * 0.16); gd.stroke();
|
||||
gd.filter = 'none';
|
||||
gd.strokeStyle = 'rgba(255,255,255,0.95)'; gd.lineWidth = 4;
|
||||
rr(gd, 20, 20, w, h - 4, h * 0.16); gd.stroke();
|
||||
addCanvas(scene, 'mt-glow', gl);
|
||||
// drop slot (dashed)
|
||||
const sl = canvas(w + 8, h + 8), sld = sl.getContext('2d');
|
||||
sld.fillStyle = 'rgba(255,248,226,0.28)';
|
||||
rr(sld, 4, 4, w, h - 2, h * 0.16); sld.fill();
|
||||
sld.setLineDash([10, 7]); sld.strokeStyle = 'rgba(255,250,236,0.95)'; sld.lineWidth = 4;
|
||||
rr(sld, 4, 4, w, h - 2, h * 0.16); sld.stroke();
|
||||
addCanvas(scene, 'mt-slot', sl);
|
||||
}
|
||||
|
||||
// ── hub + markers ────────────────────────────────────────────────────────────
|
||||
function bakeHub(scene) {
|
||||
const R = HUB.r, S = (R + 14) * 2 * RES;
|
||||
const c = canvas(S, S), d = c.getContext('2d');
|
||||
d.scale(RES, RES);
|
||||
const cx = R + 14, cy = R + 14;
|
||||
shadowed(d, () => { d.fillStyle = '#b88a52'; d.beginPath(); d.arc(cx, cy, R, 0, Math.PI * 2); d.fill(); }, { blur: 12, dx: 4, dy: 7, alpha: 0.5 });
|
||||
const g = d.createRadialGradient(cx - 18, cy - 18, 6, cx, cy, R);
|
||||
g.addColorStop(0, '#f2d6a6'); g.addColorStop(0.7, '#d4a86c'); g.addColorStop(1, '#a87a44');
|
||||
d.fillStyle = g;
|
||||
d.beginPath(); d.arc(cx, cy, R, 0, Math.PI * 2); d.fill();
|
||||
// turned rings
|
||||
for (let r = R - 3; r > 10; r -= 5) {
|
||||
d.strokeStyle = `rgba(120,78,34,${0.1 + (r % 10 === 0 ? 0.1 : 0)})`; d.lineWidth = 1;
|
||||
d.beginPath(); d.arc(cx, cy, r, 0, Math.PI * 2); d.stroke();
|
||||
}
|
||||
d.strokeStyle = '#c9a046'; d.lineWidth = 3.5;
|
||||
d.beginPath(); d.arc(cx, cy, R - 2, 0, Math.PI * 2); d.stroke();
|
||||
d.strokeStyle = 'rgba(255,240,190,0.7)'; d.lineWidth = 1;
|
||||
d.beginPath(); d.arc(cx, cy, R - 3.5, Math.PI * 1.05, Math.PI * 1.7); d.stroke();
|
||||
// slot notches round the rim
|
||||
for (let k = 0; k < 8; k++) {
|
||||
const a = (k / 8) * Math.PI * 2 + Math.PI / 8;
|
||||
d.save(); d.translate(cx + Math.cos(a) * (R - 11), cy + Math.sin(a) * (R - 11)); d.rotate(a);
|
||||
d.fillStyle = 'rgba(80,46,14,0.6)'; rr(d, -6, -4, 12, 8, 3); d.fill();
|
||||
d.restore();
|
||||
}
|
||||
// centre recess for the engine
|
||||
d.fillStyle = 'rgba(90,52,18,0.55)';
|
||||
rr(d, cx - 40, cy - 22, 80, 44, 8); d.fill();
|
||||
d.strokeStyle = 'rgba(255,230,180,0.5)'; d.lineWidth = 1.2;
|
||||
rr(d, cx - 40, cy - 22, 80, 44, 8); d.stroke();
|
||||
addCanvas(scene, 'mt-hub', c);
|
||||
}
|
||||
|
||||
function bakeEngine(scene, key, col) {
|
||||
const w = 64, h = 34;
|
||||
const c = canvas(w * RES, h * RES), d = c.getContext('2d');
|
||||
d.scale(RES, RES);
|
||||
// wheels
|
||||
d.fillStyle = '#1c1a18';
|
||||
for (const x of [12, 25, 38, 50]) { rr(d, x - 4, 2, 9, 5, 2); d.fill(); rr(d, x - 4, h - 7, 9, 5, 2); d.fill(); }
|
||||
shadowed(d, () => { d.fillStyle = col.base; rr(d, 4, 6, 56, 22, 6); d.fill(); }, { blur: 5, dx: 2, dy: 3, alpha: 0.45 });
|
||||
const g = d.createLinearGradient(0, 6, 0, 28);
|
||||
g.addColorStop(0, col.light); g.addColorStop(1, col.dark);
|
||||
d.fillStyle = g; rr(d, 4, 6, 56, 22, 6); d.fill();
|
||||
// cab at the back (left), boiler bands, smokestack at the front (right)
|
||||
d.fillStyle = col.dark; rr(d, 4, 4, 18, 26, 4); d.fill();
|
||||
d.fillStyle = 'rgba(255,255,255,0.3)'; rr(d, 7, 8, 12, 6, 2); d.fill();
|
||||
d.strokeStyle = '#e8c46a'; d.lineWidth = 1.6;
|
||||
for (const x of [30, 40, 50]) { d.beginPath(); d.moveTo(x, 7); d.lineTo(x, 27); d.stroke(); }
|
||||
d.fillStyle = '#222'; d.beginPath(); d.arc(48, 17, 4.5, 0, Math.PI * 2); d.fill();
|
||||
d.fillStyle = '#e8c46a'; d.beginPath(); d.arc(58, 17, 3, 0, Math.PI * 2); d.fill();
|
||||
d.fillStyle = '#c9a046'; d.beginPath(); d.moveTo(60, 8); d.lineTo(64, 17); d.lineTo(60, 26); d.fill();
|
||||
addCanvas(scene, key, c);
|
||||
}
|
||||
|
||||
// ── paper + wood furniture ───────────────────────────────────────────────────
|
||||
export function bakeCard(scene, key, w, h, { ruled = true, tape = true, tint = '#fbf6ea' } = {}) {
|
||||
const pad = 14;
|
||||
const c = canvas((w + pad * 2) * RES, (h + pad * 2) * RES), d = c.getContext('2d');
|
||||
d.scale(RES, RES);
|
||||
shadowed(d, () => { d.fillStyle = tint; rr(d, pad, pad, w, h, 6); d.fill(); }, { blur: 12, dx: 4, dy: 7, alpha: 0.4 });
|
||||
d.fillStyle = tint; rr(d, pad, pad, w, h, 6); d.fill();
|
||||
if (ruled) {
|
||||
d.strokeStyle = 'rgba(90,130,190,0.28)'; d.lineWidth = 1;
|
||||
for (let y = pad + 34; y < pad + h - 6; y += 22) { d.beginPath(); d.moveTo(pad + 8, y); d.lineTo(pad + w - 8, y); d.stroke(); }
|
||||
d.strokeStyle = 'rgba(210,80,80,0.45)';
|
||||
d.beginPath(); d.moveTo(pad + 8, pad + 26); d.lineTo(pad + w - 8, pad + 26); d.stroke();
|
||||
}
|
||||
if (tape) {
|
||||
d.save(); d.translate(pad + w / 2, pad + 2); d.rotate(-0.04);
|
||||
d.fillStyle = 'rgba(240,228,190,0.75)'; d.fillRect(-36, -9, 72, 18);
|
||||
d.restore();
|
||||
}
|
||||
addCanvas(scene, key, c);
|
||||
}
|
||||
|
||||
function bakePad(scene) {
|
||||
const { w, h } = SCORE_PAD;
|
||||
const pad = 16;
|
||||
const c = canvas((w + pad * 2) * RES, (h + pad * 2) * RES), d = c.getContext('2d');
|
||||
d.scale(RES, RES);
|
||||
shadowed(d, () => { d.fillStyle = '#f7ec9e'; rr(d, pad, pad + 8, w, h - 8, 4); d.fill(); }, { blur: 14, dx: 5, dy: 9 });
|
||||
d.fillStyle = '#f7ec9e'; rr(d, pad, pad + 8, w, h - 8, 4); d.fill();
|
||||
d.strokeStyle = 'rgba(70,110,170,0.4)'; d.lineWidth = 1;
|
||||
for (let y = pad + 60; y < pad + h - 8; y += 26) { d.beginPath(); d.moveTo(pad + 4, y); d.lineTo(pad + w - 4, y); d.stroke(); }
|
||||
d.strokeStyle = 'rgba(200,60,60,0.5)';
|
||||
d.beginPath(); d.moveTo(pad + 40, pad + 30); d.lineTo(pad + 40, pad + h - 6); d.stroke();
|
||||
// spiral
|
||||
for (let x = pad + 14; x < pad + w - 8; x += 18) {
|
||||
d.strokeStyle = '#8a8a90'; d.lineWidth = 3;
|
||||
d.beginPath(); d.ellipse(x, pad + 10, 4, 9, 0, 0, Math.PI * 2); d.stroke();
|
||||
d.fillStyle = '#3a2a1a'; d.beginPath(); d.arc(x, pad + 18, 2.5, 0, Math.PI * 2); d.fill();
|
||||
}
|
||||
addCanvas(scene, 'mt-pad', c);
|
||||
// the pencil (its own sprite so it can scribble)
|
||||
const pc = canvas(220 * RES, 22 * RES), p = pc.getContext('2d');
|
||||
p.scale(RES, RES);
|
||||
p.fillStyle = '#f2b52c'; p.fillRect(30, 4, 160, 14);
|
||||
p.fillStyle = 'rgba(255,255,255,0.35)'; p.fillRect(30, 5, 160, 3);
|
||||
p.fillStyle = '#c8c8cc'; p.fillRect(190, 3, 12, 16);
|
||||
p.fillStyle = '#e8828a'; rr(p, 200, 3, 18, 16, 4); p.fill();
|
||||
p.fillStyle = '#ecc89a'; p.beginPath(); p.moveTo(30, 4); p.lineTo(6, 11); p.lineTo(30, 18); p.fill();
|
||||
p.fillStyle = '#333'; p.beginPath(); p.moveTo(12, 9.3); p.lineTo(2, 11); p.lineTo(12, 12.7); p.fill();
|
||||
addCanvas(scene, 'mt-pencil', pc);
|
||||
}
|
||||
|
||||
function bakeRack(scene) {
|
||||
const { w, h } = RACK;
|
||||
const pad = 14;
|
||||
const c = canvas((w + pad * 2) * RES, (h + pad * 2) * RES), d = c.getContext('2d');
|
||||
d.scale(RES, RES);
|
||||
const rnd = seeded(77);
|
||||
shadowed(d, () => { d.fillStyle = '#6a3a18'; rr(d, pad, pad + 20, w, h - 20, 12); d.fill(); }, { blur: 16, dx: 5, dy: 10 });
|
||||
const g = d.createLinearGradient(0, pad + 20, 0, pad + h);
|
||||
g.addColorStop(0, '#8a4e22'); g.addColorStop(0.5, '#74401a'); g.addColorStop(1, '#4e2a10');
|
||||
d.fillStyle = g; rr(d, pad, pad + 20, w, h - 20, 12); d.fill();
|
||||
for (let i = 0; i < 30; i++) {
|
||||
d.strokeStyle = `rgba(40,18,4,${0.12 + rnd() * 0.18})`; d.lineWidth = 1 + rnd();
|
||||
const y = pad + 24 + rnd() * (h - 28);
|
||||
d.beginPath(); d.moveTo(pad + 6, y); d.bezierCurveTo(pad + w * 0.3, y + 3, pad + w * 0.6, y - 3, pad + w - 6, y + rnd() * 2); d.stroke();
|
||||
}
|
||||
// the ledge the tiles lean on
|
||||
d.fillStyle = '#9a5c2a'; rr(d, pad + 8, pad + h - 26, w - 16, 16, 6); d.fill();
|
||||
d.fillStyle = 'rgba(255,220,170,0.35)'; d.fillRect(pad + 14, pad + h - 25, w - 28, 2);
|
||||
d.fillStyle = 'rgba(255,220,170,0.25)'; rr(d, pad + 4, pad + 22, w - 8, 3, 2); d.fill();
|
||||
addCanvas(scene, 'mt-rack', c);
|
||||
// the tiny rack on opponents' seat cards
|
||||
const mc = canvas(240 * RES, 30 * RES), md = mc.getContext('2d');
|
||||
md.scale(RES, RES);
|
||||
md.fillStyle = '#6e3c1a'; rr(md, 0, 8, 240, 20, 5); md.fill();
|
||||
md.fillStyle = '#9a5c2a'; rr(md, 3, 20, 234, 7, 3); md.fill();
|
||||
addCanvas(scene, 'mt-mini', mc);
|
||||
}
|
||||
|
||||
function bakeBits(scene) {
|
||||
const m = canvas(16, 16), md = m.getContext('2d');
|
||||
const mg = md.createRadialGradient(8, 8, 0, 8, 8, 8);
|
||||
mg.addColorStop(0, 'rgba(255,240,200,1)'); mg.addColorStop(1, 'rgba(255,240,200,0)');
|
||||
md.fillStyle = mg; md.fillRect(0, 0, 16, 16);
|
||||
addCanvas(scene, 'mt-mote', m);
|
||||
const st = canvas(64, 64), sd = st.getContext('2d');
|
||||
const sg = sd.createRadialGradient(32, 32, 0, 32, 32, 32);
|
||||
sg.addColorStop(0, 'rgba(255,255,255,0.5)'); sg.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
sd.fillStyle = sg; sd.fillRect(0, 0, 64, 64);
|
||||
addCanvas(scene, 'mt-steam', st);
|
||||
const sp = canvas(24, 24), spd = sp.getContext('2d');
|
||||
const spg = spd.createRadialGradient(12, 12, 0, 12, 12, 12);
|
||||
spg.addColorStop(0, 'rgba(255,255,255,1)'); spg.addColorStop(0.4, 'rgba(255,240,200,0.8)'); spg.addColorStop(1, 'rgba(255,220,150,0)');
|
||||
spd.fillStyle = spg; spd.fillRect(0, 0, 24, 24);
|
||||
addCanvas(scene, 'mt-spark', sp);
|
||||
// end badge: a little wooden token
|
||||
const b = canvas(60, 60), bd = b.getContext('2d');
|
||||
shadowed(bd, () => { bd.fillStyle = '#fbf4e2'; bd.beginPath(); bd.arc(30, 30, 22, 0, Math.PI * 2); bd.fill(); }, { blur: 5, dx: 2, dy: 3, alpha: 0.5 });
|
||||
bd.fillStyle = '#fbf4e2'; bd.beginPath(); bd.arc(30, 30, 22, 0, Math.PI * 2); bd.fill();
|
||||
addCanvas(scene, 'mt-badge', b);
|
||||
}
|
||||
|
||||
let baked = false;
|
||||
export async function prepareMexicanTrainArt(scene, { set = 12, colored = true } = {}) {
|
||||
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('mt-room')) {
|
||||
bakeRoom(scene); bakeSun(scene); bakeTail(scene); bakeTileBits(scene); bakeHub(scene);
|
||||
SEAT.forEach((col, i) => bakeEngine(scene, `mt-engine-${i}`, col));
|
||||
bakeEngine(scene, 'mt-engine-m', MEX);
|
||||
bakeCard(scene, 'mt-card-status', STATUS.w, STATUS.h);
|
||||
bakeCard(scene, 'mt-card-talk', TALK.w, TALK.h);
|
||||
for (const [k, r] of Object.entries(SEAT_CARDS)) bakeCard(scene, `mt-seat-${k}`, r.w, r.h, { ruled: false, tape: k !== 'human', tint: '#fcf7ec' });
|
||||
bakeCard(scene, 'mt-card-buttons', 404, 152, { ruled: false, tape: false, tint: '#f3e6cc' });
|
||||
bakePad(scene); bakeRack(scene); bakeBits(scene);
|
||||
baked = true;
|
||||
}
|
||||
bakeTiles(scene, set, colored);
|
||||
}
|
||||
void H;
|
||||
|
|
@ -0,0 +1,176 @@
|
|||
// MexicanTrainDialogs.js — recipe-card pop-ups with a gingham border. Each
|
||||
// opener returns { close() } and swallows clicks beneath it.
|
||||
|
||||
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { DISPLAY_FONT, SERIF, HAND_FONT } from './MexicanTrainArt.js';
|
||||
|
||||
const RED = 0xc23b2e;
|
||||
export const INK = '#3a2a18';
|
||||
|
||||
export function frame(scene, x, y, w, h, depth) {
|
||||
const g = scene.add.graphics().setDepth(depth);
|
||||
g.fillStyle(0x000000, 0.4).fillRoundedRect(x + 6, y + 10, w, h, 14);
|
||||
g.fillStyle(0xffffff, 1).fillRoundedRect(x, y, w, h, 14);
|
||||
// gingham: red bands both ways over white
|
||||
const cell = 14;
|
||||
g.fillStyle(RED, 0.45);
|
||||
for (let xx = x; xx < x + w; xx += cell * 2) g.fillRect(xx, y, Math.min(cell, x + w - xx), h);
|
||||
for (let yy = y; yy < y + h; yy += cell * 2) g.fillRect(x, yy, w, Math.min(cell, y + h - yy));
|
||||
g.fillStyle(0xfbf6ea, 1).fillRoundedRect(x + 22, y + 22, w - 44, h - 44, 8);
|
||||
g.lineStyle(2, 0x9a3a2a, 0.6).strokeRoundedRect(x + 22, y + 22, w - 44, h - 44, 8);
|
||||
g.lineStyle(1, 0x5a82c0, 0.25);
|
||||
for (let yy = y + 96; yy < y + h - 30; yy += 28) g.lineBetween(x + 34, yy, x + w - 34, yy);
|
||||
return g;
|
||||
}
|
||||
|
||||
export function blocker(scene, depth, alpha = 0) {
|
||||
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x140a02, alpha).setDepth(depth).setInteractive();
|
||||
}
|
||||
|
||||
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 = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' };
|
||||
const SETS = { 12: 'Double-12', 9: 'Double-9', 6: 'Double-6' };
|
||||
|
||||
export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewGame, onLeave, onClose }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.5)];
|
||||
const w = 1080, 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(scene.add.text(x + w / 2, y + 62, 'Kitchen Table Rules', { fontFamily: DISPLAY_FONT, fontSize: '34px', color: '#9a2a1e' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
let hRef = null;
|
||||
const cycle = (k, order) => onChange(k, order[(order.indexOf(settings[k]) + 1) % order.length]);
|
||||
const left = [
|
||||
['TABLE', null],
|
||||
[() => `Opponent speed: ${PACE[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'fast'])],
|
||||
[() => `Coloured pips: ${onOff(settings.colored)}`, () => onChange('colored', !settings.colored)],
|
||||
[() => `Show where tiles fit: ${onOff(settings.previews)}`, () => onChange('previews', !settings.previews)],
|
||||
[() => `Auto-draw when stuck: ${onOff(settings.autoDraw)}`, () => onChange('autoDraw', !settings.autoDraw)],
|
||||
[() => `Auto-pass after a dud draw: ${onOff(settings.autoPass)}`, () => onChange('autoPass', !settings.autoPass)],
|
||||
[() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)],
|
||||
[() => `Birds & the lawnmower: ${onOff(settings.birds)}`, () => onChange('birds', !settings.birds)],
|
||||
[() => `Kitchen clock: ${onOff(settings.clock)}`, () => onChange('clock', !settings.clock)],
|
||||
];
|
||||
const right = [
|
||||
['HOUSE RULES (next game)', null],
|
||||
[() => `Domino set: ${SETS[settings.set]}`, () => cycle('set', [12, 9, 6])],
|
||||
[() => `Match: ${settings.mode === 'descent' ? 'one round per engine' : `first to ${settings.target}`}`, () => {
|
||||
const order = ['descent:0', 'points:100', 'points:200', 'points:300', 'points:500'];
|
||||
const cur = settings.mode === 'descent' ? 'descent:0' : `points:${settings.target}`;
|
||||
const [m, t] = order[(order.indexOf(cur) + 1) % order.length].split(':');
|
||||
onChange('mode', m);
|
||||
if (m === 'points') onChange('target', Number(t));
|
||||
}],
|
||||
[() => `First turn: lay out your whole train: ${onOff(settings.opening)}`, () => onChange('opening', !settings.opening)],
|
||||
[() => `Doubles: ${settings.doubles === 'cover' ? 'must be covered' : 'bonus play'}`, () => onChange('doubles', settings.doubles === 'cover' ? 'relaxed' : 'cover')],
|
||||
[() => `Double-blank counts 50: ${onOff(settings.blank50)}`, () => onChange('blank50', !settings.blank50)],
|
||||
[() => `Knock on your last tile: ${onOff(settings.knock)}`, () => onChange('knock', !settings.knock)],
|
||||
];
|
||||
const col = (rows, cx) => rows.forEach(([label, fn], i) => {
|
||||
const yy = y + 130 + i * 56;
|
||||
if (!fn) { objs.push(scene.add.text(cx, yy, label, { fontFamily: SERIF, fontSize: '16px', fontStyle: 'bold', color: '#9a2a1e' }).setOrigin(0.5).setDepth(depth + 1)); return; }
|
||||
const btn = new Button(scene, cx, yy, label(), () => { fn(); btn.setLabel(label()); }, { width: 460, height: 44, fontSize: 15, bg: 0x6a3a18 }).setDepth(depth + 2);
|
||||
objs.push(btn);
|
||||
});
|
||||
col(left, x + 280);
|
||||
col(right, x + w - 280);
|
||||
const by = y + h - 92;
|
||||
const bottom = [
|
||||
['Resume', () => hRef.close(), 0x2e64ad],
|
||||
['How to Play', () => onRules(), 0x3a8f47],
|
||||
['New Game', () => { hRef.close(); onNewGame(); }, 0x8a5a1e],
|
||||
['Leave Table', () => { hRef.close(); onLeave(); }, 0x9a2a1e],
|
||||
];
|
||||
bottom.forEach(([label, fn, bg], i) => objs.push(new Button(scene, x + 150 + i * 260, by, label, fn, { width: 230, height: 50, fontSize: 18, bg }).setDepth(depth + 2)));
|
||||
objs.push(scene.add.text(x + w / 2, y + h - 40, 'Keys: click / drag tiles · 1–5 pick a train · D draw · P pass · E end turn · H hint · Z undo · K knock · S sort · Esc menu', {
|
||||
fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#5a4a32', align: 'center',
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
hRef = handle(objs, 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 = 560, h = 300;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(scene.add.text(x + w / 2, y + 70, heading, { fontFamily: DISPLAY_FONT, fontSize: '28px', color: '#9a2a1e' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(x + w / 2, y + 138, text, { fontFamily: SERIF, fontSize: '18px', color: INK, align: 'center', wordWrap: { width: w - 100 } }).setOrigin(0.5).setDepth(depth + 1));
|
||||
let hRef = null;
|
||||
objs.push(new Button(scene, x + w / 2 - 120, y + h - 70, yes, () => { hRef.close(); onYes?.(); }, { width: 210, height: 46, fontSize: 18, bg: 0x9a2a1e }).setDepth(depth + 2));
|
||||
objs.push(new Button(scene, x + w / 2 + 120, y + h - 70, no, () => { hRef.close(); onNo?.(); }, { width: 210, height: 46, fontSize: 18, bg: 0x2e64ad }).setDepth(depth + 2));
|
||||
hRef = handle(objs);
|
||||
return hRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* The score pad, opened up: one row per round, a column per player, the
|
||||
* round winner circled, running totals at the bottom.
|
||||
*/
|
||||
export function openScorePad(scene, { gs, names, colors, depth, title = 'The Score Pad', button = 'Close', onButton, onClose, highlightLast = false }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.55)];
|
||||
const n = gs.n;
|
||||
const total = gs.opts.mode === 'descent' ? gs.opts.set + 1 : null;
|
||||
const rows = Math.max(gs.history.length, total ?? gs.history.length);
|
||||
const rowH = Math.min(36, Math.floor(520 / Math.max(1, rows)));
|
||||
const w = Math.max(640, 260 + n * 160), h = 260 + rows * rowH;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = Math.max(16, GAME_HEIGHT / 2 - h / 2);
|
||||
const g = scene.add.graphics().setDepth(depth);
|
||||
objs.push(g);
|
||||
g.fillStyle(0x000000, 0.4).fillRoundedRect(x + 8, y + 12, w, h, 8);
|
||||
g.fillStyle(0xf7ec9e, 1).fillRoundedRect(x, y, w, h, 8);
|
||||
g.lineStyle(1, 0x4670aa, 0.35);
|
||||
for (let yy = y + 110; yy < y + h - 20; yy += rowH) g.lineBetween(x + 10, yy, x + w - 10, yy);
|
||||
g.lineStyle(2, 0xc84040, 0.55).lineBetween(x + 170, y + 70, x + 170, y + h - 14);
|
||||
for (let xx = x + 24; xx < x + w - 10; xx += 22) { g.lineStyle(3, 0x8a8a90, 1).strokeEllipse(xx, y + 6, 8, 18); }
|
||||
objs.push(scene.add.text(x + w / 2, y + 42, title, { fontFamily: HAND_FONT, fontSize: '40px', color: '#1d3e78' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
const colX = (i) => x + 250 + (n > 1 ? (i * (w - 320)) / (n - 1) : 0);
|
||||
for (let i = 0; i < n; i++) {
|
||||
objs.push(scene.add.text(colX(i), y + 90, names[i], { fontFamily: HAND_FONT, fontSize: '26px', color: colors[i] }).setOrigin(0.5).setDepth(depth + 1));
|
||||
}
|
||||
for (let r = 0; r < rows; r++) {
|
||||
const yy = y + 110 + r * rowH + rowH / 2;
|
||||
const hv = gs.opts.mode === 'descent' ? gs.opts.set - r : gs.history[r]?.hub;
|
||||
objs.push(scene.add.text(x + 30, yy, hv != null ? `${hv}-${hv}` : '', { fontFamily: HAND_FONT, fontSize: `${Math.min(26, rowH - 6)}px`, color: '#5a4a32' }).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
const hr = gs.history[r];
|
||||
if (!hr) continue;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const t = scene.add.text(colX(i), yy, hr.scores[i] === 0 && hr.winner === i ? '0 ✓' : String(hr.scores[i]), {
|
||||
fontFamily: HAND_FONT, fontSize: `${Math.min(28, rowH - 4)}px`, color: '#2a2a3a',
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
objs.push(t);
|
||||
if (hr.winner === i) {
|
||||
const c = scene.add.graphics().setDepth(depth + 1);
|
||||
c.lineStyle(2.5, 0xc23b2e, 0.85).strokeEllipse(colX(i), yy, 64, rowH - 2);
|
||||
objs.push(c);
|
||||
}
|
||||
if (highlightLast && r === gs.history.length - 1) {
|
||||
t.setAlpha(0);
|
||||
scene.tweens.add({ targets: t, alpha: 1, delay: 200 + i * 260, duration: 260 });
|
||||
}
|
||||
}
|
||||
}
|
||||
const ty = y + 110 + rows * rowH + 34;
|
||||
g.lineStyle(2.5, 0x2a2a3a, 0.8).lineBetween(x + 180, ty - 22, x + w - 20, ty - 22);
|
||||
objs.push(scene.add.text(x + 30, ty, 'Total', { fontFamily: HAND_FONT, fontSize: '28px', color: '#5a4a32' }).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
const min = Math.min(...gs.players.map((p) => p.score));
|
||||
for (let i = 0; i < n; i++) {
|
||||
objs.push(scene.add.text(colX(i), ty, String(gs.players[i].score), { fontFamily: HAND_FONT, fontSize: '32px', color: gs.players[i].score === min ? '#1e7a3a' : '#2a2a3a' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
}
|
||||
let hRef = null;
|
||||
objs.push(new Button(scene, x + w / 2, y + h + 40, button, () => { hRef.close(); onButton?.(); }, { width: 240, height: 50, fontSize: 20, bg: 0x2e64ad }).setDepth(depth + 2));
|
||||
hRef = handle(objs, onClose);
|
||||
return hRef;
|
||||
}
|
||||
|
||||
export function toast(scene, text, { depth, x = GAME_WIDTH / 2, y = 168, ms = 2200 } = {}) {
|
||||
const t = scene.add.text(x, y, text, { fontFamily: SERIF, fontSize: '19px', color: INK, backgroundColor: '#fbf6ea', padding: { x: 18, y: 10 } }).setOrigin(0.5).setDepth(depth).setAlpha(0);
|
||||
scene.tweens.add({ targets: t, alpha: 1, duration: 200 });
|
||||
scene.tweens.add({ targets: t, alpha: 0, delay: ms, duration: 400, onComplete: () => t.destroy() });
|
||||
return t;
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
// MexicanTrainEndScreen.js — the final tally on a recipe card: places (lowest
|
||||
// total wins), a stats table per seat, and a chart of everyone's running total
|
||||
// round by round.
|
||||
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
|
||||
import { DISPLAY_FONT, SERIF, HAND_FONT, PRINT_FONT, SEAT } from './MexicanTrainArt.js';
|
||||
import { frame } from './MexicanTrainDialogs.js';
|
||||
import { rankings, getWinners } from './MexicanTrainLogic.js';
|
||||
|
||||
const PLACE = ['1st', '2nd', '3rd', '4th'];
|
||||
|
||||
export function openEndScreen(scene, { gs, names, depth, onPlayAgain, onMenu }) {
|
||||
const objs = [];
|
||||
const w = 1140, h = 820;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
objs.push(scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x140a02, 0.5).setDepth(depth - 1).setInteractive());
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
const order = rankings(gs);
|
||||
const winners = getWinners(gs);
|
||||
const youWon = winners.includes(0);
|
||||
const head = youWon ? (winners.length > 1 ? 'A tie at the top — you share it!' : 'Lowest score — you win!') : `${names[order[0]]} wins the match`;
|
||||
objs.push(scene.add.text(x + w / 2, y + 66, head, { fontFamily: DISPLAY_FONT, fontSize: '36px', color: youWon ? '#2b7a3a' : '#9a2a1e' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
|
||||
// places
|
||||
const px = x + 70, py = y + 120;
|
||||
order.forEach((i, k) => {
|
||||
const yy = py + k * 54;
|
||||
const tie = k > 0 && gs.players[i].score === gs.players[order[k - 1]].score;
|
||||
objs.push(scene.add.text(px, yy, tie ? '=' : PLACE[k], { fontFamily: DISPLAY_FONT, fontSize: '26px', color: k === 0 || winners.includes(i) ? '#c8901a' : '#5a4a32' }).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(px + 78, yy, i === 0 ? 'You' : names[i], { fontFamily: HAND_FONT, fontSize: '32px', color: SEAT[i].ink }).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(px + 400, yy, `${gs.players[i].score}`, { fontFamily: HAND_FONT, fontSize: '34px', color: '#2a2a3a' }).setOrigin(1, 0.5).setDepth(depth + 1));
|
||||
});
|
||||
|
||||
// stats
|
||||
const rows = [
|
||||
['Rounds won', (s) => s.roundsWon],
|
||||
['Went out', (s) => s.outs],
|
||||
['Tiles played', (s) => s.played],
|
||||
['Doubles laid', (s) => s.doubles],
|
||||
['Doubles covered', (s) => s.covered],
|
||||
['Tiles drawn', (s) => s.drawn],
|
||||
['Times marked open', (s) => s.passes],
|
||||
['Longest own train', (s) => s.longest],
|
||||
];
|
||||
const tx = x + 70, ty = y + 120 + gs.n * 54 + 30;
|
||||
const colW = 92;
|
||||
order.forEach((i, k) => objs.push(scene.add.text(tx + 300 + k * colW, ty, (i === 0 ? 'YOU' : names[i].toUpperCase()).slice(0, 8), { fontFamily: PRINT_FONT, fontSize: '13px', color: SEAT[i].ink }).setOrigin(0.5).setDepth(depth + 1)));
|
||||
rows.forEach(([label, fn], r) => {
|
||||
const yy = ty + 30 + r * 29;
|
||||
objs.push(scene.add.text(tx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: '#3a2a18' }).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
order.forEach((i, k) => objs.push(scene.add.text(tx + 300 + k * colW, yy, String(fn(gs.stats[i])), { fontFamily: SERIF, fontSize: '16px', color: SEAT[i].ink }).setOrigin(0.5).setDepth(depth + 1)));
|
||||
});
|
||||
|
||||
// running totals chart
|
||||
const cx0 = x + 690, cy0 = y + 140, cw = 380, ch = 470;
|
||||
const g = scene.add.graphics().setDepth(depth + 1);
|
||||
objs.push(g);
|
||||
g.fillStyle(0xffffff, 0.6).fillRect(cx0, cy0, cw, ch);
|
||||
g.lineStyle(1, 0x4670aa, 0.22);
|
||||
for (let k = 1; k < 5; k++) g.lineBetween(cx0, cy0 + (ch * k) / 5, cx0 + cw, cy0 + (ch * k) / 5);
|
||||
g.lineStyle(1.5, 0x3a2a18, 0.6).strokeRect(cx0, cy0, cw, ch);
|
||||
const hist = gs.history;
|
||||
const maxT = Math.max(1, ...hist.flatMap((r) => r.totals));
|
||||
const steps = Math.max(1, hist.length);
|
||||
for (let i = 0; i < gs.n; i++) {
|
||||
g.lineStyle(3.5, SEAT[i].hex, 0.95);
|
||||
g.beginPath();
|
||||
g.moveTo(cx0, cy0 + ch);
|
||||
hist.forEach((r, k) => g.lineTo(cx0 + ((k + 1) / steps) * cw, cy0 + ch - (r.totals[i] / maxT) * ch));
|
||||
g.strokePath();
|
||||
hist.forEach((r, k) => { if (r.winner === i) g.fillStyle(SEAT[i].hex, 1).fillCircle(cx0 + ((k + 1) / steps) * cw, cy0 + ch - (r.totals[i] / maxT) * ch, 4.5); });
|
||||
}
|
||||
objs.push(scene.add.text(cx0 + cw / 2, cy0 - 18, 'Running totals, round by round (dots: round won)', { fontFamily: PRINT_FONT, fontSize: '12px', color: '#3a2a18' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(cx0 - 8, cy0, String(maxT), { fontFamily: SERIF, fontSize: '12px', color: '#5a4a32' }).setOrigin(1, 0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(cx0 - 8, cy0 + ch, '0', { fontFamily: SERIF, fontSize: '12px', color: '#5a4a32' }).setOrigin(1, 0.5).setDepth(depth + 1));
|
||||
|
||||
const by = y + h - 74;
|
||||
objs.push(new Button(scene, x + w / 2 - 140, by, 'Play Again', () => { close(); onPlayAgain(); }, { width: 250, height: 52, fontSize: 20, bg: 0x3a8f47 }).setDepth(depth + 2));
|
||||
objs.push(new Button(scene, x + w / 2 + 140, by, 'Leave Table', () => { close(); onMenu(); }, { width: 250, height: 52, fontSize: 20, bg: 0x2e64ad }).setDepth(depth + 2));
|
||||
let closed = false;
|
||||
function close() { if (closed) return; closed = true; objs.forEach((o) => o.destroy()); }
|
||||
return { close, objs };
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,220 @@
|
|||
// MexicanTrainHud.js — the paper and wood around the table: a card per seat
|
||||
// (portrait, name, skill, a little rack of tile backs, total, OPEN stamp,
|
||||
// last-tile knock), the status card, the table-talk card, the button board,
|
||||
// the score pad prop with its pencil, and speech bubbles.
|
||||
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
|
||||
import {
|
||||
SEAT_CARDS, STATUS, TALK, BUTTONS, BTN, BUTTONS_BOX, SCORE_PAD, seatPlaces,
|
||||
} from './MexicanTrainLayout.js';
|
||||
import { DISPLAY_FONT, SERIF, HAND_FONT, PRINT_FONT, SEAT, colorOf } from './MexicanTrainArt.js';
|
||||
import { handPips, roundsTotal } from './MexicanTrainLogic.js';
|
||||
|
||||
function parts(place) {
|
||||
const r = SEAT_CARDS[place];
|
||||
if (place === 'top') {
|
||||
return {
|
||||
portrait: { x: r.x + 58, y: r.y + 60, r: 40 }, name: { x: r.x + 112, y: r.y + 30 }, skill: { x: r.x + 112, y: r.y + 56 },
|
||||
score: { x: r.x + 112, y: r.y + 88 }, mini: { x: r.x + 268, y: r.y + 30, w: 236 }, count: { x: r.x + 386, y: r.y + 86 },
|
||||
tag: { x: r.x + 470, y: r.y + 20 }, bubble: { x: r.x + 110, y: r.y + r.h + 14, w: 300, h: 66, up: true },
|
||||
};
|
||||
}
|
||||
if (place === 'human') {
|
||||
return {
|
||||
portrait: { x: r.x + 62, y: r.y + 76, r: 46 }, name: { x: r.x + 126, y: r.y + 34 }, skill: null,
|
||||
score: { x: r.x + 126, y: r.y + 74 }, inhand: { x: r.x + 126, y: r.y + 112 }, tag: { x: r.x + 340, y: r.y + 30 },
|
||||
};
|
||||
}
|
||||
const right = place === 'right';
|
||||
return {
|
||||
portrait: { x: r.x + 58, y: r.y + 62, r: 40 }, name: { x: r.x + 110, y: r.y + 36 }, skill: { x: r.x + 110, y: r.y + 62 },
|
||||
score: { x: r.x + 110, y: r.y + 94 }, mini: { x: r.x + 14, y: r.y + 124, w: 240 }, count: { x: r.x + r.w / 2, y: r.y + 182 },
|
||||
tag: { x: r.x + 210, y: r.y + 128 },
|
||||
bubble: right ? { x: r.x - 300, y: r.y + 30, w: 286, h: 70, side: 'right' } : { x: r.x + r.w + 14, y: r.y + 30, w: 286, h: 70, side: 'left' },
|
||||
};
|
||||
}
|
||||
|
||||
export class Hud {
|
||||
constructor(scene, depth, { n, names, skills, opponents, onButton, onPad }) {
|
||||
this.scene = scene;
|
||||
this.depth = depth;
|
||||
this.n = n;
|
||||
this.names = names;
|
||||
this.skills = skills;
|
||||
this.opponents = opponents;
|
||||
this.onButton = onButton;
|
||||
this.onPad = onPad;
|
||||
this.places = seatPlaces(n);
|
||||
this.seats = [];
|
||||
this.buttons = {};
|
||||
this.bubbles = {};
|
||||
}
|
||||
|
||||
build() {
|
||||
const s = this.scene, D = this.depth;
|
||||
this.places.forEach((place, i) => {
|
||||
const r = SEAT_CARDS[place];
|
||||
const P = parts(place);
|
||||
const col = SEAT[i];
|
||||
s.add.image(r.x - 14, r.y - 14, `mt-seat-${place}`).setOrigin(0).setScale(0.5).setDepth(D);
|
||||
const stripe = s.add.graphics().setDepth(D + 1);
|
||||
stripe.fillStyle(col.hex, 1).fillRoundedRect(r.x + 6, r.y + 6, r.w - 12, 7, 3);
|
||||
const glow = s.add.graphics().setDepth(D - 1);
|
||||
s.add.circle(P.portrait.x, P.portrait.y, P.portrait.r + 5, col.hex, 1).setDepth(D + 1);
|
||||
const portrait = i === 0
|
||||
? createPlayerPortrait(s, P.portrait.x, P.portrait.y, P.portrait.r, D + 2, 'MexicanTrainGame')
|
||||
: createOpponentPortrait(s, this.opponents[i] ?? { id: 'bot', spriteIndex: 0 }, P.portrait.x, P.portrait.y, P.portrait.r, D + 2);
|
||||
const nm = i === 0 ? 'You' : (this.names[i].length > 12 ? this.names[i].slice(0, 11) + '…' : this.names[i]);
|
||||
s.add.text(P.name.x, P.name.y, nm, { fontFamily: DISPLAY_FONT, fontSize: '24px', color: col.ink }).setOrigin(0, 0.5).setDepth(D + 1);
|
||||
if (P.skill) {
|
||||
const k = this.skills[i] ?? 3;
|
||||
s.add.text(P.skill.x, P.skill.y, `${'●'.repeat(k)}${'○'.repeat(5 - k)} skill`, { fontFamily: SERIF, fontSize: '13px', color: '#8a6a3a' }).setOrigin(0, 0.5).setDepth(D + 1);
|
||||
}
|
||||
const score = s.add.text(P.score.x, P.score.y, '', { fontFamily: HAND_FONT, fontSize: '28px', color: '#2a2a3a' }).setOrigin(0, 0.5).setDepth(D + 1);
|
||||
let mini = null, backs = null, count = null, inhand = null;
|
||||
if (P.mini) {
|
||||
mini = s.add.image(P.mini.x, P.mini.y, 'mt-mini').setOrigin(0).setScale(P.mini.w / 480, 0.5).setDepth(D + 1);
|
||||
backs = s.add.graphics().setDepth(D + 2);
|
||||
count = s.add.text(P.count.x, P.count.y, '', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#5a4a32' }).setOrigin(0.5).setDepth(D + 1);
|
||||
}
|
||||
if (P.inhand) inhand = s.add.text(P.inhand.x, P.inhand.y, '', { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#5a4a32' }).setOrigin(0, 0.5).setDepth(D + 1);
|
||||
const tag = s.add.text(P.tag.x, P.tag.y, 'OPEN', { fontFamily: DISPLAY_FONT, fontSize: '22px', color: '#c23b2e', stroke: '#fbf6ea', strokeThickness: 3 })
|
||||
.setOrigin(0.5).setRotation(-0.16).setDepth(D + 3).setVisible(false);
|
||||
const knock = s.add.text(P.tag.x, P.tag.y + (place === 'human' ? 34 : 26), '✊ last tile', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'bold', color: '#fbf6ea', backgroundColor: '#8a5a1e', padding: { x: 6, y: 2 } })
|
||||
.setOrigin(0.5).setDepth(D + 3).setVisible(false);
|
||||
this.seats.push({ place, P, r, col, glow, portrait, score, mini, backs, count, inhand, tag, knock });
|
||||
});
|
||||
|
||||
// status + talk
|
||||
s.add.image(STATUS.x - 14, STATUS.y - 14, 'mt-card-status').setOrigin(0).setScale(0.5).setDepth(D);
|
||||
this.status = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 44, '', { fontFamily: DISPLAY_FONT, fontSize: '26px', color: '#2a3e6e', align: 'center', wordWrap: { width: STATUS.w - 30 } }).setOrigin(0.5).setDepth(D + 1);
|
||||
this.sub = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 88, '', { fontFamily: SERIF, fontSize: '15px', color: '#3a2a18', align: 'center', wordWrap: { width: STATUS.w - 36 }, lineSpacing: 2 }).setOrigin(0.5).setDepth(D + 1);
|
||||
s.add.image(TALK.x - 14, TALK.y - 14, 'mt-card-talk').setOrigin(0).setScale(0.5).setDepth(D);
|
||||
s.add.text(TALK.x + 16, TALK.y + 14, 'ROUND THE TABLE', { fontFamily: PRINT_FONT, fontSize: '12px', color: '#8a6a3a' }).setOrigin(0, 0.5).setDepth(D + 1);
|
||||
this.talk = [0, 1, 2, 3].map((i) => s.add.text(TALK.x + 18, TALK.y + 38 + i * 22, '', { fontFamily: SERIF, fontSize: '15px', color: '#3a2a18' }).setOrigin(0, 0.5).setDepth(D + 1));
|
||||
|
||||
// buttons
|
||||
s.add.image(BUTTONS_BOX.x - 14, BUTTONS_BOX.y - 14, 'mt-card-buttons').setOrigin(0).setScale(0.5).setDepth(D);
|
||||
const label = { hint: 'Hint (H)', undo: 'Undo (Z)', end: 'End Turn', knock: 'Knock (K)', sort: 'Sort (S)', menu: 'Menu' };
|
||||
const bg = { hint: 0x2e64ad, undo: 0x8a5a1e, end: 0x3a8f47, knock: 0x6a3a18, sort: 0x6a3a18, menu: 0x5a2a14 };
|
||||
for (const [k, b] of Object.entries(BUTTONS)) {
|
||||
this.buttons[k] = new Button(s, b.x, b.y, label[k], () => this.onButton(k), { width: BTN.w, height: BTN.h, fontSize: 15, bg: bg[k] }).setDepth(D + 3);
|
||||
if (k !== 'menu' && k !== 'sort') this.buttons[k].setEnabled(false);
|
||||
}
|
||||
|
||||
// the score pad
|
||||
const sp = SCORE_PAD;
|
||||
s.add.image(sp.x - 16, sp.y - 16, 'mt-pad').setOrigin(0).setScale(0.5).setDepth(D);
|
||||
this.padTitle = s.add.text(sp.x + sp.w / 2 + 14, sp.y + 34, '', { fontFamily: HAND_FONT, fontSize: '22px', color: '#1d3e78' }).setOrigin(0.5).setDepth(D + 1);
|
||||
this.padRows = [0, 1, 2, 3].map((i) => ({
|
||||
name: s.add.text(sp.x + 52, sp.y + 74 + i * 26 + 26, '', { fontFamily: HAND_FONT, fontSize: '22px', color: '#2a2a3a' }).setOrigin(0, 0.5).setDepth(D + 1),
|
||||
val: s.add.text(sp.x + sp.w - 18, sp.y + 74 + i * 26 + 26, '', { fontFamily: HAND_FONT, fontSize: '24px', color: '#2a2a3a' }).setOrigin(1, 0.5).setDepth(D + 1),
|
||||
}));
|
||||
this.padHint = s.add.text(sp.x + sp.w / 2 + 14, sp.y + sp.h - 22, 'tap for the whole pad', { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#6a5a3a' }).setOrigin(0.5).setDepth(D + 1);
|
||||
this.pencil = s.add.image(sp.x + 150, sp.y + sp.h - 46, 'mt-pencil').setScale(0.5).setRotation(-0.5).setDepth(D + 2);
|
||||
const z = s.add.zone(sp.x + sp.w / 2, sp.y + sp.h / 2, sp.w, sp.h).setDepth(D + 4).setInteractive({ useHandCursor: true });
|
||||
z.on('pointerdown', () => this.onPad());
|
||||
return this;
|
||||
}
|
||||
|
||||
refresh(gs, { current = gs.current, human = 0 } = {}) {
|
||||
this.seats.forEach((st, i) => {
|
||||
const p = gs.players[i];
|
||||
st.score.setText(`${p.score} pts`);
|
||||
if (st.inhand) st.inhand.setText(`${p.hand.length} tiles · ${handPips(p.hand, gs.opts)} pips in hand`);
|
||||
if (st.backs) {
|
||||
st.backs.clear();
|
||||
const cnt = p.hand.length, P = st.P.mini;
|
||||
const pitch = Math.min(15, (P.w - 24) / Math.max(1, cnt));
|
||||
for (let k = 0; k < cnt; k++) {
|
||||
const x = P.x + 12 + k * pitch, y = P.y - 14;
|
||||
st.backs.fillStyle(0x6a4a22, 0.35).fillRoundedRect(x + 1.5, y + 2, 12, 24, 2);
|
||||
st.backs.fillStyle(0xf3ead2, 1).fillRoundedRect(x, y, 12, 24, 2);
|
||||
st.backs.lineStyle(1, 0xb8a47a, 1).strokeRoundedRect(x, y, 12, 24, 2);
|
||||
}
|
||||
st.count.setText(`${cnt} tile${cnt === 1 ? '' : 's'}`);
|
||||
}
|
||||
const marked = gs.trains[String(i)]?.marker;
|
||||
st.tag.setVisible(!!marked && gs.phase === 'playing');
|
||||
st.knock.setVisible(gs.phase === 'playing' && p.hand.length === 1 && (p.knocked || !gs.opts.knock));
|
||||
st.glow.clear();
|
||||
if (gs.phase === 'playing' && current === i) {
|
||||
st.glow.fillStyle(st.col.hex, 0.35).fillRoundedRect(st.r.x - 9, st.r.y - 9, st.r.w + 18, st.r.h + 18, 14);
|
||||
st.glow.lineStyle(4, st.col.hex, 1).strokeRoundedRect(st.r.x - 6, st.r.y - 6, st.r.w + 12, st.r.h + 12, 12);
|
||||
}
|
||||
});
|
||||
// pad
|
||||
const total = roundsTotal(gs.opts);
|
||||
this.padTitle.setText(total ? `Round ${gs.round + 1} of ${total}` : `Round ${gs.round + 1} · to ${gs.opts.target}`);
|
||||
const min = Math.min(...gs.players.map((q) => q.score));
|
||||
this.padRows.forEach((row, i) => {
|
||||
const p = gs.players[i];
|
||||
if (!p) { row.name.setText(''); row.val.setText(''); return; }
|
||||
const nm = i === human ? 'You' : p.name;
|
||||
row.name.setText(nm.length > 9 ? nm.slice(0, 8) + '…' : nm).setColor(SEAT[i].ink);
|
||||
row.val.setText(String(p.score)).setColor(p.score === min && gs.history.length ? '#1e7a3a' : '#2a2a3a');
|
||||
});
|
||||
}
|
||||
|
||||
setStatus(main, sub = '') { this.status.setText(main); this.sub.setText(sub); }
|
||||
|
||||
setTalk(log, names) {
|
||||
const lines = log.slice(-this.talk.length);
|
||||
this.talk.forEach((t, i) => {
|
||||
const e = lines[i];
|
||||
if (!e) { t.setText(''); return; }
|
||||
const who = e.seat === 0 ? 'You' : names[e.seat];
|
||||
let line = `${who}: ${e.text}`;
|
||||
if (line.length > 52) line = line.slice(0, 51) + '…';
|
||||
t.setText(line).setColor(SEAT[e.seat]?.ink ?? '#3a2a18');
|
||||
});
|
||||
}
|
||||
|
||||
setButton(k, on, label = null) {
|
||||
const b = this.buttons[k];
|
||||
if (!b) return;
|
||||
if (label && b._lbl !== label) { b.setLabel(label); b._lbl = label; }
|
||||
b.setEnabled(!!on);
|
||||
}
|
||||
|
||||
seatCenter(i) { const st = this.seats[i]; return { x: st.r.x + st.r.w / 2, y: st.r.y + st.r.h / 2 }; }
|
||||
handSpot(i) {
|
||||
const st = this.seats[i];
|
||||
if (st.P.mini) return { x: st.P.mini.x + st.P.mini.w / 2, y: st.P.mini.y };
|
||||
return { x: st.P.portrait.x, y: st.P.portrait.y };
|
||||
}
|
||||
|
||||
scribble(dur = 700) {
|
||||
const p = this.pencil;
|
||||
const x0 = p.x, y0 = p.y;
|
||||
this.scene.tweens.add({ targets: p, x: { from: x0 - 30, to: x0 + 10 }, y: { from: y0 - 120, to: y0 - 100 }, duration: dur / 6, yoyo: true, repeat: 2, ease: 'Sine.InOut', onComplete: () => p.setPosition(x0, y0) });
|
||||
}
|
||||
|
||||
say(i, text, dur = 2600) {
|
||||
const st = this.seats[i];
|
||||
if (!st || i === 0 || !st.P.bubble) return;
|
||||
const s = this.scene;
|
||||
this.bubbles[i]?.destroy();
|
||||
const b = st.P.bubble;
|
||||
const t = s.add.text(b.x + b.w / 2, b.y + b.h / 2, text, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#2a1a08', align: 'center', wordWrap: { width: b.w - 26 } }).setOrigin(0.5);
|
||||
const g = s.add.graphics();
|
||||
g.fillStyle(0x000000, 0.25).fillRoundedRect(b.x + 3, b.y + 5, b.w, b.h, 14);
|
||||
g.fillStyle(0xfffcf2, 1).fillRoundedRect(b.x, b.y, b.w, b.h, 14);
|
||||
g.lineStyle(2.5, st.col.hex, 1).strokeRoundedRect(b.x, b.y, b.w, b.h, 14);
|
||||
g.fillStyle(0xfffcf2, 1);
|
||||
if (b.up) g.fillTriangle(b.x + 30, b.y + 1, b.x + 54, b.y + 1, b.x + 26, b.y - 16);
|
||||
else if (b.side === 'left') g.fillTriangle(b.x + 1, b.y + 22, b.x + 1, b.y + 44, b.x - 16, b.y + 26);
|
||||
else g.fillTriangle(b.x + b.w - 1, b.y + 22, b.x + b.w - 1, b.y + 44, b.x + b.w + 16, b.y + 26);
|
||||
const cont = s.add.container(0, 0, [g, t]).setDepth(this.depth + 20).setAlpha(0);
|
||||
this.bubbles[i] = cont;
|
||||
s.tweens.add({ targets: cont, alpha: 1, duration: 160 });
|
||||
s.tweens.add({ targets: cont, alpha: 0, delay: dur, duration: 300, onComplete: () => { cont.destroy(); if (this.bubbles[i] === cont) delete this.bubbles[i]; } });
|
||||
}
|
||||
|
||||
emotion(i, e) { this.seats[i]?.portrait?.playEmotion?.(e); }
|
||||
hidePortraits() { this.seats.forEach((st) => st.portrait?.setVideoVisible?.(false)); }
|
||||
showPortraits() { this.seats.forEach((st) => st.portrait?.setVideoVisible?.(true)); }
|
||||
}
|
||||
|
||||
export { colorOf };
|
||||
|
|
@ -0,0 +1,264 @@
|
|||
// MexicanTrainLayout.js — pure geometry for the kitchen table (no Phaser).
|
||||
//
|
||||
// Screen furniture (status card, seat cards, rack, buttons, boneyard, score
|
||||
// pad) plus the train paths. Every train leaves the station hub toward its
|
||||
// owner's seat (the "spoke" = lane 0), and when it reaches the edge of its
|
||||
// patch of table it turns a corner (one tile laid crosswise) and snakes back
|
||||
// and forth (boustrophedon lanes) across that patch.
|
||||
//
|
||||
// arms(n) → { [trainKey]: arm }
|
||||
// layoutTrain(arm, tiles, zoom) → { poses: [{x,y,rot,dbl,corner}], next, fits }
|
||||
// layoutAll(n, trains, zoom) → { poses, next, fits } (per key)
|
||||
// fitZoom(n, trains, maxZoom) → largest zoom (0.5–1) at which every train fits
|
||||
//
|
||||
// A pose's rot is the travel direction (radians); the scene adds π when the
|
||||
// tile's low face isn't the one touching the previous tile, and doubles are
|
||||
// laid crosswise (rot already includes the quarter turn for them).
|
||||
|
||||
export const W = 1920;
|
||||
export const H = 1080;
|
||||
|
||||
// ── furniture ────────────────────────────────────────────────────────────────
|
||||
export const TABLE = { l: 300, r: 1620, t: 140, b: 904 };
|
||||
export const HUB = { x: 960, y: 522, r: 62 };
|
||||
export const STATUS = { x: 16, y: 12, w: 470, h: 120 };
|
||||
export const TALK = { x: 1434, y: 12, w: 470, h: 120 };
|
||||
export const SEAT_CARDS = {
|
||||
left: { x: 16, y: 152, w: 268, h: 214 },
|
||||
top: { x: 700, y: 10, w: 520, h: 118 },
|
||||
right: { x: 1636, y: 152, w: 268, h: 214 },
|
||||
human: { x: 16, y: 916, w: 404, h: 152 },
|
||||
};
|
||||
export const RACK = { x: 438, y: 922, w: 1046, h: 150 };
|
||||
export const BUTTONS_BOX = { x: 1500, y: 916, w: 404, h: 152 };
|
||||
export const BONEYARD = { x: 22, y: 600, w: 266, h: 300, box: { x: 155, y: 640 }, pile: { x: 30, y: 700, w: 250, h: 190 } };
|
||||
export const SCORE_PAD = { x: 1640, y: 604, w: 260, h: 296 };
|
||||
export const BANNER = { x: 960, y: 420 };
|
||||
|
||||
const BTN_W = 126, BTN_H = 62;
|
||||
export const BUTTONS = (() => {
|
||||
const keys = [['hint', 'undo', 'end'], ['knock', 'sort', 'menu']];
|
||||
const out = {};
|
||||
keys.forEach((row, r) => row.forEach((k, c) => {
|
||||
out[k] = { x: BUTTONS_BOX.x + 8 + BTN_W / 2 + c * (BTN_W + 8), y: BUTTONS_BOX.y + 8 + BTN_H / 2 + r * (BTN_H + 12) };
|
||||
}));
|
||||
return out;
|
||||
})();
|
||||
export const BTN = { w: BTN_W, h: BTN_H };
|
||||
|
||||
/** Which seat card each player uses (seat 0 = you). Clockwise from you. */
|
||||
export function seatPlaces(n) {
|
||||
if (n === 2) return ['human', 'top'];
|
||||
if (n === 3) return ['human', 'left', 'right'];
|
||||
return ['human', 'left', 'top', 'right'];
|
||||
}
|
||||
|
||||
// ── tiles ────────────────────────────────────────────────────────────────────
|
||||
// Table tiles at zoom 1: a 72×36 domino; gap between tiles; lane spacing lets
|
||||
// a crosswise double sit between neighbours without touching them.
|
||||
export const TILE = { u: 36, gap: 3, lane: 60 };
|
||||
export const RACK_TILE = { u: 46, pitch: 52, lift: 20 };
|
||||
|
||||
// ── arms ─────────────────────────────────────────────────────────────────────
|
||||
// An arm: lane 0 runs from the hub (along axis 'h' or 'v', direction sign
|
||||
// `dir`) to `far`; further lanes step by `sweep` (±1) across the arm's patch,
|
||||
// alternating direction, between `lo` and `hi` on the lane axis, up to the
|
||||
// cross-coordinate `limit`. `cross0` is lane 0's cross-coordinate.
|
||||
const OFF = 40; // lane-0 offset from the hub's centre lines
|
||||
const START = 66; // lane 0 begins this far from the hub centre
|
||||
const CORNER = TILE.u + TILE.gap * 2; // room reserved past each lane end
|
||||
|
||||
function arm(key, spec) { return { key, ...spec }; }
|
||||
|
||||
const A = {
|
||||
// up the left of centre, snaking left (top-left patch)
|
||||
up: (key, { lo = TABLE.t, hi = HUB.y - 38, limit = TABLE.l } = {}) => arm(key, {
|
||||
axis: 'v', dir: -1, cross0: HUB.x - OFF, start: HUB.y - START, far: TABLE.t, sweep: -1, lo, hi, limit,
|
||||
}),
|
||||
// up the right of centre, snaking right (top-right, left part)
|
||||
up2: (key, { lo = TABLE.t, hi = HUB.y - 80, limit = TABLE.r } = {}) => arm(key, {
|
||||
axis: 'v', dir: -1, cross0: HUB.x + OFF, start: HUB.y - START, far: TABLE.t, sweep: 1, lo, hi, limit,
|
||||
}),
|
||||
// right, above centre, snaking up (top-right patch)
|
||||
right: (key, { lo = HUB.x - 2, hi = TABLE.r, limit = TABLE.t } = {}) => arm(key, {
|
||||
axis: 'h', dir: 1, cross0: HUB.y - OFF, start: HUB.x + START, far: TABLE.r, sweep: -1, lo, hi, limit,
|
||||
}),
|
||||
// down the right of centre, snaking right (bottom-right patch)
|
||||
down: (key, { lo = HUB.y - 2, hi = TABLE.b, limit = TABLE.r } = {}) => arm(key, {
|
||||
axis: 'v', dir: 1, cross0: HUB.x + OFF, start: HUB.y + START, far: TABLE.b, sweep: 1, lo, hi, limit,
|
||||
}),
|
||||
// left, below centre, snaking down (bottom-left patch)
|
||||
left: (key, { lo = TABLE.l, hi = HUB.x + 2, limit = TABLE.b } = {}) => arm(key, {
|
||||
axis: 'h', dir: -1, cross0: HUB.y + OFF, start: HUB.x - START, far: TABLE.l, sweep: 1, lo, hi, limit,
|
||||
}),
|
||||
};
|
||||
|
||||
const SPLIT_X = 1350; // 4 players: the top-right patch is shared
|
||||
|
||||
export function arms(n) {
|
||||
if (n === 2) {
|
||||
return {
|
||||
0: A.down('0'),
|
||||
1: A.up('1', { hi: TABLE.b }), // the whole left half is theirs
|
||||
mexican: A.right('mexican'),
|
||||
};
|
||||
}
|
||||
if (n === 3) {
|
||||
return { 0: A.down('0'), 1: A.left('1'), 2: A.right('2'), mexican: A.up('mexican') };
|
||||
}
|
||||
return {
|
||||
0: A.down('0'),
|
||||
1: A.left('1'),
|
||||
2: A.up('2'),
|
||||
3: A.right('3', { lo: SPLIT_X + 30 }),
|
||||
mexican: A.up2('mexican', { limit: SPLIT_X - 30 }),
|
||||
};
|
||||
}
|
||||
|
||||
// ── placing tiles along an arm ───────────────────────────────────────────────
|
||||
// tiles: [{ left, right }] (only doubles matter here). Returns a pose per tile
|
||||
// plus `next`: where the following tile would go (for the drop slot / badge).
|
||||
export function layoutTrain(a, tiles, zoom = 1) {
|
||||
const u = TILE.u * zoom, L = u * 2, gap = TILE.gap * zoom, lane = TILE.lane * zoom, corner = CORNER * zoom;
|
||||
const poses = [];
|
||||
let j = 0; // lane index
|
||||
let dir = a.dir; // travel direction on this lane
|
||||
let cross = a.cross0;
|
||||
let c = a.start; // cursor (lane-axis coordinate, back edge of next tile)
|
||||
let fits = true;
|
||||
const laneEnd = (jj, d) => {
|
||||
if (jj === 0) return a.far - d * corner;
|
||||
return d > 0 ? a.hi - corner : a.lo + corner;
|
||||
};
|
||||
const toXY = (along, cr) => (a.axis === 'h' ? { x: along, y: cr } : { x: cr, y: along });
|
||||
const travelRot = (d) => (a.axis === 'h' ? (d > 0 ? 0 : Math.PI) : (d > 0 ? Math.PI / 2 : -Math.PI / 2));
|
||||
const sweepRot = a.axis === 'h' ? (a.sweep > 0 ? Math.PI / 2 : -Math.PI / 2) : (a.sweep > 0 ? 0 : Math.PI);
|
||||
const nextLaneOk = () => {
|
||||
const nc = cross + a.sweep * lane;
|
||||
return a.sweep > 0 ? nc + u <= a.limit : nc - u >= a.limit; // room for a crosswise double
|
||||
};
|
||||
|
||||
let prevDbl = []; // along-intervals of crosswise doubles, previous lane
|
||||
let curDbl = [];
|
||||
const clashes = (a0, a1) => prevDbl.some(([b0, b1]) => a0 < b1 + gap && b0 < a1 + gap);
|
||||
|
||||
const place = (isDbl, peek = false) => {
|
||||
const end = laneEnd(j, dir);
|
||||
// a double lies crosswise unless a crosswise double in the lane beside it is in the way
|
||||
let cross90 = isDbl;
|
||||
if (isDbl) {
|
||||
const a0 = Math.min(c, c + dir * u), a1 = Math.max(c, c + dir * u);
|
||||
if (clashes(a0, a1)) cross90 = false;
|
||||
}
|
||||
const len = cross90 ? u : L;
|
||||
const fitsHere = dir > 0 ? c + len <= end + 0.01 : c - len >= end - 0.01;
|
||||
if (fitsHere) {
|
||||
const mid = c + dir * len / 2;
|
||||
const p = { ...toXY(mid, cross), rot: travelRot(dir) + (cross90 ? Math.PI / 2 : 0), dbl: isDbl, crosswise: cross90, corner: false };
|
||||
if (!peek) {
|
||||
if (cross90) curDbl.push([Math.min(c, c + dir * u), Math.max(c, c + dir * u)]);
|
||||
c += dir * (len + gap);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
if (!nextLaneOk()) {
|
||||
if (!peek) fits = false;
|
||||
const mid = c + dir * L / 2;
|
||||
const p = { ...toXY(mid, cross), rot: travelRot(dir), dbl: isDbl, crosswise: false, corner: false, overflow: true };
|
||||
if (!peek) c += dir * (L + gap);
|
||||
return p;
|
||||
}
|
||||
// turn the corner right against the last tile, so the chain never breaks:
|
||||
// this tile goes crosswise, bridging into the next lane
|
||||
const colAlong = c + dir * (u / 2);
|
||||
const p = { ...toXY(colAlong, cross + a.sweep * lane / 2), rot: sweepRot, dbl: isDbl, crosswise: false, corner: true };
|
||||
if (!peek) {
|
||||
j++;
|
||||
cross += a.sweep * lane;
|
||||
dir = -dir;
|
||||
c = colAlong + dir * (u / 2 + gap);
|
||||
prevDbl = curDbl;
|
||||
curDbl = [];
|
||||
}
|
||||
return p;
|
||||
};
|
||||
|
||||
for (const t of tiles) poses.push(place(t.left === t.right));
|
||||
const next = place(false, true);
|
||||
const nextDbl = place(true, true);
|
||||
return { poses, next, nextDbl, fits, lanes: j + 1 };
|
||||
}
|
||||
|
||||
export function layoutAll(n, trains, zoom = 1) {
|
||||
const as = arms(n);
|
||||
const out = {};
|
||||
let fits = true;
|
||||
for (const [k, a] of Object.entries(as)) {
|
||||
const r = layoutTrain(a, trains[k]?.tiles ?? [], zoom);
|
||||
out[k] = r;
|
||||
if (!r.fits) fits = false;
|
||||
}
|
||||
return { trains: out, fits };
|
||||
}
|
||||
|
||||
export const ZOOM_MIN = 0.5;
|
||||
/** Largest zoom ≤ maxZoom (steps of 0.025) at which every train fits its patch. */
|
||||
export function fitZoom(n, trains, maxZoom = 1) {
|
||||
for (let z = maxZoom; z >= ZOOM_MIN - 1e-9; z -= 0.025) {
|
||||
if (layoutAll(n, trains, z).fits) return Math.round(z * 1000) / 1000;
|
||||
}
|
||||
return ZOOM_MIN;
|
||||
}
|
||||
|
||||
/** Where a train's first tile (and its marker) sits: just off the hub. */
|
||||
export function trainMouth(n, key) {
|
||||
const a = arms(n)[key];
|
||||
if (!a) return { x: HUB.x, y: HUB.y };
|
||||
const along = a.start + a.dir * 4;
|
||||
return a.axis === 'h' ? { x: along, y: a.cross0, rot: a.dir > 0 ? 0 : Math.PI } : { x: a.cross0, y: along, rot: a.dir > 0 ? Math.PI / 2 : -Math.PI / 2 };
|
||||
}
|
||||
|
||||
/** The marker (toy engine) spot: parked in the hub's slot at the train's mouth. */
|
||||
export const MARKER = { along: 51, scale: 0.45, len: 29, wid: 15 };
|
||||
export function markerSpot(n, key) {
|
||||
const a = arms(n)[key];
|
||||
if (!a) return { x: HUB.x, y: HUB.y, rot: 0 };
|
||||
const along = (a.axis === 'h' ? HUB.x : HUB.y) + a.dir * MARKER.along;
|
||||
const rot = a.axis === 'h' ? (a.dir > 0 ? 0 : Math.PI) : (a.dir > 0 ? Math.PI / 2 : -Math.PI / 2);
|
||||
return a.axis === 'h' ? { x: along, y: a.cross0, rot } : { x: a.cross0, y: along, rot };
|
||||
}
|
||||
|
||||
// ── rack ─────────────────────────────────────────────────────────────────────
|
||||
/** x-centres for `count` rack tiles (compresses when the rack is crowded). */
|
||||
export function rackSlots(count) {
|
||||
const inner = RACK.w - 60;
|
||||
const pitch = count > 1 ? Math.min(RACK_TILE.pitch, (inner - RACK_TILE.u) / (count - 1)) : RACK_TILE.pitch;
|
||||
const span = (count - 1) * pitch;
|
||||
const x0 = RACK.x + RACK.w / 2 - span / 2;
|
||||
return { xs: Array.from({ length: count }, (_, i) => x0 + i * pitch), y: RACK.y + 70, pitch };
|
||||
}
|
||||
export function rackIndexAt(x, count) {
|
||||
const { xs } = rackSlots(Math.max(1, count));
|
||||
let best = 0, bd = Infinity;
|
||||
xs.forEach((sx, i) => { const d = Math.abs(sx - x); if (d < bd) { bd = d; best = i; } });
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Random-looking but stable boneyard pile spots for up to `count` tiles. */
|
||||
export function pileSpots(count, seed = 7) {
|
||||
let a = seed >>> 0;
|
||||
const rnd = () => { a = (a * 1664525 + 1013904223) >>> 0; return a / 4294967296; };
|
||||
const P = BONEYARD.pile;
|
||||
return Array.from({ length: count }, () => ({
|
||||
x: P.x + 26 + rnd() * (P.w - 52), y: P.y + 16 + rnd() * (P.h - 32), rot: (rnd() - 0.5) * Math.PI,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Rects the verify script checks for overlaps. */
|
||||
export function hudFurniture(n) {
|
||||
const out = [
|
||||
['status', STATUS], ['talk', TALK], ['rack', RACK], ['buttons', BUTTONS_BOX], ['boneyard', BONEYARD], ['scorepad', SCORE_PAD],
|
||||
];
|
||||
for (const p of seatPlaces(n)) out.push([`seat-${p}`, SEAT_CARDS[p]]);
|
||||
return out;
|
||||
}
|
||||
|
|
@ -1,227 +1,461 @@
|
|||
// Pure Mexican Train rules (double-six set). No Phaser dependency.
|
||||
// MexicanTrainLogic.js — pure Mexican Train rules. No Phaser; seedable, and the
|
||||
// whole state is plain JSON (cloneState is a JSON round-trip).
|
||||
//
|
||||
// Match structure:
|
||||
// - Successive rounds. Each round pulls an "engine" double into the central
|
||||
// hub: round 0 -> 6-6, round 1 -> 5-5, ... round 6 -> 0-0, then wraps.
|
||||
// - Players play tiles onto trains radiating from the hub. Each player owns
|
||||
// one personal train; there is also one communal "Mexican" train.
|
||||
// - A round ends when a player empties their hand (scores 0 that round) or
|
||||
// the round is blocked (boneyard empty + everyone passed in a row). Each
|
||||
// remaining hand's pip total is added to that player's cumulative score.
|
||||
// - The match ends when any player's cumulative score reaches the target.
|
||||
// LOWEST cumulative score wins.
|
||||
// Match:
|
||||
// • Double-12 (default), double-9 or double-6 set. Each round the "engine"
|
||||
// double sits in the station hub: 12-12, then 11-11 … down to 0-0. The
|
||||
// classic match ('descent') is exactly one round per engine; the house
|
||||
// rule 'points' keeps dealing (wrapping) until someone reaches the target.
|
||||
// • A round ends when a player empties their hand, or is blocked (boneyard
|
||||
// empty and every seat passed in a row). Everyone adds the pips left in
|
||||
// their hand. LOWEST total wins the match.
|
||||
//
|
||||
// Train access:
|
||||
// - You may always play on your own train and the Mexican train.
|
||||
// - You may play on another player's train only while it is "open" (marked,
|
||||
// because that player couldn't play on their turn).
|
||||
// - Playing on your own train removes your marker.
|
||||
// Trains:
|
||||
// • Each seat owns a train; there is one communal Mexican Train. You may
|
||||
// always play on your own train and the Mexican Train, and on another
|
||||
// seat's train only while it is open (marked — they couldn't play).
|
||||
// Playing on your own train takes your marker off.
|
||||
//
|
||||
// Doubles (house rule: must be covered immediately):
|
||||
// - Placing a double opens it; the next play (by anyone, in turn) must cover
|
||||
// that double before any other play is allowed. The player who laid it
|
||||
// keeps the turn to try to cover it themselves.
|
||||
// Turn (the 1994 Galt rules, as on Wikipedia):
|
||||
// • Play ONE matching tile. No play? Draw one; if it fits you must play it,
|
||||
// else pass and your train is marked open.
|
||||
// • Doubles ('cover', default): whoever lays a double plays again and must
|
||||
// cover it; until it's covered nobody may play anywhere else. If they
|
||||
// can't (even after drawing) they pass, mark their train, and the next
|
||||
// seat must cover it. A double needs no cover when every other tile of
|
||||
// its number is already on the table. ('relaxed'): a double just earns
|
||||
// one extra play anywhere.
|
||||
// • Going out on a double ends the round at once.
|
||||
// • House rules: `opening` (Pagat's first turn: lay as many tiles as chain
|
||||
// onto your own train — own train only, no drawing; a run ending on a
|
||||
// double is covered once everyone has had a first turn), `blank50` (0-0
|
||||
// left in hand scores 50), `knock` (forget to knock on your last tile and
|
||||
// get caught: draw two).
|
||||
// • Ties for the match go to the most 0-point rounds, then the lowest
|
||||
// non-zero round.
|
||||
|
||||
export const SET_MAX = 6; // double-six
|
||||
export const MEXICAN = 'mexican';
|
||||
export const SET_SIZES = [12, 9, 6];
|
||||
|
||||
export function makeTileSet() {
|
||||
export const DEFAULT_OPTS = {
|
||||
set: 12,
|
||||
mode: 'descent', // 'descent' | 'points'
|
||||
target: 300, // points mode only
|
||||
opening: false,
|
||||
doubles: 'cover', // 'cover' | 'relaxed'
|
||||
blank50: false,
|
||||
knock: false,
|
||||
};
|
||||
|
||||
const HAND = {
|
||||
12: { 2: 15, 3: 15, 4: 15 },
|
||||
9: { 2: 10, 3: 10, 4: 9 },
|
||||
6: { 2: 7, 3: 6, 4: 5 },
|
||||
};
|
||||
|
||||
export function handSizeFor(set, n) { return HAND[set]?.[n] ?? HAND[12][4]; }
|
||||
|
||||
export function makeTileSet(set = 12) {
|
||||
const tiles = [];
|
||||
for (let a = 0; a <= SET_MAX; a++) {
|
||||
for (let b = a; b <= SET_MAX; b++) tiles.push({ a, b });
|
||||
}
|
||||
return tiles; // 28 tiles
|
||||
for (let a = 0; a <= set; a++) for (let b = a; b <= set; b++) tiles.push({ id: tiles.length, a, b });
|
||||
return tiles;
|
||||
}
|
||||
|
||||
export const tilePips = (t) => t.a + t.b;
|
||||
export const isDoubleTile = (t) => t.a === t.b;
|
||||
|
||||
export function handSizeFor(n) {
|
||||
if (n === 2) return 7;
|
||||
if (n === 3) return 6;
|
||||
return 5; // 4 players
|
||||
export function tileCount(set) { return ((set + 1) * (set + 2)) / 2; }
|
||||
export const isDouble = (t) => t.a === t.b;
|
||||
export const tileName = (t) => `${t.a}-${t.b}`;
|
||||
export function tilePips(t, opts) {
|
||||
if (opts?.blank50 && t.a === 0 && t.b === 0) return 50;
|
||||
return t.a + t.b;
|
||||
}
|
||||
export function handPips(hand, opts) { return hand.reduce((n, t) => n + tilePips(t, opts), 0); }
|
||||
|
||||
export function cloneState(state) {
|
||||
return JSON.parse(JSON.stringify(state));
|
||||
export function cloneState(s) { return JSON.parse(JSON.stringify(s)); }
|
||||
|
||||
// seedable PRNG kept in the state (mulberry32 step)
|
||||
function rand(s) {
|
||||
s.rng = (s.rng + 0x6d2b79f5) >>> 0;
|
||||
let t = s.rng;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
}
|
||||
|
||||
function shuffle(arr) {
|
||||
function shuffle(s, arr) {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
const j = Math.floor(rand(s) * (i + 1));
|
||||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
// Engine double value for a given round index.
|
||||
export function hubValueForRound(roundIndex) {
|
||||
return SET_MAX - (roundIndex % (SET_MAX + 1));
|
||||
export function roundsTotal(opts) { return opts.mode === 'descent' ? opts.set + 1 : null; }
|
||||
export function hubValueForRound(set, round) { return set - (round % (set + 1)); }
|
||||
export const trainKeys = (n) => [...Array.from({ length: n }, (_, i) => String(i)), MEXICAN];
|
||||
|
||||
function blankStats() {
|
||||
return { played: 0, doubles: 0, covered: 0, drawn: 0, passes: 0, roundsWon: 0, longest: 0, outs: 0, caught: 0 };
|
||||
}
|
||||
|
||||
export function createInitialState({ playerNames, target = 100 }) {
|
||||
const players = playerNames.map((p) => ({
|
||||
name: p.name,
|
||||
isAI: !!p.isAI,
|
||||
avatar: p.avatar ?? null,
|
||||
hand: [],
|
||||
score: 0,
|
||||
}));
|
||||
const state = {
|
||||
players,
|
||||
current: 0,
|
||||
export function createInitialState({ playerNames, opts = {}, seed = null }) {
|
||||
const o = { ...DEFAULT_OPTS, ...opts };
|
||||
if (!SET_SIZES.includes(o.set)) o.set = 12;
|
||||
const s = {
|
||||
opts: o,
|
||||
n: playerNames.length,
|
||||
players: playerNames.map((p) => ({ name: p.name, isAI: !!p.isAI, hand: [], score: 0, knocked: false })),
|
||||
round: 0,
|
||||
target,
|
||||
hub: { value: SET_MAX },
|
||||
trains: {}, // key -> { tiles: [{left, right}], marker }
|
||||
hub: null,
|
||||
trains: {},
|
||||
boneyard: [],
|
||||
openDouble: null, // { train, value } when a double awaits covering
|
||||
phase: 'playing', // playing -> roundover -> (next round) | gameover
|
||||
openDouble: null,
|
||||
current: 0,
|
||||
roundStarter: 0,
|
||||
turn: null,
|
||||
firstDone: [],
|
||||
consecutivePasses: 0,
|
||||
startPlayer: 0,
|
||||
phase: 'playing',
|
||||
roundWinner: null,
|
||||
lastRoundScores: null,
|
||||
blocked: false,
|
||||
history: [],
|
||||
stats: playerNames.map(() => blankStats()),
|
||||
log: [],
|
||||
lastEvent: null,
|
||||
rng: (seed ?? Math.floor(Math.random() * 2 ** 31)) >>> 0,
|
||||
};
|
||||
dealRound(state, 0, 0);
|
||||
return state;
|
||||
const starter = Math.floor(rand(s) * s.n);
|
||||
dealRound(s, 0, starter);
|
||||
return s;
|
||||
}
|
||||
|
||||
// Mutates `s` to set up a fresh round. Used internally.
|
||||
function dealRound(s, roundIndex, startPlayer) {
|
||||
const n = s.players.length;
|
||||
const hubVal = hubValueForRound(roundIndex);
|
||||
s.hub = { value: hubVal };
|
||||
|
||||
const tiles = shuffle(makeTileSet().filter((t) => !(t.a === hubVal && t.b === hubVal)));
|
||||
const hs = handSizeFor(n);
|
||||
s.players.forEach((p) => { p.hand = tiles.splice(0, hs); });
|
||||
s.boneyard = tiles;
|
||||
|
||||
function dealRound(s, round, starter) {
|
||||
const { set } = s.opts;
|
||||
const hv = hubValueForRound(set, round);
|
||||
const all = makeTileSet(set);
|
||||
const engine = all.find((t) => t.a === hv && t.b === hv);
|
||||
s.hub = { value: hv, id: engine.id };
|
||||
const pool = shuffle(s, all.filter((t) => t.id !== engine.id));
|
||||
const hs = handSizeFor(set, s.n);
|
||||
s.players.forEach((p) => { p.hand = pool.splice(0, hs); p.knocked = false; });
|
||||
s.boneyard = pool;
|
||||
s.trains = {};
|
||||
for (let i = 0; i < n; i++) s.trains[String(i)] = { tiles: [], marker: false };
|
||||
s.trains[MEXICAN] = { tiles: [], marker: false };
|
||||
|
||||
for (const k of trainKeys(s.n)) s.trains[k] = { tiles: [], marker: false };
|
||||
s.openDouble = null;
|
||||
s.deferred = []; // opening-run doubles waiting for everyone's first turn
|
||||
s.consecutivePasses = 0;
|
||||
s.current = startPlayer ?? 0;
|
||||
s.round = round;
|
||||
s.roundStarter = starter;
|
||||
s.current = starter;
|
||||
s.firstDone = s.players.map(() => false);
|
||||
s.voids = s.players.map(() => ({})); // seat → { number: draws since they showed they lacked it }
|
||||
s.phase = 'playing';
|
||||
s.roundWinner = null;
|
||||
s.lastRoundScores = null;
|
||||
s.blocked = false;
|
||||
s.turn = freshTurn(s, starter);
|
||||
s.lastEvent = { type: 'deal', round, hub: hv, starter };
|
||||
pushLog(s, starter, `starts round ${round + 1} (engine ${hv}-${hv})`);
|
||||
}
|
||||
|
||||
function freshTurn(s, seat) {
|
||||
return { seat, played: 0, drew: false, opening: !!s.opts.opening && !s.firstDone[seat], run: false, bonus: false };
|
||||
}
|
||||
|
||||
function pushLog(s, seat, text) {
|
||||
s.log.push({ seat, text, round: s.round });
|
||||
if (s.log.length > 60) s.log.splice(0, s.log.length - 60);
|
||||
}
|
||||
|
||||
export function startNextRound(state) {
|
||||
if (state.phase !== 'roundover') return state;
|
||||
const s = cloneState(state);
|
||||
s.round += 1;
|
||||
dealRound(s, s.round, s.startPlayer ?? 0);
|
||||
dealRound(s, s.round + 1, (s.roundStarter + 1) % s.n);
|
||||
return s;
|
||||
}
|
||||
|
||||
// The currently exposed end value of a train (hub value if empty).
|
||||
export function trainOpenEnd(state, key) {
|
||||
const tr = state.trains[key];
|
||||
if (!tr || tr.tiles.length === 0) return state.hub.value;
|
||||
// ── queries ──────────────────────────────────────────────────────────────────
|
||||
export function trainOpenEnd(s, key) {
|
||||
const tr = s.trains[key];
|
||||
if (!tr || tr.tiles.length === 0) return s.hub.value;
|
||||
return tr.tiles[tr.tiles.length - 1].right;
|
||||
}
|
||||
|
||||
// Train keys the given player may currently play on.
|
||||
export function playableTrainKeys(state, idx) {
|
||||
if (state.openDouble) return [state.openDouble.train];
|
||||
const keys = [String(idx), MEXICAN];
|
||||
for (let j = 0; j < state.players.length; j++) {
|
||||
if (j !== idx && state.trains[String(j)]?.marker) keys.push(String(j));
|
||||
}
|
||||
export function trainLabel(s, key, you = 0) {
|
||||
if (key === MEXICAN) return 'the Mexican Train';
|
||||
return Number(key) === you ? 'your train' : `${s.players[Number(key)].name}'s train`;
|
||||
}
|
||||
|
||||
/** Train keys `seat` may play on right now (ignores whether it's their turn). */
|
||||
export function playableTrainKeys(s, seat = s.current) {
|
||||
if (s.openDouble) return [s.openDouble.train];
|
||||
if (s.turn?.opening && seat === s.current) return [String(seat)]; // first turn: own train only
|
||||
const keys = [String(seat), MEXICAN];
|
||||
for (let j = 0; j < s.n; j++) if (j !== seat && s.trains[String(j)].marker) keys.push(String(j));
|
||||
return keys;
|
||||
}
|
||||
|
||||
// All legal moves for a player: [{ tileIndex, train }].
|
||||
export function getLegalMoves(state, idx) {
|
||||
if (state.phase !== 'playing') return [];
|
||||
const moves = [];
|
||||
const hand = state.players[idx].hand;
|
||||
for (const key of playableTrainKeys(state, idx)) {
|
||||
const end = trainOpenEnd(state, key);
|
||||
hand.forEach((t, i) => {
|
||||
if (t.a === end || t.b === end) moves.push({ tileIndex: i, train: key });
|
||||
});
|
||||
}
|
||||
return moves;
|
||||
/** Legal plays for the current seat: [{ tileId, train, left, right }]. */
|
||||
export function getLegalMoves(s, seat = s.current) {
|
||||
if (s.phase !== 'playing' || seat !== s.current) return [];
|
||||
return movesFor(s, seat, s.players[seat].hand);
|
||||
}
|
||||
|
||||
// Place a tile. Returns new state. Advances the turn unless the placed tile is
|
||||
// a double (the player keeps the turn to cover it). Ends/score the round if the
|
||||
// player goes out.
|
||||
/** Plays a hand could make against the current table (no turn checks). */
|
||||
export function movesFor(s, seat, hand) {
|
||||
const out = [];
|
||||
for (const key of playableTrainKeys(s, seat)) {
|
||||
const end = trainOpenEnd(s, key);
|
||||
for (const t of hand) {
|
||||
if (t.a === end || t.b === end) out.push({ tileId: t.id, train: key, left: end, right: t.a === end ? t.b : t.a });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const pendingMine = (s, seat) => !!s.openDouble && s.openDouble.by === seat;
|
||||
|
||||
export function canDraw(s) {
|
||||
if (s.phase !== 'playing' || s.turn.drew || s.boneyard.length === 0) return false;
|
||||
if (s.turn.opening) return false; // can't start your train on the first turn: no draw, just the marker
|
||||
return getLegalMoves(s).length === 0;
|
||||
}
|
||||
|
||||
export function canPass(s) {
|
||||
if (s.phase !== 'playing') return false;
|
||||
if (s.turn.run && !pendingMine(s, s.current)) return false;
|
||||
if (getLegalMoves(s).length) return false;
|
||||
return s.turn.drew || s.boneyard.length === 0 || (s.turn.opening && s.turn.played === 0);
|
||||
}
|
||||
|
||||
/** Is any tile carrying `v` still unplayed (in a hand or the boneyard)? */
|
||||
export function numberLive(s, v) {
|
||||
const has = (t) => t.a === v || t.b === v;
|
||||
return s.boneyard.some(has) || s.players.some((p) => p.hand.some(has));
|
||||
}
|
||||
|
||||
/** May the current seat end its turn voluntarily (the opening run)? */
|
||||
export function canEndTurn(s) {
|
||||
return s.phase === 'playing' && !!s.turn.run && !pendingMine(s, s.current) && !s.turn.bonus;
|
||||
}
|
||||
|
||||
// ── actions ──────────────────────────────────────────────────────────────────
|
||||
export function playTile(state, move) {
|
||||
if (state.phase !== 'playing') return state;
|
||||
const legal = getLegalMoves(state).find((m) => m.tileId === move.tileId && m.train === move.train);
|
||||
if (!legal) return state;
|
||||
const s = cloneState(state);
|
||||
const player = s.players[s.current];
|
||||
const tile = player.hand[move.tileIndex];
|
||||
if (!tile) return state;
|
||||
|
||||
const seat = s.current;
|
||||
const p = s.players[seat];
|
||||
const hi = p.hand.findIndex((t) => t.id === move.tileId);
|
||||
const tile = p.hand[hi];
|
||||
p.hand.splice(hi, 1);
|
||||
delete s.voids[seat][tile.a];
|
||||
delete s.voids[seat][tile.b];
|
||||
const key = move.train;
|
||||
const end = trainOpenEnd(s, key);
|
||||
if (tile.a !== end && tile.b !== end) return state; // illegal
|
||||
|
||||
const left = tile.a === end ? tile.a : tile.b;
|
||||
const right = tile.a === end ? tile.b : tile.a;
|
||||
s.trains[key].tiles.push({ left, right });
|
||||
player.hand.splice(move.tileIndex, 1);
|
||||
|
||||
if (key === String(s.current)) s.trains[key].marker = false; // played own train
|
||||
const own = key === String(seat);
|
||||
const tr = s.trains[key];
|
||||
tr.tiles.push({ id: tile.id, left: legal.left, right: legal.right, by: seat });
|
||||
const st = s.stats[seat];
|
||||
st.played++;
|
||||
if (own) {
|
||||
tr.marker = false;
|
||||
st.longest = Math.max(st.longest, tr.tiles.length);
|
||||
}
|
||||
s.consecutivePasses = 0;
|
||||
const dbl = legal.left === legal.right;
|
||||
const cover = !!s.openDouble && s.openDouble.train === key;
|
||||
if (cover) { s.openDouble = null; st.covered++; activateDeferred(s); }
|
||||
if (dbl) st.doubles++;
|
||||
s.turn.played++;
|
||||
const wasBonus = s.turn.bonus;
|
||||
s.turn.bonus = false;
|
||||
s.lastEvent = { type: 'play', seat, tile: { id: tile.id, a: tile.a, b: tile.b }, train: key, left: legal.left, right: legal.right, double: dbl, cover, bonus: wasBonus };
|
||||
const where = own ? 'own train' : key === MEXICAN ? 'Mexican Train' : `${s.players[Number(key)].name}'s train`;
|
||||
pushLog(s, seat, `${tileName(tile)} → ${where}${cover ? ' (covered the double)' : ''}`);
|
||||
|
||||
const placedDouble = left === right;
|
||||
s.openDouble = placedDouble ? { train: key, value: right } : null;
|
||||
|
||||
if (player.hand.length === 0) {
|
||||
endRound(s);
|
||||
if (p.hand.length === 0) {
|
||||
st.outs++;
|
||||
endRound(s, false);
|
||||
return s;
|
||||
}
|
||||
if (!placedDouble) advance(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
// Draw one tile from the boneyard into the current player's hand.
|
||||
export function drawTile(state) {
|
||||
if (state.phase !== 'playing' || state.boneyard.length === 0) return state;
|
||||
const s = cloneState(state);
|
||||
s.players[s.current].hand.push(s.boneyard.pop());
|
||||
return s;
|
||||
}
|
||||
|
||||
export const canDraw = (state) => state.boneyard.length > 0;
|
||||
|
||||
// Current player gives up their turn: marks their own train and advances.
|
||||
export function passTurn(state) {
|
||||
if (state.phase !== 'playing') return state;
|
||||
const s = cloneState(state);
|
||||
s.trains[String(s.current)].marker = true;
|
||||
s.consecutivePasses += 1;
|
||||
advance(s);
|
||||
if (s.boneyard.length === 0 && s.consecutivePasses >= s.players.length) {
|
||||
endRound(s); // blocked
|
||||
// what happens next in this turn
|
||||
if (s.turn.opening) { s.turn.run = true; return s; } // the run goes on (a double is just part of the chain)
|
||||
if (dbl && s.openDouble == null) {
|
||||
if (s.opts.doubles === 'relaxed') { s.turn.drew = false; s.turn.bonus = true; return s; }
|
||||
if (numberLive(s, legal.right)) {
|
||||
s.turn.drew = false;
|
||||
s.openDouble = { train: key, value: legal.right, by: seat };
|
||||
return s; // keeps the turn to cover it
|
||||
}
|
||||
s.lastEvent.dead = true; // every other tile of that number is out: nothing to cover
|
||||
}
|
||||
endTurn_(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function advance(s) {
|
||||
s.current = (s.current + 1) % s.players.length;
|
||||
export function drawTile(state) {
|
||||
if (!canDraw(state)) return state;
|
||||
const s = cloneState(state);
|
||||
const seat = s.current;
|
||||
const t = s.boneyard.pop();
|
||||
s.players[seat].hand.push(t);
|
||||
s.players[seat].knocked = false;
|
||||
s.turn.drew = true;
|
||||
for (const v of Object.keys(s.voids[seat])) s.voids[seat][v]++;
|
||||
s.stats[seat].drawn++;
|
||||
s.lastEvent = { type: 'draw', seat, tile: { id: t.id, a: t.a, b: t.b }, playable: getLegalMoves(s).length > 0 };
|
||||
pushLog(s, seat, 'drew from the boneyard');
|
||||
return s;
|
||||
}
|
||||
|
||||
function endRound(s) {
|
||||
const roundPts = s.players.map((p) => p.hand.reduce((a, t) => a + t.a + t.b, 0));
|
||||
export function passTurn(state) {
|
||||
if (!canPass(state)) return state;
|
||||
const s = cloneState(state);
|
||||
const seat = s.current;
|
||||
// everyone saw them unable to play on any end open to them
|
||||
for (const k of playableTrainKeys(s, seat)) s.voids[seat][trainOpenEnd(s, k)] = 0;
|
||||
const mark = s.turn.played === 0 || pendingMine(s, seat);
|
||||
if (mark) {
|
||||
s.trains[String(seat)].marker = true;
|
||||
s.stats[seat].passes++;
|
||||
}
|
||||
if (s.turn.played === 0) s.consecutivePasses++;
|
||||
s.lastEvent = { type: 'pass', seat, marked: mark, double: s.openDouble ? { ...s.openDouble } : null };
|
||||
pushLog(s, seat, mark ? (s.openDouble ? "couldn't cover — train open" : 'passed — train open') : 'ended the turn');
|
||||
endTurn_(s);
|
||||
if (s.phase === 'playing' && s.boneyard.length === 0 && s.consecutivePasses >= s.n) endRound(s, true);
|
||||
return s;
|
||||
}
|
||||
|
||||
export function endTurn(state) {
|
||||
if (!canEndTurn(state)) return state;
|
||||
const s = cloneState(state);
|
||||
// a run that ends on a double: covered once everyone has had their first turn
|
||||
const tr = s.trains[String(s.current)].tiles;
|
||||
const last = tr[tr.length - 1];
|
||||
if (last && last.left === last.right && s.opts.doubles === 'cover') s.deferred.push({ train: String(s.current), value: last.right, by: -1 });
|
||||
s.lastEvent = { type: 'end', seat: s.current, played: s.turn.played };
|
||||
pushLog(s, s.current, `ended the opening run (${s.turn.played} tile${s.turn.played === 1 ? '' : 's'})`);
|
||||
endTurn_(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
function endTurn_(s) {
|
||||
const seat = s.current;
|
||||
s.firstDone[seat] = true;
|
||||
s.current = (seat + 1) % s.n;
|
||||
s.turn = freshTurn(s, s.current);
|
||||
if (s.firstDone.every(Boolean)) activateDeferred(s);
|
||||
}
|
||||
|
||||
// Opening-run doubles are covered in the order they were laid, starting once
|
||||
// every seat has had its first turn. Dead ones (no tile of that number left)
|
||||
// and ones already covered are skipped.
|
||||
function activateDeferred(s) {
|
||||
if (s.openDouble || !s.deferred?.length || !s.firstDone.every(Boolean)) return;
|
||||
while (s.deferred.length) {
|
||||
const d = s.deferred.shift();
|
||||
const tr = s.trains[d.train].tiles;
|
||||
const last = tr[tr.length - 1];
|
||||
if (!last || last.left !== last.right || last.right !== d.value) continue;
|
||||
if (!numberLive(s, d.value)) continue;
|
||||
s.openDouble = d;
|
||||
pushLog(s, Number(d.train) || 0, `the ${d.value}-${d.value} must now be covered`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ── knocking (house rule) ────────────────────────────────────────────────────
|
||||
export function knock(state, seat) {
|
||||
const p = state.players[seat];
|
||||
if (!p || p.knocked || p.hand.length > 2 || state.phase !== 'playing') return state;
|
||||
const s = cloneState(state);
|
||||
s.players[seat].knocked = true;
|
||||
s.lastEvent = { type: 'knock', seat };
|
||||
pushLog(s, seat, 'knocked — one tile to go');
|
||||
return s;
|
||||
}
|
||||
export function catchable(s, seat) {
|
||||
const p = s.players[seat];
|
||||
return !!s.opts.knock && s.phase === 'playing' && p.hand.length === 1 && !p.knocked;
|
||||
}
|
||||
/** `catcher` calls out `target` for not knocking: target draws two. */
|
||||
export function catchKnock(state, catcher, target) {
|
||||
if (!catchable(state, target)) return state;
|
||||
const s = cloneState(state);
|
||||
const p = s.players[target];
|
||||
let drawn = 0;
|
||||
while (drawn < 2 && s.boneyard.length) { p.hand.push(s.boneyard.pop()); drawn++; }
|
||||
for (const v of Object.keys(s.voids[target])) s.voids[target][v] += drawn;
|
||||
p.knocked = false;
|
||||
s.stats[target].caught++;
|
||||
s.lastEvent = { type: 'caught', seat: target, by: catcher, drawn };
|
||||
pushLog(s, catcher, `caught ${s.players[target].name} not knocking (+${drawn})`);
|
||||
return s;
|
||||
}
|
||||
|
||||
// ── round / match end ────────────────────────────────────────────────────────
|
||||
function endRound(s, blocked) {
|
||||
const pts = s.players.map((p) => handPips(p.hand, s.opts));
|
||||
let winner = s.players.findIndex((p) => p.hand.length === 0);
|
||||
if (winner === -1) winner = roundPts.indexOf(Math.min(...roundPts)); // blocked
|
||||
s.players.forEach((p, i) => { p.score += roundPts[i]; });
|
||||
s.lastRoundScores = roundPts;
|
||||
if (winner === -1) {
|
||||
const min = Math.min(...pts);
|
||||
// ties broken in turn order from the seat to play
|
||||
for (let k = 0; k < s.n; k++) { const i = (s.current + k) % s.n; if (pts[i] === min) { winner = i; break; } }
|
||||
}
|
||||
s.players.forEach((p, i) => { p.score += pts[i]; });
|
||||
s.lastRoundScores = pts;
|
||||
s.roundWinner = winner;
|
||||
s.startPlayer = winner;
|
||||
s.phase = s.players.some((p) => p.score >= s.target) ? 'gameover' : 'roundover';
|
||||
s.blocked = blocked;
|
||||
s.stats[winner].roundsWon++;
|
||||
s.history.push({ round: s.round, hub: s.hub.value, scores: pts.slice(), totals: s.players.map((p) => p.score), winner, blocked, tiles: Object.fromEntries(Object.entries(s.trains).map(([k, t]) => [k, t.tiles.length])) });
|
||||
s.openDouble = null;
|
||||
s.deferred = [];
|
||||
s.lastEvent = { type: 'roundEnd', winner, blocked, scores: pts.slice() };
|
||||
pushLog(s, winner, blocked ? 'wins the blocked round' : 'went out!');
|
||||
const total = roundsTotal(s.opts);
|
||||
const over = total != null ? s.history.length >= total : s.players.some((p) => p.score >= s.opts.target);
|
||||
s.phase = over ? 'gameover' : 'roundover';
|
||||
}
|
||||
|
||||
export const isMatchOver = (state) => state.phase === 'gameover';
|
||||
export const isMatchOver = (s) => s.phase === 'gameover';
|
||||
|
||||
// Match winners: indices tied for the lowest cumulative score.
|
||||
export function getWinners(state) {
|
||||
const min = Math.min(...state.players.map((p) => p.score));
|
||||
return state.players.map((p, i) => ({ i, s: p.score })).filter((x) => x.s === min).map((x) => x.i);
|
||||
// Ranking key: lowest total, then most 0-point rounds, then lowest non-zero round.
|
||||
function rankKey(s, i) {
|
||||
const rounds = s.history.map((h) => h.scores[i]);
|
||||
const zeros = rounds.filter((x) => x === 0).length;
|
||||
const nz = rounds.filter((x) => x > 0);
|
||||
return [s.players[i].score, -zeros, nz.length ? Math.min(...nz) : 0];
|
||||
}
|
||||
function cmpRank(s, a, b) {
|
||||
const ka = rankKey(s, a), kb = rankKey(s, b);
|
||||
for (let k = 0; k < ka.length; k++) if (ka[k] !== kb[k]) return ka[k] - kb[k];
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** The match winner(s): lowest total, ties broken as above (a true tie is shared). */
|
||||
export function getWinners(s) {
|
||||
const order = rankings(s);
|
||||
return order.filter((i) => cmpRank(s, i, order[0]) === 0);
|
||||
}
|
||||
|
||||
/** Seats ordered best to worst. */
|
||||
export function rankings(s) {
|
||||
return s.players.map((p, i) => i).sort((a, b) => cmpRank(s, a, b) || a - b);
|
||||
}
|
||||
|
||||
/** Every tile id the given seat can't see (others' hands + boneyard). */
|
||||
export function unseenTiles(s, seat) {
|
||||
const seen = new Set([s.hub.id]);
|
||||
for (const t of s.players[seat].hand) seen.add(t.id);
|
||||
for (const tr of Object.values(s.trains)) for (const t of tr.tiles) seen.add(t.id);
|
||||
return makeTileSet(s.opts.set).filter((t) => !seen.has(t.id));
|
||||
}
|
||||
|
||||
/** Sanity: every tile exactly once across hub/hands/boneyard/trains. */
|
||||
export function tileCensus(s) {
|
||||
const ids = [s.hub.id];
|
||||
for (const p of s.players) for (const t of p.hand) ids.push(t.id);
|
||||
for (const t of s.boneyard) ids.push(t.id);
|
||||
for (const tr of Object.values(s.trains)) for (const t of tr.tiles) ids.push(t.id);
|
||||
return { total: ids.length, unique: new Set(ids).size, expected: tileCount(s.opts.set) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,209 @@
|
|||
// MexicanTrainSound.js — tiny Web Audio synths for the kitchen table. No audio
|
||||
// files; silent without Web Audio or when the game is muted.
|
||||
//
|
||||
// clack(scene, {k}) a domino set down on the oak (k varies the pitch a hair)
|
||||
// rackTick(scene) a tile nudged on the wooden rack
|
||||
// wash(scene, secs) the face-down tiles swirled ("washing the bones")
|
||||
// whistle(scene) the little toy-train toot (a train opens / closes)
|
||||
// knockKnock(scene) two knuckle raps on the table
|
||||
// pencil(scene, secs) a pencil scratching on the score pad
|
||||
// chime(scene) someone goes out
|
||||
// Ambience birds outside, the kitchen clock, a far-off mower
|
||||
|
||||
function ctxOf(scene) {
|
||||
const sm = scene?.sound;
|
||||
if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null;
|
||||
return sm.context;
|
||||
}
|
||||
const noiseCache = new WeakMap();
|
||||
function noise(ac) {
|
||||
if (noiseCache.has(ac)) return noiseCache.get(ac);
|
||||
const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate);
|
||||
const d = buf.getChannelData(0);
|
||||
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
|
||||
noiseCache.set(ac, buf);
|
||||
return buf;
|
||||
}
|
||||
function out(scene, ac, gain) {
|
||||
const sm = scene.sound;
|
||||
const node = sm.masterVolumeNode ?? sm.destination ?? null;
|
||||
const g = ac.createGain();
|
||||
g.gain.value = node ? gain : gain * (sm.volume ?? 1);
|
||||
g.connect(node ?? ac.destination);
|
||||
return g;
|
||||
}
|
||||
function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.004 } = {}) {
|
||||
const o = ac.createOscillator(); o.type = type;
|
||||
o.frequency.setValueAtTime(f, t0);
|
||||
if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d);
|
||||
const g = ac.createGain();
|
||||
g.gain.setValueAtTime(0, t0);
|
||||
g.gain.linearRampToValueAtTime(a, t0 + attack);
|
||||
g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
|
||||
o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03);
|
||||
}
|
||||
function burst(ac, dest, t0, f, { q = 2, vol = 1, d = 0.03, type = 'bandpass' } = {}) {
|
||||
const n = ac.createBufferSource(); n.buffer = noise(ac);
|
||||
const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.value = f; bp.Q.value = q;
|
||||
const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
|
||||
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02);
|
||||
}
|
||||
const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } };
|
||||
|
||||
export function clack(scene, { k = 0, vol = 0.22 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
|
||||
const f = 2300 + ((k * 137) % 5) * 140 + Math.random() * 120;
|
||||
burst(ac, dest, t, f, { q: 3.5, vol: 1, d: 0.045 });
|
||||
burst(ac, dest, t + 0.012, f * 1.6, { q: 5, vol: 0.4, d: 0.03 });
|
||||
tone(ac, dest, t, 180, { type: 'sine', a: 0.6, d: 0.07, glide: 0.6 }); // the wood underneath
|
||||
});
|
||||
}
|
||||
|
||||
export function rackTick(scene, { vol = 0.1 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
|
||||
burst(ac, dest, t, 3200 + Math.random() * 400, { q: 4, d: 0.025 });
|
||||
tone(ac, dest, t, 300, { a: 0.3, d: 0.04, glide: 0.7 });
|
||||
});
|
||||
}
|
||||
|
||||
export function wash(scene, secs = 1.6, { vol = 0.16 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t0 = ac.currentTime + 0.01;
|
||||
// a bed of sliding hiss…
|
||||
const n = ac.createBufferSource(); n.buffer = noise(ac); n.loop = true;
|
||||
const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 1800; bp.Q.value = 0.8;
|
||||
const g = ac.createGain();
|
||||
g.gain.setValueAtTime(0, t0);
|
||||
g.gain.linearRampToValueAtTime(0.25, t0 + 0.2);
|
||||
g.gain.setValueAtTime(0.25, t0 + secs - 0.3);
|
||||
g.gain.linearRampToValueAtTime(0, t0 + secs);
|
||||
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0); n.stop(t0 + secs + 0.05);
|
||||
// …and the tiles knocking into each other
|
||||
const clicks = Math.round(secs * 34);
|
||||
for (let i = 0; i < clicks; i++) {
|
||||
const t = t0 + Math.random() * secs;
|
||||
burst(ac, dest, t, 2000 + Math.random() * 2400, { q: 4, vol: 0.25 + Math.random() * 0.5, d: 0.025 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function whistle(scene, { vol = 0.06 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
|
||||
for (const [f, dt, d] of [[880, 0, 0.18], [1108, 0, 0.18], [880, 0.22, 0.3], [1108, 0.22, 0.3]]) {
|
||||
const o = ac.createOscillator(); o.type = 'triangle';
|
||||
o.frequency.setValueAtTime(f * 0.97, t + dt); o.frequency.linearRampToValueAtTime(f, t + dt + 0.05);
|
||||
const lfo = ac.createOscillator(); lfo.frequency.value = 7;
|
||||
const lg = ac.createGain(); lg.gain.value = 6;
|
||||
lfo.connect(lg); lg.connect(o.frequency);
|
||||
const g = ac.createGain();
|
||||
g.gain.setValueAtTime(0, t + dt); g.gain.linearRampToValueAtTime(0.5, t + dt + 0.03);
|
||||
g.gain.setValueAtTime(0.5, t + dt + d - 0.05); g.gain.linearRampToValueAtTime(0, t + dt + d);
|
||||
o.connect(g); g.connect(dest); o.start(t + dt); lfo.start(t + dt); o.stop(t + dt + d + 0.02); lfo.stop(t + dt + d + 0.02);
|
||||
}
|
||||
burst(ac, dest, t, 4000, { q: 0.6, vol: 0.15, d: 0.5, type: 'highpass' });
|
||||
});
|
||||
}
|
||||
|
||||
export function knockKnock(scene, { vol = 0.35 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
|
||||
for (const dt of [0, 0.17]) {
|
||||
tone(ac, dest, t + dt, 150, { a: 1, d: 0.12, glide: 0.7 });
|
||||
burst(ac, dest, t + dt, 900, { q: 1.5, vol: 0.7, d: 0.05 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function pencil(scene, secs = 0.6, { vol = 0.08 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t0 = ac.currentTime + 0.01;
|
||||
const strokes = Math.max(2, Math.round(secs * 7));
|
||||
for (let i = 0; i < strokes; i++) {
|
||||
const t = t0 + (i / strokes) * secs;
|
||||
burst(ac, dest, t, 5200 + Math.random() * 1600, { q: 1.2, vol: 0.8, d: 0.08 + Math.random() * 0.05 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function chime(scene, { vol = 0.07 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
|
||||
for (const [f, a, d, dt] of [[660, 1, 1.4, 0], [831, 0.8, 1.2, 0.1], [990, 0.7, 1.1, 0.2], [1320, 0.4, 1.0, 0.3]]) tone(ac, dest, t + dt, f, { a, d });
|
||||
});
|
||||
}
|
||||
|
||||
export function thud(scene, { vol = 0.25 } = {}) {
|
||||
const ac = ctxOf(scene); if (!ac) return;
|
||||
safe(() => {
|
||||
const dest = out(scene, ac, vol), t = ac.currentTime + 0.005;
|
||||
tone(ac, dest, t, 120, { a: 1, d: 0.4, glide: 0.5 });
|
||||
});
|
||||
}
|
||||
|
||||
/** Afternoon sounds through the open window. Each layer can be switched. */
|
||||
export class Ambience {
|
||||
constructor(scene) { this.scene = scene; this.timers = []; this.mower = null; this.on = { birds: false, clock: false }; }
|
||||
set(layer, on) {
|
||||
if (this.on[layer] === on) return;
|
||||
this.on[layer] = on;
|
||||
this.restart();
|
||||
}
|
||||
restart() {
|
||||
this.stop();
|
||||
const s = this.scene;
|
||||
if (this.on.clock) {
|
||||
let tock = false;
|
||||
this.timers.push(setInterval(() => {
|
||||
const ac = ctxOf(s); if (!ac) return;
|
||||
safe(() => { const d = out(s, ac, 0.018), t = ac.currentTime + 0.01; burst(ac, d, t, tock ? 2600 : 3300, { q: 6, d: 0.03 }); tock = !tock; });
|
||||
}, 1000));
|
||||
}
|
||||
if (this.on.birds) {
|
||||
const chirp = () => {
|
||||
const ac = ctxOf(s); if (!ac) return;
|
||||
safe(() => {
|
||||
const d = out(s, ac, 0.02), t = ac.currentTime + 0.02;
|
||||
const base = 2600 + Math.random() * 1800, notes = 2 + Math.floor(Math.random() * 4);
|
||||
for (let i = 0; i < notes; i++) tone(ac, d, t + i * 0.09, base * (1 + (Math.random() - 0.5) * 0.25), { a: 0.8, d: 0.07, glide: 1.3 + Math.random() * 0.4 });
|
||||
});
|
||||
};
|
||||
this.timers.push(setInterval(() => { if (Math.random() < 0.45) chirp(); }, 1900));
|
||||
this.startMower();
|
||||
}
|
||||
}
|
||||
startMower() {
|
||||
const ac = ctxOf(this.scene); if (!ac) return;
|
||||
try {
|
||||
const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true;
|
||||
const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 320; lp.Q.value = 3;
|
||||
const g = ac.createGain(); g.gain.value = 0;
|
||||
const lfo = ac.createOscillator(); lfo.frequency.value = 0.05; // comes and goes
|
||||
const lg = ac.createGain(); lg.gain.value = 0.006;
|
||||
const bias = ac.createConstantSource ? ac.createConstantSource() : null;
|
||||
lfo.connect(lg); lg.connect(g.gain);
|
||||
if (bias) { bias.offset.value = 0.006; bias.connect(g.gain); bias.start(); }
|
||||
const base = out(this.scene, ac, 1);
|
||||
src.connect(lp); lp.connect(g); g.connect(base);
|
||||
src.start(); lfo.start();
|
||||
this.mower = { src, lfo, bias, base };
|
||||
} catch (_) { this.mower = null; }
|
||||
}
|
||||
stop() {
|
||||
this.timers.forEach(clearInterval);
|
||||
this.timers = [];
|
||||
if (this.mower) {
|
||||
const m = this.mower; this.mower = null;
|
||||
try { m.src.stop(); m.lfo.stop(); m.bias?.stop(); m.base.disconnect(); } catch (_) { /* gone */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
// MexicanTrainTiles.js — one persistent sprite per domino (keyed by tile id),
|
||||
// with its own soft shadow. Tiles never get redrawn: they slide, lift, flip
|
||||
// and clack between the boneyard, the racks, the hub and the trains.
|
||||
//
|
||||
// const ts = new TileSprites(scene, { colored });
|
||||
// ts.reset(set) — (re)create sprites for a whole set
|
||||
// ts.set(id, pose) — snap: { x, y, rot, s, faceUp, depth, visible }
|
||||
// await ts.move(id, pose, { dur, lift, delay, ease }) — tween (flips mid-way)
|
||||
// ts.pick(x, y, ids) — top-most of `ids` under a point
|
||||
|
||||
import * as Phaser from 'phaser';
|
||||
import { tileKey } from './MexicanTrainArt.js';
|
||||
|
||||
const SHADOW = { dx: 3, dy: 5 };
|
||||
|
||||
export class TileSprites {
|
||||
constructor(scene, { colored = true, depth = 20 } = {}) {
|
||||
this.scene = scene;
|
||||
this.colored = colored;
|
||||
this.depth = depth;
|
||||
this.items = new Map();
|
||||
}
|
||||
|
||||
reset(set) {
|
||||
for (const it of this.items.values()) { it.face.destroy(); it.shadow.destroy(); }
|
||||
this.items.clear();
|
||||
for (let a = 0; a <= set; a++) for (let b = a; b <= set; b++) this.create({ id: this.items.size, a, b });
|
||||
}
|
||||
|
||||
create(tile) {
|
||||
const s = this.scene;
|
||||
const shadow = s.add.image(0, 0, 'mt-tshadow').setVisible(false).setDepth(this.depth - 1);
|
||||
const face = s.add.image(0, 0, 'mt-back').setVisible(false).setDepth(this.depth);
|
||||
const it = { tile, face, shadow, x: 0, y: 0, rot: 0, s: 0.4, faceUp: false, lift: 0, sq: 1, tween: null };
|
||||
this.items.set(tile.id, it);
|
||||
return it;
|
||||
}
|
||||
|
||||
get(id) { return this.items.get(id); }
|
||||
|
||||
/** Stop a tile's tween; anyone awaiting it is released (never left hanging). */
|
||||
halt(it) {
|
||||
if (it.tween) { it.tween.stop(); it.tween = null; }
|
||||
const done = it.done;
|
||||
it.done = null;
|
||||
done?.();
|
||||
}
|
||||
tileOf(id) { return this.items.get(id)?.tile; }
|
||||
|
||||
setColored(colored) {
|
||||
this.colored = colored;
|
||||
for (const it of this.items.values()) if (it.faceUp) it.face.setTexture(tileKey(it.tile.a, it.tile.b, colored));
|
||||
}
|
||||
|
||||
apply(it) {
|
||||
const sx = it.s, sy = it.s * it.sq;
|
||||
it.face.setPosition(it.x, it.y - it.lift).setRotation(it.rot).setScale(sx, sy);
|
||||
const off = 1 + it.lift * 0.09;
|
||||
it.shadow.setPosition(it.x + SHADOW.dx * off * it.s * 2.2, it.y + SHADOW.dy * off * it.s * 2.2).setRotation(it.rot)
|
||||
.setScale(sx * (1 + it.lift * 0.004), sy * (1 + it.lift * 0.004)).setAlpha(Math.max(0.25, 0.85 - it.lift * 0.012));
|
||||
}
|
||||
|
||||
setFace(it, up) {
|
||||
it.faceUp = up;
|
||||
it.face.setTexture(up ? tileKey(it.tile.a, it.tile.b, this.colored) : 'mt-back');
|
||||
}
|
||||
|
||||
setDepth(id, d) {
|
||||
const it = this.items.get(id);
|
||||
if (!it) return;
|
||||
it.face.setDepth(d);
|
||||
it.shadow.setDepth(d - 0.5);
|
||||
}
|
||||
|
||||
/** Snap a tile to a pose. */
|
||||
set(id, pose) {
|
||||
const it = this.items.get(id);
|
||||
if (!it) return null;
|
||||
this.halt(it);
|
||||
Object.assign(it, { x: pose.x ?? it.x, y: pose.y ?? it.y, rot: pose.rot ?? it.rot, s: pose.s ?? it.s, lift: pose.lift ?? 0, sq: 1 });
|
||||
if (pose.faceUp != null) this.setFace(it, pose.faceUp);
|
||||
if (pose.depth != null) this.setDepth(id, pose.depth);
|
||||
const vis = pose.visible ?? true;
|
||||
it.face.setVisible(vis); it.shadow.setVisible(vis && !pose.noShadow);
|
||||
it.face.setAlpha(pose.alpha ?? 1);
|
||||
this.apply(it);
|
||||
return it;
|
||||
}
|
||||
|
||||
/** Tween a tile to a pose. Turns face-up/down half-way when asked. */
|
||||
move(id, pose, { dur = 380, lift = 0, delay = 0, ease = 'Cubic.InOut', onLand = null } = {}) {
|
||||
const it = this.items.get(id);
|
||||
if (!it) return Promise.resolve();
|
||||
this.halt(it);
|
||||
it.face.setVisible(true); it.shadow.setVisible(!pose.noShadow);
|
||||
if (pose.alpha != null) it.face.setAlpha(pose.alpha);
|
||||
if (pose.depth != null) this.setDepth(id, pose.depth);
|
||||
const from = { x: it.x, y: it.y, rot: it.rot, s: it.s };
|
||||
const to = { x: pose.x ?? it.x, y: pose.y ?? it.y, rot: pose.rot ?? it.rot, s: pose.s ?? it.s };
|
||||
// shortest way round
|
||||
let dr = to.rot - from.rot;
|
||||
while (dr > Math.PI) dr -= Math.PI * 2;
|
||||
while (dr < -Math.PI) dr += Math.PI * 2;
|
||||
const flip = pose.faceUp != null && pose.faceUp !== it.faceUp;
|
||||
let flipped = false;
|
||||
if (dur <= 0) { this.set(id, { ...pose }); onLand?.(); return Promise.resolve(); }
|
||||
return new Promise((resolve) => {
|
||||
it.done = resolve;
|
||||
const p = { t: 0 };
|
||||
it.tween = this.scene.tweens.add({
|
||||
targets: p, t: 1, duration: dur, delay, ease,
|
||||
onUpdate: () => {
|
||||
const t = p.t;
|
||||
it.x = Phaser.Math.Linear(from.x, to.x, t);
|
||||
it.y = Phaser.Math.Linear(from.y, to.y, t);
|
||||
it.rot = from.rot + dr * t;
|
||||
it.s = Phaser.Math.Linear(from.s, to.s, t);
|
||||
it.lift = lift * Math.sin(Math.PI * t);
|
||||
if (flip) {
|
||||
it.sq = Math.max(0.04, Math.abs(Math.cos(Math.PI * t)));
|
||||
if (!flipped && t >= 0.5) { flipped = true; this.setFace(it, pose.faceUp); }
|
||||
}
|
||||
this.apply(it);
|
||||
},
|
||||
onComplete: () => {
|
||||
it.tween = null;
|
||||
if (flip && !flipped) this.setFace(it, pose.faceUp);
|
||||
Object.assign(it, { x: to.x, y: to.y, rot: to.rot, s: to.s, lift: 0, sq: 1 });
|
||||
this.apply(it);
|
||||
if (pose.visible === false) { it.face.setVisible(false); it.shadow.setVisible(false); }
|
||||
onLand?.();
|
||||
it.done = null;
|
||||
resolve();
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
hide(id) {
|
||||
const it = this.items.get(id);
|
||||
if (!it) return;
|
||||
this.halt(it);
|
||||
it.face.setVisible(false); it.shadow.setVisible(false);
|
||||
}
|
||||
|
||||
/** Lift (or drop) a resting tile without moving it — hover feedback. */
|
||||
hover(id, lift, dur = 120) {
|
||||
const it = this.items.get(id);
|
||||
if (!it || it.tween) return;
|
||||
const p = { l: it.lift };
|
||||
this.scene.tweens.add({ targets: p, l: lift, duration: dur, ease: 'Quad.Out', onUpdate: () => { it.lift = p.l; this.apply(it); } });
|
||||
}
|
||||
|
||||
/** Top-most visible tile of `ids` under (x, y). */
|
||||
pick(x, y, ids) {
|
||||
let best = null, bd = -Infinity;
|
||||
for (const id of ids) {
|
||||
const it = this.items.get(id);
|
||||
if (!it || !it.face.visible) continue;
|
||||
const c = Math.cos(-it.rot), s = Math.sin(-it.rot);
|
||||
const dx = x - it.x, dy = y - (it.y - it.lift);
|
||||
const lx = dx * c - dy * s, ly = dx * s + dy * c;
|
||||
const hw = (it.face.width * it.s) / 2, hh = (it.face.height * it.s * it.sq) / 2;
|
||||
if (Math.abs(lx) <= hw && Math.abs(ly) <= hh && it.face.depth > bd) { bd = it.face.depth; best = id; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
|
@ -4,101 +4,90 @@
|
|||
|
||||
---
|
||||
|
||||
Well, pull up a chair and set a spell! Name's Jerry. Got my chores done early today — Bessie was cooperative as ever, gave a full bucket by sunrise — so I figured I'd sit down and teach you the best domino game this side of the Mississippi. Grab yourself a glass of sweet tea and let's get to it!
|
||||
Well, pull up a chair at the kitchen table and set a spell! Name's Jerry. Chores are done, the lemonade's poured, the cat's asleep on the end of the table like she owns it — so let's wash the bones and play the best domino game this side of the Mississippi.
|
||||
|
||||
I learned Mexican Train from my neighbor Earl at the county fair about twelve years back. We were waiting out a thunderstorm in the equipment barn and he had a set in his jacket pocket. Been playing ever since. Even taught Bessie to watch, though she mostly just chews her cud and judges my tile choices.
|
||||
I learned Mexican Train from my neighbor Earl at the county fair, waiting out a thunderstorm in the equipment barn. He had a double-twelve set in his jacket pocket. Been playing every Sunday afternoon since.
|
||||
|
||||
## What's the Big Picture?
|
||||
|
||||
Mexican Train is a domino game where everybody's building trains of tiles out from a central hub. **The player with the LOWEST score at the end wins** — and that right there is the key. You're not trying to rack up points. You're trying to get rid of every last tile in your hand before the round ends, because whatever pips are left in your hand get added to your score. When any player hits 100 points, the match is over and whoever's got the least points wins.
|
||||
Everybody builds trains of dominoes out from a station hub in the middle of the table. **The LOWEST score wins.** Whatever pips are still in your hand when a round ends get added to your score — so the whole idea is to get rid of your tiles, and the heavy ones first.
|
||||
|
||||
Think of it like getting your field work done before the rain comes. You want to get those tiles played out quick, or you're stuck holding the bag!
|
||||
We play with a **double-twelve set** (91 tiles), and a match is **13 rounds**: the first round starts on the 12-12, then 11-11, all the way down to the 0-0. Lowest total after the 0-0 round wins the match. If two of you tie, the one with more 0-point rounds wins; still tied, the lowest non-zero round. (In the menu you can switch to a double-nine or double-six set, or play "first to so-many points" instead.)
|
||||
|
||||
## The Hub — That's Your Engine Double
|
||||
## Washing the Bones and the Deal
|
||||
|
||||
Each round starts with a special tile called the **engine double** placed right in the center. Round one uses the double-6, then double-5, all the way down to double-0. That center tile is the hub everything branches out from.
|
||||
At the start of every round, all the tiles get swirled face-down on the table — that's "washing the bones." That round's **engine double** goes in the hub, and everybody draws 15 tiles onto their rack (fewer with the smaller sets). What's left over is the **boneyard**, piled up beside the old wooden box.
|
||||
|
||||
Whoever plays first in a round kicks things off. The round winner from last round goes first in the next one. Fair and neighborly!
|
||||
## The Trains
|
||||
|
||||
## Trains — Your Track Out of the Station
|
||||
Every player has a **personal train** that runs from the hub toward their seat, and there's one shared **Mexican Train** with the little purple engine on it.
|
||||
|
||||
Radiating out from that hub are the **trains** — one personal train for each player, plus one shared **Mexican Train** that anybody can play on.
|
||||
- **Your train**: always yours to play on.
|
||||
- **The Mexican Train**: anybody, anytime.
|
||||
- **Somebody else's train**: only while it's **open**. A train opens when its owner couldn't play — you'll see their little toy engine parked at the start of it, and an OPEN stamp on their card. It stays open until they play on their own train again.
|
||||
|
||||
- **Your train**: All yours. You can always play here.
|
||||
- **The Mexican Train**: Belongs to everybody. Open season, any time.
|
||||
- **Other players' trains**: Normally off-limits — BUT if a player couldn't play on their turn, their train gets **marked** (you'll see a marker on it). A marked train is open for anyone to play on. It's like a neighbor who left their gate unlatched — anybody can wander in!
|
||||
The first tile on any train has to match the engine number. After that, each tile has to match the number showing at the end of that train. The little wooden token at the end of each train tells you exactly what number it needs.
|
||||
|
||||
When a train gets marked, it stays marked until that player successfully plays on their own train. Once they do, the marker comes off and it's private again.
|
||||
Long trains don't fall off the table — when one reaches the edge it turns a corner and snakes back, just like at home. If the table gets really crowded, everything shifts in a bit so it all fits.
|
||||
|
||||
## How a Turn Works
|
||||
## Your Turn
|
||||
|
||||
### Step 1: Can You Play?
|
||||
You play **one tile per turn** — that's the standard game.
|
||||
|
||||
Look at your hand. Each tile has two pip values. You need a tile whose end matches the **open end** of a train you're allowed to play on.
|
||||
1. **Play a tile** that matches an end you're allowed to use. Click it, or drag it onto one of the glowing spots. If it only fits one place, a click puts it right there.
|
||||
2. **Can't play?** Draw one from the boneyard (click the pile or press D). If it fits, you've got to play it.
|
||||
3. **Still can't?** You pass, and **your train opens** for everybody. That's the painful part!
|
||||
|
||||
- The very first tile on any train must match the hub value (e.g., a 6 on either end to start round 1).
|
||||
- After that, each new tile must match whatever pip count is showing at the end of that train.
|
||||
### Doubles
|
||||
|
||||
If you've got a match, pick your tile and pick your train!
|
||||
When you play a **double**, you play again — and that second tile has to **cover the double**. Until it's covered, nobody plays anywhere else. If you can't cover it, even after drawing, your train opens and the next player has to cover it, and so on round the table. The end token turns red while a double is waiting.
|
||||
|
||||
### Step 2: No Match? Draw from the Boneyard
|
||||
One exception: if every other tile with that number is already on the table, there's nothing left to cover it with, so it doesn't need covering.
|
||||
|
||||
Can't play? That happens. Head to the **boneyard** — the pile of leftover tiles — and draw one. Maybe you'll get lucky and draw something you can use. Bessie always says the boneyard is like the bargain bin at the farm supply store: sometimes you find gold, sometimes you find nothing useful.
|
||||
(House rule option: "bonus play" — a double doesn't need covering, it just earns you one extra play anywhere.)
|
||||
|
||||
If that drawn tile plays, go right ahead and play it. If not, well...
|
||||
### First-Turn Run (house rule, off unless you turn it on)
|
||||
|
||||
### Step 3: Still Can't Play? Pass Your Turn
|
||||
|
||||
If you draw and still can't play, you've got to **pass**. And here's the painful part: when you pass, **your personal train gets marked**. That means everyone else can play on your train until you get back on it yourself.
|
||||
|
||||
It's like borrowing Earl's tractor — you don't want folks poking around your train, so get back on it as soon as you can!
|
||||
|
||||
## Doubles — The House Rule That Keeps Things Spicy
|
||||
|
||||
Oh, doubles. Here's where things get real interesting. When someone plays a **double tile** (same number on both ends, like 4-4 or 2-2), that double **must be covered immediately**.
|
||||
|
||||
The player who laid the double keeps their turn and gets to try covering it first. If they can, great — play continues normally. If they *can't* cover it, then they draw from the boneyard. If they still can't cover it, the next player *must* cover it before doing anything else.
|
||||
|
||||
Until that double is covered, everybody's locked into covering it. No playing elsewhere. No shenanigans. It's like a fence post that's fallen over — you fix it before you do anything else, or everything goes sideways.
|
||||
Some families let everybody, on their **first turn of each round**, lay as many tiles as chain together onto **their own train** (nowhere else), then press **End Turn**. You can't draw on that first turn — if you can't start your train, it just opens. A double at the end of somebody's run gets covered once everybody has had their first turn. When it's on, you'll see folks lay out a whole string of tiles at once — that's why!
|
||||
|
||||
## How a Round Ends
|
||||
|
||||
The round ends when:
|
||||
- **Someone plays their last tile** — that player wins the round with 0 points, and everyone else counts up the pips left in their hand.
|
||||
- **The round gets blocked** — if the boneyard's empty and nobody can play, the round ends. Everyone counts their pips and the player with the fewest pips wins that round.
|
||||
- **Somebody plays their last tile** — "Domino!" They score 0, and everybody else counts their pips.
|
||||
- **The round is blocked** — the boneyard's empty and nobody can play. Everybody counts up.
|
||||
|
||||
Those pip totals get added to your running score. Low score stays low, and that's what you want!
|
||||
The pencil scratches the totals onto the score pad by the lemonade. You can tap that pad any time to see the whole thing, round by round.
|
||||
|
||||
## Scoring Quick Reference
|
||||
## Kitchen-Table House Rules (in the Menu)
|
||||
|
||||
| Situation | Your Score |
|
||||
|---|---|
|
||||
| Emptied your hand | 0 points this round |
|
||||
| Round ends with tiles left | Sum of all pips on remaining tiles |
|
||||
| Match over (someone hits 100) | Lowest total score wins! |
|
||||
- **Domino set**: double-12, double-9 or double-6.
|
||||
- **Match**: one round per engine (the classic), or first to 100 / 200 / 300 / 500.
|
||||
- **First-turn run** (lay out your whole train on your first turn), **doubles** (must be covered or bonus play).
|
||||
- **Double-blank counts 50** — get caught holding the 0-0 and it costs you!
|
||||
- **Knock on your last tile** — when you get down to one tile you've got to knock (K). Forget, and if somebody catches you, you draw two. And if *they* forget to knock, hit **Catch!** quick.
|
||||
|
||||
## Handy Things on the Table
|
||||
|
||||
- **Hover a tile** to see where it fits; tiles you can't use right now sit a bit dimmer.
|
||||
- **Your rack is yours to arrange**: tiles come in the order you drew them, new ones land on the right, and you can drag them around however you like. **Sort (S)** gives it a quick tidy *by number* or *by pips* — but figuring out which tiles chain together is up to you!
|
||||
- **Hint (H)**: I'll tell you what I'd play, and why.
|
||||
- **Undo (Z)**: changed your mind? You've got a moment before the next player moves.
|
||||
- **Hover a train** to see whose it is, how long it is, and what it needs.
|
||||
- **Keys**: arrows pick a playable tile, 1–5 choose a train, D draw, P pass, E end turn, Esc menu.
|
||||
|
||||
## Jerry's Farming Wisdom (Tips)
|
||||
|
||||
**1. Play your doubles early.** Doubles are double-dangerous to hold — they count for more pips if you get stuck with them. Play them when you can, not when you're forced to. Get those troublesome tiles out of your hand like you'd fix a wobbly fence post: sooner is better.
|
||||
**1. Plan your train first.** Before you play anything, work out the longest chain your hand makes off your own train, and drag those tiles together on your rack. That chain is your money in the bank — nobody else can touch it while your train is closed.
|
||||
|
||||
**2. Keep your personal train clean.** Don't let your train stay marked any longer than needed. An open train is like leaving your barn door ajar — folks'll wander through it whether you like it or not.
|
||||
**2. Dump the loose ones elsewhere.** Tiles that don't fit your chain are the ones that'll get you stuck. Play those on the Mexican Train or on somebody's open train first, and save your own train for later.
|
||||
|
||||
**3. Watch the Mexican Train.** It's the social train, the one everybody shares. If the end value matches a lot of tiles in your hand, the Mexican Train can be your best friend for getting rid of tiles fast.
|
||||
**3. Keep your train closed.** An open train is a barn door left ajar — folks wander in and wreck your plans by changing your number. If it opens, get back on it as soon as you can.
|
||||
|
||||
**4. Count what your opponents are playing.** When someone draws from the boneyard, they're hurting. When someone passes, they're in trouble. Keep an eye on who's holding a lot of tiles — they're likely to score big if you can end the round quickly.
|
||||
**4. Don't lay a double you can't cover.** You'll end up drawing and opening your train. Lay doubles when you've got the tile to cover them — two tiles gone in one turn!
|
||||
|
||||
**5. Plan ahead for the end of a train.** Every tile you play changes what end value that train shows. Before you play, think about what you've got left in your hand that can follow on that train. You don't want to paint yourself into a corner with no tiles that match what you just put down.
|
||||
**5. Watch who passes.** When somebody passes, they just told the whole table which numbers they don't have. Leave the Mexican Train on one of those numbers and they'll stay stuck.
|
||||
|
||||
**6. Don't fear the Mexican Train.** New players sometimes forget about the Mexican Train and try to play everything on their personal train. The Mexican Train is there for a reason — use it! When your personal train is tied up and the Mexican Train matches, play there.
|
||||
|
||||
## The Final Stretch
|
||||
|
||||
When any player's cumulative score hits 100, the match is over. Whoever has the **lowest total score** wins. So even if you've had a rough round or two, you can still come back if you play smart and keep those pip totals down.
|
||||
|
||||
It's like a long growing season — one bad week doesn't ruin the harvest if you tend to things right the rest of the time!
|
||||
**6. Shed the heavy tiles late.** When somebody's down to a couple of tiles, the round's about to end — get those 12s out of your hand before they cost you.
|
||||
|
||||
---
|
||||
|
||||
Well, that's everything you need to know! Mexican Train is a wonderful game — simple enough to learn over sweet tea, but deep enough to keep you thinking all night. Even Bessie gets excited when she hears the tiles rattling around.
|
||||
|
||||
Now get out there, play your tiles, keep that score low, and remember: slow and steady wins the farm. Good luck, neighbor!
|
||||
That's everything, neighbor. Mexican Train is simple enough to learn over sweet tea and deep enough to keep you thinking till supper. Now wash those bones, and remember: slow and steady wins the farm!
|
||||
|
|
|
|||
|
|
@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
|
||||
// Skill control: pips always show the level; the +/- buttons appear only
|
||||
// when this opponent is selected. Enabled for games with a 1–5 AI skill.
|
||||
if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg', 'tickettoride', 'backgammon', 'parchisi'].includes(this.gameDef.slug)) {
|
||||
if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg', 'tickettoride', 'backgammon', 'parchisi', 'mexicantrain'].includes(this.gameDef.slug)) {
|
||||
bio.style.webkitLineClamp = '1';
|
||||
|
||||
const skillRow = document.createElement('div');
|
||||
|
|
|
|||
|
|
@ -0,0 +1,374 @@
|
|||
#!/usr/bin/env node
|
||||
// verifyMexicanTrain.js — headless checks for Mexican Train ("Sunday afternoon
|
||||
// at the kitchen table"):
|
||||
// • rules on hand-built positions: sets / hands / engines, train access,
|
||||
// markers, draw → pass, doubles (cover and the 'relaxed' bonus play),
|
||||
// the opening run, going out on a double, blocked rounds, 0-0 = 50,
|
||||
// knocking + catching, descent vs points matches, voids
|
||||
// • chain search against brute force; hints are always legal
|
||||
// • AI soak over every set / player count / house rule: games finish, every
|
||||
// tile accounted for after every action
|
||||
// • skill ladder (mirrored seeds, two players)
|
||||
// • layout: trains from real games never overlap, stay on the table, clear
|
||||
// the hub; markers and HUD furniture don't collide
|
||||
// Usage: node tools/verifyMexicanTrain.js [--quick]
|
||||
|
||||
import * as L from '../src/games/mexicantrain/MexicanTrainLogic.js';
|
||||
import * as AI from '../src/games/mexicantrain/MexicanTrainAI.js';
|
||||
import * as Lay from '../src/games/mexicantrain/MexicanTrainLayout.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 T = (a, b, set = 12) => L.makeTileSet(set).find((t) => t.a === Math.min(a, b) && t.b === Math.max(a, b));
|
||||
const names = (n) => Array.from({ length: n }, (_, i) => ({ name: `P${i}`, isAI: i > 0 }));
|
||||
|
||||
/** A hand-built position: hands as [[a,b],…] per seat; trains as { key: [[l,r],…] }. */
|
||||
function pos({ n = 2, set = 12, hub = 12, hands = [], trains = {}, markers = [], boneyard = null, current = 0, opts = {}, firstDone = true }) {
|
||||
const s = L.createInitialState({ playerNames: names(n), opts: { set, ...opts }, seed: 1 });
|
||||
s.hub = { value: hub, id: T(hub, hub, set).id };
|
||||
const used = new Set([s.hub.id]);
|
||||
s.players.forEach((p, i) => { p.hand = (hands[i] ?? []).map(([a, b]) => T(a, b, set)); p.hand.forEach((t) => used.add(t.id)); });
|
||||
for (const k of L.trainKeys(n)) {
|
||||
s.trains[k] = { tiles: (trains[k] ?? []).map(([l, r]) => { const t = T(l, r, set); used.add(t.id); return { id: t.id, left: l, right: r, by: 0 }; }), marker: markers.includes(k) };
|
||||
}
|
||||
s.boneyard = boneyard ? boneyard.map(([a, b]) => T(a, b, set)) : L.makeTileSet(set).filter((t) => !used.has(t.id));
|
||||
s.current = current;
|
||||
s.firstDone = s.players.map(() => firstDone);
|
||||
s.turn = { seat: current, played: 0, drew: false, opening: !!s.opts.opening && !firstDone, run: false, bonus: false };
|
||||
s.openDouble = null;
|
||||
s.voids = s.players.map(() => ({}));
|
||||
s.deferred = [];
|
||||
return s;
|
||||
}
|
||||
const mv = (s) => L.getLegalMoves(s).map((m) => `${L.tileName(L.makeTileSet(s.opts.set)[m.tileId])}@${m.train}`).sort();
|
||||
const play = (s, a, b, train) => L.playTile(s, { tileId: T(a, b, s.opts.set).id, train });
|
||||
|
||||
section('Sets, hands, deal');
|
||||
{
|
||||
ok('double-12 has 91 tiles', L.makeTileSet(12).length === 91 && L.tileCount(12) === 91);
|
||||
ok('double-9 has 55, double-6 has 28', L.makeTileSet(9).length === 55 && L.makeTileSet(6).length === 28);
|
||||
ok('hand sizes', L.handSizeFor(12, 4) === 15 && L.handSizeFor(9, 4) === 9 && L.handSizeFor(6, 4) === 5 && L.handSizeFor(6, 2) === 7);
|
||||
for (const set of [6, 9, 12]) for (const n of [2, 3, 4]) {
|
||||
const s = L.createInitialState({ playerNames: names(n), opts: { set }, seed: set * 10 + n });
|
||||
const c = L.tileCensus(s);
|
||||
ok(`deal d${set} ${n}p: every tile once`, c.total === c.expected && c.unique === c.expected, JSON.stringify(c));
|
||||
ok(`deal d${set} ${n}p: engine ${set}-${set} in the hub`, s.hub.value === set && !s.players.some((p) => p.hand.some((t) => t.id === s.hub.id)));
|
||||
ok(`deal d${set} ${n}p: hands`, s.players.every((p) => p.hand.length === L.handSizeFor(set, n)));
|
||||
ok(`deal d${set} ${n}p: trains (${n} + Mexican), all empty`, Object.keys(s.trains).length === n + 1 && Object.values(s.trains).every((t) => !t.tiles.length && !t.marker));
|
||||
}
|
||||
ok('engines descend 12 → 0', [0, 1, 5, 12].map((r) => L.hubValueForRound(12, r)).join() === '12,11,7,0');
|
||||
ok('points mode wraps the engines', L.hubValueForRound(6, 7) === 6 && L.hubValueForRound(6, 8) === 5);
|
||||
}
|
||||
|
||||
section('Train access, markers, draw and pass');
|
||||
{
|
||||
let s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]], trains: { 1: [[12, 5]] } });
|
||||
ok('empty trains need the engine number; others closed', mv(s).join() === '3-12@0,3-12@mexican', mv(s).join());
|
||||
s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]], trains: { 1: [[12, 5]] }, markers: ['1'] });
|
||||
ok('an open (marked) train is playable', mv(s).includes('5-6@1'), mv(s).join());
|
||||
s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]], markers: ['0'] });
|
||||
s = play(s, 12, 3, '0');
|
||||
ok('playing your own train takes your marker back', !s.trains['0'].marker && s.current === 1);
|
||||
ok('…the tile is oriented to match', s.trains['0'].tiles[0].left === 12 && s.trains['0'].tiles[0].right === 3);
|
||||
s = pos({ hands: [[[1, 2], [5, 6]], [[1, 1]]], boneyard: [[2, 3], [4, 4]] });
|
||||
ok('no play → may draw, not pass', L.canDraw(s) && !L.canPass(s));
|
||||
ok('may not draw while a play exists', !L.canDraw(pos({ hands: [[[12, 2]], [[1, 1]]] })));
|
||||
s = L.drawTile(s);
|
||||
ok('draw takes the top tile', s.players[0].hand.some((t) => t.a === 4 && t.b === 4) && s.boneyard.length === 1);
|
||||
ok('one draw only', !L.canDraw(s) && L.canPass(s));
|
||||
s = L.passTurn(s);
|
||||
ok('pass marks your train and moves on', s.trains['0'].marker && s.current === 1 && s.lastEvent.marked);
|
||||
ok('pass records the numbers you showed you lack', s.voids[0][12] === 0);
|
||||
s = pos({ hands: [[[1, 2]], [[1, 1]]], boneyard: [] });
|
||||
ok('empty boneyard → pass straight away', !L.canDraw(s) && L.canPass(s));
|
||||
s = pos({ hands: [[[1, 2], [12, 0]], [[1, 1]]], boneyard: [[2, 3]] });
|
||||
s = play(s, 12, 0, L.MEXICAN);
|
||||
ok('the Mexican Train takes anyone', s.trains.mexican.tiles.length === 1 && s.current === 1);
|
||||
ok('illegal plays are ignored', play(s, 1, 1, '0') === s || play(s, 1, 1, '0').trains['0'].tiles.length === 0);
|
||||
}
|
||||
|
||||
section('Doubles');
|
||||
{
|
||||
let s = pos({ hands: [[[12, 12].map((x) => x), [12, 4], [5, 5]], [[4, 9], [12, 7]]], hub: 11, trains: { 0: [[11, 12]] } });
|
||||
s = play(s, 12, 12, '0');
|
||||
ok('a double keeps the turn', s.current === 0 && s.openDouble?.value === 12 && s.openDouble.by === 0);
|
||||
ok('only the double can be covered', mv(s).join() === '4-12@0', mv(s).join());
|
||||
s = play(s, 12, 4, '0');
|
||||
ok('covering it passes the turn', s.current === 1 && !s.openDouble && s.stats[0].covered === 1);
|
||||
s = pos({ hands: [[[12, 12], [1, 2]], [[4, 9], [12, 7]]], hub: 11, trains: { 0: [[11, 12]] }, boneyard: [[3, 3]] });
|
||||
s = play(s, 12, 12, '0');
|
||||
ok('can\'t cover → draw', L.canDraw(s));
|
||||
s = L.drawTile(s);
|
||||
s = L.passTurn(s);
|
||||
ok('…then pass: your train opens and the double stays', s.trains['0'].marker && s.openDouble?.train === '0' && s.current === 1);
|
||||
ok('the next player must cover it (on the now-open train)', mv(s).join() === '7-12@0', mv(s).join());
|
||||
s = pos({ hands: [[[12, 12], [3, 4]], [[4, 9]]], hub: 11, trains: { 0: [[11, 12]] }, opts: { doubles: 'relaxed' } });
|
||||
s = play(s, 12, 12, '0');
|
||||
ok('relaxed: a double earns a bonus play, nothing to cover', s.current === 0 && !s.openDouble && s.turn.bonus);
|
||||
s = pos({ hands: [[[12, 12], [3, 4]], [[4, 9]]], hub: 11, trains: { 0: [[11, 12]] }, opts: { doubles: 'relaxed' }, boneyard: [[6, 6]] });
|
||||
s = play(s, 12, 12, '0');
|
||||
s = L.drawTile(s); s = L.passTurn(s);
|
||||
ok('relaxed: a missed bonus play doesn\'t open your train', !s.trains['0'].marker && s.current === 1);
|
||||
s = pos({ hands: [[[12, 12]], [[4, 9]]], hub: 11, trains: { 0: [[11, 12]] } });
|
||||
s = play(s, 12, 12, '0');
|
||||
ok('going out on a double ends the round', s.phase !== 'playing' && s.roundWinner === 0 && s.stats[0].outs === 1);
|
||||
}
|
||||
|
||||
section('One tile per turn (default) and the first-turn run (house rule)');
|
||||
{
|
||||
ok('default: no first-turn run', L.DEFAULT_OPTS.opening === false);
|
||||
let s = pos({ hands: [[[12, 3], [3, 7], [7, 1]], [[4, 9]]], firstDone: false });
|
||||
s = play(s, 12, 3, '0');
|
||||
ok('default: one tile and the turn passes', s.current === 1 && s.trains['0'].tiles.length === 1);
|
||||
s = pos({ hands: [[[12, 3], [3, 7], [7, 7], [7, 1], [12, 9]], [[4, 9]]], firstDone: false, opts: { opening: true } });
|
||||
ok('run: first turn is own train only (no Mexican Train)', mv(s).every((m) => m.endsWith('@0')), mv(s).join());
|
||||
s = play(s, 12, 3, '0');
|
||||
ok('run: playing your own train keeps the turn', s.current === 0 && s.turn.run && L.canEndTurn(s));
|
||||
s = play(s, 3, 7, '0'); s = play(s, 7, 7, '0');
|
||||
ok('run: a double inside the run is just part of the chain', !s.openDouble && L.canEndTurn(s));
|
||||
s = play(s, 7, 1, '0');
|
||||
s = L.endTurn(s);
|
||||
ok('run: End Turn passes play', s.current === 1 && s.firstDone[0] && s.trains['0'].tiles.length === 4);
|
||||
s = pos({ n: 2, hands: [[[12, 5], [5, 5], [1, 2]], [[2, 9], [5, 8], [12, 4]]], firstDone: false, opts: { opening: true } });
|
||||
s = play(s, 12, 5, '0'); s = play(s, 5, 5, '0'); s = L.endTurn(s);
|
||||
ok('run ending on a double: not enforced during first turns', !s.openDouble && s.deferred.length === 1 && mv(s).join() === '4-12@1', mv(s).join());
|
||||
s = play(s, 12, 4, '1'); s = L.endTurn(s);
|
||||
ok('…enforced once everyone has had a first turn', s.current === 0 && s.openDouble?.value === 5 && s.openDouble.train === '0');
|
||||
s = pos({ hands: [[[1, 2]], [[4, 9]]], firstDone: false, opts: { opening: true } });
|
||||
ok('run: can\'t start → no draw, the train is marked', !L.canDraw(s) && L.canPass(s));
|
||||
s = L.passTurn(s);
|
||||
ok('…marked open', s.trains['0'].marker && s.current === 1);
|
||||
}
|
||||
|
||||
section('Dead doubles');
|
||||
{
|
||||
// every other 6 is already on the table, so a 6-6 needs no cover
|
||||
let s = pos({
|
||||
set: 6, hub: 5, hands: [[[6, 6], [0, 0]], [[1, 1]]],
|
||||
trains: { 0: [[5, 6]], mexican: [[5, 4], [4, 6], [6, 0]], 1: [[5, 3], [3, 6], [6, 1], [1, 2], [2, 6]] },
|
||||
});
|
||||
ok('setup: the 6-6 is the only 6 still unplayed', !L.numberLive({ ...s, players: s.players.map((p, i) => (i ? p : { ...p, hand: p.hand.filter((t) => !(t.a === 6 && t.b === 6)) })) }, 6));
|
||||
const after = play(s, 6, 6, '0');
|
||||
ok('a dead double needs no cover: the turn passes', after.current === 1 && !after.openDouble && after.lastEvent.dead);
|
||||
let t = pos({ hands: [[[12, 12], [1, 2]], [[12, 7]]], hub: 11, trains: { 0: [[11, 12]] } });
|
||||
t = play(t, 12, 12, '0');
|
||||
ok('a live double still has to be covered', t.current === 0 && t.openDouble?.value === 12);
|
||||
}
|
||||
|
||||
section('Round end, scoring, match');
|
||||
{
|
||||
let s = pos({ hands: [[[1, 2]], [[0, 0], [3, 4]]], boneyard: [], opts: { blank50: true } });
|
||||
s = L.passTurn(s); s = L.passTurn(s);
|
||||
ok('blocked round ends when everyone passes on an empty boneyard', s.phase !== 'playing' && s.blocked);
|
||||
ok('blocked: fewest pips wins the round', s.roundWinner === 0);
|
||||
ok('0-0 counts 50 with the house rule', s.lastRoundScores[1] === 57, String(s.lastRoundScores));
|
||||
ok('history is kept', s.history.length === 1 && s.history[0].totals[1] === 57);
|
||||
let g = L.createInitialState({ playerNames: names(2), opts: { set: 6 }, seed: 9 });
|
||||
const rnd = mulberry32(5);
|
||||
let guard = 0, rounds = 0;
|
||||
while (g.phase !== 'gameover' && guard++ < 20000) {
|
||||
if (g.phase === 'roundover') { const st = g.roundStarter; g = L.startNextRound(g); rounds++; if (g.roundStarter !== (st + 1) % 2) ok('starter rotates', false); continue; }
|
||||
const a = AI.chooseAction(g, g.current, 3, rnd);
|
||||
g = a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g);
|
||||
}
|
||||
ok('descent: exactly one round per engine (d6 → 7)', g.history.length === 7 && g.history.map((h) => h.hub).join() === '6,5,4,3,2,1,0', g.history.map((h) => h.hub).join());
|
||||
g = L.createInitialState({ playerNames: names(3), opts: { set: 6, mode: 'points', target: 60 }, seed: 4 });
|
||||
guard = 0;
|
||||
while (g.phase !== 'gameover' && guard++ < 40000) {
|
||||
if (g.phase === 'roundover') { g = L.startNextRound(g); continue; }
|
||||
const a = AI.chooseAction(g, g.current, 3, rnd);
|
||||
g = a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g);
|
||||
}
|
||||
ok('points: ends once someone reaches the target', g.phase === 'gameover' && g.players.some((p) => p.score >= 60) && g.history.slice(0, -1).every((h) => h.totals.every((t) => t < 60)));
|
||||
ok('winners = lowest total', L.getWinners(g).every((i) => g.players[i].score === Math.min(...g.players.map((p) => p.score))));
|
||||
const tie = { players: [{ score: 40 }, { score: 40 }, { score: 55 }], history: [{ scores: [20, 0, 30] }, { scores: [20, 40, 25] }] };
|
||||
ok('tie on total → most 0-point rounds wins', L.getWinners(tie).join() === '1' && L.rankings(tie).join() === '1,0,2');
|
||||
const tie2 = { players: [{ score: 30 }, { score: 30 }], history: [{ scores: [10, 18] }, { scores: [20, 12] }] };
|
||||
ok('…then the lowest non-zero round', L.getWinners(tie2).join() === '0');
|
||||
}
|
||||
|
||||
section('Knocking');
|
||||
{
|
||||
let s = pos({ hands: [[[12, 3], [5, 6]], [[1, 1], [2, 2]]], opts: { knock: true } });
|
||||
s = play(s, 12, 3, '0');
|
||||
ok('down to one without knocking → catchable', L.catchable(s, 0));
|
||||
const c = L.catchKnock(s, 1, 0);
|
||||
ok('caught: draw two', c.players[0].hand.length === 3 && c.stats[0].caught === 1 && !L.catchable(c, 0));
|
||||
const k = L.knock(s, 0);
|
||||
ok('knocked → safe', !L.catchable(k, 0) && k.players[0].knocked);
|
||||
ok('no knock rule → never catchable', !L.catchable(play(pos({ hands: [[[12, 3], [5, 6]], [[1, 1]]] }), 12, 3, '0'), 0));
|
||||
}
|
||||
|
||||
section('AI: chain search, hints');
|
||||
{
|
||||
const brute = (hand, v) => {
|
||||
let best = 0;
|
||||
const rec = (val, used, len) => {
|
||||
best = Math.max(best, len);
|
||||
hand.forEach((t, i) => { if (used & (1 << i)) return; if (t.a === val) rec(t.b, used | (1 << i), len + 1); else if (t.b === val) rec(t.a, used | (1 << i), len + 1); });
|
||||
};
|
||||
rec(v, 0, 0);
|
||||
return best;
|
||||
};
|
||||
const rnd = mulberry32(77);
|
||||
const all = L.makeTileSet(9);
|
||||
let agree = 0;
|
||||
for (let k = 0; k < 300; k++) {
|
||||
const hand = all.slice().sort(() => rnd() - 0.5).slice(0, 9);
|
||||
const v = Math.floor(rnd() * 10);
|
||||
if (AI.bestChain(hand, v).path.length === brute(hand, v)) agree++;
|
||||
}
|
||||
ok('bestChain = brute-force longest trail (300 hands)', agree === 300, `${agree}/300`);
|
||||
const ch = AI.bestChain([T(12, 3), T(3, 3), T(3, 9), T(9, 1), T(5, 6)], 12);
|
||||
ok('chain takes the double on the way', ch.path.map((p) => `${p.left}${p.right}`).join(' ') === '123 33 39 91', ch.path.map((p) => `${p.left}${p.right}`).join(' '));
|
||||
let hintOk = 0, hints = 0;
|
||||
let g = L.createInitialState({ playerNames: names(3), opts: { set: 12 }, seed: 31 });
|
||||
for (let i = 0; i < 400 && g.phase === 'playing'; i++) {
|
||||
const h = AI.hint(g, g.current);
|
||||
hints++;
|
||||
if (h && (h.action.type !== 'play' || L.getLegalMoves(g).some((m) => m.tileId === h.action.tileId && m.train === h.action.train)) && h.text.length > 10) hintOk++;
|
||||
const a = AI.chooseAction(g, g.current, 4, rnd);
|
||||
g = a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g);
|
||||
}
|
||||
ok('hints are legal and explained', hintOk === hints, `${hintOk}/${hints}`);
|
||||
}
|
||||
|
||||
// ── soak ─────────────────────────────────────────────────────────────────────
|
||||
function applyA(g, a) { return a.type === 'play' ? L.playTile(g, a) : a.type === 'draw' ? L.drawTile(g) : a.type === 'pass' ? L.passTurn(g) : L.endTurn(g); }
|
||||
function playGame({ n, set, skills, opts = {}, seed, onState = null }) {
|
||||
const rnd = mulberry32(seed * 7 + 1);
|
||||
let g = L.createInitialState({ playerNames: names(n), opts: { set, ...opts }, seed });
|
||||
let guard = 0, problems = [];
|
||||
while (g.phase !== 'gameover' && guard++ < 60000) {
|
||||
if (g.phase === 'roundover') { g = L.startNextRound(g); continue; }
|
||||
const a = AI.chooseAction(g, g.current, skills[g.current], rnd);
|
||||
if (!a) { problems.push('no action'); break; }
|
||||
const next = applyA(g, a);
|
||||
if (next === g) { problems.push(`no-op ${a.type}`); break; }
|
||||
g = next;
|
||||
if (g.opts.knock && L.catchable(g, (g.current + g.n - 1) % g.n) && rnd() < 0.3) g = L.catchKnock(g, g.current, (g.current + g.n - 1) % g.n);
|
||||
const c = L.tileCensus(g);
|
||||
if (c.total !== c.expected || c.unique !== c.expected) { problems.push('census'); break; }
|
||||
onState?.(g, a);
|
||||
}
|
||||
if (g.phase !== 'gameover') problems.push('unfinished');
|
||||
return { g, problems };
|
||||
}
|
||||
|
||||
section('AI soak');
|
||||
{
|
||||
const games = QUICK ? 24 : 90;
|
||||
let bad = 0, rounds = 0;
|
||||
for (let k = 0; k < games; k++) {
|
||||
const n = 2 + (k % 3), set = [12, 9, 6][Math.floor(k / 3) % 3];
|
||||
const opts = { opening: k % 4 !== 1, doubles: k % 5 === 2 ? 'relaxed' : 'cover', blank50: k % 2 === 1, knock: k % 3 === 0, ...(k % 7 === 6 ? { mode: 'points', target: 150 } : {}) };
|
||||
const skills = Array.from({ length: n }, (_, i) => 1 + ((k + i) % 5));
|
||||
const { g, problems } = playGame({ n, set, skills, opts, seed: 900 + k });
|
||||
rounds += g.history.length;
|
||||
if (problems.length) { bad++; console.error(` soak ${k}: ${problems.join(', ')}`); }
|
||||
}
|
||||
ok(`${games} games across sets / players / house rules finish cleanly`, bad === 0, `${bad} bad`);
|
||||
console.log(` (${rounds} rounds played)`);
|
||||
}
|
||||
|
||||
section('Skill ladder (2 players, mirrored seeds, double-12)');
|
||||
{
|
||||
const pairs = QUICK ? 10 : 40;
|
||||
const ladder = QUICK ? [[2, 1], [5, 3]] : [[2, 1], [3, 2], [4, 3], [5, 4]];
|
||||
for (const [hi, lo] of ladder) {
|
||||
let w = 0, cnt = 0, margin = 0;
|
||||
for (let k = 0; k < pairs; k++) {
|
||||
for (const order of [[hi, lo], [lo, hi]]) {
|
||||
const { g } = playGame({ n: 2, set: 12, skills: order, seed: 4000 + k });
|
||||
const me = order[0] === hi ? 0 : 1, you = 1 - me;
|
||||
const a = g.players[me].score, b = g.players[you].score;
|
||||
w += a < b ? 1 : a === b ? 0.5 : 0;
|
||||
margin += b - a;
|
||||
cnt++;
|
||||
}
|
||||
}
|
||||
const pct = (100 * w) / cnt;
|
||||
console.log(` skill ${hi} vs ${lo}: ${pct.toFixed(1)}% wins, avg margin ${(margin / cnt).toFixed(1)} (${cnt} games)`);
|
||||
// lowest total wins, so the average margin is the steadier signal (win % swings ±10 at this sample size)
|
||||
ok(`skill ${hi} beats skill ${lo} on average score`, margin / cnt > 0, `${(margin / cnt).toFixed(1)} pts, ${pct.toFixed(1)}%`);
|
||||
}
|
||||
}
|
||||
|
||||
section('Layout');
|
||||
{
|
||||
const corners = (p, z, pad = 0) => {
|
||||
const hw = Lay.TILE.u * z + pad, hh = (Lay.TILE.u * z) / 2 + pad, c = Math.cos(p.rot), s = Math.sin(p.rot);
|
||||
return [[1, 1], [1, -1], [-1, -1], [-1, 1]].map(([i, j]) => ({ x: p.x + c * hw * i - s * hh * j, y: p.y + s * hw * i + c * hh * j }));
|
||||
};
|
||||
const overlap = (A, B) => {
|
||||
for (const P of [A, B]) for (let i = 0; i < 4; i++) {
|
||||
const a = P[i], b = P[(i + 1) % 4], nx = -(b.y - a.y), ny = b.x - a.x, len = Math.hypot(nx, ny);
|
||||
const pa = A.map((q) => q.x * nx + q.y * ny), pb = B.map((q) => q.x * nx + q.y * ny);
|
||||
if (Math.max(...pa) < Math.min(...pb) + 0.5 * len || Math.max(...pb) < Math.min(...pa) + 0.5 * len) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
for (const n of [2, 3, 4]) {
|
||||
let checks = 0, overlaps = 0, outside = 0, hub = 0, minZoom = 1, markerHits = 0, links = 0, breaks = 0, bends = 0;
|
||||
const games = QUICK ? 3 : 10;
|
||||
for (let k = 0; k < games; k++) {
|
||||
let zoom = 1, step = 0;
|
||||
playGame({ n, set: 12, skills: Array(n).fill(3), seed: 7000 + k * 3 + n, onState: (g, a) => {
|
||||
if (g.phase === 'playing' && g.lastEvent.type === 'deal') zoom = 1;
|
||||
if (a.type !== 'play' || (++step % 5 && g.phase === 'playing')) return;
|
||||
zoom = Lay.fitZoom(n, g.trains, zoom);
|
||||
minZoom = Math.min(minZoom, zoom);
|
||||
const all = Lay.layoutAll(n, g.trains, zoom);
|
||||
const boxes = [];
|
||||
for (const [key, r] of Object.entries(all.trains)) r.poses.forEach((p) => boxes.push({ key, p, c: corners(p, zoom) }));
|
||||
// a contiguous train: every tile touches the one before it (within the tile gap), bends included
|
||||
for (const r of Object.values(all.trains)) for (let i = 1; i < r.poses.length; i++) {
|
||||
links++;
|
||||
if (r.poses[i].corner) bends++;
|
||||
const pad = (Lay.TILE.gap * zoom) / 2 + 0.6;
|
||||
if (!overlap(corners(r.poses[i - 1], zoom, pad), corners(r.poses[i], zoom, pad))) breaks++;
|
||||
}
|
||||
for (const b of boxes) {
|
||||
if (b.c.some((q) => q.x < Lay.TABLE.l - 2 || q.x > Lay.TABLE.r + 2 || q.y < Lay.TABLE.t - 2 || q.y > Lay.TABLE.b + 2)) outside++;
|
||||
if (Math.hypot(b.p.x - Lay.HUB.x, b.p.y - Lay.HUB.y) < Lay.HUB.r + 10) hub++;
|
||||
}
|
||||
for (let i = 0; i < boxes.length; i++) for (let j = i + 1; j < boxes.length; j++) { checks++; if (overlap(boxes[i].c, boxes[j].c)) overlaps++; }
|
||||
for (const key of L.trainKeys(n)) {
|
||||
const m = Lay.markerSpot(n, key);
|
||||
const hl = Lay.MARKER.len / 2, hw = Lay.MARKER.wid / 2;
|
||||
const mc = [[-hl, -hw], [hl, -hw], [hl, hw], [-hl, hw]].map(([dx, dy]) => ({ x: m.x + dx * Math.cos(m.rot) - dy * Math.sin(m.rot), y: m.y + dx * Math.sin(m.rot) + dy * Math.cos(m.rot) }));
|
||||
for (const b of boxes) if (b.key !== key && overlap(mc, b.c)) markerHits++;
|
||||
}
|
||||
} });
|
||||
}
|
||||
ok(`${n}p: no two tiles overlap (${checks} pairs)`, overlaps === 0, `${overlaps}`);
|
||||
ok(`${n}p: every tile on the table, clear of the hub`, outside === 0 && hub === 0, `${outside} outside, ${hub} on the hub`);
|
||||
ok(`${n}p: open-train engines don't sit on other trains`, markerHits === 0, `${markerHits}`);
|
||||
ok(`${n}p: trains are unbroken — every tile touches the last, round the bends too (${links} links, ${bends} bends)`, breaks === 0 && bends > 0, `${breaks} breaks`);
|
||||
console.log(` ${n}p: smallest zoom ${minZoom}`);
|
||||
}
|
||||
// furniture
|
||||
const inter = (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;
|
||||
for (const n of [2, 3, 4]) {
|
||||
const f = Lay.hudFurniture(n);
|
||||
let hits = [];
|
||||
for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) if (inter(f[i][1], f[j][1])) hits.push(`${f[i][0]}×${f[j][0]}`);
|
||||
ok(`${n}p: HUD furniture doesn't overlap`, hits.length === 0, hits.join(' '));
|
||||
const table = { x: Lay.TABLE.l, y: Lay.TABLE.t, w: Lay.TABLE.r - Lay.TABLE.l, h: Lay.TABLE.b - Lay.TABLE.t };
|
||||
const onTable = f.filter(([, r]) => inter(r, table)).map(([k]) => k);
|
||||
ok(`${n}p: HUD furniture stays off the train area`, onTable.length === 0, onTable.join(' '));
|
||||
for (const p of f) ok(`${n}p: ${p[0]} on screen`, p[1].x >= 0 && p[1].y >= 0 && p[1].x + p[1].w <= Lay.W && p[1].y + p[1].h <= Lay.H);
|
||||
}
|
||||
const rs = Lay.rackSlots(25);
|
||||
ok('a 25-tile rack fits on the rack', rs.xs[0] - Lay.RACK_TILE.u / 2 >= Lay.RACK.x && rs.xs[24] + Lay.RACK_TILE.u / 2 <= Lay.RACK.x + Lay.RACK.w);
|
||||
ok('rack hit-test round-trips', [0, 7, 14].every((i) => Lay.rackIndexAt(Lay.rackSlots(15).xs[i], 15) === i));
|
||||
}
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
Loading…
Reference in New Issue