Overhaul Mahjong into a full parlour experience with rich AI and helpers

- Rebuild the table scene: procedural room/table art, persistent tile sprites
  that slide and flip between wall, rack, river and melds, dice break ritual,
  call stamps, speech bubbles and score rolls
- Add MahjongAdvisor (shared by UI and AI): waits, unseen counts, discard
  advice, danger map, hand-pattern compass and opponent reads
- Strengthen the AI skill ladder: value awareness, one-suit commitment, wait
  pricing, defense/folding at skill 5, and explainable claims/discards for the
  coach
- Add house rules (rounds, min faan, faan cap, rob-kong, bonus tiles, stake),
  limit hands (Nine Gates, All Terminals, Four Kongs, Heavenly/Earthly, etc.)
  and robbing the kong in the engine
- New UI: settings/helpers dialogs, scoring slip, end-of-session screen with
  stats and score chart, tile tracker, danger shading, table log, tips
- Web Audio synths for clacks, wash, chime/gong plus rain/murmur ambience
- Expand verifyMahjong: limit-hand fixtures, rob-kong scenario, wall geometry,
  advisor brute-force checks, layout overlap checks, ledger-vs-engine self-play
  and an optional skill ladder benchmark
This commit is contained in:
Brian Fertig 2026-11-25 22:05:25 -07:00
parent e74449ffa1
commit 98a6cd56d9
No known key found for this signature in database
16 changed files with 4787 additions and 949 deletions

Binary file not shown.

View File

@ -1,21 +1,48 @@
// Mahjong — heuristic opponent. No Phaser, no timers, no state mutation.
// Discards minimise shanten with an ukeire (useful-draw count) tiebreak at
// skill 3+; skills 1-2 use a cheap tile-isolation heuristic instead and claim
// every pung/chow they are offered. Higher skills subtract tiles they can see
// from ukeire counts and lean toward safe discards once an opponent shows a
// big exposed hand. Wins are always taken.
// Mahjong — opponents. No Phaser, no timers, no state mutation.
//
// Skill ladder:
// 1–2 cheap tile-isolation discards, claim everything they're offered.
// 3 shanten + useful-draw (ukeire) discards; claims only when it brings
// the hand closer AND the hand can still reach the table minimum.
// 4 + counts tiles it can see, values honor pungs, commits to one-suit
// hands when the tiles lean that way (bigger, slower wins),
// prices its waits (prefers winnable ones), basic defense.
// 5 + full defense: reads who's close and what they collect, and folds
// (plays safe tiles) when far from ready against a dangerous table.
// Every decision can explain itself — the Coach and claim advisor show the
// skill-5 reasoning to the human.
import { isSuited, isHonor, rankOf } from './MahjongData.js';
import { counts34, shanten, claimOptionsFor } from './MahjongLogic.js';
import { TILES, SUIT_NAMES, isSuited, isHonor, rankOf, WIND_KINDS, DRAGON_KINDS } from './MahjongData.js';
import { counts34, shanten, claimOptionsFor, seatWindOf, wallRemaining } from './MahjongLogic.js';
import {
unseenCounts, improverKinds, discardAdvice, dangerMap, readTable, patternCompass, valueOutlook,
} from './MahjongAdvisor.js';
const SKILL_PROFILES = {
1: { noise: 3.0, claimAlways: true, seenAware: false, defense: 0.0, delay: [750, 1300] },
2: { noise: 2.0, claimAlways: true, seenAware: false, defense: 0.0, delay: [700, 1200] },
3: { noise: 1.0, claimAlways: false, seenAware: false, defense: 0.3, delay: [620, 1050] },
4: { noise: 0.4, claimAlways: false, seenAware: true, defense: 0.7, delay: [540, 950] },
5: { noise: 0.0, claimAlways: false, seenAware: true, defense: 1.0, delay: [460, 850] },
1: { noise: 3.0, claimAlways: true, seenAware: false, value: 0, defense: 0, fold: false, delay: [750, 1300] },
2: { noise: 2.0, claimAlways: true, seenAware: false, value: 0, defense: 0, fold: false, delay: [700, 1200] },
3: { noise: 1.0, claimAlways: false, seenAware: false, value: 0.3, defense: 0.3, fold: false, delay: [620, 1050] },
4: { noise: 0.4, claimAlways: false, seenAware: true, value: 0.8, defense: 0.7, fold: false, delay: [540, 950] },
5: { noise: 0.0, claimAlways: false, seenAware: true, value: 1.0, defense: 1.0, fold: true, delay: [460, 850] },
};
function profileFor(skill) {
// Tuning knobs (the ladder benchmark sweeps these; see verifyMahjong).
export const TUNE = { dangerW: 12, dangerFrom: 0.4, foldThreat: 0.72, foldSh: 2, concealChow: true, honorKeep: 6, flushShed: 4, readyWin: 2, flushAt: 0.6, flushWall: 40, flushSkill: 4, flushLoss: 1 };
// One-suit commitment: { suit, f } when the hand (and its melds) lean hard
// enough into one suit + honors that shedding the rest is worth it.
export function flushPlan(state, seat) {
const p = state.players[seat];
const all = p.hand.concat(...p.melds.map((m) => m.kinds));
const n = [0, 0, 0];
let honors = 0;
for (const k of all) { if (k < 27) n[Math.floor(k / 9)]++; else honors++; }
const suit = n.indexOf(Math.max(...n));
if (!p.melds.every((m) => m.kinds[0] >= 27 || Math.floor(m.kinds[0] / 9) === suit)) return null;
const f = (n[suit] + honors) / Math.max(1, all.length);
return { suit, f, off: all.length - n[suit] - honors };
}
export function profileFor(skill) {
return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3];
}
@ -24,16 +51,8 @@ export function nextThinkDelay(skill) {
return lo + Math.random() * (hi - lo);
}
// Tiles visible to everyone: all rivers, exposed melds and bonus rows. (We
// also count concealed kongs — a minor peek that keeps the bookkeeping flat.)
function seenCounts(state) {
const seen = new Array(34).fill(0);
for (const river of state.discards) for (const k of river) seen[k]++;
for (const p of state.players) {
for (const m of p.melds) for (const k of m.kinds) seen[k]++;
}
return seen;
}
const nm = (k) => TILES[k].name;
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
// Cheap usefulness of holding `kind` — for the skill 1-2 discard heuristic.
function usefulness(counts, kind) {
@ -48,83 +67,162 @@ function usefulness(counts, kind) {
return u;
}
// Draws that could improve a hand: pairing an existing tile or extending a
// suited shape. A brand-new isolated kind never lowers standard shanten.
function improverKinds(counts) {
const out = new Set();
for (let k = 0; k < 34; k++) {
if (counts[k] === 0) continue;
out.add(k);
if (!isSuited(k)) continue;
const r = rankOf(k);
for (const d of [-2, -1, 1, 2]) {
const t = k + d;
if (r + d >= 1 && r + d <= 9) out.add(t);
}
}
return [...out];
}
const isValueHonor = (state, seat, k) =>
DRAGON_KINDS.includes(k) || k === WIND_KINDS[seatWindOf(state, seat)] || k === WIND_KINDS[state.roundWind % 4];
// Pick a discard for the player on turn (hand holds 14 − 3·melds tiles).
export function chooseDiscard(state, seat, skill = 3) {
// ── discards ─────────────────────────────────────────────────────────────────
// Detailed choice: { kind, reason, close (how hard the call was, 0…1),
// tsumogiri (throwing the tile just drawn), fold }.
export function chooseDiscardDetailed(state, seat, skill = 3, rnd = Math.random) {
const prof = profileFor(skill);
const p = state.players[seat];
const counts = counts34(p.hand);
const kinds = [];
for (let k = 0; k < 34; k++) if (counts[k] > 0) kinds.push(k);
const tsu = (k) => state.drawnTile === k;
if (prof.claimAlways) { // skills 1-2: discard the least useful tile
let best = kinds[0], bestScore = Infinity;
let best = kinds[0], bestScore = Infinity, second = Infinity;
for (const k of kinds) {
const s = usefulness(counts, k) + Math.random() * prof.noise * 2;
if (s < bestScore) { bestScore = s; best = k; }
const s = usefulness(counts, k) + rnd() * prof.noise * 2;
if (s < bestScore) { second = bestScore; bestScore = s; best = k; } else if (s < second) second = s;
}
return best;
return { kind: best, reason: `the ${nm(best)} looked least useful`, close: Math.max(0, 1 - (second - bestScore) / 3), tsumogiri: tsu(best), fold: false };
}
const m = p.melds.length;
const unseen = prof.seenAware ? unseenCounts(state, seat) : counts.map((n) => 4 - n);
const reads = prof.defense > 0 ? readTable(state, seat) : [];
const maxThreat = reads.reduce((a, r) => Math.max(a, r.threat), 0);
const danger = prof.defense > 0 ? dangerMap(state, seat, reads) : null;
const comp = prof.value > 0 ? patternCompass(state, seat) : null;
const flushItem = comp?.items.find((it) => (it.id === 'mixed-one-suit' || it.id === 'pure-one-suit') && it.progress >= 0.62);
const flushSuit = flushItem ? SUIT_NAMES.findIndex((sn) => flushItem.label.includes(sn)) : -1;
const minFaan = state.opts.minFaan;
const rows = [];
let minSh = Infinity;
const perKind = new Map();
for (const k of kinds) {
counts[k]--;
const s = shanten(counts, m);
const sh = shanten(counts, m);
counts[k]++;
perKind.set(k, s);
if (s < minSh) minSh = s;
rows.push({ kind: k, sh });
if (sh < minSh) minSh = sh;
}
const candidates = kinds.filter((k) => perKind.get(k) === minSh);
const seen = prof.seenAware ? seenCounts(state) : null;
const threat = prof.defense > 0 && minSh >= 2
&& state.players.some((q) => q.seat !== seat && q.melds.length >= 3);
// fold: far from ready against a dangerous table — play the safest tile
if (prof.fold && minSh >= TUNE.foldSh && maxThreat >= TUNE.foldThreat && danger) {
let best = null;
for (const r of rows) {
const sc = -danger[r.kind] * 10 - (r.sh - minSh) * 0.8;
if (!best || sc > best.sc) best = { ...r, sc };
}
const who = reads.reduce((a, r) => (r.threat > a.threat ? r : a));
return {
kind: best.kind, fold: true, tsumogiri: tsu(best.kind), close: 0.6,
reason: `playing safe — ${state.players[who.seat].name} looks close, and the ${nm(best.kind)} is one of the safest tiles`,
};
}
let best = candidates[0], bestScore = -Infinity;
for (const k of candidates) {
counts[k]--;
let ukeire = 0;
for (const t of improverKinds(counts)) {
counts[t]++;
if (shanten(counts, m) < minSh) {
let left = 4 - counts[t] + 1;
if (seen) left -= seen[t];
if (left > 0) ukeire += left;
// committed to one suit: throw off-suit tiles while it costs at most
// TUNE.flushLoss steps of shanten
const fp = skill >= TUNE.flushSkill ? flushPlan(state, seat) : null;
if (fp && fp.off > 0 && fp.f >= TUNE.flushAt && wallRemaining(state) > TUNE.flushWall) {
const off = rows.filter((r) => r.kind < 27 && Math.floor(r.kind / 9) !== fp.suit && r.sh <= minSh + TUNE.flushLoss);
if (off.length) {
let bestOff = null;
for (const r of off) {
const iso = usefulness(counts, r.kind);
const sc = -r.sh * 10 - iso + rnd() * 0.01;
if (!bestOff || sc > bestOff.sc) bestOff = { ...r, sc };
}
return {
kind: bestOff.kind, tsumogiri: tsu(bestOff.kind), close: 0.3, fold: false, shanten: bestOff.sh,
reason: `shed the off-suit tile — you're building ${SUIT_NAMES[fp.suit]} (one-suit hands score 3–6 faan)`,
};
}
}
const cands = rows.filter((r) => r.sh === minSh);
const readyAdv = minSh === 0 && prof.value >= 0.8 ? discardAdvice(state, seat, { withDanger: false }) : null;
let best = null, second = null;
for (const r of cands) {
const k = r.kind;
counts[k]--;
let uke = 0;
for (const t of improverKinds(counts)) {
if (counts[t] >= 4) continue;
counts[t]++;
if (shanten(counts, m) < minSh) uke += unseen[t];
counts[t]--;
}
counts[k]++;
let score = ukeire + Math.random() * prof.noise * 2;
// someone looks close to winning — favour tiles already seen on the table
if (threat && seen && seen[k] >= 1) score += 4 * prof.defense;
if (score > bestScore) { bestScore = score; best = k; }
let score = uke;
const notes = [];
// value: keep honor pairs that score, shed off-suit tiles when flushing
if (prof.value > 0) {
if (isValueHonor(state, seat, k) && counts[k] >= 2) { score -= TUNE.honorKeep * prof.value; }
if (flushSuit >= 0 && isSuited(k)) {
if (Math.floor(k / 9) !== flushSuit) { score += TUNE.flushShed * prof.value; notes.push('flush'); }
else score -= 2 * prof.value;
}
if (isHonor(k) && counts[k] === 1 && !isValueHonor(state, seat, k) && wallRemaining(state) > 60) score += 0.8 * prof.value;
}
// ready: price the waits
if (minSh === 0 && prof.value >= 0.8) {
const adv = readyAdv.find((x) => x.kind === k);
const win = adv?.winnable ?? 0;
score += win * TUNE.readyWin;
if (adv && adv.waits && !adv.waits.some((w) => w.ok || w.okSelf)) score -= 25;
r.waits = adv?.waits;
r.winnable = win;
}
if (danger && maxThreat >= TUNE.dangerFrom) score -= danger[k] * TUNE.dangerW * prof.defense * maxThreat;
score += rnd() * prof.noise * 2;
const row = { ...r, uke, score, notes };
if (!best || score > best.score) { second = best; best = row; } else if (!second || score > second.score) second = row;
}
return best;
const close = second ? Math.max(0, Math.min(1, 1 - (best.score - second.score) / 6)) : 0;
let reason;
if (minSh === 0 && best.waits?.length) {
const live = best.waits.filter((w) => w.ok || w.okSelf);
const list = (live.length ? live : best.waits).slice(0, 3).map((w) => nm(w.kind)).join(' / ');
reason = live.length
? `you'll be ready, waiting on ${list} (${plural(best.winnable ?? 0, 'tile')} left)`
: `you'll be ready on ${list}, but that hand can't reach ${minFaan} faan yet`;
} else if (best.notes.includes('flush')) {
reason = `shed the off-suit tile — you're building ${SUIT_NAMES[flushSuit]}`;
} else {
reason = `keeps the most useful draws (${plural(best.uke, 'tile')} would improve your hand)`;
}
return { kind: best.kind, reason, close, tsumogiri: tsu(best.kind), fold: false, shanten: minSh };
}
// React to another player's discard. `options` comes from claimOptionsFor.
// Returns a claim ({ type, tiles? }) or null to pass.
export function chooseClaim(state, seat, options, skill = 3) {
if (!options) return null;
if (options.win) return { type: 'win' };
// Pick a discard for the player on turn (hand holds 14 − 3·melds tiles).
export function chooseDiscard(state, seat, skill = 3, rnd = Math.random) {
return chooseDiscardDetailed(state, seat, skill, rnd).kind;
}
// ── claims ───────────────────────────────────────────────────────────────────
// The hand as it would be after claiming: { state, seat } for the advisor.
function afterClaim(state, seat, type, tiles, kind) {
const p = state.players[seat];
const hand = p.hand.slice();
const take = (k, n) => { for (let i = 0; i < n; i++) hand.splice(hand.indexOf(k), 1); };
let meld;
if (type === 'pung') { take(kind, 2); meld = { type: 'pung', kinds: [kind, kind, kind], concealed: false }; }
else if (type === 'kong') { take(kind, 3); meld = { type: 'kong', kinds: [kind, kind, kind, kind], concealed: false }; }
else { take(tiles[0], 1); take(tiles[1], 1); meld = { type: 'chow', kinds: [tiles[0], tiles[1], kind].sort((a, b) => a - b), concealed: false }; }
const players = state.players.slice();
players[seat] = { ...p, hand, melds: p.melds.concat([meld]) };
return { ...state, players };
}
// React to another player's discard. Returns { claim, reason } — claim is
// { type, tiles? } or null to pass.
export function explainClaim(state, seat, options, skill = 3) {
if (!options) return { claim: null, reason: '' };
if (options.win) return { claim: { type: 'win' }, reason: 'that tile completes your hand — call Mahjong!' };
const prof = profileFor(skill);
const p = state.players[seat];
const kind = state.lastDiscard.kind;
@ -132,32 +230,78 @@ export function chooseClaim(state, seat, options, skill = 3) {
const counts = counts34(p.hand);
if (prof.claimAlways) {
if (options.kong) return { type: 'kong' };
if (options.pung) return { type: 'pung' };
if (options.chows.length) return { type: 'chow', tiles: options.chows[0] };
return null;
if (options.kong) return { claim: { type: 'kong' }, reason: 'kong!' };
if (options.pung) return { claim: { type: 'pung' }, reason: 'pung!' };
if (options.chows.length) return { claim: { type: 'chow', tiles: options.chows[0] }, reason: 'chow!' };
return { claim: null, reason: '' };
}
const minFaan = state.opts.minFaan;
const s0 = shanten(counts, m);
if (options.kong) { // free replacement draw — accept when not a step back
const valueHonor = isValueHonor(state, seat, kind);
const outlookOk = (type, tiles) => {
const after = afterClaim(state, seat, type, tiles, kind);
const o = valueOutlook(after, seat, { afterExposing: true });
const need = minFaan;
const est = o.sure + (prof.value >= 0.8 ? o.likely * 0.7 : o.likely);
return { ok: est >= need, sure: o.sure };
};
const before = valueOutlook(state, seat);
const losingConcealed = before.concealed && minFaan > 0;
const consider = [];
if (options.kong) {
counts[kind] -= 3;
const s = shanten(counts, m + 1);
counts[kind] += 3;
if (s <= s0) return { type: 'kong' };
consider.push({ type: 'kong', s, tiles: null });
}
if (options.pung) {
counts[kind] -= 2;
const s = shanten(counts, m + 1);
counts[kind] += 2;
if (s < s0) return { type: 'pung' };
consider.push({ type: 'pung', s, tiles: null });
}
for (const tiles of options.chows) {
counts[tiles[0]]--; counts[tiles[1]]--;
const s = shanten(counts, m + 1);
counts[tiles[0]]++; counts[tiles[1]]++;
if (s < s0) return { type: 'chow', tiles };
consider.push({ type: 'chow', s, tiles });
}
return null;
const fpc = skill >= TUNE.flushSkill ? flushPlan(state, seat) : null;
const flushing = fpc && fpc.f >= TUNE.flushAt && wallRemaining(state) > TUNE.flushWall;
if (flushing && kind < 27 && Math.floor(kind / 9) !== fpc.suit) {
return { claim: null, reason: `you're building ${SUIT_NAMES[fpc.suit]} — an off-suit meld would spoil it` };
}
let passWhy = `it wouldn't bring you closer to ready (you're ${s0 <= 0 ? 'already ready' : plural(s0, 'step') + ' away'})`;
for (const c of consider) {
const improves = c.type === 'kong' ? c.s <= s0 : c.s < s0;
const honorPung = c.type !== 'chow' && valueHonor && c.s <= s0;
if (!improves && !honorPung) continue;
const look = outlookOk(c.type, c.tiles);
if (!look.ok && prof.value > 0) {
passWhy = `claiming would open your hand and leave it short of the ${minFaan}-faan minimum`;
continue;
}
// skill 5: don't spend a concealed hand on a slow chow
if (TUNE.concealChow && prof.fold && c.type === 'chow' && losingConcealed && s0 >= 3 && look.sure < minFaan + 1) {
passWhy = 'too early to open a concealed hand for a chow';
continue;
}
const claim = c.type === 'chow' ? { type: 'chow', tiles: c.tiles } : { type: c.type };
let reason;
if (honorPung) reason = `a ${nm(kind)} ${c.type} is worth a faan`;
else if (c.type === 'kong') reason = 'a kong — and a free replacement draw';
else reason = `one step closer to ready (${s0} → ${c.s} away)`;
if (losingConcealed) reason += ' (you give up the concealed-hand faan)';
return { claim, reason };
}
return { claim: null, reason: passWhy };
}
export function chooseClaim(state, seat, options, skill = 3) {
return explainClaim(state, seat, options, skill).claim;
}
// Decide on a self-drawn win or a kong declaration while awaiting discard.
@ -213,3 +357,23 @@ export function collectAIClaims(state, humanSeat = 0) {
}
return intents;
}
// ── coach (the human's hint) ─────────────────────────────────────────────────
export function coachDiscard(state, seat) {
const d = chooseDiscardDetailed(state, seat, 5, () => 0.5);
return { kind: d.kind, text: `Throw the ${nm(d.kind)} — ${d.reason}.` };
}
export function coachClaim(state, seat, options) {
const { claim, reason } = explainClaim(state, seat, options, 5);
if (!claim) return { claim: null, label: 'Pass', text: `Pass — ${reason}.` };
const label = claim.type === 'win' ? 'Mahjong!' : claim.type === 'chow' ? 'Chow' : claim.type === 'pung' ? 'Pung' : 'Kong';
return { claim, label, text: `${label} — ${reason}.` };
}
export function coachSelf(state, seat, actions) {
const a = chooseSelfAction(state, seat, actions, 5);
if (a?.type === 'win') return { action: a, text: 'Declare Mahjong — your drawn tile completes the hand!' };
if (a?.type === 'kong') return { action: a, text: `Declare the kong of ${nm(a.spec.kind)} — it costs nothing and draws you a replacement.` };
return { action: null, text: coachDiscard(state, seat).text };
}

View File

@ -0,0 +1,320 @@
// MahjongAdvisor.js — table sense, Phaser-free. Shared by the on-screen
// helpers (ready indicator, discard advisor, tile tracker, danger shading,
// hand-pattern compass, opponent reads) and by the AI, so what the coach
// tells you is exactly how the strongest opponents think.
//
// Everything here only uses what `seat` could legitimately know: its own
// hand, every river, every exposed meld and bonus tile.
import {
TILES, SUIT_NAMES, WIND_NAMES, isSuited, isHonor, rankOf, isTerminal,
WIND_KINDS, DRAGON_KINDS, FIRST_BONUS,
} from './MahjongData.js';
import {
counts34, shanten, canWinWith, evaluateWin, seatWindOf, wallRemaining,
} from './MahjongLogic.js';
export const ORPHANS = [0, 8, 9, 17, 18, 26, 27, 28, 29, 30, 31, 32, 33];
// ── what's been seen ─────────────────────────────────────────────────────────
// Copies of each kind `seat` can account for: its hand, all rivers, all
// melds (concealed kongs are shown with two faces up, so they count too).
export function visibleCounts(state, seat) {
const v = new Array(34).fill(0);
for (const k of state.players[seat].hand) v[k]++;
for (const river of state.discards) for (const k of river) v[k]++;
for (const p of state.players) for (const m of p.melds) for (const k of m.kinds) v[k]++;
return v;
}
// How many of each kind are still out there (wall or other hands).
export function unseenCounts(state, seat) {
return visibleCounts(state, seat).map((n) => Math.max(0, 4 - n));
}
// Tiles that could lower shanten when drawn: anything paired with or next to
// a held tile. A brand-new isolated kind never lowers standard shanten.
export function improverKinds(counts) {
const out = new Set();
for (let k = 0; k < 34; k++) {
if (counts[k] === 0) continue;
out.add(k);
if (!isSuited(k)) continue;
const r = rankOf(k);
for (const d of [-2, -1, 1, 2]) if (r + d >= 1 && r + d <= 9) out.add(k + d);
}
// thirteen-orphans shapes improve on any missing orphan
let orph = 0;
for (const k of ORPHANS) if (counts[k] > 0) orph++;
if (orph >= 7) for (const k of ORPHANS) out.add(k);
return [...out];
}
// A copy of `state` in which `seat` has just won on `kind` — used to price
// a wait before it happens. Contextual faan (last tile, kong draw) ignored.
function hypoWin(state, seat, kind, selfDraw) {
const p = state.players[seat];
const players = state.players.slice();
players[seat] = { ...p, hand: selfDraw ? p.hand.concat([kind]) : p.hand };
const fake = {
...state, players,
lastDiscard: selfDraw ? null : { kind, from: (seat + 3) % 4 },
lastDrawWasKongReplacement: false, wallPos: 0, wallEnd: 10,
claimCount: 1, kongCount: 1, discardCount: 9,
};
return evaluateWin(fake, seat, kind, !selfDraw);
}
// Waits of a 13 − 3·melds hand: [{ kind, left, faan, faanSelf, ok, okSelf }]
// (`ok` = the table minimum is met on a discard win, `okSelf` on self-draw).
export function waitsOf(state, seat, unseen = unseenCounts(state, seat)) {
const p = state.players[seat];
const out = [];
for (let k = 0; k < 34; k++) {
if (!canWinWith(p.hand, p.melds, k)) continue;
const d = hypoWin(state, seat, k, false);
const sd = hypoWin(state, seat, k, true);
out.push({
kind: k, left: unseen[k], faan: d.faan, faanSelf: sd.faan,
ok: d.faan >= state.opts.minFaan, okSelf: sd.faan >= state.opts.minFaan,
});
}
return out;
}
// Same as waitsOf, for the hand left after discarding `discard` (on turn).
function waitsAfter(state, seat, discard, unseen) {
const p = state.players[seat];
const hand = p.hand.slice();
hand.splice(hand.indexOf(discard), 1);
const players = state.players.slice();
players[seat] = { ...p, hand };
return waitsOf({ ...state, players }, seat, unseen);
}
// Useful-draw count for a 13 − 3·m concealed count vector.
export function ukeireOf(counts, meldCount, unseen) {
const s0 = shanten(counts, meldCount);
let n = 0;
const kinds = [];
for (const t of improverKinds(counts)) {
if (counts[t] >= 4) continue;
counts[t]++;
if (shanten(counts, meldCount) < s0) { n += unseen[t]; if (unseen[t] > 0) kinds.push(t); }
counts[t]--;
}
return { shanten: s0, ukeire: n, kinds };
}
// Discard analysis for the player on turn (hand of 14 − 3·m): one row per
// distinct kind, best first: { kind, shanten, ukeire, kinds, waits?,
// winnable (live winning tiles that meet the minimum), danger }.
export function discardAdvice(state, seat, { withDanger = true } = {}) {
const p = state.players[seat];
const m = p.melds.length;
const counts = counts34(p.hand);
const unseen = unseenCounts(state, seat);
const danger = withDanger ? dangerMap(state, seat) : null;
const rows = [];
for (let k = 0; k < 34; k++) {
if (!counts[k]) continue;
counts[k]--;
const u = ukeireOf(counts, m, unseen);
counts[k]++;
const row = { kind: k, shanten: u.shanten, ukeire: u.ukeire, kinds: u.kinds, danger: danger ? danger[k] : 0 };
if (u.shanten === 0) {
row.waits = waitsAfter(state, seat, k, unseen);
row.winnable = row.waits.reduce((a, w) => a + (w.ok || w.okSelf ? w.left : 0), 0);
}
rows.push(row);
}
rows.sort((a, b) => a.shanten - b.shanten
|| (b.winnable ?? 0) - (a.winnable ?? 0)
|| b.ukeire - a.ukeire
|| a.danger - b.danger);
return rows;
}
// ── reading the other players ────────────────────────────────────────────────
// For each opponent: how close they look and what they seem to collect.
export function readOpponent(state, seat, q) {
const p = state.players[q];
const exposed = p.melds.filter((mm) => !mm.concealed);
const suits = new Set();
let honorMelds = 0, chows = 0, pungs = 0;
const yakuhai = [];
const sw = WIND_KINDS[seatWindOf(state, q)], rw = WIND_KINDS[state.roundWind % 4];
for (const mm of p.melds) {
const k = mm.kinds[0];
if (isSuited(k)) suits.add(Math.floor(k / 9)); else honorMelds++;
if (mm.type === 'chow') chows++; else pungs++;
if (mm.type !== 'chow' && (DRAGON_KINDS.includes(k) || k === sw || k === rw)) yakuhai.push(k);
}
// a suit they're hoarding: few or none of it in their river
const river = state.discards[q];
const riverSuit = [0, 0, 0];
for (const k of river) if (isSuited(k)) riverSuit[Math.floor(k / 9)]++;
let flush = -1;
if (p.melds.length >= 2 && suits.size === 1) {
const s = [...suits][0];
const others = riverSuit.reduce((a, n, i) => a + (i === s ? 0 : n), 0);
if (riverSuit[s] <= 1 || others >= riverSuit[s] * 3) flush = s;
} else if (river.length >= 9 && p.melds.length <= 1) {
const zero = riverSuit.findIndex((n) => n === 0);
if (zero >= 0 && riverSuit.filter((n) => n === 0).length === 1 && (p.melds.length === 0 || suits.has(zero))) flush = zero;
}
const wallLeft = wallRemaining(state);
const late = wallLeft < 24 ? 0.18 : wallLeft < 48 ? 0.08 : 0;
let threat = 0.08 + 0.21 * exposed.length + late + Math.min(0.12, river.length * 0.007) + (flush >= 0 ? 0.12 : 0);
if (p.melds.length >= 4) threat = 1;
threat = Math.max(0, Math.min(1, threat));
return { seat: q, melds: p.melds.length, exposed: exposed.length, chows, pungs, honorMelds, yakuhai, flush, threat };
}
export function readTable(state, seat) {
const out = [];
for (let q = 0; q < 4; q++) if (q !== seat) out.push(readOpponent(state, seat, q));
return out;
}
// One line per opponent for the "opponent reads" helper.
export function describeRead(state, r) {
const bits = [];
if (r.melds >= 3) bits.push('one or two tiles from ready');
else if (r.melds === 2) bits.push('two melds down');
else if (r.melds === 1) bits.push('one meld down');
if (r.flush >= 0) bits.push(`collecting ${SUIT_NAMES[r.flush]}`);
if (r.yakuhai.length) bits.push(`${r.yakuhai.map((k) => TILES[k].name.replace(' Dragon', '').replace(' Wind', '')).join(' & ')} pung showing`);
if (r.pungs >= 2 && r.chows === 0) bits.push('going for pungs?');
if (!bits.length) bits.push(r.threat < 0.25 ? 'quiet so far' : 'building');
return bits.join(' · ');
}
// Risk (0…1) of throwing each kind into someone's win, from `seat`'s view.
export function dangerMap(state, seat, reads = readTable(state, seat)) {
const vis = visibleCounts(state, seat);
const risk = new Array(34).fill(0);
for (let k = 0; k < 34; k++) {
const seen = vis[k];
if (seen >= 4) { risk[k] = 0; continue; }
let base;
if (isHonor(k)) base = seen >= 3 ? 0.06 : seen === 2 ? 0.28 : 0.55;
else if (isTerminal(k)) base = 0.38;
else if (rankOf(k) === 2 || rankOf(k) === 8) base = 0.5;
else base = 0.62;
let worst = 0;
for (const r of reads) {
let x = base;
if (r.flush >= 0) {
if (isSuited(k)) x *= Math.floor(k / 9) === r.flush ? 1.7 : 0.3;
else x *= 0.9;
}
if (state.discards[r.seat].includes(k)) x *= 0.55; // they let it go once
worst = Math.max(worst, Math.min(1, x * r.threat * 1.6));
}
risk[k] = Math.round(worst * 100) / 100;
}
return risk;
}
// ── hand-pattern compass ─────────────────────────────────────────────────────
// What this hand could become: [{ id, label, faan, progress (0…1), note }],
// most promising first, plus `sure` — faan already banked.
export function patternCompass(state, seat) {
const p = state.players[seat];
const o = state.opts;
const all = p.hand.concat(...p.melds.map((m) => m.kinds));
const c = counts34(all);
const exposed = p.melds.filter((m) => !m.concealed);
const sw = WIND_KINDS[seatWindOf(state, seat)], rw = WIND_KINDS[state.roundWind % 4];
const items = [];
let sure = 0;
const sureBits = [];
if (o.bonusTiles) {
const seatWind = seatWindOf(state, seat);
const own = p.bonus.filter((b) => (b - FIRST_BONUS) % 4 === seatWind).length;
if (own) { sure += own; sureBits.push(`own flower ×${own}`); }
if (p.bonus.length === 0) { sure += 1; sureBits.push('no bonus tiles'); }
}
for (const m of p.melds) {
const k = m.kinds[0];
if (m.type === 'chow') continue;
if (DRAGON_KINDS.includes(k)) { sure += 1; sureBits.push(`${TILES[k].name} pung`); }
if (k === sw) { sure += 1; sureBits.push('seat wind pung'); }
if (k === rw) { sure += 1; sureBits.push('round wind pung'); }
}
// honor pungs still in the hand
for (const k of [...DRAGON_KINDS, ...new Set([sw, rw])]) {
const inHand = p.hand.filter((t) => t === k).length;
if (inHand >= 2 && !p.melds.some((m) => m.kinds[0] === k)) {
const name = DRAGON_KINDS.includes(k) ? `${TILES[k].name} Pung` : `${WIND_NAMES[k - 27]} Wind Pung`;
items.push({ id: DRAGON_KINDS.includes(k) ? 'dragon-pung' : (k === sw ? 'seat-wind' : 'round-wind'), label: name, faan: (k === sw && k === rw) ? 2 : 1,
progress: inHand >= 3 ? 1 : 0.66, note: inHand >= 3 ? 'held concealed' : 'one more makes it' });
}
}
// one suit
const suitN = [0, 1, 2].map((s) => c.slice(s * 9, s * 9 + 9).reduce((a, x) => a + x, 0));
const honors = c.slice(27).reduce((a, x) => a + x, 0);
const best = suitN.indexOf(Math.max(...suitN));
const meldSuitsOk = p.melds.every((m) => !isSuited(m.kinds[0]) || Math.floor(m.kinds[0] / 9) === best);
if (meldSuitsOk) {
const f = (suitN[best] + honors) / Math.max(1, all.length);
const pure = honors === 0;
if (f >= 0.55) {
const off = all.length - suitN[best] - honors;
items.push({ id: pure ? 'pure-one-suit' : 'mixed-one-suit', label: `${pure ? 'Pure' : 'Mixed'} One Suit (${SUIT_NAMES[best]})`,
faan: pure ? 6 : 3, progress: f, note: off ? `${off} off-suit tile${off === 1 ? '' : 's'} to shed` : 'all in!' });
}
}
// all pungs
if (p.melds.every((m) => m.type !== 'chow')) {
let trip = 0, pairs = 0;
for (let k = 0; k < 34; k++) { if (c[k] >= 3) trip++; else if (c[k] === 2) pairs++; }
const prog = Math.min(1, (trip * 3 + Math.min(pairs, 5 - trip) * 2) / 14);
if (trip + pairs >= 4) items.push({ id: 'all-pungs', label: 'All Pungs', faan: 3, progress: prog, note: `${trip} pung${trip === 1 ? '' : 's'}, ${pairs} pair${pairs === 1 ? '' : 's'}` });
}
// dragons
const dr = DRAGON_KINDS.map((k) => c[k]);
const drPungs = dr.filter((n) => n >= 3).length, drPairs = dr.filter((n) => n === 2).length;
if (drPungs + drPairs >= 2 && drPungs >= 1) {
items.push({ id: drPungs + drPairs >= 3 ? 'great-dragons' : 'small-dragons', label: drPungs + drPairs >= 3 ? 'Great Dragons' : 'Small Dragons',
faan: drPungs + drPairs >= 3 ? 8 : 5, progress: (drPungs * 3 + drPairs * 2) / 9, note: 'big hand brewing!' });
}
// concealed
if (exposed.length === 0) items.push({ id: 'concealed', label: 'Concealed Hand', faan: 1, progress: 0.5, note: 'keep it closed: no claims except to win' });
// common hand (all chows)
if (p.melds.every((m) => m.type === 'chow') && honors <= 1) {
items.push({ id: 'common-hand', label: 'Common Hand', faan: 1, progress: 0.45, note: 'runs only, suited pair' });
}
// thirteen orphans
if (p.melds.length === 0) {
const have = ORPHANS.filter((k) => c[k] > 0).length;
if (have >= 9) items.push({ id: 'thirteen-orphans', label: 'Thirteen Orphans', faan: o.faanCap, progress: have / 13, note: `${have} of 13 orphans` });
}
items.sort((a, b) => (b.progress * Math.sqrt(b.faan)) - (a.progress * Math.sqrt(a.faan)));
return { sure, sureBits, items: items.slice(0, 4) };
}
// The best faan a winning hand here could realistically carry — used by the
// AI to avoid claiming its way into a hand that can never meet the minimum.
export function valueOutlook(state, seat, { afterExposing = false } = {}) {
const comp = patternCompass(state, seat);
let sure = comp.sure;
const concealed = state.players[seat].melds.every((m) => m.concealed) && !afterExposing;
let likely = 0;
for (const it of comp.items) {
if (it.id === 'concealed') continue;
if (it.progress >= 0.99 && (it.id === 'dragon-pung' || it.id === 'seat-wind' || it.id === 'round-wind')) sure += it.faan;
else likely = Math.max(likely, it.faan * Math.max(0, (it.progress - 0.5) * 2));
}
return { sure: sure + (concealed ? 1 : 0), likely, concealed };
}

View File

@ -0,0 +1,600 @@
// MahjongArt.js — baked canvas textures for "An evening at the mahjong
// parlour". All procedural except the shared tile-label PNGs (mahjong-*).
//
// mj-room the parlour: lacquered walls, lattice screens, lanterns,
// a rain-streaked window, dark floorboards
// mj-table the square table in perspective: jade felt, mahogany rail
// with its near face, tea things on the far corners, the
// centre compass plate (transparent outside the table)
// mj-light pendant-lamp pool + vignette (ADD/normal overlays)
// mj-flat-p atlas: lying tiles, portrait (frames `0-<kind>`, `2-<kind>`, `back`)
// mj-flat-l atlas: lying tiles, landscape (frames `1-<kind>`, `3-<kind>`, `back`)
// mj-hand atlas: your standing tiles (frames `<kind>`, `back`)
// mj-stand atlas: opponents' standing tiles (`sb` back-on, `sl`/`sr` side-on)
// mj-shadow, mj-glow, mj-lantern, mj-steam, mj-rain, mj-panel-<w>x<h>
//
// Tile atlases are CanvasTextures redrawn in place when Western corner
// indices are toggled, so sprites never need re-texturing.
import { canvas, rr } from '../../ui/casino/CasinoArt.js';
import {
W, H, FW, FH, STRIP, HAND, TABLE, COMPASS, project, quad,
} from './MahjongLayout.js';
import { TILES, KIND_COUNT, isSuited, rankOf } from './MahjongData.js';
export const DISPLAY_FONT = 'Righteous, Georgia, serif';
export const LABEL_FONT = '"Julius Sans One", Georgia, serif';
export const SERIF = 'Georgia, "Times New Roman", serif';
export const LABEL_W = 128, LABEL_H = 178;
// Seat colours (seat 0 = you) — lacquer red, peacock blue, jade, gold.
export const SEAT = [
{ base: '#c8402e', hex: 0xc8402e, ink: '#f2a08e', light: 0xf07a5e },
{ base: '#2f7fc0', hex: 0x2f7fc0, ink: '#9fcaf0', light: 0x6fb2ec },
{ base: '#3a9a5e', hex: 0x3a9a5e, ink: '#a6e2b8', light: 0x72d095 },
{ base: '#d9a42a', hex: 0xd9a42a, ink: '#f6d88a', light: 0xf3cd6a },
];
const IVORY = ['#fffaf0', '#f4ead2', '#e6d9b8'];
// Tile backs: orchid purple (light, mid, deep) — a traditional backing
// colour that stands clear of the jade felt. Change here to recolour every back.
const BACK = ['#a35fb6', '#7e4196', '#55286c'];
const BACK_EDGE = '#371446', BACK_SHEEN = 'rgba(236,196,250,0.38)', BACK_SWIRL = 'rgba(244,206,255,0.2)', BACK_LIT = '#b77fcb';
const EDGE = '#b9a57e';
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 addCanvas(scene, key, c) {
if (scene.textures.exists(key)) scene.textures.remove(key);
scene.textures.addCanvas(key, c);
}
function polyPath(ctx, pts) {
ctx.beginPath();
pts.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.closePath();
}
// ── the room ─────────────────────────────────────────────────────────────────
function bakeRoom(scene) {
const c = canvas(W, H);
const ctx = c.getContext('2d');
const rnd = seeded(88);
// lacquered wall: deep oxblood with a warm gradient
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, '#3a1410');
g.addColorStop(0.45, '#2a0e0b');
g.addColorStop(1, '#140806');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
// vertical panel seams
for (let x = 0; x < W; x += 240) {
ctx.fillStyle = 'rgba(0,0,0,0.28)'; ctx.fillRect(x, 0, 6, H);
ctx.fillStyle = 'rgba(255,190,140,0.05)'; ctx.fillRect(x + 6, 0, 2, H);
}
// carved lattice band along the top
ctx.save();
ctx.fillStyle = '#4a1c12';
ctx.fillRect(0, 0, W, 92);
ctx.strokeStyle = 'rgba(214,160,80,0.42)';
ctx.lineWidth = 3;
for (let x = -20; x < W + 40; x += 46) {
ctx.strokeRect(x, 14, 30, 30);
ctx.strokeRect(x + 23, 46, 30, 30);
ctx.beginPath(); ctx.moveTo(x + 15, 44); ctx.lineTo(x + 15, 60); ctx.stroke();
}
ctx.fillStyle = '#7a2a18'; ctx.fillRect(0, 88, W, 8);
ctx.fillStyle = 'rgba(240,190,110,0.5)'; ctx.fillRect(0, 88, W, 2);
ctx.restore();
// rain-streaked window, top left & top right, behind lattice frames
for (const wx of [70, W - 370]) {
const wy = 120, ww = 300, wh = 230;
const sky = ctx.createLinearGradient(0, wy, 0, wy + wh);
sky.addColorStop(0, '#13233a'); sky.addColorStop(1, '#0b1422');
ctx.fillStyle = sky; ctx.fillRect(wx, wy, ww, wh);
// distant neon blur
for (let i = 0; i < 14; i++) {
const col = ['rgba(255,80,90,', 'rgba(80,200,255,', 'rgba(255,200,90,'][i % 3];
const rg = ctx.createRadialGradient(wx + rnd() * ww, wy + wh * (0.5 + rnd() * 0.5), 0, wx + rnd() * ww, wy + wh * 0.8, 30 + rnd() * 50);
rg.addColorStop(0, col + '0.35)'); rg.addColorStop(1, col + '0)');
ctx.fillStyle = rg; ctx.fillRect(wx, wy, ww, wh);
}
for (let i = 0; i < 160; i++) {
ctx.strokeStyle = `rgba(190,215,255,${0.08 + rnd() * 0.18})`;
ctx.lineWidth = 1;
const x = wx + rnd() * ww, y = wy + rnd() * wh;
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x - 2, y + 8 + rnd() * 14); ctx.stroke();
}
ctx.strokeStyle = '#5a2414'; ctx.lineWidth = 12; ctx.strokeRect(wx, wy, ww, wh);
ctx.lineWidth = 5;
for (let k = 1; k < 4; k++) { ctx.beginPath(); ctx.moveTo(wx + (ww * k) / 4, wy); ctx.lineTo(wx + (ww * k) / 4, wy + wh); ctx.stroke(); }
ctx.beginPath(); ctx.moveTo(wx, wy + wh / 2); ctx.lineTo(wx + ww, wy + wh / 2); ctx.stroke();
ctx.strokeStyle = 'rgba(230,170,90,0.35)'; ctx.lineWidth = 2; ctx.strokeRect(wx - 6, wy - 6, ww + 12, wh + 12);
}
// hanging scroll between the windows (calligraphy-ish strokes)
// floorboards at the very bottom
const fy = 930;
const fg = ctx.createLinearGradient(0, fy, 0, H);
fg.addColorStop(0, '#2a1409'); fg.addColorStop(1, '#120803');
ctx.fillStyle = fg; ctx.fillRect(0, fy, W, H - fy);
for (let y = fy; y < H; y += 26) { ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(0, y, W, 2); }
// noise
for (let i = 0; i < 14000; i++) {
ctx.fillStyle = `rgba(${rnd() < 0.5 ? '0,0,0' : '255,200,150'},${0.02 + rnd() * 0.04})`;
ctx.fillRect(rnd() * W, rnd() * H, 1 + rnd() * 2, 1);
}
addCanvas(scene, 'mj-room', c);
}
// ── the table ────────────────────────────────────────────────────────────────
function bakeTable(scene) {
const c = canvas(W, H);
const ctx = c.getContext('2d');
const rnd = seeded(7);
const R = TABLE.half + TABLE.rail;
const outer = quad(-R, -R, R, R);
const inner = quad(-TABLE.half, -TABLE.half, TABLE.half, TABLE.half);
// shadow on the floor/room
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.7)'; ctx.shadowBlur = 60; ctx.shadowOffsetY = 30;
polyPath(ctx, outer); ctx.fillStyle = '#1a0a05'; ctx.fill();
ctx.restore();
// rail front face (near edge, thickness)
const nearL = outer[3], nearR = outer[2];
const faceH = 30;
const fg = ctx.createLinearGradient(0, nearL.y, 0, nearL.y + faceH);
fg.addColorStop(0, '#4a1a0c'); fg.addColorStop(1, '#1e0904');
ctx.fillStyle = fg;
polyPath(ctx, [nearL, nearR, { x: nearR.x - 4, y: nearR.y + faceH }, { x: nearL.x + 4, y: nearL.y + faceH }]);
ctx.fill();
// side faces (slivers)
ctx.fillStyle = '#2a0e06';
polyPath(ctx, [outer[0], outer[3], { x: outer[3].x + 4, y: outer[3].y + faceH }]); ctx.fill();
polyPath(ctx, [outer[1], outer[2], { x: outer[2].x - 4, y: outer[2].y + faceH }]); ctx.fill();
// rail top — mahogany with grain
ctx.save();
polyPath(ctx, outer); ctx.clip();
const rg = ctx.createLinearGradient(0, outer[0].y, 0, outer[3].y);
rg.addColorStop(0, '#5e2210'); rg.addColorStop(1, '#7a2e14');
ctx.fillStyle = rg; ctx.fillRect(0, 0, W, H);
for (let i = 0; i < 600; i++) {
ctx.strokeStyle = `rgba(${rnd() < 0.5 ? '30,8,2' : '160,80,40'},${0.06 + rnd() * 0.1})`;
ctx.lineWidth = 1 + rnd() * 1.5;
const y = outer[0].y + rnd() * (outer[3].y - outer[0].y + 30);
ctx.beginPath(); ctx.moveTo(0, y); ctx.bezierCurveTo(W * 0.3, y + rnd() * 8 - 4, W * 0.6, y + rnd() * 8 - 4, W, y + rnd() * 6 - 3); ctx.stroke();
}
ctx.restore();
// gold inlay line around the felt
const inlay = quad(-TABLE.half - 0.02, -TABLE.half - 0.02, TABLE.half + 0.02, TABLE.half + 0.02);
ctx.strokeStyle = 'rgba(226,180,96,0.75)'; ctx.lineWidth = 2;
polyPath(ctx, inlay); ctx.stroke();
// felt
ctx.save();
polyPath(ctx, inner); ctx.clip();
const ctr = project(0, -0.05);
const fe = ctx.createRadialGradient(ctr.x, ctr.y, 30, ctr.x, ctr.y, 760);
fe.addColorStop(0, '#2c8a62'); fe.addColorStop(0.55, '#1b6a4a'); fe.addColorStop(1, '#0c3d2a');
ctx.fillStyle = fe; ctx.fillRect(0, 0, W, H);
for (let i = 0; i < 52000; i++) {
const x = rnd() * W, y = 120 + rnd() * 780;
ctx.fillStyle = `rgba(${rnd() < 0.5 ? '0,30,18' : '120,220,170'},${0.03 + rnd() * 0.05})`;
ctx.fillRect(x, y, 1, 1 + rnd());
}
// inner felt bevel shadow
ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 16; polyPath(ctx, inner); ctx.stroke();
// the compass plate: a lacquered square with gold trim
const ch = COMPASS.half;
const plate = quad(-ch, -ch, ch, ch);
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 18; ctx.shadowOffsetY = 8;
polyPath(ctx, plate);
const pg = ctx.createLinearGradient(0, plate[0].y, 0, plate[3].y);
pg.addColorStop(0, '#5a1410'); pg.addColorStop(1, '#7c1f14');
ctx.fillStyle = pg; ctx.fill();
ctx.restore();
ctx.strokeStyle = '#d9a441'; ctx.lineWidth = 3; polyPath(ctx, plate); ctx.stroke();
const pin = quad(-ch + 0.03, -ch + 0.03, ch - 0.03, ch - 0.03);
ctx.strokeStyle = 'rgba(217,164,65,0.55)'; ctx.lineWidth = 1.5; polyPath(ctx, pin); ctx.stroke();
// centre medallion
const m = project(0, 0);
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.beginPath(); ctx.ellipse(m.x, m.y, 46 * m.s, 40 * m.s, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(217,164,65,0.6)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.ellipse(m.x, m.y, 46 * m.s, 40 * m.s, 0, 0, Math.PI * 2); ctx.stroke();
ctx.restore();
// tea things on the far corners of the rail
for (const side of [-1, 1]) {
const p = project(side * (TABLE.half + 0.0), -TABLE.half - 0.02);
teacup(ctx, p.x + side * 8, p.y - 2, p.s * 0.95);
}
const tp = project(-TABLE.half - 0.02, 0.15);
addCanvas(scene, 'mj-table', c);
return tp;
}
function teacup(ctx, x, y, s) {
ctx.save();
ctx.translate(x, y); ctx.scale(s, s);
// saucer
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.beginPath(); ctx.ellipse(4, 8, 36, 13, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#ece6d8';
ctx.beginPath(); ctx.ellipse(0, 4, 34, 12, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#3d6fb0'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.ellipse(0, 4, 28, 9, 0, 0, Math.PI * 2); ctx.stroke();
// cup
const cg = ctx.createLinearGradient(-20, 0, 20, 0);
cg.addColorStop(0, '#d8d0c0'); cg.addColorStop(0.4, '#fbf8f0'); cg.addColorStop(1, '#bfb6a4');
ctx.fillStyle = cg;
ctx.beginPath(); ctx.moveTo(-20, -18); ctx.lineTo(20, -18); ctx.quadraticCurveTo(18, 6, 0, 6); ctx.quadraticCurveTo(-18, 6, -20, -18); ctx.fill();
ctx.strokeStyle = '#3d6fb0'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(-17, -8); ctx.quadraticCurveTo(0, -2, 17, -8); ctx.stroke();
// tea
ctx.fillStyle = '#8a5a1c';
ctx.beginPath(); ctx.ellipse(0, -18, 20, 6, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,220,150,0.35)';
ctx.beginPath(); ctx.ellipse(-5, -19, 8, 2, 0, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
function bakeLight(scene) {
const c = canvas(W, H);
const ctx = c.getContext('2d');
const p = project(0, -0.1);
const g = ctx.createRadialGradient(p.x, p.y, 40, p.x, p.y, 1150);
g.addColorStop(0, 'rgba(0,0,0,0)');
g.addColorStop(0.5, 'rgba(0,0,0,0.08)');
g.addColorStop(0.8, 'rgba(10,2,0,0.45)');
g.addColorStop(1, 'rgba(8,2,0,0.75)');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
addCanvas(scene, 'mj-vignette', c);
// warm lamp pool (ADD)
const c2 = canvas(1024, 768);
const x2 = c2.getContext('2d');
const g2 = x2.createRadialGradient(512, 384, 10, 512, 384, 500);
g2.addColorStop(0, 'rgba(255,214,150,0.30)');
g2.addColorStop(0.5, 'rgba(255,190,120,0.10)');
g2.addColorStop(1, 'rgba(255,170,100,0)');
x2.fillStyle = g2; x2.fillRect(0, 0, 1024, 768);
addCanvas(scene, 'mj-lamp', c2);
}
// ── small bits ───────────────────────────────────────────────────────────────
function bakeBits(scene) {
// soft shadow
{
const c = canvas(96, 96); const ctx = c.getContext('2d');
ctx.filter = 'blur(10px)';
ctx.fillStyle = 'rgba(0,0,0,0.85)';
rr(ctx, 22, 22, 52, 52, 10); ctx.fill();
addCanvas(scene, 'mj-shadow', c);
}
// glow ring for highlighted tiles
{
const c = canvas(128, 160); const ctx = c.getContext('2d');
ctx.shadowColor = 'rgba(255,210,90,1)'; ctx.shadowBlur = 18;
ctx.strokeStyle = 'rgba(255,224,130,0.95)'; ctx.lineWidth = 6;
rr(ctx, 24, 24, 80, 112, 12); ctx.stroke();
addCanvas(scene, 'mj-glow', c);
}
// lantern
{
const c = canvas(120, 200); const ctx = c.getContext('2d');
ctx.strokeStyle = '#2a120a'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.moveTo(60, 0); ctx.lineTo(60, 40); ctx.stroke();
const glow = ctx.createRadialGradient(60, 110, 6, 60, 110, 60);
glow.addColorStop(0, '#ffd27a'); glow.addColorStop(0.45, '#e0452c'); glow.addColorStop(1, '#8a1a10');
ctx.fillStyle = '#3a160c'; ctx.fillRect(40, 38, 40, 10); ctx.fillRect(40, 172, 40, 10);
ctx.fillStyle = glow;
ctx.beginPath(); ctx.ellipse(60, 110, 52, 64, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(80,16,8,0.6)'; ctx.lineWidth = 2;
for (let k = -2; k <= 2; k++) { ctx.beginPath(); ctx.ellipse(60, 110, Math.abs(k) * 12 + 2, 64, 0, 0, Math.PI * 2); ctx.stroke(); }
ctx.strokeStyle = '#e8b24a'; ctx.lineWidth = 2;
for (let i = 0; i < 7; i++) { ctx.beginPath(); ctx.moveTo(48 + i * 4, 182); ctx.lineTo(48 + i * 4, 198); ctx.stroke(); }
addCanvas(scene, 'mj-lantern', c);
}
{
const c = canvas(260, 260); const ctx = c.getContext('2d');
const g = ctx.createRadialGradient(130, 130, 4, 130, 130, 130);
g.addColorStop(0, 'rgba(255,180,100,0.55)'); g.addColorStop(1, 'rgba(255,120,60,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, 260, 260);
addCanvas(scene, 'mj-lantern-glow', c);
}
// steam wisp
{
const c = canvas(48, 48); const ctx = c.getContext('2d');
const g = ctx.createRadialGradient(24, 24, 1, 24, 24, 22);
g.addColorStop(0, 'rgba(255,255,255,0.55)'); g.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, 48, 48);
addCanvas(scene, 'mj-steam', c);
}
// rain streak (for the window)
{
const c = canvas(4, 40); const ctx = c.getContext('2d');
const g = ctx.createLinearGradient(0, 0, 0, 40);
g.addColorStop(0, 'rgba(200,225,255,0)'); g.addColorStop(1, 'rgba(200,225,255,0.7)');
ctx.fillStyle = g; ctx.fillRect(1, 0, 2, 40);
addCanvas(scene, 'mj-rain', c);
}
// wind disc (the seat-wind chip on each panel)
{
const c = canvas(96, 96); const ctx = c.getContext('2d');
ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.beginPath(); ctx.arc(50, 52, 44, 0, Math.PI * 2); ctx.fill();
const g = ctx.createRadialGradient(40, 36, 4, 48, 48, 46);
g.addColorStop(0, '#fffaf0'); g.addColorStop(1, '#dccfae');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(48, 48, 44, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#a8813e'; ctx.lineWidth = 4; ctx.stroke();
addCanvas(scene, 'mj-disc', c);
}
// dealer marker (a little red lacquer block with a gold rim)
{
const c = canvas(96, 64); const ctx = c.getContext('2d');
ctx.fillStyle = 'rgba(0,0,0,0.45)'; rr(ctx, 8, 14, 84, 46, 10); ctx.fill();
const g = ctx.createLinearGradient(0, 4, 0, 52);
g.addColorStop(0, '#d8432c'); g.addColorStop(1, '#7c160c');
ctx.fillStyle = g; rr(ctx, 4, 6, 84, 46, 10); ctx.fill();
ctx.strokeStyle = '#f0c25a'; ctx.lineWidth = 3; rr(ctx, 4, 6, 84, 46, 10); ctx.stroke();
addCanvas(scene, 'mj-dealer', c);
}
}
// Lacquer panel with a gold trim: mj-panel-<w>x<h> (drawn at 1× screen px).
export function panelKey(scene, w, h, { tint = '#2a0f0a', trim = '#d9a441' } = {}) {
const key = `mj-panel-${w}x${h}-${tint.slice(1)}`;
if (scene.textures.exists(key)) return key;
const pad = 18;
const c = canvas(w + pad * 2, h + pad * 2);
const ctx = c.getContext('2d');
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 6;
rr(ctx, pad, pad, w, h, 14);
const g = ctx.createLinearGradient(0, pad, 0, pad + h);
g.addColorStop(0, shadeHex(tint, 18)); g.addColorStop(1, shadeHex(tint, -10));
ctx.fillStyle = g; ctx.fill();
ctx.restore();
ctx.strokeStyle = trim; ctx.lineWidth = 2.5; rr(ctx, pad + 1, pad + 1, w - 2, h - 2, 13); ctx.stroke();
ctx.strokeStyle = 'rgba(217,164,65,0.28)'; ctx.lineWidth = 1; rr(ctx, pad + 6, pad + 6, w - 12, h - 12, 10); ctx.stroke();
// corner cloud-knots
ctx.strokeStyle = 'rgba(232,186,90,0.6)'; ctx.lineWidth = 2;
for (const [cx, cy, sx, sy] of [[pad + 6, pad + 6, 1, 1], [pad + w - 6, pad + 6, -1, 1], [pad + 6, pad + h - 6, 1, -1], [pad + w - 6, pad + h - 6, -1, -1]]) {
ctx.beginPath(); ctx.moveTo(cx, cy + sy * 16); ctx.lineTo(cx, cy); ctx.lineTo(cx + sx * 16, cy); ctx.stroke();
ctx.beginPath(); ctx.moveTo(cx + sx * 5, cy + sy * 10); ctx.lineTo(cx + sx * 5, cy + sy * 5); ctx.lineTo(cx + sx * 10, cy + sy * 5); ctx.stroke();
}
addCanvas(scene, key, c);
return key;
}
export const PANEL_PAD = 18;
function shadeHex(hex, amt) {
const n = parseInt(hex.slice(1), 16);
const f = (v) => Math.max(0, Math.min(255, v + amt));
return `rgb(${f(n >> 16)},${f((n >> 8) & 255)},${f(n & 255)})`;
}
// ── tiles ────────────────────────────────────────────────────────────────────
const IDX_COLOR = ['#2a7a3a', '#2a4fa0', '#b0281c'];
function indexText(kind) {
if (isSuited(kind)) return String(rankOf(kind));
if (kind >= 27 && kind <= 30) return 'ESWN'[kind - 27];
if (kind === 31) return 'R';
if (kind === 32) return 'G';
if (kind === 33) return 'Wh';
return '';
}
function indexColor(kind) {
if (isSuited(kind)) return IDX_COLOR[Math.floor(kind / 9)];
if (kind === 31) return '#b0281c';
if (kind === 32) return '#2a7a3a';
if (kind === 33) return '#2a4fa0';
return '#1a1a1a';
}
// The face of `kind`, label upright, inside a fw×fh box centred at (0,0).
function drawLabel(scene, ctx, kind, fw, fh, { index }) {
const t = TILES[kind];
const src = t.label && scene.textures.exists(t.label) ? scene.textures.get(t.label).getSourceImage() : null;
if (src) {
const sc = Math.min((fw * 0.8) / LABEL_W, (fh * 0.8) / LABEL_H);
const w = LABEL_W * sc, h = LABEL_H * sc;
ctx.drawImage(src, -w / 2, -h / 2 + (index ? fh * 0.02 : 0), w, h);
} else if (t.id === 'dragon-white') {
ctx.strokeStyle = '#3f6bb5'; ctx.lineWidth = Math.max(2, fw * 0.06);
rr(ctx, -fw * 0.29, -fh * 0.31, fw * 0.58, fh * 0.62, 5); ctx.stroke();
ctx.lineWidth = Math.max(1, fw * 0.025);
rr(ctx, -fw * 0.21, -fh * 0.23, fw * 0.42, fh * 0.46, 3); ctx.stroke();
}
if (index && kind < 34) {
const txt = indexText(kind);
ctx.font = `bold ${Math.round(fw * (txt.length > 1 ? 0.2 : 0.25))}px Righteous, Georgia, sans-serif`;
ctx.textAlign = 'left'; ctx.textBaseline = 'top';
ctx.fillStyle = 'rgba(255,250,240,0.85)';
ctx.fillText(txt, -fw / 2 + fw * 0.09 + 1, -fh / 2 + fh * 0.05 + 1);
ctx.fillStyle = indexColor(kind);
ctx.fillText(txt, -fw / 2 + fw * 0.09, -fh / 2 + fh * 0.05);
}
}
function faceFill(ctx, x, y, w, h, r, faceUp) {
const g = ctx.createLinearGradient(x, y, x + w * 0.4, y + h);
const cols = faceUp ? IVORY : BACK;
g.addColorStop(0, cols[0]); g.addColorStop(0.6, cols[1]); g.addColorStop(1, cols[2]);
ctx.fillStyle = g;
rr(ctx, x, y, w, h, r); ctx.fill();
ctx.strokeStyle = faceUp ? EDGE : BACK_EDGE; ctx.lineWidth = 2;
rr(ctx, x + 1, y + 1, w - 2, h - 2, r); ctx.stroke();
ctx.strokeStyle = faceUp ? 'rgba(255,255,255,0.7)' : BACK_SHEEN; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(x + r, y + 3); ctx.lineTo(x + w - r, y + 3); ctx.stroke();
if (!faceUp) {
// a faint swirl on the backs
ctx.strokeStyle = BACK_SWIRL; ctx.lineWidth = 2;
ctx.beginPath(); ctx.ellipse(x + w / 2, y + h / 2, w * 0.22, h * 0.18, 0.4, 0, Math.PI * 1.6); ctx.stroke();
}
}
// A lying tile: face box (fw×fh) at the top of the frame, the visible side
// strip below (ivory over the coloured back when face-up; back over ivory face-down).
function drawFlat(scene, ctx, x, y, fw, fh, rot, kind, opts) {
const r = 9;
const faceUp = kind != null;
// strip
const sy = y + fh * 0.5;
const sh = fh * 0.5 + STRIP;
ctx.fillStyle = faceUp ? BACK[1] : '#d9cba6';
rr(ctx, x, sy, fw, sh, r); ctx.fill();
ctx.fillStyle = faceUp ? '#e0d2ae' : BACK[2];
rr(ctx, x, sy, fw, sh - STRIP * 0.42, r); ctx.fill();
ctx.fillStyle = 'rgba(0,0,0,0.18)';
ctx.fillRect(x + 4, y + fh + STRIP - 3, fw - 8, 2);
faceFill(ctx, x, y, fw, fh, r, faceUp);
if (faceUp) {
ctx.save();
ctx.translate(x + fw / 2, y + fh / 2);
ctx.rotate((rot * Math.PI) / 2);
const pw = rot % 2 ? fh : fw, ph = rot % 2 ? fw : fh;
drawLabel(scene, ctx, kind, pw, ph, opts);
ctx.restore();
}
}
const PADX = 4;
function buildFlatAtlas(scene, key, land, opts) {
const fw = land ? FH : FW, fh = land ? FW : FH;
const cw = fw + PADX * 2, ch = fh + STRIP + PADX * 2;
const rots = land ? [1, 3] : [0, 2];
const cols = 12;
const frames = [];
for (const r of rots) for (let k = 0; k < KIND_COUNT; k++) frames.push({ name: `${r}-${k}`, r, k });
frames.push({ name: 'back', r: rots[0], k: null });
const rows = Math.ceil(frames.length / cols);
let tex = scene.textures.exists(key) ? scene.textures.get(key) : null;
if (!tex || tex.getSourceImage().width !== cols * cw) {
if (tex) scene.textures.remove(key);
tex = scene.textures.createCanvas(key, cols * cw, rows * ch);
}
const ctx = tex.getContext();
ctx.clearRect(0, 0, cols * cw, rows * ch);
frames.forEach((f, i) => {
const x = (i % cols) * cw, y = Math.floor(i / cols) * ch;
drawFlat(scene, ctx, x + PADX, y + PADX, fw, fh, f.r, f.k, opts);
if (!tex.has(f.name)) tex.add(f.name, 0, x + PADX, y + PADX, fw, fh + STRIP);
});
tex.refresh();
}
// Your standing tiles: face HAND.w×HAND.h at 2×, with the top cap above.
const HRES = 2;
export const HAND_TEX = { w: HAND.w * HRES, h: HAND.h * HRES, cap: HAND.cap * HRES };
function buildHandAtlas(scene, opts) {
const key = 'mj-hand';
const { w, h, cap } = HAND_TEX;
const cw = w + PADX * 2, ch = h + cap + PADX * 2;
const cols = 11;
const frames = [];
for (let k = 0; k < KIND_COUNT; k++) frames.push({ name: String(k), k });
frames.push({ name: 'back', k: null });
const rows = Math.ceil(frames.length / cols);
let tex = scene.textures.exists(key) ? scene.textures.get(key) : null;
if (!tex) tex = scene.textures.createCanvas(key, cols * cw, rows * ch);
const ctx = tex.getContext();
ctx.clearRect(0, 0, cols * cw, rows * ch);
frames.forEach((f, i) => {
const x = (i % cols) * cw + PADX, y = Math.floor(i / cols) * ch + PADX;
const up = f.k != null;
// top cap: far layer on top (the back colour for a face toward you), near layer below
ctx.fillStyle = up ? BACK[1] : '#e8dcbc';
rr(ctx, x, y, w, cap + 14, 12); ctx.fill();
ctx.fillStyle = up ? '#efe4c6' : BACK[0];
rr(ctx, x, y + cap * 0.45, w, cap * 0.55 + 14, 12); ctx.fill();
faceFill(ctx, x, y + cap, w, h, 14, up);
if (up) {
ctx.save();
ctx.translate(x + w / 2, y + cap + h / 2);
drawLabel(scene, ctx, f.k, w, h, opts);
ctx.restore();
}
// a little ambient darkening at the foot
const g = ctx.createLinearGradient(0, y + cap + h - 20, 0, y + cap + h);
g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(1, 'rgba(60,40,10,0.18)');
ctx.fillStyle = g; rr(ctx, x, y + cap + h - 20, w, 20, 12); ctx.fill();
if (!tex.has(f.name)) tex.add(f.name, 0, x, y, w, h + cap);
});
tex.refresh();
}
// Opponents' standing tiles. `sb`: back toward you (top player), `sl`/`sr`:
// side-on slabs for the left/right players.
export const STAND_TEX = { bw: FW, bh: 70, bcap: 18, sw: 40, sh: 104 };
function bakeStand(scene) {
const { bw, bh, bcap, sw, sh } = STAND_TEX;
const c = canvas(bw + sw * 2 + 30, Math.max(bh + bcap, sh) + 10);
const ctx = c.getContext('2d');
// sb
ctx.fillStyle = '#e6d8b4'; rr(ctx, 2, 2, bw, bcap + 12, 9); ctx.fill();
ctx.fillStyle = BACK[0]; rr(ctx, 2, 2 + bcap * 0.5, bw, bcap * 0.5 + 12, 9); ctx.fill();
faceFill(ctx, 2, 2 + bcap, bw, bh, 9, false);
// sl (left player's tile seen from the table's right: back on the right)
const slab = (x0, mirror) => {
ctx.save();
ctx.translate(x0 + (mirror ? sw : 0), 2);
ctx.scale(mirror ? -1 : 1, 1);
// top cap
const capH = 30;
let g = ctx.createLinearGradient(0, 0, sw, 0);
g.addColorStop(0, '#fbf3df'); g.addColorStop(0.55, '#e9dcbb'); g.addColorStop(0.56, BACK[0]); g.addColorStop(1, BACK[1]);
ctx.fillStyle = g; rr(ctx, 0, 0, sw, capH + 10, 7); ctx.fill();
// body: ivory face edge on the outside, coloured back toward the table centre
g = ctx.createLinearGradient(0, 0, sw, 0);
g.addColorStop(0, '#cdbf9c'); g.addColorStop(0.22, '#e4d6b2'); g.addColorStop(0.24, BACK[2]); g.addColorStop(0.7, BACK[1]); g.addColorStop(1, BACK_LIT);
ctx.fillStyle = g; rr(ctx, 0, capH, sw, sh - capH, 7); ctx.fill();
ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 1.5; rr(ctx, 0.5, 0.5, sw - 1, sh - 1, 7); ctx.stroke();
ctx.restore();
};
slab(bw + 12, false);
slab(bw + 12 + sw + 12, true);
const tex = scene.textures.exists('mj-stand') ? scene.textures.get('mj-stand') : null;
if (tex) scene.textures.remove('mj-stand');
const t = scene.textures.addCanvas('mj-stand', c);
t.add('sb', 0, 2, 2, bw, bh + bcap);
t.add('sl', 0, bw + 12, 2, sw, sh);
t.add('sr', 0, bw + 12 + sw + 12, 2, sw, sh);
}
export function bakeTiles(scene, { indices = true } = {}) {
const opts = { index: indices };
buildFlatAtlas(scene, 'mj-flat-p', false, opts);
buildFlatAtlas(scene, 'mj-flat-l', true, opts);
buildHandAtlas(scene, opts);
}
let baked = false;
export async function prepareMahjongArt(scene, { indices = true } = {}) {
try {
if (document.fonts?.load) {
await Promise.race([
Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"')]),
new Promise((res) => setTimeout(res, 1200)),
]);
}
} catch (_) { /* fall back to Georgia */ }
if (!baked || !scene.textures.exists('mj-room')) {
bakeRoom(scene); bakeTable(scene); bakeLight(scene); bakeBits(scene); bakeStand(scene);
baked = true;
}
bakeTiles(scene, { indices });
}
// Frame for a tile in a pose.
export function flatFrame(r, kind, faceUp) {
const key = r % 2 ? 'mj-flat-l' : 'mj-flat-p';
return { key, frame: faceUp ? `${r}-${kind}` : 'back' };
}

View File

@ -56,63 +56,92 @@ export const TILES = (() => {
return t;
})();
// Full 144-tile wall: 4 copies of each playing tile, 1 of each bonus tile.
export function buildWall() {
// Full wall: 4 copies of each playing tile, plus 1 of each bonus tile when
// flowers & seasons are in play (144 tiles; 136 without them).
export function buildWall(bonusTiles = true) {
const wall = [];
for (let k = 0; k < FIRST_BONUS; k++) wall.push(k, k, k, k);
for (let k = FIRST_BONUS; k < KIND_COUNT; k++) wall.push(k);
if (bonusTiles) for (let k = FIRST_BONUS; k < KIND_COUNT; k++) wall.push(k);
return wall;
}
// ── Scoring ──────────────────────────────────────────────────────────────────
// Classic HK Old Style faan values with a 1-faan minimum: a "chicken hand"
// (no faan at all) may not declare a win, but bonus-tile and contextual faan
// count toward the minimum, so hands stay fast. `excludes` lists faan ids the
// engine must NOT also award when this row applies (prevents double counting,
// e.g. Great Dragons already contains its three dragon pungs).
// ── House rules ──────────────────────────────────────────────────────────────
// rounds: 1 = East round only, 2 = East + South, 4 = all four winds.
// minFaan: the smallest hand that may declare a win. faanCap: the limit (a
// limit hand scores exactly this). stake: everyone's opening score.
export const DEFAULT_OPTS = {
rounds: 1, minFaan: 1, faanCap: 13, robKong: true, bonusTiles: true, stake: 500,
};
export function normalizeOpts(o = {}) {
const r = { ...DEFAULT_OPTS, ...o };
r.rounds = [1, 2, 4].includes(r.rounds) ? r.rounds : 1;
r.minFaan = Math.max(0, Math.min(5, r.minFaan | 0));
r.faanCap = [8, 10, 13].includes(r.faanCap) ? r.faanCap : 13;
r.robKong = !!r.robKong;
r.bonusTiles = !!r.bonusTiles;
r.stake = Math.max(0, r.stake | 0);
return r;
}
export const MIN_FAAN = 1;
export const LIMIT_FAAN = 13;
// ── Scoring ──────────────────────────────────────────────────────────────────
// Classic HK Old Style faan values. A hand must reach the table's minimum
// (1 faan by default) to win; bonus-tile and contextual faan count toward it.
// `excludes` lists faan ids the engine must NOT also award when this row
// applies (prevents double counting, e.g. Great Dragons already contains its
// three dragon pungs). `limit` rows are worth the table's faan cap and
// replace every other row (a limit hand is scored as the limit alone).
// `group` orders the in-game reference panel.
export const MIN_FAAN = 1; // default table minimum (see DEFAULT_OPTS)
export const LIMIT_FAAN = 13; // the largest cap; BASE_POINTS covers 0..13
export const FAAN_TABLE = [
// hand patterns
{ id: 'common-hand', label: 'Common Hand', faan: 1, desc: 'Four chows and a pair of suited tiles' },
{ id: 'all-pungs', label: 'All Pungs', faan: 3, desc: 'Four pungs or kongs and a pair' },
{ id: 'mixed-one-suit', label: 'Mixed One Suit', faan: 3, desc: 'One suit plus honor tiles only' },
{ id: 'pure-one-suit', label: 'Pure One Suit', faan: 6, desc: 'One suit only, no honors',
{ id: 'common-hand', group: 'pattern', label: 'Common Hand', faan: 1, desc: 'Four chows and a pair of suited tiles' },
{ id: 'all-pungs', group: 'pattern', label: 'All Pungs', faan: 3, desc: 'Four pungs or kongs and a pair' },
{ id: 'mixed-one-suit', group: 'pattern', label: 'Mixed One Suit', faan: 3, desc: 'One suit plus honor tiles only' },
{ id: 'pure-one-suit', group: 'pattern', label: 'Pure One Suit', faan: 6, desc: 'One suit only, no honors',
excludes: ['mixed-one-suit'] },
{ id: 'small-dragons', label: 'Small Dragons', faan: 5, desc: 'Two dragon pungs and a dragon pair',
{ id: 'mixed-terminals', group: 'pattern', label: 'Mixed Terminals', faan: 1, desc: 'Only 1s, 9s and honors, all in pungs' },
{ id: 'small-dragons', group: 'pattern', label: 'Small Dragons', faan: 5, desc: 'Two dragon pungs and a dragon pair',
excludes: ['dragon-pung'] },
{ id: 'great-dragons', label: 'Great Dragons', faan: 8, desc: 'All three dragon pungs',
{ id: 'great-dragons', group: 'pattern', label: 'Great Dragons', faan: 8, desc: 'All three dragon pungs',
excludes: ['dragon-pung', 'small-dragons'] },
{ id: 'small-winds', label: 'Small Winds', faan: 6, desc: 'Three wind pungs and a wind pair',
{ id: 'small-winds', group: 'pattern', label: 'Small Winds', faan: 6, desc: 'Three wind pungs and a wind pair',
excludes: ['seat-wind', 'round-wind'] },
{ id: 'great-winds', label: 'Great Winds', faan: 13, desc: 'All four wind pungs',
excludes: ['seat-wind', 'round-wind', 'small-winds', 'all-pungs'] },
{ id: 'all-honors', label: 'All Honors', faan: 13, desc: 'Winds and dragons only',
excludes: ['all-pungs', 'mixed-one-suit'] },
{ id: 'thirteen-orphans', label: 'Thirteen Orphans', faan: 13, desc: 'One of every 1, 9 and honor, plus a duplicate' },
// limit hands
{ id: 'great-winds', group: 'limit', limit: true, label: 'Great Winds', faan: 13, desc: 'All four wind pungs' },
{ id: 'all-honors', group: 'limit', limit: true, label: 'All Honors', faan: 13, desc: 'Winds and dragons only' },
{ id: 'thirteen-orphans', group: 'limit', limit: true, label: 'Thirteen Orphans', faan: 13, desc: 'One of every 1, 9 and honor, plus a duplicate' },
{ id: 'nine-gates', group: 'limit', limit: true, label: 'Nine Gates', faan: 13, desc: 'Concealed 1112345678999 of one suit + one more of it' },
{ id: 'all-terminals', group: 'limit', limit: true, label: 'All Terminals', faan: 13, desc: 'Pungs and a pair of 1s and 9s only' },
{ id: 'four-kongs', group: 'limit', limit: true, label: 'Four Kongs', faan: 13, desc: 'Four kongs and a pair' },
{ id: 'four-concealed-pungs', group: 'limit', limit: true, label: 'Four Concealed Pungs', faan: 13, desc: 'Four pungs, none claimed from a discard' },
{ id: 'heavenly-hand', group: 'limit', limit: true, label: 'Heavenly Hand', faan: 13, desc: 'Dealer wins with the opening deal' },
{ id: 'earthly-hand', group: 'limit', limit: true, label: 'Earthly Hand', faan: 13, desc: "Win on the dealer's very first discard" },
// per-meld faan
{ id: 'dragon-pung', label: 'Dragon Pung', faan: 1, desc: 'Each pung or kong of a dragon' },
{ id: 'seat-wind', label: 'Seat Wind Pung', faan: 1, desc: 'Pung or kong of your seat wind' },
{ id: 'round-wind', label: 'Round Wind Pung', faan: 1, desc: 'Pung or kong of East, the round wind' },
{ id: 'dragon-pung', group: 'meld', label: 'Dragon Pung', faan: 1, desc: 'Each pung or kong of a dragon' },
{ id: 'seat-wind', group: 'meld', label: 'Seat Wind Pung', faan: 1, desc: 'Pung or kong of your seat wind' },
{ id: 'round-wind', group: 'meld', label: 'Round Wind Pung', faan: 1, desc: 'Pung or kong of the prevailing wind' },
// win context
{ id: 'self-draw', label: 'Self Draw', faan: 1, desc: 'Winning tile drawn from the wall' },
{ id: 'concealed', label: 'Concealed Hand', faan: 1, desc: 'No melds claimed from discards' },
{ id: 'last-tile', label: 'Last Wall Tile', faan: 1, desc: 'Win on the very last wall tile' },
{ id: 'kong-draw', label: 'Kong Replacement', faan: 1, desc: 'Win on the tile drawn after a kong' },
{ id: 'self-draw', group: 'context', label: 'Self Draw', faan: 1, desc: 'Winning tile drawn from the wall' },
{ id: 'concealed', group: 'context', label: 'Concealed Hand', faan: 1, desc: 'No melds claimed from discards' },
{ id: 'last-tile', group: 'context', label: 'Last Wall Tile', faan: 1, desc: 'Win on the very last wall tile' },
{ id: 'last-discard', group: 'context', label: 'Last Discard', faan: 1, desc: 'Win on the discard after the wall runs out' },
{ id: 'kong-draw', group: 'context', label: 'Kong Replacement', faan: 1, desc: 'Win on the tile drawn after a kong' },
{ id: 'rob-kong', group: 'context', label: 'Robbing the Kong', faan: 1, desc: "Win on the tile another player adds to a pung" },
// bonus tiles
{ id: 'seat-flower', label: 'Own Flower / Season', faan: 1, desc: 'Each flower or season matching your seat' },
{ id: 'flower-set', label: 'All Four Flowers', faan: 2, desc: 'The complete flower set' },
{ id: 'season-set', label: 'All Four Seasons', faan: 2, desc: 'The complete season set' },
{ id: 'no-bonus', label: 'No Bonus Tiles', faan: 1, desc: 'Hand finished with no flowers or seasons' },
{ id: 'seat-flower', group: 'bonus', label: 'Own Flower / Season', faan: 1, desc: 'Each flower or season matching your seat' },
{ id: 'flower-set', group: 'bonus', label: 'All Four Flowers', faan: 2, desc: 'The complete flower set' },
{ id: 'season-set', group: 'bonus', label: 'All Four Seasons', faan: 2, desc: 'The complete season set' },
{ id: 'no-bonus', group: 'bonus', label: 'No Bonus Tiles', faan: 1, desc: 'Hand finished with no flowers or seasons' },
];
export const FAAN_BY_ID = Object.fromEntries(FAAN_TABLE.map((r) => [r.id, r]));
// Base points per faan (half-doubling ladder, capped at the 13-faan limit).
// Base points per faan (half-doubling ladder; the cap's value is the limit).
export const BASE_POINTS = [1, 2, 4, 8, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384];
export const basePoints = (faan) => BASE_POINTS[Math.min(faan, LIMIT_FAAN)];
export const basePoints = (faan, cap = LIMIT_FAAN) => BASE_POINTS[Math.min(faan, cap, LIMIT_FAAN)];
// Payments: winner by discard collects 2× base from the discarder alone;
// a self-drawn winner collects 1× base from each of the three others.

View File

@ -0,0 +1,232 @@
// MahjongDialogs.js — lacquer-and-gold pop-ups: the menu (table settings +
// house rules), the helpers board, confirmations, first-time tips, and the
// scoring slip shown at the end of every hand. 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, LABEL_FONT, SERIF, SEAT, panelKey, PANEL_PAD } from './MahjongArt.js';
import { TILES, WIND_NAMES } from './MahjongData.js';
const GOLD = '#f0c25a', INK = '#f4e6c8', MUTED = '#c9b08a';
export function frame(scene, x, y, w, h, depth, opts) {
return scene.add.image(x - PANEL_PAD, y - PANEL_PAD, panelKey(scene, w, h, opts)).setOrigin(0).setDepth(depth);
}
export function blocker(scene, depth, alpha = 0.55) {
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x0a0402, alpha).setDepth(depth).setInteractive();
}
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');
// ── settings ─────────────────────────────────────────────────────────────────
export const HELPER_LIST = [
['ready', 'Ready indicator', 'Tells you when you are one tile from winning, which tiles you wait on and how many are left.'],
['names', 'Tile names on hover', 'Hover any tile on the table or in your rack to see its name.'],
['indices', 'Western corner numbers', 'Prints 1–9, E/S/W/N and R/G/Wh in the tile corners, like a beginner set.'],
['claimAdvice', 'Claim advisor', 'When you can call a discard, a ★ marks the call a strong player would make, with the reason.'],
['discardAdvice', 'Discard advisor', 'Green edges on your best discards; hover a tile to see how far from ready it leaves you.'],
['tracker', 'Tile tracker', 'A board of every tile showing how many copies are still unseen.'],
['danger', 'Danger shading', 'Red edges on tiles likely to hand someone a win; grey on tiles that are completely safe.'],
['compass', 'Hand compass', 'Which scoring patterns your hand is heading toward, and the faan you have banked.'],
['reads', 'Opponent reads', 'What each opponent seems to be collecting and how close they look.'],
['log', 'Table log', 'A running list of draws, calls and discards.'],
['tips', 'First-time tips', 'Short explanations the first time something new happens.'],
];
export const HELPER_PRESETS = {
learner: { ready: true, names: true, indices: true, claimAdvice: true, discardAdvice: false, tracker: false, danger: false, compass: false, reads: false, log: false, tips: true },
all: { ready: true, names: true, indices: true, claimAdvice: true, discardAdvice: true, tracker: true, danger: true, compass: true, reads: true, log: true, tips: true },
none: { ready: false, names: false, indices: false, claimAdvice: false, discardAdvice: false, tracker: false, danger: false, compass: false, reads: false, log: false, tips: false },
};
export function openHelpers(scene, { helpers, depth, onChange, onClose }) {
const objs = [blocker(scene, depth - 1, 0.45)];
const w = 980, h = 760;
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 + 44, 'Table Helpers', { fontFamily: DISPLAY_FONT, fontSize: '34px', color: GOLD }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 80, 'Turn on whatever helps — a real table has none of these, but every player started somewhere.', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: MUTED }).setOrigin(0.5).setDepth(depth + 1));
const btns = [];
HELPER_LIST.forEach(([k, label, desc], i) => {
const yy = y + 124 + i * 50;
const b = new Button(scene, x + 150, yy, `${onOff(helpers[k])}`, () => { onChange(k, !helpers[k]); b.setLabel(onOff(helpers[k])); }, { width: 90, height: 38, fontSize: 16, bg: 0x5a1a10 }).setDepth(depth + 2);
btns.push([k, b]);
objs.push(b);
objs.push(scene.add.text(x + 216, yy - 10, label, { fontFamily: DISPLAY_FONT, fontSize: '18px', color: INK }).setOrigin(0, 0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + 216, yy + 11, desc, { fontFamily: SERIF, fontSize: '13px', color: MUTED }).setOrigin(0, 0.5).setDepth(depth + 1));
});
const preset = (name) => {
for (const [k, v] of Object.entries(HELPER_PRESETS[name])) if (helpers[k] !== v) onChange(k, v);
btns.forEach(([k, b]) => b.setLabel(onOff(helpers[k])));
};
let hRef = null;
const by = y + h - 50;
[['Learner set', () => preset('learner')], ['Everything', () => preset('all')], ['Clean table', () => preset('none')], ['Done', () => hRef.close()]]
.forEach(([label, fn], i) => objs.push(new Button(scene, x + 140 + i * 233, by, label, fn, { width: 210, height: 46, fontSize: 17, bg: i === 3 ? 0x2e6a44 : 0x5a1a10 }).setDepth(depth + 2)));
hRef = handle(objs, onClose);
return hRef;
}
const PACE = { relaxed: 'Relaxed', normal: 'Normal', brisk: 'Brisk' };
const INTRO = { full: 'Full ritual', quick: 'Quick deal', off: 'Skip' };
const PROMPT = { all: 'Every call', noChow: 'Skip chows', winOnly: 'Mahjong only' };
const ROUNDS = { 1: 'East round', 2: 'East + South', 4: 'All four winds' };
export function openMenu(scene, { settings, depth, onChange, onRules, onNewGame, onLeave, onClose }) {
const objs = [blocker(scene, depth - 1, 0.5)];
const w = 1100, h = 800;
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 + 46, 'The Parlour', { fontFamily: DISPLAY_FONT, fontSize: '36px', color: GOLD }).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 = [
['AT THE TABLE', null],
[() => `Opponent pace: ${PACE[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'brisk'])],
[() => `Shuffle & deal: ${INTRO[settings.intro]}`, () => cycle('intro', ['full', 'quick', 'off'])],
[() => `Stop for my calls: ${PROMPT[settings.claimPrompt]}`, () => cycle('claimPrompt', ['all', 'noChow', 'winOnly'])],
[() => `Call timer: ${settings.claimTimer ? `${settings.claimTimer} s` : 'Off'}`, () => cycle('claimTimer', [0, 8, 15])],
[() => `Auto-sort my rack: ${onOff(settings.autoSort)}`, () => onChange('autoSort', !settings.autoSort)],
[() => `Show every hand at the end: ${onOff(settings.revealHands)}`, () => onChange('revealHands', !settings.revealHands)],
[() => `Opponent chatter & tells: ${onOff(settings.tells)}`, () => onChange('tells', !settings.tells)],
[() => `Rain on the window: ${onOff(settings.rain)}`, () => onChange('rain', !settings.rain)],
[() => `Parlour murmur: ${onOff(settings.murmur)}`, () => onChange('murmur', !settings.murmur)],
];
const right = [
['HOUSE RULES (next game)', null],
[() => `Session: ${ROUNDS[settings.rounds]}`, () => cycle('rounds', [1, 2, 4])],
[() => `Minimum to win: ${settings.minFaan} faan`, () => cycle('minFaan', [1, 3, 0])],
[() => `Limit hand: ${settings.faanCap} faan`, () => cycle('faanCap', [13, 10, 8])],
[() => `Robbing the kong: ${onOff(settings.robKong)}`, () => onChange('robKong', !settings.robKong)],
[() => `Flowers & seasons: ${onOff(settings.bonusTiles)}`, () => onChange('bonusTiles', !settings.bonusTiles)],
[() => `Starting stake: ${settings.stake || 'none (net score)'}`, () => cycle('stake', [500, 1000, 0])],
];
const col = (rows, cx) => rows.forEach(([label, fn], i) => {
const yy = y + 116 + i * 56;
if (!fn) { objs.push(scene.add.text(cx, yy, label, { fontFamily: LABEL_FONT, fontSize: '15px', color: GOLD }).setOrigin(0.5).setDepth(depth + 1)); return; }
const btn = new Button(scene, cx, yy, label(), () => { fn(); btn.setLabel(label()); }, { width: 470, height: 44, fontSize: 16, bg: 0x4a1a10 }).setDepth(depth + 2);
objs.push(btn);
});
col(left, x + 290);
col(right, x + w - 290);
objs.push(scene.add.text(x + w - 290, y + 116 + 7 * 56 + 10, 'House rules start with your next game.\nMinimum 3 faan is a common club rule —\nhands are bigger and slower.', {
fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: MUTED, align: 'center',
}).setOrigin(0.5, 0).setDepth(depth + 1));
const by = y + h - 96;
[
['Resume', () => hRef.close(), 0x2e6a44],
['How to Play', () => onRules(), 0x2f5f9a],
['New Game', () => { hRef.close(); onNewGame(); }, 0x7a4a14],
['Leave Table', () => { hRef.close(); onLeave(); }, 0x8a2414],
].forEach(([label, fn, bg], i) => objs.push(new Button(scene, x + 160 + i * 260, by, label, fn, { width: 236, height: 50, fontSize: 18, bg }).setDepth(depth + 2)));
objs.push(scene.add.text(x + w / 2, y + h - 40, 'Keys: click a tile to pick, click again (or double-click / drag up) to discard · ←/→ choose · Enter discard · M/K/P/C calls · Space pass · H hint · S sort · Z undo · Esc menu', {
fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: MUTED, align: 'center', wordWrap: { width: w - 80 },
}).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 = 580, h = 290;
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 + 56, heading, { fontFamily: DISPLAY_FONT, fontSize: '28px', color: GOLD }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 126, text, { fontFamily: SERIF, fontSize: '18px', color: INK, align: 'center', wordWrap: { width: w - 90 } }).setOrigin(0.5).setDepth(depth + 1));
let hRef = null;
objs.push(new Button(scene, x + w / 2 - 125, y + h - 60, yes, () => { hRef.close(); onYes?.(); }, { width: 220, height: 46, fontSize: 18, bg: 0x8a2414 }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 125, y + h - 60, no, () => { hRef.close(); onNo?.(); }, { width: 220, height: 46, fontSize: 18, bg: 0x2e6a44 }).setDepth(depth + 2));
hRef = handle(objs);
return hRef;
}
// A first-time tip: a small card above your rack with a "Got it".
export function tipCard(scene, { title, text, depth, onClose }) {
const objs = [];
const w = 620, h = 150;
const x = GAME_WIDTH / 2 - w / 2, y = 690;
objs.push(frame(scene, x, y, w, h, depth, { tint: '#123a28' }));
objs.push(scene.add.text(x + 22, y + 26, title, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: GOLD }).setOrigin(0, 0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + 22, y + 50, text, { fontFamily: SERIF, fontSize: '15px', color: INK, wordWrap: { width: w - 44 }, lineSpacing: 2 }).setOrigin(0, 0).setDepth(depth + 1));
let hRef = null;
objs.push(new Button(scene, x + w - 76, y + h - 26, 'Got it', () => hRef.close(), { width: 120, height: 34, fontSize: 15, bg: 0x2e6a44 }).setDepth(depth + 2));
objs.forEach((o) => { o.setAlpha?.(0); scene.tweens.add({ targets: o, alpha: 1, duration: 200 }); });
hRef = handle(objs, onClose);
return hRef;
}
// ── the scoring slip ─────────────────────────────────────────────────────────
// Rows tick in one by one; payments roll on the seat panels (the scene
// passes onPayments). Returns { close, hide(bool) }.
export function openHandSlip(scene, { gs, names, depth, last, onPayments, onNext, sound }) {
const r = gs.result;
const objs = [];
const isDraw = r.type === 'draw';
const rows = isDraw ? [] : r.faanList;
const w = 720;
const h = isDraw ? 270 : Math.min(640, 300 + rows.length * 30 + 4 * 30);
const x = GAME_WIDTH / 2 - w / 2, y = Math.max(150, 470 - h / 2);
const ctr = scene.add.container(0, 0).setDepth(depth);
const add = (o) => { ctr.add(o); return o; };
add(scene.add.image(x - PANEL_PAD, y - PANEL_PAD, panelKey(scene, w, h, { tint: '#26100a' })).setOrigin(0));
const timers = [];
const later = (ms, fn) => timers.push(scene.time.delayedCall(ms, fn));
if (isDraw) {
add(scene.add.text(x + w / 2, y + 60, 'Wall exhausted', { fontFamily: DISPLAY_FONT, fontSize: '36px', color: GOLD }).setOrigin(0.5));
add(scene.add.text(x + w / 2, y + 112, 'Nobody went out. No points change hands —\nthe dealer keeps the deal.', { fontFamily: SERIF, fontSize: '19px', color: INK, align: 'center' }).setOrigin(0.5, 0));
} else {
const who = r.winner === 0 ? 'You win!' : `${names[r.winner]} wins!`;
add(scene.add.text(x + w / 2, y + 44, who, { fontFamily: DISPLAY_FONT, fontSize: '38px', color: SEAT[r.winner].ink }).setOrigin(0.5));
const how = r.rob ? `robbing ${r.discarder === 0 ? 'your' : `${names[r.discarder]}'s`} kong of the ${TILES[r.winTile].name}`
: r.byDiscard ? `on ${r.discarder === 0 ? 'your' : `${names[r.discarder]}'s`} discard: the ${TILES[r.winTile].name}`
: `self-drawn: the ${TILES[r.winTile].name}`;
add(scene.add.text(x + w / 2, y + 84, how, { fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: MUTED }).setOrigin(0.5));
let yy = y + 124;
rows.forEach((row, i) => {
const a = add(scene.add.text(x + 70, yy, row.label, { fontFamily: SERIF, fontSize: '19px', color: INK }).setOrigin(0, 0.5).setAlpha(0));
const b = add(scene.add.text(x + w - 70, yy, row.limit ? `LIMIT ${row.faan}` : `${row.faan} faan`, { fontFamily: DISPLAY_FONT, fontSize: '19px', color: GOLD }).setOrigin(1, 0.5).setAlpha(0));
later(280 + i * 260, () => { scene.tweens.add({ targets: [a, b], alpha: 1, duration: 180 }); sound?.('row'); });
yy += 30;
});
const t0 = 280 + rows.length * 260 + 200;
yy += 8;
const g = add(scene.add.graphics());
g.lineStyle(2, 0xd9a441, 0.6).lineBetween(x + 60, yy - 14, x + w - 60, yy - 14);
const tot = add(scene.add.text(x + 70, yy + 6, `Total ${r.faan} faan → ${r.base} base points`, { fontFamily: DISPLAY_FONT, fontSize: '24px', color: GOLD }).setOrigin(0, 0.5).setAlpha(0));
later(t0, () => { scene.tweens.add({ targets: tot, alpha: 1, duration: 220 }); sound?.('total'); });
yy += 46;
const pays = [0, 1, 2, 3].filter((s) => r.payments[s] !== 0);
pays.forEach((s, i) => {
const d = r.payments[s];
const a = add(scene.add.text(x + 70, yy, s === 0 ? 'You' : names[s], { fontFamily: SERIF, fontSize: '19px', color: SEAT[s].ink }).setOrigin(0, 0.5).setAlpha(0));
const b = add(scene.add.text(x + w - 70, yy, d > 0 ? `+${d}` : String(d), { fontFamily: DISPLAY_FONT, fontSize: '21px', color: d > 0 ? GOLD : '#ff8a7a' }).setOrigin(1, 0.5).setAlpha(0));
later(t0 + 300 + i * 120, () => scene.tweens.add({ targets: [a, b], alpha: 1, duration: 180 }));
yy += 30;
});
later(t0 + 360, () => onPayments?.());
}
const btnY = y + h - 40;
const next = new Button(scene, x + w / 2 + 120, btnY, last ? 'Final Scores' : 'Next Hand', () => onNext(), { width: 220, height: 48, fontSize: 19, bg: 0x2e6a44 });
add(next);
let hidden = false;
const peek = new Button(scene, x + w / 2 - 120, btnY, 'Look at the table', () => setHidden(true), { width: 220, height: 48, fontSize: 17, bg: 0x4a1a10 });
add(peek);
const show = new Button(scene, GAME_WIDTH / 2, 120, 'Show the score slip', () => setHidden(false), { width: 300, height: 48, fontSize: 18, bg: 0x2e6a44 }).setDepth(depth).setVisible(false);
objs.push(show);
function setHidden(v) {
hidden = v;
ctr.setVisible(!v);
show.setVisible(v);
}
ctr.setAlpha(0);
scene.tweens.add({ targets: ctr, alpha: 1, duration: 220 });
return {
close() { timers.forEach((t) => t.remove(false)); ctr.destroy(true); objs.forEach((o) => o.destroy()); },
get hidden() { return hidden; },
};
}
export function windName(i) { return WIND_NAMES[i % 4]; }

View File

@ -0,0 +1,107 @@
// MahjongEndScreen.js — the session's reckoning on a lacquer board: places,
// a hand-by-hand sheet, everyone's stats, and a chart of running scores.
import { Button } from '../../ui/Button.js';
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { DISPLAY_FONT, LABEL_FONT, SERIF, SEAT } from './MahjongArt.js';
import { frame } from './MahjongDialogs.js';
import { WIND_NAMES } from './MahjongData.js';
const GOLD = '#f0c25a', INK = '#f4e6c8', MUTED = '#c9b08a';
const PLACE = ['1st', '2nd', '3rd', '4th'];
export function openEndScreen(scene, { gs, names, depth, practice, onPlayAgain, onMenu }) {
const objs = [];
const w = 1480, h = 900;
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, 0x0a0402, 0.6).setDepth(depth - 1).setInteractive());
objs.push(frame(scene, x, y, w, h, depth));
const order = [0, 1, 2, 3].sort((a, b) => gs.players[b].score - gs.players[a].score);
const winners = gs.winners ?? [];
const youWon = winners.includes(0);
const head = youWon ? (winners.length > 1 ? 'A shared victory at the parlour!' : 'You leave the parlour on top!') : `${names[order[0]]} takes the evening`;
objs.push(scene.add.text(x + w / 2, y + 50, head, { fontFamily: DISPLAY_FONT, fontSize: '38px', color: youWon ? '#a6e2b8' : GOLD }).setOrigin(0.5).setDepth(depth + 1));
if (practice) objs.push(scene.add.text(x + w / 2, y + 86, 'Practice game (undo was used) — not recorded in your history.', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: MUTED }).setOrigin(0.5).setDepth(depth + 1));
// places
const stake = gs.opts.stake;
order.forEach((s, k) => {
const yy = y + 130 + k * 50;
const tie = k > 0 && gs.players[s].score === gs.players[order[k - 1]].score;
objs.push(scene.add.text(x + 50, yy, tie ? '=' : PLACE[k], { fontFamily: DISPLAY_FONT, fontSize: '26px', color: winners.includes(s) ? GOLD : MUTED }).setOrigin(0, 0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + 120, yy, s === 0 ? 'You' : names[s], { fontFamily: DISPLAY_FONT, fontSize: '28px', color: SEAT[s].ink }).setOrigin(0, 0.5).setDepth(depth + 1));
const net = gs.players[s].score - stake;
objs.push(scene.add.text(x + 470, yy, `${gs.players[s].score}`, { fontFamily: DISPLAY_FONT, fontSize: '28px', color: INK }).setOrigin(1, 0.5).setDepth(depth + 1));
if (stake) objs.push(scene.add.text(x + 480, yy, `(${net >= 0 ? '+' : ''}${net})`, { fontFamily: SERIF, fontSize: '16px', color: net >= 0 ? '#a6e2b8' : '#ff8a7a' }).setOrigin(0, 0.5).setDepth(depth + 1));
});
// stats
const stats = [
['Hands won', (st) => st.wins],
['…by self-draw', (st) => st.selfDraws],
['Dealt into a win', (st) => st.dealIns],
['Calls made', (st) => st.claims],
['Kongs', (st) => st.kongs],
['Flowers & seasons', (st) => st.flowers],
['Biggest hand (faan)', (st) => st.biggest],
];
const sx = x + 50, sy = y + 360;
order.forEach((s, k) => objs.push(scene.add.text(sx + 300 + k * 72, sy, (s === 0 ? 'YOU' : names[s].toUpperCase()).slice(0, 7), { fontFamily: LABEL_FONT, fontSize: '12px', color: SEAT[s].ink }).setOrigin(0.5).setDepth(depth + 1)));
stats.forEach(([label, fn], r) => {
const yy = sy + 30 + r * 30;
objs.push(scene.add.text(sx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: INK }).setOrigin(0, 0.5).setDepth(depth + 1));
order.forEach((s, k) => objs.push(scene.add.text(sx + 300 + k * 72, yy, String(fn(gs.stats[s])), { fontFamily: SERIF, fontSize: '16px', color: SEAT[s].ink }).setOrigin(0.5).setDepth(depth + 1)));
});
// hand-by-hand sheet
const hx = x + 640, hy = y + 120;
objs.push(scene.add.text(hx, hy, 'HAND BY HAND', { fontFamily: LABEL_FONT, fontSize: '14px', color: GOLD }).setOrigin(0, 0.5).setDepth(depth + 1));
const hist = gs.history;
const maxRows = 14;
const shown = hist.slice(-maxRows);
shown.forEach((hr, i) => {
const yy = hy + 28 + i * 24;
const wind = WIND_NAMES[hr.roundWind % 4][0];
let what;
if (hr.type === 'draw') what = 'wall exhausted';
else {
const who = hr.winner === 0 ? 'You' : names[hr.winner];
what = `${who} · ${hr.faan} faan · ${hr.byDiscard ? `off ${hr.discarder === 0 ? 'you' : names[hr.discarder]}` : 'self-drawn'}`;
}
objs.push(scene.add.text(hx, yy, `${wind}${hr.hand}`, { fontFamily: DISPLAY_FONT, fontSize: '14px', color: MUTED }).setOrigin(0, 0.5).setDepth(depth + 1));
objs.push(scene.add.text(hx + 50, yy, what, { fontFamily: SERIF, fontSize: '14px', color: hr.winner != null ? SEAT[hr.winner].ink : INK }).setOrigin(0, 0.5).setDepth(depth + 1));
});
if (hist.length > maxRows) objs.push(scene.add.text(hx, hy + 28 + maxRows * 24, `…and ${hist.length - maxRows} earlier hands`, { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: MUTED }).setOrigin(0, 0.5).setDepth(depth + 1));
// running totals chart
const cx0 = x + 1010, cy0 = y + 140, cw = 420, ch = 560;
const g = scene.add.graphics().setDepth(depth + 1);
objs.push(g);
g.fillStyle(0x000000, 0.25).fillRect(cx0, cy0, cw, ch);
const series = [0, 1, 2, 3].map((s) => [stake, ...hist.map((hr) => hr.scores[s])]);
const all = series.flat();
const lo = Math.min(...all), hi = Math.max(...all);
const span = Math.max(1, hi - lo);
const Y = (v) => cy0 + ch - ((v - lo) / span) * (ch - 20) - 10;
g.lineStyle(1, 0xd9a441, 0.25);
for (let k = 0; k <= 4; k++) g.lineBetween(cx0, cy0 + (ch * k) / 4, cx0 + cw, cy0 + (ch * k) / 4);
if (lo < stake && hi > stake) { g.lineStyle(1.5, 0xffffff, 0.35); g.lineBetween(cx0, Y(stake), cx0 + cw, Y(stake)); }
const steps = Math.max(1, hist.length);
for (let s = 0; s < 4; s++) {
g.lineStyle(3.5, SEAT[s].hex, 0.95);
g.beginPath();
series[s].forEach((v, k) => { const px = cx0 + (k / steps) * cw; if (k) g.lineTo(px, Y(v)); else g.moveTo(px, Y(v)); });
g.strokePath();
}
g.lineStyle(1.5, 0xd9a441, 0.7).strokeRect(cx0, cy0, cw, ch);
objs.push(scene.add.text(cx0 + cw / 2, cy0 - 18, 'Scores through the evening', { fontFamily: LABEL_FONT, fontSize: '13px', color: GOLD }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(cx0 - 8, cy0 + 10, String(hi), { fontFamily: SERIF, fontSize: '12px', color: MUTED }).setOrigin(1, 0.5).setDepth(depth + 1));
objs.push(scene.add.text(cx0 - 8, cy0 + ch - 10, String(lo), { fontFamily: SERIF, fontSize: '12px', color: MUTED }).setOrigin(1, 0.5).setDepth(depth + 1));
const by = y + h - 58;
objs.push(new Button(scene, x + w / 2 - 150, by, 'Play Again', () => { close(); onPlayAgain(); }, { width: 260, height: 52, fontSize: 20, bg: 0x2e6a44 }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 150, by, 'Leave Table', () => { close(); onMenu(); }, { width: 260, height: 52, fontSize: 20, bg: 0x8a2414 }).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

View File

@ -0,0 +1,456 @@
// MahjongHud.js — everything around the table: the four seat panels
// (portrait, wind disc, dealer block, score, turn glow, speech bubbles), the
// round card, the coach pill above your rack, call stamps on the felt, the
// helper cards (tile tracker, hand compass + opponent reads, table log), the
// action dock, and the slide-in "Winning Hands" reference.
import { Button } from '../../ui/Button.js';
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
import { GAME_HEIGHT } from '../../config.js';
import { WIND_NAMES, FAAN_TABLE } from './MahjongData.js';
import {
ROUND_CARD, LOG_CARD, TRACKER, SEAT_PANELS, TOP_BUTTONS, INFO_CARD, DOCK, COACH_PILL, REF_W, W, callSpot,
} from './MahjongLayout.js';
import { panelKey, PANEL_PAD, DISPLAY_FONT, LABEL_FONT, SERIF, SEAT } from './MahjongArt.js';
const WIND_LABEL = ['mahjong-pinyin4', 'mahjong-pinyin3', 'mahjong-pinyin6', 'mahjong-pinyin5'];
const GOLD = '#f0c25a';
const INK = '#f4e6c8';
const MUTED = '#c9b08a';
export function panel(scene, r, depth, opts) {
return scene.add.image(r.x - PANEL_PAD, r.y - PANEL_PAD, panelKey(scene, r.w, r.h, opts)).setOrigin(0).setDepth(depth);
}
export class Hud {
constructor(scene, depth, { names, skills, opponents, onButton, onCall }) {
this.scene = scene;
this.depth = depth;
this.names = names;
this.skills = skills;
this.opponents = opponents;
this.onButton = onButton;
this.onCall = onCall;
this.seats = [];
this.bubbles = {};
this.buttons = {};
this.calls = [];
this.helperObjs = {};
}
build() {
const s = this.scene, D = this.depth;
// round card
panel(s, ROUND_CARD, D);
this.roundDisc = s.add.image(ROUND_CARD.x + 58, ROUND_CARD.y + ROUND_CARD.h / 2, 'mj-disc').setScale(0.92).setDepth(D + 1);
this.roundGlyph = s.add.image(this.roundDisc.x, this.roundDisc.y, WIND_LABEL[0]).setScale(0.36).setDepth(D + 2);
this.roundTitle = s.add.text(ROUND_CARD.x + 116, ROUND_CARD.y + 30, '', { fontFamily: DISPLAY_FONT, fontSize: '26px', color: GOLD }).setOrigin(0, 0.5).setDepth(D + 1);
this.roundSub = s.add.text(ROUND_CARD.x + 116, ROUND_CARD.y + 64, '', { fontFamily: SERIF, fontSize: '16px', color: INK }).setOrigin(0, 0.5).setDepth(D + 1);
this.roundRules = s.add.text(ROUND_CARD.x + 116, ROUND_CARD.y + 94, '', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: MUTED }).setOrigin(0, 0.5).setDepth(D + 1);
// seat panels
for (let seat = 0; seat < 4; seat++) {
const r = SEAT_PANELS[seat];
const col = SEAT[seat];
const glow = s.add.graphics().setDepth(D - 1);
panel(s, r, D);
const px = r.x + 64, py = r.y + (seat === 0 ? 72 : r.h / 2 - (seat === 2 ? 0 : 6));
const pr = seat === 0 ? 46 : 40;
s.add.circle(px, py, pr + 5, col.hex).setDepth(D + 1);
const portrait = seat === 0
? createPlayerPortrait(s, px, py, pr, D + 2, 'MahjongGame')
: createOpponentPortrait(s, this.opponents[seat] ?? { id: 'bot', spriteIndex: 0 }, px, py, pr, D + 2);
const name = seat === 0 ? 'You' : (this.names[seat].length > 14 ? `${this.names[seat].slice(0, 13)}…` : this.names[seat]);
const nx = r.x + 124;
s.add.text(nx, r.y + 30, name, { fontFamily: DISPLAY_FONT, fontSize: '24px', color: col.ink }).setOrigin(0, 0.5).setDepth(D + 1);
if (seat !== 0) {
const k = this.skills[seat] ?? 3;
s.add.text(nx, r.y + 56, `${'●'.repeat(k)}${'○'.repeat(5 - k)} skill`, { fontFamily: SERIF, fontSize: '13px', color: MUTED }).setOrigin(0, 0.5).setDepth(D + 1);
}
const score = s.add.text(nx, r.y + (seat === 2 ? 92 : 96), '', { fontFamily: DISPLAY_FONT, fontSize: '30px', color: INK }).setOrigin(0, 0.5).setDepth(D + 1);
const delta = s.add.text(nx + 110, r.y + (seat === 2 ? 92 : 96), '', { fontFamily: DISPLAY_FONT, fontSize: '22px', color: GOLD }).setOrigin(0, 0.5).setDepth(D + 1).setAlpha(0);
const dx = r.x + r.w - 46, dy = r.y + 40;
const disc = s.add.image(dx, dy, 'mj-disc').setScale(0.6).setDepth(D + 1);
const glyph = s.add.image(dx, dy, WIND_LABEL[0]).setScale(0.23).setDepth(D + 2);
const windTxt = s.add.text(dx, dy + 38, '', { fontFamily: LABEL_FONT, fontSize: '12px', color: MUTED }).setOrigin(0.5).setDepth(D + 1);
const dealer = s.add.image(dx - 64, dy, 'mj-dealer').setScale(0.5).setDepth(D + 1).setVisible(false);
// the dealer is always East: an East glyph on the red block
const dealerTxt = s.add.image(dx - 66, dy - 2, WIND_LABEL[0]).setScale(0.13).setTint(0xffe7a0).setDepth(D + 2).setVisible(false);
const extra = s.add.text(r.x + r.w - 16, r.y + r.h - 20, '', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: MUTED }).setOrigin(1, 0.5).setDepth(D + 1);
this.seats.push({ r, col, glow, portrait, score, delta, disc, glyph, windTxt, dealer, dealerTxt, extra, px, py, pr, shown: null });
}
// top-right buttons
const tb = TOP_BUTTONS;
const mk = (k, label, x, w, bg = 0x5a1a10) => {
this.buttons[k] = new Button(s, x, tb.y + tb.h / 2, label, () => this.onButton(k), { width: w, height: 46, fontSize: 17, bg }).setDepth(D + 3);
};
mk('hands', 'Hands', tb.x + 66, 128);
mk('helpers', 'Helpers', tb.x + 202, 128);
mk('menu', 'Menu', tb.x + 338, 128);
// dock
panel(s, DOCK, D);
this.dockTitle = s.add.text(DOCK.x + DOCK.w / 2, DOCK.y + 22, '', { fontFamily: LABEL_FONT, fontSize: '14px', color: MUTED }).setOrigin(0.5).setDepth(D + 1);
const by = DOCK.y + DOCK.h - 34;
const small = (k, label, x) => {
this.buttons[k] = new Button(s, x, by, label, () => this.onButton(k), { width: 118, height: 44, fontSize: 15, bg: 0x3a1a10 }).setDepth(D + 3);
};
small('hint', 'Hint (H)', DOCK.x + 72);
small('sort', 'Sort (S)', DOCK.x + 202);
small('undo', 'Undo (Z)', DOCK.x + 332);
this.timerBar = s.add.graphics().setDepth(D + 4);
// coach pill
this.pill = s.add.container(COACH_PILL.x, COACH_PILL.y).setDepth(D + 6).setAlpha(0);
this.pillBg = s.add.graphics();
this.pillText = s.add.text(0, 0, '', { fontFamily: SERIF, fontSize: '18px', color: INK, align: 'center' }).setOrigin(0.5);
this.pillIcons = s.add.container(0, 0);
this.pill.add([this.pillBg, this.pillText, this.pillIcons]);
// reference panel
this.buildReference();
return this;
}
// ── round / seats ───────────────────────────────────────────────────────────
refresh(gs, { turn = gs.turn, wallLeft = 0, active = true } = {}) {
const rw = gs.roundWind % 4;
this.roundGlyph.setTexture(WIND_LABEL[rw]);
this.roundTitle.setText(`${WIND_NAMES[rw]} Round · Hand ${gs.handNumber}`);
const dealerName = gs.dealer === 0 ? 'you' : this.names[gs.dealer];
this.roundSub.setText(`Dealer: ${dealerName} · Wall: ${wallLeft} tile${wallLeft === 1 ? '' : 's'}`);
const o = gs.opts;
const rounds = o.rounds === 1 ? 'East round' : o.rounds === 2 ? 'East + South' : 'Four winds';
this.roundRules.setText(`${rounds} · min ${o.minFaan} faan · limit ${o.faanCap}${o.robKong ? ' · rob the kong' : ''}`);
for (let seat = 0; seat < 4; seat++) {
const st = this.seats[seat];
const p = gs.players[seat];
const sw = (seat - gs.dealer + 4) % 4;
st.glyph.setTexture(WIND_LABEL[sw]);
st.windTxt.setText(WIND_NAMES[sw]);
st.dealer.setVisible(gs.dealer === seat);
st.dealerTxt.setVisible(gs.dealer === seat);
if (st.shown == null) { st.shown = p.score; st.score.setText(String(p.score)); }
st.glow.clear();
if (active && turn === seat && gs.phase !== 'handOver' && gs.phase !== 'gameOver') {
const r = st.r;
st.glow.fillStyle(st.col.hex, 0.28).fillRoundedRect(r.x - 10, r.y - 10, r.w + 20, r.h + 20, 18);
st.glow.lineStyle(4, st.col.light, 1).strokeRoundedRect(r.x - 6, r.y - 6, r.w + 12, r.h + 12, 16);
}
const n = p.bonus.length;
st.extra.setText(n ? `${n} flower${n === 1 ? '' : 's'}` : '');
}
}
// Roll a score from its shown value to the engine's, with a +/− flash.
rollScore(seat, to, dur = 900) {
const st = this.seats[seat];
const from = st.shown ?? to;
const d = to - from;
st.shown = to;
if (!d) { st.score.setText(String(to)); return; }
const c = { v: from };
this.scene.tweens.add({ targets: c, v: to, duration: dur, ease: 'Cubic.Out', onUpdate: () => st.score.setText(String(Math.round(c.v))) });
st.delta.setText(d > 0 ? `+${d}` : `${d}`).setColor(d > 0 ? GOLD : '#ff8a7a').setAlpha(1).setY(st.score.y);
this.scene.tweens.add({ targets: st.delta, alpha: 0, y: st.score.y - 22, delay: 1600, duration: 700 });
}
setScoreNow(seat, v) { const st = this.seats[seat]; st.shown = v; st.score.setText(String(v)); }
seatCenter(seat) { const st = this.seats[seat]; return { x: st.px, y: st.py }; }
// ── speech ──────────────────────────────────────────────────────────────────
say(seat, text, dur = 2200) {
const st = this.seats[seat];
if (!st || seat === 0) return;
const s = this.scene;
this.bubbles[seat]?.destroy();
const r = st.r;
const bw = 240, bh = 54;
let bx, by, tail;
if (seat === 1) { bx = r.x - bw - 18; by = r.y + 20; tail = 'right'; }
else if (seat === 3) { bx = r.x + r.w + 18; by = r.y + 20; tail = 'left'; }
else { bx = r.x - bw - 18; by = r.y + 30; tail = 'right'; }
const g = s.add.graphics();
g.fillStyle(0x000000, 0.3).fillRoundedRect(bx + 3, by + 5, bw, bh, 14);
g.fillStyle(0xfdf6e6, 1).fillRoundedRect(bx, by, bw, bh, 14);
g.lineStyle(2.5, st.col.hex, 1).strokeRoundedRect(bx, by, bw, bh, 14);
g.fillStyle(0xfdf6e6, 1);
if (tail === 'right') g.fillTriangle(bx + bw - 1, by + 16, bx + bw - 1, by + 36, bx + bw + 16, by + 22);
else g.fillTriangle(bx + 1, by + 16, bx + 1, by + 36, bx - 16, by + 22);
const t = s.add.text(bx + bw / 2, by + bh / 2, text, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#2a1408', align: 'center', wordWrap: { width: bw - 22 } }).setOrigin(0.5);
const cont = s.add.container(0, 0, [g, t]).setDepth(this.depth + 30).setAlpha(0);
this.bubbles[seat] = cont;
s.tweens.add({ targets: cont, alpha: 1, duration: 140 });
s.tweens.add({ targets: cont, alpha: 0, delay: dur, duration: 300, onComplete: () => { cont.destroy(); if (this.bubbles[seat] === cont) delete this.bubbles[seat]; } });
}
// A call stamped onto the felt in front of the caller.
stamp(seat, text, { color = 0xb8281c, big = false } = {}) {
const s = this.scene;
const p = callSpot(seat);
const t = s.add.text(0, 0, text, { fontFamily: DISPLAY_FONT, fontSize: big ? '64px' : '46px', color: '#ffe7a0', stroke: '#3a0c06', strokeThickness: 8 }).setOrigin(0.5);
const w = t.width + 50, h = t.height + 18;
const g = s.add.graphics();
g.fillStyle(0x000000, 0.35).fillRoundedRect(-w / 2 + 4, -h / 2 + 6, w, h, 14);
g.fillStyle(color, 0.95).fillRoundedRect(-w / 2, -h / 2, w, h, 14);
g.lineStyle(3, 0xf0c25a, 1).strokeRoundedRect(-w / 2 + 4, -h / 2 + 4, w - 8, h - 8, 10);
const c = s.add.container(p.x, p.y, [g, t]).setDepth(this.depth + 28).setScale(1.8).setAlpha(0).setAngle(seat % 2 ? 0 : -4);
s.tweens.add({ targets: c, scale: 1, alpha: 1, duration: 220, ease: 'Back.Out' });
s.tweens.add({ targets: c, alpha: 0, y: p.y - 30, delay: big ? 1500 : 900, duration: 320, onComplete: () => c.destroy() });
return c;
}
emotion(seat, e) { this.seats[seat]?.portrait?.playEmotion?.(e); }
hidePortraits() { this.seats.forEach((st) => st.portrait?.setVideoVisible?.(false)); }
showPortraits() { this.seats.forEach((st) => st.portrait?.setVideoVisible?.(true)); }
// ── coach pill ──────────────────────────────────────────────────────────────
// icons: [{ kind, n }] small tiles with a count, drawn after the text.
setPill(text, { icons = [], tone = 'info' } = {}) {
const s = this.scene;
this.pillIcons.removeAll(true);
if (!text) { s.tweens.add({ targets: this.pill, alpha: 0, duration: 160 }); this.pillKey = ''; return; }
const key = text + icons.map((i) => `${i.kind}:${i.n}:${i.dim}`).join(',') + tone;
if (key === this.pillKey) return;
this.pillKey = key;
this.pillText.setText(text);
const iconW = 34;
const iw = icons.length ? icons.length * iconW + 12 : 0;
if (this.pillText.width > COACH_PILL.w - iw) this.pillText.setFontSize(Math.max(12, Math.floor(18 * (COACH_PILL.w - iw) / this.pillText.width)));
else this.pillText.setFontSize(18);
const w = Math.min(COACH_PILL.w, this.pillText.width + iw + 40);
const h = 40;
this.pillText.setX(-w / 2 + 20 + this.pillText.width / 2);
icons.forEach((ic, i) => {
const x = -w / 2 + 20 + this.pillText.width + 14 + i * iconW + iconW / 2;
const img = s.add.image(x, -2, 'mj-flat-p', `0-${ic.kind}`).setScale(0.36).setAlpha(ic.dim ? 0.45 : 1);
const n = s.add.text(x + 10, 9, String(ic.n), { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#ffffff', backgroundColor: ic.n ? '#2a6a3a' : '#7a2a1a', padding: { x: 3, y: 0 } }).setOrigin(0.5);
this.pillIcons.add([img, n]);
});
const fill = tone === 'ready' ? 0x1e5a34 : tone === 'warn' ? 0x6a2a12 : 0x1a0c08;
this.pillBg.clear();
this.pillBg.fillStyle(0x000000, 0.35).fillRoundedRect(-w / 2 + 3, -h / 2 + 5, w, h, 20);
this.pillBg.fillStyle(fill, 0.92).fillRoundedRect(-w / 2, -h / 2, w, h, 20);
this.pillBg.lineStyle(2, tone === 'ready' ? 0x8fe0a8 : 0xd9a441, 0.9).strokeRoundedRect(-w / 2, -h / 2, w, h, 20);
s.tweens.add({ targets: this.pill, alpha: 1, duration: 160 });
}
// ── dock: calls & self actions ──────────────────────────────────────────────
// items: [{ label, key, rec, onHover(on) }] — stacked big buttons.
showCalls(items, title = '') {
this.clearCalls();
const s = this.scene, D = this.depth;
this.dockTitle.setText(title);
const top = DOCK.y + 50, avail = DOCK.h - 50 - 70;
const h = Math.min(54, Math.floor((avail - (items.length - 1) * 8) / Math.max(1, items.length)));
items.forEach((it, i) => {
const y = top + h / 2 + i * (h + 8);
const bg = it.key === 'win' ? 0xb8861c : it.key === 'pass' ? 0x3a2a20 : 0x8a2414;
const b = new Button(s, DOCK.x + DOCK.w / 2, y, it.label, () => this.onCall(it), { width: DOCK.w - 40, height: h, fontSize: 21, bg }).setDepth(D + 5);
if (it.onHover) {
b.on('pointerover', () => it.onHover(true));
b.on('pointerout', () => it.onHover(false));
}
this.calls.push(b);
if (it.rec) {
const star = s.add.text(DOCK.x + 34, y, '★', { fontFamily: SERIF, fontSize: '22px', color: '#ffe07a' }).setOrigin(0.5).setDepth(D + 6);
s.tweens.add({ targets: star, scale: { from: 0.8, to: 1.2 }, yoyo: true, repeat: -1, duration: 600 });
this.calls.push(star);
}
});
}
clearCalls() {
this.calls.forEach((c) => c.destroy());
this.calls = [];
this.dockTitle.setText('');
this.timerBar.clear();
}
setTimer(frac) {
this.timerBar.clear();
if (frac == null) return;
this.timerBar.fillStyle(0x000000, 0.4).fillRoundedRect(DOCK.x + 20, DOCK.y + 36, DOCK.w - 40, 6, 3);
this.timerBar.fillStyle(0xd9a441, 1).fillRoundedRect(DOCK.x + 20, DOCK.y + 36, (DOCK.w - 40) * frac, 6, 3);
}
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);
b.setAlpha(on ? 1 : 0.45);
}
// ── helper cards ────────────────────────────────────────────────────────────
card(key, r, title) {
if (this.helperObjs[key]) return this.helperObjs[key];
const s = this.scene, D = this.depth;
const bg = panel(s, r, D, { tint: '#1e0c08' });
const t = s.add.text(r.x + 16, r.y + 18, title, { fontFamily: LABEL_FONT, fontSize: '14px', color: GOLD }).setOrigin(0, 0.5).setDepth(D + 1);
const box = { bg, t, objs: [], r };
this.helperObjs[key] = box;
return box;
}
hideCard(key) {
const c = this.helperObjs[key];
if (!c) return;
c.objs.forEach((o) => o.destroy());
c.bg.destroy(); c.t.destroy();
delete this.helperObjs[key];
}
clearCard(c) { c.objs.forEach((o) => o.destroy()); c.objs = []; }
// Tile tracker: unseen copies of every kind (from your seat).
drawTracker(unseen) {
const c = this.card('tracker', TRACKER, 'TILE TRACKER · copies still unseen');
const key = unseen.join('');
if (c.key === key && c.objs.length) return;
c.key = key;
this.clearCard(c);
const s = this.scene, D = this.depth;
const rows = [[0, 9], [9, 9], [18, 9], [27, 7]];
rows.forEach(([k0, n], ri) => {
for (let i = 0; i < n; i++) {
const k = k0 + i;
const x = TRACKER.x + 30 + i * 42 + (ri === 3 ? 42 : 0);
const y = TRACKER.y + 70 + ri * 70;
const left = unseen[k];
const img = s.add.image(x, y, 'mj-flat-p', `0-${k}`).setScale(0.42).setDepth(D + 1).setAlpha(left ? 1 : 0.3);
c.objs.push(img);
const g = s.add.graphics().setDepth(D + 2);
for (let j = 0; j < 4; j++) {
g.fillStyle(j < left ? (left === 1 ? 0xf0a040 : 0x8fe0a8) : 0x4a3020, 1);
g.fillCircle(x - 12 + j * 8, y + 32, 3);
}
c.objs.push(g);
}
});
}
// Hand compass + opponent reads.
drawInfo({ compass = null, reads = null, names }) {
if (!compass && !reads) { this.hideCard('info'); return; }
const c = this.card('info', INFO_CARD, compass ? 'HEADING TOWARD' : 'READING THE TABLE');
this.clearCard(c);
const s = this.scene, D = this.depth;
let y = INFO_CARD.y + 44;
const x = INFO_CARD.x + 18;
if (compass) {
const sure = compass.sure;
c.objs.push(s.add.text(x, y, `Banked: ${sure} faan${compass.sureBits.length ? ` (${compass.sureBits.join(', ')})` : ''}`, { fontFamily: SERIF, fontSize: '14px', color: INK, wordWrap: { width: INFO_CARD.w - 36 } }).setOrigin(0, 0).setDepth(D + 1));
y += 24;
if (!compass.items.length) { c.objs.push(s.add.text(x, y, 'Nothing special yet — build sets and a pair.', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: MUTED }).setDepth(D + 1)); y += 22; }
for (const it of compass.items.slice(0, reads ? 3 : 5)) {
const g = s.add.graphics().setDepth(D + 1);
g.fillStyle(0x3a2018, 1).fillRoundedRect(x, y + 4, 90, 8, 4);
g.fillStyle(it.progress >= 0.85 ? 0x8fe0a8 : 0xd9a441, 1).fillRoundedRect(x, y + 4, 90 * Math.min(1, it.progress), 8, 4);
c.objs.push(g);
c.objs.push(s.add.text(x + 100, y, `${it.label} (${it.faan})`, { fontFamily: SERIF, fontSize: '14px', color: INK }).setDepth(D + 1));
c.objs.push(s.add.text(x + 100, y + 17, it.note, { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: MUTED }).setDepth(D + 1));
y += 38;
}
}
if (reads) {
if (compass) {
y += 4;
c.objs.push(s.add.text(x, y, 'READING THE TABLE', { fontFamily: LABEL_FONT, fontSize: '13px', color: GOLD }).setDepth(D + 1));
y += 22;
}
for (const r of reads) {
const danger = r.threat >= 0.7 ? '#ff8a7a' : r.threat >= 0.45 ? '#f0c25a' : '#a6e2b8';
c.objs.push(s.add.circle(x + 6, y + 9, 5, parseInt(danger.slice(1), 16)).setDepth(D + 1));
c.objs.push(s.add.text(x + 18, y, `${names[r.seat]}: ${r.text}`, { fontFamily: SERIF, fontSize: '13px', color: INK, wordWrap: { width: INFO_CARD.w - 50 } }).setDepth(D + 1));
y += 22;
}
}
}
// Table log: the last few things that happened.
drawLog(lines) {
const c = this.card('log', LOG_CARD, 'AT THE TABLE');
this.clearCard(c);
const s = this.scene, D = this.depth;
lines.slice(-6).forEach((ln, i) => {
c.objs.push(s.add.text(LOG_CARD.x + 18, LOG_CARD.y + 38 + i * 22, ln.text, { fontFamily: SERIF, fontSize: '14px', color: ln.color ?? INK }).setDepth(D + 1));
});
}
// ── reference ───────────────────────────────────────────────────────────────
buildReference() {
const s = this.scene;
const panelC = s.add.container(W, 0).setDepth(this.depth + 40);
const g = s.add.graphics();
g.fillStyle(0x1a0a06, 0.97).fillRect(0, 0, REF_W, GAME_HEIGHT);
g.lineStyle(3, 0xd9a441, 1).lineBetween(0, 0, 0, GAME_HEIGHT);
panelC.add(g);
panelC.add(s.add.text(REF_W / 2, 36, 'Winning Hands', { fontFamily: DISPLAY_FONT, fontSize: '34px', color: GOLD }).setOrigin(0.5));
this.refRows = new Map();
// two columns: name + faan on one line, the description beneath it
const PAD = 26, GUT = 44, ROW = 50;
const colW = (REF_W - PAD * 2 - GUT) / 2;
const columns = [
[['pattern', 'HAND PATTERNS'], ['meld', 'PUNGS THAT SCORE'], ['context', 'HOW YOU WIN']],
[['limit', 'LIMIT HANDS — score the limit'], ['bonus', 'FLOWERS & SEASONS']],
];
let footY = 0;
columns.forEach((groups, ci) => {
const x0 = PAD + ci * (colW + GUT);
let y = 74;
for (const [gid, head] of groups) {
panelC.add(s.add.text(x0, y, head, { fontFamily: LABEL_FONT, fontSize: '16px', color: MUTED }));
y += 30;
for (const r of FAAN_TABLE.filter((x) => x.group === gid)) {
const hl = s.add.rectangle(x0 + colW / 2, y + ROW / 2 - 3, colW + 12, ROW - 4, 0x2e6a44, 0).setOrigin(0.5);
panelC.add(hl);
panelC.add(s.add.text(x0 + 4, y + 12, r.label, { fontFamily: SERIF, fontSize: '21px', fontStyle: 'bold', color: INK }).setOrigin(0, 0.5));
panelC.add(s.add.text(x0 + colW, y + 12, r.limit ? 'limit' : `${r.faan} faan`, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: GOLD }).setOrigin(1, 0.5));
panelC.add(s.add.text(x0 + 4, y + 34, r.desc, { fontFamily: SERIF, fontSize: '16px', color: MUTED, wordWrap: { width: colW - 8 } }).setOrigin(0, 0.5));
this.refRows.set(r.id, hl);
y += ROW;
}
y += 8;
}
if (ci === 1) footY = y + 10;
});
// a divider between the columns
g.lineStyle(1, 0xd9a441, 0.35).lineBetween(REF_W / 2, 80, REF_W / 2, GAME_HEIGHT - 40);
this.refFoot = s.add.text(PAD + colW + GUT + colW / 2, footY, '', { fontFamily: SERIF, fontSize: '18px', color: GOLD, align: 'center', wordWrap: { width: colW } }).setOrigin(0.5, 0);
panelC.add(this.refFoot);
// a vertical "Close Hands" tab on the panel's left edge, centred top to bottom
const tabW = 44, tabH = 210;
const tab = s.add.container(-tabW / 2, GAME_HEIGHT / 2);
const tg = s.add.graphics();
tg.fillStyle(0x000000, 0.35).fillRoundedRect(-tabW / 2 - 3, -tabH / 2 + 4, tabW, tabH, { tl: 12, bl: 12, tr: 0, br: 0 });
tg.fillStyle(0x5a1a10, 1).fillRoundedRect(-tabW / 2, -tabH / 2, tabW, tabH, { tl: 12, bl: 12, tr: 0, br: 0 });
tg.lineStyle(2, 0xd9a441, 1).strokeRoundedRect(-tabW / 2, -tabH / 2, tabW + 2, tabH, { tl: 12, bl: 12, tr: 0, br: 0 });
const tt = s.add.text(0, 0, 'Close Hands ›', { fontFamily: LABEL_FONT, fontSize: '17px', color: GOLD }).setOrigin(0.5).setAngle(-90);
const hit = s.add.rectangle(0, 0, tabW, tabH, 0xffffff, 0.001).setInteractive({ useHandCursor: true });
hit.on('pointerover', () => tt.setColor('#ffffff'));
hit.on('pointerout', () => tt.setColor(GOLD));
hit.on('pointerup', () => { if (this.refOpen) this.onButton('hands'); });
tab.add([tg, tt, hit]);
tab.setVisible(false);
panelC.add(tab);
this.refTab = tab;
this.ref = panelC;
this.refOpen = false;
}
setReferenceFooter(o) {
this.refFoot.setText(`A hand needs at least ${o.minFaan} faan to win · limit ${o.faanCap} faan.\nPoints double with faan · the discarder pays 2×, everyone pays on a self-draw.`);
}
highlightReference(ids) {
for (const [id, hl] of this.refRows) hl.setFillStyle(0x2e6a44, ids.has(id) ? 0.55 : 0);
}
toggleReference(open = !this.refOpen) {
this.refOpen = open;
// the wide pull-out covers both right-hand portraits and the top one
if (open) this.refTab.setVisible(true);
this.scene.tweens.add({
targets: this.ref, x: open ? W - REF_W : W, duration: 220, ease: 'Quad.Out',
onComplete: () => { if (!this.refOpen) this.refTab.setVisible(false); }, // parked off-screen, the tab would peek in
});
// DOM portraits would float over the panel
[1, 2].forEach((seat) => this.seats[seat]?.portrait?.setVideoVisible?.(!open));
}
}
export { WIND_LABEL, GOLD, INK, MUTED };

View File

@ -0,0 +1,203 @@
// MahjongLayout.js — the parlour table's geometry. Phaser-free.
//
// One perspective camera (the casino kit's makeProjection) looks at a square
// table from the human's chair. Table space: x, z ∈ [−1, 1], x to the right,
// z toward the viewer (z = +1 is the near rail). Each seat has local
// coordinates (a, d): d = distance from the centre toward that seat, a =
// sideways, increasing toward that player's RIGHT hand.
//
// seat 0 (you) south — world (a, d)
// seat 1 east — world (d, −a) (screen right)
// seat 2 north — world (−a, −d) (far side)
// seat 3 west — world (−d, a) (screen left)
//
// Turn order 0→1→2→3 runs counter-clockwise as at a real table; the wall is
// drawn clockwise from the break.
//
// Flat tiles have an orientation r (0…3, quarter turns clockwise of the label)
// so a tile "faces" a seat: its label reads upright from that chair.
import { makeProjection } from '../../ui/casino/CasinoGeometry.js';
export const W = 1920, H = 1080;
export const VIEW = { cx: 960, yFar: 150, yNear: 864, sFar: 0.7, halfW: 600 };
export const CAM = makeProjection(VIEW);
export const CAM_SIN = 0.85, CAM_COS = 0.53; // ground foreshortening / height foreshortening
// world (x, z) → screen { x, y, s }
export function project(x, z) { return CAM.project(x, (z + 1) / 2); }
export function unproject(sx, sy) { const p = CAM.unproject(sx, sy); return { x: p.u, z: p.v * 2 - 1, s: p.s }; }
// ── tiles ────────────────────────────────────────────────────────────────────
export const TW = 0.07; // tile width (table units)
export const TD = 0.094; // tile length (lying flat, along its label)
export const GAP = 0.004;
export const STACK_PX = 10; // screen px a second tile layer sits above the first (× s)
export const STAND_PX = 34; // screen px a standing tile rises (× s)
// Texture sizes (see MahjongArt): flat face FW×FH (portrait), strip below.
export const FW = 72, FH = 98, STRIP = 22;
export const HAND = { y: 992, w: 66, h: 90, step: 70, gap: 22, lift: 18, cap: 12 }; // the human's rack (screen space)
export const ORIENT = [0, 3, 2, 1]; // label orientation facing each seat
export function world(seat, a, d) {
switch (seat) {
case 0: return { x: a, z: d };
case 1: return { x: d, z: -a };
case 2: return { x: -a, z: -d };
default: return { x: -d, z: a };
}
}
// Screen pose of a flat tile centred on world (x, z) with orientation r.
// Returns { x, y, sx, sy, s, depth, r, w, h } — sx/sy scale the face part of
// the texture (FW×FH portrait, FH×FW landscape) onto its projected footprint.
export function flatPose(x, z, r, { layer = 0, lift = 0 } = {}) {
const land = r % 2 === 1;
const wx = land ? TD : TW, wz = land ? TW : TD;
const c = project(x, z);
const top = project(x, z - wz / 2), bot = project(x, z + wz / 2);
const w = wx * VIEW.halfW * c.s;
const h = bot.y - top.y;
const texW = land ? FH : FW, texH = land ? FW : FH;
const y = (top.y + bot.y) / 2 - layer * STACK_PX * c.s - lift;
return { x: c.x, y, sx: w / texW, sy: h / texH, s: c.s, depth: 100 + c.y * 0.1 + layer * 2, r, w, h };
}
// ── table furniture ──────────────────────────────────────────────────────────
export const TABLE = { half: 1.0, rail: 0.075 };
export const WALL_D = 0.685;
export const RIVER_D0 = 0.228;
export const RIVER_COLS = 6;
export const MELD_D = 0.835;
export const HAND_D = 0.935;
export const REVEAL_D = 0.935;
export const MELD_A0 = 0.66; // melds start at the player's right end…
export const BONUS_A0 = -0.66; // …bonus tiles at their left end
export const COMPASS = { half: 0.165 };
// The wall: `stacks` stacks (72 with flowers, 68 without) in four walls.
// stackInfo = { wall (seat), j (0 = that wall's right end) }.
export function wallTilePose(wallSeat, j, per, layer) {
const halfLen = (per * TW) / 2;
const a = halfLen - (j + 0.5) * TW;
const p = world(wallSeat, a, WALL_D);
return { ...flatPose(p.x, p.z, ORIENT[wallSeat], { layer }), faceUp: false };
}
// River slot `i` of `seat`: rows of six from the centre outward.
export function riverPose(seat, i) {
let row = Math.floor(i / RIVER_COLS), col = i % RIVER_COLS;
if (row > 3) { col = i - 3 * RIVER_COLS; row = 3; }
const a = (col - (RIVER_COLS - 1) / 2) * (TW + GAP);
const d = RIVER_D0 + TD / 2 + row * (TD + GAP);
const p = world(seat, a, d);
return { ...flatPose(p.x, p.z, ORIENT[seat]), faceUp: true };
}
// An opponent's standing tile i of n (seats 1–3).
export function standPose(seat, i, n) {
const a = (i - (n - 1) / 2) * (TW + GAP * 0.5);
const p = world(seat, a, HAND_D);
const c = project(p.x, p.z);
if (seat === 2) {
// back to us: width TW, standing height above the footprint
return { x: c.x, y: c.y, s: c.s, depth: 100 + c.y * 0.1 + 1, stand: 'back', sx: (TW * VIEW.halfW * c.s) / FW, sy: (TW * VIEW.halfW * c.s) / FW };
}
// seen from the side: a column of slabs; nearer tiles overlap farther ones
return { x: c.x, y: c.y, s: c.s, depth: 100 + c.y * 0.1 + 1, stand: seat === 1 ? 'right' : 'left', sx: c.s * 0.62, sy: c.s * 0.62 };
}
// Flat tiles of a meld/bonus row, laid out from (a0) in direction dir along
// the seat's a-axis. items: [{ id, side (lies sideways), faceUp, stackOn }]
// Returns Map id → pose.
export function rowPoses(seat, items, a0, dir) {
const out = new Map();
let a = a0;
const r0 = ORIENT[seat];
for (const it of items) {
if (it.gapBefore) a += dir * it.gapBefore;
const along = it.side ? TD : TW;
if (it.stackOn != null) {
const base = out.get(it.stackOn);
if (base) { out.set(it.id, { ...base, ...flatPose(base.wx, base.wz, base.r, { layer: 1 }), wx: base.wx, wz: base.wz, faceUp: true }); continue; }
}
const ca = a + (dir * along) / 2;
// sideways tiles sit flush with the outer edge of the row
const d = it.side ? MELD_D + (TD - TW) / 2 : MELD_D;
const p = world(seat, ca, d);
const r = it.side ? (r0 + 1) % 4 : r0;
out.set(it.id, { ...flatPose(p.x, p.z, r), wx: p.x, wz: p.z, faceUp: it.faceUp !== false });
a += dir * (along + GAP);
}
return out;
}
// A knocked-down hand (hand end): flat, face-up, facing the seat, centred.
export function revealPose(seat, i, n, extraGapAt = -1) {
let a = (i - (n - 1) / 2) * (TW + GAP);
if (extraGapAt >= 0 && i >= extraGapAt) a += TW * 0.4;
const p = world(seat, a, REVEAL_D);
return { ...flatPose(p.x, p.z, ORIENT[seat]), faceUp: true };
}
// The human's rack, in screen space. order: ids left→right; drawn id (or
// null) sits apart on the right. Returns Map id → { x, y }.
export function humanRack(order, drawn) {
const n = order.length + (drawn != null ? 1 : 0);
const totalW = n * HAND.step + (drawn != null ? HAND.gap : 0);
let x = W / 2 - totalW / 2 + HAND.step / 2;
const out = new Map();
for (const id of order) { out.set(id, { x, y: HAND.y }); x += HAND.step; }
if (drawn != null) out.set(drawn, { x: x + HAND.gap, y: HAND.y });
return out;
}
// Where a dropped tile counts as "thrown onto the table".
export const DISCARD_DROP_Y = HAND.y - HAND.h / 2 - 60;
// ── screen furniture (HUD) ───────────────────────────────────────────────────
export const ROUND_CARD = { x: 18, y: 16, w: 404, h: 124 };
export const LOG_CARD = { x: 18, y: 152, w: 404, h: 172 };
export const TRACKER = { x: 18, y: 512, w: 404, h: 340 };
export const SEAT_PANELS = [
{ x: 18, y: 872, w: 404, h: 192 }, // you
{ x: 1498, y: 336, w: 404, h: 164 }, // right
{ x: 1450, y: 16, w: 404, h: 124 }, // top (far side)
{ x: 18, y: 336, w: 404, h: 164 }, // left
];
export const TOP_BUTTONS = { x: 1498, y: 152, w: 404, h: 56 };
export const INFO_CARD = { x: 1498, y: 512, w: 404, h: 262 };
export const DOCK = { x: 1498, y: 786, w: 404, h: 278 };
export const COACH_PILL = { x: 960, y: 906, w: 940 };
export const REF_W = 1140; // the "Winning Hands" pull-out: two columns
// Where a call stamp ("Pung!") pops for each seat.
export function callSpot(seat) {
const p = world(seat, 0, 0.56);
const c = project(p.x, p.z);
return { x: c.x, y: c.y - 20 };
}
// Dice tray: the felt inside the compass, in px "world" units for Dice3D.
export const DICE_TRAY = { w: 250, h: 250 };
export function diceGround(u, v) {
const x = -0.2 + (u / DICE_TRAY.w) * 0.4, z = -0.2 + (v / DICE_TRAY.h) * 0.4;
return project(x, z);
}
export function diceOrigin(seat) {
const w = DICE_TRAY.w, h = DICE_TRAY.h;
return [
{ u: w * 0.5, v: h + 80, h: 70 },
{ u: w + 80, v: h * 0.5, h: 70 },
{ u: w * 0.5, v: -80, h: 70 },
{ u: -80, v: h * 0.5, h: 70 },
][seat];
}
// Projected corners of a flat world rectangle (x0..x1, z0..z1).
export function quad(x0, z0, x1, z1) {
return [project(x0, z0), project(x1, z0), project(x1, z1), project(x0, z1)];
}

View File

@ -0,0 +1,158 @@
// MahjongLedger.js — follows every physical tile through a hand. Phaser-free.
//
// The engine tracks kinds; the table needs to know which of the 144 tile
// sprites to move. A tile's id is its wall index for the hand (the engine
// says so in every event that takes a tile off the wall); after that the
// ledger decides which same-kind tile moves (the clicked one, the one just
// drawn, …) — identical tiles are interchangeable, so any choice is honest.
//
// const led = new Ledger();
// const moves = led.apply(event, { preferId }) // one engine log event
// led.hand[seat] ids in display order (new tiles appended)
// led.where(id) { zone: 'wall'|'hand'|'river'|'meld'|'bonus', seat, … }
//
// apply() returns the moves the event caused, in order, for animation:
// { id, zone, seat, from: {zone, seat}, ...extra }
// verifyMahjong checks the ledger against the engine after every step.
export class Ledger {
constructor() { this.reset([]); }
reset(wall) {
this.kinds = wall.slice();
this.n = wall.length;
this.wall = new Set(wall.map((_, i) => i));
this.hand = [[], [], [], []];
this.river = [[], [], [], []];
this.melds = [[], [], [], []]; // { type, ids, kinds, from, claimedId, concealed, addedId }
this.bonus = [[], [], [], []];
this.drawn = [null, null, null, null]; // the id each seat drew last (still in hand)
this.winId = null;
this.loc = new Map();
for (let i = 0; i < this.n; i++) this.loc.set(i, { zone: 'wall' });
}
kindOf(id) { return this.kinds[id]; }
where(id) { return this.loc.get(id); }
takeFromHand(seat, kind, preferId = null) {
const h = this.hand[seat];
let i = -1;
if (preferId != null && this.kinds[preferId] === kind) i = h.indexOf(preferId);
if (i < 0 && this.drawn[seat] != null && this.kinds[this.drawn[seat]] === kind) i = h.indexOf(this.drawn[seat]);
if (i < 0) for (let k = h.length - 1; k >= 0; k--) if (this.kinds[h[k]] === kind) { i = k; break; }
if (i < 0) throw new Error(`ledger: seat ${seat} holds no ${kind}`);
const [id] = h.splice(i, 1);
if (this.drawn[seat] === id) this.drawn[seat] = null;
return id;
}
apply(ev, { preferId = null } = {}) {
const moves = [];
const mv = (id, zone, seat, extra = {}) => {
const from = this.loc.get(id);
this.loc.set(id, { zone, seat, ...extra });
moves.push({ id, zone, seat, from, ...extra });
};
switch (ev.t) {
case 'hand':
this.reset(ev.wall);
break;
case 'deal':
for (const id of ev.ids) { this.wall.delete(id); this.hand[ev.seat].push(id); mv(id, 'hand', ev.seat, { deal: true }); }
break;
case 'draw':
this.wall.delete(ev.id);
this.hand[ev.seat].push(ev.id);
this.drawn[ev.seat] = ev.deal ? null : ev.id;
mv(ev.id, 'hand', ev.seat, { drawn: !ev.deal, back: !!ev.back });
break;
case 'flower': {
let id = ev.id;
if (ev.fromHand) id = this.takeFromHand(ev.seat, ev.kind);
else this.wall.delete(id);
this.bonus[ev.seat].push(id);
mv(id, 'bonus', ev.seat, { index: this.bonus[ev.seat].length - 1 });
break;
}
case 'discard': {
const id = this.takeFromHand(ev.seat, ev.kind, preferId);
this.drawn[ev.seat] = null;
this.river[ev.seat].push(id);
mv(id, 'river', ev.seat, { index: this.river[ev.seat].length - 1 });
break;
}
case 'claim': {
const claimed = this.river[ev.from].pop();
const ids = [];
let usedClaim = false;
for (const k of ev.kinds) {
if (!usedClaim && k === ev.kind) { ids.push(claimed); usedClaim = true; } else ids.push(this.takeFromHand(ev.seat, k));
}
const meld = { type: ev.type, ids, kinds: ev.kinds.slice(), from: ev.from, claimedId: claimed, concealed: false, addedId: null };
this.melds[ev.seat].push(meld);
const mi = this.melds[ev.seat].length - 1;
ids.forEach((id, k) => mv(id, 'meld', ev.seat, { meld: mi, pos: k, claimed: id === claimed }));
break;
}
case 'kong': {
if (ev.kongType === 'concealed') {
const ids = [0, 1, 2, 3].map(() => this.takeFromHand(ev.seat, ev.kind));
this.melds[ev.seat].push({ type: 'kong', ids, kinds: [ev.kind, ev.kind, ev.kind, ev.kind], from: null, claimedId: null, concealed: true, addedId: null });
const mi = this.melds[ev.seat].length - 1;
ids.forEach((id, k) => mv(id, 'meld', ev.seat, { meld: mi, pos: k }));
} else {
const mi = this.melds[ev.seat].findIndex((m) => m.type === 'pung' && m.kinds[0] === ev.kind);
const m = this.melds[ev.seat][mi];
const id = this.takeFromHand(ev.seat, ev.kind);
m.type = 'kong'; m.kinds.push(ev.kind); m.ids.push(id); m.addedId = id;
mv(id, 'meld', ev.seat, { meld: mi, pos: 3, added: true });
}
this.drawn[ev.seat] = null;
break;
}
case 'rob': {
const mi = this.melds[ev.from].findIndex((m) => m.addedId != null && m.kinds[0] === ev.kind);
const m = this.melds[ev.from][mi];
const id = m.addedId;
m.ids = m.ids.filter((x) => x !== id); m.kinds.pop(); m.type = 'pung'; m.addedId = null;
this.robbed = id;
break;
}
case 'win': {
let id;
if (ev.byDiscard && ev.rob) id = this.robbed;
else if (ev.byDiscard) id = this.river[ev.from].pop();
else id = this.drawn[ev.seat] ?? this.hand[ev.seat][this.hand[ev.seat].length - 1];
if (ev.byDiscard) this.hand[ev.seat].push(id);
this.winId = id;
mv(id, 'hand', ev.seat, { win: true });
break;
}
default: break; // exhausted / gameOver: nothing moves
}
return moves;
}
// Snapshot / restore (undo).
save() {
return JSON.parse(JSON.stringify({
kinds: this.kinds, n: this.n, wall: [...this.wall], hand: this.hand, river: this.river, melds: this.melds,
bonus: this.bonus, drawn: this.drawn, winId: this.winId, loc: [...this.loc.entries()],
}));
}
load(snap) {
const s = JSON.parse(JSON.stringify(snap));
Object.assign(this, s);
this.wall = new Set(s.wall);
this.loc = new Map(s.loc);
}
}
// Multiset compare helper used by the verifier.
export function sameKinds(ledger, ids, kinds) {
if (ids.length !== kinds.length) return false;
const a = ids.map((id) => ledger.kindOf(id)).sort((x, y) => x - y);
const b = kinds.slice().sort((x, y) => x - y);
return a.every((k, i) => k === b[i]);
}

View File

@ -1,22 +1,32 @@
// Mahjong (Hong Kong style) — pure game engine. No Phaser, no timers.
// Deterministic given a seed so AI self-play is reproducible.
//
// One session is one full East round: every player deals at least once; the
// dealer repeats after a dealer win or a wall-exhausted draw (goulash). Chow
// claims come only from the player to the left; pung/kong/win from anyone.
// Flowers and seasons are revealed and replaced immediately. Kong and bonus
// replacement tiles draw from the back of the live wall (no reserved dead
// wall). Deliberately out of scope: robbing the kong, rare limit hands other
// than Thirteen Orphans, and sacred-discard etiquette rules.
// A session is one or more wind rounds (house rule; East only by default):
// every player deals at least once per round; the dealer repeats after a
// dealer win or a wall-exhausted draw (goulash). Chow claims come only from
// the player to the left; pung/kong/win from anyone. Flowers and seasons are
// revealed and replaced immediately. Kong and bonus replacement tiles draw
// from the back of the live wall (no reserved dead wall). An added kong can be
// robbed (house rule, on by default). Deliberately out of scope: multiple
// winners and sacred-discard etiquette rules.
//
// Hands are stored merged: while a player is awaiting discard their hand
// holds 14 − 3·melds tiles (the drawn tile already in it, with state.drawnTile
// recording which kind arrived); otherwise 13 − 3·melds.
//
// Tile identity: the wall index of a tile is its id for the whole hand
// (state.wall[id] is its kind). The engine itself only tracks kinds, but every
// change is appended to state.log as an event — tiles leaving the wall carry
// their id — so a view (MahjongLedger) can follow each physical tile.
//
// Physical wall: the dealer rolls three dice; the total picks whose wall is
// broken and where (stackOfIndex). Wall index i sits in stack ⌊i/2⌋ after the
// break (clockwise), the even index on top; replacements come off the far end.
import {
buildWall, isSuited, isHonor, isBonus, rankOf,
buildWall, isSuited, isHonor, isBonus, rankOf, isTerminal,
WIND_KINDS, DRAGON_KINDS, FIRST_BONUS,
FAAN_BY_ID, MIN_FAAN, LIMIT_FAAN, basePoints,
FAAN_BY_ID, LIMIT_FAAN, basePoints, normalizeOpts,
} from './MahjongData.js';
// ── seeded RNG (mulberry32) ──────────────────────────────────────────────────
@ -40,16 +50,23 @@ export function counts34(tiles) {
const sortHand = (hand) => hand.sort((a, b) => a - b);
export const seatWindOf = (state, seat) => (seat - state.dealer + 4) % 4;
export const wallRemaining = (state) => Math.max(0, state.wallEnd - state.wallPos + 1);
const emit = (state, ev) => { state.log.push(ev); };
const blankStats = () => ({
wins: 0, selfDraws: 0, dealIns: 0, claims: 0, kongs: 0, flowers: 0, biggest: 0, ready: 0,
});
// ── state ────────────────────────────────────────────────────────────────────
export function createInitialState({ names = [], skills = {}, seed } = {}) {
export function createInitialState({ names = [], skills = {}, seed, opts } = {}) {
const o = normalizeOpts(opts);
const rng = mulberry32((seed ?? (Date.now() & 0x7fffffff)) | 0);
const players = [];
for (let seat = 0; seat < 4; seat++) {
players.push({
name: names[seat] ?? `Player ${seat + 1}`,
seat,
score: 0,
score: o.stake,
skill: skills[seat] ?? 3,
isAI: seat !== 0,
hand: [],
@ -58,19 +75,25 @@ export function createInitialState({ names = [], skills = {}, seed } = {}) {
});
}
const state = {
opts: o,
players,
wall: [], wallPos: 0, wallEnd: 143,
dice: [1, 1, 1], breakWall: 0, breakStack: 0, stacks: 72,
dealer: 0,
roundWind: 0, // East round only — one full round per session
roundWind: 0, // 0 East, 1 South, …
handNumber: 1,
turn: 0,
phase: 'awaitDiscard', // awaitDiscard | awaitClaims | handOver | gameOver
phase: 'awaitDiscard', // awaitDiscard | awaitClaims | awaitRob | handOver | gameOver
drawnTile: null,
lastDrawWasKongReplacement: false,
lastDiscard: null, // { kind, from }
lastDiscard: null, // { kind, from, rob? }
discards: [[], [], [], []],
discardCount: 0, claimCount: 0, kongCount: 0, // this hand
result: null,
winners: [],
history: [], // one row per finished hand
stats: [0, 1, 2, 3].map(blankStats),
log: [],
_rng: rng,
};
dealHand(state);
@ -78,15 +101,26 @@ export function createInitialState({ names = [], skills = {}, seed } = {}) {
}
export function cloneState(s) {
const rngState = s._rng; // functions don't clone; lookahead must not draw tiles
const rngState = s._rng; // functions don't clone; the wall is shuffled up front
const copy = JSON.parse(JSON.stringify({ ...s, _rng: undefined }));
copy._rng = rngState;
return copy;
}
// Where wall index `i` physically sits: { stack (0…stacks−1, clockwise from
// South's right end), wall (seat whose wall), j (0 = that wall's right end
// from its owner's view), top (upper layer) }.
export const WALL_ORDER = [0, 3, 2, 1]; // walls clockwise: S, W, N, E
export function stackOfIndex(state, i) {
const n = state.stacks, per = n / 4;
const g = (state.breakStack + Math.floor(i / 2)) % n;
return { stack: g, wall: WALL_ORDER[Math.floor(g / per)], j: g % per, top: i % 2 === 0 };
}
export function dealHand(state) {
const rng = state._rng;
const wall = buildWall();
const o = state.opts;
const wall = buildWall(o.bonusTiles);
for (let i = wall.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[wall[i], wall[j]] = [wall[j], wall[i]];
@ -94,31 +128,56 @@ export function dealHand(state) {
state.wall = wall;
state.wallPos = 0;
state.wallEnd = wall.length - 1;
state.stacks = wall.length / 2;
state.discards = [[], [], [], []];
state.discardCount = 0; state.claimCount = 0; state.kongCount = 0;
state.result = null;
state.lastDiscard = null;
state.drawnTile = null;
state.lastDrawWasKongReplacement = false;
for (const p of state.players) { p.hand = []; p.melds = []; p.bonus = []; }
// 13 tiles each (dealer first), then reveal and replace bonus tiles in the
// same order. The wall cannot run out during the deal.
for (let i = 0; i < 4; i++) {
const p = state.players[(state.dealer + i) % 4];
for (let n = 0; n < 13; n++) p.hand.push(state.wall[state.wallPos++]);
// Break the wall: three dice, counted counter-clockwise from the dealer
// (dealer = 1) to pick the wall, then that many stacks in from its right end.
state.dice = [1, 2, 3].map(() => 1 + Math.floor(rng() * 6));
const total = state.dice[0] + state.dice[1] + state.dice[2];
const per = state.stacks / 4;
state.breakWall = (state.dealer + total - 1) % 4;
state.breakStack = (WALL_ORDER.indexOf(state.breakWall) * per + total) % state.stacks;
state.turn = state.dealer;
emit(state, {
t: 'hand', hand: state.handNumber, dealer: state.dealer, roundWind: state.roundWind,
dice: state.dice.slice(), breakWall: state.breakWall, breakStack: state.breakStack,
wall: wall.slice(),
});
// Deal in blocks: four tiles each three times round (dealer first), then
// one each. Bonus tiles are then revealed and replaced in seat order.
for (let round = 0; round < 4; round++) {
const n = round < 3 ? 4 : 1;
for (let i = 0; i < 4; i++) {
const seat = (state.dealer + i) % 4;
const ids = [];
for (let k = 0; k < n; k++) { ids.push(state.wallPos); state.players[seat].hand.push(state.wall[state.wallPos++]); }
emit(state, { t: 'deal', seat, ids });
}
}
for (let i = 0; i < 4; i++) {
const p = state.players[(state.dealer + i) % 4];
const seat = (state.dealer + i) % 4;
const p = state.players[seat];
for (let h = 0; h < p.hand.length; h++) {
while (isBonus(p.hand[h])) {
p.bonus.push(p.hand[h]);
p.hand[h] = state.wall[state.wallEnd--];
state.stats[seat].flowers++;
emit(state, { t: 'flower', seat, kind: p.hand[h], fromHand: true });
const id = state.wallEnd--;
p.hand[h] = state.wall[id];
emit(state, { t: 'draw', seat, id, kind: p.hand[h], back: true, deal: true });
}
}
sortHand(p.hand);
}
state.turn = state.dealer;
drawForCurrent(state); // dealer's 14th tile
return state;
}
@ -129,17 +188,24 @@ export function dealHand(state) {
export function drawForCurrent(state) {
if (state.wallPos > state.wallEnd) return endInDraw(state);
const p = state.players[state.turn];
let k = state.wall[state.wallPos++];
let id = state.wallPos++;
let k = state.wall[id];
let back = false;
while (isBonus(k)) {
p.bonus.push(k);
state.stats[state.turn].flowers++;
emit(state, { t: 'flower', seat: state.turn, kind: k, id, fromHand: false });
if (state.wallPos > state.wallEnd) return endInDraw(state);
k = state.wall[state.wallEnd--];
id = state.wallEnd--;
k = state.wall[id];
back = true;
}
p.hand.push(k);
sortHand(p.hand);
state.drawnTile = k;
state.lastDrawWasKongReplacement = false;
state.phase = 'awaitDiscard';
emit(state, { t: 'draw', seat: state.turn, id, kind: k, back });
return state;
}
@ -148,21 +214,31 @@ function drawReplacement(state) {
const p = state.players[state.turn];
for (;;) {
if (state.wallPos > state.wallEnd) return endInDraw(state);
const k = state.wall[state.wallEnd--];
if (isBonus(k)) { p.bonus.push(k); continue; }
const id = state.wallEnd--;
const k = state.wall[id];
if (isBonus(k)) {
p.bonus.push(k);
state.stats[state.turn].flowers++;
emit(state, { t: 'flower', seat: state.turn, kind: k, id, fromHand: false });
continue;
}
p.hand.push(k);
sortHand(p.hand);
state.drawnTile = k;
state.lastDrawWasKongReplacement = true;
state.phase = 'awaitDiscard';
emit(state, { t: 'draw', seat: state.turn, id, kind: k, back: true, kong: true });
return state;
}
}
function endInDraw(state) {
state.drawnTile = null;
state.lastDiscard = null;
state.result = { type: 'draw' };
state.phase = 'handOver';
recordHand(state);
emit(state, { t: 'exhausted' });
return state;
}
@ -176,46 +252,56 @@ export function discardTile(state, kind) {
if (state.phase !== 'awaitDiscard') return false;
const p = state.players[state.turn];
if (!p.hand.includes(kind)) return false;
const tsumogiri = state.drawnTile === kind;
removeFromHand(p.hand, kind, 1);
state.discards[state.turn].push(kind);
state.lastDiscard = { kind, from: state.turn };
state.drawnTile = null;
state.lastDrawWasKongReplacement = false;
state.discardCount++;
state.phase = 'awaitClaims';
emit(state, { t: 'discard', seat: state.turn, kind, tsumogiri });
return true;
}
// What `seat` may do with the tile just discarded. Null when nothing.
// Chows only off the player to the left. Win is only offered when the hand
// would score at least MIN_FAAN.
// What `seat` may do with the tile just discarded (or the tile being added
// to a kong, when it can be robbed). Null when nothing. Chows only off the
// player to the left. Win is only offered when the hand would score at least
// the table minimum.
export function claimOptionsFor(state, seat) {
if (state.phase !== 'awaitClaims' || !state.lastDiscard) return null;
const { kind, from } = state.lastDiscard;
if ((state.phase !== 'awaitClaims' && state.phase !== 'awaitRob') || !state.lastDiscard) return null;
const { kind, from, rob } = state.lastDiscard;
if (seat === from) return null;
const p = state.players[seat];
const n = p.hand.filter((t) => t === kind).length;
const opts = { win: false, pung: n >= 2, kong: n >= 3, chows: [] };
if (seat === (from + 1) % 4 && isSuited(kind)) {
const r = rankOf(kind);
const has = (kk) => p.hand.includes(kk);
if (r >= 3 && has(kind - 2) && has(kind - 1)) opts.chows.push([kind - 2, kind - 1]);
if (r >= 2 && r <= 8 && has(kind - 1) && has(kind + 1)) opts.chows.push([kind - 1, kind + 1]);
if (r <= 7 && has(kind + 1) && has(kind + 2)) opts.chows.push([kind + 1, kind + 2]);
const opts = { win: false, pung: false, kong: false, chows: [] };
if (!rob) {
const n = p.hand.filter((t) => t === kind).length;
opts.pung = n >= 2;
opts.kong = n >= 3 && wallRemaining(state) > 0;
if (seat === (from + 1) % 4 && isSuited(kind)) {
const r = rankOf(kind);
const has = (kk) => p.hand.includes(kk);
if (r >= 3 && has(kind - 2) && has(kind - 1)) opts.chows.push([kind - 2, kind - 1]);
if (r >= 2 && r <= 8 && has(kind - 1) && has(kind + 1)) opts.chows.push([kind - 1, kind + 1]);
if (r <= 7 && has(kind + 1) && has(kind + 2)) opts.chows.push([kind + 1, kind + 2]);
}
}
if (canWinWith(p.hand, p.melds, kind)) {
opts.win = evaluateWin(state, seat, kind, true).faan >= MIN_FAAN;
opts.win = evaluateWin(state, seat, kind, true).faan >= state.opts.minFaan;
}
return (opts.win || opts.pung || opts.kong || opts.chows.length) ? opts : null;
}
// Resolve all claim intents on the current discard. intents is an array of
// { seat, claim } where claim is null (pass) or { type, tiles? }. Priority:
// win beats kong/pung beats chow; among multiple wins the seat nearest
// counter-clockwise from the discarder takes it (one-winner rule). With no
// claims the next player simply draws. Returns { applied } for animation.
// Resolve all claim intents on the current discard (or robbable kong tile).
// intents is an array of { seat, claim } where claim is null (pass) or
// { type, tiles? }. Priority: win beats kong/pung beats chow; among multiple
// wins the seat nearest counter-clockwise from the discarder takes it
// (head bump). With no claims the next player simply draws (or, after a
// kong nobody robbed, the kong's owner draws the replacement).
// Returns { applied } for animation.
export function resolveClaims(state, intents) {
if (state.phase !== 'awaitClaims' || !state.lastDiscard) return { applied: null };
const { kind, from } = state.lastDiscard;
if ((state.phase !== 'awaitClaims' && state.phase !== 'awaitRob') || !state.lastDiscard) return { applied: null };
const { kind, from, rob } = state.lastDiscard;
const bySeat = new Map();
for (const i of intents) if (i && i.claim) bySeat.set(i.seat, i.claim);
@ -224,6 +310,23 @@ export function resolveClaims(state, intents) {
const s = (from + d) % 4;
if (bySeat.get(s)?.type === 'win') chosen = { seat: s, claim: bySeat.get(s) };
}
if (rob) {
if (chosen) {
// the robbed tile comes back off the kong, which reverts to a pung
const kp = state.players[from];
const m = kp.melds.find((x) => x.type === 'kong' && x.kinds[0] === kind && x.added);
if (m) { m.type = 'pung'; m.kinds.pop(); delete m.added; }
state.kongCount = Math.max(0, state.kongCount - 1);
state.stats[from].kongs = Math.max(0, state.stats[from].kongs - 1);
emit(state, { t: 'rob', seat: chosen.seat, from, kind });
declareWin(state, chosen.seat, { byDiscard: true });
return { applied: chosen };
}
state.lastDiscard = null;
state.turn = from;
drawReplacement(state);
return { applied: null };
}
if (!chosen) {
for (const [s, c] of bySeat) {
if (c.type === 'kong' || c.type === 'pung') { chosen = { seat: s, claim: c }; break; }
@ -244,10 +347,15 @@ export function resolveClaims(state, intents) {
const c = chosen.claim;
if (c.type === 'win') {
declareWin(state, chosen.seat, { byDiscard: true });
} else if (c.type === 'pung') {
return { applied: chosen };
}
state.claimCount++;
state.stats[chosen.seat].claims++;
if (c.type === 'pung') {
state.discards[from].pop();
removeFromHand(p.hand, kind, 2);
p.melds.push({ type: 'pung', kinds: [kind, kind, kind], concealed: false, from });
emit(state, { t: 'claim', seat: chosen.seat, from, type: 'pung', kind, kinds: [kind, kind, kind] });
state.turn = chosen.seat;
state.drawnTile = null;
state.lastDiscard = null;
@ -256,6 +364,9 @@ export function resolveClaims(state, intents) {
state.discards[from].pop();
removeFromHand(p.hand, kind, 3);
p.melds.push({ type: 'kong', kinds: [kind, kind, kind, kind], concealed: false, from });
state.kongCount++;
state.stats[chosen.seat].kongs++;
emit(state, { t: 'claim', seat: chosen.seat, from, type: 'kong', kind, kinds: [kind, kind, kind, kind] });
state.turn = chosen.seat;
state.lastDiscard = null;
drawReplacement(state);
@ -264,7 +375,9 @@ export function resolveClaims(state, intents) {
const [a, b] = c.tiles;
removeFromHand(p.hand, a, 1);
removeFromHand(p.hand, b, 1);
p.melds.push({ type: 'chow', kinds: [a, b, kind].sort((x, y) => x - y), concealed: false, from });
const kinds = [a, b, kind].sort((x, y) => x - y);
p.melds.push({ type: 'chow', kinds, concealed: false, from });
emit(state, { t: 'claim', seat: chosen.seat, from, type: 'chow', kind, kinds });
state.turn = chosen.seat;
state.drawnTile = null;
state.lastDiscard = null;
@ -281,16 +394,17 @@ export function selfActions(state) {
if (state.phase !== 'awaitDiscard') return res;
const p = state.players[state.turn];
const c = counts34(p.hand);
for (let k = 0; k < 34; k++) if (c[k] === 4) res.concealedKongs.push(k);
for (const m of p.melds) {
if (m.type === 'pung' && p.hand.includes(m.kinds[0])) res.addedKongs.push(m.kinds[0]);
const wallLeft = wallRemaining(state) > 0;
if (wallLeft) {
for (let k = 0; k < 34; k++) if (c[k] === 4) res.concealedKongs.push(k);
for (const m of p.melds) {
if (m.type === 'pung' && p.hand.includes(m.kinds[0])) res.addedKongs.push(m.kinds[0]);
}
}
if (state.drawnTile !== null) {
const need = 4 - p.melds.length;
if (isThirteenOrphans(c) && p.melds.length === 0) {
res.canWin = evaluateWin(state, state.turn, state.drawnTile, false).faan >= MIN_FAAN;
} else if (decompose(c, need).length > 0) {
res.canWin = evaluateWin(state, state.turn, state.drawnTile, false).faan >= MIN_FAAN;
if ((isThirteenOrphans(c) && p.melds.length === 0) || decompose(c, need).length > 0) {
res.canWin = evaluateWin(state, state.turn, state.drawnTile, false).faan >= state.opts.minFaan;
}
}
return res;
@ -298,9 +412,13 @@ export function selfActions(state) {
// Declare a concealed or added kong for the player on turn, then draw the
// replacement tile. (Exposed kongs of a discard go through resolveClaims.)
// An added kong may instead open a rob window (phase 'awaitRob') when the
// house rule is on and another player could win on that tile.
export function declareKong(state, { type, kind }) {
if (state.phase !== 'awaitDiscard') return false;
const p = state.players[state.turn];
if (wallRemaining(state) <= 0) return false;
const seat = state.turn;
const p = state.players[seat];
if (type === 'concealed') {
if (p.hand.filter((t) => t === kind).length !== 4) return false;
removeFromHand(p.hand, kind, 4);
@ -311,50 +429,96 @@ export function declareKong(state, { type, kind }) {
removeFromHand(p.hand, kind, 1);
m.type = 'kong';
m.kinds.push(kind);
m.added = true;
} else {
return false;
}
state.kongCount++;
state.stats[seat].kongs++;
state.drawnTile = null;
emit(state, { t: 'kong', seat, kind, kongType: type });
if (type === 'added' && state.opts.robKong) {
state.lastDiscard = { kind, from: seat, rob: true };
state.phase = 'awaitRob';
let robbable = false;
for (let s = 0; s < 4 && !robbable; s++) if (s !== seat && claimOptionsFor(state, s)?.win) robbable = true;
if (robbable) return true;
state.lastDiscard = null;
state.phase = 'awaitDiscard';
}
drawReplacement(state);
return true;
}
// Declare a win for `seat` — self-drawn or off the current discard. Applies
// payments and ends the hand.
// Declare a win for `seat` — self-drawn or off the current discard (or a
// robbed kong tile). Applies payments and ends the hand.
export function declareWin(state, seat, { byDiscard }) {
const winTile = byDiscard ? state.lastDiscard.kind : state.drawnTile;
const res = evaluateWin(state, seat, winTile, byDiscard);
const rob = byDiscard && !!state.lastDiscard.rob;
const discarder = byDiscard ? state.lastDiscard.from : null;
if (byDiscard) state.discards[discarder].pop();
if (byDiscard && !rob) state.discards[discarder].pop();
if (byDiscard) state.players[seat].hand.push(winTile); // the hand is shown whole
sortHand(state.players[seat].hand);
for (let s = 0; s < 4; s++) state.players[s].score += res.payments[s];
state.result = {
type: 'win', winner: seat, byDiscard, discarder, winTile,
faanList: res.faanList, faan: res.faan, base: res.base, payments: res.payments,
type: 'win', winner: seat, byDiscard, discarder, winTile, rob,
faanList: res.faanList, faan: res.faan, base: res.base, payments: res.payments, limit: res.limit,
};
const st = state.stats[seat];
st.wins++;
if (!byDiscard) st.selfDraws++;
else state.stats[discarder].dealIns++;
st.biggest = Math.max(st.biggest, res.faan);
state.lastDiscard = null;
state.drawnTile = null;
state.phase = 'handOver';
recordHand(state);
emit(state, { t: 'win', seat, byDiscard, from: discarder, kind: winTile, rob });
return state;
}
function recordHand(state) {
const r = state.result;
state.history.push({
hand: state.handNumber, dealer: state.dealer, roundWind: state.roundWind,
type: r.type, winner: r.winner ?? null, discarder: r.discarder ?? null, byDiscard: !!r.byDiscard,
faan: r.faan ?? 0, payments: r.payments ? r.payments.slice() : [0, 0, 0, 0],
scores: state.players.map((p) => p.score),
});
}
// Advance to the next hand. The dealer repeats after a dealer win or a drawn
// hand; otherwise the deal passes on, and once the fourth dealer's turn ends
// the round — and the session — is over.
// hand; otherwise the deal passes on. Once the fourth dealer's turn ends the
// wind round is over — and the session too, unless the house rules play on
// into the next prevailing wind.
export function startNextHand(state) {
if (state.phase !== 'handOver') return false;
if (willSessionEnd(state)) {
state.phase = 'gameOver';
state.winners = computeWinners(state);
emit(state, { t: 'gameOver', winners: state.winners.slice() });
return true;
}
const r = state.result;
const repeat = r.type === 'draw' || (r.type === 'win' && r.winner === state.dealer);
if (!repeat) {
if (state.dealer === 3) {
state.phase = 'gameOver';
state.winners = computeWinners(state);
return true;
}
state.dealer += 1;
if (state.dealer === 3) { state.dealer = 0; state.roundWind += 1; }
else state.dealer += 1;
}
state.handNumber += 1;
dealHand(state);
return true;
}
// Would startNextHand end the session (for "Next Hand" vs "Final Scores")?
export function willSessionEnd(state) {
if (state.phase !== 'handOver') return state.phase === 'gameOver';
const r = state.result;
const repeat = r.type === 'draw' || (r.type === 'win' && r.winner === state.dealer);
return !repeat && state.dealer === 3 && state.roundWind + 1 >= state.opts.rounds;
}
function computeWinners(state) {
let max = -Infinity;
state.players.forEach((p) => { if (p.score > max) max = p.score; });
@ -502,12 +666,13 @@ export function shanten(counts, meldCount = 0) {
const row = (id, times = 1) => {
const r = FAAN_BY_ID[id];
const out = [];
for (let i = 0; i < times; i++) out.push({ id: r.id, label: r.label, faan: r.faan });
for (let i = 0; i < times; i++) out.push({ id: r.id, label: r.label, faan: r.faan, limit: !!r.limit });
return out;
};
// Faan rows for one reading of the hand (concealed decomposition + melds).
function patternRows(dec, meldSets, seatWindKind, roundWindKind) {
// ctx: { seatWindKind, roundWindKind, winTile, byDiscard, melds }
function patternRows(dec, meldSets, ctx) {
const sets = dec.sets.concat(meldSets);
const rows = [];
@ -523,8 +688,17 @@ function patternRows(dec, meldSets, seatWindKind, roundWindKind) {
if (suits.size === 0) rows.push(...row('all-honors'));
else if (suits.size === 1) rows.push(...row(hasHonor ? 'mixed-one-suit' : 'pure-one-suit'));
const allPungs = sets.every((s) => s.type === 'pung');
if (sets.every((s) => s.type === 'chow') && isSuited(dec.pair)) rows.push(...row('common-hand'));
if (sets.every((s) => s.type === 'pung')) rows.push(...row('all-pungs'));
if (allPungs) rows.push(...row('all-pungs'));
// terminals & honors (pungs only — a chow always holds a middle tile)
if (allPungs) {
const allTerm = kinds.every((k) => isTerminal(k));
const termOrHonor = kinds.every((k) => isTerminal(k) || isHonor(k));
if (allTerm) rows.push(...row('all-terminals'));
else if (termOrHonor && suits.size > 0) rows.push(...row('mixed-terminals'));
}
const dragonPungs = sets.filter((s) => s.type === 'pung' && DRAGON_KINDS.includes(s.kind)).length;
const dragonPair = DRAGON_KINDS.includes(dec.pair);
@ -537,8 +711,15 @@ function patternRows(dec, meldSets, seatWindKind, roundWindKind) {
if (windPungKinds.length === 4) rows.push(...row('great-winds'));
else if (windPungKinds.length === 3 && windPair) rows.push(...row('small-winds'));
else {
if (windPungKinds.includes(seatWindKind)) rows.push(...row('seat-wind'));
if (windPungKinds.includes(roundWindKind)) rows.push(...row('round-wind'));
if (windPungKinds.includes(ctx.seatWindKind)) rows.push(...row('seat-wind'));
if (windPungKinds.includes(ctx.roundWindKind)) rows.push(...row('round-wind'));
}
// four kongs / four concealed pungs (a pung finished off a discard is
// exposed, so a discard win only counts when the discard made the pair)
if (ctx.melds.length === 4 && ctx.melds.every((m) => m.type === 'kong')) rows.push(...row('four-kongs'));
if (allPungs && ctx.melds.every((m) => m.concealed) && (!ctx.byDiscard || dec.pair === ctx.winTile)) {
rows.push(...row('four-concealed-pungs'));
}
return applyExcludes(rows);
}
@ -549,47 +730,92 @@ function applyExcludes(rows) {
return rows.filter((r) => !excluded.has(r.id));
}
// Nine Gates: concealed 1112345678999 of one suit plus one more of that suit.
export function isNineGates(counts) {
for (let s = 0; s < 3; s++) {
let total = 0;
for (let k = 0; k < 34; k++) if (counts[k] && Math.floor(k / 9) !== s) return false;
const need = [3, 1, 1, 1, 1, 1, 1, 1, 3];
let ok = true;
for (let r = 0; r < 9; r++) {
const c = counts[s * 9 + r];
if (c < need[r]) { ok = false; break; }
total += c;
}
if (ok && total === 14) return true;
}
return false;
}
// Score a completed hand for `seat`. winTile is added to the concealed hand
// for discard wins (it is already in the hand for self-draws). Returns
// { faanList, faan, base, payments } — payments is a zero-sum array of four
// score deltas: 2× base from the discarder, or 1× base from everyone on a
// self-draw.
// { faanList, faan, base, payments, limit } — payments is a zero-sum array of
// four score deltas: 2× base from the discarder, or 1× base from everyone on
// a self-draw. A limit hand scores the table's cap and nothing else.
export function evaluateWin(state, seat, winTile, byDiscard) {
const p = state.players[seat];
const o = state.opts ?? { minFaan: 1, faanCap: LIMIT_FAAN, bonusTiles: true };
const cap = o.faanCap ?? LIMIT_FAAN;
const counts = counts34(byDiscard ? p.hand.concat([winTile]) : p.hand);
const seatWindKind = WIND_KINDS[seatWindOf(state, seat)];
const roundWindKind = WIND_KINDS[state.roundWind];
const ctx = {
seatWindKind: WIND_KINDS[seatWindOf(state, seat)],
roundWindKind: WIND_KINDS[(state.roundWind ?? 0) % 4],
winTile, byDiscard, melds: p.melds,
};
const meldSets = p.melds.map((m) => ({ type: m.type === 'chow' ? 'chow' : 'pung', kind: m.kinds[0] }));
const rob = byDiscard && !!state.lastDiscard?.rob;
const wallOut = state.wallPos > state.wallEnd;
let bestRows = [];
let bestFaan = -1;
if (p.melds.length === 0 && isThirteenOrphans(counts)) {
bestRows = row('thirteen-orphans');
bestFaan = LIMIT_FAAN;
} else if (p.melds.length === 0 && isNineGates(counts)) {
bestRows = row('nine-gates');
bestFaan = LIMIT_FAAN;
} else {
for (const dec of decompose(counts, 4 - p.melds.length)) {
const rows = patternRows(dec, meldSets, seatWindKind, roundWindKind);
const total = rows.reduce((a, r) => a + r.faan, 0);
const rows = patternRows(dec, meldSets, ctx);
const total = rows.some((r) => r.limit) ? 1000 : rows.reduce((a, r) => a + r.faan, 0);
if (total > bestFaan) { bestFaan = total; bestRows = rows; }
}
if (bestFaan < 0) { bestFaan = 0; bestRows = []; } // defensive; callers check canWinWith
}
const faanList = bestRows.slice();
let faanList = bestRows.slice();
if (!byDiscard) faanList.push(...row('self-draw'));
if (p.melds.every((m) => m.concealed)) faanList.push(...row('concealed'));
if (!byDiscard && state.wallPos > state.wallEnd) faanList.push(...row('last-tile'));
if (!byDiscard && wallOut) faanList.push(...row('last-tile'));
if (byDiscard && wallOut && !rob) faanList.push(...row('last-discard'));
if (!byDiscard && state.lastDrawWasKongReplacement) faanList.push(...row('kong-draw'));
if (rob) faanList.push(...row('rob-kong'));
const seatWind = seatWindOf(state, seat);
const own = p.bonus.filter((b) => (b - FIRST_BONUS) % 4 === seatWind).length;
if (own > 0) faanList.push(...row('seat-flower', own));
if ([34, 35, 36, 37].every((k) => p.bonus.includes(k))) faanList.push(...row('flower-set'));
if ([38, 39, 40, 41].every((k) => p.bonus.includes(k))) faanList.push(...row('season-set'));
if (p.bonus.length === 0) faanList.push(...row('no-bonus'));
// heavenly / earthly hands (no claims or kongs yet this hand)
const untouched = (state.claimCount ?? 1) === 0 && (state.kongCount ?? 1) === 0;
if (untouched && !byDiscard && seat === state.dealer && state.discardCount === 0) faanList.push(...row('heavenly-hand'));
if (untouched && byDiscard && !rob && state.discardCount === 1 && state.lastDiscard?.from === state.dealer) {
faanList.push(...row('earthly-hand'));
}
const faan = Math.min(faanList.reduce((a, r) => a + r.faan, 0), LIMIT_FAAN);
const base = basePoints(faan);
if (o.bonusTiles !== false) {
const seatWind = seatWindOf(state, seat);
const own = p.bonus.filter((b) => (b - FIRST_BONUS) % 4 === seatWind).length;
if (own > 0) faanList.push(...row('seat-flower', own));
if ([34, 35, 36, 37].every((k) => p.bonus.includes(k))) faanList.push(...row('flower-set'));
if ([38, 39, 40, 41].every((k) => p.bonus.includes(k))) faanList.push(...row('season-set'));
if (p.bonus.length === 0) faanList.push(...row('no-bonus'));
}
const limitRow = faanList.find((r) => r.limit);
let faan;
if (limitRow) {
faanList = [{ ...limitRow, faan: cap }];
faan = cap;
} else {
faan = Math.min(faanList.reduce((a, r) => a + r.faan, 0), cap);
}
const base = basePoints(faan, cap);
const payments = [0, 0, 0, 0];
if (byDiscard) {
payments[seat] = 2 * base;
@ -598,5 +824,5 @@ export function evaluateWin(state, seat, winTile, byDiscard) {
payments[seat] = 3 * base;
for (let s = 0; s < 4; s++) if (s !== seat) payments[s] = -base;
}
return { faanList, faan, base, payments };
return { faanList, faan, base, payments, limit: !!limitRow };
}

View File

@ -0,0 +1,207 @@
// MahjongSound.js — tiny Web Audio synths for the parlour. No audio files;
// silent without Web Audio or when the game is muted.
//
// clack(scene) a tile laid down on the felt
// tap(scene) tile against tile (racking, stacking the wall)
// slap(scene) a claim slapped down ("Pung!")
// wash(scene, s) the face-down tiles swirled by four pairs of hands
// sticks(scene,n) scoring sticks / chips changing hands
// chime(scene) somebody wins (pentatonic bells)
// gong(scene) the session's last hand
// tick(scene) a soft UI tick (helpers, toggles)
// Ambience rain on the window · the parlour's murmur (with other
// tables clacking far off) · a teacup now and then
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, { vol = 0.24, pitch = 1 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
const f = (2600 + Math.random() * 500) * pitch;
burst(ac, dest, t, f, { q: 4, vol: 1, d: 0.04 });
burst(ac, dest, t + 0.008, f * 1.7, { q: 6, vol: 0.45, d: 0.025 });
tone(ac, dest, t, 210 * pitch, { a: 0.5, d: 0.06, glide: 0.6 }); // the felt-damped table
});
}
export function tap(scene, { vol = 0.14 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
const f = 3400 + Math.random() * 700;
burst(ac, dest, t, f, { q: 7, vol: 1, d: 0.022 });
tone(ac, dest, t, 1850 + Math.random() * 200, { a: 0.25, d: 0.03 });
});
}
export function slap(scene, { vol = 0.4 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
tone(ac, dest, t, 130, { a: 1, d: 0.16, glide: 0.55 });
burst(ac, dest, t, 900, { q: 1.2, vol: 0.8, d: 0.07 });
for (let i = 0; i < 3; i++) burst(ac, dest, t + 0.01 + i * 0.018, 2800 + i * 300, { q: 5, vol: 0.5, d: 0.03 });
});
}
export function wash(scene, secs = 1.8, { vol = 0.2 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t0 = ac.currentTime + 0.01;
const n = ac.createBufferSource(); n.buffer = noise(ac); n.loop = true;
const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 1500; bp.Q.value = 0.7;
const g = ac.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(0.22, t0 + 0.25);
g.gain.setValueAtTime(0.22, t0 + secs - 0.35);
g.gain.linearRampToValueAtTime(0, t0 + secs);
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0); n.stop(t0 + secs + 0.05);
const clicks = Math.round(secs * 46);
for (let i = 0; i < clicks; i++) {
const t = t0 + Math.random() * secs;
burst(ac, dest, t, 2200 + Math.random() * 2600, { q: 5, vol: 0.2 + Math.random() * 0.55, d: 0.022 });
}
});
}
export function sticks(scene, n = 4, { vol = 0.16 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t0 = ac.currentTime + 0.01;
for (let i = 0; i < Math.min(12, n); i++) {
const t = t0 + i * 0.06 + Math.random() * 0.02;
burst(ac, dest, t, 1700 + Math.random() * 900, { q: 3, vol: 0.9, d: 0.04 });
tone(ac, dest, t, 600 + Math.random() * 200, { a: 0.2, d: 0.05 });
}
});
}
export function chime(scene, { vol = 0.09 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
// a pentatonic run: G A C D E G
[392, 440, 523, 587, 659, 784].forEach((f, i) => {
tone(ac, dest, t + i * 0.09, f, { a: 0.9, d: 1.1 });
tone(ac, dest, t + i * 0.09, f * 2.01, { a: 0.18, d: 0.6 });
});
});
}
export function gong(scene, { vol = 0.12 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
for (const [f, a, d] of [[98, 1, 3.2], [147, 0.5, 2.6], [196, 0.35, 2.2], [261, 0.2, 1.8], [329, 0.12, 1.4]]) {
tone(ac, dest, t, f, { a, d, glide: 0.985, attack: 0.02 });
}
burst(ac, dest, t, 500, { q: 0.8, vol: 0.4, d: 0.3 });
});
}
export function tick(scene, { vol = 0.06 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => { const dest = out(scene, ac, vol); tone(ac, dest, ac.currentTime + 0.003, 1400, { a: 0.8, d: 0.05 }); });
}
/** Parlour ambience. Each layer can be switched. */
export class Ambience {
constructor(scene) { this.scene = scene; this.timers = []; this.loops = []; this.on = { rain: false, murmur: 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.rain) {
this.loop({ type: 'highpass', f: 1800, q: 0.5, gain: 0.012 });
this.loop({ type: 'lowpass', f: 420, q: 0.6, gain: 0.01 });
this.timers.push(setInterval(() => {
const ac = ctxOf(s); if (!ac) return;
safe(() => {
const d = out(s, ac, 0.02), t = ac.currentTime + 0.01;
for (let i = 0; i < 3; i++) if (Math.random() < 0.6) burst(ac, d, t + Math.random() * 0.4, 3000 + Math.random() * 3000, { q: 8, vol: 0.6, d: 0.015 });
});
}, 420));
}
if (this.on.murmur) {
this.loop({ type: 'bandpass', f: 520, q: 1.6, gain: 0.014, lfo: 0.13 });
// other tables: a clack, a wash, a laugh-like burst now and then
this.timers.push(setInterval(() => {
const ac = ctxOf(s); if (!ac) return;
safe(() => {
const d = out(s, ac, 0.035), t = ac.currentTime + 0.01;
const r = Math.random();
if (r < 0.55) burst(ac, d, t, 2400 + Math.random() * 800, { q: 5, vol: 0.5, d: 0.03 });
else if (r < 0.62) for (let i = 0; i < 20; i++) burst(ac, d, t + Math.random() * 1.2, 2000 + Math.random() * 2000, { q: 5, vol: 0.25, d: 0.02 });
else if (r < 0.66) tone(ac, d, t, 2600, { a: 0.25, d: 0.5 }); // a teacup set on its saucer
});
}, 1600));
}
}
loop({ type, f, q, gain, lfo = 0 }) {
const ac = ctxOf(this.scene); if (!ac) return;
try {
const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true;
const fl = ac.createBiquadFilter(); fl.type = type; fl.frequency.value = f; fl.Q.value = q;
const g = ac.createGain(); g.gain.value = gain;
let osc = null;
if (lfo) {
osc = ac.createOscillator(); osc.frequency.value = lfo;
const lg = ac.createGain(); lg.gain.value = gain * 0.6;
osc.connect(lg); lg.connect(g.gain); osc.start();
}
const base = out(this.scene, ac, 1);
src.connect(fl); fl.connect(g); g.connect(base);
src.start();
this.loops.push({ src, osc, base });
} catch (_) { /* no audio */ }
}
stop() {
this.timers.forEach(clearInterval);
this.timers = [];
for (const l of this.loops) { try { l.src.stop(); l.osc?.stop(); l.base.disconnect(); } catch (_) { /* gone */ } }
this.loops = [];
}
}

View File

@ -0,0 +1,169 @@
// MahjongTiles.js — one persistent sprite (plus soft shadow) per physical
// tile, keyed by its wall index for the hand. Tiles are never redrawn: they
// slide, lift, flip and clack between the wall, the racks, the rivers and
// the melds.
//
// const ts = new TileSprites(scene)
// ts.ensure(n) — make sure n sprites exist
// ts.set(id, pose) — snap
// await ts.move(id, pose, { dur, lift, delay, ease, flipAt })
// ts.hide(id) / ts.halt(id)
//
// A pose is { x, y, sx, sy, key, frame, ox, oy, depth, alpha, shadow } —
// everything needed to draw the tile; MahjongGame builds poses from
// MahjongLayout. Awaited moves are always released (halt resolves them), so
// a re-layout can never leave the turn driver hanging.
import * as Phaser from 'phaser';
const SH = { dx: 4, dy: 7 };
export class TileSprites {
constructor(scene) {
this.scene = scene;
this.items = [];
}
ensure(n) {
while (this.items.length < n) {
const s = this.scene;
const shadow = s.add.image(0, 0, 'mj-shadow').setVisible(false);
const img = s.add.image(0, 0, 'mj-flat-p', 'back').setVisible(false);
this.items.push({ img, shadow, p: null, tween: null, done: null, lift: 0, sq: 1 });
}
}
get(id) { return this.items[id]; }
halt(id) {
const it = this.items[id];
if (!it) return;
if (it.tween) { it.tween.stop(); it.tween = null; }
if (it.hoverTween) { it.hoverTween.stop(); it.hoverTween = null; }
const done = it.done;
it.done = null;
done?.();
}
haltAll() { for (let i = 0; i < this.items.length; i++) this.halt(i); }
apply(it) {
const p = it.p;
if (!p) return;
const img = it.img;
if (img.texture.key !== p.key || img.frame.name !== p.frame) img.setTexture(p.key, p.frame);
img.setOrigin(p.ox ?? 0.5, p.oy ?? 0.5);
img.setPosition(p.x, p.y - it.lift).setScale(p.sx, p.sy * it.sq).setAlpha(p.alpha ?? 1).setRotation(p.rot ?? 0);
img.setDepth(p.depth + (it.lift > 0.5 ? 200 : 0));
const sh = it.shadow;
if (p.shadow === false || !img.visible) { sh.setVisible(false); return; }
sh.setVisible(true);
const fw = img.frame.width * p.sx, fh = (p.shadowH ?? img.frame.height) * p.sy;
const k = 1 + it.lift * 0.004;
const off = 1 + it.lift * 0.06;
const cy = p.y + (p.shadowDy ?? 0);
sh.setPosition(p.x + SH.dx * off * (p.s ?? 1), cy + SH.dy * off * (p.s ?? 1))
.setScale((fw / 52) * k * 1.05, (fh / 52) * k * 1.05)
.setAlpha(Math.max(0.18, (p.shadowA ?? 0.55) - it.lift * 0.004))
.setDepth(p.depth - 0.5 + (it.lift > 0.5 ? 200 : 0));
}
set(id, pose) {
const it = this.items[id];
if (!it) return null;
this.halt(id);
it.p = { ...pose };
it.lift = 0; it.sq = 1;
const vis = pose.visible !== false;
it.img.setVisible(vis);
this.apply(it);
if (!vis) it.shadow.setVisible(false);
return it;
}
// Tween to a pose. If the texture/frame changes, the tile turns over at
// `flipAt` (0…1) with a squash — a flip on the way to its new spot.
move(id, pose, { dur = 380, lift = 0, delay = 0, ease = 'Cubic.InOut', flipAt = 0.5, onLand = null } = {}) {
const it = this.items[id];
if (!it) return Promise.resolve();
this.halt(id);
if (!it.p || dur <= 0) { this.set(id, pose); onLand?.(); return Promise.resolve(); }
it.img.setVisible(true);
const from = { ...it.p };
const to = { ...pose };
const changes = from.key !== to.key || from.frame !== to.frame;
let flipped = !changes;
const lerp = Phaser.Math.Linear;
return new Promise((resolve) => {
it.done = resolve;
const prog = { t: 0 };
it.tween = this.scene.tweens.add({
targets: prog, t: 1, duration: dur, delay, ease,
onUpdate: () => {
const t = prog.t;
const base = flipped ? to : from;
it.p = {
...base,
x: lerp(from.x, to.x, t), y: lerp(from.y, to.y, t),
sx: lerp(from.sx, to.sx, t), sy: lerp(from.sy, to.sy, t),
depth: t < 0.5 ? Math.max(from.depth, to.depth) : to.depth,
alpha: lerp(from.alpha ?? 1, to.alpha ?? 1, t),
s: lerp(from.s ?? 1, to.s ?? 1, t),
rot: lerp(from.rot ?? 0, to.rot ?? 0, t),
};
it.lift = lift * Math.sin(Math.PI * t);
if (changes) {
const w = 0.18;
const d = Math.abs(t - flipAt);
it.sq = d < w ? Math.max(0.05, d / w) : 1;
if (!flipped && t >= flipAt) { flipped = true; it.p = { ...it.p, key: to.key, frame: to.frame, ox: to.ox, oy: to.oy, shadow: to.shadow, shadowH: to.shadowH, shadowDy: to.shadowDy }; }
}
this.apply(it);
},
onComplete: () => {
it.tween = null;
it.p = to; it.lift = 0; it.sq = 1;
this.apply(it);
if (to.visible === false) { it.img.setVisible(false); it.shadow.setVisible(false); }
it.done = null;
onLand?.();
resolve();
},
});
});
}
hide(id) {
const it = this.items[id];
if (!it) return;
this.halt(id);
it.img.setVisible(false); it.shadow.setVisible(false);
}
hideAll() { for (let i = 0; i < this.items.length; i++) this.hide(i); }
// Raise/lower a resting tile in place (hover / selection).
hover(id, lift, dur = 110) {
const it = this.items[id];
if (!it || it.tween || !it.p) return;
it.hoverTween?.stop();
const prog = { l: it.lift };
it.hoverTween = this.scene.tweens.add({
targets: prog, l: lift, duration: dur, ease: 'Quad.Out',
onUpdate: () => { it.lift = prog.l; this.apply(it); },
onComplete: () => { it.hoverTween = null; },
});
}
setTint(id, tint) {
const it = this.items[id];
if (!it) return;
if (tint == null) it.img.clearTint(); else it.img.setTint(tint);
}
bounds(id) {
const it = this.items[id];
if (!it?.p || !it.img.visible) return null;
return it.img.getBounds();
}
}

View File

@ -59,16 +59,19 @@ Here are some of the highlights:
| Pure One Suit | 6 |
| Small Winds | 6 |
| Great Dragons | 8 |
| Great Winds / All Honors / Thirteen Orphans | 13 (limit) |
| Great Winds / All Honors / Thirteen Orphans | limit |
| Nine Gates / All Terminals / Four Kongs | limit |
| Four Concealed Pungs / Heavenly Hand / Earthly Hand | limit |
Then there's the bonus faan that stacks on top: Dragon pungs are 1 each, punging your own seat wind or East (the round wind) is 1, winning by self-draw is 1, a fully concealed hand is 1, each Flower or Season matching your seat is 1, and having *no* bonus tiles at all is also 1. They all add up. A simple hand can quietly become a very expensive hand if you let it sit and ripen. Like me. Quietly. On my branch.
Then there's the bonus faan that stacks on top: Dragon pungs are 1 each, punging your own seat wind or the round wind (East, in the East round) is 1, winning by self-draw is 1, a fully concealed hand is 1, each Flower or Season matching your seat is 1, and having *no* bonus tiles at all is also 1. They all add up. A simple hand can quietly become a very expensive hand if you let it sit and ripen. Like me. Quietly. On my branch.
## Getting Paid
Faan converts to base points on a doubling scale: 1 faan = 2 points, 2 = 4, 3 = 8... capped at the 13-faan limit. It grows fast. I like that. I'm not doing anything, but the points are compounding.
Faan converts to base points on a doubling scale: 1 faan = 2 points, 2 = 4, 3 = 8... up to the limit (13 faan unless the house rules say otherwise). A limit hand scores the limit, full stop. Everyone sits down with 500 points, so you can watch your pile grow. Or shrink. No judgement. It grows fast. I like that. I'm not doing anything, but the points are compounding.
- **Win by discard** — the player who threw the winning tile pays you **double** the base. Alone. By themselves. It stings. Don't be that player.
- **Win by self-draw** — *everyone* pays you the base. Extremely satisfying. Maximum faan, maximum income, minimum effort. My favorite kind of win.
- **Robbing the kong** — if someone adds the fourth tile to their pung and it's the exact tile you're waiting on, you can snatch it and win. They pay. It's rude. It's legal. It's worth a faan.
## Jeff's Extremely Relaxed Strategy Notes
@ -84,6 +87,38 @@ Faan converts to base points on a doubling scale: 1 faan = 2 points, 2 = 4, 3 =
**6. Watch the dealer.** The dealer keeps the deal by winning. A dealer on a streak is a problem. Sometimes the smartest move is to finish a fast, cheap hand just to end the round and rotate the deal. Put out the fire. Move forward. Even slowly forward is forward.
## At the Parlour Table
Every hand starts the way it does at a real table, and honestly the ritual is my favorite part. Everyone **washes** the tiles face down: that clattery swirl. Then four walls get built, two tiles high. The dealer rolls **three dice**, counts around the table to pick whose wall gets broken, and counts stacks along it to find the break. Tiles are dealt in blocks of four, then one more each. Flowers get flipped and replaced. Then we play.
You can watch the wall shrink as the hand goes on. When it's getting thin, people slow down and think harder. The opponents do too: they throw a useless tile fast and take their time over a hard choice. If you're in a hurry, click during the deal to speed it up, or choose **Quick deal** or **Skip** in the Menu. I never skip it. Obviously.
Called sets go face up in front of the caller, with the claimed tile turned **sideways** toward the player who threw it. Real tables do that, so everyone remembers who fed whom.
## Table Helpers
Nobody learns mahjong alone. The **Helpers** button has a whole drawer of them, and the beginner set is switched on to start:
- **Ready indicator.** When you're one tile from winning, it tells you which tiles you're waiting on and how many are still out there. It also warns you if your hand has the right shape but not enough faan to count.
- **Tile names on hover.** Point at any tile.
- **Western corner numbers.** Little 1–9 and E/S/W/N marks in the corners, like a beginner's set.
- **Claim advisor.** When you can call a discard, a ★ marks the call a strong player would make, and it says why.
Want more? Turn on the **discard advisor** (green edges on your best throws), the **tile tracker** (how many of each tile are still unseen), **danger shading** (red under tiles likely to feed someone a win), the **hand compass** (which scoring patterns you're heading toward), **opponent reads**, and the **table log**. Or hit **Hint** (H) any time to ask the coach. That's the best opponent's brain, explaining itself.
**Undo** (Z) takes back your last discard. It turns the session into a practice game, which doesn't go into your history. No shame. I undo things constantly. Mostly naps.
## House Rules
The **Menu** has house rules for your next game. Play just the East round, East + South, or all four winds. Raise the minimum to 3 faan (a common club rule: bigger, slower hands). Change the limit, turn robbing the kong or the flowers off, and pick the starting stake. There are table settings too: opponent pace, whether the game stops for every possible call, a call timer, auto-sorting your rack, and the rain and parlour murmur.
## Controls
- **Click** a tile to pick it up. **Click it again** (or double-click, or drag it up onto the table) to discard. **Drag sideways** to rearrange your rack.
- **←/→** choose a tile, **Enter** discards it.
- **M** Mahjong, **K** Kong, **P** Pung, **C** Chow, **Space** Pass.
- **H** hint, **S** sort, **Z** undo, **Esc** menu.
## The AI Opponents
There are five skill levels. The low ones claim tiles carelessly and telegraph everything. The high ones pay attention, adjust their plans, and know exactly which tile you need — and they will not throw it. A skill-5 opponent has a lot of patience. Almost as much as me.

View File

@ -1,12 +1,19 @@
// Headless verification for Mahjong (Hong Kong style).
// node server/scripts/verifyMahjong.js
// node tools/verifyMahjong.js [--quick] [--ladder]
// Exits non-zero on any failure.
//
// 1. Tile catalog: 144-tile wall, label assets exist on disk.
// 2. Faan evaluator fixtures: known hands score the expected faan rows.
// 2. Faan evaluator fixtures: known hands score the expected faan rows,
// including limit hands, contextual faan and house-rule caps.
// 3. Payments: zero-sum, points ladder monotonic and capped.
// 4. AI self-play: full sessions with per-step invariants (tile conservation,
// hand sizes, legal claims, minimum faan, zero-sum scores, termination).
// 4. Robbing the kong: a forced scenario end to end.
// 5. Wall geometry: dice break, every stack holds exactly two tiles.
// 6. Advisor: waits, unseen counts and discard advice agree with brute force.
// 7. Layout: every slot lands on the table, rivers never overlap.
// 8. AI self-play under several house rules, with per-step invariants (tile
// conservation, hand sizes, legal claims, minimum faan, scores sum to the
// stakes, termination) AND the tile ledger checked against the engine.
// 9. (--ladder) skill ladder: 3 beats 2 beats 1 over mirrored seats.
import fs from 'node:fs';
import path from 'node:path';
@ -23,6 +30,15 @@ import {
import {
chooseDiscard, chooseClaim, chooseSelfAction,
} from '../src/games/mahjong/MahjongAI.js';
import { Ledger } from '../src/games/mahjong/MahjongLedger.js';
import {
unseenCounts, waitsOf, discardAdvice, dangerMap, patternCompass, readTable,
} from '../src/games/mahjong/MahjongAdvisor.js';
import * as Lay from '../src/games/mahjong/MahjongLayout.js';
import { stackOfIndex, wallRemaining } from '../src/games/mahjong/MahjongLogic.js';
const QUICK = process.argv.includes('--quick');
const LADDER = process.argv.includes('--ladder');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const IMG_DIR = path.join(__dirname, '../assets/images/mahjong');
@ -57,7 +73,7 @@ console.log(' ok');
// Build a minimal state around one player's completed hand. For discard wins
// `hand` excludes the winning tile; for self-draws it includes it.
function fixtureState({ hand, melds = [], bonus = [], seat = 0, dealer = 0,
byDiscard, winTile, lastKong = false, wallEmpty = false }) {
byDiscard, winTile, lastKong = false, wallEmpty = false, opts, ctx = {}, from }) {
const players = [];
for (let s = 0; s < 4; s++) {
players.push({ name: `P${s + 1}`, seat: s, score: 0, skill: 3, isAI: s !== 0,
@ -68,7 +84,9 @@ function fixtureState({ hand, melds = [], bonus = [], seat = 0, dealer = 0,
players, dealer, roundWind: 0,
wallPos: wallEmpty ? 1 : 0, wallEnd: wallEmpty ? 0 : 90,
lastDrawWasKongReplacement: lastKong,
lastDiscard: byDiscard ? { kind: winTile, from: (seat + 1) % 4 } : null,
lastDiscard: byDiscard ? { kind: winTile, from: from ?? (seat + 1) % 4, rob: !!ctx.rob } : null,
opts: opts ?? { minFaan: 1, faanCap: 13, bonusTiles: true },
claimCount: ctx.claimCount ?? 3, kongCount: ctx.kongCount ?? 0, discardCount: ctx.discardCount ?? 9,
};
}
@ -91,10 +109,15 @@ checkFixture('thirteen orphans',
13, ['thirteen-orphans']);
checkFixture('pure one suit',
{ hand: [b(1), b(1), b(1), b(2), b(3), b(4), b(4), b(5), b(6), b(7), b(8), b(9), b(9)],
{ hand: [b(2), b(2), b(2), b(3), b(4), b(5), b(5), b(6), b(7), b(7), b(8), b(9), b(9)],
byDiscard: true, winTile: b(9) },
8, ['pure-one-suit', 'concealed', 'no-bonus'], ['mixed-one-suit']);
checkFixture('nine gates (limit replaces every other row)',
{ hand: [b(1), b(1), b(1), b(2), b(3), b(4), b(4), b(5), b(6), b(7), b(8), b(9), b(9)],
byDiscard: true, winTile: b(9) },
13, ['nine-gates'], ['pure-one-suit', 'concealed', 'no-bonus']);
checkFixture('mixed one suit + round wind',
{ hand: [c(1), c(2), c(3), c(4), c(5), c(6), c(7), c(8), c(9), E, E, R, R],
seat: 1, byDiscard: true, winTile: E },
@ -154,6 +177,48 @@ checkFixture('flowers: own + full set',
bonus: [34, 35, 36, 37], byDiscard: true, winTile: c(9) },
5, ['common-hand', 'concealed', 'seat-flower', 'flower-set'], ['no-bonus']);
const concealedKong = (k) => ({ type: 'kong', kinds: [k, k, k, k], concealed: true, from: null });
const exposedKong = (k) => ({ type: 'kong', kinds: [k, k, k, k], concealed: false, from: 1 });
checkFixture('all terminals (limit)',
{ hand: [b(1), b(1), b(1), b(9), b(9), b(9), c(1), c(1), c(1), ch(9), ch(9), ch(9), c(9)], byDiscard: true, winTile: c(9) },
13, ['all-terminals'], ['all-pungs', 'concealed']);
checkFixture('mixed terminals + all pungs',
{ hand: [b(1), b(1), b(1), c(9), c(9), c(9), N, N, N, S], melds: [exposedPung(ch(1))], seat: 2, byDiscard: true, winTile: S },
5, ['mixed-terminals', 'all-pungs', 'no-bonus'], ['all-terminals']);
checkFixture('four kongs (limit)',
{ hand: [c(5)], melds: [concealedKong(b(2)), exposedKong(b(7)), exposedKong(ch(3)), concealedKong(c(8))], byDiscard: true, winTile: c(5) },
13, ['four-kongs']);
checkFixture('four concealed pungs, self-drawn (limit)',
{ hand: [b(2), b(2), b(2), c(4), c(4), c(4), ch(6), ch(6), ch(6), b(8), b(8), b(8), c(1), c(1)], byDiscard: false, winTile: b(8) },
13, ['four-concealed-pungs']);
checkFixture('four concealed pungs on a discard needs the pair wait',
{ hand: [b(2), b(2), b(2), c(4), c(4), c(4), ch(6), ch(6), ch(6), b(8), b(8), b(8), c(1)], byDiscard: true, winTile: c(1) },
13, ['four-concealed-pungs']);
checkFixture('…but not when the discard completes a pung',
{ hand: [b(2), b(2), b(2), c(4), c(4), c(4), ch(6), ch(6), ch(6), b(8), b(8), c(1), c(1)], byDiscard: true, winTile: b(8) },
5, ['all-pungs', 'concealed', 'no-bonus'], ['four-concealed-pungs']);
checkFixture('heavenly hand',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9), c(9)], byDiscard: false, winTile: c(9),
ctx: { claimCount: 0, kongCount: 0, discardCount: 0 } },
13, ['heavenly-hand']);
checkFixture('earthly hand (dealer\'s first discard)',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], seat: 1, byDiscard: true, winTile: c(9), from: 0,
ctx: { claimCount: 0, kongCount: 0, discardCount: 1 } },
13, ['earthly-hand']);
checkFixture('robbing the kong is a faan',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], byDiscard: true, winTile: c(9), ctx: { rob: true } },
4, ['rob-kong', 'common-hand', 'concealed', 'no-bonus']);
checkFixture('last discard after the wall runs out',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], byDiscard: true, winTile: c(9), wallEmpty: true },
4, ['last-discard'], ['last-tile']);
checkFixture('a 10-faan cap makes a limit hand worth 10',
{ hand: [b(1), b(1), b(9), c(1), c(9), ch(1), ch(9), E, S, W, N, R, G, Wh], byDiscard: false, winTile: b(1), opts: { minFaan: 1, faanCap: 10, bonusTiles: true } },
10, ['thirteen-orphans']);
checkFixture('no flowers in play: no "no bonus" faan',
{ hand: [b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)], byDiscard: true, winTile: c(9), opts: { minFaan: 1, faanCap: 13, bonusTiles: false } },
2, ['common-hand', 'concealed'], ['no-bonus']);
// decomposer / shanten sanity
{
const tenpai = counts34([b(1), b(2), b(3), b(4), b(5), b(6), c(1), c(2), c(3), ch(4), ch(5), ch(6), c(9)]);
@ -178,9 +243,153 @@ for (let i = 1; i < BASE_POINTS.length; i++) {
}
console.log(' ok');
// ── 4. AI self-play ──────────────────────────────────────────────────────────
console.log('Self-play (40 sessions, mixed skills):');
// ── 4. Robbing the kong ──────────────────────────────────────────────────────
console.log('Robbing the kong:');
{
const st = createInitialState({ names: ['A', 'B', 'C', 'D'], seed: 4242 });
const sumBefore = st.players.reduce((a, p) => a + p.score, 0);
// seat 0 (on turn) holds an exposed pung of 5 Circle and the fourth copy;
// seat 1 is ready on 5 Circle (4-6 circle chow wait).
st.players[0].hand = [c(5), b(1), b(2), b(3), b(4), b(5), b(6), ch(1), ch(2), ch(3), E];
st.players[0].melds = [{ type: 'pung', kinds: [c(5), c(5), c(5)], concealed: false, from: 2 }];
st.players[1].hand = [c(4), c(6), b(7), b(8), b(9), ch(4), ch(5), ch(6), ch(7), ch(8), ch(9), S, S];
st.players[1].melds = [];
st.turn = 0; st.phase = 'awaitDiscard'; st.drawnTile = c(5);
const acts = selfActions(st);
check(acts.addedKongs.includes(c(5)), 'added kong not offered');
check(declareKong(st, { type: 'added', kind: c(5) }), 'added kong refused');
check(st.phase === 'awaitRob', `phase after a robbable kong is ${st.phase}`);
const o1 = claimOptionsFor(st, 1);
check(!!o1?.win && !o1.pung && !o1.chows.length, 'robber should be offered the win only');
check(!claimOptionsFor(st, 0), 'the kong owner cannot rob himself');
resolveClaims(st, [{ seat: 1, claim: { type: 'win' } }]);
check(st.phase === 'handOver' && st.result.winner === 1 && st.result.rob, 'rob did not win the hand');
check(st.result.faanList.some((r) => r.id === 'rob-kong'), 'rob-kong faan missing');
check(st.players[0].melds[0].type === 'pung' && st.players[0].melds[0].kinds.length === 3, 'robbed kong did not revert to a pung');
check(st.result.payments[0] < 0 && st.result.payments[2] === 0, 'the kong owner should pay alone');
check(st.players.reduce((a, p) => a + p.score, 0) === sumBefore, 'rob payments not zero-sum');
// with the house rule off the kong just stands
const st2 = createInitialState({ names: ['A', 'B', 'C', 'D'], seed: 4242, opts: { robKong: false } });
st2.players[0].hand = st.players[0].hand.slice(); st2.players[0].hand.push(c(5));
st2.players[0].hand = [c(5), b(1), b(2), b(3), b(4), b(5), b(6), ch(1), ch(2), ch(3), E];
st2.players[0].melds = [{ type: 'pung', kinds: [c(5), c(5), c(5)], concealed: false, from: 2 }];
st2.players[1].hand = [c(4), c(6), b(7), b(8), b(9), ch(4), ch(5), ch(6), ch(7), ch(8), ch(9), S, S];
st2.turn = 0; st2.phase = 'awaitDiscard'; st2.drawnTile = c(5);
declareKong(st2, { type: 'added', kind: c(5) });
check(st2.phase === 'awaitDiscard' || st2.phase === 'handOver', `robKong off: phase ${st2.phase}`);
}
console.log(` ${failures === 0 ? 'ok' : 'see failures above'}`);
// ── 5. Wall geometry ─────────────────────────────────────────────────────────
console.log('Wall geometry:');
for (const bonusTiles of [true, false]) {
for (let seed = 1; seed <= 30; seed++) {
const st = createInitialState({ seed, opts: { bonusTiles } });
const n = st.wall.length;
check(n === (bonusTiles ? 144 : 136), `wall length ${n}`);
check(st.stacks === n / 2, 'stack count');
const per = new Map();
for (let i = 0; i < n; i++) {
const info = stackOfIndex(st, i);
check(info.stack >= 0 && info.stack < st.stacks && info.j >= 0 && info.j < st.stacks / 4, `bad stack for ${i}`);
per.set(info.stack, (per.get(info.stack) ?? 0) + 1);
}
check(per.size === st.stacks && [...per.values()].every((v) => v === 2), 'every stack must hold two tiles');
const total = st.dice.reduce((a, d) => a + d, 0);
check(st.dice.every((d) => d >= 1 && d <= 6), 'dice out of range');
check(st.breakWall === (st.dealer + total - 1) % 4, 'wrong wall broken');
check(stackOfIndex(st, 0).stack === st.breakStack, 'first tile not at the break');
}
}
console.log(` ${failures === 0 ? 'ok' : 'see failures above'}`);
// ── 6. Advisor ───────────────────────────────────────────────────────────────
console.log('Advisor:');
{
let checked = 0;
for (let seed = 1; seed <= (QUICK ? 6 : 16); seed++) {
const st = createInitialState({ seed: 500 + seed, skills: { 0: 3, 1: 3, 2: 3, 3: 3 } });
for (let step = 0; step < 400 && st.phase !== 'handOver'; step++) {
if (st.phase === 'awaitDiscard') {
const seat = st.turn;
if (step % 5 === 0) {
const adv = discardAdvice(st, seat);
const p = st.players[seat];
for (const row of adv.slice(0, 4)) {
const cc = counts34(p.hand); cc[row.kind]--;
check(shanten(cc, p.melds.length) === row.shanten, `advice shanten wrong for kind ${row.kind}`);
check(row.danger >= 0 && row.danger <= 1, 'danger out of range');
}
for (let i = 1; i < adv.length; i++) check(adv[i - 1].shanten <= adv[i].shanten, 'advice not sorted by shanten');
const un = unseenCounts(st, seat);
check(un.every((x) => x >= 0 && x <= 4), 'unseen out of range');
const comp = patternCompass(st, seat);
check(comp.sure >= 0 && Array.isArray(comp.items), 'compass malformed');
check(readTable(st, seat).every((r) => r.threat >= 0 && r.threat <= 1), 'threat out of range');
check(dangerMap(st, seat).every((x) => x >= 0 && x <= 1), 'danger map out of range');
checked++;
}
const sa = chooseSelfAction(st, st.turn, selfActions(st), 3);
if (sa?.type === 'win') { declareWin(st, st.turn, { byDiscard: false }); break; }
if (sa?.type === 'kong') { declareKong(st, sa.spec); continue; }
discardTile(st, chooseDiscard(st, st.turn, 3));
continue;
}
// between turns: the waits helper must agree with winningTiles
for (let seat = 0; seat < 4; seat++) {
const p = st.players[seat];
if (p.hand.length !== 13 - 3 * p.melds.length) continue;
const w = waitsOf(st, seat).map((x) => x.kind).join();
check(w === winningTiles(p.hand, p.melds).join(), `waitsOf disagrees with winningTiles for seat ${seat}`);
}
const intents = [];
for (let seat = 0; seat < 4; seat++) {
const o = claimOptionsFor(st, seat);
if (o) { const cl = chooseClaim(st, seat, o, 3); if (cl) intents.push({ seat, claim: cl }); }
}
resolveClaims(st, intents);
}
}
console.log(` ${failures === 0 ? `ok (${checked} positions)` : 'see failures above'}`);
}
// ── 7. Layout ────────────────────────────────────────────────────────────────
console.log('Layout:');
{
const inTable = (p) => {
const q = Lay.unproject(p.x, p.y);
return Math.abs(q.x) <= 1.0 && Math.abs(q.z) <= 1.0;
};
const boxes = [];
for (let seat = 0; seat < 4; seat++) {
for (let i = 0; i < 24; i++) {
const p = Lay.riverPose(seat, i);
check(inTable(p), `river ${seat}/${i} off the table`);
// footprint in table space (screen boxes would be inflated by perspective)
const row = Math.min(3, Math.floor(i / Lay.RIVER_COLS)), col = row === 3 ? i - 18 : i % Lay.RIVER_COLS;
const w = Lay.world(seat, (col - (Lay.RIVER_COLS - 1) / 2) * (Lay.TW + Lay.GAP), Lay.RIVER_D0 + Lay.TD / 2 + row * (Lay.TD + Lay.GAP));
const hx = (seat % 2 ? Lay.TD : Lay.TW) / 2, hz = (seat % 2 ? Lay.TW : Lay.TD) / 2;
boxes.push({ seat, x0: w.x - hx, x1: w.x + hx, y0: w.z - hz, y1: w.z + hz });
}
for (let j = 0; j < 18; j++) check(inTable(Lay.wallTilePose(seat, j, 18, 0)), `wall ${seat}/${j} off the table`);
for (let i = 0; i < 14; i++) check(inTable(Lay.revealPose(seat, i, 14)), `reveal ${seat}/${i} off the table`);
}
// rivers of different seats never overlap (first 24 tiles each)
let overlaps = 0;
for (const a of boxes) for (const b2 of boxes) {
if (a.seat >= b2.seat) continue;
if (a.x0 < b2.x1 && b2.x0 < a.x1 && a.y0 < b2.y1 && b2.y0 < a.y1) overlaps++;
}
check(overlaps === 0, `${overlaps} river tiles overlap another seat's river`);
// your rack fits between the side panels
const rack = Lay.humanRack(Array.from({ length: 13 }, (_, i) => i), 13);
const xs = [...rack.values()].map((p) => p.x);
check(Math.min(...xs) - Lay.HAND.w / 2 > Lay.SEAT_PANELS[0].x + Lay.SEAT_PANELS[0].w, 'rack runs under your seat panel');
check(Math.max(...xs) + Lay.HAND.w / 2 < Lay.DOCK.x, 'rack runs under the dock');
}
console.log(` ${failures === 0 ? 'ok' : 'see failures above'}`);
// ── 8. AI self-play + ledger ─────────────────────────────────────────────────
function tileConservation(state) {
let total = state.wallEnd - state.wallPos + 1;
for (const p of state.players) {
@ -194,7 +403,7 @@ function tileConservation(state) {
function checkInvariants(state, tag) {
if (state.phase === 'handOver' || state.phase === 'gameOver') return;
const total = tileConservation(state);
check(total === 144, `${tag}: ${total} tiles accounted for, expected 144`);
check(total === state.wall.length, `${tag}: ${total} tiles accounted for, expected ${state.wall.length}`);
for (const p of state.players) {
const drawing = state.phase === 'awaitDiscard' && state.turn === p.seat;
const expected = (drawing ? 14 : 13) - 3 * p.melds.length;
@ -203,29 +412,55 @@ function checkInvariants(state, tag) {
}
}
function playSession(seed) {
const skills = { 0: 1 + (seed % 5), 1: 1 + ((seed >> 2) % 5), 2: 3, 3: 5 };
const state = createInitialState({ names: ['A', 'B', 'C', 'D'], skills, seed });
const dealersSeen = new Set();
let hands = 0, wins = 0, draws = 0, claims = 0, kongs = 0;
let guard = 100000;
const sortedJoin = (a) => a.slice().sort((x, y) => x - y).join();
function checkLedger(state, led, tag) {
for (let s = 0; s < 4; s++) {
const p = state.players[s];
if (sortedJoin(led.hand[s].map((id) => led.kindOf(id))) !== sortedJoin(p.hand)) { check(false, `${tag}: ledger hand ${s} differs`); return; }
if (led.river[s].map((id) => led.kindOf(id)).join() !== state.discards[s].join()) { check(false, `${tag}: ledger river ${s} differs`); return; }
if (sortedJoin(led.bonus[s].map((id) => led.kindOf(id))) !== sortedJoin(p.bonus)) { check(false, `${tag}: ledger bonus ${s} differs`); return; }
if (led.melds[s].length !== p.melds.length) { check(false, `${tag}: ledger melds ${s} differ`); return; }
led.melds[s].forEach((m, i) => {
check(sortedJoin(m.ids.map((id) => led.kindOf(id))) === sortedJoin(p.melds[i].kinds), `${tag}: meld ${s}/${i} kinds differ`);
});
}
if (state.phase !== 'handOver' && state.phase !== 'gameOver') {
check(led.wall.size === wallRemaining(state), `${tag}: ledger wall ${led.wall.size} vs ${wallRemaining(state)}`);
for (const id of led.wall) check(id >= state.wallPos && id <= state.wallEnd, `${tag}: id ${id} outside the live wall`);
}
}
function playSession(seed, opts, skillsIn) {
const skills = skillsIn ?? { 0: 1 + (seed % 5), 1: 1 + ((seed >> 2) % 5), 2: 3, 3: 5 };
const state = createInitialState({ names: ['A', 'B', 'C', 'D'], skills, seed, opts });
const led = new Ledger();
let li = 0;
const sync = (tag) => { while (li < state.log.length) led.apply(state.log[li++]); checkLedger(state, led, tag); };
const dealersSeen = new Set();
let hands = 0, wins = 0, draws = 0, claims = 0, kongs = 0, robs = 0;
let guard = 100000;
sync(`seed ${seed} start`);
while (!isGameOver(state) && guard-- > 0) {
checkInvariants(state, `seed ${seed} hand ${state.handNumber}`);
const tag = `seed ${seed} hand ${state.handNumber}`;
checkInvariants(state, tag);
if (state.phase === 'handOver') {
dealersSeen.add(state.dealer);
dealersSeen.add(`${state.roundWind}:${state.dealer}`);
hands++;
const r = state.result;
if (r.type === 'win') {
wins++;
check(r.faan >= MIN_FAAN, `seed ${seed}: win below minimum faan (${r.faan})`);
if (r.rob) robs++;
check(r.faan >= state.opts.minFaan, `seed ${seed}: win below minimum faan (${r.faan})`);
check(r.faan <= state.opts.faanCap, `seed ${seed}: win above the cap (${r.faan})`);
check(r.payments.reduce((a, x) => a + x, 0) === 0, `seed ${seed}: payments not zero-sum`);
check(led.winId != null && led.hand[r.winner].includes(led.winId), `seed ${seed}: ledger lost the winning tile`);
} else {
draws++;
}
const sum = state.players.reduce((a, p) => a + p.score, 0);
check(sum === 0, `seed ${seed}: cumulative scores sum to ${sum}, expected 0`);
check(sum === 4 * state.opts.stake, `seed ${seed}: cumulative scores sum to ${sum}, expected ${4 * state.opts.stake}`);
startNextHand(state);
sync(`${tag} next`);
continue;
}
if (state.phase === 'awaitDiscard') {
@ -236,19 +471,22 @@ function playSession(seed) {
if (sa?.type === 'win') {
check(acts.canWin, `seed ${seed}: AI declared an unoffered win`);
declareWin(state, seat, { byDiscard: false });
sync(`${tag} self-win`);
continue;
}
if (sa?.type === 'kong') {
kongs++;
check(declareKong(state, sa.spec), `seed ${seed}: illegal kong ${JSON.stringify(sa.spec)}`);
sync(`${tag} kong`);
continue;
}
const d = chooseDiscard(state, seat, p.skill);
check(p.hand.includes(d), `seed ${seed}: AI discarded unheld kind ${d}`);
discardTile(state, d);
sync(`${tag} discard`);
continue;
}
if (state.phase === 'awaitClaims') {
if (state.phase === 'awaitClaims' || state.phase === 'awaitRob') {
const from = state.lastDiscard.from;
const intents = [];
for (let seat = 0; seat < 4; seat++) {
@ -256,6 +494,7 @@ function playSession(seed) {
if (!options) continue;
check(seat !== from, `seed ${seed}: discarder offered a claim`);
if (options.chows.length) {
check(state.phase === 'awaitClaims', `seed ${seed}: chow offered on a robbable kong`);
check(seat === (from + 1) % 4, `seed ${seed}: chow offered to non-left seat`);
}
const claim = chooseClaim(state, seat, options, state.players[seat].skill);
@ -263,27 +502,76 @@ function playSession(seed) {
}
const { applied } = resolveClaims(state, intents);
if (applied && applied.claim.type !== 'win') claims++;
sync(`${tag} claims`);
continue;
}
check(false, `seed ${seed}: unknown phase ${state.phase}`);
break;
}
check(guard > 0, `seed ${seed}: session did not terminate`);
check(dealersSeen.size === 4 || guard <= 0, `seed ${seed}: only ${dealersSeen.size}/4 seats dealt`);
const rounds = state.opts.rounds;
check(dealersSeen.size >= 4 * rounds || guard <= 0, `seed ${seed}: only ${dealersSeen.size}/${4 * rounds} deals seen`);
check(getWinners(state).length >= 1, `seed ${seed}: no session winner`);
return { hands, wins, draws, claims, kongs };
check(state.history.length === hands, `seed ${seed}: history has ${state.history.length} rows for ${hands} hands`);
return { hands, wins, draws, claims, kongs, robs };
}
let tHands = 0, tWins = 0, tDraws = 0, tClaims = 0, tKongs = 0;
const t0 = Date.now();
for (let g = 0; g < 40; g++) {
const r = playSession(1000 + g * 7919);
tHands += r.hands; tWins += r.wins; tDraws += r.draws; tClaims += r.claims; tKongs += r.kongs;
const VARIANTS = [
['default rules', {}],
['minimum 3 faan, no flowers', { minFaan: 3, bonusTiles: false }],
['East + South, cap 10', { rounds: 2, faanCap: 10 }],
['no robbing, no stake, minimum 0', { robKong: false, stake: 0, minFaan: 0 }],
];
const PER = QUICK ? 4 : 12;
for (const [label, opts] of VARIANTS) {
console.log(`Self-play — ${label} (${PER} sessions, mixed skills):`);
let tHands = 0, tWins = 0, tDraws = 0, tClaims = 0, tKongs = 0, tRobs = 0;
const t0 = Date.now();
for (let g = 0; g < PER; g++) {
const r = playSession(1000 + g * 7919, opts);
tHands += r.hands; tWins += r.wins; tDraws += r.draws; tClaims += r.claims; tKongs += r.kongs; tRobs += r.robs;
}
const secs = ((Date.now() - t0) / 1000).toFixed(1);
console.log(` ${tHands} hands in ${secs}s — ${tWins} wins (${tRobs} robbed kongs), ${tDraws} drawn, ${tClaims} claims, ${tKongs} kongs`);
check(tWins > 0, `${label}: no hand was ever won`);
if (!opts.minFaan || opts.minFaan <= 1) check(tWins / Math.max(1, tHands) > 0.3, `${label}: only ${tWins}/${tHands} hands won`);
}
// ── 9. Skill ladder (optional, slow) ─────────────────────────────────────────
if (LADDER) {
console.log('Skill ladder (mirrored seats):');
const duel = (a, bSkill, sessions) => {
let delta = 0, hands = 0;
for (let g = 0; g < sessions; g++) {
for (let seat = 0; seat < 4; seat++) {
const skills = {};
for (let s2 = 0; s2 < 4; s2++) skills[s2] = s2 === seat ? a : bSkill;
const st = createInitialState({ names: ['A', 'B', 'C', 'D'], skills, seed: 77 + g * 104729 });
while (!isGameOver(st)) {
if (st.phase === 'handOver') { startNextHand(st); continue; }
if (st.phase === 'awaitDiscard') {
const sk = st.players[st.turn].skill;
const sa = chooseSelfAction(st, st.turn, selfActions(st), sk);
if (sa?.type === 'win') { declareWin(st, st.turn, { byDiscard: false }); continue; }
if (sa?.type === 'kong') { declareKong(st, sa.spec); continue; }
discardTile(st, chooseDiscard(st, st.turn, sk)); continue;
}
const ints = [];
for (let s2 = 0; s2 < 4; s2++) { const o = claimOptionsFor(st, s2); if (o) { const cl = chooseClaim(st, s2, o, st.players[s2].skill); if (cl) ints.push({ seat: s2, claim: cl }); } }
resolveClaims(st, ints);
}
delta += st.players[seat].score - st.opts.stake;
hands += st.history.length;
}
}
return delta / hands;
};
for (const [a, b2] of [[2, 1], [3, 2]]) {
const d = duel(a, b2, 10);
console.log(` skill ${a} vs three skill ${b2}: ${d >= 0 ? '+' : ''}${d.toFixed(2)} points per hand`);
check(d > 0, `skill ${a} should beat skill ${b2}`);
}
}
const secs = ((Date.now() - t0) / 1000).toFixed(1);
console.log(` ${tHands} hands over 40 sessions in ${secs}s — ${tWins} wins, ${tDraws} drawn, ${tClaims} claims, ${tKongs} kongs`);
check(tWins > 0, 'no hand was ever won — evaluator or AI suspect');
check(tWins / Math.max(1, tHands) > 0.3, `only ${tWins}/${tHands} hands won — too many goulash draws`);
if (failures) {
console.error(`\nFAILED: ${failures} check(s).`);