diff --git a/assets/videos/aiko-idle.mp4 b/assets/videos/aiko-idle.mp4 index c66f123..c47c2f2 100644 Binary files a/assets/videos/aiko-idle.mp4 and b/assets/videos/aiko-idle.mp4 differ diff --git a/src/games/mahjong/MahjongAI.js b/src/games/mahjong/MahjongAI.js index eea193e..8f4ec31 100644 --- a/src/games/mahjong/MahjongAI.js +++ b/src/games/mahjong/MahjongAI.js @@ -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 }; +} diff --git a/src/games/mahjong/MahjongAdvisor.js b/src/games/mahjong/MahjongAdvisor.js new file mode 100644 index 0000000..0f15d5b --- /dev/null +++ b/src/games/mahjong/MahjongAdvisor.js @@ -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 }; +} diff --git a/src/games/mahjong/MahjongArt.js b/src/games/mahjong/MahjongArt.js new file mode 100644 index 0000000..38163b1 --- /dev/null +++ b/src/games/mahjong/MahjongArt.js @@ -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-`, `2-`, `back`) +// mj-flat-l atlas: lying tiles, landscape (frames `1-`, `3-`, `back`) +// mj-hand atlas: your standing tiles (frames ``, `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-x +// +// 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-x (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' }; +} diff --git a/src/games/mahjong/MahjongData.js b/src/games/mahjong/MahjongData.js index 00fc515..3a36a42 100644 --- a/src/games/mahjong/MahjongData.js +++ b/src/games/mahjong/MahjongData.js @@ -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. diff --git a/src/games/mahjong/MahjongDialogs.js b/src/games/mahjong/MahjongDialogs.js new file mode 100644 index 0000000..0153899 --- /dev/null +++ b/src/games/mahjong/MahjongDialogs.js @@ -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]; } diff --git a/src/games/mahjong/MahjongEndScreen.js b/src/games/mahjong/MahjongEndScreen.js new file mode 100644 index 0000000..59cfd0b --- /dev/null +++ b/src/games/mahjong/MahjongEndScreen.js @@ -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 }; +} diff --git a/src/games/mahjong/MahjongGame.js b/src/games/mahjong/MahjongGame.js index 1056427..e630850 100644 --- a/src/games/mahjong/MahjongGame.js +++ b/src/games/mahjong/MahjongGame.js @@ -1,809 +1,1453 @@ +// MahjongGame.js — "An evening at the mahjong parlour". The scene only +// orchestrates: rules in MahjongLogic, opponents in MahjongAI, table sense +// in MahjongAdvisor, which physical tile is which in MahjongLedger, geometry +// in MahjongLayout, the 144 tile sprites in MahjongTiles, the furniture in +// MahjongHud / MahjongDialogs / MahjongEndScreen. +// +// Flow per hand: wash the tiles → build the four walls → the dealer rolls +// three dice and breaks the wall → deal in blocks of four → flowers revealed +// and replaced → turns (draw, think, discard; anyone may call the discard) → +// someone goes out (or the wall runs dry) → hands knocked down, the scoring +// slip, points change hands → next hand … → the evening's reckoning. +// +// Every engine change is appended to gs.log; pump() replays new events +// through the ledger and animates them, so the table is always exactly the +// engine's state — just with the tiles travelling there. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; import { getGameSoundtrack } from '../../services/soundtrack.js'; +import { aiTiming, clampSkill } from '../../ui/cardtable/AITiming.js'; +import { Die3D, planTrayThrow, poseFromPlan, restingQ } from '../../ui/dice/Dice3D.js'; +import { TILES, WIND_NAMES, isSuited, rankOf, SUIT_NAMES } from './MahjongData.js'; import { - TILES, SUIT_NAMES, WIND_NAMES, rankOf, isSuited, - FAAN_TABLE, MIN_FAAN, PLAYER_COLOR_HEX, -} from './MahjongData.js'; -import { - createInitialState, discardTile, claimOptionsFor, resolveClaims, - selfActions, declareKong, declareWin, startNextHand, - isGameOver, getWinners, seatWindOf, + createInitialState, discardTile, claimOptionsFor, resolveClaims, selfActions, declareKong, declareWin, + startNextHand, getWinners, stackOfIndex, wallRemaining, cloneState, willSessionEnd, counts34, shanten, } from './MahjongLogic.js'; import { - chooseDiscard, chooseSelfAction, collectAIClaims, nextThinkDelay, + chooseDiscardDetailed, chooseSelfAction, collectAIClaims, coachDiscard, coachClaim, coachSelf, } from './MahjongAI.js'; +import { + unseenCounts, waitsOf, discardAdvice, dangerMap, patternCompass, readTable, describeRead, +} from './MahjongAdvisor.js'; +import { Ledger } from './MahjongLedger.js'; +import * as Lay from './MahjongLayout.js'; +import { prepareMahjongArt, bakeTiles, flatFrame, HAND_TEX, DISPLAY_FONT, SERIF, SEAT } from './MahjongArt.js'; +import { TileSprites } from './MahjongTiles.js'; +import { Hud } from './MahjongHud.js'; +import { openMenu, openHelpers, confirmBox, tipCard, openHandSlip, HELPER_PRESETS } from './MahjongDialogs.js'; +import { openEndScreen } from './MahjongEndScreen.js'; +import * as Snd from './MahjongSound.js'; -// Deep-green felt with ivory tiles — same table look as Mahjong Match. -const FELT = 0x0e2a1c; -const FACE = 0xf6efdb; -const FACE_EDGE = 0x8d7c52; -const SIDE = 0xb59c66; -const DRAGON_BLUE = 0x3f6bb5; -const BACK_FACE = 0x2e6e4e; -const BACK_INSET = 0x3f8a63; - -// Label art is 128×178; keep its aspect when fitting it onto a tile face. -const LABEL_W = 128; -const LABEL_H = 178; - -// ── layout ──────────────────────────────────────────────────────────────────── -const HAND_Y = 975, HAND_TW = 76, HAND_TH = 104, HAND_STEP = 80; -const SM_W = 44, SM_H = 60; // opponent backs, melds, modal tiles -const RIV_W = 42, RIV_H = 58; // discard rivers - -// per-seat river grids: 8 per row, growing toward the table centre -const RIVERS = [ - { cx: 960, y0: 652, dy: 64 }, // seat 0 — bottom - { cx: 1320, y0: 412, dy: 64 }, // seat 1 — right - { cx: 960, y0: 198, dy: 64 }, // seat 2 — top - { cx: 600, y0: 412, dy: 64 }, // seat 3 — left -]; - -const CLAIM_Y = 820; -const REF_W = 430; - -const DEPTH = { - bg: -2, panel: 0, text: 2, tiles: 5, ui: 20, claims: 30, toast: 55, ref: 60, modal: 70, +const SETTINGS_KEY = 'mahjong-settings'; +const TIPS_KEY = 'mahjong-tips'; +const DEFAULT_SETTINGS = { + pace: 'normal', intro: 'full', claimPrompt: 'all', claimTimer: 0, autoSort: true, + revealHands: true, tells: true, rain: true, murmur: true, + rounds: 1, minFaan: 1, faanCap: 13, robKong: true, bonusTiles: true, stake: 500, + helpers: { ...HELPER_PRESETS.learner }, }; +const RULE_KEYS = ['rounds', 'minFaan', 'faanCap', 'robKong', 'bonusTiles', 'stake']; +const PACE = { relaxed: 1.35, normal: 1, brisk: 0.6 }; +const D = { room: 0, table: 2, lamp: 4, compass: 6, glowUnder: 90, hand: 300, dice: 260, fx: 290, hud: 400, tooltip: 600, tip: 480, modal: 520 }; // tooltip sits above lifted rack tiles (hand + 200) +const HUMAN = 0; +const nm = (k) => TILES[k].name; +const pick = (a) => a[Math.floor(Math.random() * a.length)]; -const tileName = (k) => TILES[k].name; +const SPEECH = { + pung: ['Pung!', 'I\'ll take that.', 'Thank you kindly.', 'Mine!'], + chow: ['Chow.', 'That fits nicely.', 'Thank you.'], + kong: ['Kong!', 'Four of a kind!'], + win: ['Sik wu!', 'Mahjong!', 'That\'s the one!', 'Read \'em and weep.'], + dealtIn: ['Oh no…', 'Of course it was that tile.', 'Aiya.', 'I should have kept it.'], + ready: ['*sips tea calmly*', 'Hmm.', '*straightens tiles*', 'Mm-hm.'], + late: ['Not many tiles left…', 'Wall\'s getting thin.', 'Come on, come on…'], + flower: ['A flower!', 'Ooh, a flower.'], + bad: ['*sighs*', 'Hmph.', 'Useless.'], +}; export default class MahjongGame extends Phaser.Scene { constructor() { super('MahjongGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - - this.humanSeat = 0; + this.initData = data ?? {}; + this.gameDef = this.initData.game; + this.opponents = (this.initData.opponents ?? []).slice(0, 3); + this.playfield = this.initData.playfield ?? null; + this.ended = false; this.driving = false; - this.gameOverShown = false; - this.humanCanDiscard = false; - this.sel = null; // selected hand tile { c, baseY } - this.handTiles = []; + this.modal = null; + this.humanTurn = false; this.claimResolve = null; - this.kongSpecs = []; - this.chowOptions = []; - this.portraitCtrls = []; - this.refOpen = false; + this.order = []; + this.drawnId = null; + this.sel = null; + this.press = null; + this.drag = null; + this.preferId = null; + this.revealed = [false, false, false, false]; + this.humanFaceUp = false; + this.snaps = []; + this.practice = false; + this.logLines = []; + this.lastClick = { id: null, t: 0 }; + this.saidLate = false; + this.wasReady = [false, false, false, false]; + this.slip = null; + this.ff = false; + try { + const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + this.settings = { ...DEFAULT_SETTINGS, ...saved, helpers: { ...DEFAULT_SETTINGS.helpers, ...(saved.helpers ?? {}) } }; + } catch (_) { this.settings = { ...DEFAULT_SETTINGS, helpers: { ...DEFAULT_SETTINGS.helpers } }; } + try { this.tipsSeen = new Set(JSON.parse(localStorage.getItem(TIPS_KEY) || '[]')); } catch (_) { this.tipsSeen = new Set(); } } + get H() { return this.settings.helpers; } + get k() { return PACE[this.settings.pace] ?? 1; } + // ritual speed: the pace, faster on 'quick', much faster when clicked through + get rk() { return this.k * (this.settings.intro === 'quick' ? 0.55 : 1) * (this.ff ? 0.3 : 1); } + // the deal itself: unhurried on the full ritual, brisk otherwise + get dk() { return this.k * ({ full: 1, quick: 0.45, off: 0.22 }[this.settings.intro] ?? 1) * (this.ff ? 0.25 : 1); } + + saveSettings() { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } } + create() { try { const { tracks, volume } = getGameSoundtrack(this); if (tracks.length) new MusicPlayer(this, tracks, volume); - } catch { /* optional */ } - // Backdrop: the playfield chosen on the opponent-select screen (image - // texture, or the generated canvas texture for the "colored" playfields), - // falling back to its flat color and finally to the classic deep green. + } catch (_) { /* optional */ } + this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x140806).setDepth(-5); + this.names = [auth.user?.username ?? 'You']; + this.skills = [5]; + this.oppOf = [null]; + for (let seat = 1; seat < 4; seat++) { + const o = this.opponents[seat - 1] ?? { id: `bot${seat}`, name: `Guest ${seat}` }; + this.oppOf.push(o); + this.names.push(o.name ?? `Player ${seat + 1}`); + this.skills.push(clampSkill(o.skill ?? 3)); + } + const opts = Object.fromEntries(RULE_KEYS.map((k) => [k, this.settings[k]])); + this.gs = createInitialState({ names: this.names, skills: Object.fromEntries(this.skills.map((s, i) => [i, s])), opts }); + this.ledger = new Ledger(); + this.logIdx = 0; + prepareMahjongArt(this, { indices: !!this.H.indices }).then(() => { + if (!this.sys.isActive()) return; + this.build(); + this.time.delayedCall(250, () => this.advance()); + }); + } + + // ── build ─────────────────────────────────────────────────────────────────── + build() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(DEPTH.bg); + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.room); } else { - const color = pf?.fallbackColor ? parseInt(pf.fallbackColor.replace('#', ''), 16) : FELT; - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, color).setDepth(DEPTH.bg); + this.add.image(0, 0, 'mj-room').setOrigin(0).setDepth(D.room); } + this.add.image(0, 0, 'mj-table').setOrigin(0).setDepth(D.table); + const lampP = Lay.project(0, -0.05); + this.lamp = this.add.image(lampP.x, lampP.y, 'mj-lamp').setScale(1.9, 1.5).setBlendMode(Phaser.BlendModes.ADD).setDepth(D.lamp).setAlpha(0.85); + this.tweens.add({ targets: this.lamp, alpha: { from: 0.78, to: 0.92 }, duration: 3800, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.add.image(0, 0, 'mj-vignette').setOrigin(0).setDepth(D.fx + 5).setAlpha(0.9); + this.buildAmbientFx(); - const names = [auth.user?.username ?? 'You']; - const skills = { 0: 5 }; - for (let seat = 1; seat < 4; seat++) { - const opp = this.opponents[seat - 1]; - names.push(opp?.name ?? `Player ${seat + 1}`); - skills[seat] = Math.max(1, Math.min(5, opp?.skill ?? 3)); - } - this.gs = createInitialState({ names, skills }); + // compass (seat-wind glyphs that turn with the deal) and the turn glow + this.compassG = this.add.graphics().setDepth(D.compass); + this.compassGlyphs = [0, 1, 2, 3].map(() => this.add.image(0, 0, 'mahjong-pinyin4').setDepth(D.compass + 1)); + const cc = Lay.project(0, 0.075); + this.wallText = this.add.text(cc.x, cc.y + 6, '', { fontFamily: DISPLAY_FONT, fontSize: '15px', color: '#f0c25a' }).setOrigin(0.5).setDepth(D.compass + 1).setAlpha(0.85); - this.dyn = this.add.container(0, 0).setDepth(DEPTH.tiles); - this.buildScoreboard(); - this.buildPortraits(); - this.buildCentreTexts(); - this.buildActionButtons(); - this.buildReferencePanel(); + this.ts = new TileSprites(this); + this.ts.ensure(144); + this.liveGlow = this.add.image(0, 0, 'mj-glow').setDepth(D.glowUnder).setVisible(false).setBlendMode(Phaser.BlendModes.ADD); + this.tweens.add({ targets: this.liveGlow, alpha: { from: 0.55, to: 1 }, duration: 520, yoyo: true, repeat: -1 }); + this.rackG = this.add.graphics().setDepth(D.hand - 1); + this.fxG = this.add.graphics().setDepth(D.fx); + this.dice = [0, 1, 2].map(() => new Die3D(this, D.dice, { size: 26, body: [232, 226, 212], pip: 0x9a1c12, sin: Lay.CAM_SIN, cos: Lay.CAM_COS, ground: Lay.diceGround }).setVisible(false)); - new Button(this, 80, GAME_HEIGHT - 40, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 140, height: 52, fontSize: 20, - }).setDepth(DEPTH.ui); + this.hud = new Hud(this, D.hud, { + names: this.names, skills: this.skills, opponents: this.oppOf, + onButton: (k) => this.onButton(k), onCall: (it) => this.onCall(it), + }).build(); + this.hud.setReferenceFooter(this.gs.opts); + this.tooltip = this.add.text(0, 0, '', { fontFamily: SERIF, fontSize: '16px', color: '#2a1408', backgroundColor: '#fdf6e6', padding: { x: 8, y: 4 } }).setDepth(D.tooltip).setVisible(false); + this.banner = this.add.text(GAME_WIDTH / 2, Lay.project(0, 0).y - 60, '', { fontFamily: DISPLAY_FONT, fontSize: '30px', color: '#ffe7a0', stroke: '#2a0c06', strokeThickness: 6, align: 'center' }).setOrigin(0.5).setDepth(D.fx + 8).setAlpha(0); - this.refresh(); - this.advance(); - } + this.ambience = new Snd.Ambience(this); + this.ambience.set('rain', !!this.settings.rain); + this.ambience.set('murmur', !!this.settings.murmur); - // ── static chrome ─────────────────────────────────────────────────────────── - buildScoreboard() { - this.add.rectangle(180, 132, 320, 224, COLORS.panel, 0.92) - .setStrokeStyle(2, COLORS.accent).setDepth(DEPTH.panel); - this.sbHeader = this.add.text(180, 48, '', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.text); - this.sbRows = []; - for (let seat = 0; seat < 4; seat++) { - const y = 88 + seat * 40; - const dot = this.add.circle(48, y, 8, Phaser.Display.Color.HexStringToColor(PLAYER_COLOR_HEX[seat]).color) - .setDepth(DEPTH.text); - const name = this.add.text(66, y, '', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.text); - const score = this.add.text(312, y, '', { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.accentHex, - }).setOrigin(1, 0.5).setDepth(DEPTH.text); - this.sbRows.push({ dot, name, score }); - } - } - - buildPortraits() { - // Each portrait sits just to the left of its own tiles, at the vertical - // centre of that area (rows/columns are all centred on their midpoints), - // so it reads as belonging to that player without ever covering a tile. - // Keep ~18-20px clearance: human hand left edge ≥ 391 (14 tiles), left - // column left edge 133, right column left edge 1836, top row ≥ 616. - const spots = [ - { x: 325, y: 975, r: 46 }, // human — left of the bottom hand row - { x: 1778, y: 580, r: 40 }, // seat 1 — left of the right column - { x: 558, y: 70, r: 40 }, // seat 2 — left of the top row - { x: 75, y: 580, r: 40 }, // seat 3 — left of the left column - ]; - for (let seat = 0; seat < 4; seat++) { - const { x, y, r } = spots[seat]; - const ring = this.add.graphics().setDepth(DEPTH.ui); - let ctrl; - if (seat === this.humanSeat) { - ctrl = createPlayerPortrait(this, x, y, r, DEPTH.ui, 'MahjongGame'); - } else { - const opp = this.opponents[seat - 1] ?? { id: 'bot', spriteIndex: 0 }; - ctrl = createOpponentPortrait(this, opp, x, y, r, DEPTH.ui); - } - this.add.text(x, y + r + 14, this.gs.players[seat].name, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); - this.portraitCtrls.push({ ring, controller: ctrl, x, y, r }); - } - } - - buildCentreTexts() { - this.wallText = this.add.text(960, 448, '', { - fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.text); - this.statusText = this.add.text(960, 505, '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(DEPTH.text); - } - - buildActionButtons() { - const mk = (label, cb, w = 180) => - new Button(this, 0, CLAIM_Y, label, cb, { width: w, height: 60, fontSize: 24 }) - .setDepth(DEPTH.claims).setVisible(false); - - this.claimBtns = { - win: mk('Mahjong!', () => this.resolveClaim({ type: 'win' })), - kong: mk('Kong', () => this.resolveClaim({ type: 'kong' })), - pung: mk('Pung', () => this.resolveClaim({ type: 'pung' })), - chows: [0, 1, 2].map((i) => mk('Chow', () => this.resolveClaim({ type: 'chow', tiles: this.chowOptions[i] }), 210)), - pass: mk('Pass', () => this.resolveClaim(null)), - }; - - this.selfWinBtn = new Button(this, 1770, CLAIM_Y, 'Mahjong!', () => this.onSelfWin(), { - width: 170, height: 60, fontSize: 24, - }).setDepth(DEPTH.claims).setVisible(false); - this.selfKongBtns = [0, 1].map((i) => - new Button(this, 1770, CLAIM_Y + 70 + i * 70, 'Kong', () => this.onSelfKong(i), { - width: 170, height: 60, fontSize: 22, - }).setDepth(DEPTH.claims).setVisible(false)); - } - - // Toggleable list of every scoring hand — the same table the engine scores - // with, so the panel can never drift from the rules. - buildReferencePanel() { - const panel = this.add.container(GAME_WIDTH, 0).setDepth(DEPTH.ref); - const g = this.add.graphics(); - g.fillStyle(COLORS.panel, 0.97); - g.fillRect(0, 0, REF_W, GAME_HEIGHT); - g.lineStyle(2, COLORS.accent, 1); - g.lineBetween(0, 0, 0, GAME_HEIGHT); - panel.add(g); - panel.add(this.add.text(REF_W / 2, 34, 'Winning Hands', { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex, - }).setOrigin(0.5)); - - let y = 76; - for (const r of FAAN_TABLE) { - panel.add(this.add.text(24, y, r.label, { - fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, - }).setOrigin(0, 0.5)); - panel.add(this.add.text(REF_W - 24, y, `${r.faan}`, { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.accentHex, - }).setOrigin(1, 0.5)); - panel.add(this.add.text(24, y + 18, r.desc, { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5)); - y += 44; - } - panel.add(this.add.text(REF_W / 2, y + 14, `A hand needs at least ${MIN_FAAN} faan to win.`, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.goldHex, - }).setOrigin(0.5)); - panel.add(this.add.text(REF_W / 2, y + 38, 'Points double with faan · discarder pays 2×, everyone pays on self-draw', { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, - }).setOrigin(0.5)); - this.refPanel = panel; - - // Parked just left of the reference panel's open position (1490) so it - // never ends up under it; y=210 clears seat 2's melds (y≤98) and bonus - // tiles (y≤157), which sit at x 1330+. - this.refBtn = new Button(this, 1399, 210, 'Hands', () => this.toggleReference(), { - width: 150, height: 52, fontSize: 22, variant: 'ghost', - }).setDepth(DEPTH.ref + 1); - } - - toggleReference() { - this.refOpen = !this.refOpen; - this.tweens.add({ - targets: this.refPanel, - x: this.refOpen ? GAME_WIDTH - REF_W : GAME_WIDTH, - duration: 200, - ease: 'Quad.Out', + this.input.on('pointerdown', (p) => this.onPointerDown(p)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this.events.once('shutdown', () => { + this.ended = true; + this.ambience?.stop(); + this.ts?.haltAll(); + this.hud?.hidePortraits(); }); - this.refBtn.setLabel(this.refOpen ? 'Close' : 'Hands'); - // Seat 1's portrait sits under the open panel. Its