Rebuild Azul as a full tile workshop scene with procedural art, AI, and tests

- Split the monolithic scene into focused modules: layout, art baking, HUD, dialogs, end screen, sound, tile identity tracking, and a verification harness
- Replace the 1-ply greedy AI with an incremental valuation that scores placement points, bonus progress, floor liability, end-timing, denial, exposure, and optional rollouts across a 5-level skill ladder; add free-wall column picking
- Add the free (grey) wall variant end-to-end: per-row/per-column colour constraints, legal-column queries, dump-to-floor when no cell fits, player column choices during scoring, and AI support
- Track all 100 tiles as persistent sprites with stable ids so they slide between bag, plates, centre, lines, walls, floor, and lid instead of being recreated each render
- Bake the Lisbon workshop (azulejo wainscot, oak bench, glazed tiles, plates, tray, bag, lid, panels) into canvas textures with optional colour-blind glyphs; add Web Audio ceramic SFX
- Add quality-of-life UI: hover/keyboard move preview with points and floor cost, drag-to-place, undo until the next player moves, tile tracker, bonus badges, opponent board zoom popover, tooltips, order book, pause/settings, and a detailed end screen with per-round chart
- Extend rules logic with stats, round summaries, placement runs, bonus status, previewMove, tile census, and richer log entries; update sprite and tutorial docs
- Add tools/verifyAzul.js to check rules, preview accuracy, all-AI soak games, the skill ladder, tile-id stability, and screen layout
This commit is contained in:
Brian Fertig 2026-11-25 01:47:25 -07:00
parent 8ef312ef45
commit 01372c1c62
No known key found for this signature in database
13 changed files with 4157 additions and 831 deletions

View File

@ -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;
}

671
src/games/azul/AzulArt.js Normal file
View File

@ -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-<big|mini>[-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-<name> wood-framed cream panels for the HUD
// azul-notepad the workshop order book (log)
// azul-t-<colour>[-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);
}

View File

@ -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;
}

View File

@ -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?.()); } };
}

File diff suppressed because it is too large Load Diff

312
src/games/azul/AzulHud.js Normal file
View File

@ -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')); }
}
}

View File

@ -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;
}

View File

@ -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 };

174
src/games/azul/AzulSound.js Normal file
View File

@ -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 */ }
}

189
src/games/azul/AzulTiles.js Normal file
View File

@ -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 };
}
}

View File

@ -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

View File

@ -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.

391
tools/verifyAzul.js Normal file
View File

@ -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);