// Azul — pure state engine. No Phaser, no network, no rendering. // // State is immutable from the outside: every mutator deep-clones and returns a // fresh state (the SplendorLogic idiom). Randomness lives in `rngState` inside // the state itself so deals stay reproducible across the whole game and survive // JSON clone. A round runs in two beats: // 1. 'offer' — players take turns drafting tiles onto pattern lines. // 2. 'scoring' — once every factory and the centre are empty the offer phase // 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, 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) { let a = s.rngState >>> 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; s.rngState = a >>> 0; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; } const emptyCounts = () => ({ blue: 0, yellow: 0, red: 0, black: 0, white: 0 }); function emptyLines() { return Array.from({ length: WALL_SIZE }, () => ({ color: null, count: 0 })); } 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); } // Pull one random tile from the bag, refilling from the lid (discard) when the // bag runs dry. Returns a colour string, or null when both are empty. function drawTile(s) { let total = bagTotal(s); if (total === 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; } let r = Math.floor(nextRand(s) * total); for (const c of COLORS) { if (r < s.bag[c]) { s.bag[c]--; return c; } r -= s.bag[c]; } return null; } // Fill every factory with up to 4 tiles and reset the centre with the first- // 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, 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(), factories: [], center: [], centerHasFirst: true, players: [], current: 0, 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: [], }; s.rngState = (s.seed + 0x9e3779b9) >>> 0; for (const c of COLORS) s.bag[c] = TILES_PER_COLOR; for (let seat = 0; seat < pc; seat++) { s.players.push({ seat, 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(), }); } s.startPlayer = Math.floor(nextRand(s) * pc); s.current = s.startPlayer; dealFactories(s); return s; } // ── queries ────────────────────────────────────────────────────────────────── export function currentPlayer(state) { return state.players[state.current]; } export function isFreeWall(state) { return state.variant === 'free'; } // 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 } })); sources.push({ tiles: state.center, source: { type: 'center' } }); for (const { tiles, source } of sources) { 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, free)) moves.push({ source, color, line: i }); } moves.push({ source, color, line: 'floor' }); } } 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) { for (let k = 0; k < n; k++) { if (p.floor.length < FLOOR_SIZE) p.floor.push(color); else s.lid[color]++; } } 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); if (s.phase !== 'offer') return s; const p = currentPlayer(s); const { source, color } = move; // 1. Gather the chosen colour from the source; scatter the rest as needed. 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.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. 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; placed = Math.min(space, taken); line.count += placed; } 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); 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; const empty = s.factories.every((f) => f.length === 0) && s.center.length === 0; if (empty) s.phase = 'scoring'; return s; } // ── wall-tiling scoring ────────────────────────────────────────────────────── // Points for placing a tile at (row, col) on `wall` (the cell already set true). // Counts the contiguous horizontal and vertical runs through the new tile. export function scorePlacement(wall, row, col) { let h = 1; for (let c = col - 1; c >= 0 && wall[row][c]; c--) h++; for (let c = col + 1; c < WALL_SIZE && wall[row][c]; c++) h++; let v = 1; for (let r = row - 1; r >= 0 && wall[r][col]; r--) v++; for (let r = row + 1; r < WALL_SIZE && wall[r][col]; r++) v++; if (h > 1 && v > 1) return h + v; if (h > 1) return h; if (v > 1) return v; 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 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. // 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: [], 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)) 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). 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; }); s.roundSummary = summary; // The game ends after any round in which a player completes a wall row. const ended = s.players.some((p) => { for (let row = 0; row < WALL_SIZE; row++) if (wallRowComplete(p.wall, row)) return true; return false; }); if (ended) { for (const p of s.players) { 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; s.phase = 'offer'; dealFactories(s); } 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'; } function completedRows(p) { let n = 0; for (let row = 0; row < WALL_SIZE; row++) if (wallRowComplete(p.wall, row)) n++; return n; } // Ranking: highest score, then most complete horizontal rows (official tiebreak). export function finalRanking(state) { return state.players .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 };