diff --git a/src/games/azul/AzulAI.js b/src/games/azul/AzulAI.js index a8255ab..9882993 100644 --- a/src/games/azul/AzulAI.js +++ b/src/games/azul/AzulAI.js @@ -1,22 +1,37 @@ -// Azul AI — synchronous, in-browser heuristic. 1-ply greedy over a board -// evaluation, with a skill model (1–5) that adds blunders / score noise and -// picks from a widening top-N, exactly the shape used by SplendorAI. +// Azul AI — synchronous, in-browser heuristic with a real skill ladder. +// +// The core is a fast incremental valuation of "player P takes N tiles of colour +// C onto line L" (no state cloning), built from: +// • wall points the line will score when it tiles (adjacency), plus progress +// toward the +7 column / +10 colour sets, discounted by how soon the game +// will end +// • partial lines valued by their chance to complete (they carry over rounds, +// but are worthless if the game ends first) +// • floor-line penalty change, and the first-player marker's worth +// • end-timing: completing a wall row ends the game — good when ahead, +// bad when behind +// Higher skills add denial — how good the table is for the next player(s) after +// this take, which also produces natural hate-drafting — and skill 5 checks its +// best few candidates with a greedy rollout to the end of the round. import { COLORS, WALL_SIZE, FLOOR_PENALTIES, FLOOR_SIZE, - lineCapacity, wallColumnFor, ROW_BONUS, COLUMN_BONUS, COLOR_BONUS, + lineCapacity, ROW_BONUS, COLUMN_BONUS, COLOR_BONUS, } from './AzulData.js'; -import { legalMoves, applyMove, scorePlacement } from './AzulLogic.js'; +import { + legalMoves, applyMove, resolveRound, scorePlacement, wallOptions, cellColor, + isFreeWall, bonusStatus, defaultWallColumn, +} from './AzulLogic.js'; const SKILL_PROFILES = { - 1: { topN: 5, blunder: 0.45, noise: 14, delay: [700, 1200] }, - 2: { topN: 4, blunder: 0.25, noise: 9, delay: [650, 1100] }, - 3: { topN: 3, blunder: 0.12, noise: 5, delay: [600, 1000] }, - 4: { topN: 2, blunder: 0.04, noise: 2, delay: [520, 900] }, - 5: { topN: 1, blunder: 0.00, noise: 0, delay: [440, 820] }, + 1: { topN: 2, blunder: 0.20, noise: 2.2, denial: 0, others: 0, plan: 1, rollout: 0, delay: [700, 1200] }, + 2: { topN: 1, blunder: 0.10, noise: 1.8, denial: 0.15, others: 0, plan: 1, rollout: 0, delay: [650, 1100] }, + 3: { topN: 1, blunder: 0.06, noise: 1.2, denial: 0.3, others: 0.1, plan: 1, rollout: 0, delay: [600, 1000] }, + 4: { topN: 1, blunder: 0.01, noise: 0.3, denial: 0.6, others: 0.2, plan: 1, rollout: 0, delay: [520, 900] }, + 5: { topN: 1, blunder: 0, noise: 0, denial: 0.75, others: 0.25, plan: 1, rollout: 6, delay: [440, 820] }, }; -function profileFor(skill) { +export function profileFor(skill) { return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; } @@ -25,73 +40,353 @@ export function nextThinkDelay(skill) { return lo + Math.random() * (hi - lo); } -// Static evaluation of a player's board (higher = better). Captures realised -// score plus the *potential* locked up in pattern lines, minus floor liability, -// plus a nudge toward the lucrative end-game row/column/colour bonuses. -function evalPlayer(state, seat) { - const p = state.players[seat]; - let v = p.score * 10; +const FLOOR_CUM = [0]; +for (let k = 0; k < FLOOR_SIZE; k++) FLOOR_CUM.push(FLOOR_CUM[k] + FLOOR_PENALTIES[k]); +const floorPen = (len) => FLOOR_CUM[Math.min(FLOOR_SIZE, Math.max(0, len))]; - // Pattern lines: reward progress, and reward a line that is exactly full - // (it will tile and score next phase) by the points it would earn. - for (let i = 0; i < WALL_SIZE; i++) { - const line = p.lines[i]; - if (line.color === null) continue; - const cap = lineCapacity(i); - if (line.count === cap) { - const col = wallColumnFor(i, line.color); - const wall = p.wall.map((r) => r.slice()); - wall[i][col] = true; - v += scorePlacement(wall, i, col) * 8; - } else { - // Partial: value tiles already banked, scaled by how close to full it is. - v += line.count * 2 + (line.count / cap) * 3; +// Tunable weights (measured with tools/verifyAzul.js's ladder). +export const TUNE = { + needCost: 0.6, // per tile a partial line still needs + probBase: 0.92, probSlope: 0.13, + exposure: 1.5, // colours left on the table that no line of ours can take + floorMul: 1.3, // floor-penalty weight + endLead: 2, endTrail: -8, +}; + +// Set-bonus potential by how many of the five are in place. +const POTENTIAL = [0, 0.03, 0.09, 0.2, 0.45, 1]; + +// ── game context ───────────────────────────────────────────────────────────── +// How close the game is to ending, and who is ahead (projected). +export function gameContext(state, seat) { + const free = isFreeWall(state); + let maxRow = 0, endsThisRound = false; + for (const p of state.players) { + for (let r = 0; r < WALL_SIZE; r++) { + const n = p.wall[r].filter(Boolean).length; + maxRow = Math.max(maxRow, n); + if (n === WALL_SIZE - 1) { + const l = p.lines[r]; + if (l.color && l.count === lineCapacity(r) && wallOptions(p, r, l.color, free).length) endsThisRound = true; + } } } + const future = endsThisRound ? 0 : maxRow >= 4 ? 0.4 : maxRow === 3 ? 0.75 : 1; + const proj = state.players.map((p) => p.score + bonusStatus(p).locked + pendingPoints(p, free) + floorPen(p.floor.length)); + const mine = proj[seat]; + let best = -Infinity; + proj.forEach((v, i) => { if (i !== seat) best = Math.max(best, v); }); + return { free, future, endsThisRound, lead: mine - best, proj, players: state.playerCount }; +} - // Floor liability: the penalties these tiles will cost. - let penalty = 0; - for (let k = 0; k < p.floor.length && k < FLOOR_SIZE; k++) penalty += FLOOR_PENALTIES[k]; - v += penalty * 4; +// Points the already-full pattern lines will score this round (top to bottom). +function pendingPoints(p, free) { + const placed = []; + let pts = 0; + for (let r = 0; r < WALL_SIZE; r++) { + const l = p.lines[r]; + if (!l.color || l.count !== lineCapacity(r)) continue; + const opts = wallOptions(p, r, l.color, free); + if (!opts.length) continue; + const c = free ? defaultWallColumn(p, r, l.color, opts) : opts[0]; + p.wall[r][c] = true; + pts += scorePlacement(p.wall, r, c); + placed.push([r, c]); + } + for (const [r, c] of placed) p.wall[r][c] = false; + return pts; +} - // Permanent wall tiles, and proximity to the end-game bonuses. - let wallTiles = 0; - for (let row = 0; row < WALL_SIZE; row++) for (let col = 0; col < WALL_SIZE; col++) if (p.wall[row][col]) wallTiles++; - v += wallTiles; - for (let row = 0; row < WALL_SIZE; row++) { - const n = p.wall[row].filter(Boolean).length; - if (n === WALL_SIZE) v += ROW_BONUS; else if (n === WALL_SIZE - 1) v += 3; - } - for (let col = 0; col < WALL_SIZE; col++) { - let n = 0; for (let row = 0; row < WALL_SIZE; row++) if (p.wall[row][col]) n++; - if (n === WALL_SIZE) v += COLUMN_BONUS; else if (n === WALL_SIZE - 1) v += 4; - } - for (const c of COLORS) { - let n = 0; for (let row = 0; row < WALL_SIZE; row++) if (p.wall[row][wallColumnFor(row, c)]) n++; - if (n === WALL_SIZE) v += COLOR_BONUS; else if (n === WALL_SIZE - 1) v += 5; +// ── valuation ──────────────────────────────────────────────────────────────── +// Value of eventually setting `color` on wall row `row` (wall cell chosen as the +// free-wall default). Returns { v, col } or null when it has nowhere to go. +function placeValue(p, row, color, ctx, plan) { + const opts = wallOptions(p, row, color, ctx.free); + if (!opts.length) return null; + const col = ctx.free ? defaultWallColumn(p, row, color, opts) : opts[0]; + p.wall[row][col] = true; + const pts = scorePlacement(p.wall, row, col); + p.wall[row][col] = false; + + let colN = 0, colorN = 0, rowN = 0; + for (let r = 0; r < WALL_SIZE; r++) if (p.wall[r][col]) colN++; + for (let c = 0; c < WALL_SIZE; c++) if (p.wall[row][c]) rowN++; + for (let r = 0; r < WALL_SIZE; r++) for (let c = 0; c < WALL_SIZE; c++) if (cellColor(p, r, c) === color) colorN++; + + const f = ctx.future; + const gain = (n, bonus) => { + const after = n + 1; + const a = after === WALL_SIZE ? bonus : bonus * POTENTIAL[after] * f; + const b = n === WALL_SIZE ? bonus : bonus * POTENTIAL[n] * f; + return a - b; + }; + let v = pts; + v += plan * (gain(colN, COLUMN_BONUS) + gain(colorN, COLOR_BONUS) + gain(rowN, ROW_BONUS) * 0.5); + // Central cells connect in more directions — a small early-game preference. + v += plan * f * (2 - Math.abs(col - 2)) * 0.15; + // End-timing: completing a row ends the game after this round. + if (rowN + 1 === WALL_SIZE) v += plan * (ctx.lead >= 0 ? TUNE.endLead + Math.min(6, ctx.lead * 0.3) : TUNE.endTrail + ctx.lead * 0.4); + return { v, col }; +} + +// Value of a pattern line holding `count` of `color` (count may be 0). +function lineValue(p, row, color, count, ctx, plan) { + if (!color || count === 0) return 0; + const cap = lineCapacity(row); + const pv = placeValue(p, row, color, ctx, plan); + if (!pv) return -count; // free wall: would be dumped + if (count >= cap) return pv.v; + const need = cap - count; + // Partial lines carry over — but only matter if the game continues. + const carry = ctx.endsThisRound ? 0 : ctx.future; + const prob = Math.max(0.15, TUNE.probBase - TUNE.probSlope * need) * (0.35 + 0.65 * carry); + return pv.v * prob - TUNE.needCost * need * plan; +} + +// Gain for player `p` taking `n` tiles of `color` onto `line` (index or +// 'floor'), optionally with the first-player marker. No mutation. +function takeGain(p, color, n, line, takesFirst, ctx, plan) { + let placed = 0, v = 0; + if (line !== 'floor') { + const l = p.lines[line]; + const cap = lineCapacity(line); + placed = Math.min(cap - l.count, n); + v += lineValue(p, line, color, l.count + placed, ctx, plan) - lineValue(p, line, l.color, l.count, ctx, plan); } + const add = n - placed + (takesFirst ? 1 : 0); + v += TUNE.floorMul * (floorPen(p.floor.length + add) - floorPen(p.floor.length)); + if (takesFirst) v += ctx.endsThisRound ? 0 : (1 + 0.3 * (ctx.players - 2)) * ctx.future * plan; return v; } +// Colour counts per source: [{ counts, type, index }] +function sourceCounts(state) { + const out = state.factories.map((f, index) => { + const counts = {}; for (const t of f) counts[t] = (counts[t] ?? 0) + 1; + return { type: 'factory', index, counts }; + }); + const counts = {}; for (const t of state.center) counts[t] = (counts[t] ?? 0) + 1; + out.push({ type: 'center', counts, first: state.centerHasFirst }); + return out; +} + +// The best gain a player could get from a table of sources. +function bestGain(p, sources, ctx, plan) { + let best = -Infinity; + for (const s of sources) { + for (const color of COLORS) { + const n = s.counts[color]; + if (!n) continue; + const tf = s.type === 'center' && s.first; + for (let i = 0; i < WALL_SIZE; i++) { + const l = p.lines[i]; + if (l.count >= lineCapacity(i) || (l.color && l.color !== color)) continue; + if (!wallOptions(p, i, color, ctx.free).length) continue; + const g = takeGain(p, color, n, i, tf, ctx, plan); + if (g > best) best = g; + } + const g = takeGain(p, color, n, 'floor', tf, ctx, plan); + if (g > best) best = g; + } + } + return best === -Infinity ? 0 : best; +} + +// The table after taking `color` from source `si` (leftovers to the centre). +function tableAfter(sources, si, color) { + const src = sources[si]; + const out = sources.map((s) => ({ ...s, counts: { ...s.counts } })); + const center = out[out.length - 1]; + if (src.type === 'factory') { + for (const c of COLORS) if (c !== color && src.counts[c]) center.counts[c] = (center.counts[c] ?? 0) + src.counts[c]; + out[si].counts = {}; + } else { + center.counts[color] = 0; + center.first = false; + } + return out; +} + +// Score every legal move for the current player. +export function rankMoves(state, skill = 3) { + const prof = profileFor(skill); + const seat = state.current; + const p = state.players[seat]; + const ctx = gameContext(state, seat); + const legal = legalMoves(state); + const sources = sourceCounts(state); + const n = state.playerCount; + const nextSeat = (seat + 1) % n; + const denialCache = new Map(); + const ctxBySeat = state.players.map((q) => (q.seat === seat ? ctx : (prof.denial ? gameContext(state, q.seat) : null))); + const denial = (si, color) => { + if (!prof.denial) return 0; + const key = `${si}:${color}`; + if (denialCache.has(key)) return denialCache.get(key); + const after = tableAfter(sources, si, color); + let d = 0; + for (let k = 1; k < n; k++) { + const q = state.players[(seat + k) % n]; + const qctx = ctxBySeat[q.seat]; + const w = (q.seat === nextSeat) ? prof.denial : prof.others; + if (w) d += w * bestGain(q, after, qctx, 1); + } + denialCache.set(key, d); + return d; + }; + const sourceIndex = (src) => (src.type === 'center' ? sources.length - 1 : src.index); + + // Exposure: after this take, which colours left on the table have no line of + // ours that could take them? Those are the tiles we may be forced to floor. + const expCache = new Map(); + const exposure = (si, move) => { + if (!TUNE.exposure || !prof.plan) return 0; + const key = `${si}:${move.color}:${move.line}`; + if (expCache.has(key)) return expCache.get(key); + const after = tableAfter(sources, si, move.color); + const remain = {}; + for (const src of after) for (const c of COLORS) if (src.counts[c]) remain[c] = (remain[c] ?? 0) + src.counts[c]; + let e = 0; + for (const c of COLORS) { + const R = remain[c]; + if (!R) continue; + let home = false; + for (let i = 0; i < WALL_SIZE && !home; i++) { + const l = p.lines[i]; + let color = l.color, count = l.count; + if (move.line === i) { color = move.color; count = Math.min(lineCapacity(i), l.count + sources[si].counts[move.color]); } + if (count >= lineCapacity(i) || (color && color !== c)) continue; + if (wallOptions(p, i, c, ctx.free).length) home = true; + } + if (!home) e += Math.min(R, 4); + } + const v = TUNE.exposure * prof.plan * e / n; + expCache.set(key, v); + return v; + }; + + return legal.map((move) => { + const si = sourceIndex(move.source); + const s = sources[si]; + const cnt = s.counts[move.color]; + const tf = s.type === 'center' && s.first; + const gain = takeGain(p, move.color, cnt, move.line, tf, ctx, prof.plan); + const score = gain - denial(si, move.color) - exposure(si, move); + return { move, score, gain }; + }).sort((a, b) => b.score - a.score); +} + +// Greedy policy used inside rollouts (fast, no denial). +function greedyMove(state) { + const seat = state.current; + const p = state.players[seat]; + const ctx = gameContext(state, seat); + const sources = sourceCounts(state); + let best = null, bestV = -Infinity; + for (const move of legalMoves(state)) { + const s = sources[move.source.type === 'center' ? sources.length - 1 : move.source.index]; + const v = takeGain(p, move.color, s.counts[move.color], move.line, s.type === 'center' && s.first, ctx, 1); + if (v > bestV) { bestV = v; best = move; } + } + return best; +} + +// Play the rest of the round greedily, tile it, and judge the result for `seat`. +function rolloutValue(state, seat) { + let s = state; + let guard = 0; + while (s.phase === 'offer' && guard++ < 200) { + const m = greedyMove(s); + if (!m) break; + s = applyMove(s, m); + } + if (s.phase === 'scoring') s = resolveRound(s); + const free = isFreeWall(s); + const val = (p) => { + const ctx = gameContext(s, p.seat); + let v = p.score + (s.phase === 'gameOver' ? 0 : bonusStatus(p).locked * 0.6); + if (s.phase !== 'gameOver') { + for (let r = 0; r < WALL_SIZE; r++) { + const l = p.lines[r]; + if (l.color && l.count) v += lineValue(p, r, l.color, l.count, ctx, 1) * 0.8; + } + } + void free; + return v; + }; + const mine = val(s.players[seat]); + let opp = 0; + for (const p of s.players) if (p.seat !== seat) opp = Math.max(opp, val(p)); + return mine - 0.5 * opp; +} + // Returns a single move object for the current player, or null if none exist. export function chooseMove(state, skill) { const prof = profileFor(skill); - const seat = state.current; const legal = legalMoves(state); if (legal.length === 0) return null; if (legal.length === 1) return legal[0]; - const ranked = legal - .map((move) => { - let score = evalPlayer(applyMove(state, move), seat); - score += (Math.random() * 2 - 1) * prof.noise; - return { move, score }; - }) - .sort((a, b) => b.score - a.score); - if (Math.random() < prof.blunder) { - return legal[Math.floor(Math.random() * legal.length)]; + // A "blunder" is a plausible-but-loose move — a line move from the top of + // the list, never a needless floor dump. + const ranked = rankMoves(state, skill); + const lines = ranked.filter((r) => r.move.line !== 'floor' && r.gain > -2); + const pool = (lines.length ? lines : ranked).slice(0, 6); + return pool[Math.floor(Math.random() * pool.length)].move; } + + let ranked = rankMoves(state, skill); + if (prof.noise) { + ranked = ranked.map((r) => ({ ...r, score: r.score + (Math.random() * 2 - 1) * prof.noise })) + .sort((a, b) => b.score - a.score); + } + + if (prof.rollout && state.phase === 'offer') { + const seat = state.current; + const top = ranked.slice(0, prof.rollout); + let best = null, bestV = -Infinity; + for (const r of top) { + const v = rolloutValue(applyMove(state, r.move), seat) + r.score * 0.35; + if (v > bestV) { bestV = v; best = r.move; } + } + if (best) return best; + } + const pool = ranked.slice(0, Math.max(1, prof.topN)); return pool[Math.floor(Math.random() * pool.length)].move; } + +// Free wall: pick columns for this seat's completed lines, top to bottom. +// Returns { [row]: col }. Standard wall → {}. +export function chooseWallColumns(state, seat, skill = 3) { + if (!isFreeWall(state)) return {}; + const p = JSON.parse(JSON.stringify(state.players[seat])); + const ctx = gameContext(state, seat); + const prof = profileFor(skill); + const out = {}; + for (let r = 0; r < WALL_SIZE; r++) { + const l = p.lines[r]; + if (!l.color || l.count !== lineCapacity(r)) continue; + const opts = wallOptions(p, r, l.color, true); + if (!opts.length) continue; + let best = opts[0], bestV = -Infinity; + for (const c of opts) { + p.wall[r][c] = true; + let v = scorePlacement(p.wall, r, c); + let colN = 0; for (let rr = 0; rr < WALL_SIZE; rr++) if (p.wall[rr][c]) colN++; + p.wall[r][c] = false; + v += prof.plan * COLUMN_BONUS * (colN === WALL_SIZE ? 1 : POTENTIAL[colN] * ctx.future); + // Keep later rows' options open: count colours still placeable in this column. + let open = 0; + for (let rr = r + 1; rr < WALL_SIZE; rr++) if (!p.wall[rr][c]) open++; + v += prof.plan * open * 0.05; + v += (Math.random() * 2 - 1) * prof.noise * 0.5; + if (v > bestV) { bestV = v; best = c; } + } + out[r] = best; + p.wall[r][best] = true; + p.wallColors[r][best] = l.color; + } + return out; +} diff --git a/src/games/azul/AzulArt.js b/src/games/azul/AzulArt.js new file mode 100644 index 0000000..5aa4f00 --- /dev/null +++ b/src/games/azul/AzulArt.js @@ -0,0 +1,671 @@ +// AzulArt.js — procedural canvas art for the Azul tile workshop (Lisbon). +// +// Everything is baked once into Phaser canvas textures (no new image files): +// azul-room plaster wall with an azulejo wainscot + title +// cartouche, over a worn oak workbench and lamp pool +// azul-board-[-free][-g] +// a player board: walnut frame, cream plaster, cobalt +// header band, recessed pattern-line cells, the wall +// (faint glazed ghosts of each tile, or grey cells for +// the free wall), the floor line with its penalties; +// -g adds colour-blind glyphs to the ghosts +// azul-plate a glazed factory plate with a painted cobalt rim +// azul-tray the centre tray (wooden rim, green baize) +// azul-bag / azul-lid the cloth tile bag and the box lid (discards) +// azul-panel- wood-framed cream panels for the HUD +// azul-notepad the workshop order book (log) +// azul-t-[-g] a bevelled, glazed tile with its shadow baked in +// (from the user's azul-tiles sheet when loaded) +// azul-t-first the first-player token +// azul-glow / azul-spark / azul-dust / azul-glint FX sprites +// +// Boards and panels carry a shadow margin of SHADOW px on every side: place +// them at (x - SHADOW, y - SHADOW) with origin 0. + +import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { mulberry32 } from '../../ui/cardtable/AITiming.js'; +import { + COLORS, TILE_HEX, TILE_EDGE, FLOOR_PENALTIES, FLOOR_SIZE, WALL_SIZE, wallColor, lineCapacity, tileFrame, FIRST_PLAYER_FRAME, +} from './AzulData.js'; +import { + W, H, MINI, BIG, WAINSCOT, TITLE, RING, TRAY, BAG, LID, NOTEPAD, TRACKER, ACTION, SCORES, +} from './AzulLayout.js'; + +export const SERIF = 'Georgia, "Times New Roman", serif'; +export const DISPLAY = 'Caesar, Georgia, serif'; +export const SHADOW = 14; +export const TILE_TEX = { size: 112, tile: 96, ox: 7, oy: 5 }; // tile drawn at (ox, oy) in the texture +export const PLATE_TEX = 132; +export const COBALT = '#1d4f8f'; +export const INK = '#3a2a16'; +const hex = (n) => `#${n.toString(16).padStart(6, '0')}`; + +// Colour-blind glyphs (drawn on tiles and wall ghosts when enabled). +export const GLYPH = { blue: 'circle', yellow: 'triangle', red: 'diamond', black: 'square', white: 'cross' }; + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); + return key; +} + +// ── shared painters ──────────────────────────────────────────────────────────── +function grain(ctx, x, y, w, h, rnd, { dark = 'rgba(50,28,10,0.16)', light = 'rgba(255,225,180,0.07)', spacing = 6, amp = 2 } = {}) { + ctx.save(); + ctx.lineWidth = 1; + for (let yy = y; yy < y + h; yy += spacing * (0.6 + rnd() * 0.8)) { + ctx.strokeStyle = rnd() < 0.7 ? dark : light; + ctx.beginPath(); + const ph = rnd() * 6, fq = 0.004 + rnd() * 0.01; + for (let xx = x; xx <= x + w; xx += 10) { + const yv = yy + Math.sin(xx * fq + ph) * amp + Math.sin(xx * fq * 3.1 + ph) * amp * 0.3; + if (xx === x) ctx.moveTo(xx, yv); else ctx.lineTo(xx, yv); + } + ctx.stroke(); + } + ctx.restore(); +} + +function wood(ctx, x, y, w, h, top, bottom, rnd, spacing = 6) { + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, top); g.addColorStop(1, bottom); + ctx.fillStyle = g; + ctx.fill(); + ctx.save(); + ctx.clip(); + grain(ctx, x, y, w, h, rnd, { spacing }); + ctx.fillStyle = noisePattern(ctx, 64, 20); + ctx.fillRect(x, y, w, h); + ctx.restore(); +} + +function softShadow(ctx, draw, { blur = 14, dx = 0, dy = 6, color = 'rgba(0,0,0,0.45)' } = {}) { + ctx.save(); + ctx.shadowColor = color; + ctx.shadowBlur = blur; + ctx.shadowOffsetX = dx; + ctx.shadowOffsetY = dy; + draw(); + ctx.restore(); +} + +// A recessed square (grout / inset) — darker top-left inner edge. +function inset(ctx, x, y, s, r, { fill = 'rgba(90,64,30,0.16)', dark = 'rgba(60,40,15,0.45)', light = 'rgba(255,248,230,0.7)' } = {}) { + rr(ctx, x, y, s, s, r); + ctx.fillStyle = fill; + ctx.fill(); + ctx.save(); + rr(ctx, x, y, s, s, r); + ctx.clip(); + ctx.lineWidth = 2.5; + ctx.strokeStyle = dark; + ctx.beginPath(); ctx.moveTo(x, y + s); ctx.lineTo(x, y); ctx.lineTo(x + s, y); ctx.stroke(); + ctx.strokeStyle = light; + ctx.beginPath(); ctx.moveTo(x + s, y); ctx.lineTo(x + s, y + s); ctx.lineTo(x, y + s); ctx.stroke(); + ctx.restore(); +} + +export function drawGlyph(ctx, kind, cx, cy, s, { fill = '#ffffff', stroke = 'rgba(0,0,0,0.75)', lw = Math.max(1.5, s * 0.14) } = {}) { + ctx.save(); + ctx.beginPath(); + const h = s / 2; + if (kind === 'circle') ctx.arc(cx, cy, h * 0.85, 0, Math.PI * 2); + else if (kind === 'triangle') { ctx.moveTo(cx, cy - h); ctx.lineTo(cx + h, cy + h * 0.8); ctx.lineTo(cx - h, cy + h * 0.8); ctx.closePath(); } + else if (kind === 'diamond') { ctx.moveTo(cx, cy - h); ctx.lineTo(cx + h, cy); ctx.lineTo(cx, cy + h); ctx.lineTo(cx - h, cy); ctx.closePath(); } + else if (kind === 'square') ctx.rect(cx - h * 0.78, cy - h * 0.78, h * 1.56, h * 1.56); + else if (kind === 'cross') { + const t = h * 0.36; + ctx.moveTo(cx - t, cy - h); ctx.lineTo(cx + t, cy - h); ctx.lineTo(cx + t, cy - t); ctx.lineTo(cx + h, cy - t); + ctx.lineTo(cx + h, cy + t); ctx.lineTo(cx + t, cy + t); ctx.lineTo(cx + t, cy + h); ctx.lineTo(cx - t, cy + h); + ctx.lineTo(cx - t, cy + t); ctx.lineTo(cx - h, cy + t); ctx.lineTo(cx - h, cy - t); ctx.lineTo(cx - t, cy - t); ctx.closePath(); + } + ctx.lineJoin = 'round'; + ctx.lineWidth = lw; + ctx.strokeStyle = stroke; + ctx.stroke(); + ctx.fillStyle = fill; + ctx.fill(); + ctx.restore(); +} + +// The source image + frame rect of a tile in the user's sheet, or null. +function sheetFrame(scene, frameIndex) { + if (!scene.textures.exists('azul-tiles')) return null; + const tex = scene.textures.get('azul-tiles'); + const fr = tex.get(frameIndex); + if (!fr || fr.name === '__BASE') return null; + return { img: tex.getSourceImage(), sx: fr.cutX, sy: fr.cutY, sw: fr.cutWidth, sh: fr.cutHeight }; +} + +// Procedural azulejo face (fallback when the sheet is missing). +function proceduralFace(ctx, color, x, y, s) { + const base = hex(TILE_HEX[color]); + const edge = hex(TILE_EDGE[color]); + ctx.fillStyle = base; + ctx.fillRect(x, y, s, s); + const light = color === 'black' ? 'rgba(235,235,225,0.85)' : color === 'white' ? 'rgba(30,70,95,0.55)' : 'rgba(255,245,225,0.55)'; + ctx.strokeStyle = light; + ctx.lineWidth = s * 0.05; + ctx.beginPath(); + for (const [ax, ay] of [[0, 0], [1, 0], [0, 1], [1, 1]]) { ctx.moveTo(x + ax * s + (ax ? -1 : 1) * s * 0.36, y + ay * s); ctx.arc(x + ax * s, y + ay * s, s * 0.36, 0, Math.PI * 2); } + ctx.stroke(); + ctx.fillStyle = light; + ctx.beginPath(); + ctx.moveTo(x + s / 2, y + s * 0.22); ctx.lineTo(x + s * 0.78, y + s / 2); ctx.lineTo(x + s / 2, y + s * 0.78); ctx.lineTo(x + s * 0.22, y + s / 2); + ctx.closePath(); ctx.fill(); + ctx.strokeStyle = edge; ctx.lineWidth = 2; ctx.strokeRect(x + 1, y + 1, s - 2, s - 2); +} + +function drawFace(scene, ctx, color, x, y, s) { + const f = sheetFrame(scene, color === 'first' ? FIRST_PLAYER_FRAME : tileFrame(color)); + if (f) { ctx.drawImage(f.img, f.sx, f.sy, f.sw, f.sh, x, y, s, s); return; } + if (color === 'first') { + ctx.fillStyle = '#222428'; ctx.fillRect(x, y, s, s); + ctx.fillStyle = '#f4efe2'; + ctx.font = `bold ${Math.round(s * 0.62)}px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('1', x + s / 2, y + s / 2 + 2); + return; + } + proceduralFace(ctx, color, x, y, s); +} + +// ── tiles ─────────────────────────────────────────────────────────────────────── +function bakeTile(scene, color, glyphs) { + const { size, tile: s, ox, oy } = TILE_TEX; + const c = canvas(size, size); + const ctx = c.getContext('2d'); + const r = 9; + // Shadow. + softShadow(ctx, () => { rr(ctx, ox, oy, s, s, r); ctx.fillStyle = '#000'; ctx.fill(); }, { blur: 7, dy: 4, dx: 1, color: 'rgba(0,0,0,0.5)' }); + // Face, clipped to the rounded square. + ctx.save(); + rr(ctx, ox, oy, s, s, r); + ctx.clip(); + drawFace(scene, ctx, color, ox - 2, oy - 2, s + 4); + // Glaze: a diagonal sheen and a soft pool of light top-left. + const g = ctx.createLinearGradient(ox, oy, ox + s, oy + s); + g.addColorStop(0, 'rgba(255,255,255,0.30)'); + g.addColorStop(0.38, 'rgba(255,255,255,0.06)'); + g.addColorStop(0.6, 'rgba(255,255,255,0)'); + g.addColorStop(1, 'rgba(0,0,0,0.16)'); + ctx.fillStyle = g; + ctx.fillRect(ox, oy, s, s); + const spec = ctx.createRadialGradient(ox + s * 0.28, oy + s * 0.22, 1, ox + s * 0.28, oy + s * 0.22, s * 0.34); + spec.addColorStop(0, 'rgba(255,255,255,0.32)'); spec.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = spec; + ctx.fillRect(ox, oy, s, s); + // Bevel: light top-left, dark bottom-right. + ctx.lineWidth = 5; + ctx.strokeStyle = 'rgba(255,255,255,0.34)'; + ctx.beginPath(); ctx.moveTo(ox + 2, oy + s - 4); ctx.lineTo(ox + 2, oy + 2); ctx.lineTo(ox + s - 4, oy + 2); ctx.stroke(); + ctx.strokeStyle = 'rgba(0,0,0,0.30)'; + ctx.beginPath(); ctx.moveTo(ox + s - 2, oy + 4); ctx.lineTo(ox + s - 2, oy + s - 2); ctx.lineTo(ox + 4, oy + s - 2); ctx.stroke(); + ctx.restore(); + rr(ctx, ox + 0.5, oy + 0.5, s - 1, s - 1, r); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(20,12,4,0.65)'; + ctx.stroke(); + if (glyphs && GLYPH[color]) { + // Badge in the lower-right corner. + const bx = ox + s - 22, by = oy + s - 22; + ctx.beginPath(); ctx.arc(bx, by, 17, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(15,12,8,0.62)'; ctx.fill(); + drawGlyph(ctx, GLYPH[color], bx, by, 20, { fill: '#fffaf0', stroke: 'rgba(0,0,0,0.0)', lw: 0.1 }); + } + addCanvas(scene, `azul-t-${color}${glyphs ? '-g' : ''}`, c); +} + +export function tileKey(color, glyphs) { + if (color === 'first') return 'azul-t-first'; + return `azul-t-${color}${glyphs ? '-g' : ''}`; +} +// Display size of a tile texture so its tile face measures `face` px. +export const tileDisplay = (face) => face * TILE_TEX.size / TILE_TEX.tile; +// Offset of the tile face centre from the texture centre, in face px. +export const TILE_FACE_OFF = { + x: (TILE_TEX.ox + TILE_TEX.tile / 2 - TILE_TEX.size / 2) / TILE_TEX.tile, + y: (TILE_TEX.oy + TILE_TEX.tile / 2 - TILE_TEX.size / 2) / TILE_TEX.tile, +}; + +// ── boards ────────────────────────────────────────────────────────────────────── +export function boardKey(size, { free = false, glyphs = false } = {}) { + return `azul-board-${size}${free ? '-free' : ''}${glyphs ? '-g' : ''}`; +} + +export function ensureBoard(scene, size, opts = {}) { + const key = boardKey(size, opts); + if (scene.textures.exists(key)) return key; + const m = size === 'big' ? BIG : MINI; + const S = SHADOW; + const c = canvas(m.w + S * 2, m.h + S * 2); + const ctx = c.getContext('2d'); + const rnd = mulberry32(size === 'big' ? 11 : 13); + const x0 = S, y0 = S; + const R = size === 'big' ? 12 : 9; + // Frame + shadow. + softShadow(ctx, () => { rr(ctx, x0, y0, m.w, m.h, R); ctx.fillStyle = '#3a2412'; ctx.fill(); }, { blur: 16, dy: 7 }); + rr(ctx, x0, y0, m.w, m.h, R); + wood(ctx, x0, y0, m.w, m.h, '#6a4122', '#3e2412', rnd, 5); + // Inner plaster. + const ib = size === 'big' ? 6 : 4; + rr(ctx, x0 + ib, y0 + ib, m.w - ib * 2, m.h - ib * 2, R - 3); + const pg = ctx.createLinearGradient(0, y0, 0, y0 + m.h); + pg.addColorStop(0, '#f2e8d0'); pg.addColorStop(1, '#e2d2ac'); + ctx.fillStyle = pg; ctx.fill(); + ctx.save(); rr(ctx, x0 + ib, y0 + ib, m.w - ib * 2, m.h - ib * 2, R - 3); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 16); ctx.fillRect(x0, y0, m.w, m.h); + // Cobalt header band with a gold hairline. + const hb = m.headerH - (size === 'big' ? 8 : 6); + const hg = ctx.createLinearGradient(0, y0, 0, y0 + hb); + hg.addColorStop(0, '#265b9c'); hg.addColorStop(1, '#173f72'); + ctx.fillStyle = hg; ctx.fillRect(x0, y0, m.w, hb); + // A run of tiny painted quatrefoils along the band. + ctx.fillStyle = 'rgba(255,255,255,0.10)'; + for (let x = x0 + 14; x < x0 + m.w; x += 22) { + ctx.beginPath(); ctx.arc(x, y0 + hb - 6, 2.2, 0, Math.PI * 2); ctx.fill(); + } + ctx.fillStyle = '#c9a24a'; ctx.fillRect(x0, y0 + hb, m.w, 2); + ctx.restore(); + + const bodyTop = y0 + m.headerH; + const pad = m.pad; + const cellIn = (m.cell - m.tile) / 2; + // Pattern lines: a stepped tray of recessed cells. + for (let i = 0; i < WALL_SIZE; i++) { + const cap = lineCapacity(i); + for (let col = WALL_SIZE - cap; col < WALL_SIZE; col++) { + inset(ctx, x0 + pad + col * m.cell + cellIn - 1, bodyTop + i * m.cell + cellIn - 1, m.tile + 2, 4); + } + // A cobalt guide dot in the gap, pointing at the wall. + const gx = x0 + pad + WALL_SIZE * m.cell + m.wallGap / 2; + const gy = bodyTop + i * m.cell + m.cell / 2; + ctx.fillStyle = 'rgba(29,79,143,0.55)'; + ctx.beginPath(); ctx.moveTo(gx - m.wallGap * 0.22, gy - 4); ctx.lineTo(gx + m.wallGap * 0.22, gy); ctx.lineTo(gx - m.wallGap * 0.22, gy + 4); ctx.closePath(); ctx.fill(); + } + // Wall: grout bed then glazed ghosts. + const wx = x0 + pad + WALL_SIZE * m.cell + m.wallGap; + rr(ctx, wx - 3, bodyTop - 3, WALL_SIZE * m.cell + 6, WALL_SIZE * m.cell + 6, 6); + ctx.fillStyle = '#c6b48c'; ctx.fill(); + ctx.strokeStyle = 'rgba(90,64,30,0.5)'; ctx.lineWidth = 1.5; ctx.stroke(); + for (let r = 0; r < WALL_SIZE; r++) { + for (let col = 0; col < WALL_SIZE; col++) { + const cx = wx + col * m.cell + cellIn, cy = bodyTop + r * m.cell + cellIn; + ctx.save(); + rr(ctx, cx, cy, m.tile, m.tile, 4); + ctx.clip(); + if (opts.free) { + const g = ctx.createLinearGradient(cx, cy, cx + m.tile, cy + m.tile); + g.addColorStop(0, '#c9ccc6'); g.addColorStop(1, '#a9ada6'); + ctx.fillStyle = g; ctx.fillRect(cx, cy, m.tile, m.tile); + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; ctx.lineWidth = 1; + ctx.strokeRect(cx + m.tile * 0.2, cy + m.tile * 0.2, m.tile * 0.6, m.tile * 0.6); + } else { + const color = wallColor(r, col); + drawFace(scene, ctx, color, cx, cy, m.tile); + // Wash it out toward the plaster so it reads as a ghost. + ctx.fillStyle = 'rgba(238,228,204,0.62)'; + ctx.fillRect(cx, cy, m.tile, m.tile); + ctx.fillStyle = `${hex(TILE_HEX[color])}2e`; + ctx.fillRect(cx, cy, m.tile, m.tile); + if (opts.glyphs) drawGlyph(ctx, GLYPH[color], cx + m.tile / 2, cy + m.tile / 2, m.tile * 0.42, { fill: hex(TILE_HEX[color]), stroke: 'rgba(255,255,255,0.9)', lw: Math.max(1.2, m.tile * 0.06) }); + } + ctx.restore(); + inset(ctx, cx, cy, m.tile, 4, { fill: 'rgba(0,0,0,0)', dark: 'rgba(60,40,15,0.35)', light: 'rgba(255,250,235,0.45)' }); + } + } + // Floor line. + const fy = y0 + m.floorTop; + const fw = FLOOR_SIZE * (m.floorCell + m.floorGap) - m.floorGap; + rr(ctx, x0 + pad - 4, fy - m.floorLabel + 2, fw + 8, m.floorCell + m.floorLabel + 2, 6); + ctx.fillStyle = 'rgba(122,32,24,0.10)'; ctx.fill(); + ctx.font = `bold ${size === 'big' ? 13 : 10}px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic'; + for (let k = 0; k < FLOOR_SIZE; k++) { + const fx = x0 + pad + k * (m.floorCell + m.floorGap); + inset(ctx, fx, fy, m.floorCell, 4, { fill: 'rgba(110,40,30,0.10)' }); + ctx.fillStyle = '#7a2018'; + ctx.fillText(`${FLOOR_PENALTIES[k]}`, fx + m.floorCell / 2, fy - 4); + } + addCanvas(scene, key, c); + return key; +} + +// ── plate, tray, bag, lid ───────────────────────────────────────────────────── +function bakePlate(scene) { + const S = PLATE_TEX, cx = S / 2, cy = S / 2 - 3, r = RING.r; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + softShadow(ctx, () => { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fillStyle = '#000'; ctx.fill(); }, { blur: 12, dy: 6 }); + // Glazed white body. + const g = ctx.createRadialGradient(cx - r * 0.3, cy - r * 0.35, r * 0.1, cx, cy, r); + g.addColorStop(0, '#fffdf7'); g.addColorStop(0.75, '#efe9dc'); g.addColorStop(1, '#d9d0bd'); + ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fillStyle = g; ctx.fill(); + // Cobalt rim band + painted dots and petals. + ctx.lineWidth = 7; ctx.strokeStyle = '#1f4f8f'; + ctx.beginPath(); ctx.arc(cx, cy, r - 5, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = 1.4; ctx.strokeStyle = '#2b62a8'; + ctx.beginPath(); ctx.arc(cx, cy, r - 11, 0, Math.PI * 2); ctx.stroke(); + ctx.fillStyle = '#f7f2e6'; + for (let k = 0; k < 16; k++) { + const a = (k / 16) * Math.PI * 2; + ctx.beginPath(); ctx.arc(cx + Math.cos(a) * (r - 5), cy + Math.sin(a) * (r - 5), 1.5, 0, Math.PI * 2); ctx.fill(); + } + ctx.fillStyle = 'rgba(31,79,143,0.55)'; + for (let k = 0; k < 8; k++) { + const a = (k / 8) * Math.PI * 2 + Math.PI / 8; + ctx.save(); ctx.translate(cx + Math.cos(a) * (r - 15), cy + Math.sin(a) * (r - 15)); ctx.rotate(a); + ctx.beginPath(); ctx.ellipse(0, 0, 3.2, 1.5, 0, 0, Math.PI * 2); ctx.fill(); ctx.restore(); + } + // Well of the plate. + const w = ctx.createRadialGradient(cx + 4, cy + 5, 2, cx, cy, r - 16); + w.addColorStop(0, 'rgba(255,255,255,0.0)'); w.addColorStop(1, 'rgba(120,100,70,0.16)'); + ctx.beginPath(); ctx.arc(cx, cy, r - 16, 0, Math.PI * 2); ctx.fillStyle = w; ctx.fill(); + // Glaze highlight. + ctx.beginPath(); ctx.ellipse(cx - r * 0.42, cy - r * 0.5, r * 0.32, r * 0.12, -0.6, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(255,255,255,0.55)'; ctx.fill(); + addCanvas(scene, 'azul-plate', c); +} + +function bakeTray(scene) { + const S = SHADOW; + const c = canvas(TRAY.w + S * 2, TRAY.h + S * 2); + const ctx = c.getContext('2d'); + const rnd = mulberry32(5); + softShadow(ctx, () => { rr(ctx, S, S, TRAY.w, TRAY.h, 16); ctx.fillStyle = '#000'; ctx.fill(); }, { blur: 14, dy: 6 }); + rr(ctx, S, S, TRAY.w, TRAY.h, 16); + wood(ctx, S, S, TRAY.w, TRAY.h, '#8a5a30', '#5a361a', rnd, 5); + rr(ctx, S + 9, S + 9, TRAY.w - 18, TRAY.h - 18, 10); + const g = ctx.createRadialGradient(S + TRAY.w / 2, S + TRAY.h / 2, 10, S + TRAY.w / 2, S + TRAY.h / 2, TRAY.w * 0.6); + g.addColorStop(0, '#2f5a48'); g.addColorStop(1, '#1b3a2d'); + ctx.fillStyle = g; ctx.fill(); + ctx.save(); rr(ctx, S + 9, S + 9, TRAY.w - 18, TRAY.h - 18, 10); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 48, 26); ctx.fillRect(S, S, TRAY.w, TRAY.h); + // Inner shadow under the rim. + ctx.lineWidth = 8; ctx.strokeStyle = 'rgba(0,0,0,0.35)'; + rr(ctx, S + 9, S + 9, TRAY.w - 18, TRAY.h - 18, 10); ctx.stroke(); + ctx.restore(); + ctx.strokeStyle = 'rgba(255,220,170,0.25)'; ctx.lineWidth = 1.5; + rr(ctx, S + 2, S + 2, TRAY.w - 4, TRAY.h - 4, 14); ctx.stroke(); + addCanvas(scene, 'azul-tray', c); +} + +function bakeBag(scene) { + const S = SHADOW, w = BAG.w, h = BAG.h; + const c = canvas(w + S * 2, h + S * 2); + const ctx = c.getContext('2d'); + const x0 = S, y0 = S; + const body = () => { + ctx.beginPath(); + ctx.moveTo(x0 + w * 0.32, y0 + h * 0.22); + ctx.bezierCurveTo(x0 + w * 0.05, y0 + h * 0.35, x0 - 2, y0 + h * 0.8, x0 + w * 0.14, y0 + h * 0.95); + ctx.quadraticCurveTo(x0 + w * 0.5, y0 + h + 4, x0 + w * 0.86, y0 + h * 0.95); + ctx.bezierCurveTo(x0 + w + 2, y0 + h * 0.8, x0 + w * 0.95, y0 + h * 0.35, x0 + w * 0.68, y0 + h * 0.22); + ctx.closePath(); + }; + softShadow(ctx, () => { body(); ctx.fillStyle = '#000'; ctx.fill(); }, { blur: 16, dy: 8 }); + body(); + const g = ctx.createRadialGradient(x0 + w * 0.38, y0 + h * 0.5, 10, x0 + w * 0.5, y0 + h * 0.62, w * 0.75); + g.addColorStop(0, '#2f5f9e'); g.addColorStop(1, '#122c52'); + ctx.fillStyle = g; ctx.fill(); + ctx.save(); body(); ctx.clip(); + // Woven texture. + ctx.strokeStyle = 'rgba(255,255,255,0.05)'; ctx.lineWidth = 1; + for (let y = y0; y < y0 + h; y += 4) { ctx.beginPath(); ctx.moveTo(x0, y); ctx.lineTo(x0 + w, y + 2); ctx.stroke(); } + ctx.fillStyle = noisePattern(ctx, 48, 30); ctx.fillRect(x0, y0, w, h); + // Folds. + ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.lineWidth = 3; + for (const fx of [0.3, 0.5, 0.7]) { ctx.beginPath(); ctx.moveTo(x0 + w * fx, y0 + h * 0.26); ctx.quadraticCurveTo(x0 + w * (fx + 0.06), y0 + h * 0.5, x0 + w * (fx - 0.02), y0 + h * 0.62); ctx.stroke(); } + // An embroidered tile motif. + ctx.translate(x0 + w / 2, y0 + h * 0.64); ctx.rotate(Math.PI / 4); + ctx.strokeStyle = '#e9c46a'; ctx.lineWidth = 2.5; ctx.strokeRect(-20, -20, 40, 40); + ctx.strokeStyle = 'rgba(240,235,220,0.8)'; ctx.lineWidth = 1.5; ctx.strokeRect(-12, -12, 24, 24); + ctx.restore(); + // Gathered neck + drawstring. + ctx.fillStyle = '#183a6a'; + ctx.beginPath(); ctx.ellipse(x0 + w / 2, y0 + h * 0.2, w * 0.2, h * 0.06, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#244f8a'; + ctx.beginPath(); ctx.moveTo(x0 + w * 0.3, y0 + h * 0.2); ctx.lineTo(x0 + w * 0.36, y0 + 4); ctx.lineTo(x0 + w * 0.64, y0 + 4); ctx.lineTo(x0 + w * 0.7, y0 + h * 0.2); ctx.closePath(); ctx.fill(); + ctx.strokeStyle = '#d8b56a'; ctx.lineWidth = 4; ctx.lineCap = 'round'; + ctx.beginPath(); ctx.moveTo(x0 + w * 0.3, y0 + h * 0.21); ctx.quadraticCurveTo(x0 + w / 2, y0 + h * 0.27, x0 + w * 0.7, y0 + h * 0.21); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x0 + w * 0.62, y0 + h * 0.23); ctx.quadraticCurveTo(x0 + w * 0.8, y0 + h * 0.34, x0 + w * 0.74, y0 + h * 0.46); ctx.stroke(); + ctx.beginPath(); ctx.arc(x0 + w * 0.74, y0 + h * 0.47, 4, 0, Math.PI * 2); ctx.fillStyle = '#d8b56a'; ctx.fill(); + addCanvas(scene, 'azul-bag', c); +} + +function bakeLid(scene) { + const S = SHADOW, w = LID.w, h = LID.h; + const c = canvas(w + S * 2, h + S * 2); + const ctx = c.getContext('2d'); + const x0 = S, y0 = S; + softShadow(ctx, () => { rr(ctx, x0, y0, w, h, 8); ctx.fillStyle = '#000'; ctx.fill(); }, { blur: 14, dy: 6 }); + // Cardboard rim printed cobalt. + rr(ctx, x0, y0, w, h, 8); + const g = ctx.createLinearGradient(0, y0, 0, y0 + h); + g.addColorStop(0, '#2a62a6'); g.addColorStop(1, '#173c6c'); + ctx.fillStyle = g; ctx.fill(); + ctx.strokeStyle = '#c9a24a'; ctx.lineWidth = 2; rr(ctx, x0 + 3, y0 + 3, w - 6, h - 6, 6); ctx.stroke(); + // Interior. + rr(ctx, x0 + 12, y0 + 12, w - 24, h - 24, 4); + const ig = ctx.createLinearGradient(0, y0 + 12, 0, y0 + h - 12); + ig.addColorStop(0, '#2a2016'); ig.addColorStop(1, '#4a3b28'); + ctx.fillStyle = ig; ctx.fill(); + ctx.save(); rr(ctx, x0 + 12, y0 + 12, w - 24, h - 24, 4); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 48, 24); ctx.fillRect(x0, y0, w, h); + ctx.lineWidth = 10; ctx.strokeStyle = 'rgba(0,0,0,0.4)'; rr(ctx, x0 + 12, y0 + 12, w - 24, h - 24, 4); ctx.stroke(); + ctx.restore(); + addCanvas(scene, 'azul-lid', c); +} + +// ── panels and the order book ──────────────────────────────────────────────── +export function ensurePanel(scene, name, w, h, { header = true } = {}) { + const key = `azul-panel-${name}`; + if (scene.textures.exists(key)) return key; + const S = SHADOW; + const c = canvas(w + S * 2, h + S * 2); + const ctx = c.getContext('2d'); + const rnd = mulberry32(w * 7 + h); + softShadow(ctx, () => { rr(ctx, S, S, w, h, 12); ctx.fillStyle = '#000'; ctx.fill(); }, { blur: 16, dy: 7 }); + rr(ctx, S, S, w, h, 12); + wood(ctx, S, S, w, h, '#6a4122', '#3e2412', rnd, 5); + rr(ctx, S + 7, S + 7, w - 14, h - 14, 8); + const pg = ctx.createLinearGradient(0, S, 0, S + h); + pg.addColorStop(0, '#f3ead4'); pg.addColorStop(1, '#e4d5b2'); + ctx.fillStyle = pg; ctx.fill(); + ctx.save(); rr(ctx, S + 7, S + 7, w - 14, h - 14, 8); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 16); ctx.fillRect(S, S, w, h); + if (header) { + // Azulejo corner tiles. + for (const [cx, cy] of [[S + 7, S + 7], [S + w - 7 - 26, S + 7]]) { + ctx.fillStyle = '#f7f1e3'; ctx.fillRect(cx, cy, 26, 26); + ctx.strokeStyle = COBALT; ctx.lineWidth = 2; + ctx.beginPath(); ctx.arc(cx + 13, cy + 13, 8, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(cx + 13, cy + 2); ctx.lineTo(cx + 24, cy + 13); ctx.lineTo(cx + 13, cy + 24); ctx.lineTo(cx + 2, cy + 13); ctx.closePath(); ctx.stroke(); + } + } + ctx.restore(); + ctx.strokeStyle = 'rgba(201,162,74,0.8)'; ctx.lineWidth = 1.5; + rr(ctx, S + 11, S + 11, w - 22, h - 22, 6); ctx.stroke(); + addCanvas(scene, key, c); + return key; +} + +function bakeNotepad(scene) { + const S = SHADOW, w = NOTEPAD.w, h = NOTEPAD.h; + const c = canvas(w + S * 2, h + S * 2); + const ctx = c.getContext('2d'); + const x0 = S, y0 = S; + softShadow(ctx, () => { ctx.fillStyle = '#000'; ctx.fillRect(x0, y0 + 6, w, h - 6); }, { blur: 14, dy: 6 }); + // Leather spine. + rr(ctx, x0, y0, w, 30, 6); + ctx.fillStyle = '#6b2a1a'; ctx.fill(); + ctx.fillStyle = 'rgba(255,220,170,0.25)'; ctx.fillRect(x0 + 6, y0 + 6, w - 12, 2); + // Paper. + ctx.fillStyle = '#f6f0df'; + ctx.fillRect(x0 + 6, y0 + 26, w - 12, h - 28); + ctx.save(); ctx.beginPath(); ctx.rect(x0 + 6, y0 + 26, w - 12, h - 28); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 14); ctx.fillRect(x0, y0, w, h); + ctx.strokeStyle = 'rgba(60,110,170,0.25)'; ctx.lineWidth = 1; + for (let y = y0 + 70; y < y0 + h - 6; y += 26) { ctx.beginPath(); ctx.moveTo(x0 + 6, y); ctx.lineTo(x0 + w - 6, y); ctx.stroke(); } + ctx.strokeStyle = 'rgba(190,60,50,0.35)'; + ctx.beginPath(); ctx.moveTo(x0 + 44, y0 + 26); ctx.lineTo(x0 + 44, y0 + h); ctx.stroke(); + ctx.restore(); + // Rings. + for (let x = x0 + 40; x < x0 + w - 20; x += 48) { + ctx.beginPath(); ctx.arc(x, y0 + 26, 5, 0, Math.PI * 2); ctx.fillStyle = '#b9b2a0'; ctx.fill(); + ctx.strokeStyle = '#6d675a'; ctx.lineWidth = 1.5; ctx.stroke(); + } + addCanvas(scene, 'azul-notepad', c); +} + +// ── the room ────────────────────────────────────────────────────────────────── +function azulejo(ctx, x, y, s, rnd) { + ctx.fillStyle = '#f5f0e4'; + ctx.fillRect(x, y, s, s); + ctx.fillStyle = noisePattern(ctx, 32, 14); ctx.fillRect(x, y, s, s); + ctx.strokeStyle = COBALT; ctx.fillStyle = COBALT; + ctx.lineWidth = s * 0.06; + // Quarter arcs at each corner join into circles across tiles. + for (const [ax, ay] of [[0, 0], [1, 0], [0, 1], [1, 1]]) { + ctx.beginPath(); ctx.arc(x + ax * s, y + ay * s, s * 0.42, 0, Math.PI * 2); ctx.stroke(); + } + ctx.beginPath(); ctx.moveTo(x + s / 2, y + s * 0.16); ctx.lineTo(x + s * 0.84, y + s / 2); ctx.lineTo(x + s / 2, y + s * 0.84); ctx.lineTo(x + s * 0.16, y + s / 2); ctx.closePath(); + ctx.globalAlpha = 0.85; ctx.fill(); ctx.globalAlpha = 1; + ctx.fillStyle = '#e8b64a'; + ctx.beginPath(); ctx.arc(x + s / 2, y + s / 2, s * 0.1, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = `rgba(120,100,70,${0.25 + rnd() * 0.2})`; ctx.lineWidth = 1; + ctx.strokeRect(x + 0.5, y + 0.5, s - 1, s - 1); +} + +function bakeRoom(scene) { + const c = canvas(W, H); + const ctx = c.getContext('2d'); + const rnd = mulberry32(31); + // Oak workbench: long planks. + const plankH = 120; + for (let y = WAINSCOT.h, i = 0; y < H; y += plankH, i++) { + const t = i % 2 ? ['#8b5e34', '#704623'] : ['#966a3d', '#7a4f29']; + ctx.beginPath(); ctx.rect(0, y, W, plankH); + wood(ctx, 0, y, W, plankH, t[0], t[1], rnd, 6); + ctx.fillStyle = 'rgba(30,16,6,0.55)'; ctx.fillRect(0, y, W, 2); + ctx.fillStyle = 'rgba(255,220,170,0.08)'; ctx.fillRect(0, y + 2, W, 1); + // Butt joints. + const jx = (i * 613) % 1500 + 200; + ctx.fillStyle = 'rgba(30,16,6,0.4)'; ctx.fillRect(jx, y, 2, plankH); + } + // Wear: a few scratches and old glaze spatters. + for (let k = 0; k < 140; k++) { + const x = rnd() * W, y = WAINSCOT.h + rnd() * (H - WAINSCOT.h); + ctx.strokeStyle = `rgba(255,230,190,${0.03 + rnd() * 0.05})`; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + 10 + rnd() * 40, y + (rnd() - 0.5) * 6); ctx.stroke(); + } + for (let k = 0; k < 26; k++) { + const x = rnd() * W, y = WAINSCOT.h + rnd() * (H - WAINSCOT.h); + ctx.fillStyle = rnd() < 0.6 ? 'rgba(40,90,160,0.16)' : 'rgba(230,180,70,0.14)'; + ctx.beginPath(); ctx.arc(x, y, 1.5 + rnd() * 3.5, 0, Math.PI * 2); ctx.fill(); + } + // Lamp pool + vignette. + const lamp = ctx.createRadialGradient(960, 520, 60, 960, 560, 1150); + lamp.addColorStop(0, 'rgba(255,214,150,0.22)'); + lamp.addColorStop(0.45, 'rgba(255,190,120,0.06)'); + lamp.addColorStop(1, 'rgba(10,4,0,0.62)'); + ctx.fillStyle = lamp; ctx.fillRect(0, WAINSCOT.h, W, H - WAINSCOT.h); + // Wainscot: a band of azulejos with an ochre border. + const s = WAINSCOT.h - 8; + for (let x = -((W % s) / 2); x < W; x += s) azulejo(ctx, x, 0, s, rnd); + ctx.fillStyle = '#c9a24a'; ctx.fillRect(0, s, W, 3); + ctx.fillStyle = '#5a3a1c'; ctx.fillRect(0, s + 3, W, WAINSCOT.h - s - 3); + ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(0, WAINSCOT.h, W, 4); + // Title cartouche. + const tw = 230, th = 50, tx = TITLE.x - tw / 2, ty = TITLE.y - th / 2; + softShadow(ctx, () => { rr(ctx, tx, ty, tw, th, 10); ctx.fillStyle = '#000'; ctx.fill(); }, { blur: 10, dy: 4 }); + rr(ctx, tx, ty, tw, th, 10); + ctx.fillStyle = '#f6f0e1'; ctx.fill(); + ctx.lineWidth = 3; ctx.strokeStyle = COBALT; rr(ctx, tx + 4, ty + 4, tw - 8, th - 8, 7); ctx.stroke(); + ctx.lineWidth = 1; ctx.strokeStyle = '#c9a24a'; rr(ctx, tx + 8, ty + 8, tw - 16, th - 16, 5); ctx.stroke(); + ctx.font = `32px ${DISPLAY}`; + ctx.fillStyle = COBALT; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('AZUL', TITLE.x, TITLE.y + 2); + // A burlap mat under the bag and lid. + ctx.save(); + rr(ctx, 70, 380, 450, 250, 18); + ctx.fillStyle = 'rgba(176,146,98,0.55)'; ctx.fill(); + ctx.clip(); + ctx.strokeStyle = 'rgba(90,64,30,0.25)'; ctx.lineWidth = 1; + for (let x = 70; x < 520; x += 5) { ctx.beginPath(); ctx.moveTo(x, 380); ctx.lineTo(x, 630); ctx.stroke(); } + for (let y = 380; y < 630; y += 5) { ctx.beginPath(); ctx.moveTo(70, y); ctx.lineTo(520, y); ctx.stroke(); } + ctx.restore(); + addCanvas(scene, 'azul-room', c); +} + +// The wainscot alone (kept over a chosen playfield cloth). +function bakeWainscot(scene) { + const c = canvas(W, WAINSCOT.h + 4); + const ctx = c.getContext('2d'); + const room = scene.textures.get('azul-room').getSourceImage(); + ctx.drawImage(room, 0, 0, W, WAINSCOT.h + 4, 0, 0, W, WAINSCOT.h + 4); + addCanvas(scene, 'azul-wainscot', c); +} + +// ── FX ────────────────────────────────────────────────────────────────────────── +function bakeFx(scene) { + const radial = (key, s, stops) => { + const c = canvas(s, s); const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); + stops.forEach(([o, col]) => g.addColorStop(o, col)); + ctx.fillStyle = g; ctx.fillRect(0, 0, s, s); + addCanvas(scene, key, c); + }; + radial('azul-glow', 128, [[0, 'rgba(255,255,255,1)'], [0.4, 'rgba(255,255,255,0.45)'], [1, 'rgba(255,255,255,0)']]); + radial('azul-dust', 24, [[0, 'rgba(255,240,210,0.9)'], [1, 'rgba(255,240,210,0)']]); + { + const s = 32, c = canvas(s, s), ctx = c.getContext('2d'); + ctx.translate(s / 2, s / 2); ctx.fillStyle = '#fff'; + ctx.beginPath(); + for (let k = 0; k < 8; k++) { const r = k % 2 ? 4 : 15; const a = (k / 8) * Math.PI * 2; ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r); } + ctx.closePath(); ctx.fill(); + addCanvas(scene, 'azul-spark', c); + } + { + const c = canvas(64, 128), ctx = c.getContext('2d'); + const g = ctx.createLinearGradient(0, 0, 64, 0); + g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, 'rgba(255,255,255,0.85)'); g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, 64, 128); + addCanvas(scene, 'azul-glint', c); + } + { + // A shard for the floor-line "crack". + const c = canvas(16, 16), ctx = c.getContext('2d'); + ctx.fillStyle = '#fff'; + ctx.beginPath(); ctx.moveTo(2, 3); ctx.lineTo(14, 1); ctx.lineTo(10, 14); ctx.closePath(); ctx.fill(); + addCanvas(scene, 'azul-shard', c); + } +} + +// ── entry point ────────────────────────────────────────────────────────────────── +// Waits (briefly) for the display font so canvas text bakes in the right face. +export async function prepareAzulArt(scene, { glyphs = false, free = false } = {}) { + try { + if (document.fonts?.load) { + await Promise.race([ + Promise.all([document.fonts.load('20px Caesar'), document.fonts.load('14px "Julius Sans One"')]), + new Promise((res) => setTimeout(res, 1200)), + ]); + } + } catch (_) { /* fall back to Georgia */ } + bakeRoom(scene); + bakeWainscot(scene); + for (const c of COLORS) { bakeTile(scene, c, false); bakeTile(scene, c, true); } + bakeTile(scene, 'first', false); + ensureBoard(scene, 'big', { glyphs, free }); + ensureBoard(scene, 'mini', { glyphs, free }); + bakePlate(scene); + bakeTray(scene); + bakeBag(scene); + bakeLid(scene); + bakeNotepad(scene); + ensurePanel(scene, 'tracker', TRACKER.w, TRACKER.h); + ensurePanel(scene, 'action', ACTION.w, ACTION.h); + ensurePanel(scene, 'scores', SCORES.w, SCORES.h); + bakeFx(scene); +} diff --git a/src/games/azul/AzulDialogs.js b/src/games/azul/AzulDialogs.js new file mode 100644 index 0000000..4d18665 --- /dev/null +++ b/src/games/azul/AzulDialogs.js @@ -0,0 +1,141 @@ +// AzulDialogs.js — the workshop's pop-ups: a cream plaster card in a walnut +// frame with a cobalt hairline. Each opener returns { close() } and swallows +// clicks beneath it. +// +// openPauseMenu resume · opponent speed · helpers · wall variant · rules · new game · leave +// openLog the full order book (wheel scroll) +// confirmBox yes / no + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { SERIF, DISPLAY, COBALT, INK } from './AzulArt.js'; + +export function frame(scene, x, y, w, h, depth) { + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 4, y + 8, w, h, 14); + g.fillStyle(0x4a2d16, 1).fillRoundedRect(x, y, w, h, 14); + g.lineStyle(2, 0xc9a24a, 0.9).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 11); + g.fillStyle(0xf3ead4, 1).fillRoundedRect(x + 10, y + 10, w - 20, h - 20, 8); + g.lineStyle(2, 0x1d4f8f, 0.8).strokeRoundedRect(x + 16, y + 16, w - 32, h - 32, 6); + return g; +} + +export function blocker(scene, depth, alpha = 0) { + return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, alpha) + .setDepth(depth).setInteractive(); +} + +export function title(scene, x, y, text, depth, size = 26) { + return scene.add.text(x, y, text, { fontFamily: DISPLAY, fontSize: `${size}px`, color: COBALT, align: 'center' }) + .setOrigin(0.5).setDepth(depth); +} + +export function handle(objs, onClose) { + let closed = false; + return { + objs, + close() { + if (closed) return; + closed = true; + objs.forEach((o) => o?.destroy?.()); + onClose?.(); + }, + }; +} + +const onOff = (v) => (v ? 'On' : 'Off'); +const PACE_LABEL = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' }; + +// ── pause / settings ────────────────────────────────────────────────────────────── +export function openPauseMenu(scene, { settings, variantNow, depth, onChange, onRules, onNewGame, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 500, h = 720; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 50, 'The Workshop', depth + 1, 28)); + const cx = x + w / 2; + let hRef = null; + const variantLabel = () => { + const v = settings.variant === 'free' ? 'Free (grey) wall' : 'Printed wall'; + return `Wall: ${v}${settings.variant !== variantNow ? ' · next game' : ''}`; + }; + const rows = [ + ['Resume', () => hRef.close(), 0x1d4f8f], + [() => `Opponent speed: ${PACE_LABEL[settings.pace]}`, () => { + const order = ['relaxed', 'normal', 'fast']; + onChange('pace', order[(order.indexOf(settings.pace) + 1) % order.length]); + }], + [() => `Move preview: ${onOff(settings.preview)}`, () => onChange('preview', !settings.preview)], + [() => `Undo last move: ${onOff(settings.undo)}`, () => onChange('undo', !settings.undo)], + [() => `Tile tracker: ${onOff(settings.tracker)}`, () => onChange('tracker', !settings.tracker)], + [() => `Bonus hints on boards: ${onOff(settings.bonusHints)}`, () => onChange('bonusHints', !settings.bonusHints)], + [() => `Colour-blind symbols: ${onOff(settings.glyphs)}`, () => onChange('glyphs', !settings.glyphs)], + [variantLabel, () => onChange('variant', settings.variant === 'free' ? 'standard' : 'free')], + ['How to Play', () => onRules()], + ['New Game', () => { hRef.close(); onNewGame(); }, 0x6a4a1a], + ['Leave Table', () => { hRef.close(); onLeave(); }, 0x7a2a1a], + ]; + rows.forEach(([label, fn, bg], i) => { + const text = typeof label === 'function' ? label() : label; + const btn = new Button(scene, cx, y + 106 + i * 52, text, () => { + fn(); + if (typeof label === 'function') btn.setLabel(label()); + }, { width: 400, height: 44, fontSize: 17, bg: bg ?? 0x5a3820 }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(scene.add.text(cx, y + h - 34, 'Keys: 1–9 plates · C centre · ←/→ colour · ↑/↓ line · Enter place · F floor · Z undo · L log', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#5a4428', align: 'center', wordWrap: { width: w - 60 }, + }).setOrigin(0.5).setDepth(depth + 1)); + hRef = handle(objs, onClose); + return hRef; +} + +// ── log ──────────────────────────────────────────────────────────────────────────── +export function openLog(scene, { log, depth, onClose }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 760, h = 700; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 48, 'Order Book', depth + 1, 28)); + const viewY = y + 84, viewH = h - 160; + const lines = log.slice().reverse(); + const body = scene.add.text(x + 44, viewY, lines.join('\n'), { + fontFamily: SERIF, fontSize: '16px', color: '#1d3f6e', lineSpacing: 8, wordWrap: { width: w - 88 }, + }).setDepth(depth + 1); + const maskG = scene.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff).fillRect(x + 20, viewY, w - 40, viewH); + body.setMask(maskG.createGeometryMask()); + objs.push(body, { destroy: () => maskG.destroy() }); + const maxScroll = Math.max(0, body.height - viewH); + let off = 0; + const onWheel = (_p, _o, _dx, dy) => { off = Math.max(0, Math.min(maxScroll, off + dy * 0.6)); body.y = viewY - off; }; + scene.input.on('wheel', onWheel); + objs.push({ destroy: () => scene.input.off('wheel', onWheel) }); + if (maxScroll > 0) { + objs.push(scene.add.text(x + w - 44, viewY + viewH + 8, 'newest first · scroll for more ↓', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#5a4428', + }).setOrigin(1, 0).setDepth(depth + 1)); + } + let hRef = null; + objs.push(new Button(scene, x + w / 2, y + h - 42, 'Close', () => hRef.close(), { width: 200, height: 44, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2)); + objs[0].on('pointerdown', () => hRef.close()); + hRef = handle(objs, onClose); + return hRef; +} + +// ── confirm ──────────────────────────────────────────────────────────────────────── +export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 500, h = 240; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 48, heading, depth + 1, 24)); + objs.push(scene.add.text(x + w / 2, y + 104, text, { + fontFamily: SERIF, fontSize: '16px', color: INK, align: 'center', wordWrap: { width: w - 70 }, + }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + objs.push(new Button(scene, x + w / 2 - 112, y + h - 52, yes, () => { hRef.close(); onYes?.(); }, { width: 196, height: 46, fontSize: 18, bg: 0x1d4f8f }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 112, y + h - 52, no, () => { hRef.close(); onNo?.(); }, { width: 196, height: 46, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} diff --git a/src/games/azul/AzulEndScreen.js b/src/games/azul/AzulEndScreen.js new file mode 100644 index 0000000..61a1286 --- /dev/null +++ b/src/games/azul/AzulEndScreen.js @@ -0,0 +1,127 @@ +// AzulEndScreen.js — the final tally, shown after the end-game bonuses have +// been counted on the boards. A plaster card in a walnut frame with: +// • one row per player: rank, name, total, points by source (wall, floor, +// rows, columns, colours), their finished wall in miniature, a few stats +// • a points-by-round chart +// • Play Again · View Table (hide the card to look at the boards) · Leave + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { TILE_HEX, WALL_SIZE } from './AzulData.js'; +import { finalRanking, cellColor } from './AzulLogic.js'; +import { SERIF, DISPLAY, COBALT, INK } from './AzulArt.js'; +import { frame, blocker } from './AzulDialogs.js'; + +export const SEAT_INK = [0x1d4f8f, 0xa7311d, 0xb07a12, 0x3c7a3a]; +const hexStr = (n) => `#${n.toString(16).padStart(6, '0')}`; + +export function showAzulEndScreen(scene, { depth, onPlayAgain, onLeave, onHidePortraits, onShowPortraits }) { + const gs = scene.gs; + const ranking = finalRanking(gs); + const objs = []; + const add = (o) => { objs.push(o); return o; }; + const n = ranking.length; + const w = 1280, rowH = 92, chartH = 210; + const h = 150 + n * rowH + chartH + 96; + const x = GAME_WIDTH / 2 - w / 2, y = Math.max(16, GAME_HEIGHT / 2 - h / 2); + + add(blocker(scene, depth - 1, 0.55)); + add(frame(scene, x, y, w, h, depth)); + const top = ranking[0]; + const won = top.seat === 0; + const tied = ranking.length > 1 && ranking[1].score === top.score && ranking[1].rows === top.rows; + add(scene.add.text(x + w / 2, y + 52, tied ? 'A shared victory!' : won ? 'Your wall is the finest!' : `${top.name} wins the commission`, { + fontFamily: DISPLAY, fontSize: '34px', color: won ? '#b07a12' : COBALT, + }).setOrigin(0.5).setDepth(depth + 1)); + + // Column heads. + const cols = [ + ['Wall', 520], ['Floor', 590], ['Rows', 660], ['Columns', 740], ['Colours', 826], ['Total', 912], + ]; + const headY = y + 104; + cols.forEach(([t, cx]) => add(scene.add.text(x + cx, headY, t, { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#6b5226' }).setOrigin(0.5).setDepth(depth + 1))); + add(scene.add.text(x + 1010, headY, 'Wall', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#6b5226' }).setOrigin(0.5).setDepth(depth + 1)); + add(scene.add.text(x + 1150, headY, 'Stats', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#6b5226' }).setOrigin(0.5).setDepth(depth + 1)); + + ranking.forEach((r, i) => { + const p = gs.players[r.seat]; + const st = p.stats; + const ry = y + 150 + i * rowH; + const g = add(scene.add.graphics().setDepth(depth + 1)); + g.fillStyle(i === 0 ? 0xffe7a8 : r.seat === 0 ? 0xe6ecf4 : 0xffffff, i === 0 ? 0.85 : 0.5).fillRoundedRect(x + 36, ry - 38, w - 72, rowH - 12, 8); + g.fillStyle(SEAT_INK[r.seat % SEAT_INK.length], 1).fillRect(x + 36, ry - 38, 6, rowH - 12); + add(scene.add.text(x + 70, ry, `${i + 1}`, { fontFamily: 'Righteous', fontSize: '30px', color: i === 0 ? '#b07a12' : '#6b5226' }).setOrigin(0.5).setDepth(depth + 2)); + add(scene.add.text(x + 100, ry - 12, r.seat === 0 ? `${p.name} (you)` : p.name, { fontFamily: SERIF, fontSize: '22px', color: INK }).setOrigin(0, 0.5).setDepth(depth + 2)); + add(scene.add.text(x + 100, ry + 16, `${r.rows} row${r.rows === 1 ? '' : 's'} complete`, { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#6b5226' }).setOrigin(0, 0.5).setDepth(depth + 2)); + const b = gs.roundSummary?.[r.seat]?.endBonuses ?? { rowPts: 0, colPts: 0, colorPts: 0 }; + const vals = [`+${st.placementPts}`, st.floorLost ? `−${st.floorLost}` : '0', `+${b.rowPts}`, `+${b.colPts}`, `+${b.colorPts}`]; + vals.forEach((v, k) => add(scene.add.text(x + cols[k][1], ry, v, { + fontFamily: 'Righteous', fontSize: '20px', color: v.startsWith('−') ? '#a7311d' : INK, + }).setOrigin(0.5).setDepth(depth + 2))); + add(scene.add.text(x + cols[5][1], ry, `${p.score}`, { fontFamily: 'Righteous', fontSize: '30px', color: COBALT }).setOrigin(0.5).setDepth(depth + 2)); + // Miniature wall. + const cs = 13, wx = x + 1010 - (WALL_SIZE * cs) / 2, wy = ry - (WALL_SIZE * cs) / 2; + const wg = add(scene.add.graphics().setDepth(depth + 2)); + wg.fillStyle(0xc6b48c, 1).fillRect(wx - 2, wy - 2, WALL_SIZE * cs + 3, WALL_SIZE * cs + 3); + for (let rr = 0; rr < WALL_SIZE; rr++) for (let cc = 0; cc < WALL_SIZE; cc++) { + const col = cellColor(p, rr, cc); + wg.fillStyle(col ? TILE_HEX[col] : 0xeee4cc, 1).fillRect(wx + cc * cs, wy + rr * cs, cs - 1, cs - 1); + } + add(scene.add.text(x + 1080, ry, `set ${st.tilesPlaced} · floored ${st.tilesFloored}\nfirst ×${st.firstTaken} · best +${st.bestPlacement}`, { + fontFamily: SERIF, fontSize: '13px', color: INK, lineSpacing: 4, + }).setOrigin(0, 0.5).setDepth(depth + 2)); + }); + + // ── points by round ────────────────────────────────────────────────────────── + const cx0 = x + 110, cy0 = y + 150 + n * rowH + 10, cw = w - 260, ch = chartH - 40; + const series = gs.players.map((p) => [0, ...p.stats.roundScores]); + const maxV = Math.max(10, ...series.flat()); + const steps = Math.max(...series.map((s) => s.length)) - 1; + const cg = add(scene.add.graphics().setDepth(depth + 1)); + cg.fillStyle(0xffffff, 0.45).fillRoundedRect(cx0 - 60, cy0 - 10, cw + 120, ch + 50, 8); + cg.lineStyle(1, 0x6b5226, 0.35); + const gridStep = maxV > 60 ? 20 : 10; + for (let v = 0; v <= maxV; v += gridStep) { + const yy = cy0 + ch - (v / maxV) * ch; + cg.lineBetween(cx0, yy, cx0 + cw, yy); + add(scene.add.text(cx0 - 10, yy, `${v}`, { fontFamily: SERIF, fontSize: '11px', color: '#6b5226' }).setOrigin(1, 0.5).setDepth(depth + 2)); + } + const xAt = (k) => cx0 + (steps ? (k / steps) * cw : 0); + const lastRound = gs.round; + for (let k = 0; k <= steps; k++) { + const label = k === 0 ? 'start' : k <= lastRound ? `R${k}` : 'bonus'; + add(scene.add.text(xAt(k), cy0 + ch + 14, label, { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#6b5226' }).setOrigin(0.5).setDepth(depth + 2)); + } + series.forEach((s, seat) => { + const col = SEAT_INK[seat % SEAT_INK.length]; + cg.lineStyle(seat === 0 ? 4 : 2.5, col, 0.95); + cg.beginPath(); + s.forEach((v, k) => { const px = xAt(k), py = cy0 + ch - (v / maxV) * ch; if (k) cg.lineTo(px, py); else cg.moveTo(px, py); }); + cg.strokePath(); + s.forEach((v, k) => cg.fillStyle(col, 1).fillCircle(xAt(k), cy0 + ch - (v / maxV) * ch, seat === 0 ? 4.5 : 3.5)); + add(scene.add.text(xAt(steps) + 12, cy0 + ch - (s[s.length - 1] / maxV) * ch, gs.players[seat].name, { + fontFamily: SERIF, fontSize: '12px', color: hexStr(col), + }).setOrigin(0, 0.5).setDepth(depth + 2)); + }); + + // ── buttons ────────────────────────────────────────────────────────────────── + const by = y + h - 50; + let hidden = false; + const panelObjs = objs.slice(); + const viewBtn = new Button(scene, x + w / 2, by, 'View Table', () => { + hidden = !hidden; + panelObjs.forEach((o) => o.setVisible?.(!hidden)); + if (panelObjs[0].input) panelObjs[0].input.enabled = !hidden; // the click blocker + viewBtn.setLabel(hidden ? 'Show Results' : 'View Table'); + viewBtn.setPosition(hidden ? GAME_WIDTH / 2 : x + w / 2, hidden ? 652 : by); + if (hidden) onShowPortraits?.(); else onHidePortraits?.(); + }, { width: 220, height: 48, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 3); + add(viewBtn); + add(new Button(scene, x + w / 2 - 260, by, 'Play Again', () => onPlayAgain(), { width: 220, height: 48, fontSize: 19, bg: 0x1d4f8f }).setDepth(depth + 3)); + add(new Button(scene, x + w / 2 + 260, by, 'Leave', () => onLeave(), { width: 220, height: 48, fontSize: 19, bg: 0x7a2a1a }).setDepth(depth + 3)); + onHidePortraits?.(); + + // Fade in. + panelObjs.forEach((o) => { if (o.setAlpha) { const a = o.alpha; o.setAlpha(0); scene.tweens.add({ targets: o, alpha: a, duration: 350 }); } }); + return { close() { objs.forEach((o) => o.destroy?.()); } }; +} diff --git a/src/games/azul/AzulGame.js b/src/games/azul/AzulGame.js index 1bae81d..559a7f7 100644 --- a/src/games/azul/AzulGame.js +++ b/src/games/azul/AzulGame.js @@ -1,791 +1,1286 @@ +// AzulGame.js — the Azul table: a Lisbon tile workshop. +// +// A worn oak workbench under an azulejo wainscot. Glazed factory plates ring +// the centre tray; the tile bag and the box lid sit on a burlap mat; every +// player works at a walnut-framed board. All 100 tiles are persistent sprites +// (AzulTiles gives each a stable id) that slide between plate, centre, line, +// wall, floor, lid and bag. +// +// AzulLogic rules (pure) AzulAI opponents (skill 1–5) +// AzulLayout every rect (pure) AzulTiles tile identities (pure) +// AzulArt canvas bakes AzulHud panels, headers, dock +// AzulDialogs pause / log / confirm AzulEndScreen the final tally +// AzulSound ceramic clacks, chimes, the bag +// +// Quality of life: hover/keyboard move preview (where tiles land, floor cost, +// wall points, bonus progress), click or drag to place, undo until the next +// player moves, a tile tracker, bonus badges, opponent board zoom, colour-blind +// symbols, adjustable pace, and the free (grey) wall variant. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { Tooltip } from '../../ui/Tooltip.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { PACE, clampSkill } from '../../ui/cardtable/AITiming.js'; import { - COLORS as TILE_COLORS, TILE_HEX, TILE_EDGE, TILE_NAME, - FLOOR_PENALTIES, FLOOR_SIZE, WALL_SIZE, - factoryCount, lineCapacity, wallColor, tileFrame, FIRST_PLAYER_FRAME, + COLORS as TILE_COLORS, TILE_NAME, WALL_SIZE, FLOOR_SIZE, FLOOR_PENALTIES, lineCapacity, } from './AzulData.js'; +import * as L from './AzulLogic.js'; +import * as AI from './AzulAI.js'; +import { TileTracker, TILE_COUNT, colorOfId } from './AzulTiles.js'; import { - createInitialState, legalMoves, applyMove, resolveRound, - lineAccepts, isGameOver, finalRanking, -} from './AzulLogic.js'; -import { chooseMove, nextThinkDelay } from './AzulAI.js'; + BIG, RING, TRAY, BAG, LID, MUSIC, MENU_BTN, LOG_BTN, HELP_BTN, POPOVER, BANNER, SUPPLY, + boardOf, tilePose, lineZoneAt, floorZoneAt, wallCellAt, lineTileAt, floorCellAt, platePos, portraitPos, contains, +} from './AzulLayout.js'; +import { + prepareAzulArt, ensureBoard, boardKey, tileKey, tileDisplay, TILE_FACE_OFF, SHADOW, PLATE_TEX, + SERIF, DISPLAY, +} from './AzulArt.js'; +import { AzulHud } from './AzulHud.js'; +import { openPauseMenu, openLog, confirmBox } from './AzulDialogs.js'; +import { showAzulEndScreen } from './AzulEndScreen.js'; +import { clack, tap, crunch, chime, thunk, rattle, flourish } from './AzulSound.js'; -const CX = GAME_WIDTH / 2; -const DEPTH = { bg: 0, panel: 6, tray: 8, board: 10, hint: 11, glow: 13, tile: 16, label: 30, ui: 40, banner: 90 }; - -// Player boards use the warm cream/tan of the retail cardboard board, so the -// on-board text and empty cells are drawn dark for contrast. -const BOARD_FILL = 0xe7d9b6; -const BOARD_EDGE = 0x9c7c46; -const BOARD_INK_HEX = '#3a2c16'; // dark-brown name text -const BOARD_SCORE_HEX = '#5c3d0e'; // deep gold score, readable on cream -const BOARD_LINE = 0x6b5226; // dark-tan cell outlines (strong on cream) -const BOARD_PEN_HEX = '#7a2018'; // dark maroon for floor penalty numbers - -// Opponent mini-boards (top row). -const MINI = { tile: 24, cell: 27, wallGap: 16, pad: 10, headerH: 44, floorCell: 22, top: 70, gap: 104 }; -const MINI_W = MINI.pad * 2 + 5 * MINI.cell + MINI.wallGap + 5 * MINI.cell; // ≈ 296 -const MINI_H = MINI.headerH + 5 * MINI.cell + 16 + MINI.floorCell + 12; // ≈ 232 -// Opponent avatars hang mostly to the left of their board, overlapping only a -// little; the wide gap leaves room for them between boards. -const OPP_PORTRAIT_R = 46; -const OPP_PORTRAIT_OVERLAP = 18; - -// Human board (bottom). Its x is set below so the board + instructions panel -// pair is centred on screen. -const HB = { tile: 42, cell: 50, wallGap: 22, pad: 12, headerH: 42, floorCell: 40, x: 0, y: 690 }; -const HUMAN_W = HB.pad * 2 + 5 * HB.cell + HB.wallGap + 5 * HB.cell; // ≈ 546 -const HUMAN_H = HB.headerH + 5 * HB.cell + 16 + HB.floorCell + 12; // ≈ 360 -const HUMAN_PORTRAIT_R = 56; - -// Instructions panel sits to the right of the board with a small gutter. -const PANEL_GAP = 36, PANEL_W = 560; -// Centre the [board · gap · panel] group horizontally. -HB.x = CX - (HUMAN_W + PANEL_GAP + PANEL_W) / 2; -const PANEL_X = HB.x + HUMAN_W + PANEL_GAP; - -// Factory ring (centre band) — an ellipse so it fits between the two rows. -const RING = { cx: CX, cy: 470, rx: 250, ry: 116, disc: 44, ftile: 30 }; -const TRAY = { cx: CX, cy: 470, w: 300, h: 150, tile: 26, gap: 4 }; +const D = { + room: -30, furniture: -20, board: -12, panel: -11, boardGlow: -10, label: 2, ghost: 4, runGlow: 5, + zoneLow: 5, tile: 6, tileLift: 9, zone: 12, popover: 30, flight: 40, fx: 45, banner: 60, modal: 70, tooltip: 95, +}; +const SETTINGS_KEY = 'azul-settings'; +const DEFAULT_SETTINGS = { + pace: 'normal', preview: true, undo: true, tracker: true, bonusHints: true, glyphs: false, variant: 'standard', +}; +const HUMAN = 0; +const srcKey = (source) => (source.type === 'center' ? 'c' : `f${source.index}`); +const sameSource = (a, b) => a && b && a.type === b.type && (a.type === 'center' || a.index === b.index); +const srcLabel = (source) => (source.type === 'center' ? 'the centre' : `plate ${source.index + 1}`); +const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`; export default class AzulGame extends Phaser.Scene { constructor() { super('AzulGame'); } init(data) { - this._initData = { ...data }; - this.gameDef = data.game; + this.initData = { ...data }; + this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; - this.humanSeat = 0; - this.gs = null; - this.busy = false; - this.sel = null; // { source, color } currently picked up - this.dyn = []; // dynamic objects rebuilt every render + this.gs = null; + this.busy = true; + this.ended = false; + this.modal = null; + this.sel = null; // { source, color } + this.hoverLine = null; // line index | 'floor' | null (preview target) + this.kbLine = null; + this.drag = null; + this.undoSnap = null; + this.aiTimer = null; this.portraits = []; - this.skillBySeat = {}; - this.animating = null; // suppresses just-placed tiles while they fly in - this.scoreHide = null; // during round scoring: seat → Set(rows) to hide - this.scoreOverlay = []; // persistent landed wall tiles during scoring + this.ghosts = []; + this.popover = null; + this.pick = null; // free-wall column picking + try { this.settings = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } + catch (_) { this.settings = { ...DEFAULT_SETTINGS }; } } create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch { /* optional */ } - this.hasArt = this.textures.exists('azul-tiles'); - - const playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); - const names = []; - for (let seat = 0; seat < playerCount; seat++) { - if (seat === this.humanSeat) { - names.push(auth.user?.username ?? 'You'); - this.skillBySeat[seat] = 5; - } else { - const opp = this.opponents[seat - 1]; - names.push(opp?.name ?? `Player ${seat}`); - this.skillBySeat[seat] = Math.max(1, Math.min(5, opp?.skill ?? 3)); - } - } - - this.buildBackground(); - this.gs = createInitialState({ playerCount, names }); - this.buildPortraits(); - this.render(); - this.advance(); + try { + new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? [], undefined, { + right: MUSIC.right, top: MUSIC.top, infoColor: '#f3e6c8', + }); + } catch (_) { /* no music json */ } + this.events.once('shutdown', () => { this.ended = true; }); + prepareAzulArt(this, { glyphs: this.settings.glyphs, free: this.settings.variant === 'free' }).then(() => { + if (!this.sys?.isActive()) return; + this.build(); + }); } - // ── chrome ────────────────────────────────────────────────────────────────── - buildBackground() { + // ── build ───────────────────────────────────────────────────────────────────── + build() { + const playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); + this.n = playerCount; + this.names = []; + this.skill = []; + for (let seat = 0; seat < playerCount; seat++) { + if (seat === HUMAN) { this.names.push(auth.user?.username ?? 'You'); this.skill.push(5); } + else { + const opp = this.opponents[seat - 1]; + this.names.push(opp?.name ?? `Player ${seat}`); + this.skill.push(clampSkill(opp?.skill ?? 3)); + } + } + this.gs = L.createInitialState({ playerCount, names: this.names, variant: this.settings.variant }); + this.free = this.gs.variant === 'free'; + + this.tooltip = new Tooltip(this, { depth: D.tooltip, hoverDelay: 260 }); + this.buildRoom(); + this.buildBoards(); + this.buildSupply(); + this.hud = new AzulHud(this, { depth: D, playerCount, names: this.names, tooltip: this.tooltip }); + this.buildButtons(); + this.buildPortraits(); + this.buildZones(); + this.buildTiles(); + this.buildFx(); + this.buildInput(); + this.refreshHud(); + this.hud.setAction('A new commission', 'The tiles are being dealt…'); + this.time.delayedCall(350, () => this.dealAnimation(this.initialDeal).then(() => this.advance())); + } + + get k() { return PACE[this.settings.pace] ?? 1; } + wait(ms) { return new Promise((res) => this.time.delayedCall(Math.max(0, ms), res)); } + tw(cfg) { return new Promise((res) => this.tweens.add({ ...cfg, onComplete: () => { cfg.onComplete?.(); res(); } })); } + + buildRoom() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, 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); + this.add.image(0, 0, 'azul-wainscot').setOrigin(0).setDepth(D.room + 1); + // Keep the title cartouche legible over the cloth. } else { - const g = this.add.graphics().setDepth(DEPTH.bg); - g.fillGradientStyle(0x16130d, 0x16130d, 0x070503, 0x070503, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); + this.add.image(0, 0, 'azul-room').setOrigin(0).setDepth(D.room); } - this.add.text(CX, 22, 'Azul', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex, - }).setOrigin(0.5, 0).setDepth(DEPTH.ui); + // A slow warm flicker from the workshop lamp. + this.lamp = this.add.image(960, 520, 'azul-glow').setDisplaySize(2000, 1300) + .setTint(0xffc27a).setBlendMode('ADD').setAlpha(0.05).setDepth(D.fx - 1); + this.time.addEvent({ + delay: 2600, loop: true, + callback: () => this.tweens.add({ targets: this.lamp, alpha: 0.035 + Math.random() * 0.035, duration: 1000 + Math.random() * 900 }), + }); + // Dust motes drifting in the lamp light. + this.dust = this.add.particles(0, 0, 'azul-dust', { + x: { min: 300, max: 1620 }, y: { min: 120, max: 900 }, lifespan: 9000, speedX: { min: -6, max: 6 }, speedY: { min: -4, max: 3 }, + scale: { min: 0.2, max: 0.55 }, alpha: { values: [0, 0.32, 0.32, 0], interpolation: 'linear' }, frequency: 650, blendMode: 'ADD', + }).setDepth(D.fx - 2); + } - new Button(this, GAME_WIDTH - 96, GAME_HEIGHT - 34, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 140, height: 42, fontSize: 18 }).setDepth(DEPTH.ui); + buildBoards() { + const opts = { free: this.free, glyphs: this.settings.glyphs }; + this.boardImgs = []; + for (let seat = 0; seat < this.n; seat++) { + const { rect, m } = boardOf(seat, this.n); + const key = ensureBoard(this, m.size, opts); + this.boardImgs.push(this.add.image(rect.x - SHADOW, rect.y - SHADOW, key).setOrigin(0).setDepth(D.board)); + } + } + + buildSupply() { + const n = this.gs.factories.length; + this.plates = []; + for (let i = 0; i < n; i++) { + const p = platePos(i, n); + const img = this.add.image(p.x, p.y + 3, 'azul-plate').setDisplaySize(PLATE_TEX, PLATE_TEX).setDepth(D.furniture); + const num = this.add.text(p.x + RING.r * 0.72, p.y - RING.r * 0.78, `${i + 1}`, { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'bold', color: '#f6efdc', backgroundColor: '#1d4f8f', padding: { x: 4, y: 1 }, + }).setOrigin(0.5).setDepth(D.label); + this.plates.push({ img, num }); + } + this.add.image(TRAY.cx - TRAY.w / 2 - SHADOW, TRAY.cy - TRAY.h / 2 - SHADOW, 'azul-tray').setOrigin(0).setDepth(D.furniture); + this.bag = this.add.image(BAG.x, BAG.y, 'azul-bag').setDisplaySize(BAG.w + SHADOW * 2, BAG.h + SHADOW * 2).setDepth(D.furniture); + this.add.image(LID.x, LID.y, 'azul-lid').setDisplaySize(LID.w + SHADOW * 2, LID.h + SHADOW * 2).setDepth(D.furniture); + const lbl = (x, y, t) => this.add.text(x, y, t, { fontFamily: DISPLAY, fontSize: '16px', color: '#f6efdc', stroke: '#2a1a0a', strokeThickness: 4 }).setOrigin(0.5).setDepth(D.label); + lbl(BAG.x, SUPPLY.y + 24, 'Bag'); + lbl(LID.x, LID.y - LID.h / 2 - 18, 'Lid'); + this.bagCount = this.add.text(BAG.x, BAG.y + BAG.h / 2 + 4, '', { fontFamily: 'Righteous', fontSize: '18px', color: '#f6efdc', stroke: '#2a1a0a', strokeThickness: 4 }).setOrigin(0.5).setDepth(D.label); + this.lidCount = this.add.text(LID.x, LID.y + LID.h / 2 + 18, '', { fontFamily: 'Righteous', fontSize: '18px', color: '#f6efdc', stroke: '#2a1a0a', strokeThickness: 4 }).setOrigin(0.5).setDepth(D.label); + // A small heap of discards in the lid (decoration; count is exact below it). + this.lidHeap = Array.from({ length: 14 }, (_, i) => { + const jx = ((i * 37) % 100) / 100 - 0.5, jy = ((i * 61) % 100) / 100 - 0.5; + return this.add.image(LID.x + jx * (LID.w - 60), LID.y + jy * (LID.h - 50), tileKey('blue', false)) + .setDisplaySize(tileDisplay(22), tileDisplay(22)).setAngle((i * 47) % 40 - 20).setDepth(D.furniture + 1).setVisible(false); + }); + const bz = this.add.zone(BAG.x, BAG.y, BAG.w, BAG.h).setInteractive().setDepth(D.zoneLow); + this.tooltip.attachTo(bz, () => this.bagTooltip('bag')); + const lz = this.add.zone(LID.x, LID.y, LID.w, LID.h).setInteractive().setDepth(D.zoneLow); + this.tooltip.attachTo(lz, () => this.bagTooltip('lid')); + } + + bagTooltip(which) { + const gs = this.gs; + const src = which === 'bag' ? gs.bag : gs.lid; + const total = TILE_COLORS.reduce((a, c) => a + src[c], 0); + return { + title: which === 'bag' ? `Tile bag — ${total}` : `Box lid (discards) — ${total}`, + lines: [ + ...TILE_COLORS.map((c) => ({ text: `${TILE_NAME[c]}: ${src[c]}` })), + { text: which === 'bag' ? 'Plates are filled from here. When it runs dry, the lid is poured back in.' : 'Surplus tiles from tiled lines and every floor tile end up here.', color: '#b8a888' }, + ], + }; + } + + buildButtons() { + const mk = (r, label, fn) => new Button(this, r.x + r.w / 2, r.y + r.h / 2, label, fn, { + width: r.w, height: r.h, fontSize: 16, bg: 0x173f72, + }).setDepth(D.label + 4); + mk(MENU_BTN, '☰ Menu', () => this.openMenu()); + mk(LOG_BTN, 'Log', () => this.openLogView()); + mk(HELP_BTN, 'How to Play', () => this.openRules()); } buildPortraits() { - // Human avatar hangs off the left edge of their board, like the opponents. - const hp = this.humanPortraitPos(); - this.portraits[this.humanSeat] = createPlayerPortrait(this, hp.x, hp.y, HUMAN_PORTRAIT_R, DEPTH.ui + 1, 'AzulGame'); - // Opponent avatars hang off the left edge of each mini-board. - for (let k = 0; k < this.nOpp; k++) { - const pos = this.oppPortraitPos(k); - this.portraits[k + 1] = createOpponentPortrait(this, this.opponents[k], pos.x, pos.y, OPP_PORTRAIT_R, DEPTH.ui + 1); + for (let seat = 0; seat < this.n; seat++) { + const pp = portraitPos(seat, this.n); + this.portraits[seat] = seat === HUMAN + ? createPlayerPortrait(this, pp.x, pp.y, pp.r, D.label + 3, 'AzulGame') + : createOpponentPortrait(this, this.opponents[seat - 1], pp.x, pp.y, pp.r, D.label + 3); + } + } + hidePortraits() { this.portraits.forEach((p) => p?.hide?.()); } + showPortraits() { this.portraits.forEach((p) => p?.show?.()); } + emote(seat, e) { if (seat !== HUMAN) this.portraits[seat]?.playEmotion?.(e); } + + // Drop zones on the human board + hover zones on the opponents' boards. + buildZones() { + const { rect, m } = boardOf(HUMAN, this.n); + this.lineZones = []; + for (let r = 0; r < WALL_SIZE; r++) { + const z = lineZoneAt(rect, m, r); + const zone = this.add.zone(z.x + z.w / 2, z.y + z.h / 2, z.w, z.h).setInteractive({ useHandCursor: true }).setDepth(D.zone); + zone.on('pointerover', () => this.onLineHover(r)); + zone.on('pointerout', () => this.onLineHover(null, r)); + zone.on('pointerdown', () => this.onLineClick(r)); + this.lineZones.push(zone); + } + const fz = floorZoneAt(rect, m); + this.floorZone = this.add.zone(fz.x + fz.w / 2, fz.y + fz.h / 2, fz.w, fz.h).setInteractive({ useHandCursor: true }).setDepth(D.zone); + this.floorZone.on('pointerover', () => this.onLineHover('floor')); + this.floorZone.on('pointerout', () => this.onLineHover(null, 'floor')); + this.floorZone.on('pointerdown', () => this.onLineClick('floor')); + this.tooltip.attachTo(this.floorZone, () => ({ + title: 'Floor line', + lines: [ + { text: `Penalties ${FLOOR_PENALTIES.join(' ')} — paid when the round's walls are tiled (your score never drops below 0).` }, + { text: 'Overflow and unwanted tiles land here; the first-player marker does too.' }, + ], + }), { delay: 700 }); + this.zoneGfx = this.add.graphics().setDepth(D.ghost); + this.runGfx = this.add.graphics().setDepth(D.runGlow + 2); + + this.oppZones = []; + for (let seat = 1; seat < this.n; seat++) { + const { rect: r } = boardOf(seat, this.n); + const z = this.add.zone(r.x + r.w / 2, r.y + r.h / 2, r.w, r.h).setInteractive().setDepth(D.zoneLow); + z.on('pointerover', () => { this._popTimer?.remove(); this._popTimer = this.time.delayedCall(280, () => this.showPopover(seat)); }); + z.on('pointerout', () => { this._popTimer?.remove(); this.hidePopover(); }); + this.oppZones.push(z); } } - oppPortraitPos(k) { - const o = this.miniOrigin(k); - return { x: o.x - OPP_PORTRAIT_R + OPP_PORTRAIT_OVERLAP, y: o.y + 50 }; - } - humanPortraitPos() { - return { x: HB.x - HUMAN_PORTRAIT_R + OPP_PORTRAIT_OVERLAP, y: HB.y + HUMAN_PORTRAIT_R + 8 }; - } - - // ── geometry helpers ───────────────────────────────────────────────────────── - get nOpp() { return this.gs.playerCount - 1; } - - miniOrigin(k) { - const rowW = this.nOpp * MINI_W + (this.nOpp - 1) * MINI.gap; - const startX = CX - rowW / 2; - return { x: startX + k * (MINI_W + MINI.gap), y: MINI.top }; - } - humanOrigin() { return { x: HB.x, y: HB.y }; } - - boardScoreAnchor(seat) { - if (seat === this.humanSeat) { const o = this.humanOrigin(); return { x: o.x + HUMAN_W - 30, y: o.y + 20 }; } - const o = this.miniOrigin(seat - 1); return { x: o.x + MINI_W - 26, y: o.y + 20 }; - } - - // Per-seat board metrics + cell-centre positions (shared by render & animation). - boardLayout(seat) { - return (seat === this.humanSeat) - ? { origin: this.humanOrigin(), m: HB } - : { origin: this.miniOrigin(seat - 1), m: MINI }; - } - patternCellPos(seat, row, colIndex) { - const { origin, m } = this.boardLayout(seat); - return { - x: origin.x + m.pad + colIndex * m.cell + m.cell / 2, - y: origin.y + m.headerH + row * m.cell + m.cell / 2, - }; - } - floorCellPos(seat, k) { - const { origin, m } = this.boardLayout(seat); - return { - x: origin.x + m.pad + k * (m.floorCell + 2) + m.floorCell / 2, - y: origin.y + m.headerH + 5 * m.cell + 16 + m.floorCell / 2, - }; - } - - // Screen positions of the selected-colour tiles currently in their source. - sourceTilePositions(source, color) { - const out = []; - if (source.type === 'factory') { - const n = factoryCount(this.gs.playerCount); - const ang = -Math.PI / 2 + (source.index / n) * Math.PI * 2; - const dx = RING.cx + Math.cos(ang) * RING.rx; - const dy = RING.cy + Math.sin(ang) * RING.ry; - const off = RING.ftile / 2 + 1; - const slots = [[-off, -off], [off, -off], [-off, off], [off, off]]; - this.gs.factories[source.index].forEach((c, ti) => { - if (c === color) { const [sx, sy] = slots[ti] ?? [0, 0]; out.push({ x: dx + sx, y: dy + sy }); } - }); - } else { - const items = []; - if (this.gs.centerHasFirst) items.push('first'); - for (const cc of TILE_COLORS) for (const t of this.gs.center) if (t === cc) items.push(t); - const step = TRAY.tile + TRAY.gap; - const perRow = Math.max(1, Math.floor((TRAY.w - 16) / step)); - const left = TRAY.cx - (perRow * step - TRAY.gap) / 2 + TRAY.tile / 2; - const top = TRAY.cy - TRAY.h / 2 + 18 + TRAY.tile / 2; - items.forEach((c, idx) => { - if (c !== color) return; - out.push({ x: left + (idx % perRow) * step, y: top + Math.floor(idx / perRow) * step }); - }); + // ── tiles ─────────────────────────────────────────────────────────────────── + buildTiles() { + const g = this.settings.glyphs; + this.tracker = new TileTracker(this.gs); + this.sprites = []; + for (let id = 0; id < TILE_COUNT; id++) { + const img = this.add.image(BAG.x, BAG.y - 40, tileKey(colorOfId(id), g)).setDepth(D.tile).setVisible(false); + img.tileId = id; + img.setInteractive({ hitArea: new Phaser.Geom.Rectangle(7, 5, 96, 96), hitAreaCallback: Phaser.Geom.Rectangle.Contains, useHandCursor: true }); + img.on('pointerover', () => this.onTileOver(id)); + img.on('pointerout', () => this.onTileOut(id)); + img.on('pointerdown', (ptr) => this.onTileDown(id, ptr)); + this.sprites.push(img); } - return out; - } - - // Final resting cell positions for the tiles a move places (pre-move state). - destTilePositions(seat, move) { - const p = this.gs.players[seat]; - const color = move.color; - const taken = (move.source.type === 'factory') - ? this.gs.factories[move.source.index].filter((t) => t === color).length - : this.gs.center.filter((t) => t === color).length; - const out = []; - // Taking from the centre also drops the first-player marker on the floor, - // which shifts any overflow tiles one slot to the right. - const firstExtra = (move.source.type === 'center' && this.gs.centerHasFirst) ? 1 : 0; - const preFloor = p.floor.length + firstExtra; - const floorSlot = (k) => this.floorCellPos(seat, Math.min(preFloor + k, FLOOR_SIZE - 1)); - if (move.line === 'floor') { - for (let k = 0; k < taken; k++) out.push(floorSlot(k)); - } else { - const cap = lineCapacity(move.line); - const oldCount = p.lines[move.line].count; - const placed = Math.min(cap - oldCount, taken); - for (let j = 0; j < placed; j++) out.push(this.patternCellPos(seat, move.line, 5 - oldCount - 1 - j)); - for (let k = 0; k < taken - placed; k++) out.push(floorSlot(k)); + this.marker = this.add.image(BAG.x, BAG.y, 'azul-t-first').setDepth(D.tile).setVisible(false); + this.placeMarker(false); + // The opening deal is animated from the bag. + this.initialDeal = []; + for (let id = 0; id < TILE_COUNT; id++) { + const loc = this.tracker.loc(id); + if (loc.kind === 'factory') this.initialDeal.push({ id, from: { kind: 'bag' }, to: loc, moved: true, fromKey: 'bag', toKey: `f${loc.index}` }); } - return out; + this.updateInteractivity(); } - // ── render plumbing ────────────────────────────────────────────────────────── - reg(obj) { this.dyn.push(obj); return obj; } - clearDyn() { for (const o of this.dyn) { try { o.destroy(); } catch { /* noop */ } } this.dyn = []; } - - canInput() { - return !this.busy && this.gs.phase === 'offer' && this.gs.current === this.humanSeat; + // Sprite position/size for a face pose. + spriteAt(pose) { + const ds = tileDisplay(pose.size); + return { x: pose.x - TILE_FACE_OFF.x * pose.size, y: pose.y - TILE_FACE_OFF.y * pose.size, ds }; } - pname(seat) { return this.gs.players[seat]?.name ?? `Player ${seat}`; } - sameSource(a, b) { return a.type === b.type && (a.type === 'center' || a.index === b.index); } - - // ── a single tile (sprite or vector fallback) ──────────────────────────────── - // Dark contour + soft drop shadow built from tinted duplicate sprites (the PNG - // alpha defines the shape, so they wrap only visible pixels). Plain batched - // sprites — no postFX — so they don't flicker while tweens are running. - addTileFx(cx, cy, size, frame, depth) { - const sw = Math.max(1.5, size * 0.045); // outline thickness - const sh = Math.max(1.5, size * 0.06); // shadow drop - // Drop shadow (furthest back), kept subtle. - this.reg(this.add.image(cx, cy + sh, 'azul-tiles', frame) - .setDisplaySize(size, size).setTintFill(0x000000).setAlpha(0.25).setDepth(depth - 2)); - // Dark outline: silhouettes nudged in 8 directions. - const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]]; - for (const [dx, dy] of dirs) { - this.reg(this.add.image(cx + dx * sw, cy + dy * sw, 'azul-tiles', frame) - .setDisplaySize(size, size).setTintFill(0x140d04).setDepth(depth - 1)); + poseOf(id) { return tilePose(this.tracker.loc(id), this.n); } + place(img, pose) { + const s = this.spriteAt(pose); + img.setPosition(s.x, s.y).setDisplaySize(s.ds, s.ds).setVisible(!pose.hidden).setAlpha(1).setDepth(D.tile); + } + placeMarker(animate = true) { + const loc = TileTracker.markerLoc(this.gs); + const pose = tilePose(loc, this.n); + const s = this.spriteAt(pose); + if (!animate || !this.marker.visible) { + this.marker.setPosition(s.x, s.y).setDisplaySize(s.ds, s.ds).setVisible(!loc.hidden); + return Promise.resolve(); + } + return this.tw({ targets: this.marker, x: s.x, y: s.y, displayWidth: s.ds, displayHeight: s.ds, duration: 420 * this.k, ease: 'Cubic.easeInOut' }); + } + updateInteractivity() { + for (let id = 0; id < TILE_COUNT; id++) { + const kind = this.tracker.loc(id).kind; + if (this.sprites[id].input) this.sprites[id].input.enabled = kind === 'factory' || kind === 'center'; } } - - makeTile(cx, cy, size, color, { depth = DEPTH.tile, selectable = false, onPick = null, highlight = false, fx = false } = {}) { - if (highlight) { - this.reg(this.add.rectangle(cx, cy, size + 8, size + 8, COLORS.gold, 0) - .setStrokeStyle(3, COLORS.gold).setDepth(depth - 1)); - } - let main; - if (this.hasArt) { - const frame = color === 'first' ? FIRST_PLAYER_FRAME : tileFrame(color); - if (fx) this.addTileFx(cx, cy, size, frame, depth); - main = this.add.image(cx, cy, 'azul-tiles', frame).setDisplaySize(size, size).setDepth(depth); - } else { - const hex = color === 'first' ? 0x2c2b30 : TILE_HEX[color]; - const edge = color === 'first' ? 0xdfe6e9 : TILE_EDGE[color]; - main = this.add.rectangle(cx, cy, size, size, hex).setStrokeStyle(2, edge).setDepth(depth); - if (color === 'first') { - this.reg(this.add.text(cx, cy, '1', { fontFamily: 'Righteous', fontSize: `${Math.floor(size * 0.6)}px`, color: '#eef' }) - .setOrigin(0.5).setDepth(depth + 1)); - } - } - this.reg(main); - if (selectable && onPick) { - main.setInteractive({ useHandCursor: true }); - main.on('pointerdown', () => { if (this.canInput()) onPick(); }); - } - return main; + snapAll() { + for (let id = 0; id < TILE_COUNT; id++) { this.tweens.killTweensOf(this.sprites[id]); this.place(this.sprites[id], this.poseOf(id)); } + this.placeMarker(false); } - // A transient tile that flies between source and destination. Not registered - // in `dyn` (so render()'s clearDyn won't kill it mid-flight); the tween frees it. - makeFlyingTile(x, y, size, color, depth = DEPTH.banner - 4) { - if (this.hasArt) { - const frame = color === 'first' ? FIRST_PLAYER_FRAME : tileFrame(color); - return this.add.image(x, y, 'azul-tiles', frame).setDisplaySize(size, size).setDepth(depth); - } - const hex = color === 'first' ? 0x2c2b30 : TILE_HEX[color]; - return this.add.rectangle(x, y, size, size, hex).setStrokeStyle(2, TILE_EDGE[color] ?? 0xdfe6e9).setDepth(depth); - } - - emptyCell(cx, cy, size, depth = DEPTH.board + 1) { - this.reg(this.add.rectangle(cx, cy, size, size, 0x000000, 0.14).setStrokeStyle(2, BOARD_LINE, 0.85).setDepth(depth)); - } - hintCell(cx, cy, size, color, depth = DEPTH.board + 1) { - this.reg(this.add.rectangle(cx, cy, size, size, TILE_HEX[color], 0.42).setStrokeStyle(2, BOARD_LINE, 0.85).setDepth(depth)); - } - - // ── full render ────────────────────────────────────────────────────────────── - render() { - this.clearDyn(); - this.drawSupply(); - for (let k = 0; k < this.nOpp; k++) this.drawBoard(k + 1, this.miniOrigin(k), MINI, false); - this.drawBoard(this.humanSeat, this.humanOrigin(), { ...HB, cell: HB.cell, tile: HB.tile, wallGap: HB.wallGap, pad: HB.pad, headerH: HB.headerH, floorCell: HB.floorCell }, true); - this.drawStatus(); - } - - // Factories ring + centre pool. - drawSupply() { - const n = factoryCount(this.gs.playerCount); - - // Centre tray (drawn under the discs) — same cream as the player boards. - this.reg(this.add.rectangle(TRAY.cx, TRAY.cy, TRAY.w, TRAY.h, BOARD_FILL, 0.97) - .setStrokeStyle(2, BOARD_EDGE, 0.85).setDepth(DEPTH.tray)); - this.reg(this.add.text(TRAY.cx, TRAY.cy - TRAY.h / 2 - 16, 'Centre', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.tray)); - this.drawCenterTiles(); - - // Factory discs evenly spaced around the ellipse, top-anchored. - for (let i = 0; i < n; i++) { - const ang = -Math.PI / 2 + (i / n) * Math.PI * 2; - const dx = RING.cx + Math.cos(ang) * RING.rx; - const dy = RING.cy + Math.sin(ang) * RING.ry; - this.reg(this.add.circle(dx, dy, RING.disc, BOARD_FILL).setStrokeStyle(3, BOARD_EDGE, 0.9).setDepth(DEPTH.board)); - const tiles = this.gs.factories[i]; - const off = RING.ftile / 2 + 1; - const slots = [[-off, -off], [off, -off], [-off, off], [off, off]]; - tiles.forEach((color, ti) => { - const [sx, sy] = slots[ti] ?? [0, 0]; - const highlight = this.sel && this.sameSource(this.sel.source, { type: 'factory', index: i }) && this.sel.color === color; - this.makeTile(dx + sx, dy + sy, RING.ftile, color, { - selectable: true, - highlight, - onPick: () => this.onTileClick({ type: 'factory', index: i }, color), - }); - }); - } - } - - drawCenterTiles() { - const items = []; - if (this.gs.centerHasFirst) items.push('first'); - // Group by colour for a tidy read. - for (const c of TILE_COLORS) for (const t of this.gs.center) if (t === c) items.push(t); - - const step = TRAY.tile + TRAY.gap; - const perRow = Math.max(1, Math.floor((TRAY.w - 16) / step)); - const left = TRAY.cx - (perRow * step - TRAY.gap) / 2 + TRAY.tile / 2; - const top = TRAY.cy - TRAY.h / 2 + 18 + TRAY.tile / 2; - items.forEach((color, idx) => { - const r = Math.floor(idx / perRow), c = idx % perRow; - const x = left + c * step; - const y = top + r * step; - if (color === 'first') { - this.makeTile(x, y, TRAY.tile, 'first'); // marker is not selectable - return; - } - const highlight = this.sel && this.sameSource(this.sel.source, { type: 'center' }) && this.sel.color === color; - this.makeTile(x, y, TRAY.tile, color, { - selectable: true, - highlight, - onPick: () => this.onTileClick({ type: 'center' }, color), - }); - }); - } - - // One player board (mini or full). `m` carries the per-size metrics. - drawBoard(seat, origin, m, interactive) { - const p = this.gs.players[seat]; - const w = (m === MINI) ? MINI_W : HUMAN_W; - const h = (m === MINI) ? MINI_H : HUMAN_H; - const ox = origin.x, oy = origin.y; - const active = this.gs.phase === 'offer' && this.gs.current === seat; - - // Panel — warm cream cardboard, like the retail player board. - this.reg(this.add.rectangle(ox + w / 2, oy + h / 2, w, h, BOARD_FILL, 0.97) - .setStrokeStyle(active ? 4 : 2, active ? COLORS.gold : BOARD_EDGE, active ? 1 : 0.85) - .setDepth(DEPTH.panel)); - - // Header: name + score (dark ink on cream). - const nameX = ox + m.pad + 16; // clears the left-hanging avatar - this.reg(this.add.text(nameX, oy + 12, p.name + (seat === this.humanSeat ? ' (you)' : ''), { - fontFamily: 'Righteous', fontSize: (m === MINI ? '16px' : '20px'), color: BOARD_INK_HEX, - }).setOrigin(0, 0).setDepth(DEPTH.label)); - this.reg(this.add.text(ox + w - m.pad, oy + 10, `${p.score}`, { - fontFamily: 'Righteous', fontSize: (m === MINI ? '22px' : '30px'), color: BOARD_SCORE_HEX, - }).setOrigin(1, 0).setDepth(DEPTH.label)); - - const bodyTop = oy + m.headerH; - const patternLeft = ox + m.pad; - const wallLeft = patternLeft + 5 * m.cell + m.wallGap; - // While a move's tiles fly in, keep their resting cells empty on this board. - const anim = (this.animating && this.animating.seat === seat) ? this.animating : null; - const fx = (seat === this.humanSeat); // dark stroke + shadow on the player's tiles - - // Pattern lines (capacity i+1, filled right-to-left) and the wall. - for (let i = 0; i < WALL_SIZE; i++) { - const rowCY = bodyTop + i * m.cell + m.cell / 2; - const cap = lineCapacity(i); - const line = p.lines[i]; - let shownCount = (anim && anim.line === i) ? anim.lineShown : line.count; - if (this.scoreHide && this.scoreHide[seat] && this.scoreHide[seat].has(i)) shownCount = 0; - for (let cidx = 5 - cap; cidx < 5; cidx++) { - const cellCX = patternLeft + cidx * m.cell + m.cell / 2; - const filledFromRight = cidx >= 5 - shownCount; - if (filledFromRight && line.color) this.makeTile(cellCX, rowCY, m.tile, line.color, { fx }); - else this.emptyCell(cellCX, rowCY, m.tile); - } - // Wall row. - for (let j = 0; j < WALL_SIZE; j++) { - const cellCX = wallLeft + j * m.cell + m.cell / 2; - const wc = wallColor(i, j); - if (p.wall[i][j]) this.makeTile(cellCX, rowCY, m.tile, wc, { fx }); - else this.hintCell(cellCX, rowCY, m.tile, wc); - } - - // Interactive destination zone for the human's legal lines. - if (interactive && this.sel && this.canInput() && lineAccepts(p, i, this.sel.color)) { - const zone = this.add.rectangle(patternLeft + (5 * m.cell) / 2, rowCY, 5 * m.cell, m.cell, COLORS.gold, 0.12) - .setStrokeStyle(2, COLORS.gold, 0.9).setDepth(DEPTH.glow).setInteractive({ useHandCursor: true }); - zone.on('pointerdown', () => this.onLineClick(i)); - this.reg(zone); - } - } - - // Floor line. - const floorY = bodyTop + 5 * m.cell + 16 + m.floorCell / 2; - const floorShown = anim ? anim.floorShown : p.floor.length; - for (let k = 0; k < FLOOR_SIZE; k++) { - const cellCX = patternLeft + k * (m.floorCell + 2) + m.floorCell / 2; - this.emptyCell(cellCX, floorY, m.floorCell); - this.reg(this.add.text(cellCX, floorY - m.floorCell / 2 - 7, `${FLOOR_PENALTIES[k]}`, { - fontFamily: '"Julius Sans One"', fontSize: (m === MINI ? '10px' : '13px'), color: BOARD_PEN_HEX, - }).setOrigin(0.5, 1).setDepth(DEPTH.label)); - if (k < floorShown && p.floor[k] !== undefined) this.makeTile(cellCX, floorY, m.floorCell - 4, p.floor[k], { fx }); - } - if (interactive && this.sel && this.canInput()) { - const fw = FLOOR_SIZE * (m.floorCell + 2); - const zone = this.add.rectangle(patternLeft + fw / 2 - 1, floorY, fw, m.floorCell, COLORS.danger, 0.10) - .setStrokeStyle(2, COLORS.danger, 0.7).setDepth(DEPTH.glow).setInteractive({ useHandCursor: true }); - zone.on('pointerdown', () => this.onLineClick('floor')); - this.reg(zone); - } - } - - // ── status panel (right of the human board) ────────────────────────────────── - drawStatus() { - // Panel mirrors the human board's vertical band (same top & height) and sits - // just to its right, so the two read as a balanced pair. - const PX = PANEL_X, PY = HB.y, PW = PANEL_W, PH = HUMAN_H, R = 18; - const cx = PX + PW / 2; - - const g = this.add.graphics().setDepth(DEPTH.panel); - g.fillStyle(0x000000, 0.72); - g.fillRoundedRect(PX, PY, PW, PH, R); - g.lineStyle(2.5, COLORS.accent, 0.75); - g.strokeRoundedRect(PX, PY, PW, PH, R); - this.reg(g); - - // Header + divider. - this.reg(this.add.text(cx, PY + 32, `Round ${this.gs.round}`, { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.label)); - const div = this.add.graphics().setDepth(DEPTH.label); - div.lineStyle(1.5, COLORS.accent, 0.4); - div.lineBetween(PX + 44, PY + 62, PX + PW - 44, PY + 62); - this.reg(div); - - // Status message (centred). - let msg, color = COLORS.textHex; - if (isGameOver(this.gs)) { msg = 'Game over'; color = COLORS.mutedHex; } - else if (this.gs.current !== this.humanSeat) { msg = `${this.pname(this.gs.current)}\nis thinking…`; color = COLORS.mutedHex; } - else if (this.sel) { - const src = this.sel.source.type === 'center' ? 'the centre' : `factory ${this.sel.source.index + 1}`; - msg = `Picked ${TILE_NAME[this.sel.color]} from ${src}.\n\nClick a glowing pattern line,\nor the floor line.`; - color = COLORS.goldHex; - } else { - msg = 'Your turn.\n\nClick a tile to take every tile of\nthat colour from a factory or the centre.'; - } - this.reg(this.add.text(cx, PY + 168, msg, { - fontFamily: '"Julius Sans One"', fontSize: '21px', color, align: 'center', lineSpacing: 8, - }).setOrigin(0.5).setDepth(DEPTH.label)); - - // Cancel button (centred) while a pick is held. - if (this.sel && this.canInput()) { - this.reg(new Button(this, cx, PY + 270, 'Cancel pick', () => { this.sel = null; this.render(); }, - { variant: 'ghost', width: 180, height: 42, fontSize: 18 }).setDepth(DEPTH.ui)); - } - - // Tile-bag summary at the foot. - const bagTotal = TILE_COLORS.reduce((s, c) => s + this.gs.bag[c], 0); - const lidTotal = TILE_COLORS.reduce((s, c) => s + this.gs.lid[c], 0); - this.reg(this.add.text(cx, PY + PH - 30, `Bag ${bagTotal} · Discard ${lidTotal}`, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.label)); - } - - // ── input ──────────────────────────────────────────────────────────────────── - onTileClick(source, color) { - if (!this.canInput()) return; - if (this.sel && this.sameSource(this.sel.source, source) && this.sel.color === color) { - this.sel = null; // toggle off - } else { - this.sel = { source, color }; - playSound(this, SFX.UI_PICK); - } - this.render(); - } - - onLineClick(line) { - if (!this.canInput() || !this.sel) return; - const move = { source: this.sel.source, color: this.sel.color, line }; - // Guard: pattern-line moves must be legal (floor always is). - if (line !== 'floor' && !lineAccepts(this.gs.players[this.humanSeat], line, this.sel.color)) return; - this.sel = null; - this.busy = true; - this.animateMove(this.humanSeat, move, () => this.advance()); - } - - // Apply `move` for `seat`, but fly the taken tiles from their source to their - // resting cells over ~0.75s before the board reveals them. - animateMove(seat, move, onComplete) { - const color = move.color; - const srcs = this.sourceTilePositions(move.source, color); - const dests = this.destTilePositions(seat, move); - const destSize = this.boardLayout(seat).m.tile; - - // Remember how much of the destination was already present so render() can - // hide the newly-placed tiles until they land. - const p = this.gs.players[seat]; - this.animating = { - seat, - line: (move.line === 'floor') ? null : move.line, - lineShown: (move.line === 'floor') ? 0 : p.lines[move.line].count, - floorShown: p.floor.length, - }; - - this.gs = applyMove(this.gs, move); - this.render(); - - const n = Math.max(srcs.length, dests.length); - if (n === 0) { this.finishAnimateMove(onComplete); return; } - - let landed = 0; - for (let k = 0; k < n; k++) { - const s = srcs[k] ?? srcs[srcs.length - 1] ?? dests[k]; - const d = dests[k] ?? dests[dests.length - 1]; - const fly = this.makeFlyingTile(s.x, s.y, destSize, color); + // Fly one tile to `pose`. Arc + a lift scale; from the bag it starts small. + flyTile(id, pose, { delay = 0, dur = 520, arc = 34, fromBag = false, toHidden = false, fade = false } = {}) { + const img = this.sprites[id]; + this.tweens.killTweensOf(img); + const s = this.spriteAt(pose); + if (fromBag) { + img.setPosition(BAG.x + (Math.random() - 0.5) * 30, BAG.y - BAG.h * 0.32).setDisplaySize(s.ds * 0.5, s.ds * 0.5).setVisible(true).setAlpha(0); + } else img.setVisible(true); + const x0 = img.x, y0 = img.y, d0 = img.displayWidth; + const dist = Math.hypot(s.x - x0, s.y - y0); + const duration = Math.max(160, Math.min(dur * 1.4, dur * (0.55 + dist / 900))) * this.k; + const lift = Math.min(arc, dist * 0.25); + const o = { t: 0 }; + return new Promise((res) => { this.tweens.add({ - targets: fly, x: d.x, y: d.y, duration: 750, ease: 'Cubic.easeInOut', - delay: k * 40, - onComplete: () => { fly.destroy(); if (++landed >= n) this.finishAnimateMove(onComplete); }, - }); - } - } - - finishAnimateMove(onComplete) { - this.animating = null; - this.render(); - playSound(this, SFX.UI_PLACE); - this.time.delayedCall(80, () => onComplete && onComplete()); - } - - // ── turn loop ──────────────────────────────────────────────────────────────── - advance() { - if (isGameOver(this.gs)) { this.render(); this.onGameOver(); return; } - if (this.gs.phase === 'scoring') { this.resolveRoundAnimated(); return; } - // Safety net: a deal that leaves nothing draftable (no tiles anywhere) can't - // progress — end on current scores rather than hang. Practically unreachable. - if (legalMoves(this.gs).length === 0) { this.render(); this.onGameOver(); return; } - if (this.gs.current === this.humanSeat) { this.busy = false; this.render(); return; } - this.aiTurn(); - } - - aiTurn() { - this.busy = true; - this.render(); - const seat = this.gs.current; - const skill = this.skillBySeat[seat]; - this.showBanner(`${this.pname(seat)}'s turn`); - this.time.delayedCall(nextThinkDelay(skill), () => { - const move = chooseMove(this.gs, skill); - if (!move) { this.busy = false; this.advance(); return; } - this.animateMove(seat, move, () => this.advance()); - }); - } - - // End-of-round scoring. Renders the pre-tiling state (completed pattern lines - // still full), then animates each board in turn: every completed row merges - // into one tile and flies to its wall cell. The resolved state is only shown - // once every board has finished. - resolveRoundAnimated() { - this.busy = true; - this.showBanner(`Wall-tiling — round ${this.gs.round}`); - this.render(); // pre-resolve frame - const resolved = resolveRound(this.gs); - const summary = resolved.roundSummary ?? []; - playSound(this, SFX.UI_CHIME); - - this.scoreHide = {}; // seat → Set(rows) whose pattern tiles are hidden - this.scoreOverlay = []; // persistent "landed" wall tiles drawn over the board - - this.animateScoring(summary, () => { - for (const o of this.scoreOverlay) { try { o.destroy(); } catch { /* noop */ } } - this.scoreOverlay = []; - this.scoreHide = null; - this.gs = resolved; - this.render(); - this.time.delayedCall(500, () => { this.busy = false; this.advance(); }); - }); - } - - // Walk the boards one at a time (player first), animating each in full. - animateScoring(summary, onDone) { - const order = this.gs.players.map((_, i) => i); - let idx = 0; - const nextSeat = () => { - if (idx >= order.length) { onDone(); return; } - const seat = order[idx++]; - const entry = summary.find((e) => e.seat === seat) ?? { placements: [], floorPenalty: 0 }; - this.animateSeatScoring(seat, entry, nextSeat); - }; - nextSeat(); - } - - animateSeatScoring(seat, entry, done) { - const placements = entry.placements ?? []; - const hasFloor = (entry.floorPenalty ?? 0) < 0; - if (placements.length === 0 && !hasFloor) { done(); return; } - - this.flashBoard(seat); - // Opponents react: happy when they bank a wall tile, upset on a net loss. - const emotion = (seat !== this.humanSeat) ? this.scoringEmotion(entry) : null; - - if (placements.length === 0) { // floor penalty only - const a = this.boardScoreAnchor(seat); - this.floatText(a.x - 10, a.y + 30, `${entry.floorPenalty}`, COLORS.dangerHex, { size: 24 }); - if (emotion) this.portraits[seat]?.playEmotion?.(emotion); - this.time.delayedCall(650, done); - return; - } - - // Hide every completing row's pattern tiles up front, then fly each in. - if (!this.scoreHide[seat]) this.scoreHide[seat] = new Set(); - for (const pl of placements) this.scoreHide[seat].add(pl.row); - this.render(); - - // A happy reaction fires as the first wall tile lands (~merge + move time). - if (emotion === 'happy') this.time.delayedCall(720, () => this.portraits[seat]?.playEmotion?.('happy')); - - let pending = placements.length; - const rowFinished = () => { - if (--pending > 0) return; - if (hasFloor) { - const a = this.boardScoreAnchor(seat); - this.floatText(a.x - 10, a.y + 30, `${entry.floorPenalty}`, COLORS.dangerHex, { size: 24 }); - } - if (emotion === 'upset') this.portraits[seat]?.playEmotion?.('upset'); - this.time.delayedCall(hasFloor ? 550 : 300, done); - }; - placements.forEach((pl, i) => { - this.time.delayedCall(i * 120, () => this.animateScoreRow(seat, pl, rowFinished)); - }); - } - - // Which reaction (if any) an opponent shows for a round. Completing a row is - // happy unless floor penalties drag the round's net score negative, in which - // case (or with no placements at all) they're upset. - scoringEmotion(entry) { - const placements = entry.placements ?? []; - const penalty = entry.floorPenalty ?? 0; - const gained = entry.gained ?? placements.reduce((s, p) => s + (p.points || 0), 0); - if (placements.length >= 1 && gained + penalty >= 0) return 'happy'; - if (penalty < 0) return 'upset'; - return null; - } - - // One completed row: its tiles converge to a single tile, which then flies to - // its wall cell and stays there (as an overlay) until the board is rebuilt. - animateScoreRow(seat, placement, rowDone) { - const { row, col, color, points } = placement; - const size = this.boardLayout(seat).m.tile; - const merge = this.patternCellPos(seat, row, 4); // rightmost pattern cell - - const tiles = []; - for (let c = 4 - row; c <= 4; c++) { - const pos = this.patternCellPos(seat, row, c); - tiles.push(this.makeFlyingTile(pos.x, pos.y, size, color)); - } - playSound(this, SFX.UI_PICK); - - let merged = 0; - tiles.forEach((t, i) => { - this.tweens.add({ - targets: t, x: merge.x, y: merge.y, duration: 280, ease: 'Cubic.easeIn', + targets: o, t: 1, delay: delay * this.k, duration, ease: 'Cubic.easeInOut', + onStart: () => { img.setDepth(D.flight); if (fromBag) img.setAlpha(1); }, + onUpdate: () => { + const t = o.t; + const bump = Math.sin(Math.PI * t); + img.setPosition(x0 + (s.x - x0) * t, y0 + (s.y - y0) * t - lift * bump); + const ds = d0 + (s.ds - d0) * t; + img.setDisplaySize(ds * (1 + 0.12 * bump), ds * (1 + 0.12 * bump)); + if (fade) img.setAlpha(1 - t * 0.9); + }, onComplete: () => { - if (i !== 0) t.destroy(); - if (++merged < tiles.length) return; - // The single surviving tile flies to its wall cell. - const dest = this.wallCellPos(seat, row, col); - const lead = tiles[0]; - lead.setDepth(DEPTH.banner - 3); - this.tweens.add({ - targets: lead, x: dest.x, y: dest.y, duration: 430, ease: 'Cubic.easeInOut', - onComplete: () => { - lead.destroy(); - this.scoreOverlay.push(this.makeFlyingTile(dest.x, dest.y, size, color, DEPTH.banner - 6)); - playSound(this, SFX.UI_PLACE); - if (points) this.floatText(dest.x, dest.y - size * 0.55, `+${points}`, COLORS.goldHex, { size: 22 }); - rowDone(); - }, - }); + img.setDepth(D.tile); + if (toHidden || pose.hidden) img.setVisible(false).setAlpha(1); + res(); }, }); }); } - flashBoard(seat) { - const { origin, m } = this.boardLayout(seat); - const w = (m === MINI) ? MINI_W : HUMAN_W; - const h = (m === MINI) ? MINI_H : HUMAN_H; - const fr = this.add.rectangle(origin.x + w / 2, origin.y + h / 2, w + 10, h + 10, COLORS.gold, 0) - .setStrokeStyle(4, COLORS.gold, 0.9).setDepth(DEPTH.banner - 2); - this.tweens.add({ targets: fr, alpha: 0, duration: 750, ease: 'Cubic.easeOut', onComplete: () => fr.destroy() }); + buildFx() { + this.sparks = this.add.particles(0, 0, 'azul-spark', { + lifespan: 650, speed: { min: 60, max: 200 }, angle: { min: 0, max: 360 }, scale: { start: 0.7, end: 0 }, + alpha: { start: 1, end: 0 }, tint: [0xffe08a, 0xffffff, 0x9cc2ff], emitting: false, blendMode: 'ADD', + }).setDepth(D.fx); + this.shards = this.add.particles(0, 0, 'azul-shard', { + lifespan: 600, speed: { min: 50, max: 160 }, angle: { min: 200, max: 340 }, gravityY: 420, rotate: { min: 0, max: 360 }, + scale: { start: 0.8, end: 0.3 }, alpha: { start: 1, end: 0 }, emitting: false, + }).setDepth(D.fx); } - wallCellPos(seat, row, col) { - const { origin, m } = this.boardLayout(seat); - const wallLeft = origin.x + m.pad + 5 * m.cell + m.wallGap; - return { x: wallLeft + col * m.cell + m.cell / 2, y: origin.y + m.headerH + row * m.cell + m.cell / 2 }; - } - - floatText(x, y, text, colorHex, { size = 24, depth = DEPTH.banner, rise = 26, dur = 1200 } = {}) { - const t = this.add.text(x, y, text, { fontFamily: 'Righteous', fontSize: `${size}px`, color: colorHex }) - .setOrigin(0.5).setDepth(depth); - this.tweens.add({ targets: t, y: y - rise, alpha: 0, duration: dur, ease: 'Cubic.easeOut', onComplete: () => t.destroy() }); - return t; - } - - showBanner(text) { - const banner = this.add.text(CX, 360, text, { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.textHex, - backgroundColor: '#111923ee', padding: { x: 22, y: 10 }, - }).setOrigin(0.5).setDepth(DEPTH.banner); - this.tweens.add({ - targets: banner, y: 386, duration: 260, ease: 'Back.easeOut', - onComplete: () => this.time.delayedCall(750, () => - this.tweens.add({ targets: banner, alpha: 0, y: 360, duration: 220, onComplete: () => banner.destroy() })), + // ── HUD refresh ──────────────────────────────────────────────────────────────── + refreshHud() { + const gs = this.gs; + this.hud.setRound(gs); + this.hud.setTracker(L.tileCensus(gs), this.settings.tracker); + this.hud.setBonuses(gs, this.settings.bonusHints); + this.hud.setLog(gs.log); + this.hud.setStartPlayer(gs.startPlayer, !gs.centerHasFirst && gs.phase === 'offer'); + const bag = TILE_COLORS.reduce((a, c) => a + gs.bag[c], 0); + const lid = TILE_COLORS.reduce((a, c) => a + gs.lid[c], 0); + this.bagCount.setText(`${bag} tiles`); + this.lidCount.setText(`${lid} discarded`); + const lidCols = []; + for (const c of TILE_COLORS) for (let k = 0; k < gs.lid[c]; k++) lidCols.push(c); + this.lidHeap.forEach((img, i) => { + const c = lidCols[Math.floor((i * lidCols.length) / this.lidHeap.length)]; + const show = i < Math.min(this.lidHeap.length, Math.ceil(lid / 2)); + img.setVisible(show && !!c); + if (c) img.setTexture(tileKey(c, false)); }); } - // ── game over ──────────────────────────────────────────────────────────────── - onGameOver() { + // ── turn loop ────────────────────────────────────────────────────────────────── + advance() { + if (this.ended) return; + this.refreshHud(); + if (L.isGameOver(this.gs)) { this.finishGame(); return; } + if (this.gs.phase === 'scoring') { + this.busy = true; + this.hud.setActive(-1); + const grace = this.undoSnap ? this.undoWindow() : 0; + this.setDockForWaiting(); + this.aiTimer = this.time.delayedCall(grace, () => { this.aiTimer = null; this.undoSnap = null; this.scoreRound(); }); + return; + } + if (L.legalMoves(this.gs).length === 0) { this.finishGame(); return; } + this.hud.setActive(this.gs.current); + if (this.gs.current === HUMAN) { this.busy = false; this.undoSnap = null; this.promptHuman(); return; } + this.aiTurn(); + } + + undoWindow() { return Math.round(1300 * this.k); } + + canInput() { + return !this.busy && !this.modal && !this.ended && !this.pick && this.gs?.phase === 'offer' && this.gs.current === HUMAN; + } + + promptHuman() { + this.sel = null; + this.kbLine = null; + this.clearPreview(); + this.drawZones(); + const p = this.gs.players[HUMAN]; + const blocked = TILE_COLORS.filter((c) => L.legalMoves(this.gs).some((m) => m.color === c)) + .every((c) => ![0, 1, 2, 3, 4].some((i) => L.lineAccepts(p, i, c, this.free))); + this.hud.setAction('Your turn', blocked + ? 'None of the colours on the table fit your pattern lines. Pick tiles to send to your floor — the fewest is usually best.' + : 'Click a tile to take every tile of that colour from a plate or the centre, then click (or drag to) a glowing pattern line.', 'you'); + this.hud.setPreview(null); + this.hud.setDock([]); + } + + setDockForWaiting() { + const buttons = []; + if (this.settings.undo && this.undoSnap) buttons.push({ label: 'Undo (Z)', fn: () => this.undo(), bg: 0x6a4a1a }); + this.hud.setDock(buttons); + } + + aiTurn() { this.busy = true; - const ranking = finalRanking(this.gs); - const humanRank = ranking.findIndex((r) => r.seat === this.humanSeat); - const won = humanRank === 0; - const humanScore = this.gs.players[this.humanSeat].score; - const oppScores = ranking.filter((r) => r.seat !== this.humanSeat).map((r) => r.score); - this.recordResult(won ? 'win' : 'loss', humanScore, oppScores); - - const cx = CX, cy = GAME_HEIGHT / 2; - const w = 640, h = 120 + ranking.length * 46; - this.add.rectangle(cx, cy, w, h, 0x0a0e14, 0.95).setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.banner); - this.add.text(cx, cy - h / 2 + 30, won ? '🎉 You win!' : 'Game over', { - fontFamily: 'Righteous', fontSize: '34px', color: won ? COLORS.goldHex : COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); - ranking.forEach((r, i) => { - this.add.text(cx, cy - h / 2 + 80 + i * 40, - `${i + 1}. ${this.pname(r.seat)}${r.seat === this.humanSeat ? ' (you)' : ''} — ${r.score} pts`, { - fontFamily: '"Julius Sans One"', fontSize: '22px', - color: i === 0 ? COLORS.goldHex : COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); + const seat = this.gs.current; + this.hud.setAction(`${this.names[seat]}'s turn`, `${this.names[seat]} is studying the plates…`); + this.hud.setPreview(null); + this.setDockForWaiting(); + const think = AI.nextThinkDelay(this.skill[seat]) * this.k; + const delay = this.undoSnap ? Math.max(think, this.undoWindow()) : think; + this.aiTimer = this.time.delayedCall(delay, async () => { + this.aiTimer = null; + this.undoSnap = null; + this.hud.setDock([]); + if (this.ended) return; + const move = AI.chooseMove(this.gs, this.skill[seat]); + if (!move) { this.finishGame(); return; } + await this.flashSource(move.source, move.color, 420 * this.k); + if (this.ended) return; + await this.doMove(seat, move); + if (!this.ended) this.advance(); + }); + } + + // Briefly lift + glow the tiles an AI is about to take. + async flashSource(source, color, ms) { + const ids = this.tracker.idsIn(srcKey(source)).filter((id) => colorOfId(id) === color); + const glows = ids.map((id) => { + const s = this.sprites[id]; + return this.add.image(s.x, s.y, 'azul-glow').setDisplaySize(s.displayWidth * 1.5, s.displayWidth * 1.5) + .setTint(0xffd36b).setBlendMode('ADD').setAlpha(0).setDepth(D.tile - 1); + }); + this.tweens.add({ targets: glows, alpha: 0.85, duration: 160 }); + ids.forEach((id) => this.tweens.add({ targets: this.sprites[id], y: this.sprites[id].y - 6, duration: 160, ease: 'Sine.easeOut' })); + tap(this); + await this.wait(ms); + glows.forEach((g) => g.destroy()); + } + + // Apply a drafting move with its animation. + async doMove(seat, move) { + this.busy = true; + this.clearPreview(); + this.lowerSelection(); + const before = this.gs; + const tf = move.source.type === 'center' && before.centerHasFirst; + this.gs = L.applyMove(before, move); + const changes = this.tracker.sync(this.gs); + const sk = srcKey(move.source); + const taken = changes.filter((c) => c.moved && c.fromKey === sk && c.toKey !== 'c'); + const leftovers = changes.filter((c) => c.moved && c.toKey === 'c'); + const shifts = changes.filter((c) => !c.moved); + // Order the taken tiles so the line fills right-to-left before any spill. + taken.sort((a, b) => (a.to.kind === 'floor') - (b.to.kind === 'floor') || a.to.slot - b.to.slot); + const jobs = []; + const dests = taken.map((c) => c.to.kind); + taken.forEach((c, i) => jobs.push(this.flyTile(c.id, tilePose(c.to, this.n), { delay: i * 70, dur: 560, arc: 46 }) + .then(() => { + if (c.to.kind === 'floor') { crunch(this, { n: 1 }); this.shards.explode(5, this.sprites[c.id].x, this.sprites[c.id].y); } + else clack(this, { n: 1, pitch: 0.9 + i * 0.06 }); + }))); + leftovers.forEach((c, i) => jobs.push(this.flyTile(c.id, tilePose(c.to, this.n), { delay: 140 + i * 50, dur: 480, arc: 14 }))); + shifts.forEach((c) => jobs.push(this.flyTile(c.id, tilePose(c.to, this.n), { delay: 60, dur: 300, arc: 0 }))); + if (tf) jobs.push(this.wait(200).then(() => this.placeMarker(true)).then(() => crunch(this, { n: 1, vol: 0.06 }))); + else jobs.push(this.placeMarker(true)); + void dests; + await Promise.all(jobs); + if (leftovers.length) clack(this, { n: Math.min(3, leftovers.length), pitch: 0.75, vol: 0.04 }); + this.updateInteractivity(); + this.drawZones(); + this.refreshHud(); + this.reactions(this.gs.lastMove); + } + + // Opponents' faces: sniped colours, ugly floor dumps, tidy fills. + reactions(lm) { + if (!lm) return; + const gs = this.gs; + if (lm.seat !== HUMAN && lm.overflow + (lm.tookFirst ? 1 : 0) >= 3) { this.emote(lm.seat, 'upset'); return; } + if (lm.seat !== HUMAN && lm.filled && lm.overflow === 0 && lm.taken >= 3 && Math.random() < 0.6) { this.emote(lm.seat, 'happy'); return; } + for (const p of gs.players) { + if (p.seat === lm.seat || p.seat === HUMAN) continue; + const wanted = p.lines.some((l, i) => l.color === lm.color && l.count > 0 && l.count < lineCapacity(i) && lineCapacity(i) - l.count <= lm.taken); + if (wanted && Math.random() < 0.55) { this.emote(p.seat, 'upset'); return; } + } + } + + // ── human input ────────────────────────────────────────────────────────────────── + sourceOf(id) { + const loc = this.tracker.loc(id); + if (loc.kind === 'factory') return { type: 'factory', index: loc.index }; + if (loc.kind === 'center') return { type: 'center' }; + return null; + } + + onTileOver(id) { + if (!this.canInput() || this.drag?.active) return; + const source = this.sourceOf(id); + if (!source) return; + const color = colorOfId(id); + if (this.sel && sameSource(this.sel.source, source) && this.sel.color === color) return; + this.hoverGroup = { source, color }; + const ids = this.tracker.idsIn(srcKey(source)).filter((t) => colorOfId(t) === color); + this.clearHoverGlow(); + this.hoverGlows = ids.map((t) => { + const s = this.sprites[t]; + return this.add.image(s.x, s.y, 'azul-glow').setDisplaySize(s.displayWidth * 1.45, s.displayWidth * 1.45) + .setTint(0xfff0b0).setBlendMode('ADD').setAlpha(0.55).setDepth(D.tile - 1); + }); + if (!this.sel) { + const n = ids.length; + const tf = source.type === 'center' && this.gs.centerHasFirst; + this.hud.setPreview(`Take ${plural(n, TILE_NAME[color].toLowerCase() + ' tile')} from ${srcLabel(source)}${tf ? ' (and the first-player marker: −1, you start next round)' : ''}`); + } + } + onTileOut() { + this.clearHoverGlow(); + if (!this.sel && this.canInput()) this.hud.setPreview(null); + } + clearHoverGlow() { (this.hoverGlows ?? []).forEach((g) => g.destroy()); this.hoverGlows = null; } + + onTileDown(id, ptr) { + if (!this.canInput()) return; + const source = this.sourceOf(id); + if (!source) return; + const color = colorOfId(id); + const already = this.sel && sameSource(this.sel.source, source) && this.sel.color === color; + if (!already) this.select(source, color); + this.drag = { x: ptr.x, y: ptr.y, active: false, toggleOnUp: already, ids: this.selectedIds() }; + } + + selectedIds() { + if (!this.sel) return []; + return this.tracker.idsIn(srcKey(this.sel.source)).filter((t) => colorOfId(t) === this.sel.color); + } + + select(source, color) { + this.lowerSelection(true); + this.clearHoverGlow(); + this.sel = { source, color }; + tap(this); + const ids = this.selectedIds(); + this.selIds = ids.slice(); + this.selGlows = ids.map((id) => { + const s = this.sprites[id]; + this.tweens.add({ targets: s, y: this.spriteAt(this.poseOf(id)).y - 7, duration: 140, ease: 'Sine.easeOut' }); + return this.add.image(s.x, s.y - 7, 'azul-glow').setDisplaySize(s.displayWidth * 1.6, s.displayWidth * 1.6) + .setTint(0xffd36b).setBlendMode('ADD').setAlpha(0.9).setDepth(D.tile - 1); + }); + this.kbLine = this.firstLegalLine(); + this.drawZones(); + const p = this.gs.players[HUMAN]; + const anyLine = [0, 1, 2, 3, 4].some((i) => L.lineAccepts(p, i, color, this.free)); + this.hud.setAction(`${plural(ids.length, TILE_NAME[color] + ' tile')} picked`, anyLine + ? `From ${srcLabel(source)}. Click or drag to a glowing pattern line — or to your floor. Hover a line to preview it.` + : `From ${srcLabel(source)}. No pattern line can take ${TILE_NAME[color].toLowerCase()} — these go to your floor.`, 'you'); + this.hud.setDock([ + { label: 'Cancel', fn: () => this.cancelSelection(), bg: 0x5a3820 }, + { label: anyLine ? 'To floor (F)' : 'Floor it (F)', fn: () => this.onLineClick('floor'), bg: anyLine ? 0x7a3a2a : 0xa7311d }, + ]); + if (this.kbLine !== null && this.settings.preview) this.showPreview(this.kbLine); + else if (!anyLine) this.showPreview('floor'); + else this.hud.setPreview(null); + } + + // Drop the glow; with `restore`, settle the lifted tiles back into place. + lowerSelection(restore = false) { + (this.selGlows ?? []).forEach((g) => g.destroy()); + this.selGlows = null; + if (restore) (this.selIds ?? []).forEach((id) => this.flyTile(id, this.poseOf(id), { dur: 160, arc: 0 })); + this.selIds = null; + } + + cancelSelection() { + if (!this.sel) return; + this.lowerSelection(true); + this.sel = null; + this.promptHuman(); + } + + firstLegalLine() { + if (!this.sel) return null; + const p = this.gs.players[HUMAN]; + for (let i = 0; i < WALL_SIZE; i++) if (L.lineAccepts(p, i, this.sel.color, this.free)) return i; + return 'floor'; + } + + legalTargets() { + if (!this.sel) return []; + const p = this.gs.players[HUMAN]; + const out = []; + for (let i = 0; i < WALL_SIZE; i++) if (L.lineAccepts(p, i, this.sel.color, this.free)) out.push(i); + out.push('floor'); + return out; + } + + drawZones() { + const g = this.zoneGfx; + g.clear(); + if (!this.sel || !this.canInput()) return; + const { rect, m } = boardOf(HUMAN, this.n); + const p = this.gs.players[HUMAN]; + const t = this.time.now; + void t; + for (let i = 0; i < WALL_SIZE; i++) { + const ok = L.lineAccepts(p, i, this.sel.color, this.free); + if (!ok) continue; + const z = lineZoneAt(rect, m, i); + const cap = lineCapacity(i); + const x = z.x + (WALL_SIZE - cap) * m.cell; + const hot = this.hoverLine === i || (this.hoverLine === null && this.kbLine === i); + g.fillStyle(0xffd36b, hot ? 0.28 : 0.12).fillRoundedRect(x + 1, z.y + 2, cap * m.cell - 2, z.h - 4, 6); + g.lineStyle(hot ? 3 : 2, 0xffc23a, hot ? 1 : 0.8).strokeRoundedRect(x + 1, z.y + 2, cap * m.cell - 2, z.h - 4, 6); + } + const fz = floorZoneAt(rect, m); + const hotF = this.hoverLine === 'floor' || (this.hoverLine === null && this.kbLine === 'floor'); + g.lineStyle(hotF ? 3 : 2, 0xc0392b, hotF ? 1 : 0.6).strokeRoundedRect(fz.x, fz.y, fz.w, fz.h, 6); + if (hotF) g.fillStyle(0xc0392b, 0.12).fillRoundedRect(fz.x, fz.y, fz.w, fz.h, 6); + } + + onLineHover(line, leaving) { + if (line === null) { + if (this.hoverLine === leaving) { + this.hoverLine = null; + this.drawZones(); + if (this.sel && this.kbLine !== null) this.showPreview(this.kbLine); else this.clearPreview(); + } + return; + } + if (!this.canInput() || !this.sel) return; + this.hoverLine = line; + this.drawZones(); + if (this.legalTargets().includes(line)) this.showPreview(line); + } + + onLineClick(line) { + if (!this.canInput() || !this.sel) return; + if (!this.legalTargets().includes(line)) { tap(this); return; } + const move = { source: this.sel.source, color: this.sel.color, line }; + this.commitHumanMove(move); + } + + async commitHumanMove(move) { + this.undoSnap = { gs: this.gs, tracker: this.snapTracker() }; + this.sel = null; + this.hoverLine = null; + this.kbLine = null; + this.drag = null; + this.zoneGfx.clear(); + this.hud.setPreview(null); + await this.doMove(HUMAN, move); + if (!this.ended) this.advance(); + } + + snapTracker() { + const t = this.tracker; + return { where: t.where.slice(), slot: t.slot.slice(), seq: t.seq.slice(), tick: t.tick, last: t._last }; + } + + undo() { + if (!this.undoSnap || !this.settings.undo || !this.aiTimer) return; + this.aiTimer.remove(); + this.aiTimer = null; + const snap = this.undoSnap; + this.undoSnap = null; + this.busy = true; + this.hud.setDock([]); + this.gs = snap.gs; + const t = this.tracker; + t.where = snap.tracker.where; t.slot = snap.tracker.slot; t.seq = snap.tracker.seq; t.tick = snap.tracker.tick; t._last = snap.tracker.last; + const flights = []; + for (let id = 0; id < TILE_COUNT; id++) { + const pose = this.poseOf(id); + const s = this.spriteAt(pose); + const img = this.sprites[id]; + if (Math.abs(img.x - s.x) > 0.5 || Math.abs(img.y - s.y) > 0.5 || img.visible === !!pose.hidden) flights.push(this.flyTile(id, pose, { dur: 380, arc: 26 })); + } + flights.push(this.placeMarker(true)); + this.updateInteractivity(); + this.refreshHud(); + tap(this); + // Hand control back once every tile is home again. + Promise.all(flights).then(() => { + if (this.ended) return; + this.hud.setActive(HUMAN); + this.busy = false; + this.promptHuman(); + this.hud.setPreview('Move taken back.'); + }); + } + + // ── preview ───────────────────────────────────────────────────────────────────── + showPreview(line) { + this.clearPreview(); + if (!this.sel) return; + const move = { source: this.sel.source, color: this.sel.color, line }; + const pv = L.previewMove(this.gs, move); + const { rect, m } = boardOf(HUMAN, this.n); + const p = this.gs.players[HUMAN]; + const color = this.sel.color; + const ghost = (pos, size, tint, alpha = 0.55) => { + const s = this.spriteAt({ ...pos, size }); + const img = this.add.image(s.x, s.y, tileKey(color, this.settings.glyphs)).setDisplaySize(s.ds, s.ds).setAlpha(alpha).setDepth(D.ghost + 1); + if (tint) img.setTint(tint); + this.ghosts.push(img); + return img; + }; + if (this.settings.preview) { + if (line !== 'floor') { + const c0 = p.lines[line].count; + for (let j = 0; j < pv.placed; j++) ghost(lineTileAt(rect, m, line, c0 + j), m.tile, null); + } + // Floor ghosts: marker first (if any), then overflow. + pv.floorSlots.forEach((k, j) => { + const pos = floorCellAt(rect, m, k); + if (pv.takesFirst && j === 0) { + const s = this.spriteAt({ ...pos, size: m.floorCell - 4 }); + this.ghosts.push(this.add.image(s.x, s.y, 'azul-t-first').setDisplaySize(s.ds, s.ds).setAlpha(0.55).setDepth(D.ghost + 1)); + } else ghost(pos, m.floorCell - 4, 0xff9a8a, 0.6); + }); + if (pv.completes && pv.wallCol !== null) { + const pos = wallCellAt(rect, m, line, pv.wallCol); + const g = ghost(pos, m.tile, null, 0.75); + this.tweens.add({ targets: g, alpha: 0.35, duration: 520, yoyo: true, repeat: -1 }); + this.runGfx.clear(); + this.runGfx.lineStyle(2.5, 0xffc23a, 0.95); + for (const [r, c] of pv.run) { + const cp = wallCellAt(rect, m, r, c); + this.runGfx.strokeRoundedRect(cp.x - m.tile / 2 - 2, cp.y - m.tile / 2 - 2, m.tile + 4, m.tile + 4, 5); + } + } + } + this.hud.setPreview(...this.previewText(pv, line, color)); + } + + previewText(pv, line, color) { + const bits = []; + let tone = 'plain'; + const name = TILE_NAME[color].toLowerCase(); + if (line === 'floor') { + bits.push(`All ${pv.taken} ${name} to the floor.`); + } else { + bits.push(`Line ${line + 1} takes ${pv.placed}${pv.overflow ? `; ${pv.overflow} spill${pv.overflow === 1 ? 's' : ''} to the floor` : ''}.`); + if (pv.completes) { + bits.push(`Line full → ${this.free ? 'best spot' : 'wall'} column ${pv.wallCol + 1}: +${pv.wallPoints} at round end.`); + for (const h of pv.bonusHints) { + if (h.kind === 'row') bits.push('Completes a wall row — the game ends after this round (+2).'); + else if (h.kind === 'col') bits.push(h.done ? `Completes column ${h.index + 1}: +${h.pts} at game end!` : `Column ${h.index + 1}: 4 of 5 (+${h.pts} bonus within reach).`); + else if (h.kind === 'color') bits.push(h.done ? `All five ${name}: +${h.pts} at game end!` : `Four of five ${name} (+${h.pts} bonus within reach).`); + } + if (pv.floorDelta === 0) tone = 'good'; + } else if (pv.dumpRisk) { + bits.push('Full, but no legal wall space — it would be dumped on the floor!'); + tone = 'bad'; + } else { + const need = lineCapacity(line) - pv.lineAfter; + bits.push(`Holds ${pv.lineAfter} of ${lineCapacity(line)} — needs ${need} more (it carries over).`); + } + } + if (pv.takesFirst) bits.push('Takes the first-player marker (you start next round).'); + if (pv.floorDelta < 0) bits.push(`Floor: ${pv.floorDelta} point${pv.floorDelta === -1 ? '' : 's'}${pv.toLid ? ` (${pv.toLid} more go straight to the lid)` : ''}.`); + if (pv.floorDelta <= -3) tone = 'bad'; + return [bits.join('\n'), tone]; + } + + clearPreview() { + this.ghosts.forEach((g) => { this.tweens.killTweensOf(g); g.destroy(); }); + this.ghosts = []; + this.runGfx?.clear(); + } + + // ── drag ──────────────────────────────────────────────────────────────────────── + buildInput() { + this.input.on('pointermove', (ptr) => this.onPointerMove(ptr)); + this.input.on('pointerup', (ptr) => this.onPointerUp(ptr)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + } + + targetAt(x, y) { + const { rect, m } = boardOf(HUMAN, this.n); + for (let i = 0; i < WALL_SIZE; i++) if (contains(lineZoneAt(rect, m, i), x, y)) return i; + if (contains(floorZoneAt(rect, m), x, y)) return 'floor'; + return null; + } + + onPointerMove(ptr) { + const d = this.drag; + if (!d || !this.sel) return; + if (!d.active) { + if (Math.hypot(ptr.x - d.x, ptr.y - d.y) < 10) return; + d.active = true; + d.ids = this.selectedIds(); + this.clearHoverGlow(); + this.lowerSelection(); + } + d.ids.forEach((id, i) => { + const img = this.sprites[id]; + img.setDepth(D.flight); + const size = 38; + const s = tileDisplay(size); + img.setDisplaySize(s, s); + img.setPosition(ptr.x + (i - (d.ids.length - 1) / 2) * 22, ptr.y + 4 + Math.abs(i - (d.ids.length - 1) / 2) * 3); + }); + const t = this.targetAt(ptr.x, ptr.y); + if (t !== this.hoverLine) { + this.hoverLine = t; + this.drawZones(); + if (t !== null && this.legalTargets().includes(t)) this.showPreview(t); else this.clearPreview(); + } + } + + onPointerUp(ptr) { + const d = this.drag; + this.drag = null; + if (!d) return; + if (!d.active) { + if (d.toggleOnUp) this.cancelSelection(); + return; + } + const t = this.targetAt(ptr.x, ptr.y); + if (t !== null && this.sel && this.legalTargets().includes(t)) { + this.commitHumanMove({ source: this.sel.source, color: this.sel.color, line: t }); + return; + } + // Dropped elsewhere: tiles return, still picked up. + this.hoverLine = null; + const sel = this.sel; + d.ids.forEach((id) => this.flyTile(id, this.poseOf(id), { dur: 260, arc: 10 })); + this.time.delayedCall(280 * this.k, () => { if (this.sel === sel && this.canInput()) this.select(sel.source, sel.color); }); + } + + // ── keyboard ──────────────────────────────────────────────────────────────────── + onKey(e) { + if (this.ended || !this.gs) return; + const k = e.key; + if (k === 'Escape') { + if (this.modal) { this.closeModal(); return; } + if (this.sel) { this.cancelSelection(); return; } + this.openMenu(); + return; + } + if (this.modal) return; + if (k === 'z' || k === 'Z') { this.undo(); return; } + if (k === 'l' || k === 'L') { this.openLogView(); return; } + if (!this.canInput()) return; + const n = this.gs.factories.length; + const pickSource = (source) => { + const tiles = L.sourceTiles(this.gs, source); + const colors = TILE_COLORS.filter((c) => tiles.includes(c)); + if (!colors.length) return; + const cur = this.sel && sameSource(this.sel.source, source) ? colors.indexOf(this.sel.color) : -1; + this.select(source, colors[(cur + 1) % colors.length]); + }; + if (k >= '1' && k <= '9' && Number(k) <= n) pickSource({ type: 'factory', index: Number(k) - 1 }); + else if (k === 'c' || k === 'C' || k === '0') pickSource({ type: 'center' }); + else if (!this.sel) return; + else if (k === 'ArrowLeft' || k === 'ArrowRight') { + const tiles = L.sourceTiles(this.gs, this.sel.source); + const colors = TILE_COLORS.filter((c) => tiles.includes(c)); + const i = colors.indexOf(this.sel.color); + this.select(this.sel.source, colors[(i + (k === 'ArrowRight' ? 1 : colors.length - 1)) % colors.length]); + } else if (k === 'ArrowUp' || k === 'ArrowDown') { + const t = this.legalTargets(); + const i = Math.max(0, t.indexOf(this.kbLine)); + this.kbLine = t[(i + (k === 'ArrowDown' ? 1 : t.length - 1)) % t.length]; + this.hoverLine = null; + this.drawZones(); + this.showPreview(this.kbLine); + } else if (k === 'Enter' || k === ' ') { + if (this.kbLine !== null) this.onLineClick(this.kbLine); + } else if (k === 'f' || k === 'F') this.onLineClick('floor'); + e.preventDefault?.(); + } + + // ── opponent board zoom ───────────────────────────────────────────────────────── + showPopover(seat) { + if (this.modal || this.drag?.active || this.pick) return; + this.hidePopover(); + const objs = []; + const o = { x: POPOVER.x, y: POPOVER.y }; + const m = BIG; + objs.push(this.add.rectangle(GAME_WIDTH / 2, POPOVER.y + POPOVER.h / 2, POPOVER.w + 40, POPOVER.h + 40, 0x000000, 0.35).setDepth(D.popover - 1)); + objs.push(this.add.image(o.x - SHADOW, o.y - SHADOW, boardKey('big', { free: this.free, glyphs: this.settings.glyphs })).setOrigin(0).setDepth(D.popover)); + const p = this.gs.players[seat]; + const hy = o.y + (m.headerH - 8) / 2; + objs.push(this.add.text(o.x + m.pad + 8, hy, p.name, { fontFamily: DISPLAY, fontSize: '22px', color: '#f6efdc' }).setOrigin(0, 0.5).setDepth(D.popover + 1)); + objs.push(this.add.text(o.x + m.w - m.pad - 4, hy, `${p.score}`, { fontFamily: 'Righteous', fontSize: '28px', color: '#ffe08a', stroke: '#0e2442', strokeThickness: 3 }).setOrigin(1, 0.5).setDepth(D.popover + 1)); + const tile = (pos, size, color) => { + const s = this.spriteAt({ ...pos, size }); + objs.push(this.add.image(s.x, s.y, color === 'first' ? 'azul-t-first' : tileKey(color, this.settings.glyphs)).setDisplaySize(s.ds, s.ds).setDepth(D.popover + 2)); + }; + for (let r = 0; r < WALL_SIZE; r++) { + const l = p.lines[r]; + for (let k2 = 0; k2 < l.count; k2++) tile(lineTileAt(o, m, r, k2), m.tile, l.color); + for (let c = 0; c < WALL_SIZE; c++) { const col = L.cellColor(p, r, c); if (col) tile(wallCellAt(o, m, r, c), m.tile, col); } + } + p.floor.forEach((t, k2) => tile(floorCellAt(o, m, k2), m.floorCell - 4, t)); + objs.forEach((ob) => { ob.setAlpha(0); this.tweens.add({ targets: ob, alpha: ob === objs[0] ? 1 : 1, duration: 140 }); }); + this.popover = objs; + } + hidePopover() { (this.popover ?? []).forEach((o) => o.destroy()); this.popover = null; } + + // ── round scoring ─────────────────────────────────────────────────────────────── + async scoreRound() { + if (this.ended) return; + this.busy = true; + this.sel = null; + this.clearPreview(); + this.zoneGfx.clear(); + this.hud.setDock([]); + this.hud.setActive(-1); + this.hud.setRound(this.gs); + this.hud.setAction(`Round ${this.gs.round} complete`, 'Every full pattern line sends one tile to the wall and scores it; the floor lines are paid.'); + await this.banner(`Round ${this.gs.round} — tiling the walls`); + if (this.ended) return; + + const choices = {}; + for (const p of this.gs.players) { + if (!this.free) break; + choices[p.seat] = p.seat === HUMAN ? await this.askHumanColumns() : AI.chooseWallColumns(this.gs, p.seat, this.skill[p.seat]); + if (this.ended) return; + } + const pre = this.gs; + const resolved = L.resolveRound(pre, choices); + const changes = this.tracker.sync(resolved); + this.scoreChanges = changes; + for (let seat = 0; seat < this.n; seat++) { + const entry = resolved.roundSummary[seat]; + await this.animateSeatScoring(seat, entry, changes, pre); + if (this.ended) return; + } + this.gs = resolved; + this.refreshHud(); + if (L.isGameOver(this.gs)) { + await this.animateEndBonuses(); + if (!this.ended) this.finishGame(); + return; + } + // Next round: marker home, deal from the bag. + const deal = changes.filter((c) => c.moved && c.toKey.startsWith('f') && !c.toKey.startsWith('fl')); + await this.placeMarker(true); + await this.dealAnimation(deal, { refilled: resolved.lastDeal?.refilled }); + if (!this.ended) this.advance(); + } + + async animateSeatScoring(seat, entry, changes, pre) { + const hasFloor = (pre.players[seat].floor.length > 0); + if (!entry.placements.length && !hasFloor && !entry.dumped.length) return; + this.flashBoard(seat); + const { rect, m } = boardOf(seat, this.n); + let running = entry.scoreBefore; + const fromLine = (row) => changes.filter((c) => c.fromKey === `l${seat}.${row}`); + for (const pl of entry.placements) { + const ch = fromLine(pl.row); + const toWall = ch.find((c) => c.toKey.startsWith('w')); + const rest = ch.filter((c) => c !== toWall); + const jobs = []; + if (toWall) jobs.push(this.flyTile(toWall.id, tilePose(toWall.to, this.n), { dur: 480, arc: 22 })); + rest.forEach((c, i) => jobs.push(this.flyTile(c.id, tilePose({ kind: 'lid' }, this.n), { delay: 120 + i * 50, dur: 700, arc: 40, fade: true, toHidden: true }))); + await Promise.all(jobs.slice(0, 1)); + if (this.ended) return; + const wpos = wallCellAt(rect, m, pl.row, pl.col); + clack(this, { n: 1, pitch: 1.1 }); + chime(this, { pts: pl.points }); + this.glint(toWall?.id); + this.showRun(seat, pl.run, pl.points); + this.sparks.explode(pl.points >= 4 ? 14 : 7, wpos.x, wpos.y); + running += pl.points; + this.floatText(wpos.x, wpos.y - m.tile * 0.6, `+${pl.points}`, '#ffe08a', m.size === 'big' ? 30 : 22); + this.hud.setScore(seat, running, { roll: true, ms: 380 * this.k }); + await this.wait(420 * this.k); + await Promise.all(jobs.slice(1)); + } + // Free wall: lines with nowhere to go spill into the floor first. + if (entry.dumped.length) { + const fpos = floorCellAt(rect, m, 3); + this.floatText(fpos.x, fpos.y - 30, `${plural(entry.dumped.length, 'line')} had no space — dumped!`, '#ff9a8a', 18); + await this.wait(500 * this.k); + } + // Floor: crack, slide into the lid, pay. + const floorIds = changes.filter((c) => c.fromKey === `fl${seat}` || (entry.dumped.some((d) => c.fromKey === `l${seat}.${d.row}`))); + if (hasFloor || floorIds.length) { + floorIds.forEach((c) => { const s = this.sprites[c.id]; this.shards.explode(4, s.x, s.y); s.setTint(0xff9a8a); }); + crunch(this, { n: Math.max(1, Math.min(4, floorIds.length)) }); + const fpos = floorCellAt(rect, m, Math.min(FLOOR_SIZE - 1, Math.max(0, (entry.floorTiles?.length ?? 1) - 1))); + if (entry.floorPenalty < 0) this.floatText(fpos.x, fpos.y - 26, `${entry.floorPenalty}${entry.floorLost !== -entry.floorPenalty ? ` (−${entry.floorLost})` : ''}`, '#ff8a7a', m.size === 'big' ? 28 : 20); + this.hud.setScore(seat, entry.scoreAfter, { roll: true, ms: 420 * this.k }); + await this.wait(260 * this.k); + await Promise.all(floorIds.map((c, i) => this.flyTile(c.id, tilePose({ kind: 'lid' }, this.n), { delay: i * 40, dur: 620, arc: 30, fade: true, toHidden: true }) + .then(() => this.sprites[c.id].clearTint()))); + } + this.hud.setScore(seat, entry.scoreAfter); + if (seat !== HUMAN) { + const net = entry.gained - entry.floorLost; + if (entry.gained >= 6 || (entry.placements.length && net > 0 && Math.random() < 0.5)) this.emote(seat, 'happy'); + else if (net < 0) this.emote(seat, 'upset'); + } + await this.wait(200 * this.k); + } + + showRun(seat, cells, pts) { + if (!cells || cells.length < 2) return; + const { rect, m } = boardOf(seat, this.n); + const glows = cells.map(([r, c]) => { + const p = wallCellAt(rect, m, r, c); + return this.add.image(p.x, p.y, 'azul-glow').setDisplaySize(m.tile * 1.7, m.tile * 1.7) + .setTint(0xffd36b).setBlendMode('ADD').setAlpha(0).setDepth(D.tile + 1); + }); + glows.forEach((g, i) => this.tweens.add({ targets: g, alpha: 0.75, duration: 140, delay: i * 45, yoyo: true, hold: 260, onComplete: () => g.destroy() })); + void pts; + } + + glint(id) { + if (id === undefined) return; + const s = this.sprites[id]; + const g = this.add.image(s.x - s.displayWidth * 0.6, s.y, 'azul-glint').setDisplaySize(s.displayWidth * 0.5, s.displayHeight * 1.1) + .setAngle(18).setBlendMode('ADD').setAlpha(0.8).setDepth(D.tile + 2); + const maskG = this.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff).fillRect(s.x - s.displayWidth * 0.45, s.y - s.displayHeight * 0.45, s.displayWidth * 0.9, s.displayHeight * 0.9); + g.setMask(maskG.createGeometryMask()); + this.tweens.add({ targets: g, x: s.x + s.displayWidth * 0.6, duration: 520, ease: 'Sine.easeInOut', onComplete: () => { g.destroy(); maskG.destroy(); } }); + } + + flashBoard(seat) { + const { rect } = boardOf(seat, this.n); + const g = this.add.graphics().setDepth(D.boardGlow + 1); + g.lineStyle(5, 0xffd36b, 1).strokeRoundedRect(rect.x - 5, rect.y - 5, rect.w + 10, rect.h + 10, 14); + this.tweens.add({ targets: g, alpha: 0, duration: 900, ease: 'Cubic.easeIn', onComplete: () => g.destroy() }); + } + + floatText(x, y, text, color, size = 26) { + const t = this.add.text(x, y, text, { fontFamily: 'Righteous', fontSize: `${size}px`, color, stroke: '#1a1008', strokeThickness: 5 }) + .setOrigin(0.5).setDepth(D.fx + 2).setScale(0.6); + this.tweens.add({ targets: t, scale: 1, duration: 200, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, y: y - 34, alpha: 0, delay: 650 * this.k, duration: 700, ease: 'Cubic.easeIn', onComplete: () => t.destroy() }); + } + + async banner(text, hold = 900) { + const g = this.add.graphics().setDepth(D.banner); + const t = this.add.text(BANNER.x, BANNER.y, text, { fontFamily: DISPLAY, fontSize: '28px', color: '#f6efdc' }).setOrigin(0.5).setDepth(D.banner + 1); + const w = t.width + 80, h = 52, x = BANNER.x - w / 2, y = BANNER.y - h / 2; + g.fillStyle(0x000000, 0.4).fillRoundedRect(x + 3, y + 6, w, h, 10); + g.fillStyle(0x173f72, 0.96).fillRoundedRect(x, y, w, h, 10); + g.lineStyle(2, 0xc9a24a, 1).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 8); + [g, t].forEach((o) => o.setAlpha(0)); + await this.tw({ targets: [g, t], alpha: 1, duration: 220 }); + await this.wait(hold * this.k); + await this.tw({ targets: [g, t], alpha: 0, duration: 260 }); + g.destroy(); t.destroy(); + } + + // Free wall: the human chooses a column for each full line (top to bottom). + async askHumanColumns() { + const p = JSON.parse(JSON.stringify(this.gs.players[HUMAN])); + const out = {}; + const { rect, m } = boardOf(HUMAN, this.n); + for (let r = 0; r < WALL_SIZE; r++) { + const l = p.lines[r]; + if (!l.color || l.count !== lineCapacity(r)) continue; + const opts = L.wallOptions(p, r, l.color, true); + if (opts.length === 0) continue; + let col = opts[0]; + if (opts.length > 1) { + col = await new Promise((resolve) => { + const objs = []; + this.pick = { resolve }; + this.hud.setAction('Choose a wall space', `Your ${TILE_NAME[l.color].toLowerCase()} line (row ${r + 1}) is full. Click a glowing space on your wall — each colour once per row and column.`, 'you'); + opts.forEach((c) => { + const pos = wallCellAt(rect, m, r, c); + p.wall[r][c] = true; + const pts = L.scorePlacement(p.wall, r, c); + p.wall[r][c] = false; + const s = this.spriteAt({ ...pos, size: m.tile }); + const gimg = this.add.image(s.x, s.y, tileKey(l.color, this.settings.glyphs)).setDisplaySize(s.ds, s.ds).setAlpha(0.5).setDepth(D.ghost + 1); + this.tweens.add({ targets: gimg, alpha: 0.85, duration: 500, yoyo: true, repeat: -1 }); + const lbl = this.add.text(pos.x, pos.y, `+${pts}`, { fontFamily: 'Righteous', fontSize: '18px', color: '#ffffff', stroke: '#1a1008', strokeThickness: 4 }).setOrigin(0.5).setDepth(D.ghost + 2); + const z = this.add.zone(pos.x, pos.y, m.cell, m.cell).setInteractive({ useHandCursor: true }).setDepth(D.zone + 2); + z.on('pointerdown', () => { objs.forEach((o) => o.destroy()); this.pick = null; resolve(c); }); + objs.push(gimg, lbl, z); + }); + }); + tap(this); + } + out[r] = col; + p.wall[r][col] = true; + p.wallColors[r][col] = l.color; + } + return out; + } + + // Bag → plates, with a shake (and the lid poured back first if needed). + async dealAnimation(deal, { refilled = false } = {}) { + if (this.ended) return; + if (refilled) { + thunk(this); + this.floatText(LID.x, LID.y - 40, 'The lid is poured back into the bag', '#f6efdc', 18); + this.lidHeap.forEach((img) => this.tweens.add({ targets: img, x: BAG.x, y: BAG.y - 40, alpha: 0, duration: 500, onComplete: () => img.setAlpha(1) })); + await this.wait(560 * this.k); + } + this.refreshHud(); + rattle(this, { ms: 420 }); + this.tweens.add({ targets: this.bag, angle: { from: -4, to: 4 }, duration: 70, yoyo: true, repeat: 3, onComplete: () => this.bag.setAngle(0) }); + await this.wait(320 * this.k); + const byPlate = new Map(); + for (const c of deal) { const i = c.to.index; if (!byPlate.has(i)) byPlate.set(i, []); byPlate.get(i).push(c); } + const jobs = []; + let k = 0; + [...byPlate.keys()].sort((a, b) => a - b).forEach((i) => { + byPlate.get(i).sort((a, b) => a.to.slot - b.to.slot).forEach((c) => { + const delay = k++ * 38; + jobs.push(this.flyTile(c.id, tilePose(c.to, this.n), { fromBag: true, delay, dur: 520, arc: 70 }) + .then(() => { if (c.to.slot === 0) clack(this, { n: 2, vol: 0.04, pitch: 1.05 }); })); + }); + }); + await Promise.all(jobs); + this.updateInteractivity(); + this.refreshHud(); + } + + // ── game end ───────────────────────────────────────────────────────────────────── + async animateEndBonuses() { + await this.banner('The commission is complete — bonuses', 700); + for (let seat = 0; seat < this.n; seat++) { + const b = this.gs.roundSummary[seat].endBonuses; + if (!b || !b.total) continue; + const { rect, m } = boardOf(seat, this.n); + const p = this.gs.players[seat]; + let running = this.hud.shown[seat]; + const sets = [ + ...b.rows.map((r) => ({ cells: [0, 1, 2, 3, 4].map((c) => [r, c]), label: '+2 row', pts: 2 })), + ...b.cols.map((c) => ({ cells: [0, 1, 2, 3, 4].map((r) => [r, c]), label: '+7 column', pts: 7 })), + ...b.colors.map((color) => { + const cells = []; + for (let r = 0; r < WALL_SIZE; r++) for (let c = 0; c < WALL_SIZE; c++) if (L.cellColor(p, r, c) === color) cells.push([r, c]); + return { cells, label: `+10 ${TILE_NAME[color].toLowerCase()}`, pts: 10 }; + }), + ]; + this.flashBoard(seat); + for (const set of sets) { + const glows = set.cells.map(([r, c]) => { + const pos = wallCellAt(rect, m, r, c); + return this.add.image(pos.x, pos.y, 'azul-glow').setDisplaySize(m.tile * 1.8, m.tile * 1.8).setTint(0xffd36b).setBlendMode('ADD').setAlpha(0).setDepth(D.tile + 1); + }); + glows.forEach((g, i) => this.tweens.add({ targets: g, alpha: 0.85, duration: 120, delay: i * 60 })); + flourish(this); + await this.wait(380 * this.k); + const mid = set.cells[Math.floor(set.cells.length / 2)]; + const mp = wallCellAt(rect, m, mid[0], mid[1]); + this.floatText(mp.x, mp.y - 10, set.label, '#ffe08a', m.size === 'big' ? 30 : 22); + this.sparks.explode(16, mp.x, mp.y); + running += set.pts; + this.hud.setScore(seat, running, { roll: true, ms: 400 * this.k }); + await this.wait(520 * this.k); + this.tweens.add({ targets: glows, alpha: 0, duration: 260, onComplete: () => glows.forEach((g) => g.destroy()) }); + } + this.hud.setScore(seat, p.score); + } + await this.wait(500 * this.k); + } + + finishGame() { + if (this.ended || this.finished) return; + this.finished = true; + this.busy = true; + this.hud.setActive(-1); + this.hud.setDock([]); + this.gs.players.forEach((p) => this.hud.setScore(p.seat, p.score)); + this.refreshHud(); + const ranking = L.finalRanking(this.gs); + const won = ranking[0].seat === HUMAN; + this.hud.setAction(won ? 'You win!' : `${ranking[0].name} wins`, `Final score ${this.gs.players[HUMAN].score}.`); + const oppScores = ranking.filter((r) => r.seat !== HUMAN).map((r) => r.score); + this.recordResult(won ? 'win' : 'loss', this.gs.players[HUMAN].score, oppScores); + ranking.forEach((r, i) => { if (r.seat !== HUMAN) this.emote(r.seat, i === 0 ? 'happy' : 'upset'); }); + if (won) flourish(this); + this.time.delayedCall(900, () => { + if (this.ended) return; + this.endScreen = showAzulEndScreen(this, { + depth: D.modal, + onPlayAgain: () => this.scene.restart(this.initData), + onLeave: () => this.scene.start('GameMenu'), + onHidePortraits: () => this.hidePortraits(), + onShowPortraits: () => this.showPortraits(), + }); }); - new Button(this, cx - 110, cy + h / 2 - 36, 'Play Again', () => this.scene.restart(this._initData), - { width: 190, fontSize: 22 }).setDepth(DEPTH.banner + 1); - new Button(this, cx + 110, cy + h / 2 - 36, 'Leave', () => this.scene.start('GameMenu'), - { width: 190, fontSize: 22, variant: 'ghost' }).setDepth(DEPTH.banner + 1); } async recordResult(result, score, opponentScores) { - try { - await api.post('/history/single-player', { slug: 'azul', score, opponentScores, result }); - } catch { /* best effort */ } + try { await api.post('/history/single-player', { slug: 'azul', score, opponentScores, result }); } catch { /* best effort */ } + } + + // ── menu, settings, log ────────────────────────────────────────────────────────── + openMenu() { + if (this.modal || this.finished) return; + this.hidePopover(); + this.hidePortraits(); + this.modal = openPauseMenu(this, { + settings: this.settings, variantNow: this.gs.variant, depth: D.modal, + onChange: (key, value) => this.changeSetting(key, value), + onRules: () => this.openRules(), + onNewGame: () => this.confirmThen('New game?', 'Abandon this game and deal a fresh one?', () => this.scene.restart(this.initData)), + onLeave: () => this.confirmThen('Leave the table?', 'This game will be abandoned.', () => this.scene.start('GameMenu')), + onClose: () => { this.modal = null; this.showPortraits(); }, + }); + } + + confirmThen(heading, text, onYes) { + this.hidePortraits(); + this.modal = confirmBox(this, { + heading, text, depth: D.modal + 5, yes: 'Yes', + onYes: () => { this.modal = null; onYes(); }, + onNo: () => { this.modal = null; this.showPortraits(); }, + }); + } + + closeModal() { this.modal?.close?.(); this.modal = null; this.showPortraits(); } + + openRules() { new TutorialModal(this.gameDef).open(); } + + openLogView() { + if (this.modal) return; + this.hidePortraits(); + this.modal = openLog(this, { log: this.gs.log, depth: D.modal, onClose: () => { this.modal = null; this.showPortraits(); } }); + } + + changeSetting(key, value) { + this.settings[key] = value; + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + if (key === 'glyphs') { + const opts = { free: this.free, glyphs: value }; + this.boardImgs.forEach((img, seat) => img.setTexture(ensureBoard(this, boardOf(seat, this.n).m.size, opts))); + this.sprites.forEach((img, id) => img.setTexture(tileKey(colorOfId(id), value))); + } + if (key === 'preview' && !value) this.clearPreview(); + if (key === 'undo' && this.aiTimer) this.setDockForWaiting(); + this.refreshHud(); + } + + update() { + // Keep hover glows riding on lifted tiles. + if (this.selGlows && this.sel) { + const ids = this.selectedIds(); + this.selGlows.forEach((g, i) => { const s = this.sprites[ids[i]]; if (s) g.setPosition(s.x, s.y); }); + } } } diff --git a/src/games/azul/AzulHud.js b/src/games/azul/AzulHud.js new file mode 100644 index 0000000..5c4d94a --- /dev/null +++ b/src/games/azul/AzulHud.js @@ -0,0 +1,312 @@ +// AzulHud.js — the workshop's furniture that isn't tiles: +// • board headers (name, rolling score, first-player star) + bonus badges +// • the tile tracker (bottom-left): where every colour is +// • the work-order panel (bottom-centre): whose turn, what to do, the move +// preview and up to three dock buttons +// • the scoreboard (bottom-right): round, standings, wall variant +// • the order book (right): the last few log lines + +import { Button } from '../../ui/Button.js'; +import { COLORS, TILE_NAME, WALL_SIZE, ROW_BONUS, COLUMN_BONUS, COLOR_BONUS } from './AzulData.js'; +import { bonusStatus } from './AzulLogic.js'; +import { + TRACKER, ACTION, SCORES, NOTEPAD, DOCK, boardOf, bonusBadgeAt, +} from './AzulLayout.js'; +import { SERIF, DISPLAY, COBALT, INK, SHADOW, tileKey, tileDisplay } from './AzulArt.js'; + +const CREAM = '#f6efdc'; + +export class AzulHud { + constructor(scene, { depth, playerCount, names, tooltip }) { + this.scene = scene; + this.D = depth; + this.n = playerCount; + this.names = names; + this.tooltip = tooltip; + this.shown = Array(playerCount).fill(0); // displayed (rolling) scores + this.scoreTweens = []; + this.buildPanels(); + this.buildHeaders(); + this.buildTracker(); + this.buildAction(); + this.buildScores(); + this.buildNotepad(); + } + + add(o) { return o; } + + buildPanels() { + const s = this.scene; + const img = (key, r) => s.add.image(r.x - SHADOW, r.y - SHADOW, key).setOrigin(0).setDepth(this.D.panel); + this.trackerPanel = img('azul-panel-tracker', TRACKER); + img('azul-panel-action', ACTION); + img('azul-panel-scores', SCORES); + s.add.image(NOTEPAD.x - SHADOW, NOTEPAD.y - SHADOW, 'azul-notepad').setOrigin(0).setDepth(this.D.panel); + } + + // ── board headers ─────────────────────────────────────────────────────────── + buildHeaders() { + const s = this.scene; + this.headers = []; + for (let seat = 0; seat < this.n; seat++) { + const { rect, m } = boardOf(seat, this.n); + const big = m.size === 'big'; + const nameX = rect.x + m.pad + (big ? 40 : 30); // clears the hanging portrait + const hy = rect.y + (m.headerH - (big ? 8 : 6)) / 2; + const name = s.add.text(nameX, hy, this.names[seat] + (seat === 0 ? ' (you)' : ''), { + fontFamily: DISPLAY, fontSize: big ? '22px' : '17px', color: CREAM, + }).setOrigin(0, 0.5).setDepth(this.D.label); + const score = s.add.text(rect.x + rect.w - m.pad - 4, hy, '0', { + fontFamily: 'Righteous', fontSize: big ? '28px' : '22px', color: '#ffe08a', stroke: '#0e2442', strokeThickness: 3, + }).setOrigin(1, 0.5).setDepth(this.D.label); + const star = s.add.text(score.x - (big ? 60 : 46), hy, '①', { + fontFamily: SERIF, fontSize: big ? '22px' : '18px', color: '#ffffff', + }).setOrigin(1, 0.5).setDepth(this.D.label).setVisible(false); + // Active-turn frame (drawn just outside the board). + const glow = s.add.graphics().setDepth(this.D.boardGlow); + glow.lineStyle(big ? 5 : 4, 0xffd36b, 1).strokeRoundedRect(rect.x - 4, rect.y - 4, rect.w + 8, rect.h + 8, big ? 14 : 11); + glow.setAlpha(0); + // Bonus badge. + const bb = bonusBadgeAt(rect, m); + const badge = s.add.text(bb.x + bb.w - 2, bb.y + bb.h / 2, '', { + fontFamily: SERIF, fontSize: big ? '14px' : '11px', color: '#1d4f8f', fontStyle: 'bold', align: 'right', lineSpacing: -2, + }).setOrigin(1, 0.5).setDepth(this.D.label); + const bz = s.add.zone(bb.x + bb.w / 2, bb.y + bb.h / 2, bb.w, bb.h).setInteractive().setDepth(this.D.zone + 1); + this.tooltip.attachTo(bz, () => this.bonusTooltip(seat)); + this.headers.push({ name, score, star, glow, badge, bz, big }); + } + } + + setActive(seat) { + this.headers.forEach((h, i) => { + const on = i === seat; + this.scene.tweens.killTweensOf(h.glow); + if (on) { + h.glow.setAlpha(1); + this.scene.tweens.add({ targets: h.glow, alpha: 0.45, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + } else h.glow.setAlpha(0); + }); + } + + setStartPlayer(seat, hasMarker) { + this.headers.forEach((h, i) => h.star.setVisible(!!hasMarker && i === seat)); + } + + // Score text: snap (no animation) or roll from what's shown now. + setScore(seat, value, { roll = false, ms = 500 } = {}) { + const h = this.headers[seat]; + this.scoreTweens[seat]?.stop?.(); + if (!roll) { this.shown[seat] = value; h.score.setText(`${value}`); this.refreshScores(); return; } + const from = this.shown[seat]; + const o = { v: from }; + this.scoreTweens[seat] = this.scene.tweens.add({ + targets: o, v: value, duration: ms, ease: 'Cubic.easeOut', + onUpdate: () => { this.shown[seat] = Math.round(o.v); h.score.setText(`${this.shown[seat]}`); }, + onComplete: () => { this.shown[seat] = value; h.score.setText(`${value}`); this.refreshScores(); }, + }); + this.scene.tweens.add({ targets: h.score, scale: { from: 1.25, to: 1 }, duration: 380, ease: 'Back.easeOut' }); + } + + setBonuses(gs, show) { + this.gs = gs; + this.headers.forEach((h, seat) => { + if (!show) { h.badge.setText(''); return; } + const b = bonusStatus(gs.players[seat]); + const near = b.cols.filter((n) => n === WALL_SIZE - 1).length + Object.values(b.colors).filter((n) => n === WALL_SIZE - 1).length; + const txt = b.locked || near ? `+${b.locked}${near ? ` (${near}★)` : ''}` : ''; + h.badge.setText(txt ? (h.big ? `Bonus ${txt}` : txt) : ''); + }); + } + + bonusTooltip(seat) { + const gs = this.gs; + if (!gs) return { title: 'Bonuses', lines: [] }; + const b = bonusStatus(gs.players[seat]); + const lines = []; + const row = (label, arr, bonus) => { + const parts = arr.map((n, i) => `${label[0]}${i + 1}:${n}`).join(' '); + return { text: `${label} (+${bonus} each): ${parts}` }; + }; + lines.push(row('Rows', b.rows, ROW_BONUS)); + lines.push(row('Columns', b.cols, COLUMN_BONUS)); + lines.push({ text: `Colours (+${COLOR_BONUS} each): ${COLORS.map((c) => `${TILE_NAME[c]} ${b.colors[c]}`).join(' · ')}` }); + lines.push({ text: `Locked in: +${b.locked}. A ★ is a set with 4 of 5 — one tile from a bonus.`, color: '#ffe08a' }); + return { title: `${this.names[seat]} — end-game bonuses`, lines }; + } + + // ── tile tracker ──────────────────────────────────────────────────────────── + buildTracker() { + const s = this.scene; + const x = TRACKER.x, y = TRACKER.y; + this.trk = { objs: [] }; + const head = s.add.text(x + TRACKER.w / 2, y + 30, 'Tile Tracker', { fontFamily: DISPLAY, fontSize: '20px', color: COBALT }).setOrigin(0.5).setDepth(this.D.label); + const cols = [['Bag', 132], ['Lid', 182], ['Table', 232], ['Walls', 280]]; + const colHeads = cols.map(([t, cx]) => s.add.text(x + cx, y + 62, t, { fontFamily: SERIF, fontSize: '12px', color: '#6b5226', fontStyle: 'italic' }).setOrigin(0.5).setDepth(this.D.label)); + this.trk.rows = COLORS.map((c, i) => { + const ry = y + 96 + i * 50; + const icon = s.add.image(x + 46, ry, tileKey(c, false)).setDisplaySize(tileDisplay(32), tileDisplay(32)).setDepth(this.D.label); + const name = s.add.text(x + 70, ry, TILE_NAME[c], { fontFamily: SERIF, fontSize: '13px', color: INK }).setOrigin(0, 0.5).setDepth(this.D.label); + const nums = cols.map(([, cx]) => s.add.text(x + cx, ry, '0', { fontFamily: 'Righteous', fontSize: '18px', color: INK }).setOrigin(0.5).setDepth(this.D.label)); + const zone = s.add.zone(x + TRACKER.w / 2, ry, TRACKER.w - 28, 44).setInteractive().setDepth(this.D.zone); + this.tooltip.attachTo(zone, () => this.trackerTooltip(c)); + return { c, icon, name, nums, zone }; + }); + this.trk.foot = s.add.text(x + TRACKER.w / 2, y + TRACKER.h - 30, '', { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#6b5226', align: 'center' }).setOrigin(0.5).setDepth(this.D.label); + this.trk.hidden = s.add.text(x + TRACKER.w / 2, y + TRACKER.h / 2, 'Tracker off\n(Menu → Tile tracker)', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#6b5226', align: 'center' }).setOrigin(0.5).setDepth(this.D.label).setVisible(false); + this.trk.objs = [head, ...colHeads, ...this.trk.rows.flatMap((r) => [r.icon, r.name, ...r.nums]), this.trk.foot]; + } + + setTracker(census, visible) { + this.census = census; + this.trk.objs.forEach((o) => o.setVisible(visible)); + this.trk.hidden.setVisible(!visible); + this.trk.rows.forEach((r) => r.zone.input && (r.zone.input.enabled = visible)); + if (!visible) return; + let unseen = 0; + this.trk.rows.forEach((r) => { + const k = census[r.c]; + const vals = [k.bag, k.lid, k.table, k.walls]; + r.nums.forEach((t, i) => t.setText(`${vals[i]}`)); + // Bag low → colour the count. + r.nums[0].setColor(k.bag <= 2 ? '#a7311d' : INK); + unseen += k.bag; + }); + this.trk.foot.setText(`${unseen} in the bag · lid refills it when empty`); + } + + trackerTooltip(c) { + const k = this.census?.[c]; + if (!k) return { title: TILE_NAME[c], lines: [] }; + return { + title: `${TILE_NAME[c]} tiles (20)`, + lines: [ + { text: `In the bag: ${k.bag}` }, + { text: `In the lid (discarded): ${k.lid}` }, + { text: `On plates / centre: ${k.table}` }, + { text: `On pattern lines: ${k.lines}` }, + { text: `On floor lines: ${k.floors}` }, + { text: `Set on walls: ${k.walls}` }, + ], + }; + } + + // ── work-order panel ────────────────────────────────────────────────────────── + buildAction() { + const s = this.scene; + const cx = ACTION.x + ACTION.w / 2; + this.act = {}; + this.act.title = s.add.text(cx, ACTION.y + 40, '', { fontFamily: DISPLAY, fontSize: '26px', color: COBALT }).setOrigin(0.5).setDepth(this.D.label); + this.act.body = s.add.text(cx, ACTION.y + 100, '', { + fontFamily: SERIF, fontSize: '17px', color: INK, align: 'center', lineSpacing: 6, wordWrap: { width: ACTION.w - 70 }, + }).setOrigin(0.5, 0.5).setDepth(this.D.label); + this.act.previewBg = s.add.graphics().setDepth(this.D.label - 1); + this.act.preview = s.add.text(cx, ACTION.y + 214, '', { + fontFamily: SERIF, fontSize: '16px', color: '#1d3f6e', align: 'center', lineSpacing: 5, wordWrap: { width: ACTION.w - 80 }, + }).setOrigin(0.5).setDepth(this.D.label); + this.dock = DOCK.map((r) => { + const b = new Button(s, r.x, r.y, '', () => b._fn?.(), { width: r.w, height: r.h, fontSize: 17, bg: 0x1d4f8f }).setDepth(this.D.label + 2); + b.setVisible(false); + return b; + }); + } + + setAction(title, body, tone = 'plain') { + this.act.title.setText(title); + this.act.title.setColor(tone === 'you' ? COBALT : tone === 'warn' ? '#a7311d' : '#6b5226'); + this.act.body.setText(body); + } + + setPreview(text, tone = 'plain') { + const g = this.act.previewBg; + g.clear(); + this.act.preview.setText(text ?? ''); + if (!text) return; + const b = this.act.preview.getBounds(); + const fill = tone === 'bad' ? 0xf2d2c4 : tone === 'good' ? 0xd8e6d0 : 0xe6ecf4; + g.fillStyle(fill, 1).fillRoundedRect(b.x - 16, b.y - 10, b.width + 32, b.height + 20, 8); + g.lineStyle(1.5, tone === 'bad' ? 0xa7311d : tone === 'good' ? 0x3c7a3a : 0x1d4f8f, 0.7).strokeRoundedRect(b.x - 16, b.y - 10, b.width + 32, b.height + 20, 8); + } + + // buttons: [{ label, fn, bg }] — up to three, left to right. + setDock(buttons = []) { + this.dock.forEach((b, i) => { + const spec = buttons[i]; + if (!spec) { b.setVisible(false); b.disableInteractive(); b._fn = null; return; } + b._fn = spec.fn; + b.setLabel(spec.label); + b.options.bg = spec.bg ?? 0x1d4f8f; + b._drawBg(b.options.bg, 1); + b.setVisible(true); + b.setEnabled(spec.enabled !== false); + }); + } + + // ── scoreboard ─────────────────────────────────────────────────────────────── + buildScores() { + const s = this.scene; + const cx = SCORES.x + SCORES.w / 2; + this.sc = {}; + this.sc.round = s.add.text(cx, SCORES.y + 38, '', { fontFamily: DISPLAY, fontSize: '26px', color: COBALT }).setOrigin(0.5).setDepth(this.D.label); + this.sc.sub = s.add.text(cx, SCORES.y + 70, '', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#6b5226' }).setOrigin(0.5).setDepth(this.D.label); + this.sc.rows = Array.from({ length: this.n }, (_, i) => { + const y = SCORES.y + 116 + i * 54; + const bg = s.add.graphics().setDepth(this.D.label - 1); + const rank = s.add.text(SCORES.x + 40, y, '', { fontFamily: 'Righteous', fontSize: '18px', color: '#6b5226' }).setOrigin(0.5).setDepth(this.D.label); + const name = s.add.text(SCORES.x + 62, y - 8, '', { fontFamily: SERIF, fontSize: '17px', color: INK }).setOrigin(0, 0.5).setDepth(this.D.label); + const sub = s.add.text(SCORES.x + 62, y + 13, '', { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#6b5226' }).setOrigin(0, 0.5).setDepth(this.D.label); + const pts = s.add.text(SCORES.x + SCORES.w - 34, y, '', { fontFamily: 'Righteous', fontSize: '24px', color: COBALT }).setOrigin(1, 0.5).setDepth(this.D.label); + return { bg, rank, name, sub, pts, y }; + }); + this.sc.foot = s.add.text(cx, SCORES.y + SCORES.h - 30, '', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#6b5226', align: 'center' }).setOrigin(0.5).setDepth(this.D.label); + } + + setRound(gs, { label } = {}) { + this.gs = gs; + this.sc.round.setText(label ?? (gs.phase === 'gameOver' ? 'Final' : `Round ${gs.round}`)); + const plates = gs.factories.filter((f) => f.length).length; + this.sc.sub.setText(gs.phase === 'offer' ? `${plates} plate${plates === 1 ? '' : 's'} left · ${gs.center.length} in the centre` : gs.phase === 'scoring' ? 'tiling the walls' : ''); + this.sc.foot.setText(gs.variant === 'free' ? 'Free wall — place tiles anywhere legal' : 'Printed wall'); + this.refreshScores(); + } + + refreshScores() { + const gs = this.gs; + if (!gs) return; + const order = gs.players.map((p) => p.seat).sort((a, b) => this.shown[b] - this.shown[a] || a - b); + order.forEach((seat, i) => { + const r = this.sc.rows[i]; + const p = gs.players[seat]; + const b = bonusStatus(p); + r.rank.setText(`${i + 1}`); + r.name.setText(seat === 0 ? `${p.name} (you)` : p.name); + r.sub.setText(`${b.rows.filter((n) => n === WALL_SIZE).length ? 'row done · ' : ''}${b.rows.reduce((a, c) => a + c, 0)} on wall${b.locked ? ` · +${b.locked} locked` : ''}`); + r.pts.setText(`${this.shown[seat]}`); + r.bg.clear(); + const cur = gs.phase === 'offer' && gs.current === seat; + r.bg.fillStyle(cur ? 0xffe7a8 : seat === 0 ? 0xe6ecf4 : 0xffffff, cur ? 0.9 : 0.45) + .fillRoundedRect(SCORES.x + 22, r.y - 24, SCORES.w - 44, 48, 6); + }); + } + + // ── order book ─────────────────────────────────────────────────────────────── + buildNotepad() { + const s = this.scene; + s.add.text(NOTEPAD.x + 20, NOTEPAD.y + 13, 'Order Book', { fontFamily: DISPLAY, fontSize: '15px', color: '#f3dcc0' }).setOrigin(0, 0.5).setDepth(this.D.label); + this.np = s.add.text(NOTEPAD.x + 54, NOTEPAD.y + 46, '', { + fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#1d3f6e', lineSpacing: 10.5, wordWrap: { width: NOTEPAD.w - 74 }, + fixedWidth: NOTEPAD.w - 74, + }).setDepth(this.D.label); + const maskG = s.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff).fillRect(NOTEPAD.x + 6, NOTEPAD.y + 30, NOTEPAD.w - 12, NOTEPAD.h - 34); + this.np.setMask(maskG.createGeometryMask()); + s.events.once('shutdown', () => maskG.destroy()); + } + + setLog(log) { + // Newest at the bottom: show as many recent lines as fit. + const lines = log.slice(-12); + this.np.setText(lines.join('\n')); + const maxH = NOTEPAD.h - 56; + while (this.np.height > maxH && lines.length > 1) { lines.shift(); this.np.setText(lines.join('\n')); } + } +} diff --git a/src/games/azul/AzulLayout.js b/src/games/azul/AzulLayout.js new file mode 100644 index 0000000..a6615fd --- /dev/null +++ b/src/games/azul/AzulLayout.js @@ -0,0 +1,224 @@ +// AzulLayout.js — every screen rect for the Azul workshop table. +// Phaser-free so tools/verifyAzul.js can check on-screen, overlaps and fit. +// +// ┌────────────── azulejo wainscot · title · Menu / Log / How to Play ─────────────┐ +// │ music opponent boards (1–3, portraits hang off their left edge) │ +// │ bag + lid ○ ○ ○ factory plates round the centre tray ○ notepad │ +// │ ○ [ centre tray ] ○ │ +// │ tile tracker │ (portrait) YOUR BOARD │ work-order panel │ round + scoreboard │ +// └────────────────────────────────────────────────────────────────────────────────┘ + +import { WALL_SIZE, FLOOR_SIZE, factoryCount } from './AzulData.js'; + +export const W = 1920, H = 1080; + +// ── board metrics ────────────────────────────────────────────────────────────── +// A board is [pattern lines | gap | wall] over a floor line, below a header. +function metrics(m) { + const w = m.pad * 2 + WALL_SIZE * m.cell + m.wallGap + WALL_SIZE * m.cell; + const floorTop = m.headerH + WALL_SIZE * m.cell + m.floorLabel; + const h = floorTop + m.floorCell + m.padB; + return { ...m, w, h, floorTop }; +} +export const MINI = metrics({ size: 'mini', tile: 26, cell: 29, wallGap: 16, pad: 10, headerH: 40, floorLabel: 14, floorCell: 24, floorGap: 2, padB: 9 }); +export const BIG = metrics({ size: 'big', tile: 42, cell: 50, wallGap: 24, pad: 14, headerH: 44, floorLabel: 20, floorCell: 40, floorGap: 4, padB: 12 }); + +// ── top band ─────────────────────────────────────────────────────────────────── +export const WAINSCOT = { x: 0, y: 0, w: W, h: 62 }; +export const TITLE = { x: 960, y: 31 }; +export const MENU_BTN = { x: 1530, y: 11, w: 118, h: 40 }; +export const LOG_BTN = { x: 1656, y: 11, w: 100, h: 40 }; +export const HELP_BTN = { x: 1764, y: 11, w: 146, h: 40 }; +export const MUSIC = { right: 300, top: 2 }; + +// ── opponents ────────────────────────────────────────────────────────────────── +export const OPP_ROW = { top: 74, gap: 112 }; +export const OPP_PORTRAIT = { r: 44, overlap: 18, dy: 52 }; +export function oppRect(k, nOpp) { + const rowW = nOpp * MINI.w + (nOpp - 1) * OPP_ROW.gap; + const x = Math.round(W / 2 - rowW / 2 + k * (MINI.w + OPP_ROW.gap)); + return { x, y: OPP_ROW.top, w: MINI.w, h: MINI.h }; +} + +// ── supply: factory plates round the centre tray ────────────────────────────── +export const RING = { cx: 960, cy: 492, rx: 360, ry: 130, r: 50, tile: 32, off: 18 }; +export const TRAY = { cx: 960, cy: 492, w: 360, h: 116, tile: 30, step: 34, pad: 8 }; +// Plates sit at equal ARC LENGTHS round the ellipse (equal angles would crowd +// them at its tight left/right ends), starting from the top. +const _ringCache = new Map(); +export function platePos(i, n) { + if (!_ringCache.has(n)) { + const N = 2400, P = []; + let len = 0, prev = null; + for (let k = 0; k <= N; k++) { + const a = -Math.PI / 2 + (k / N) * Math.PI * 2; + const q = { x: RING.cx + Math.cos(a) * RING.rx, y: RING.cy + Math.sin(a) * RING.ry }; + if (prev) len += Math.hypot(q.x - prev.x, q.y - prev.y); + P.push({ ...q, len }); + prev = q; + } + const out = []; + let j = 0; + for (let k = 0; k < n; k++) { + const t = (k / n) * len; + while (P[j].len < t) j++; + out.push({ x: Math.round(P[j].x * 10) / 10, y: Math.round(P[j].y * 10) / 10 }); + } + _ringCache.set(n, out); + } + return { ..._ringCache.get(n)[i] }; +} +const PLATE_SLOTS = [[-1, -1], [1, -1], [-1, 1], [1, 1]]; +export function plateSlot(i, n, slot) { + const p = platePos(i, n); + const [sx, sy] = PLATE_SLOTS[slot] ?? [0, 0]; + return { x: p.x + sx * RING.off, y: p.y + sy * RING.off }; +} +export const TRAY_PER_ROW = Math.floor((TRAY.w - TRAY.pad * 2) / TRAY.step); +export function centerSlot(idx) { + const left = TRAY.cx - (TRAY_PER_ROW * TRAY.step - (TRAY.step - TRAY.tile)) / 2 + TRAY.tile / 2; + const top = TRAY.cy - TRAY.h / 2 + TRAY.pad + 15 + TRAY.tile / 2 - 8; + return { x: left + (idx % TRAY_PER_ROW) * TRAY.step, y: top + Math.floor(idx / TRAY_PER_ROW) * TRAY.step }; +} + +// ── bag, lid, notepad ────────────────────────────────────────────────────────── +export const SUPPLY = { x: 40, y: 330, w: 480, h: 330 }; +export const BAG = { x: 190, y: 478, w: 170, h: 190 }; +export const LID = { x: 400, y: 514, w: 180, h: 118 }; +export const NOTEPAD = { x: 1392, y: 334, w: 488, h: 322 }; + +// ── bottom row ───────────────────────────────────────────────────────────────── +export const TRACKER = { x: 20, y: 690, w: 300, h: 372 }; +export const HUMAN_BOARD = { x: 420, y: 690, w: BIG.w, h: BIG.h }; +export const HUMAN_PORTRAIT = { r: 50, overlap: 18 }; +export const ACTION = { x: 1004, y: 690, w: 500, h: 372 }; +export const SCORES = { x: 1528, y: 690, w: 372, h: 372 }; +export const POPOVER = { x: 960 - BIG.w / 2, y: 312, w: BIG.w, h: BIG.h }; +// Dock buttons inside the action panel (centres). +export const DOCK_Y = ACTION.y + ACTION.h - 44; +export const DOCK = [ + { x: ACTION.x + 92, y: DOCK_Y, w: 160, h: 46 }, + { x: ACTION.x + ACTION.w / 2, y: DOCK_Y, w: 160, h: 46 }, + { x: ACTION.x + ACTION.w - 92, y: DOCK_Y, w: 160, h: 46 }, +]; +export const BANNER = { x: 960, y: 640 }; + +// ── per-seat board geometry ─────────────────────────────────────────────────── +// seat 0 is the human (big board, bottom); seats 1..n-1 are the top row. +export function boardOf(seat, playerCount) { + if (seat === 0) return { rect: { ...HUMAN_BOARD }, m: BIG }; + return { rect: oppRect(seat - 1, playerCount - 1), m: MINI }; +} +// Cell centres for a board drawn with metrics m at origin (x, y). +export function lineCellAt(o, m, row, col) { + return { x: o.x + m.pad + col * m.cell + m.cell / 2, y: o.y + m.headerH + row * m.cell + m.cell / 2 }; +} +export function wallCellAt(o, m, row, col) { + return { x: o.x + m.pad + WALL_SIZE * m.cell + m.wallGap + col * m.cell + m.cell / 2, y: o.y + m.headerH + row * m.cell + m.cell / 2 }; +} +export function floorCellAt(o, m, k) { + return { x: o.x + m.pad + k * (m.floorCell + m.floorGap) + m.floorCell / 2, y: o.y + m.floorTop + m.floorCell / 2 }; +} +// Pattern line `row` fills right-to-left: the k-th tile sits in column 4-k. +export function lineTileAt(o, m, row, k) { return lineCellAt(o, m, row, WALL_SIZE - 1 - k); } +export function lineZoneAt(o, m, row) { + return { x: o.x + m.pad, y: o.y + m.headerH + row * m.cell, w: WALL_SIZE * m.cell, h: m.cell }; +} +export function floorZoneAt(o, m) { + return { x: o.x + m.pad - 2, y: o.y + m.floorTop - 2, w: FLOOR_SIZE * (m.floorCell + m.floorGap) + 2, h: m.floorCell + 4 }; +} +export function wallRectAt(o, m) { + return { x: o.x + m.pad + WALL_SIZE * m.cell + m.wallGap, y: o.y + m.headerH, w: WALL_SIZE * m.cell, h: WALL_SIZE * m.cell }; +} +export function bonusBadgeAt(o, m) { + // Right end of the floor row, under the wall. + return { x: o.x + m.w - m.pad - (m.size === 'big' ? 100 : 56), y: o.y + m.floorTop, w: m.size === 'big' ? 100 : 56, h: m.floorCell }; +} + +export function portraitPos(seat, playerCount) { + const { rect } = boardOf(seat, playerCount); + if (seat === 0) return { x: rect.x - HUMAN_PORTRAIT.r + HUMAN_PORTRAIT.overlap, y: rect.y + HUMAN_PORTRAIT.r + 8, r: HUMAN_PORTRAIT.r }; + return { x: rect.x - OPP_PORTRAIT.r + OPP_PORTRAIT.overlap, y: rect.y + OPP_PORTRAIT.dy, r: OPP_PORTRAIT.r }; +} + +// ── tile poses for the tracker's locations ───────────────────────────────────── +// loc: { kind: 'bag'|'lid'|'factory'|'center'|'line'|'wall'|'floor', ... } +// Returns { x, y, size, hidden }. +export function tilePose(loc, playerCount) { + switch (loc.kind) { + case 'bag': return { x: BAG.x, y: BAG.y - 20, size: RING.tile, hidden: true }; + case 'lid': return { x: LID.x, y: LID.y, size: RING.tile * 0.8, hidden: true }; + case 'factory': { const p = plateSlot(loc.index, factoryCount(playerCount), loc.slot); return { ...p, size: RING.tile }; } + case 'center': { const p = centerSlot(loc.slot); return { ...p, size: TRAY.tile }; } + default: { + const { rect, m } = boardOf(loc.seat, playerCount); + if (loc.kind === 'line') return { ...lineTileAt(rect, m, loc.row, loc.slot), size: m.tile }; + if (loc.kind === 'wall') return { ...wallCellAt(rect, m, loc.row, loc.col), size: m.tile }; + if (loc.kind === 'floor') return { ...floorCellAt(rect, m, loc.slot), size: m.floorCell - 4 }; + return { x: W / 2, y: H / 2, size: 30, hidden: true }; + } + } +} + +// ── helpers for verify / hit tests ───────────────────────────────────────────── +const centred = (c, w, h, name) => ({ name, x: c.x - w / 2, y: c.y - h / 2, w, h }); + +export function hudFurniture({ players = 4 } = {}) { + const f = [ + { name: 'menu', ...MENU_BTN }, + { name: 'log', ...LOG_BTN }, + { name: 'help', ...HELP_BTN }, + { name: 'supply', ...SUPPLY }, + { name: 'notepad', ...NOTEPAD }, + centred({ x: TRAY.cx, y: TRAY.cy }, TRAY.w, TRAY.h, 'tray'), + { name: 'tracker', ...TRACKER }, + { name: 'humanBoard', ...HUMAN_BOARD }, + { name: 'action', ...ACTION }, + { name: 'scores', ...SCORES }, + ]; + const n = factoryCount(players); + for (let i = 0; i < n; i++) f.push(centred(platePos(i, n), RING.r * 2, RING.r * 2, `plate${i}`)); + for (let k = 0; k < players - 1; k++) { + f.push({ name: `opp${k + 1}`, ...oppRect(k, players - 1) }); + const pp = portraitPos(k + 1, players); + f.push({ ...centred(pp, pp.r * 2, pp.r * 2, `oppPortrait${k + 1}`), overlapOk: [`opp${k + 1}`] }); + } + const hp = portraitPos(0, players); + f.push({ ...centred(hp, hp.r * 2, hp.r * 2, 'humanPortrait'), overlapOk: ['humanBoard'] }); + return f; +} + +// Things that live inside a furniture rect (each must sit within its parent). +export function furnitureChildren({ players = 4 } = {}) { + const kids = []; + for (let idx = 0; idx < 28; idx++) kids.push({ parent: 'tray', ...centred(centerSlot(idx), TRAY.tile, TRAY.tile, `center${idx}`) }); + const n = factoryCount(players); + for (let i = 0; i < n; i++) for (let s = 0; s < 4; s++) { + kids.push({ parent: `plate${i}`, ...centred(plateSlot(i, n, s), RING.tile, RING.tile, `plate${i}.${s}`) }); + } + for (let seat = 0; seat < players; seat++) { + const { rect, m } = boardOf(seat, players); + const parent = seat === 0 ? 'humanBoard' : `opp${seat}`; + for (let r = 0; r < WALL_SIZE; r++) { + kids.push({ parent, ...lineZoneAt(rect, m, r), name: `s${seat}line${r}` }); + kids.push({ parent, ...centred(wallCellAt(rect, m, r, 4), m.tile, m.tile), name: `s${seat}wall${r}` }); + } + kids.push({ parent, ...floorZoneAt(rect, m), name: `s${seat}floor` }); + kids.push({ parent, ...bonusBadgeAt(rect, m), name: `s${seat}bonus` }); + } + for (let i = 0; i < DOCK.length; i++) kids.push({ parent: 'action', ...centred(DOCK[i], DOCK[i].w, DOCK[i].h, `dock${i}`) }); + kids.push({ parent: 'supply', ...centred(BAG, BAG.w, BAG.h, 'bag') }); + kids.push({ parent: 'supply', ...centred(LID, LID.w, LID.h, 'lid') }); + return kids; +} + +export const onScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= W && r.y + r.h <= H; +export const rectsOverlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; +export const inside = (k, p) => k.x >= p.x - 0.5 && k.y >= p.y - 0.5 && k.x + k.w <= p.x + p.w + 0.5 && k.y + k.h <= p.y + p.h + 0.5; +export const contains = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h; +// Circle-vs-rect overlap (plates are discs). +export function circleRectOverlap(cx, cy, r, rect) { + const nx = Math.max(rect.x, Math.min(cx, rect.x + rect.w)); + const ny = Math.max(rect.y, Math.min(cy, rect.y + rect.h)); + return (cx - nx) ** 2 + (cy - ny) ** 2 < r * r; +} diff --git a/src/games/azul/AzulLogic.js b/src/games/azul/AzulLogic.js index c3c9d49..6105fa6 100644 --- a/src/games/azul/AzulLogic.js +++ b/src/games/azul/AzulLogic.js @@ -9,14 +9,22 @@ // ends; the scene (or AI loop) calls resolveRound() to tile the // walls, score, apply floor penalties, then either deal a new // round or finish the game. +// +// Two wall variants: +// 'standard' — the printed, coloured wall: each colour has one fixed cell per row. +// 'free' — the grey (blank) wall: a completed line's tile goes in ANY empty +// cell of its row, but a colour may appear only once per row and +// once per column. A line whose tile has no legal cell is dumped +// onto the floor. resolveRound(state, choices) takes the columns. import { COLORS, WALL_SIZE, TILES_PER_COLOR, TILES_PER_FACTORY, FLOOR_PENALTIES, FLOOR_SIZE, ROW_BONUS, COLUMN_BONUS, COLOR_BONUS, - factoryCount, lineCapacity, wallColumnFor, + factoryCount, lineCapacity, wallColumnFor, wallColor, } from './AzulData.js'; const clone = (s) => JSON.parse(JSON.stringify(s)); +export const VARIANTS = ['standard', 'free']; // ── seeded RNG (mulberry32) stored on the state ────────────────────────────── function nextRand(s) { @@ -36,6 +44,23 @@ function emptyLines() { function emptyWall() { return Array.from({ length: WALL_SIZE }, () => Array(WALL_SIZE).fill(false)); } +function emptyWallColors() { + return Array.from({ length: WALL_SIZE }, () => Array(WALL_SIZE).fill(null)); +} +function emptyStats() { + return { + placementPts: 0, // points from wall-tiling + floorLost: 0, // points actually lost to the floor (after the ≥0 clamp) + bonusPts: 0, // end-game row/column/colour bonuses + tilesPlaced: 0, // tiles set on the wall + tilesFloored: 0, // coloured tiles that landed on the floor line + firstTaken: 0, // times this player took the first-player marker + bestPlacement: 0, // best single wall placement + takes: 0, // drafting turns + biggestTake: 0, // most tiles taken in one turn + roundScores: [], // score after each round's tiling (then the final total) + }; +} // ── bag / lid drawing ──────────────────────────────────────────────────────── function bagTotal(s) { return COLORS.reduce((n, c) => n + s.bag[c], 0); } @@ -45,7 +70,9 @@ function bagTotal(s) { return COLORS.reduce((n, c) => n + s.bag[c], 0); } function drawTile(s) { let total = bagTotal(s); if (total === 0) { - for (const c of COLORS) { s.bag[c] += s.lid[c]; s.lid[c] = 0; } + let moved = 0; + for (const c of COLORS) { moved += s.lid[c]; s.bag[c] += s.lid[c]; s.lid[c] = 0; } + if (moved > 0 && s.lastDeal) s.lastDeal.refilled = true; total = bagTotal(s); if (total === 0) return null; } @@ -61,25 +88,29 @@ function drawTile(s) { // player marker. Mutates `s` in place (callers already cloned). function dealFactories(s) { const n = factoryCount(s.playerCount); + s.lastDeal = { round: s.round, refilled: false, short: false }; s.factories = []; for (let i = 0; i < n; i++) { const f = []; for (let t = 0; t < TILES_PER_FACTORY; t++) { const tile = drawTile(s); if (tile) f.push(tile); + else s.lastDeal.short = true; } s.factories.push(f); } s.center = []; s.centerHasFirst = true; + s.log.push(`— Round ${s.round} —`); } // ── construction ───────────────────────────────────────────────────────────── -export function createInitialState({ playerCount = 4, names = [], seed } = {}) { +export function createInitialState({ playerCount = 4, names = [], seed, variant = 'standard' } = {}) { const pc = Math.max(2, Math.min(4, playerCount)); const s = { seed: (seed ?? Math.floor(Math.random() * 1e9)) >>> 0, rngState: 0, + variant: VARIANTS.includes(variant) ? variant : 'standard', playerCount: pc, bag: emptyCounts(), lid: emptyCounts(), @@ -91,7 +122,10 @@ export function createInitialState({ playerCount = 4, names = [], seed } = {}) { startPlayer: 0, phase: 'offer', // offer | scoring | gameOver round: 1, + turn: 0, // drafting turns taken this game roundSummary: null, // per-seat tiling report for the scene to animate + lastMove: null, // what the last applyMove did (for the scene / AI reactions) + lastDeal: null, gameEnded: false, log: [], }; @@ -104,8 +138,10 @@ export function createInitialState({ playerCount = 4, names = [], seed } = {}) { name: names[seat] ?? (seat === 0 ? 'You' : `Player ${seat}`), lines: emptyLines(), wall: emptyWall(), + wallColors: emptyWallColors(), floor: [], // entries are colour strings or the literal 'first' score: 0, + stats: emptyStats(), }); } @@ -117,28 +153,66 @@ export function createInitialState({ playerCount = 4, names = [], seed } = {}) { // ── queries ────────────────────────────────────────────────────────────────── export function currentPlayer(state) { return state.players[state.current]; } +export function isFreeWall(state) { return state.variant === 'free'; } -// Can `color` legally go on pattern line `i` for this player? -export function lineAccepts(player, i, color) { +// Colour sitting on (row, col) of a player's wall, or null. +export function cellColor(player, row, col) { + if (!player.wall[row][col]) return null; + return player.wallColors?.[row]?.[col] ?? wallColor(row, col); +} + +// Does this player's wall row already hold `color`? +export function rowHasColor(player, row, color) { + for (let c = 0; c < WALL_SIZE; c++) if (cellColor(player, row, c) === color) return true; + return false; +} +function colHasColor(player, col, color) { + for (let r = 0; r < WALL_SIZE; r++) if (cellColor(player, r, col) === color) return true; + return false; +} + +// Can `color` legally go on pattern line `i` for this player? `free` selects +// the grey-wall rule (colour not yet in the wall row; any column decided later). +export function lineAccepts(player, i, color, free = false) { const line = player.lines[i]; if (line.count >= lineCapacity(i)) return false; // already full if (line.color !== null && line.color !== color) return false; + if (free) return !rowHasColor(player, i, color); // The wall cell this line feeds must still be empty. if (player.wall[i][wallColumnFor(i, color)]) return false; return true; } +// Columns a tile of `color` may occupy in `row` (free wall). Standard → [fixed]. +export function wallOptions(player, row, color, free = false) { + if (!free) { + const col = wallColumnFor(row, color); + return player.wall[row][col] ? [] : [col]; + } + if (rowHasColor(player, row, color)) return []; + const out = []; + for (let c = 0; c < WALL_SIZE; c++) { + if (!player.wall[row][c] && !colHasColor(player, c, color)) out.push(c); + } + return out; +} + // Distinct colours available from a source array of tile colours. function coloursIn(tiles) { return COLORS.filter((c) => tiles.includes(c)); } +export function sourceTiles(state, source) { + return source.type === 'factory' ? state.factories[source.index] : state.center; +} + // All legal moves for the current player during the offer phase. // A move = { source: {type:'factory', index} | {type:'center'}, color, line } // where `line` is a pattern-line index 0..4 or the string 'floor'. export function legalMoves(state) { if (state.phase !== 'offer') return []; const p = currentPlayer(state); + const free = isFreeWall(state); const moves = []; const sources = state.factories.map((f, index) => ({ tiles: f, source: { type: 'factory', index } })); @@ -148,7 +222,7 @@ export function legalMoves(state) { for (const color of coloursIn(tiles)) { // Each pattern line that can accept the colour, plus the floor (always ok). for (let i = 0; i < WALL_SIZE; i++) { - if (lineAccepts(p, i, color)) moves.push({ source, color, line: i }); + if (lineAccepts(p, i, color, free)) moves.push({ source, color, line: i }); } moves.push({ source, color, line: 'floor' }); } @@ -156,6 +230,11 @@ export function legalMoves(state) { return moves; } +export function isLegalMove(state, move) { + return legalMoves(state).some((m) => m.color === move.color && m.line === move.line + && m.source.type === move.source.type && (m.source.type === 'center' || m.source.index === move.source.index)); +} + // ── floor handling ─────────────────────────────────────────────────────────── // Add `n` tiles of `color` to a player's floor; overflow past 7 slots → lid. function addToFloor(s, p, color, n) { @@ -165,6 +244,16 @@ function addToFloor(s, p, color, n) { } } +function floorPenaltyFor(len) { + let pen = 0; + for (let k = 0; k < len && k < FLOOR_SIZE; k++) pen += FLOOR_PENALTIES[k]; + return pen; +} + +function sourceLabel(source) { + return source.type === 'center' ? 'the centre' : `plate ${source.index + 1}`; +} + // ── apply an offer move ────────────────────────────────────────────────────── export function applyMove(state, move) { const s = clone(state); @@ -173,36 +262,53 @@ export function applyMove(state, move) { const { source, color } = move; // 1. Gather the chosen colour from the source; scatter the rest as needed. - let taken = 0; + let taken = 0, tookFirst = false; + const leftovers = []; if (source.type === 'factory') { const f = s.factories[source.index]; taken = f.filter((t) => t === color).length; - for (const t of f) if (t !== color) s.center.push(t); // leftovers → centre + for (const t of f) if (t !== color) { s.center.push(t); leftovers.push(t); } // leftovers → centre s.factories[source.index] = []; } else { taken = s.center.filter((t) => t === color).length; s.center = s.center.filter((t) => t !== color); if (s.centerHasFirst) { s.centerHasFirst = false; + tookFirst = true; s.startPlayer = s.current; // takes the 1st-player marker if (p.floor.length < FLOOR_SIZE) p.floor.push('first'); + p.stats.firstTaken++; } } // 2. Place the taken tiles on the chosen destination. - if (move.line === 'floor') { - addToFloor(s, p, color, taken); - } else { + let placed = 0; + if (move.line !== 'floor') { const i = move.line; const line = p.lines[i]; line.color = color; const space = lineCapacity(i) - line.count; - const placed = Math.min(space, taken); + placed = Math.min(space, taken); line.count += placed; - addToFloor(s, p, color, taken - placed); // overflow → floor } + const overflow = taken - placed; + addToFloor(s, p, color, overflow); + p.stats.takes++; + p.stats.tilesFloored += overflow; + p.stats.biggestTake = Math.max(p.stats.biggestTake, taken); - s.log.push(`${p.name} takes ${taken} ${color}.`); + const dest = move.line === 'floor' ? 'the floor' : `line ${move.line + 1}`; + const extras = []; + if (move.line !== 'floor' && overflow > 0) extras.push(`${overflow} to the floor`); + if (tookFirst) extras.push('takes the first-player marker'); + s.log.push(`${p.name} takes ${taken} ${color} from ${sourceLabel(source)} → ${dest}${extras.length ? ` (${extras.join(', ')})` : ''}.`); + + s.lastMove = { + seat: p.seat, source: { ...source }, color, line: move.line, + taken, placed, overflow, tookFirst, leftovers, + filled: move.line !== 'floor' && p.lines[move.line].count === lineCapacity(move.line), + }; + s.turn++; // 3. Advance the turn; end the offer phase when the table is empty. s.current = (s.current + 1) % s.playerCount; @@ -227,50 +333,137 @@ export function scorePlacement(wall, row, col) { return 1; } +// The cells a placement at (row, col) scores along (for highlighting): the +// horizontal run and the vertical run through it (each only if longer than 1). +export function placementRun(wall, row, col) { + const h = [[row, col]], v = []; + for (let c = col - 1; c >= 0 && wall[row][c]; c--) h.push([row, c]); + for (let c = col + 1; c < WALL_SIZE && wall[row][c]; c++) h.push([row, c]); + for (let r = row - 1; r >= 0 && wall[r][col]; r--) v.push([r, col]); + for (let r = row + 1; r < WALL_SIZE && wall[r][col]; r++) v.push([r, col]); + const cells = h.length > 1 ? h.slice() : [[row, col]]; + if (v.length) cells.push(...v); + return { cells, horizontal: h.length > 1 ? h.length : 0, vertical: v.length ? v.length + 1 : 0 }; +} + function wallRowComplete(wall, row) { return wall[row].every(Boolean); } -function wallColumnComplete(wall, col) { return wall.every((r) => r[col]); } -function colorComplete(wall, color) { - for (let row = 0; row < WALL_SIZE; row++) if (!wall[row][wallColumnFor(row, color)]) return false; - return true; +function colorCount(player, color) { + let n = 0; + for (let r = 0; r < WALL_SIZE; r++) for (let c = 0; c < WALL_SIZE; c++) if (cellColor(player, r, c) === color) n++; + return n; +} + +// Bonus status of a wall: how full each row/column/colour is, and the bonus +// already locked in (wall tiles never leave, so completed sets are certain). +export function bonusStatus(player) { + const rows = [], cols = [], colors = {}; + for (let r = 0; r < WALL_SIZE; r++) rows.push(player.wall[r].filter(Boolean).length); + for (let c = 0; c < WALL_SIZE; c++) { let n = 0; for (let r = 0; r < WALL_SIZE; r++) if (player.wall[r][c]) n++; cols.push(n); } + for (const color of COLORS) colors[color] = colorCount(player, color); + const rowsDone = rows.map((n, i) => (n === WALL_SIZE ? i : -1)).filter((i) => i >= 0); + const colsDone = cols.map((n, i) => (n === WALL_SIZE ? i : -1)).filter((i) => i >= 0); + const colorsDone = COLORS.filter((c) => colors[c] === WALL_SIZE); + const locked = rowsDone.length * ROW_BONUS + colsDone.length * COLUMN_BONUS + colorsDone.length * COLOR_BONUS; + return { rows, cols, colors, rowsDone, colsDone, colorsDone, locked }; +} + +// End-of-game bonus breakdown for one player. +export function endBonuses(player) { + const b = bonusStatus(player); + return { + rows: b.rowsDone, cols: b.colsDone, colors: b.colorsDone, + rowPts: b.rowsDone.length * ROW_BONUS, + colPts: b.colsDone.length * COLUMN_BONUS, + colorPts: b.colorsDone.length * COLOR_BONUS, + total: b.locked, + }; +} + +// Free wall: the column a player would pick by default — most points, then the +// column already holding the most tiles (towards the +7), then leftmost. +export function defaultWallColumn(player, row, color, options) { + let best = null, bestKey = -Infinity; + for (const c of options) { + player.wall[row][c] = true; + const pts = scorePlacement(player.wall, row, c); + player.wall[row][c] = false; + let colN = 0; for (let r = 0; r < WALL_SIZE; r++) if (player.wall[r][c]) colN++; + const key = pts * 100 + colN * 10 + (WALL_SIZE - c); + if (key > bestKey) { bestKey = key; best = c; } + } + void color; + return best; } // Resolve the scoring phase: tile every completed pattern line, score it, apply // floor penalties, clear floors, then either deal the next round or finish the // game (with end-of-game bonuses). Returns a fresh state carrying `roundSummary` // (one entry per seat) for the scene to animate. -export function resolveRound(state) { +// choices (free wall only): { [seat]: { [row]: col } } — missing / illegal +// entries fall back to defaultWallColumn. +export function resolveRound(state, choices = null) { const s = clone(state); if (s.phase !== 'scoring') return s; + const free = isFreeWall(s); const summary = s.players.map((p) => { - const entry = { seat: p.seat, placements: [], floorPenalty: 0, floorTiles: p.floor.slice(), gained: 0 }; + const entry = { + seat: p.seat, placements: [], dumped: [], floorPenalty: 0, floorLost: 0, + floorTiles: null, gained: 0, scoreBefore: p.score, + }; // Tile completed lines top-to-bottom; score against the wall as it grows. for (let i = 0; i < WALL_SIZE; i++) { const line = p.lines[i]; - if (line.count === lineCapacity(i)) { - const col = wallColumnFor(i, line.color); - p.wall[i][col] = true; - const pts = scorePlacement(p.wall, i, col); - p.score += pts; - entry.gained += pts; - entry.placements.push({ row: i, col, color: line.color, points: pts }); - // Surplus tiles from the line go to the lid; the line resets. - s.lid[line.color] += line.count - 1; + if (line.count !== lineCapacity(i)) continue; + const opts = wallOptions(p, i, line.color, free); + if (opts.length === 0) { + // Free wall only: nowhere to put it — the whole line goes to the floor. + entry.dumped.push({ row: i, color: line.color, count: line.count }); + addToFloor(s, p, line.color, line.count); + p.stats.tilesFloored += line.count; p.lines[i] = { color: null, count: 0 }; + continue; } + let col = opts[0]; + if (free) { + const want = choices?.[p.seat]?.[i]; + col = opts.includes(want) ? want : defaultWallColumn(p, i, line.color, opts); + } + p.wall[i][col] = true; + p.wallColors[i][col] = line.color; + const pts = scorePlacement(p.wall, i, col); + const run = placementRun(p.wall, i, col); + p.score += pts; + entry.gained += pts; + entry.placements.push({ row: i, col, color: line.color, points: pts, run: run.cells }); + p.stats.placementPts += pts; + p.stats.tilesPlaced++; + p.stats.bestPlacement = Math.max(p.stats.bestPlacement, pts); + // Surplus tiles from the line go to the lid; the line resets. + s.lid[line.color] += line.count - 1; + p.lines[i] = { color: null, count: 0 }; } // Floor penalties (clamped so a score never drops below zero). - let penalty = 0; - for (let k = 0; k < p.floor.length && k < FLOOR_SIZE; k++) penalty += FLOOR_PENALTIES[k]; + entry.floorTiles = p.floor.slice(); + const penalty = floorPenaltyFor(p.floor.length); entry.floorPenalty = penalty; + const before = p.score; p.score = Math.max(0, p.score + penalty); + entry.floorLost = before - p.score; + p.stats.floorLost += entry.floorLost; // Clear the floor; coloured tiles go to the lid, the marker just leaves. for (const t of p.floor) if (t !== 'first') s.lid[t]++; p.floor = []; + entry.scoreAfter = p.score; + p.stats.roundScores.push(p.score); + const bits = entry.placements.map((pl) => `+${pl.points}`); + s.log.push(`${p.name} tiles ${entry.placements.length} line${entry.placements.length === 1 ? '' : 's'}` + + `${bits.length ? ` (${bits.join(' ')})` : ''}${entry.floorLost ? `, floor −${entry.floorLost}` : ''}` + + `${entry.dumped.length ? `, ${entry.dumped.length} line${entry.dumped.length === 1 ? '' : 's'} dumped` : ''} → ${p.score}.`); return entry; }); @@ -284,14 +477,17 @@ export function resolveRound(state) { if (ended) { for (const p of s.players) { - let bonus = 0; - for (let row = 0; row < WALL_SIZE; row++) if (wallRowComplete(p.wall, row)) bonus += ROW_BONUS; - for (let col = 0; col < WALL_SIZE; col++) if (wallColumnComplete(p.wall, col)) bonus += COLUMN_BONUS; - for (const c of COLORS) if (colorComplete(p.wall, c)) bonus += COLOR_BONUS; - p.score += bonus; + const b = endBonuses(p); + p.score += b.total; + p.stats.bonusPts = b.total; + p.stats.roundScores.push(p.score); + summary[p.seat].endBonuses = b; + if (b.total) s.log.push(`${p.name} bonuses: rows +${b.rowPts}, columns +${b.colPts}, colours +${b.colorPts} → ${p.score}.`); } s.gameEnded = true; s.phase = 'gameOver'; + const top = finalRanking(s)[0]; + s.log.push(`Game over — ${top.name} wins with ${top.score}.`); } else { s.round += 1; s.current = s.startPlayer; @@ -301,6 +497,94 @@ export function resolveRound(state) { return s; } +// ── move preview (for the hover UI and the verify script) ─────────────────── +// What `move` would do for the current player, without changing anything: +// taken / placed / overflow, the floor slots the overflow (and marker) would +// fill and the penalty change, whether the line completes and — if so — the +// wall column and the points it would score at round end (lines above it +// that are already full tile first), plus which bonus sets it advances. +export function previewMove(state, move) { + const p = currentPlayer(state); + const free = isFreeWall(state); + const tiles = sourceTiles(state, move.source); + const taken = tiles.filter((t) => t === move.color).length; + const takesFirst = move.source.type === 'center' && state.centerHasFirst; + + let placed = 0, lineAfter = 0, completes = false; + if (move.line !== 'floor') { + const cap = lineCapacity(move.line); + placed = Math.min(cap - p.lines[move.line].count, taken); + lineAfter = p.lines[move.line].count + placed; + completes = lineAfter === cap; + } + const overflow = taken - placed; + const floorBefore = p.floor.length; + const floorAdd = (takesFirst ? 1 : 0) + overflow; + const floorAfter = Math.min(FLOOR_SIZE, floorBefore + floorAdd); + const floorSlots = []; + for (let k = floorBefore; k < floorAfter; k++) floorSlots.push(k); + const floorDelta = floorPenaltyFor(floorAfter) - floorPenaltyFor(floorBefore); + const toLid = floorBefore + floorAdd - floorAfter; + + const out = { + taken, placed, overflow, takesFirst, floorSlots, floorDelta, toLid, + lineAfter, completes, wallCol: null, wallPoints: 0, run: [], + rowAfter: 0, colAfter: 0, colorAfter: 0, endsGame: false, bonusHints: [], + }; + if (!completes) return out; + + // Simulate the earlier (higher) full lines tiling first on a scratch wall. + const scratch = { wall: p.wall.map((r) => r.slice()), wallColors: (p.wallColors ?? emptyWallColors()).map((r) => r.slice()), lines: p.lines }; + for (let i = 0; i < move.line; i++) { + const l = p.lines[i]; + if (l.color === null || l.count !== lineCapacity(i)) continue; + const opts = wallOptions(scratch, i, l.color, free); + if (!opts.length) continue; + const c = free ? defaultWallColumn(scratch, i, l.color, opts) : opts[0]; + scratch.wall[i][c] = true; scratch.wallColors[i][c] = l.color; + } + const opts = wallOptions(scratch, move.line, move.color, free); + if (!opts.length) { out.completes = false; out.dumpRisk = true; return out; } + const col = free ? defaultWallColumn(scratch, move.line, move.color, opts) : opts[0]; + scratch.wall[move.line][col] = true; scratch.wallColors[move.line][col] = move.color; + out.wallCol = col; + out.wallPoints = scorePlacement(scratch.wall, move.line, col); + out.run = placementRun(scratch.wall, move.line, col).cells; + const b = bonusStatus(scratch); + out.rowAfter = b.rows[move.line]; + out.colAfter = b.cols[col]; + out.colorAfter = b.colors[move.color]; + out.endsGame = out.rowAfter === WALL_SIZE; + if (out.endsGame) out.bonusHints.push({ kind: 'row', pts: ROW_BONUS, done: true }); + if (out.colAfter === WALL_SIZE) out.bonusHints.push({ kind: 'col', index: col, pts: COLUMN_BONUS, done: true }); + else if (out.colAfter === WALL_SIZE - 1) out.bonusHints.push({ kind: 'col', index: col, pts: COLUMN_BONUS, done: false }); + if (out.colorAfter === WALL_SIZE) out.bonusHints.push({ kind: 'color', color: move.color, pts: COLOR_BONUS, done: true }); + else if (out.colorAfter === WALL_SIZE - 1) out.bonusHints.push({ kind: 'color', color: move.color, pts: COLOR_BONUS, done: false }); + return out; +} + +// ── tile accounting (tests + the tracker panel) ────────────────────────────── +// Where every tile of each colour is right now. +export function tileCensus(state) { + const out = {}; + for (const c of COLORS) out[c] = { bag: state.bag[c], lid: state.lid[c], table: 0, lines: 0, walls: 0, floors: 0 }; + for (const f of state.factories) for (const t of f) out[t].table++; + for (const t of state.center) out[t].table++; + for (const p of state.players) { + for (const l of p.lines) if (l.color) out[l.color].lines += l.count; + for (let r = 0; r < WALL_SIZE; r++) for (let c = 0; c < WALL_SIZE; c++) { + const col = cellColor(p, r, c); + if (col) out[col].walls++; + } + for (const t of p.floor) if (t !== 'first') out[t].floors++; + } + for (const c of COLORS) { + const o = out[c]; + o.total = o.bag + o.lid + o.table + o.lines + o.walls + o.floors; + } + return out; +} + // ── end of game ────────────────────────────────────────────────────────────── export function isGameOver(state) { return state.phase === 'gameOver'; } @@ -316,3 +600,5 @@ export function finalRanking(state) { .map((p) => ({ seat: p.seat, name: p.name, score: p.score, rows: completedRows(p) })) .sort((a, b) => (b.score - a.score) || (b.rows - a.rows)); } + +export { wallColumnFor, emptyStats }; diff --git a/src/games/azul/AzulSound.js b/src/games/azul/AzulSound.js new file mode 100644 index 0000000..08d0c36 --- /dev/null +++ b/src/games/azul/AzulSound.js @@ -0,0 +1,174 @@ +// AzulSound.js — tiny Web Audio synths for glazed ceramic tiles. No audio +// files; silently does nothing without Web Audio or when the game is muted. +// +// clack(scene, { n, pitch }) tiles set down (n staggered clicks) +// tap(scene) a soft tap on the board (hover / pick) +// crunch(scene, { n }) tiles dropped on the floor line +// chime(scene, { pts }) a wall placement scoring (brighter for more) +// thunk(scene) the lid emptied back into the bag +// rattle(scene, { ms }) the bag shaken before a deal +// flourish(scene) an end-game bonus + +function ctxOf(scene) { + const sm = scene.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} + +const noiseCache = new WeakMap(); +function noise(ac) { + if (noiseCache.has(ac)) return noiseCache.get(ac); + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 0.6), ac.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + noiseCache.set(ac, buf); + return buf; +} + +// Route through Phaser's master volume/mute node when it exposes one. +function out(scene, ac, gain) { + const sm = scene.sound; + const node = sm.masterVolumeNode ?? sm.destination ?? null; + const g = ac.createGain(); + g.gain.value = node ? gain : gain * (sm.volume ?? 1); + g.connect(node ?? ac.destination); + return g; +} + +// One ceramic click: a damped high partial pair plus a filtered noise tick. +function click(ac, dest, t0, { freq = 2900, decay = 0.05, vol = 1, body = 0.35 } = {}) { + for (const [f, a] of [[freq, 1], [freq * 1.47, 0.5], [freq * 0.52, body]]) { + const o = ac.createOscillator(); + o.type = 'sine'; + o.frequency.setValueAtTime(f, t0); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(vol * a, t0 + 0.002); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + decay * (f < freq ? 1.6 : 1)); + o.connect(g); g.connect(dest); + o.start(t0); o.stop(t0 + decay * 2 + 0.02); + } + const n = ac.createBufferSource(); + n.buffer = noise(ac); + const hp = ac.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 3000; + const ng = ac.createGain(); + ng.gain.setValueAtTime(vol * 0.6, t0); + ng.gain.exponentialRampToValueAtTime(0.0005, t0 + 0.018); + n.connect(hp); hp.connect(ng); ng.connect(dest); + n.start(t0, Math.random() * 0.4); n.stop(t0 + 0.03); +} + +export function clack(scene, { n = 1, pitch = 1, vol = 0.07, spread = 0.04 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.005; + for (let k = 0; k < Math.min(n, 6); k++) { + click(ac, dest, t0 + k * spread + Math.random() * 0.012, { freq: (2500 + Math.random() * 700) * pitch, decay: 0.045 + Math.random() * 0.02 }); + } + } catch (_) { /* audio is decoration */ } +} + +export function tap(scene, { vol = 0.035 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + click(ac, out(scene, ac, vol), ac.currentTime + 0.003, { freq: 1500 + Math.random() * 200, decay: 0.03, body: 0.6 }); + } catch (_) { /* audio is decoration */ } +} + +export function crunch(scene, { n = 1, vol = 0.09 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.005; + for (let k = 0; k < Math.min(n, 5); k++) { + const t = t0 + k * 0.05; + const src = ac.createBufferSource(); + src.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 900 + Math.random() * 400; bp.Q.value = 0.9; + const g = ac.createGain(); + g.gain.setValueAtTime(0, t); + g.gain.linearRampToValueAtTime(0.9, t + 0.004); + g.gain.exponentialRampToValueAtTime(0.001, t + 0.12); + src.connect(bp); bp.connect(g); g.connect(dest); + src.start(t, Math.random() * 0.4); src.stop(t + 0.14); + click(ac, dest, t, { freq: 1900, decay: 0.03, vol: 0.5 }); + } + // A low thud under it all. + const o = ac.createOscillator(); const og = ac.createGain(); + o.frequency.setValueAtTime(140, t0); o.frequency.exponentialRampToValueAtTime(60, t0 + 0.15); + og.gain.setValueAtTime(0.5, t0); og.gain.exponentialRampToValueAtTime(0.001, t0 + 0.18); + o.connect(og); og.connect(dest); o.start(t0); o.stop(t0 + 0.2); + } catch (_) { /* audio is decoration */ } +} + +export function chime(scene, { pts = 1, vol = 0.06 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.01; + // A rising pentatonic degree for bigger placements. + const scale = [0, 2, 4, 7, 9, 12, 14, 16, 19, 21]; + const semis = scale[Math.min(scale.length - 1, Math.max(0, pts - 1))]; + const base = 659.25 * 2 ** (semis / 12); + for (const [mul, a, dur] of [[1, 1, 0.9], [2.01, 0.35, 0.5], [3.02, 0.12, 0.3]]) { + const o = ac.createOscillator(); o.type = 'sine'; o.frequency.value = base * mul; + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(a, t0 + 0.006); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + dur); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + dur + 0.05); + } + } catch (_) { /* audio is decoration */ } +} + +export function thunk(scene, { vol = 0.12 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.01; + const o = ac.createOscillator(); const g = ac.createGain(); + o.frequency.setValueAtTime(110, t0); o.frequency.exponentialRampToValueAtTime(48, t0 + 0.25); + g.gain.setValueAtTime(0.9, t0); g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.3); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + 0.32); + rattle(scene, { ms: 350, vol: 0.05 }); + } catch (_) { /* audio is decoration */ } +} + +export function rattle(scene, { ms = 420, vol = 0.05 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.01; + const n = Math.round(ms / 28); + for (let k = 0; k < n; k++) { + click(ac, dest, t0 + (k / n) * (ms / 1000) + Math.random() * 0.02, { + freq: 1700 + Math.random() * 1500, decay: 0.025, vol: 0.4 + Math.random() * 0.6, body: 0.2, + }); + } + } catch (_) { /* audio is decoration */ } +} + +export function flourish(scene, { vol = 0.06 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.01; + [523.25, 659.25, 783.99, 1046.5].forEach((f, i) => { + const o = ac.createOscillator(); o.type = 'triangle'; o.frequency.value = f; + const g = ac.createGain(); + const t = t0 + i * 0.07; + g.gain.setValueAtTime(0, t); + g.gain.linearRampToValueAtTime(0.7, t + 0.01); + g.gain.exponentialRampToValueAtTime(0.0005, t + 0.7); + o.connect(g); g.connect(dest); o.start(t); o.stop(t + 0.75); + }); + } catch (_) { /* audio is decoration */ } +} diff --git a/src/games/azul/AzulTiles.js b/src/games/azul/AzulTiles.js new file mode 100644 index 0000000..218c5ea --- /dev/null +++ b/src/games/azul/AzulTiles.js @@ -0,0 +1,189 @@ +// AzulTiles.js — stable identities for the 100 physical tiles. Phaser-free. +// +// The engine only tracks colours and counts, but the scene wants every tile to +// be one persistent sprite that slides from plate to centre to line to wall. +// TileTracker keeps id → location and, given each new engine state, works out +// which ids moved where with the least disturbance: +// 1. every container (bag, lid, a plate, the centre, a pattern line, a wall +// cell, a floor line) keeps the ids it already holds that it still needs +// 2. the remaining ids are freed and handed to the containers short of tiles, +// colour by colour, preferring an obvious source (a seat's line feeds that +// seat's wall, a plate's leftovers feed the centre, …) +// Ids 0..99: colour = COLORS[floor(id / 20)]. +// +// Location: { kind, seat?, index?, row?, col?, slot? } — see AzulLayout.tilePose. + +import { COLORS, WALL_SIZE, TILES_PER_COLOR } from './AzulData.js'; +import { cellColor } from './AzulLogic.js'; + +export const TILE_COUNT = COLORS.length * TILES_PER_COLOR; +export const colorOfId = (id) => COLORS[Math.floor(id / TILES_PER_COLOR)]; + +// Container key → { loc template, colours wanted (ordered when it matters) }. +function containers(state) { + const out = new Map(); + const put = (key, base, colours, ordered) => out.set(key, { key, base, colours, ordered }); + const bag = [], lid = []; + for (const c of COLORS) { for (let k = 0; k < state.bag[c]; k++) bag.push(c); for (let k = 0; k < state.lid[c]; k++) lid.push(c); } + put('bag', { kind: 'bag' }, bag, false); + put('lid', { kind: 'lid' }, lid, false); + state.factories.forEach((f, i) => put(`f${i}`, { kind: 'factory', index: i }, f.slice(), true)); + put('c', { kind: 'center' }, state.center.slice(), false); + for (const p of state.players) { + for (let r = 0; r < WALL_SIZE; r++) { + const l = p.lines[r]; + put(`l${p.seat}.${r}`, { kind: 'line', seat: p.seat, row: r }, l.color ? Array(l.count).fill(l.color) : [], true); + for (let c = 0; c < WALL_SIZE; c++) { + const col = cellColor(p, r, c); + if (col) put(`w${p.seat}.${r}.${c}`, { kind: 'wall', seat: p.seat, row: r, col: c }, [col], true); + } + } + // Floor keeps marker positions so slots line up with the board. + put(`fl${p.seat}`, { kind: 'floor', seat: p.seat }, p.floor.slice(), true); + } + return out; +} + +// How natural it is for a freed tile from container `from` to fill `to`. +function affinity(from, to) { + if (!from) return 0; + if (from[0] === 'l' && to[0] === 'w' && from.slice(1).split('.').slice(0, 2).join('.') === to.slice(1).split('.').slice(0, 2).join('.')) return 9; + if (from[0] === 'f' && from[1] !== 'l' && to === 'c') return 6; // plate leftovers → centre + if (from === 'lid' && to === 'bag') return 6; // refill + if (from === 'bag' && to[0] === 'f' && to[1] !== 'l') return 6; // deal + if ((from[0] === 'l' || from.startsWith('fl')) && to === 'lid') return 5; // discards + if ((from[0] === 'f' || from === 'c') && (to[0] === 'l' || to.startsWith('fl'))) return 4; // a take + return 0; +} + +export class TileTracker { + constructor(state) { + this.where = new Array(TILE_COUNT).fill(null); // id → container key + this.slot = new Array(TILE_COUNT).fill(0); // id → slot within container + this.seq = new Array(TILE_COUNT).fill(0); // arrival order (centre sorting) + this.tick = 0; + for (let id = 0; id < TILE_COUNT; id++) this.where[id] = 'bag'; + this.sync(state); + } + + // Location object for an id. + loc(id) { + const key = this.where[id]; + const c = this._last?.get(key); + const base = c?.base ?? { kind: 'bag' }; + return { ...base, slot: this.slot[id] }; + } + + // Update to `state`. Returns [{ id, from, to, moved }] for every id whose + // container or slot changed (`moved` = container changed). + sync(state) { + const conts = containers(state); + const held = new Map(); + for (let id = 0; id < TILE_COUNT; id++) { + const k = this.where[id]; + if (!held.has(k)) held.set(k, []); + held.get(k).push(id); + } + const prevWhere = this.where.slice(); + const prevSlot = this.slot.slice(); + const prevConts = this._last; + const prevLoc = (id) => { + const c = prevConts?.get(prevWhere[id]); + return { ...(c?.base ?? { kind: 'bag' }), slot: prevSlot[id] }; + }; + + // 1. keep what still fits. + const assigned = new Map(); // key → ids (ordered by need) + const freed = []; + for (const [key, c] of conts) { + const mine = (held.get(key) ?? []).slice().sort((a, b) => this.slot[a] - this.slot[b]); + const pool = mine.slice(); + const ids = c.colours.map((col) => { + if (col === 'first') return 'first'; + const i = pool.findIndex((id) => colorOfId(id) === col); + if (i < 0) return null; + return pool.splice(i, 1)[0]; + }); + assigned.set(key, ids); + freed.push(...pool); + held.delete(key); + } + for (const ids of held.values()) freed.push(...ids); // containers that vanished + + // 2. hand freed ids to the gaps, best affinity first. + const gaps = []; + for (const [key, ids] of assigned) { + const c = conts.get(key); + ids.forEach((id, i) => { if (id === null) gaps.push({ key, i, color: c.colours[i] }); }); + } + const pairs = []; + for (const g of gaps) { + for (const id of freed) { + if (colorOfId(id) !== g.color) continue; + pairs.push({ g, id, a: affinity(prevWhere[id], g.key) }); + } + } + pairs.sort((x, y) => y.a - x.a || x.id - y.id); + const used = new Set(); + for (const { g, id } of pairs) { + if (g.done || used.has(id)) continue; + assigned.get(g.key)[g.i] = id; + g.done = true; + used.add(id); + } + if (gaps.some((g) => !g.done)) throw new Error('TileTracker: could not place every tile'); + + // 3. write back, with slots. + this.tick++; + for (const [key, ids] of assigned) { + const c = conts.get(key); + let list = ids; + if (key === 'c') { + // Centre: grouped by colour, stable within a colour (arrival order). + for (const id of ids) if (prevWhere[id] !== 'c') this.seq[id] = this.tick * 1000 + id; + list = ids.slice().sort((a, b) => COLORS.indexOf(colorOfId(a)) - COLORS.indexOf(colorOfId(b)) || this.seq[a] - this.seq[b]); + const offset = state.centerHasFirst ? 1 : 0; // the marker sits first + list.forEach((id, i) => { this.where[id] = key; this.slot[id] = i + offset; }); + continue; + } + ids.forEach((id, i) => { + if (id === 'first') return; + this.where[id] = key; + this.slot[id] = (key === 'bag' || key === 'lid') ? 0 : i; + }); + void c; + } + this._last = conts; + + const changes = []; + for (let id = 0; id < TILE_COUNT; id++) { + const moved = prevWhere[id] !== this.where[id]; + if (moved || prevSlot[id] !== this.slot[id]) changes.push({ id, from: prevLoc(id), to: this.loc(id), moved, fromKey: prevWhere[id], toKey: this.where[id] }); + } + return changes; + } + + // Ids currently in a container key (e.g. 'f3', 'c', 'l0.2', 'fl1'). + idsIn(key) { + const out = []; + for (let id = 0; id < TILE_COUNT; id++) if (this.where[id] === key) out.push(id); + return out.sort((a, b) => this.slot[a] - this.slot[b]); + } + + // Census by container kind, for tests. + counts() { + const out = {}; + for (let id = 0; id < TILE_COUNT; id++) out[this.where[id]] = (out[this.where[id]] ?? 0) + 1; + return out; + } + + // Where the first-player marker sits: { kind:'center', slot:0 } or floor. + static markerLoc(state) { + if (state.centerHasFirst) return { kind: 'center', slot: 0 }; + for (const p of state.players) { + const k = p.floor.indexOf('first'); + if (k >= 0) return { kind: 'floor', seat: p.seat, slot: k }; + } + return { kind: 'center', slot: 0, hidden: true }; + } +} diff --git a/src/games/azul/sprite.md b/src/games/azul/sprite.md index 545f44f..3921cc5 100644 --- a/src/games/azul/sprite.md +++ b/src/games/azul/sprite.md @@ -4,11 +4,11 @@ **Cell size:** 96 × 96 px (transparent PNG) **Total frames:** 6, single row (sheet is 576 × 96) -A **temporary** placeholder sheet is already committed (flat colours with a -diamond motif, generated by `tools` PIL script). Replace it with finished -azulejo-style tile art at the same dimensions and frame order and the game picks -it up automatically — no code changes needed. If the file is ever missing, the -scene falls back to vector tiles. +The committed sheet holds the finished azulejo tile art. `AzulArt.js` bakes +each frame into a glazed tile texture (rounded corners, bevel, sheen and a soft +shadow) and uses washed-out copies as the wall "ghosts" on every board, so new +art at the same dimensions and frame order is picked up automatically. If the +file is ever missing, procedural azulejo faces are drawn instead. ## Frame order diff --git a/src/games/azul/tutorial.md b/src/games/azul/tutorial.md index 86aece3..9153a6b 100644 --- a/src/games/azul/tutorial.md +++ b/src/games/azul/tutorial.md @@ -33,7 +33,9 @@ On your turn you do exactly one thing: **take all tiles of a single colour** fro - Click any tile in a **factory display** to take *every* tile of that colour there. The factory's other tiles slide into the **Centre**. - Or click a colour in the **Centre** to take all of it. The first person to take from the Centre each round also picks up the **first-player marker** (the "1" tile) — it drops onto their floor line for a small penalty, but it makes them the start player next round. -Then choose where the tiles go: click a glowing **pattern line**, or the **floor line**. +Then choose where the tiles go: click a glowing **pattern line**, or the **floor line** — or simply **drag** the tiles there. + +**Before you commit, hover a line.** Ghost tiles show exactly where your tiles would land, any spill onto the floor shows in red, and the work-order panel spells it out: how many points the line would score when it tiles, what it costs on the floor, and whether it brings a column or a colour close to its bonus. Changed your mind? Click the tiles again (or press **Esc**) to put them back. Made a move you regret? **Undo** is there until the next player actually moves. Rules for pattern lines: - The line must be empty or already holding that colour. @@ -69,6 +71,25 @@ Highest total wins; ties go to whoever completed more horizontal rows. --- +## Around the Workshop + +- **Tile Tracker** (bottom left): how many of each colour are still in the bag, in the lid, on the table and set on walls. Good tilers count tiles — now everyone can. +- **The bag and the lid**: hover either for exact counts. When the bag runs dry, the lid is poured back in. +- **Bonus badges**: each board shows the end-game bonus it has already locked in, and a ★ for every column or colour that is one tile away. +- **Opponents' boards**: hover one to see it full-size. +- **Order Book** (right): the latest moves; **Log** shows the whole game. +- **Menu**: opponent speed, move preview, undo, the tracker, colour-blind symbols, and the wall variant. + +**Keyboard:** **1–9** pick a plate (press again for its next colour), **C** the centre, **←/→** change colour, **↑/↓** choose a line, **Enter** place, **F** floor, **Z** undo, **L** log, **Esc** cancel / menu. + +--- + +## The Free Wall (variant) + +Turn on the **free (grey) wall** in the Menu for your next game. The wall has no printed colours: when a pattern line tiles, *you* choose which space in that row it goes to — but each colour may appear only once in every row **and** every column. A pattern line can't take a colour that row already has, and if a full line finds no legal space at all, its tiles crash onto your floor. Glowing spaces with their points show your options. + +--- + ## Inês's Advice - **Match the line to the haul.** Need 3 tiles to fill row 3? Take a pile of exactly 3. Overfilling feeds your floor line. diff --git a/tools/verifyAzul.js b/tools/verifyAzul.js new file mode 100644 index 0000000..cd3ed28 --- /dev/null +++ b/tools/verifyAzul.js @@ -0,0 +1,391 @@ +#!/usr/bin/env node +// verifyAzul.js — headless checks for Azul: +// • rules: lineAccepts edge cases, scorePlacement table, floor clamp, first- +// player marker, end trigger + bonus breakdown, free-wall variant rules +// • previewMove agrees with applyMove + resolveRound over random states +// • all-AI soak across 2–4 players, both wall variants and mixed skills: every +// game finishes, 100 tiles conserved after every step, scores add up +// • tile-id tracker (AzulTiles) keeps one id per tile through whole games +// • skill ladder: mirrored seats/seeds +// • screen layout: furniture on screen, no overlaps, children inside parents +// Usage: node tools/verifyAzul.js [--quick] + +import * as L from '../src/games/azul/AzulLogic.js'; +import * as AI from '../src/games/azul/AzulAI.js'; +import { + COLORS, FLOOR_SIZE, lineCapacity, wallColumnFor, wallColor, +} from '../src/games/azul/AzulData.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { TileTracker, TILE_COUNT, colorOfId } from '../src/games/azul/AzulTiles.js'; +import { + hudFurniture, furnitureChildren, onScreen, rectsOverlap, inside, circleRectOverlap, RING, +} from '../src/games/azul/AzulLayout.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +function seedRandom(seed) { const r = mulberry32(seed); Math.random = r; return r; } + +const totalTiles = (s) => { + const c = L.tileCensus(s); + return COLORS.reduce((n, k) => n + c[k].total, 0); +}; + +// A blank player for direct rule tests. +function blankPlayer() { + return { + seat: 0, name: 'T', score: 0, floor: [], + lines: Array.from({ length: 5 }, () => ({ color: null, count: 0 })), + wall: Array.from({ length: 5 }, () => Array(5).fill(false)), + wallColors: Array.from({ length: 5 }, () => Array(5).fill(null)), + stats: L.emptyStats(), + }; +} +function setWall(p, row, col, color = wallColor(row, col)) { p.wall[row][col] = true; p.wallColors[row][col] = color; } + +// ── rules ─────────────────────────────────────────────────────────────────────── +section('Rules'); +{ + const p = blankPlayer(); + ok('empty line accepts any colour', COLORS.every((c) => L.lineAccepts(p, 2, c))); + p.lines[2] = { color: 'red', count: 1 }; + ok('line holding red accepts red', L.lineAccepts(p, 2, 'red')); + ok('line holding red rejects blue', !L.lineAccepts(p, 2, 'blue')); + p.lines[0] = { color: 'blue', count: 1 }; + ok('full line rejects', !L.lineAccepts(p, 0, 'blue')); + setWall(p, 3, wallColumnFor(3, 'yellow')); + ok('wall already has yellow in row 3 → rejects', !L.lineAccepts(p, 3, 'yellow')); + ok('…but accepts black in row 3', L.lineAccepts(p, 3, 'black')); + // Free wall: colour-in-row rule only. + const q = blankPlayer(); + setWall(q, 1, 0, 'red'); + ok('free: row with red rejects red', !L.lineAccepts(q, 1, 'red', true)); + ok('free: row with red accepts blue', L.lineAccepts(q, 1, 'blue', true)); + setWall(q, 0, 3, 'blue'); + ok('free: options exclude columns already holding the colour', JSON.stringify(L.wallOptions(q, 1, 'blue', true)) === JSON.stringify([1, 2, 4])); +} +{ + // scorePlacement table. + const w = Array.from({ length: 5 }, () => Array(5).fill(false)); + const at = (r, c) => { w[r][c] = true; return L.scorePlacement(w, r, c); }; + ok('lone tile = 1', at(2, 2) === 1); + ok('horizontal pair = 2', at(2, 3) === 2); + ok('vertical join = 2', at(1, 2) === 2); + ok('cross = h + v', at(1, 3) === 2 + 2, `${L.scorePlacement(w, 1, 3)}`); + const run = L.placementRun(w, 1, 3); + ok('placementRun covers both runs', run.cells.length === 3 && run.horizontal === 2 && run.vertical === 2); +} +{ + // First-player marker + floor clamp + scoring. + let s = L.createInitialState({ playerCount: 2, seed: 7 }); + s.factories[0] = ['red', 'red', 'blue', 'blue']; + s.current = 0; + s = L.applyMove(s, { source: { type: 'factory', index: 0 }, color: 'red', line: 0 }); + ok('leftovers go to the centre', s.center.filter((t) => t === 'blue').length === 2); + ok('overflow hits the floor', s.players[0].floor.length === 1 && s.lastMove.overflow === 1); + s = L.applyMove(s, { source: { type: 'center' }, color: 'blue', line: 1 }); + ok('first centre take gets the marker', s.players[1].floor[0] === 'first' && !s.centerHasFirst && s.startPlayer === 1); + ok('stats count the marker', s.players[1].stats.firstTaken === 1); +} +{ + // End trigger + bonus breakdown. + let s = L.createInitialState({ playerCount: 2, seed: 11 }); + const p = s.players[0]; + for (let c = 0; c < 4; c++) setWall(p, 0, c); + for (let r = 1; r < 5; r++) setWall(p, r, 0); // column 0 complete with (0,0) + p.lines[0] = { color: wallColor(0, 4), count: 1 }; + s.factories = s.factories.map(() => []); s.center = []; s.centerHasFirst = false; + s.phase = 'scoring'; + const r = L.resolveRound(s); + ok('completing a row ends the game', r.phase === 'gameOver'); + const b = r.roundSummary[0].endBonuses; + ok('row bonus counted', b.rows.length === 1 && b.rowPts === 2); + ok('column bonus counted', b.cols.length === 1 && b.colPts === 7); + const st = r.players[0].stats; + ok('stats add up to the score', st.placementPts - st.floorLost + st.bonusPts === r.players[0].score, + `${st.placementPts}-${st.floorLost}+${st.bonusPts} vs ${r.players[0].score}`); +} +{ + // Floor clamp. + let s = L.createInitialState({ playerCount: 2, seed: 3 }); + s.players[0].floor = ['red', 'red', 'red', 'red']; + s.players[0].score = 2; + s.factories = s.factories.map(() => []); s.center = []; s.centerHasFirst = false; + s.phase = 'scoring'; + const r = L.resolveRound(s); + ok('floor penalty clamps at zero', r.players[0].score === 0 && r.roundSummary[0].floorLost === 2 && r.roundSummary[0].floorPenalty === -6); +} +{ + // Free wall: dump when nowhere to go, choices respected. + let s = L.createInitialState({ playerCount: 2, seed: 5, variant: 'free' }); + const p = s.players[0]; + setWall(p, 0, 0, 'blue'); setWall(p, 2, 1, 'red'); setWall(p, 3, 2, 'red'); setWall(p, 4, 3, 'red'); + // Row 1 has cells 1..4 free; red is already in columns 1,2,3 → only column 4. + p.lines[1] = { color: 'red', count: 2 }; + // Row 0: blue present → line for yellow, choose column 2. + p.lines[0] = { color: 'yellow', count: 1 }; + s.factories = s.factories.map(() => []); s.center = []; s.centerHasFirst = false; + s.phase = 'scoring'; + const r = L.resolveRound(s, { 0: { 0: 2, 1: 1 } }); // column 1 already holds red + const pl = r.roundSummary[0].placements; + ok('free: chosen column used', pl.find((x) => x.row === 0)?.col === 2); + ok('free: illegal choice falls back to the best legal column', pl.find((x) => x.row === 1)?.col === 0); + // Now a dump case. + let s2 = L.createInitialState({ playerCount: 2, seed: 6, variant: 'free' }); + const q = s2.players[0]; + for (let c = 0; c < 4; c++) setWall(q, c + 1, c, 'black'); // black in columns 0..3 + setWall(q, 0, 4, 'red'); // row 0 col 4 taken + q.lines[0] = { color: 'black', count: 1 }; + s2.factories = s2.factories.map(() => []); s2.center = []; s2.centerHasFirst = false; + s2.phase = 'scoring'; + const before2 = totalTiles(s2); + const r2 = L.resolveRound(s2); + ok('free: unplaceable line is dumped to the floor', r2.roundSummary[0].dumped.length === 1 && r2.roundSummary[0].floorPenalty === -1); + ok('free: dump conserves tiles', totalTiles(r2) === before2); +} + +// ── previewMove vs reality ──────────────────────────────────────────────────── +section('previewMove agrees with applyMove + resolveRound'); +{ + const rnd = seedRandom(42); + let checked = 0, bad = 0; + for (let g = 0; g < (QUICK ? 30 : 120); g++) { + const variant = g % 3 === 2 ? 'free' : 'standard'; + let s = L.createInitialState({ playerCount: 2 + (g % 3), seed: 1000 + g, variant }); + let guard = 0; + while (s.phase !== 'gameOver' && guard++ < 400) { + if (s.phase === 'scoring') { s = L.resolveRound(s); continue; } + const moves = L.legalMoves(s); + const m = moves[Math.floor(rnd() * moves.length)]; + const pv = L.previewMove(s, m); + const seat = s.current; + const before = s.players[seat]; + const after = L.applyMove(s, m); + const pa = after.players[seat]; + checked++; + const floorBefore = before.floor.length; + const okTake = pv.taken === after.lastMove.taken && pv.placed === after.lastMove.placed && pv.overflow === after.lastMove.overflow; + const okFloor = pa.floor.length === floorBefore + pv.floorSlots.length; + let okPts = true; + if (pv.completes && variant === 'standard') { + // Clear other lines below so only this line (and full lines above it) tile. + const t = JSON.parse(JSON.stringify(after)); + t.factories = t.factories.map(() => []); t.center = []; t.phase = 'scoring'; + const tp = t.players[seat]; + for (let i = m.line + 1; i < 5; i++) tp.lines[i] = { color: null, count: 0 }; + const r = L.resolveRound(t); + const pl = r.roundSummary[seat].placements.find((x) => x.row === m.line); + okPts = !!pl && pl.points === pv.wallPoints && pl.col === pv.wallCol; + } + if (!(okTake && okFloor && okPts)) { + bad++; + if (bad <= 3) console.error(' preview mismatch', JSON.stringify({ m, pv, last: after.lastMove })); + } + s = after; + } + } + ok(`previewMove matches (${checked} random moves)`, bad === 0, `${bad} mismatches`); +} + +// ── AI soak ───────────────────────────────────────────────────────────────────── +function playGame({ players = 4, skills = null, seed = 1, variant = 'standard', onStep = null, maxSteps = 600 } = {}) { + let s = L.createInitialState({ playerCount: players, seed, variant, names: Array.from({ length: players }, (_, i) => `P${i}`) }); + const skillOf = (seat) => (skills ? skills[seat] : 3); + const problems = []; + let steps = 0; + const check = () => { + const t = totalTiles(s); + if (t !== 100) problems.push(`tiles ${t} != 100 (round ${s.round})`); + for (const p of s.players) { + if (p.score < 0) problems.push(`seat ${p.seat} negative score`); + if (p.floor.length > FLOOR_SIZE) problems.push('floor overfull'); + for (let i = 0; i < 5; i++) if (p.lines[i].count > lineCapacity(i)) problems.push('line overfull'); + for (let r = 0; r < 5; r++) { + const seen = new Set(); + for (let c = 0; c < 5; c++) { const col = L.cellColor(p, r, c); if (col) { if (seen.has(col)) problems.push('colour repeated in a row'); seen.add(col); } } + } + for (let c = 0; c < 5; c++) { + const seen = new Set(); + for (let r = 0; r < 5; r++) { const col = L.cellColor(p, r, c); if (col) { if (seen.has(col)) problems.push('colour repeated in a column'); seen.add(col); } } + } + } + }; + while (s.phase !== 'gameOver' && steps++ < maxSteps) { + if (s.phase === 'scoring') { + const choices = {}; + for (const p of s.players) choices[p.seat] = AI.chooseWallColumns(s, p.seat, skillOf(p.seat)); + s = L.resolveRound(s, choices); + } else { + const m = AI.chooseMove(s, skillOf(s.current)); + if (!m) { problems.push('AI returned no move'); break; } + if (!L.isLegalMove(s, m)) problems.push(`illegal AI move ${JSON.stringify(m)}`); + s = L.applyMove(s, m); + } + onStep?.(s); + check(); + if (problems.length) break; + } + if (s.phase !== 'gameOver') problems.push(`did not finish (${steps} steps, round ${s.round})`); + if (s.phase === 'gameOver') { + for (const p of s.players) { + const st = p.stats; + if (st.placementPts - st.floorLost + st.bonusPts !== p.score) problems.push(`seat ${p.seat} stats don't add up`); + if (st.roundScores[st.roundScores.length - 1] !== p.score) problems.push(`seat ${p.seat} roundScores end != score`); + } + } + return { s, problems, steps }; +} + +section('All-AI soak'); +{ + seedRandom(9); + const N = QUICK ? 60 : 240; + let finished = 0, rounds = 0, issues = 0; + const scoreSum = { 2: 0, 3: 0, 4: 0 }, games = { 2: 0, 3: 0, 4: 0 }; + const t0 = Date.now(); + for (let g = 0; g < N; g++) { + const players = 2 + (g % 3); + const variant = g % 4 === 3 ? 'free' : 'standard'; + const skills = Array.from({ length: players }, (_, i) => 1 + ((g + i * 2) % 5)); + const { s, problems } = playGame({ players, skills, seed: 5000 + g, variant }); + if (problems.length) { issues++; if (issues <= 5) console.error(` game ${g}: ${problems.slice(0, 3).join('; ')}`); } + if (s.phase === 'gameOver') { finished++; rounds += s.round; } + for (const p of s.players) scoreSum[players] += p.score; + games[players] += players; + } + ok(`${N} games finish cleanly`, issues === 0 && finished === N, `${issues} with problems, ${finished} finished`); + console.log(` avg rounds ${(rounds / Math.max(1, finished)).toFixed(2)} · avg score 2p ${(scoreSum[2] / games[2]).toFixed(1)} 3p ${(scoreSum[3] / games[3]).toFixed(1)} 4p ${(scoreSum[4] / games[4]).toFixed(1)} · ${((Date.now() - t0) / N).toFixed(0)} ms/game`); +} + +// ── skill ladder ───────────────────────────────────────────────────────────── +function ladder(a, b, pairs, players = 2) { + let winsA = 0, games = 0, marginA = 0; + for (let i = 0; i < pairs; i++) { + for (const flip of [false, true]) { + seedRandom(77 + i * 2 + (flip ? 1 : 0)); + const skills = Array.from({ length: players }, (_, k) => (k === 0) !== flip ? a : b); + const { s } = playGame({ players, skills, seed: 9000 + i }); + const rank = L.finalRanking(s); + const seatA = flip ? 1 : 0; + if (rank[0].seat === seatA) winsA++; + const sa = s.players[seatA].score; + const others = s.players.filter((p) => p.seat !== seatA).map((p) => p.score); + marginA += sa - Math.max(...others); + games++; + } + } + return { rate: winsA / games, margin: marginA / games, games }; +} + +section('Skill ladder (mirrored seats + seeds, 2 players)'); +{ + const P = QUICK ? 20 : 80; + const t0 = Date.now(); + const l31 = ladder(3, 1, P); + const l53 = ladder(5, 3, P); + const l43 = ladder(4, 3, P); + const l54 = ladder(5, 4, P); + const l21 = ladder(2, 1, P); + const l32 = ladder(3, 2, P); + console.log(` 2 vs 1: ${(l21.rate * 100).toFixed(0)}% (margin ${l21.margin.toFixed(1)})`); + console.log(` 3 vs 2: ${(l32.rate * 100).toFixed(0)}% (margin ${l32.margin.toFixed(1)})`); + console.log(` 3 vs 1: ${(l31.rate * 100).toFixed(0)}% (margin ${l31.margin.toFixed(1)})`); + console.log(` 4 vs 3: ${(l43.rate * 100).toFixed(0)}% (margin ${l43.margin.toFixed(1)})`); + console.log(` 5 vs 4: ${(l54.rate * 100).toFixed(0)}% (margin ${l54.margin.toFixed(1)})`); + console.log(` 5 vs 3: ${(l53.rate * 100).toFixed(0)}% (margin ${l53.margin.toFixed(1)}) [${((Date.now() - t0) / 1000).toFixed(1)}s]`); + ok('skill 3 beats skill 1 ≥ 70%', l31.rate >= 0.7, `${(l31.rate * 100).toFixed(0)}%`); + ok('skill 5 beats skill 3 ≥ 58%', l53.rate >= 0.58, `${(l53.rate * 100).toFixed(0)}%`); + ok('skill 4 out-scores skill 3', l43.margin > 0, `${l43.margin.toFixed(1)}`); +} + +// ── tile-id tracker ───────────────────────────────────────────────────────────── +section('Tile tracker (stable sprite ids)'); +{ + seedRandom(21); + let games = 0, bad = 0, steps = 0, needless = 0; + for (let g = 0; g < (QUICK ? 12 : 40); g++) { + const players = 2 + (g % 3); + let tracker = null; + const check = (s, changes) => { + steps++; + // Every container holds exactly the colours the state says. + const c = tracker.counts(); + const cen = L.tileCensus(s); + for (const col of COLORS) { + const inBag = tracker.idsIn('bag').filter((id) => colorOfId(id) === col).length; + const inLid = tracker.idsIn('lid').filter((id) => colorOfId(id) === col).length; + if (inBag !== cen[col].bag || inLid !== cen[col].lid) { bad++; return; } + } + s.factories.forEach((f, i) => { + const ids = tracker.idsIn(`f${i}`); + if (ids.map(colorOfId).join() !== f.join()) bad++; + }); + for (const p of s.players) { + for (let r = 0; r < 5; r++) { + const ids = tracker.idsIn(`l${p.seat}.${r}`); + if (ids.length !== p.lines[r].count || ids.some((id) => colorOfId(id) !== p.lines[r].color)) bad++; + } + const fl = tracker.idsIn(`fl${p.seat}`); + if (fl.length !== p.floor.filter((t) => t !== 'first').length) bad++; + } + const total = Object.values(c).reduce((a, b) => a + b, 0); + if (total !== TILE_COUNT) bad++; + // Wall tiles never move once set. + for (const ch of changes ?? []) if (ch.from.kind === 'wall') needless++; + }; + playGame({ + players, seed: 700 + g, variant: g % 2 ? 'free' : 'standard', + skills: Array.from({ length: players }, () => 3), + onStep: (s) => { + if (!tracker) { tracker = new TileTracker(s); check(s, []); return; } + check(s, tracker.sync(s)); + }, + }); + games++; + } + ok(`tracker matches the engine after every step (${games} games, ${steps} steps)`, bad === 0, `${bad} mismatches`); + ok('wall tiles never move', needless === 0, `${needless}`); + { + // A single take moves exactly the taken tiles plus the leftovers. + let s = L.createInitialState({ playerCount: 3, seed: 4 }); + const t = new TileTracker(s); + s.factories[0] = s.factories[0]; + const f0 = s.factories[0]; + const color = f0[0]; + const ch = t.sync(L.applyMove(s, { source: { type: 'factory', index: 0 }, color, line: 'floor' })); + ok('a take moves only that plate\'s four tiles', ch.filter((c) => c.moved).length === f0.length && ch.every((c) => c.fromKey === 'f0'), + ch.map((c) => `${c.fromKey}->${c.toKey}`).join(' ')); + } +} + +// ── layout ────────────────────────────────────────────────────────────────────── +section('Screen layout'); +for (const players of [2, 3, 4]) { + const f = hudFurniture({ players }); + for (const r of f) ok(`${players}p ${r.name} on screen`, onScreen(r), JSON.stringify(r)); + const isPlate = (r) => r.name.startsWith('plate'); + for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) { + const a = f[i], b = f[j]; + if (a.overlapOk?.includes(b.name) || b.overlapOk?.includes(a.name)) continue; + let hit; + if (isPlate(a) && isPlate(b)) { + const ca = { x: a.x + a.w / 2, y: a.y + a.h / 2 }, cb = { x: b.x + b.w / 2, y: b.y + b.h / 2 }; + hit = Math.hypot(ca.x - cb.x, ca.y - cb.y) < RING.r * 2 + 4; + } else if (isPlate(a)) hit = circleRectOverlap(a.x + a.w / 2, a.y + a.h / 2, RING.r, b); + else if (isPlate(b)) hit = circleRectOverlap(b.x + b.w / 2, b.y + b.h / 2, RING.r, a); + else hit = rectsOverlap(a, b); + ok(`${players}p ${a.name} clear of ${b.name}`, !hit, `${JSON.stringify(a)} ${JSON.stringify(b)}`); + } + const byName = new Map(f.map((r) => [r.name, r])); + for (const k of furnitureChildren({ players })) { + const p = byName.get(k.parent); + ok(`${players}p ${k.name} inside ${k.parent}`, !!p && inside(k, p), `${JSON.stringify(k)} in ${JSON.stringify(p)}`); + } +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);