diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index 08fdba3..4475d55 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -56,7 +56,7 @@ registerGame({ slug: 'wordladder', name: 'Word Ladder', category: 'word', minPla registerGame({ slug: 'wordsearch', name: 'Word Search', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 26 }); registerGame({ slug: 'hangman', name: 'Hangman', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 27 }); registerGame({ slug: 'sudoku', name: 'Sudoku', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 28 }); -registerGame({ slug: 'othello', name: 'Othello', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 29, defaultPlayfield: 'cherry' }); +registerGame({ slug: 'othello', name: 'Othello', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 29 }); registerGame({ slug: 'go', name: 'Go', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 30, defaultPlayfield: 'dark' }); registerGame({ slug: 'battleship', name: 'Battleship', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 31 }); registerGame({ slug: 'mastermind', name: 'Mastermind', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 32 }); diff --git a/src/games/othello/OthelloAI.js b/src/games/othello/OthelloAI.js index 29606ce..d0e4135 100644 --- a/src/games/othello/OthelloAI.js +++ b/src/games/othello/OthelloAI.js @@ -1,117 +1,672 @@ -// Othello AI — alpha-beta minimax with classic positional heuristics. -import { other, getValidMoves, getFlips, getScore, getWinner, cloneState, applyMove, mustPass, SIZE } from './OthelloLogic.js'; +// OthelloAI.js: the opponents and the Master's analysis. Phaser-free; runs +// in the engine worker (OthelloEngine.js) and in tools/verifyOthello.js. +// +// The searcher keeps a padded "mailbox" board (works for 6×6, 8×8, 10×10), +// makes and unmakes moves in place with a flip stack and Zobrist hashing, +// and runs negamax alpha-beta with PVS, a transposition table, iterative +// deepening and "fastest-first" move ordering. With few squares left it +// solves the game exactly (final disc difference). +// +// Positions passed in are plain: { size, variant, board: [null|'black'|'white'…], turn }. +// +// chooseMove(pos, skill, { line, rnd }) → { sq, score, book, exact } +// hint(pos, { ms }) → { sq, score, exact, depth } +// rankMoves(pos, { depth, ms }) → [{ sq, score }] best first +// review(positions, { ms }) → [{ i, best, played, loss, exact }] +// describeIdea(pos, sq, res) → coach text ("takes a corner") +// describeMistake(pos, played, best) → what went wrong ("gave up a corner") +// +// Scores are from the side to move, in hundredths of a disc. A finished +// game scores ±(WIN + |diff|·10), so any win beats any non-final position. -const SKILL_PROFILES = { - 1: { depth: 1, blunder: 0.50, noise: 100, delay: [900, 1500] }, - 2: { depth: 2, blunder: 0.30, noise: 60, delay: [800, 1200] }, - 3: { depth: 3, blunder: 0.12, noise: 25, delay: [650, 1050] }, - 4: { depth: 4, blunder: 0.04, noise: 10, delay: [500, 900] }, - 5: { depth: 5, blunder: 0.00, noise: 0, delay: [400, 800] }, +import { + flipsFor, movesFor, isCorner, isEdge, xCorner, cCorner, other, parseSq, BLACK, +} from './OthelloLogic.js'; +import { bookReplies } from './OthelloBook.js'; + +export const WIN = 20000; +const INF = 1e9; +const EMPTY = 0, OUT = 3; + +export const PROFILES = { + 1: { depth: 1, ms: 60, noise: 900, blunder: 0.2, solve: 0, solveMs: 0, book: 0, style: 'greedy' }, + 2: { depth: 2, ms: 150, noise: 380, blunder: 0.06, solve: 4, solveMs: 200, book: 0, style: 'greedy' }, + 3: { depth: 4, ms: 320, noise: 140, blunder: 0, solve: 8, solveMs: 600, book: 0.6, style: 'edgy' }, + 4: { depth: 7, ms: 650, noise: 30, blunder: 0, solve: 12, solveMs: 1500, book: 1, style: 'sound' }, + 5: { depth: 16, ms: 1100, noise: 0, blunder: 0, solve: 16, solveMs: 3500, book: 1, style: 'sound' }, }; -// Classic positional weight table (corners are very valuable). -const W = [ - [120, -20, 20, 5, 5, 20, -20, 120], - [-20, -40, -5, -5, -5, -5, -40, -20], - [ 20, -5, 15, 3, 3, 15, -5, 20], - [ 5, -5, 3, 3, 3, 3, -5, 5], - [ 5, -5, 3, 3, 3, 3, -5, 5], - [ 20, -5, 15, 3, 3, 15, -5, 20], - [-20, -40, -5, -5, -5, -5, -40, -20], - [120, -20, 20, 5, 5, 20, -20, 120], -]; +export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3))); +export const profileFor = (skill) => PROFILES[clampSkill(skill)]; -function profileFor(skill) { - return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; +function rand32(rnd) { return (Math.floor(rnd() * 0x100000000) | 0); } +function seeded(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; } -export function nextThinkDelay(skill) { - const [lo, hi] = profileFor(skill).delay; - return lo + Math.random() * (hi - lo); -} +const TT_BITS = 18, TT_SIZE = 1 << TT_BITS, TT_MASK = TT_SIZE - 1; +const F_EXACT = 1, F_LOWER = 2, F_UPPER = 3; -function evaluate(state, aiColor) { - if (state.phase === 'game_over') { - const w = getWinner(state); - if (w === aiColor) return 100000; - if (w === 'draw') return 0; - return -100000; - } - const human = other(aiColor); - const board = state.board; - - // Positional score - let posScore = 0; - for (let r = 0; r < SIZE; r++) - for (let c = 0; c < SIZE; c++) { - if (board[r][c] === aiColor) posScore += W[r][c]; - else if (board[r][c] === human) posScore -= W[r][c]; +class Searcher { + constructor(size, variant) { + const n = size, P = n + 2; + this.n = n; this.P = P; this.N = n * n; + this.anti = variant === 'anti'; + this.dirs = [-P - 1, -P, -P + 1, -1, 1, P - 1, P, P + 1]; + this.b = new Int8Array(P * P).fill(OUT); + this.cells = new Int16Array(this.N); // sq → padded index + this.sqOf = new Int16Array(P * P).fill(-1); + for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) { + const i = (r + 1) * P + c + 1; + this.cells[r * n + c] = i; this.sqOf[i] = r * n + c; } - - // Mobility: difference in valid move counts - const aiMoves = getValidMoves(state, aiColor).length; - const humanMoves = getValidMoves(state, human).length; - const mobility = aiMoves - humanMoves; - - // Disc count matters more in the endgame - const { black, white } = getScore(state); - const filled = black + white; - const discDiff = (aiColor === 'black' ? black - white : white - black); - const discWeight = filled > 52 ? 3 : 0; - - return posScore * 10 + mobility * 5 + discDiff * discWeight; -} - -function search(state, depth, alpha, beta, aiColor) { - if (state.phase === 'game_over' || depth <= 0) return evaluate(state, aiColor); - - const moves = getValidMoves(state, state.turn); - - if (moves.length === 0) { - // Current player passes; check if game ends or opponent goes. - const passState = cloneState(state); - passState.turn = other(state.turn); - const oppMoves = getValidMoves(passState, passState.turn); - if (oppMoves.length === 0) { - passState.phase = 'game_over'; - passState.winner = (() => { const s = getScore(passState); return s.black > s.white ? 'black' : s.white > s.black ? 'white' : 'draw'; })(); - return evaluate(passState, aiColor); + // flips + per-ply move buffers + this.stack = new Int16Array(16384); this.sp = 0; + this.moveBuf = new Int16Array((this.N + 24) * this.N); + this.scoreBuf = new Int32Array((this.N + 24) * this.N); + // empties set + this.empties = new Int16Array(this.N); this.epos = new Int16Array(P * P); this.ne = 0; + // zobrist + const rnd = seeded(0x0e110 + n); + this.zLo = [null, new Int32Array(P * P), new Int32Array(P * P)]; + this.zHi = [null, new Int32Array(P * P), new Int32Array(P * P)]; + this.zfLo = new Int32Array(P * P); this.zfHi = new Int32Array(P * P); + for (let i = 0; i < P * P; i++) { + for (const v of [1, 2]) { this.zLo[v][i] = rand32(rnd); this.zHi[v][i] = rand32(rnd); } + this.zfLo[i] = this.zLo[1][i] ^ this.zLo[2][i]; this.zfHi[i] = this.zHi[1][i] ^ this.zHi[2][i]; } - return search(passState, depth, alpha, beta, aiColor); + this.sideLo = rand32(rnd); this.sideHi = rand32(rnd); + this.hLo = 0; this.hHi = 0; + // TT + this.ttLo = new Int32Array(TT_SIZE); this.ttHi = new Int32Array(TT_SIZE); + this.ttDepth = new Int8Array(TT_SIZE); this.ttFlag = new Int8Array(TT_SIZE); + this.ttScore = new Int32Array(TT_SIZE); this.ttMove = new Int16Array(TT_SIZE); + // square weights & corner geometry + this.w = new Int16Array(P * P); + this.cornerInfo = []; + const e = n - 1; + for (let sq = 0; sq < this.N; sq++) { + const r = Math.floor(sq / n), c = sq % n, i = this.cells[sq]; + let w; + if (isCorner(sq, n)) w = 0; // scored by the corner term + else if (xCorner(sq, n) >= 0) w = -25; + else if (cCorner(sq, n) >= 0) w = -6; + else if (r === 0 || r === e || c === 0 || c === e) w = (r === 2 || r === e - 2 || c === 2 || c === e - 2) ? 10 : 6; + else if (r === 1 || r === e - 1 || c === 1 || c === e - 1) w = -4; + else w = (r === 2 || r === e - 2 || c === 2 || c === e - 2) ? 3 : 1; + this.w[i] = w; + } + for (const [cr, cc, dr, dc] of [[0, 0, 1, 1], [0, e, 1, -1], [e, 0, -1, 1], [e, e, -1, -1]]) { + const at = (r, c) => this.cells[r * n + c]; + this.cornerInfo.push({ + corner: at(cr, cc), x: at(cr + dr, cc + dc), c1: at(cr + dr, cc), c2: at(cr, cc + dc), + // walking along the two edges away from the corner + stepA: dr * P, stepB: dc, + }); + } + this.abort = false; this.deadline = Infinity; this.nodes = 0; } - if (state.turn === aiColor) { - let value = -Infinity; - for (const m of moves) { - value = Math.max(value, search(applyMove(state, m), depth - 1, alpha, beta, aiColor)); - alpha = Math.max(alpha, value); + load(board, turn) { + this.b.fill(OUT); + this.ne = 0; this.hLo = 0; this.hHi = 0; this.sp = 0; + for (let sq = 0; sq < this.N; sq++) { + const i = this.cells[sq], v = board[sq]; + if (v === null || v === undefined) { + this.b[i] = EMPTY; this.empties[this.ne] = i; this.epos[i] = this.ne++; + } else { + const k = v === BLACK ? 1 : 2; + this.b[i] = k; this.hLo ^= this.zLo[k][i]; this.hHi ^= this.zHi[k][i]; + } + } + const me = turn === BLACK ? 1 : 2; + if (me === 2) { this.hLo ^= this.sideLo; this.hHi ^= this.sideHi; } + return me; + } + + clearTT() { this.ttDepth.fill(-1); this.ttLo.fill(0); this.ttHi.fill(0); } + + legal(i, me) { + const b = this.b, opp = 3 - me; + for (let k = 0; k < 8; k++) { + const d = this.dirs[k]; + let p = i + d; + if (b[p] !== opp) continue; + p += d; + while (b[p] === opp) p += d; + if (b[p] === me) return true; + } + return false; + } + + gen(me, ply) { + const base = ply * this.N; + let n = 0; + for (let k = 0; k < this.ne; k++) { + const i = this.empties[k]; + if (this.legal(i, me)) this.moveBuf[base + n++] = i; + } + return n; + } + + mobility(me) { + let n = 0; + for (let k = 0; k < this.ne; k++) if (this.legal(this.empties[k], me)) n++; + return n; + } + + /** Place for `me` at i; returns flips (0 = illegal, nothing changed). */ + make(i, me) { + const b = this.b, opp = 3 - me, st = this.stack; + let n = 0; + for (let k = 0; k < 8; k++) { + const d = this.dirs[k]; + let p = i + d; + if (b[p] !== opp) continue; + p += d; + while (b[p] === opp) p += d; + if (b[p] !== me) continue; + p -= d; + while (p !== i) { + b[p] = me; st[this.sp++] = p; n++; + this.hLo ^= this.zfLo[p]; this.hHi ^= this.zfHi[p]; + p -= d; + } + } + if (!n) return 0; + st[this.sp++] = n; + b[i] = me; + this.hLo ^= this.zLo[me][i] ^ this.sideLo; this.hHi ^= this.zHi[me][i] ^ this.sideHi; + const at = this.epos[i], last = this.empties[--this.ne]; + this.empties[at] = last; this.epos[last] = at; + return n; + } + + unmake(i, me) { + const b = this.b, opp = 3 - me, st = this.stack; + const n = st[--this.sp]; + for (let k = 0; k < n; k++) { + const p = st[--this.sp]; + b[p] = opp; + this.hLo ^= this.zfLo[p]; this.hHi ^= this.zfHi[p]; + } + b[i] = EMPTY; + this.hLo ^= this.zLo[me][i] ^ this.sideLo; this.hHi ^= this.zHi[me][i] ^ this.sideHi; + this.empties[this.ne] = i; this.epos[i] = this.ne++; + } + + pass() { this.hLo ^= this.sideLo; this.hHi ^= this.sideHi; } + + discDiff(me) { + const b = this.b, opp = 3 - me; + let d = 0; + for (let s = 0; s < this.N; s++) { const v = b[this.cells[s]]; if (v === me) d++; else if (v === opp) d--; } + return d; + } + + terminal(me) { + let d = this.discDiff(me); + if (this.anti) d = -d; + return d > 0 ? WIN + d * 10 : d < 0 ? -WIN + d * 10 : 0; + } + + evaluate(me) { + if (this.ne === 0) return this.terminal(me); + const opp = 3 - me, b = this.b; + const mm = this.mobility(me), om = this.mobility(opp); + if (mm === 0 && om === 0) return this.terminal(me); + const sgn = this.anti ? -1 : 1; + let pos = 0, discs = 0; + for (let s = 0; s < this.N; s++) { + const i = this.cells[s], v = b[i]; + if (v === me) { pos += this.w[i]; discs++; } else if (v === opp) { pos -= this.w[i]; discs--; } + } + let corner = 0, risk = 0, stable = 0; + for (const ci of this.cornerInfo) { + const cv = b[ci.corner]; + if (cv === EMPTY) { + const xv = b[ci.x]; + if (xv === me) risk -= 120; else if (xv === opp) risk += 120; + for (const c of [ci.c1, ci.c2]) { const v = b[c]; if (v === me) risk -= 30; else if (v === opp) risk += 30; } + } else { + corner += cv === me ? 1 : -1; + // edge discs anchored to the corner can never flip + for (const step of [ci.stepA, ci.stepB]) { + let p = ci.corner + step, k = 0; + while (b[p] === cv && k < this.n - 2) { k++; p += step; } + stable += cv === me ? k : -k; + } + } + } + // potential mobility: empty squares next to the other side's discs + let pm = 0; + for (let k = 0; k < this.ne; k++) { + const i = this.empties[k]; + for (let d = 0; d < 8; d++) { const v = b[i + this.dirs[d]]; if (v === opp) pm++; else if (v === me) pm--; } + } + const fill = 1 - this.ne / this.N; + const late = fill > 0.75; + let score = sgn * (pos * 4 + corner * 360 + risk + stable * 70); + score += (mm - om) * (late ? 30 : 48) + pm * 5; + if (late) score += sgn * discs * 22; + else if (fill < 0.4) score -= sgn * discs * 4; + if (fill > 0.7) score += (this.ne & 1) ? 35 : -35; + if (mm === 0) score -= 120; + if (om === 0) score += 120; + return score; + } + + probe() { + const k = this.hLo & TT_MASK; + if (this.ttDepth[k] >= 0 && this.ttLo[k] === this.hLo && this.ttHi[k] === this.hHi) return k; + return -1; + } + + store(depth, flag, score, move) { + const k = this.hLo & TT_MASK; + if (this.ttDepth[k] > depth && this.ttLo[k] === this.hLo && this.ttHi[k] === this.hHi && this.ttFlag[k] === F_EXACT) return; + this.ttLo[k] = this.hLo; this.ttHi[k] = this.hHi; this.ttDepth[k] = Math.min(127, depth); + this.ttFlag[k] = flag; this.ttScore[k] = score; this.ttMove[k] = move; + } + + order(me, ply, n, depth, ttMove) { + const base = ply * this.N, mv = this.moveBuf, sc = this.scoreBuf, opp = 3 - me; + for (let j = 0; j < n; j++) { + const i = mv[base + j]; + let s; + if (i === ttMove) s = 1e7; + else if (depth >= 3) { + this.make(i, me); + s = -this.mobility(opp) * 100 + this.w[i] * 3; + this.unmake(i, me); + } else s = this.w[i]; + if (this.isCornerIdx(i)) s += this.anti ? -500 : 500; + sc[base + j] = s; + } + // insertion sort, best first + for (let a = 1; a < n; a++) { + const m = mv[base + a], s = sc[base + a]; + let c = a - 1; + while (c >= 0 && sc[base + c] < s) { mv[base + c + 1] = mv[base + c]; sc[base + c + 1] = sc[base + c]; c--; } + mv[base + c + 1] = m; sc[base + c + 1] = s; + } + } + + isCornerIdx(i) { for (const ci of this.cornerInfo) if (ci.corner === i) return true; return false; } + + tick() { + if ((++this.nodes & 2047) === 0 && Date.now() > this.deadline) this.abort = true; + return this.abort; + } + + search(me, depth, alpha, beta, passed, ply) { + if (this.tick()) return 0; + if (depth <= 0 || this.ne === 0) return this.evaluate(me); + const a0 = alpha; + let ttMove = -1; + const t = this.probe(); + if (t >= 0) { + ttMove = this.ttMove[t]; + if (this.ttDepth[t] >= depth) { + const s = this.ttScore[t], f = this.ttFlag[t]; + if (f === F_EXACT) return s; + if (f === F_LOWER && s > alpha) alpha = s; + else if (f === F_UPPER && s < beta) beta = s; + if (alpha >= beta) return s; + } + } + const n = this.gen(me, ply); + if (n === 0) { + if (passed) return this.terminal(me); + this.pass(); + const v = -this.search(3 - me, depth, -beta, -alpha, true, ply + 1); + this.pass(); + return v; + } + if (n > 1) this.order(me, ply, n, depth, ttMove); + const base = ply * this.N; + let best = -INF, bestMove = -1; + for (let j = 0; j < n; j++) { + const i = this.moveBuf[base + j]; + this.make(i, me); + let v; + if (j === 0) v = -this.search(3 - me, depth - 1, -beta, -alpha, false, ply + 1); + else { + v = -this.search(3 - me, depth - 1, -alpha - 1, -alpha, false, ply + 1); + if (v > alpha && v < beta && !this.abort) v = -this.search(3 - me, depth - 1, -beta, -alpha, false, ply + 1); + } + this.unmake(i, me); + if (this.abort) return 0; + if (v > best) { best = v; bestMove = i; } + if (v > alpha) alpha = v; if (alpha >= beta) break; } - return value; + this.store(depth, best <= a0 ? F_UPPER : best >= beta ? F_LOWER : F_EXACT, best, bestMove); + return best; } - let value = Infinity; - for (const m of moves) { - value = Math.min(value, search(applyMove(state, m), depth - 1, alpha, beta, aiColor)); - beta = Math.min(beta, value); - if (beta <= alpha) break; + + /** Full-window score of every root move at `depth` (all-moves search). */ + rankAt(me, depth) { + const n = this.gen(me, 0); + const out = []; + for (let j = 0; j < n; j++) { + const i = this.moveBuf[j]; + this.make(i, me); + const v = -this.search(3 - me, depth - 1, -INF, INF, false, 1); + this.unmake(i, me); + if (this.abort) return null; + out.push({ i, score: v }); + } + out.sort((a, b) => b.score - a.score); + return out; + } + + /** Iterative-deepening alpha-beta at the root. */ + think(me, { ms, maxDepth, exact = false }) { + this.abort = false; this.nodes = 0; this.deadline = Date.now() + ms; + let rootMoves = []; + { + const n = this.gen(me, 0); + for (let j = 0; j < n; j++) rootMoves.push({ i: this.moveBuf[j], score: 0 }); + } + if (!rootMoves.length) return null; + let result = { i: rootMoves[0].i, score: 0, depth: 0 }; + for (let d = 1; d <= maxDepth; d++) { + let alpha = -INF, best = null; + const scored = []; + for (let j = 0; j < rootMoves.length; j++) { + const m = rootMoves[j]; + this.make(m.i, me); + let v; + if (j === 0) v = -this.search(3 - me, d - 1, -INF, -alpha, false, 1); + else { + v = -this.search(3 - me, d - 1, -alpha - 1, -alpha, false, 1); + if (v > alpha && !this.abort) v = -this.search(3 - me, d - 1, -INF, -alpha, false, 1); + } + this.unmake(m.i, me); + if (this.abort) break; + scored.push({ i: m.i, score: v }); + if (v > alpha) { alpha = v; best = { i: m.i, score: v, depth: d }; } + } + if (this.abort) { + // a first move that already beat the last iteration's choice is safe to keep + // (rootMoves[0] is last iteration's choice; anything in `best` beat it at this depth) + if (best && best.i !== result.i) result = best; + break; + } + result = best; + // re-order: best first, then by this iteration's scores (fail-low bounds) + const seen = new Map(scored.map((s) => [s.i, s.score])); + rootMoves = rootMoves.map((m) => ({ i: m.i, score: m.i === best.i ? INF : (seen.get(m.i) ?? -INF) })) + .sort((a, b) => b.score - a.score); + if (!exact && Math.abs(best.score) >= WIN) break; // a forced result: deeper won't change it + if (d >= this.ne) break; // reached the end of the game + } + return result; + } + + /** Exact solve; null if it ran out of time. */ + solve(me, ms) { + this.abort = false; this.nodes = 0; this.deadline = Date.now() + ms; + const r = this.think(me, { ms, maxDepth: this.ne, exact: true }); + if (!r || this.abort || r.depth < this.ne) { this.abort = false; return null; } + return r; + } + + /** Every move scored, deepening until the time runs out. */ + rankAll(me, { depth, ms }) { + this.abort = false; this.nodes = 0; this.deadline = Date.now() + ms; + let last = null; + for (let d = 1; d <= depth; d++) { + const r = this.rankAt(me, d); + if (!r) break; + last = r; + if (d >= this.ne) break; + } + this.abort = false; + return last ?? (() => { + // not even depth 1 finished (shouldn't happen): fall back to static order + const n = this.gen(me, 0); const out = []; + for (let j = 0; j < n; j++) out.push({ i: this.moveBuf[j], score: this.w[this.moveBuf[j]] }); + return out.sort((a, b) => b.score - a.score); + })(); } - return value; } -export function chooseMove(state, aiColor, skill) { +const searchers = new Map(); +function searcherFor(size, variant) { + const key = `${size}|${variant}`; + if (!searchers.has(key)) searchers.set(key, new Searcher(size, variant)); + return searchers.get(key); +} + +function setup(pos) { + const s = searcherFor(pos.size, pos.variant ?? 'standard'); + const me = s.load(pos.board, pos.turn); + s.clearTT(); + return { s, me }; +} + +/** Best move with exact solving near the end. */ +function deepBest(s, me, { ms, maxDepth, solve, solveMs }) { + if (solve && s.ne <= solve) { + const r = s.solve(me, solveMs); + if (r) return { i: r.i, score: r.score, exact: true, depth: r.depth }; + s.clearTT(); + } + const r = s.think(me, { ms, maxDepth }); + return r ? { i: r.i, score: r.score, exact: false, depth: r.depth } : null; +} + +export function rankMoves(pos, { depth = 4, ms = 300 } = {}) { + const { s, me } = setup(pos); + return s.rankAll(me, { depth, ms }).map((r) => ({ sq: s.sqOf[r.i], score: r.score })); +} + +export function hint(pos, { ms = 700, solve = 14, solveMs = 2200 } = {}) { + const { s, me } = setup(pos); + const r = deepBest(s, me, { ms, maxDepth: 30, solve, solveMs }); + return r ? { sq: s.sqOf[r.i], score: r.score, exact: r.exact, depth: r.depth } : null; +} + +export function chooseMove(pos, skill, { line = null, rnd = Math.random } = {}) { const prof = profileFor(skill); - const moves = getValidMoves(state, aiColor); - if (moves.length === 0) return null; - if (moves.length === 1) return moves[0]; - - if (Math.random() < prof.blunder) return moves[Math.floor(Math.random() * moves.length)]; - - let best = null, bestScore = -Infinity; - for (const m of moves) { - const ns = applyMove(state, m); - let val = search(ns, prof.depth - 1, -Infinity, Infinity, aiColor); - val += (Math.random() * 2 - 1) * prof.noise; - if (val > bestScore) { bestScore = val; best = m; } + const legal = movesFor(pos.board, pos.size, pos.turn); + if (!legal.length) return null; + if (legal.length === 1) return { sq: legal[0].sq, score: 0, book: false, exact: false }; + // book + if (line && pos.size === 8 && (pos.variant ?? 'standard') === 'standard' && rnd() < prof.book) { + const replies = bookReplies(line).map((n) => parseSq(n, 8)).filter((sq) => legal.some((m) => m.sq === sq)); + if (replies.length) return { sq: replies[Math.floor(rnd() * replies.length)], score: 0, book: true, exact: false }; } - return best ?? moves[0]; + const { s, me } = setup(pos); + // perfect endgame + if (prof.solve && s.ne <= prof.solve) { + const r = s.solve(me, prof.solveMs); + if (r) return { sq: s.sqOf[r.i], score: r.score, book: false, exact: true }; + s.clearTT(); + } + if (prof.blunder && rnd() < prof.blunder) { + const m = legal[Math.floor(rnd() * legal.length)]; + return { sq: m.sq, score: 0, book: false, exact: false }; + } + if (!prof.noise && prof.style === 'sound') { + const r = s.think(me, { ms: prof.ms, maxDepth: prof.depth }); + return { sq: s.sqOf[r.i], score: r.score, book: false, exact: false }; + } + const ranked = s.rankAll(me, { depth: prof.depth, ms: prof.ms }); + let best = null, bestV = -INF; + for (const r of ranked) { + const sq = s.sqOf[r.i]; + let v = r.score + (rnd() * 2 - 1) * prof.noise; + if (prof.style === 'greedy') v += flipsFor(pos.board, pos.size, sq, pos.turn).length * 40; + else if (prof.style === 'edgy' && isEdge(sq, pos.size) && cCorner(sq, pos.size) < 0) v += 70; + if (Math.abs(r.score) >= WIN) v = r.score; // never throw away a forced result + if (v > bestV) { bestV = v; best = { sq, score: r.score }; } + } + return { ...best, book: false, exact: false }; +} + +/** + * Post-game review. positions: [{ i, board, turn, played }] (the human's + * decisions). Returns each with the best move and the loss in hundredths of + * a disc (0 when the move played was best). + */ +export function review(positions, { ms = 140, depth = 6, size, variant } = {}) { + const out = []; + for (const p of positions) { + const pos = { size, variant, board: p.board, turn: p.turn }; + const legal = movesFor(p.board, size, p.turn); + if (legal.length < 2) continue; + const { s, me } = setup(pos); + let ranked = null, exact = false; + if (s.ne <= 12) { + s.abort = false; s.nodes = 0; s.deadline = Date.now() + ms * 4; + const r = s.rankAt(me, s.ne); + s.abort = false; + if (r) { ranked = r; exact = true; } + } + if (!ranked) ranked = s.rankAll(me, { depth, ms }); + const best = ranked[0]; + const mine = ranked.find((r) => s.sqOf[r.i] === p.played); + if (!best || !mine) continue; + out.push({ i: p.i, best: s.sqOf[best.i], played: p.played, loss: best.score - mine.score, bestScore: best.score, playedScore: mine.score, exact }); + } + return out; +} + +// ── words for the Master ─────────────────────────────────────────────────── + +function after(pos, sq) { + const b = pos.board.slice(); + const f = flipsFor(b, pos.size, sq, pos.turn); + b[sq] = pos.turn; + for (const x of f) b[x] = pos.turn; + return { board: b, flips: f }; +} + +function cornersOpenTo(board, size, color) { + return movesFor(board, size, color).filter((m) => isCorner(m.sq, size)).length; +} + +export function exactMargin(score) { + if (score >= WIN) return Math.round((score - WIN) / 10); + if (score <= -WIN) return Math.round((score + WIN) / 10); + return 0; +} + +/** A short verb phrase for why sq is good ("takes a corner"). */ +export function describeIdea(pos, sq, res = {}) { + const anti = pos.variant === 'anti'; + const opp = other(pos.turn); + if (res.exact) { + const m = exactMargin(res.score); + if (res.score >= WIN) return `wins by ${m} disc${m === 1 ? '' : 's'} with perfect play from here`; + if (res.score === 0) return 'holds a draw with perfect play'; + return `keeps the loss to ${-m} disc${m === -1 ? '' : 's'}, the best that's left`; + } + const { board, flips } = after(pos, sq); + const theirMoves = movesFor(board, pos.size, opp); + const om = theirMoves.length; + if (!anti && isCorner(sq, pos.size)) return 'takes a corner, and a corner can never be flipped back'; + if (om === 0) return 'leaves them no move at all, so they have to pass'; + const before = cornersOpenTo(pos.board, pos.size, opp); + const nowOpen = theirMoves.filter((m) => isCorner(m.sq, pos.size)).length; + if (!anti && before > 0 && nowOpen === 0) return 'takes away the corner they were threatening'; + if (om <= 3) return `leaves them only ${om} move${om === 1 ? '' : 's'}`; + if (anti) { + if (flips.length <= 2) return `turns over just ${flips.length} disc${flips.length === 1 ? '' : 's'}, which keeps your count low`; + return 'keeps you off the corners and edges for now'; + } + if (flips.length <= 2 && !isEdge(sq, pos.size)) return `is a quiet move: it flips only ${flips.length} disc${flips.length === 1 ? '' : 's'} and opens nothing up for them`; + if (isEdge(sq, pos.size) && cCorner(sq, pos.size) < 0) return 'takes a safe edge square'; + return `keeps your options open and limits theirs to ${om}`; +} + +/** What was wrong with `played` compared with `best` (past tense). */ +export function describeMistake(pos, played, best) { + const opp = other(pos.turn); + const anti = pos.variant === 'anti'; + const a = after(pos, played).board, b = after(pos, best).board; + if (!anti) { + const ca = cornersOpenTo(a, pos.size, opp), cb = cornersOpenTo(b, pos.size, opp); + if (ca > cb) return 'it gave them a corner'; + const xc = xCorner(played, pos.size); + if (xc >= 0 && pos.board[xc] === null) return 'it took an X-square next to an empty corner'; + } else if (isCorner(played, pos.size)) return 'it took a corner, and in Anti-Othello that disc is yours forever'; + const ma = movesFor(a, pos.size, opp).length, mb = movesFor(b, pos.size, opp).length; + if (ma - mb >= 3) return `it gave them ${ma} replies instead of ${mb}`; + const fa = flipsFor(pos.board, pos.size, played, pos.turn).length, fb = flipsFor(pos.board, pos.size, best, pos.turn).length; + if (!anti && fa - fb >= 4) return `it grabbed ${fa} discs, and big flips open doors for the other side`; + return 'it let them take the initiative'; +} + +/** Does playing sq let the opponent into a corner they couldn't reach before? */ +export function givesCorner(pos, sq) { + if (pos.variant === 'anti') return false; + const opp = other(pos.turn); + const before = cornersOpenTo(pos.board, pos.size, opp); + const nowOpen = cornersOpenTo(after(pos, sq).board, pos.size, opp); + return nowOpen > before; +} + + +// ── for tools/verifyOthello.js ───────────────────────────────────────────── + +/** Perft on the engine's own make/unmake (a pass counts as a move). */ +export function perft(pos, depth) { + const { s, me } = setup(pos); + const walk = (side, d, passed, ply) => { + if (d === 0) return 1; + const n = s.gen(side, ply); + if (n === 0) { + if (passed) return 1; + s.pass(); + const v = walk(3 - side, d - 1, true, ply + 1); + s.pass(); + return v; + } + let total = 0; + const base = ply * s.N; + for (let j = 0; j < n; j++) { + const i = s.moveBuf[base + j]; + s.make(i, side); + total += walk(3 - side, d - 1, false, ply + 1); + s.unmake(i, side); + } + return total; + }; + return walk(me, depth, false, 0); +} + +/** The engine's view of a position: legal squares, and the board after each. */ +export function engineView(pos) { + const { s, me } = setup(pos); + const n = s.gen(me, 0); + const out = []; + const lo = s.hLo, hi = s.hHi; + for (let j = 0; j < n; j++) { + const i = s.moveBuf[j]; + s.make(i, me); + const board = []; + for (let q = 0; q < s.N; q++) { const v = s.b[s.cells[q]]; board.push(v === 1 ? 'black' : v === 2 ? 'white' : null); } + s.unmake(i, me); + out.push({ sq: s.sqOf[i], board }); + } + return { moves: out.sort((a, b) => a.sq - b.sq), hashRestored: s.hLo === lo && s.hHi === hi }; +} + +/** Exact solve score (null on timeout). */ +export function solveExact(pos, ms = 5000) { + const { s, me } = setup(pos); + if (!s.gen(me, 0)) return null; + const r = s.solve(me, ms); + return r ? { sq: s.sqOf[r.i], score: r.score } : null; } diff --git a/src/games/othello/OthelloArt.js b/src/games/othello/OthelloArt.js new file mode 100644 index 0000000..a79a3e3 --- /dev/null +++ b/src/games/othello/OthelloArt.js @@ -0,0 +1,705 @@ +// OthelloArt.js: baked canvas textures for Kissa Kuro-Shiro, a narrow +// jazz coffee house on a rainy Tokyo night. All procedural: no image files. +// +// ot-room the whole room: cedar panelling, a shelf of LPs along the +// top, the rain-streaked window on a neon street (paper +// lanterns, wet reflections, gold-leaf lettering), the +// menu card, the low lacquered table under the board, the +// counter (record player, coffee siphon, cup), lamp pool +// ot-props table + counter alone (over a chosen playfield) +// ot-vignette lamp pool + vignette alone (over a chosen playfield) +// ot-board- green felt in a black-lacquer frame, gold coordinates +// ot-disc-black, ot-disc-white disc tops (2× bake), the other colour's +// rim showing underneath +// ot-edge a disc seen edge-on (half white, half black), for flips +// ot-shadow, ot-sheen, ot-glow, ot-ring, ot-spark, ot-steam, ot-rain, +// ot-dot, ot-bubble, ot-flame, ot-record, ot-record-sheen, ot-neon-glow, +// ot-slice (a disc standing in the tray), ot-tray, ot-plate, +// ot-plate-glow, ot-card-status, ot-card-log, ot-ribbon, ot-bar + +import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { + W, H, BX, BY, BOARD, FRAME, BOARD_TEX, BCX, BCY, DISC_R, PLATE, STATUS, LOG, RIBBON, + WINDOW, SIGN, NEON, COUNTER, PLATTER, SIPHON, CUP, TRAYS, BAR, +} from './OthelloLayout.js'; + +export const DISPLAY_FONT = '"Julius Sans One", Georgia, serif'; +export const SERIF = 'Georgia, "Times New Roman", serif'; +export const BOLD_FONT = 'Righteous, Georgia, serif'; +export const RES = 2; +export const DISC_TEX = (DISC_R + 12) * 2 * RES; +export const EDGE_TEX = { w: (DISC_R * 2 + 4) * RES, h: 16 * RES }; + +export const INK = { + black: { hex: 0x1c1b22, text: '#1c1b22', light: '#9a98aa', css: '#1c1b22' }, + white: { hex: 0xf2eee2, text: '#6a6252', light: '#f6f2e6', css: '#f2eee2' }, +}; +export const GOLD = 0xd8b060; +export const VERMILION = 0xb8321e; +export const CREAM = '#f3ead2'; + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); +} + +function seeded(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function grain(ctx, rnd, x, y, w, h, { tone = 'rgba(20,8,2,0.35)', lines = 30, wave = 5, vertical = false } = {}) { + ctx.save(); + ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); + ctx.strokeStyle = tone; + const L = vertical ? h : w, S = vertical ? w : h; + for (let i = 0; i < lines; i++) { + const o = rnd() * S, amp = wave * (0.4 + rnd()), f = 0.003 + rnd() * 0.01, ph = rnd() * 6; + ctx.lineWidth = 0.6 + rnd() * 1.6; + ctx.beginPath(); + for (let t = 0; t <= L; t += 8) { + const d = o + Math.sin(t * f + ph) * amp + Math.sin(t * f * 3.3 + ph) * amp * 0.3; + const px = vertical ? x + d : x + t, py = vertical ? y + t : y + d; + if (t === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + ctx.stroke(); + } + ctx.restore(); +} + +function shadowed(ctx, fn, { blur = 24, dx = 8, dy = 14, alpha = 0.55 } = {}) { + ctx.save(); + ctx.shadowColor = `rgba(0,0,0,${alpha})`; + ctx.shadowBlur = blur; ctx.shadowOffsetX = dx; ctx.shadowOffsetY = dy; + fn(); + ctx.restore(); +} + +function goldGrad(ctx, x0, y0, x1, y1) { + const g = ctx.createLinearGradient(x0, y0, x1, y1); + g.addColorStop(0, '#f6dc9a'); g.addColorStop(0.4, '#b98a34'); g.addColorStop(0.65, '#ecc878'); g.addColorStop(1, '#7a5418'); + return g; +} + +function lacquer(ctx, x0, y0, x1, y1) { + const g = ctx.createLinearGradient(x0, y0, x1, y1); + g.addColorStop(0, '#2a1c16'); g.addColorStop(0.45, '#120c0a'); g.addColorStop(0.55, '#1c1210'); g.addColorStop(1, '#0a0606'); + return g; +} + +// ── room ───────────────────────────────────────────────────────────────────── +const RAIL_Y = 776; + +function walls(ctx, rnd) { + // cedar planks, dark with age and coffee smoke + const g = ctx.createLinearGradient(0, 0, 0, H); + g.addColorStop(0, '#24160e'); g.addColorStop(0.6, '#2e1c10'); g.addColorStop(1, '#1a0f08'); + ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); + for (let x = 0; x < W; x += 64) { + const t = rnd() * 0.12; + ctx.fillStyle = `rgba(${60 + t * 200},${36 + t * 100},${18},0.35)`; ctx.fillRect(x, 0, 64, RAIL_Y); + ctx.fillStyle = 'rgba(0,0,0,0.45)'; ctx.fillRect(x, 0, 2, RAIL_Y); + ctx.fillStyle = 'rgba(255,200,140,0.05)'; ctx.fillRect(x + 2, 0, 1, RAIL_Y); + } + grain(ctx, rnd, 0, 0, W, RAIL_Y, { tone: 'rgba(10,4,0,0.28)', lines: 120, wave: 3, vertical: true }); + // lower wall: woven reed panels between posts + const lg = ctx.createLinearGradient(0, RAIL_Y, 0, H); + lg.addColorStop(0, '#3a2a18'); lg.addColorStop(1, '#22180c'); + ctx.fillStyle = lg; ctx.fillRect(0, RAIL_Y, W, H - RAIL_Y); + for (let y = RAIL_Y + 6; y < H; y += 7) { + ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke(); + } + for (let x = 0; x < W; x += 180) { + ctx.fillStyle = '#1a0e06'; ctx.fillRect(x, RAIL_Y, 14, H - RAIL_Y); + ctx.fillStyle = 'rgba(255,200,140,0.08)'; ctx.fillRect(x + 2, RAIL_Y, 2, H - RAIL_Y); + } + const rail = ctx.createLinearGradient(0, RAIL_Y - 12, 0, RAIL_Y + 12); + rail.addColorStop(0, '#5a3a20'); rail.addColorStop(1, '#24140a'); + ctx.fillStyle = rail; ctx.fillRect(0, RAIL_Y - 10, W, 20); + ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(0, 0, W, H); +} + +function lpShelf(ctx, rnd) { + // a long shelf of records along the top of the wall + const top = 0, bottom = 96; + ctx.fillStyle = '#120a06'; ctx.fillRect(0, top, W, bottom); + const palette = ['#c84a2a', '#e8c070', '#2a4a7a', '#1a1a1a', '#d8d0b8', '#6a2a4a', '#2a6a5a', '#b88a3a', '#3a3a5a', '#8a1a1a', '#e0e0d8', '#4a6a2a']; + let x = 0; + while (x < W) { + const w = 5 + Math.floor(rnd() * 5); + const col = palette[Math.floor(rnd() * palette.length)]; + const h = bottom - 8 - rnd() * 6; + ctx.fillStyle = col; ctx.fillRect(x, bottom - h - 4, w, h); + ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(x + w - 1, bottom - h - 4, 1, h); + ctx.fillStyle = 'rgba(255,255,255,0.10)'; ctx.fillRect(x, bottom - h - 4, 1, h); + if (rnd() < 0.3) { ctx.fillStyle = 'rgba(255,255,255,0.35)'; ctx.fillRect(x + 1, bottom - h + 8 + rnd() * 30, w - 2, 2); } + x += w; + if (rnd() < 0.03) x += 30; // a gap where a record's out on the player + } + // shelf plank + const pl = ctx.createLinearGradient(0, bottom - 6, 0, bottom + 12); + pl.addColorStop(0, '#6a4426'); pl.addColorStop(1, '#2a180c'); + shadowed(ctx, () => { ctx.fillStyle = pl; ctx.fillRect(0, bottom - 4, W, 14); }, { blur: 14, dx: 0, dy: 8, alpha: 0.7 }); + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + const sh = ctx.createLinearGradient(0, 0, 0, bottom); + sh.addColorStop(0, 'rgba(0,0,0,0.65)'); sh.addColorStop(1, 'rgba(0,0,0,0.15)'); + ctx.fillStyle = sh; ctx.fillRect(0, 0, W, bottom); +} + +function lantern(ctx, x, y, s) { + // a red paper lantern hanging from the eaves outside + ctx.save(); + ctx.strokeStyle = 'rgba(20,10,10,0.9)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(x, y - 40 * s); ctx.lineTo(x, y - 22 * s); ctx.stroke(); + const glow = ctx.createRadialGradient(x, y, 2, x, y, 60 * s); + glow.addColorStop(0, 'rgba(255,120,70,0.55)'); glow.addColorStop(1, 'rgba(255,90,50,0)'); + ctx.fillStyle = glow; ctx.fillRect(x - 60 * s, y - 60 * s, 120 * s, 120 * s); + const body = ctx.createRadialGradient(x - 6 * s, y - 6 * s, 2, x, y, 24 * s); + body.addColorStop(0, '#ffb070'); body.addColorStop(0.5, '#e0442a'); body.addColorStop(1, '#801a12'); + ctx.fillStyle = body; + ctx.beginPath(); ctx.ellipse(x, y, 18 * s, 24 * s, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(80,10,6,0.5)'; ctx.lineWidth = 1; + for (let k = -3; k <= 3; k++) { ctx.beginPath(); ctx.ellipse(x, y + k * 6 * s, 18 * s * Math.cos(k * 0.38), 1.5 * s, 0, 0, Math.PI * 2); ctx.stroke(); } + ctx.fillStyle = '#1a0c08'; ctx.fillRect(x - 9 * s, y - 26 * s, 18 * s, 4 * s); ctx.fillRect(x - 9 * s, y + 22 * s, 18 * s, 4 * s); + ctx.restore(); +} + +function neonSign(ctx, x, y, w, h, col, rnd) { + // a vertical shop sign: a lit box with abstract strokes for lettering + ctx.save(); + ctx.shadowColor = col; ctx.shadowBlur = 16; + ctx.fillStyle = 'rgba(10,8,14,0.9)'; ctx.fillRect(x, y, w, h); + ctx.strokeStyle = col; ctx.lineWidth = 2.2; ctx.strokeRect(x + 2, y + 2, w - 4, h - 4); + ctx.lineWidth = 2.6; + for (let gy = y + 10; gy < y + h - 14; gy += w * 0.9) { + ctx.beginPath(); + const cx = x + w / 2, s = w * 0.3; + ctx.moveTo(cx - s, gy + rnd() * 4); ctx.lineTo(cx + s, gy + rnd() * 4); + ctx.moveTo(cx + (rnd() - 0.5) * s, gy); ctx.lineTo(cx + (rnd() - 0.5) * s, gy + s * 1.6); + if (rnd() < 0.6) { ctx.moveTo(cx - s, gy + s * 1.2); ctx.lineTo(cx + s * 0.8, gy + s * 1.4); } + ctx.stroke(); + } + ctx.restore(); +} + +function windowView(ctx, rnd) { + const { x, y, w, h } = WINDOW; + ctx.save(); + rr(ctx, x, y, w, h, 3); ctx.clip(); + const sky = ctx.createLinearGradient(0, y, 0, y + h); + sky.addColorStop(0, '#120c22'); sky.addColorStop(0.5, '#1e1430'); sky.addColorStop(1, '#0a0810'); + ctx.fillStyle = sky; ctx.fillRect(x, y, w, h); + // buildings across the narrow lane + let bx = x - 10; + while (bx < x + w) { + const bw = 46 + rnd() * 60, bh = 120 + rnd() * 120; + ctx.fillStyle = '#08060c'; ctx.fillRect(bx, y + h * 0.66 - bh, bw, bh); + for (let wy = y + h * 0.66 - bh + 8; wy < y + h * 0.66 - 10; wy += 15) { + for (let wx = bx + 5; wx < bx + bw - 7; wx += 12) { + if (rnd() < 0.16) { ctx.fillStyle = rnd() < 0.5 ? 'rgba(255,220,160,0.7)' : 'rgba(180,210,255,0.45)'; ctx.fillRect(wx, wy, 5, 7); } + } + } + bx += bw + 3; + } + // overhead wires + ctx.strokeStyle = 'rgba(0,0,0,0.8)'; ctx.lineWidth = 1.2; + for (let i = 0; i < 3; i++) { + ctx.beginPath(); ctx.moveTo(x, y + 30 + i * 16); ctx.quadraticCurveTo(x + w / 2, y + 60 + i * 20, x + w, y + 24 + i * 14); ctx.stroke(); + } + // vertical neon signs + neonSign(ctx, NEON.x - 16, NEON.y - 30, 32, 150, 'rgba(255,90,150,0.95)', rnd); + neonSign(ctx, x + w - 92, y + 40, 30, 120, 'rgba(90,220,255,0.9)', rnd); + neonSign(ctx, x + w - 150, y + 96, 26, 90, 'rgba(255,200,80,0.9)', rnd); + // lanterns under the eaves + lantern(ctx, x + 60, y + 58, 0.8); + lantern(ctx, x + 230, y + 66, 0.7); + // wet lane and reflections + const st = ctx.createLinearGradient(0, y + h * 0.66, 0, y + h); + st.addColorStop(0, '#120e18'); st.addColorStop(1, '#05040a'); + ctx.fillStyle = st; ctx.fillRect(x, y + h * 0.66, w, h * 0.34); + for (let i = 0; i < 40; i++) { + const rx = x + rnd() * w, ry = y + h * 0.68 + rnd() * h * 0.3; + const c = ['rgba(255,90,150,0.22)', 'rgba(90,220,255,0.2)', 'rgba(255,200,80,0.2)', 'rgba(255,120,70,0.2)'][Math.floor(rnd() * 4)]; + ctx.fillStyle = c; ctx.fillRect(rx, ry, 1.5 + rnd() * 2.5, 6 + rnd() * 20); + } + // beaded rain on the glass + for (let i = 0; i < 160; i++) { + const dx = x + rnd() * w, dy = y + rnd() * h, r = 0.8 + rnd() * 2.6; + ctx.fillStyle = 'rgba(200,210,255,0.2)'; ctx.beginPath(); ctx.arc(dx, dy, r, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = 'rgba(255,255,255,0.32)'; ctx.beginPath(); ctx.arc(dx - r * 0.3, dy - r * 0.3, r * 0.35, 0, Math.PI * 2); ctx.fill(); + } + // gold-leaf lettering on the glass, read from inside (mirrored) + ctx.save(); + ctx.translate(x + w / 2, y + h - 54); ctx.scale(-1, 1); + ctx.font = `bold 28px ${DISPLAY_FONT}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(0,0,0,0.55)'; ctx.fillText('KURO-SHIRO', 2, 2); + ctx.fillStyle = goldGrad(ctx, -120, -14, 120, 14); ctx.fillText('KURO-SHIRO', 0, 0); + ctx.font = `italic 15px ${SERIF}`; ctx.fillStyle = 'rgba(230,200,130,0.85)'; + ctx.fillText('jazz kissa · since 1971', 0, 28); + ctx.restore(); + ctx.restore(); + // dark wood sash with a lattice transom + shadowed(ctx, () => { + ctx.strokeStyle = '#2a1a0e'; ctx.lineWidth = 18; rr(ctx, x - 9, y - 9, w + 18, h + 18, 4); ctx.stroke(); + }, { blur: 14, dx: 4, dy: 8, alpha: 0.6 }); + ctx.strokeStyle = '#4a3020'; ctx.lineWidth = 2; rr(ctx, x - 1, y - 1, w + 2, h + 2, 3); ctx.stroke(); + ctx.fillStyle = '#2a1a0e'; + ctx.fillRect(x, y + h * 0.3 - 4, w, 8); + ctx.fillRect(x + w / 2 - 4, y, 8, h * 0.3); + for (let i = 1; i < 6; i++) ctx.fillRect(x + (w / 6) * i - 1.5, y, 3, h * 0.3); + // sill + ctx.fillStyle = '#4a3020'; ctx.fillRect(x - 22, y + h + 9, w + 44, 12); + ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.fillRect(x - 22, y + h + 21, w + 44, 6); +} + +function menuCard(ctx) { + const cx = SIGN.x, cy = SIGN.y; + ctx.save(); + ctx.translate(cx, cy); ctx.rotate(0.01); + shadowed(ctx, () => { ctx.fillStyle = '#efe6cc'; ctx.fillRect(-180, -13, 360, 26); }, { blur: 6, dx: 2, dy: 3, alpha: 0.5 }); + ctx.fillStyle = '#b8321e'; ctx.fillRect(-180, -13, 360, 3); + ctx.fillStyle = '#1a1a1a'; ctx.fillRect(-180, 10, 360, 3); + ctx.font = `bold 13px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillStyle = '#2a1a10'; + ctx.fillText('BLEND ¥350 · SIPHON ¥450 · THE BOARD IS FREE', 0, 1); + ctx.restore(); +} + +function lowTable(ctx, rnd) { + // a big round table in dark lacquered keyaki; the board sits in the middle + const R = 520, cx = BCX, cy = BCY + 14; + shadowed(ctx, () => { ctx.fillStyle = '#1a0e08'; ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); }, { blur: 40, dx: 0, dy: 22, alpha: 0.75 }); + ctx.save(); + ctx.beginPath(); ctx.arc(cx, cy, R - 6, 0, Math.PI * 2); ctx.clip(); + const g = ctx.createRadialGradient(cx - 120, cy - 160, 40, cx, cy, R); + g.addColorStop(0, '#5a3a22'); g.addColorStop(0.6, '#3a2212'); g.addColorStop(1, '#1e1008'); + ctx.fillStyle = g; ctx.fillRect(cx - R, cy - R, R * 2, R * 2); + grain(ctx, rnd, cx - R, cy - R, R * 2, R * 2, { tone: 'rgba(15,6,0,0.35)', lines: 90, wave: 6 }); + // a lacquer gleam + const sh = ctx.createLinearGradient(cx - R, cy - R, cx + R, cy + R); + sh.addColorStop(0, 'rgba(255,230,190,0.10)'); sh.addColorStop(0.3, 'rgba(255,230,190,0)'); sh.addColorStop(0.75, 'rgba(255,230,190,0.04)'); sh.addColorStop(1, 'rgba(0,0,0,0.2)'); + ctx.fillStyle = sh; ctx.fillRect(cx - R, cy - R, R * 2, R * 2); + // a cup ring and a sugar cube someone left + ctx.strokeStyle = 'rgba(20,8,0,0.35)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.arc(cx - 410, cy + 260, 34, 0.2, Math.PI * 1.8); ctx.stroke(); + ctx.restore(); + ctx.strokeStyle = 'rgba(255,210,150,0.18)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(cx, cy, R - 7, Math.PI * 1.05, Math.PI * 1.65); ctx.stroke(); +} + +function counter(ctx, rnd) { + const { x, y, w, h } = COUNTER; + // counter top (dark wood) seen from above, front edge at the bottom + shadowed(ctx, () => { + const g = ctx.createLinearGradient(0, y, 0, y + h); + g.addColorStop(0, '#4a2e18'); g.addColorStop(1, '#2a180c'); + ctx.fillStyle = g; rr(ctx, x, y, w + 20, h + 20, 10); ctx.fill(); + }, { blur: 18, dx: 0, dy: -4, alpha: 0.7 }); + grain(ctx, rnd, x, y, w, h, { tone: 'rgba(10,4,0,0.35)', lines: 26, wave: 3 }); + ctx.strokeStyle = 'rgba(255,210,150,0.15)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(x + 10, y + 3); ctx.lineTo(x + w, y + 3); ctx.stroke(); + + // record player: a teak plinth with a platter well (the record itself spins in the scene) + const px = PLATTER.x, py = PLATTER.y, pr = PLATTER.r; + shadowed(ctx, () => { + const g = ctx.createLinearGradient(px - 110, py - 88, px + 110, py + 88); + g.addColorStop(0, '#8a5a2e'); g.addColorStop(1, '#4a2c14'); + ctx.fillStyle = g; rr(ctx, px - 104, py - 86, 232, 172, 8); ctx.fill(); + }, { blur: 12, dx: 4, dy: 8, alpha: 0.6 }); + grain(ctx, rnd, px - 104, py - 86, 232, 172, { tone: 'rgba(30,12,0,0.3)', lines: 14, wave: 2 }); + ctx.fillStyle = '#16120e'; ctx.beginPath(); ctx.arc(px, py, pr + 6, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(200,200,210,0.5)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(px, py, pr + 4, 0, Math.PI * 2); ctx.stroke(); + // tonearm (rest + arm + headshell) + const ax = px + 92, ay = py - 58; + ctx.fillStyle = '#c8ccd2'; ctx.beginPath(); ctx.arc(ax, ay, 11, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#3a3a40'; ctx.beginPath(); ctx.arc(ax, ay, 5, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#d8dce2'; ctx.lineWidth = 4; ctx.lineCap = 'round'; + ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(ax - 18, ay + 70); ctx.lineTo(px + 34, py + 30); ctx.stroke(); + ctx.fillStyle = '#2a2a30'; ctx.save(); ctx.translate(px + 34, py + 30); ctx.rotate(-0.5); ctx.fillRect(-7, -5, 16, 12); ctx.restore(); + ctx.lineCap = 'butt'; + // knobs + for (const [kx, ky] of [[px + 100, py + 58], [px + 76, py + 66]]) { + ctx.fillStyle = '#c8ccd2'; ctx.beginPath(); ctx.arc(kx, ky, 6, 0, Math.PI * 2); ctx.fill(); + } + + // coffee siphon: stand, lower globe, upper funnel, burner + const gx = SIPHON.x, gy = SIPHON.y; + ctx.fillStyle = '#1a1a1e'; rr(ctx, gx - 46, gy + 46, 92, 12, 4); ctx.fill(); + ctx.fillStyle = '#2a2a30'; ctx.fillRect(gx + 40, gy - 110, 6, 160); + ctx.fillRect(gx + 10, gy - 106, 34, 5); + // burner + ctx.fillStyle = '#6a6a74'; rr(ctx, gx - 14, gy + 34, 28, 14, 3); ctx.fill(); + // lower globe with coffee + const lg = ctx.createRadialGradient(gx - 10, gy - 10, 4, gx, gy, 34); + lg.addColorStop(0, 'rgba(120,70,30,0.95)'); lg.addColorStop(0.7, 'rgba(50,24,8,0.95)'); lg.addColorStop(1, 'rgba(30,14,4,0.95)'); + ctx.fillStyle = lg; ctx.beginPath(); ctx.arc(gx, gy, 32, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(220,235,255,0.55)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(gx, gy, 32, 0, Math.PI * 2); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,255,255,0.5)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(gx, gy, 26, Math.PI * 1.1, Math.PI * 1.4); ctx.stroke(); + // upper funnel + ctx.fillStyle = 'rgba(200,220,240,0.18)'; ctx.strokeStyle = 'rgba(220,235,255,0.55)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(gx - 26, gy - 100); ctx.lineTo(gx + 26, gy - 100); ctx.lineTo(gx + 8, gy - 44); ctx.lineTo(gx + 4, gy - 30); ctx.lineTo(gx - 4, gy - 30); ctx.lineTo(gx - 8, gy - 44); ctx.closePath(); ctx.fill(); ctx.stroke(); + ctx.fillStyle = 'rgba(90,50,20,0.7)'; + ctx.beginPath(); ctx.moveTo(gx - 18, gy - 76); ctx.lineTo(gx + 18, gy - 76); ctx.lineTo(gx + 8, gy - 46); ctx.lineTo(gx - 8, gy - 46); ctx.closePath(); ctx.fill(); + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(gx - 20, gy - 96); ctx.lineTo(gx - 10, gy - 52); ctx.stroke(); + + // cup and saucer, seen from above + const ux = CUP.x, uy = CUP.y; + shadowed(ctx, () => { ctx.fillStyle = '#efe8da'; ctx.beginPath(); ctx.arc(ux, uy, 34, 0, Math.PI * 2); ctx.fill(); }, { blur: 8, dx: 3, dy: 5, alpha: 0.6 }); + ctx.strokeStyle = 'rgba(40,70,120,0.6)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(ux, uy, 30, 0, Math.PI * 2); ctx.stroke(); + ctx.fillStyle = '#f6f2ea'; ctx.beginPath(); ctx.arc(ux, uy, 22, 0, Math.PI * 2); ctx.fill(); + const cof = ctx.createRadialGradient(ux - 4, uy - 4, 2, ux, uy, 17); + cof.addColorStop(0, '#6a3a18'); cof.addColorStop(1, '#2a1206'); + ctx.fillStyle = cof; ctx.beginPath(); ctx.arc(ux, uy, 17, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#f6f2ea'; rr(ctx, ux + 20, uy - 5, 14, 10, 4); ctx.fill(); +} + +function lampPool(ctx) { + // the pendant lamp over the table, and the dark corners of the room + const g = ctx.createRadialGradient(BCX, BCY - 60, 120, BCX, BCY, 1150); + g.addColorStop(0, 'rgba(255,196,120,0.10)'); g.addColorStop(0.45, 'rgba(255,170,90,0.03)'); g.addColorStop(0.75, 'rgba(0,0,0,0.35)'); g.addColorStop(1, 'rgba(0,0,0,0.7)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); +} + +function bakeRoom(scene) { + { + const c = canvas(W, H), ctx = c.getContext('2d'), rnd = seeded(1971); + walls(ctx, rnd); lpShelf(ctx, rnd); windowView(ctx, rnd); menuCard(ctx); + lowTable(ctx, rnd); counter(ctx, rnd); lampPool(ctx); + addCanvas(scene, 'ot-room', c); + } + { + const c = canvas(W, H), ctx = c.getContext('2d'), rnd = seeded(1971); + lowTable(ctx, rnd); counter(ctx, rnd); + addCanvas(scene, 'ot-props', c); + } + { + const c = canvas(W, H), ctx = c.getContext('2d'); + lampPool(ctx); + addCanvas(scene, 'ot-vignette', c); + } +} + +// ── board ──────────────────────────────────────────────────────────────────── +export const BOARD_POS = { x: BX - FRAME - 20, y: BY - FRAME - 20 }; + +export function ensureBoard(scene, size) { + const key = `ot-board-${size}`; + if (scene.textures.exists(key)) return key; + const S = BOARD_TEX, o = 20, c = canvas(S + o * 2, S + o * 2), ctx = c.getContext('2d'), rnd = seeded(40 + size); + const SQ = BOARD / size; + shadowed(ctx, () => { ctx.fillStyle = '#0a0606'; rr(ctx, o, o, S, S, 12); ctx.fill(); }, { blur: 28, dx: 6, dy: 16, alpha: 0.8 }); + // black lacquer frame + ctx.fillStyle = lacquer(ctx, o, o, o + S, o + S); rr(ctx, o, o, S, S, 12); ctx.fill(); + ctx.fillStyle = 'rgba(120,40,20,0.10)'; rr(ctx, o + 4, o + 4, S - 8, S - 8, 10); ctx.fill(); + const gl = ctx.createLinearGradient(o, o, o + S, o); + gl.addColorStop(0, 'rgba(255,240,220,0.0)'); gl.addColorStop(0.3, 'rgba(255,240,220,0.10)'); gl.addColorStop(0.32, 'rgba(255,240,220,0.0)'); + ctx.fillStyle = gl; rr(ctx, o, o, S, S, 12); ctx.fill(); + ctx.strokeStyle = goldGrad(ctx, o, o, o + S, o + S); ctx.lineWidth = 2; + rr(ctx, o + 8, o + 8, S - 16, S - 16, 8); ctx.stroke(); + // gold corner caps + for (const [px, py, a] of [[o + 8, o + 8, 0], [o + S - 8, o + 8, Math.PI / 2], [o + S - 8, o + S - 8, Math.PI], [o + 8, o + S - 8, Math.PI * 1.5]]) { + ctx.save(); ctx.translate(px, py); ctx.rotate(a); + ctx.fillStyle = goldGrad(ctx, 0, 0, 26, 26); + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(26, 0); ctx.lineTo(26, 4); ctx.lineTo(4, 4); ctx.lineTo(4, 26); ctx.lineTo(0, 26); ctx.closePath(); ctx.fill(); + ctx.restore(); + } + // coordinates in gold along the top and left + const x0 = o + FRAME, y0 = o + FRAME; + ctx.font = `${size === 10 ? 16 : 18}px ${DISPLAY_FONT}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(232,200,120,0.85)'; + for (let i = 0; i < size; i++) { + ctx.fillText(String.fromCharCode(97 + i), x0 + i * SQ + SQ / 2, o + FRAME / 2 + 2); + ctx.fillText(String.fromCharCode(97 + i), x0 + i * SQ + SQ / 2, o + S - FRAME / 2 + 1); + ctx.fillText(String(i + 1), o + FRAME / 2 + 1, y0 + i * SQ + SQ / 2); + ctx.fillText(String(i + 1), o + S - FRAME / 2, y0 + i * SQ + SQ / 2); + } + // inner bead + ctx.fillStyle = '#060404'; ctx.fillRect(x0 - 5, y0 - 5, BOARD + 10, BOARD + 10); + // felt + const felt = ctx.createRadialGradient(x0 + BOARD * 0.45, y0 + BOARD * 0.4, 40, x0 + BOARD / 2, y0 + BOARD / 2, BOARD * 0.75); + felt.addColorStop(0, '#27784c'); felt.addColorStop(0.7, '#1d6440'); felt.addColorStop(1, '#154e30'); + ctx.fillStyle = felt; ctx.fillRect(x0, y0, BOARD, BOARD); + // felt fibres + for (let i = 0; i < 2600; i++) { + const fx = x0 + rnd() * BOARD, fy = y0 + rnd() * BOARD, a = rnd() * Math.PI, l = 2 + rnd() * 5; + ctx.strokeStyle = rnd() < 0.5 ? 'rgba(120,200,140,0.10)' : 'rgba(0,30,10,0.16)'; ctx.lineWidth = 0.8; + ctx.beginPath(); ctx.moveTo(fx, fy); ctx.lineTo(fx + Math.cos(a) * l, fy + Math.sin(a) * l); ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 96, 18); ctx.fillRect(x0, y0, BOARD, BOARD); + // wear in the middle where the game starts + const wear = ctx.createRadialGradient(x0 + BOARD / 2, y0 + BOARD / 2, 10, x0 + BOARD / 2, y0 + BOARD / 2, SQ * 2.2); + wear.addColorStop(0, 'rgba(160,220,170,0.07)'); wear.addColorStop(1, 'rgba(160,220,170,0)'); + ctx.fillStyle = wear; ctx.fillRect(x0, y0, BOARD, BOARD); + // grid + ctx.strokeStyle = 'rgba(4,24,12,0.85)'; ctx.lineWidth = 2.2; + for (let i = 0; i <= size; i++) { + ctx.beginPath(); ctx.moveTo(x0 + i * SQ, y0); ctx.lineTo(x0 + i * SQ, y0 + BOARD); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x0, y0 + i * SQ); ctx.lineTo(x0 + BOARD, y0 + i * SQ); ctx.stroke(); + } + ctx.strokeStyle = 'rgba(140,220,160,0.10)'; ctx.lineWidth = 1; + for (let i = 0; i <= size; i++) { + ctx.beginPath(); ctx.moveTo(x0 + i * SQ + 1.6, y0); ctx.lineTo(x0 + i * SQ + 1.6, y0 + BOARD); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x0, y0 + i * SQ + 1.6); ctx.lineTo(x0 + BOARD, y0 + i * SQ + 1.6); ctx.stroke(); + } + // the four marking dots + const k = size === 10 ? 3 : 2; + for (const [i, j] of [[k, k], [k, size - k], [size - k, k], [size - k, size - k]]) { + ctx.fillStyle = 'rgba(4,20,10,0.95)'; ctx.beginPath(); ctx.arc(x0 + i * SQ, y0 + j * SQ, 6, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, key, c); + return key; +} + +// ── discs ──────────────────────────────────────────────────────────────────── +const FACE = { + black: { top: '#2a2930', mid: '#18171d', rim: '#08080b', hi: 'rgba(160,160,190,0.35)' }, + white: { top: '#fffdf6', mid: '#ece6d6', rim: '#b8ae96', hi: 'rgba(255,255,255,0.9)' }, +}; + +function discFace(ctx, color, cx, cy, R) { + const f = FACE[color], u = FACE[color === 'black' ? 'white' : 'black']; + // the other colour's rim, just visible beneath (discs are two-sided) + ctx.fillStyle = u.mid; ctx.beginPath(); ctx.arc(cx, cy + 5 * RES, R, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = u.rim; ctx.beginPath(); ctx.arc(cx, cy + 5 * RES, R, Math.PI * 0.1, Math.PI * 0.9); ctx.lineWidth = 1.5 * RES; ctx.strokeStyle = u.rim; ctx.stroke(); + // own side wall + ctx.fillStyle = f.rim; ctx.beginPath(); ctx.arc(cx, cy + 2.5 * RES, R, 0, Math.PI * 2); ctx.fill(); + // top face + const g = ctx.createRadialGradient(cx - R * 0.35, cy - R * 0.4, R * 0.1, cx, cy, R); + g.addColorStop(0, f.top); g.addColorStop(0.55, f.mid); g.addColorStop(1, f.rim); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); + // a shallow dish moulded into the face + ctx.strokeStyle = color === 'black' ? 'rgba(0,0,0,0.55)' : 'rgba(120,110,80,0.35)'; ctx.lineWidth = 1.6 * RES; + ctx.beginPath(); ctx.arc(cx, cy, R * 0.74, 0, Math.PI * 2); ctx.stroke(); + ctx.strokeStyle = color === 'black' ? 'rgba(140,140,170,0.18)' : 'rgba(255,255,255,0.7)'; ctx.lineWidth = 1 * RES; + ctx.beginPath(); ctx.arc(cx, cy + 1.2 * RES, R * 0.74, Math.PI * 0.15, Math.PI * 0.85); ctx.stroke(); +} + +function bakeDiscs(scene) { + const T = DISC_TEX, R = DISC_R * RES; + for (const color of ['black', 'white']) { + const c = canvas(T, T), ctx = c.getContext('2d'); + discFace(ctx, color, T / 2, T / 2 - 3 * RES, R); + addCanvas(scene, `ot-disc-${color}`, c); + } + { + // the moving highlight sits above the disc and does not rotate + const c = canvas(T, T), ctx = c.getContext('2d'); + ctx.strokeStyle = 'rgba(255,255,255,0.32)'; ctx.lineWidth = 3.2 * RES; ctx.lineCap = 'round'; + ctx.beginPath(); ctx.arc(T / 2, T / 2 - 3 * RES, R * 0.86, Math.PI * 1.08, Math.PI * 1.42); ctx.stroke(); + ctx.fillStyle = 'rgba(255,255,255,0.22)'; ctx.beginPath(); ctx.ellipse(T / 2 - R * 0.36, T / 2 - R * 0.42, R * 0.18, R * 0.1, -0.6, 0, Math.PI * 2); ctx.fill(); + addCanvas(scene, 'ot-sheen', c); + } + { + const { w, h } = EDGE_TEX, c = canvas(w, h), ctx = c.getContext('2d'); + ctx.save(); rr(ctx, 0, 0, w, h, h / 2); ctx.clip(); + const top = ctx.createLinearGradient(0, 0, w, 0); + top.addColorStop(0, '#b8ae96'); top.addColorStop(0.3, '#fffdf6'); top.addColorStop(1, '#c8bea6'); + ctx.fillStyle = top; ctx.fillRect(0, 0, w, h / 2); + const bot = ctx.createLinearGradient(0, 0, w, 0); + bot.addColorStop(0, '#08080b'); bot.addColorStop(0.3, '#3a3940'); bot.addColorStop(1, '#0c0c10'); + ctx.fillStyle = bot; ctx.fillRect(0, h / 2, w, h / 2); + ctx.restore(); + addCanvas(scene, 'ot-edge', c); + } + { + const S = DISC_TEX, c = canvas(S, S), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(S / 2, S / 2, R * 0.55, S / 2, S / 2, R * 1.18); + g.addColorStop(0, 'rgba(0,0,0,0.6)'); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, S, S); + addCanvas(scene, 'ot-shadow', c); + } + { + // a disc standing upright in the tray groove: half black, half white + const w = 9, h = 36, c = canvas(w * RES, h * RES), ctx = c.getContext('2d'); + ctx.save(); rr(ctx, 0, 0, w * RES, h * RES, 3 * RES); ctx.clip(); + const a = ctx.createLinearGradient(0, 0, 0, h * RES); + a.addColorStop(0, '#3a3940'); a.addColorStop(0.5, '#1a1920'); a.addColorStop(1, '#08080b'); + ctx.fillStyle = a; ctx.fillRect(0, 0, (w * RES) / 2, h * RES); + const b = ctx.createLinearGradient(0, 0, 0, h * RES); + b.addColorStop(0, '#fffdf6'); b.addColorStop(0.5, '#ece6d6'); b.addColorStop(1, '#a89e86'); + ctx.fillStyle = b; ctx.fillRect((w * RES) / 2, 0, (w * RES) / 2, h * RES); + ctx.restore(); + addCanvas(scene, 'ot-slice', c); + } +} + +// ── HUD furniture ──────────────────────────────────────────────────────────── +function bakePlate(scene) { + const pad = 14, w = PLATE.w, h = PLATE.h; + { + const c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(5); + shadowed(ctx, () => { ctx.fillStyle = '#0a0606'; rr(ctx, pad, pad, w, h, 12); ctx.fill(); }, { blur: 14, dx: 5, dy: 8, alpha: 0.65 }); + ctx.fillStyle = lacquer(ctx, pad, pad, pad + w, pad + h); rr(ctx, pad + 3, pad + 3, w - 6, h - 6, 10); ctx.fill(); + grain(ctx, rnd, pad + 4, pad + 4, w - 8, h - 8, { tone: 'rgba(80,30,10,0.12)', lines: 10, wave: 2 }); + ctx.strokeStyle = goldGrad(ctx, pad, pad, pad + w, pad + h); ctx.lineWidth = 2.5; rr(ctx, pad + 2, pad + 2, w - 4, h - 4, 11); ctx.stroke(); + ctx.fillStyle = '#b8321e'; rr(ctx, pad + 6, pad + 6, w - 12, 6, 3); ctx.fill(); + ctx.strokeStyle = 'rgba(216,176,96,0.35)'; ctx.lineWidth = 1; rr(ctx, pad + 10, pad + 18, w - 20, h - 28, 6); ctx.stroke(); + addCanvas(scene, 'ot-plate', c); + } + { + const P = 40, c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d'); + ctx.shadowColor = 'rgba(255,200,110,1)'; ctx.shadowBlur = 30; + ctx.strokeStyle = 'rgba(255,215,130,0.95)'; ctx.lineWidth = 5; rr(ctx, P, P, w, h, 12); ctx.stroke(); + addCanvas(scene, 'ot-plate-glow', c); + } +} + +// a kissa menu card: cream stock, vermilion rule, a coffee-ring stain +function bakeCard(scene, key, w, h, { ruled = false } = {}) { + const pad = 14, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(w + h * 3); + shadowed(ctx, () => { ctx.fillStyle = CREAM; rr(ctx, pad, pad, w, h, 6); ctx.fill(); }, { blur: 16, dx: 5, dy: 9, alpha: 0.6 }); + const paper = ctx.createLinearGradient(0, pad, 0, pad + h); + paper.addColorStop(0, '#f7f0dc'); paper.addColorStop(1, '#e8dcbc'); + ctx.fillStyle = paper; rr(ctx, pad, pad, w, h, 6); ctx.fill(); + ctx.save(); rr(ctx, pad, pad, w, h, 6); ctx.clip(); + ctx.fillStyle = '#b8321e'; ctx.fillRect(pad, pad, w, 5); + ctx.fillStyle = '#1a1a1a'; ctx.fillRect(pad, pad + 7, w, 1.5); + if (ruled) { + ctx.strokeStyle = 'rgba(60,40,20,0.16)'; ctx.lineWidth = 1; + for (let y = pad + 80; y < pad + h - 10; y += 31) { ctx.beginPath(); ctx.moveTo(pad + 12, y); ctx.lineTo(pad + w - 12, y); ctx.stroke(); } + ctx.strokeStyle = 'rgba(184,50,30,0.3)'; + ctx.beginPath(); ctx.moveTo(pad + 66, pad + 50); ctx.lineTo(pad + 66, pad + h); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(pad + 66 + (w - 66) / 2, pad + 50); ctx.lineTo(pad + 66 + (w - 66) / 2, pad + h); ctx.stroke(); + } + // a faint coffee ring + const rx = pad + w - 70 - rnd() * 60, ry = pad + h - 60 - rnd() * 40; + ctx.strokeStyle = 'rgba(120,70,30,0.10)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(rx, ry, 34, 0.4, Math.PI * 1.9); ctx.stroke(); + for (let i = 0; i < 10; i++) { + const x = pad + rnd() * w, y = pad + rnd() * h, r = 2 + rnd() * 7; + ctx.fillStyle = `rgba(150,110,50,${0.03 + rnd() * 0.05})`; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + } + ctx.fillStyle = noisePattern(ctx, 64, 12); ctx.fillRect(pad, pad, w, h); + ctx.restore(); + addCanvas(scene, key, c); +} + +function bakeRibbon(scene) { + const { w, h } = RIBBON, pad = 12, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'); + shadowed(ctx, () => { ctx.fillStyle = '#0a0606'; rr(ctx, pad, pad, w, h, 10); ctx.fill(); }, { blur: 14, dx: 3, dy: 7, alpha: 0.6 }); + ctx.fillStyle = lacquer(ctx, pad, pad, pad + w, pad + h); rr(ctx, pad, pad, w, h, 10); ctx.fill(); + ctx.strokeStyle = 'rgba(216,176,96,0.45)'; ctx.lineWidth = 1.5; rr(ctx, pad + 5, pad + 5, w - 10, h - 10, 7); ctx.stroke(); + // the Master's badge: a cup on a gold disc + const bx = pad + 40, by = pad + h / 2; + ctx.fillStyle = goldGrad(ctx, bx - 24, by - 24, bx + 24, by + 24); ctx.beginPath(); ctx.arc(bx, by, 23, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#2a1408'; + ctx.beginPath(); ctx.moveTo(bx - 12, by - 4); ctx.lineTo(bx + 8, by - 4); ctx.lineTo(bx + 5, by + 10); ctx.lineTo(bx - 9, by + 10); ctx.closePath(); ctx.fill(); + ctx.strokeStyle = '#2a1408'; ctx.lineWidth = 2.2; ctx.beginPath(); ctx.arc(bx + 10, by + 2, 4, -Math.PI / 2, Math.PI / 2); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(bx - 14, by + 13); ctx.lineTo(bx + 12, by + 13); ctx.stroke(); + ctx.lineWidth = 1.6; + for (const sx of [-6, 0]) { ctx.beginPath(); ctx.moveTo(bx + sx, by - 8); ctx.quadraticCurveTo(bx + sx - 4, by - 13, bx + sx, by - 18); ctx.stroke(); } + addCanvas(scene, 'ot-ribbon', c); +} + +function bakeTray(scene) { + const { w, h } = TRAYS.top, pad = 8, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(9); + shadowed(ctx, () => { ctx.fillStyle = '#1a0e06'; rr(ctx, pad, pad, w, h, 8); ctx.fill(); }, { blur: 10, dx: 2, dy: 5, alpha: 0.6 }); + const g = ctx.createLinearGradient(0, pad, 0, pad + h); + g.addColorStop(0, '#5a3a20'); g.addColorStop(1, '#3a2412'); + ctx.fillStyle = g; rr(ctx, pad, pad, w, h, 8); ctx.fill(); + grain(ctx, rnd, pad, pad, w, h, { tone: 'rgba(10,4,0,0.3)', lines: 8, wave: 2 }); + const gr = ctx.createLinearGradient(0, pad + 6, 0, pad + h - 6); + gr.addColorStop(0, '#120a04'); gr.addColorStop(1, '#2a1a0c'); + ctx.fillStyle = gr; rr(ctx, pad + 8, pad + 6, w - 70, h - 12, 5); ctx.fill(); + addCanvas(scene, 'ot-tray', c); +} + +function bakeBar(scene) { + const { w, h } = BAR, pad = 10, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'); + shadowed(ctx, () => { ctx.fillStyle = '#0a0606'; rr(ctx, pad, pad, w, h, h / 2); ctx.fill(); }, { blur: 12, dx: 0, dy: 6, alpha: 0.7 }); + ctx.strokeStyle = goldGrad(ctx, pad, pad, pad + w, pad + h); ctx.lineWidth = 2; rr(ctx, pad + 1, pad + 1, w - 2, h - 2, h / 2 - 1); ctx.stroke(); + addCanvas(scene, 'ot-bar', c); +} + +function bakeBits(scene) { + const radial = (key, S, stops) => { + const c = canvas(S, S), 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('ot-glow', 128, [[0, 'rgba(255,226,140,0.9)'], [0.45, 'rgba(255,200,90,0.45)'], [1, 'rgba(255,190,80,0)']]); + radial('ot-spark', 24, [[0, 'rgba(255,255,255,1)'], [0.35, 'rgba(255,240,200,0.8)'], [1, 'rgba(255,220,150,0)']]); + radial('ot-steam', 64, [[0, 'rgba(255,255,255,0.5)'], [1, 'rgba(255,255,255,0)']]); + radial('ot-neon-glow', 200, [[0, 'rgba(255,110,170,0.6)'], [0.5, 'rgba(255,90,150,0.18)'], [1, 'rgba(255,90,150,0)']]); + radial('ot-flame', 32, [[0, 'rgba(200,230,255,1)'], [0.4, 'rgba(90,140,255,0.8)'], [1, 'rgba(60,90,255,0)']]); + { + const S = 12, c = canvas(S, S), ctx = c.getContext('2d'); + ctx.strokeStyle = 'rgba(255,230,200,0.8)'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 2, 0, Math.PI * 2); ctx.stroke(); + addCanvas(scene, 'ot-bubble', c); + } + { + const S = 96, c = canvas(S, S), ctx = c.getContext('2d'); + ctx.strokeStyle = 'rgba(255,224,130,1)'; ctx.lineWidth = 5; + ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 5, 0, Math.PI * 2); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 10, 0, Math.PI * 2); ctx.stroke(); + addCanvas(scene, 'ot-ring', c); + } + { + const S = 48, c = canvas(S, S), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(S / 2 - 5, S / 2 - 5, 2, S / 2, S / 2, S / 2 - 6); + g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(1, 'rgba(225,225,225,0.85)'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 8, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(255,255,255,0.95)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 3, 0, Math.PI * 2); ctx.stroke(); + addCanvas(scene, 'ot-dot', c); + } + { + const c = canvas(3, 26), ctx = c.getContext('2d'); + const g = ctx.createLinearGradient(0, 0, 0, 26); + g.addColorStop(0, 'rgba(200,210,255,0)'); g.addColorStop(1, 'rgba(220,230,255,0.7)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, 3, 26); + addCanvas(scene, 'ot-rain', c); + } + { + // the LP on the platter (spun in the scene) + const R = PLATTER.r, S = R * 2 + 4, c = canvas(S, S), ctx = c.getContext('2d'), cx = S / 2; + ctx.fillStyle = '#0c0c0e'; ctx.beginPath(); ctx.arc(cx, cx, R, 0, Math.PI * 2); ctx.fill(); + for (let r = R * 0.42; r < R - 2; r += 2.2) { + ctx.strokeStyle = `rgba(255,255,255,${0.03 + (Math.floor(r) % 7 === 0 ? 0.05 : 0)})`; ctx.lineWidth = 0.8; + ctx.beginPath(); ctx.arc(cx, cx, r, 0, Math.PI * 2); ctx.stroke(); + } + ctx.fillStyle = '#b8321e'; ctx.beginPath(); ctx.arc(cx, cx, R * 0.34, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#f3ead2'; ctx.font = `bold 9px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('SIDE A', cx, cx - R * 0.16); + ctx.fillStyle = 'rgba(243,234,210,0.8)'; ctx.fillRect(cx - R * 0.2, cx + R * 0.1, R * 0.4, 2); + ctx.fillStyle = '#d8dce2'; ctx.beginPath(); ctx.arc(cx, cx, 3, 0, Math.PI * 2); ctx.fill(); + addCanvas(scene, 'ot-record', c); + } + { + const R = PLATTER.r, S = R * 2 + 4, c = canvas(S, S), ctx = c.getContext('2d'), cx = S / 2; + ctx.save(); ctx.beginPath(); ctx.arc(cx, cx, R, 0, Math.PI * 2); ctx.clip(); + for (const [a0, a1] of [[-2.4, -1.9], [0.7, 1.2]]) { + const g = ctx.createRadialGradient(cx, cx, R * 0.4, cx, cx, R); + g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.7, 'rgba(255,255,255,0.12)'); g.addColorStop(1, 'rgba(255,255,255,0.02)'); + ctx.fillStyle = g; ctx.beginPath(); ctx.moveTo(cx, cx); ctx.arc(cx, cx, R, a0, a1); ctx.closePath(); ctx.fill(); + } + ctx.restore(); + addCanvas(scene, 'ot-record-sheen', c); + } +} + +let baked = false; +export async function prepareOthelloArt(scene) { + try { + if (document.fonts?.load) { + await Promise.race([ + Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"')]), + new Promise((res) => setTimeout(res, 1200)), + ]); + } + } catch (_) { /* fall back to Georgia */ } + if (!baked || !scene.textures.exists('ot-room')) { + bakeRoom(scene); bakeDiscs(scene); bakePlate(scene); + bakeCard(scene, 'ot-card-status', STATUS.w, STATUS.h); + bakeCard(scene, 'ot-card-log', LOG.w, LOG.h, { ruled: true }); + bakeRibbon(scene); bakeTray(scene); bakeBar(scene); bakeBits(scene); + baked = true; + } +} + diff --git a/src/games/othello/OthelloBook.js b/src/games/othello/OthelloBook.js new file mode 100644 index 0000000..9f53509 --- /dev/null +++ b/src/games/othello/OthelloBook.js @@ -0,0 +1,85 @@ +// OthelloBook.js: a small book of named 8×8 openings, written from Black's +// usual first move f5. The four legal first moves (f5, e6, d3, c4) are +// mirror images of one another, so a game is "normalised" onto f5 before it +// is looked up, and book replies are mapped back. +// +// openingName(moves) longest named line the game has followed +// bookReplies(moves) next moves (in the game's own orientation) +// openingCard(rnd) a line for the Master's opening card, mirrored +// at random: { name, moves: ['f5', …] } + +import { parseSq, notate } from './OthelloLogic.js'; + +export const LINES = [ + { name: 'Diagonal Opening', moves: 'f5 f6' }, + { name: 'Perpendicular Opening', moves: 'f5 d6' }, + { name: 'Parallel Opening', moves: 'f5 f4' }, + { name: 'Tiger', moves: 'f5 d6 c3 d3 c4' }, + { name: 'Brightwell', moves: 'f5 d6 c3 d3 c4 f4 f6' }, + { name: 'Buffalo', moves: 'f5 d6 c3 d3 c4 f4 c5 b3 c2' }, + { name: 'Cow', moves: 'f5 d6 c5 f4 e3' }, + { name: 'Heath', moves: 'f5 f6 e6 f4 g5' }, + { name: 'Rabbit', moves: 'f5 f6 e6 f4 e3' }, +].map((l) => ({ ...l, list: l.moves.split(' ') })); + +// Lines worth starting a game from (the two-move "openings" are just families). +export const CARD_LINES = LINES.filter((l) => l.list.length >= 5); + +const SIZE = 8; +// The symmetries of the starting position, each its own inverse. +const SYMS = [ + (r, c) => [r, c], + (r, c) => [7 - r, 7 - c], + (r, c) => [c, r], + (r, c) => [7 - c, 7 - r], +]; + +function mapMove(n, sym) { + const sq = parseSq(n, SIZE); + if (sq < 0) return null; + const [r, c] = SYMS[sym](Math.floor(sq / SIZE), sq % SIZE); + return notate(r * SIZE + c, SIZE); +} + +/** The symmetry that turns the game's first move into f5, or -1. */ +function symFor(first) { + for (let i = 0; i < SYMS.length; i++) if (mapMove(first, i) === 'f5') return i; + return -1; +} + +function normalise(moves) { + if (!moves.length) return { sym: 0, list: [] }; + const sym = symFor(moves[0]); + if (sym < 0) return null; + return { sym, list: moves.map((m) => mapMove(m, sym)) }; +} + +const startsWith = (a, b) => b.length <= a.length && b.every((m, i) => a[i] === m); + +/** Name of the longest book line the moves have followed in full. */ +export function openingName(moves) { + const n = normalise(moves); + if (!n || !n.list.length) return null; + let best = null; + for (const l of LINES) if (startsWith(n.list, l.list) && (!best || l.list.length > best.list.length)) best = l; + return best?.name ?? null; +} + +/** Book continuations from here (distinct, in the game's orientation). */ +export function bookReplies(moves) { + if (!moves.length) return ['f5', 'e6', 'd3', 'c4']; + const n = normalise(moves); + if (!n) return []; + const out = new Set(); + for (const l of LINES) { + if (l.list.length > n.list.length && startsWith(l.list, n.list)) out.add(mapMove(l.list[n.list.length], n.sym)); + } + return [...out]; +} + +export function openingCard(rnd = Math.random, avoid = []) { + const pool = CARD_LINES.filter((l) => !avoid.includes(l.name)); + const l = (pool.length ? pool : CARD_LINES)[Math.floor(rnd() * (pool.length || CARD_LINES.length))]; + const sym = Math.floor(rnd() * SYMS.length); + return { name: l.name, moves: l.list.map((m) => mapMove(m, sym)) }; +} diff --git a/src/games/othello/OthelloDialogs.js b/src/games/othello/OthelloDialogs.js new file mode 100644 index 0000000..61c2273 --- /dev/null +++ b/src/games/othello/OthelloDialogs.js @@ -0,0 +1,150 @@ +// OthelloDialogs.js: kissa pop-ups: a cream menu card in a black-lacquer +// frame with a vermilion rule. Each opener returns { close() } and swallows +// clicks beneath. + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { DISPLAY_FONT, SERIF } from './OthelloArt.js'; +import { VARIANTS, VARIANT_ORDER, SIZE_INFO, SIZES } from './OthelloLogic.js'; + +const INK = '#2a1410'; +const BTN_BG = 0x3a2216; + +export function frame(scene, x, y, w, h, depth) { + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.5).fillRoundedRect(x + 6, y + 10, w, h, 14); + g.fillStyle(0x140c0a, 1).fillRoundedRect(x, y, w, h, 14); + g.lineStyle(3, 0xd8b060, 1).strokeRoundedRect(x + 5, y + 5, w - 10, h - 10, 11); + g.fillStyle(0xf3ead2, 1).fillRoundedRect(x + 14, y + 14, w - 28, h - 28, 6); + g.fillStyle(0xb8321e, 1).fillRect(x + 14, y + 14, w - 28, 7); + g.fillStyle(0x1a1a1a, 1).fillRect(x + 14, y + 23, w - 28, 2); + g.lineStyle(1.5, 0x8a6a3a, 0.5).strokeRoundedRect(x + 24, y + 34, w - 48, h - 56, 4); + return g; +} + +export function blocker(scene, depth, alpha = 0) { + return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x050302, alpha).setDepth(depth).setInteractive(); +} + +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 = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' }; + +export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewMatch, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.55)]; + const w = 640, h = 900; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(scene.add.text(x + w / 2, y + 66, 'Kuro-Shiro', { fontFamily: DISPLAY_FONT, fontSize: '32px', color: INK }).setOrigin(0.5).setDepth(depth + 1)); + const cx = x + w / 2; + let hRef = null; + const cycle = (k, order) => onChange(k, order[(order.indexOf(settings[k]) + 1) % order.length]); + const rows = [ + ['Resume', () => hRef.close(), 0x2a4a6a], + [() => `Opponent speed: ${PACE[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'fast'])], + [() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)], + [() => `Show legal moves: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)], + [() => `Preview flips on hover: ${onOff(settings.preview)}`, () => onChange('preview', !settings.preview)], + [() => `Master warns before you give up a corner: ${onOff(settings.coach)}`, () => onChange('coach', !settings.coach)], + [() => `Study: mark X- and C-squares: ${onOff(settings.danger)}`, () => onChange('danger', !settings.danger)], + [() => `Study: count their replies on each move: ${onOff(settings.mobility)}`, () => onChange('mobility', !settings.mobility)], + [() => `Study: shade discs that can't be flipped: ${onOff(settings.stable)}`, () => onChange('stable', !settings.stable)], + [() => `Rain, records & the siphon: ${onOff(settings.ambience)}`, () => onChange('ambience', !settings.ambience)], + ['How to Play', () => onRules()], + ['New Match…', () => { hRef.close(); onNewMatch(); }, 0x6a4a1a], + ['Leave the Kissa', () => { hRef.close(); onLeave(); }, 0x7a1a14], + ]; + rows.forEach(([label, fn, bg], i) => { + const text = typeof label === 'function' ? label() : label; + const btn = new Button(scene, cx, y + 128 + i * 54, text, () => { fn(); if (typeof label === 'function') btn.setLabel(label()); }, { + width: 560, height: 44, fontSize: 16, bg: bg ?? BTN_BG, + }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(scene.add.text(cx, y + h - 52, 'Click a marked square to play · Z undo · H hint · S study marks\nArrows + Enter to play with the keyboard · Esc menu', { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#4a3a22', align: 'center', + }).setOrigin(0.5).setDepth(depth + 1)); + hRef = handle(objs, onClose); + return hRef; +} + +/** The match setup card. prefs = { color, games, size, start, variant }. */ +export function openSetup(scene, { prefs, depth, opponentName, onStart, onLeave }) { + const objs = [blocker(scene, depth - 1, 0.6)]; + const w = 780, h = 730; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + const p = { ...prefs }; + const cx = x + w / 2; + objs.push(scene.add.text(cx, y + 70, 'A Table for Two', { fontFamily: DISPLAY_FONT, fontSize: '34px', color: INK }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(cx, y + 110, `You against ${opponentName}. The Master keeps the count.`, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#5a4a32' }).setOrigin(0.5).setDepth(depth + 1)); + + const labelX = x + 70, ctlX = x + 480; + const rowY = (i) => y + 172 + i * 82; + const rows = []; + const addRow = (i, title, get, fn) => { + objs.push(scene.add.text(labelX, rowY(i), title, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: INK }).setOrigin(0, 0.5).setDepth(depth + 1)); + const btn = new Button(scene, ctlX, rowY(i), get(), () => { fn(); refresh(); }, { width: 380, height: 46, fontSize: 18, bg: BTN_BG }).setDepth(depth + 2); + objs.push(btn); + rows.push({ btn, get }); + }; + const cyc = (list, v) => list[(list.indexOf(v) + 1) % list.length]; + const cardOk = () => p.size === 8 && p.variant === 'standard'; + addRow(0, 'Your colour', () => (p.color === 'random' ? 'Toss a disc' : p.color === 'black' ? 'Black (moves first)' : 'White (moves second)'), + () => { p.color = cyc(['black', 'white', 'random'], p.color); }); + addRow(1, 'Match', () => (p.games === 1 ? 'Single game' : `Best of ${p.games}`), () => { p.games = cyc([1, 3, 5], p.games); }); + addRow(2, 'Board', () => SIZE_INFO[p.size].name, () => { p.size = cyc(SIZES, p.size); }); + addRow(3, 'Rules', () => VARIANTS[p.variant].name, () => { p.variant = cyc(VARIANT_ORDER, p.variant); }); + addRow(4, 'Opening', () => (!cardOk() ? 'Standard (book is 8×8 only)' : p.start === 'card' ? 'Master\'s opening card' : 'Standard start'), + () => { if (cardOk()) p.start = p.start === 'card' ? 'standard' : 'card'; }); + + const blurb = scene.add.text(cx, y + 598, '', { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 120 } }) + .setOrigin(0.5).setDepth(depth + 1); + objs.push(blurb); + function refresh() { + rows.forEach((r) => r.btn.setLabel(r.get())); + let b = `${VARIANTS[p.variant].blurb} ${SIZE_INFO[p.size].blurb}`; + if (cardOk() && p.start === 'card') b += ' The Master deals a card with a named opening already played out; in a match each one is played twice, colours swapped.'; + if (p.games > 1) b += ' Colours alternate each game; a draw scores half.'; + blurb.setText(b); + } + refresh(); + let hRef = null; + objs.push(new Button(scene, cx - 130, y + h - 62, 'Sit Down', () => { + hRef.close(); + onStart({ ...p, start: cardOk() ? p.start : 'standard' }); + }, { width: 230, height: 50, fontSize: 20, bg: 0x1f6a3a }).setDepth(depth + 2)); + objs.push(new Button(scene, cx + 130, y + h - 62, 'Leave', () => { hRef.close(); onLeave(); }, { width: 230, height: 50, fontSize: 20, bg: 0x7a1a14 }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} + +export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', yesBg = 0x7a1a14, depth, onYes, onNo }) { + const objs = [blocker(scene, depth - 1, 0.55)]; + const w = 580, h = 300; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(scene.add.text(x + w / 2, y + 72, heading, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: INK }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(x + w / 2, y + 144, text, { fontFamily: SERIF, fontSize: '18px', color: '#2a1a10', align: 'center', wordWrap: { width: w - 90 } }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + if (no) { + objs.push(new Button(scene, x + w / 2 - 124, y + h - 62, yes, () => { hRef.close(); onYes?.(); }, { width: 220, height: 46, fontSize: 18, bg: yesBg }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 124, y + h - 62, no, () => { hRef.close(); onNo?.(); }, { width: 220, height: 46, fontSize: 18, bg: 0x2a4a6a }).setDepth(depth + 2)); + } else { + objs.push(new Button(scene, x + w / 2, y + h - 62, yes, () => { hRef.close(); onYes?.(); }, { width: 240, height: 46, fontSize: 18, bg: 0x1f6a3a }).setDepth(depth + 2)); + } + hRef = handle(objs); + return hRef; +} + +export function toast(scene, text, { depth, x = GAME_WIDTH / 2, y = 960, ms = 2200 } = {}) { + const t = scene.add.text(x, y, text, { fontFamily: SERIF, fontSize: '20px', color: '#2a1a10', backgroundColor: '#f3ead2', padding: { x: 18, y: 10 } }) + .setOrigin(0.5).setDepth(depth).setAlpha(0); + scene.tweens.add({ targets: t, alpha: 1, duration: 200 }); + scene.tweens.add({ targets: t, alpha: 0, delay: ms, duration: 400, onComplete: () => t.destroy() }); + return t; +} diff --git a/src/games/othello/OthelloEndScreen.js b/src/games/othello/OthelloEndScreen.js new file mode 100644 index 0000000..0f9d79b --- /dev/null +++ b/src/games/othello/OthelloEndScreen.js @@ -0,0 +1,242 @@ +// OthelloEndScreen.js: after a game: the between-games card (result, +// match tally, Next Game); after a match: the full summary: the result, +// the last game's numbers, the disc-difference graph, the Master's notes +// (the moves he'd have played differently, from the engine's review), your +// lifetime record against this opponent, every game of the match, and a +// replay board you can step through move by move. + +import { Button } from '../../ui/Button.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { DISPLAY_FONT, SERIF } from './OthelloArt.js'; +import { frame, blocker, handle } from './OthelloDialogs.js'; +import { boardAfter, discTrace, stats, counts, notate, other, VARIANTS, SIZE_INFO } from './OthelloLogic.js'; +import { describeMistake } from './OthelloAI.js'; + +const half = (x) => (x % 1 ? `${Math.floor(x) || ''}½` : String(x)); +const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1); +export const REASON = { + full: 'the board is full', + blocked: 'neither side can move', + wipeout: 'one side has no discs left', + resign: 'resignation', +}; + +export function resultLine(gs, humanColor, oppName) { + const c = counts(gs); + const tally = `Black ${c.black} · White ${c.white}`; + if (gs.winner === 'draw') return { title: 'A draw', good: null, why: `${tally}: dead even.` }; + const won = gs.winner === humanColor; + let why = REASON[gs.endReason] ?? ''; + if (gs.endReason === 'resign') why = won ? `${oppName} resigned` : 'you resigned'; + const anti = gs.variant === 'anti' && gs.endReason !== 'resign' ? ' (fewest discs wins)' : ''; + return { title: won ? 'You win!' : `${oppName} wins`, good: won, why: `${tally}${anti}. ${cap(why)}.` }; +} + +/** Between games of a match. */ +export function openBetween(scene, { gs, humanColor, oppName, match, depth, onNext, onLeave }) { + const objs = [blocker(scene, depth - 1, 0.45)]; + const w = 640, h = 360; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + const r = resultLine(gs, humanColor, oppName); + objs.push(scene.add.text(x + w / 2, y + 78, `Game ${match.results.length}: ${r.title}`, { fontFamily: DISPLAY_FONT, fontSize: '30px', color: r.good === null ? '#2a1410' : r.good ? '#1f6a3a' : '#8e1c16' }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(x + w / 2, y + 124, r.why, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 80 } }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(x + w / 2, y + 182, `Match: You ${half(match.human) || '0'} · ${oppName} ${half(match.ai) || '0'} (best of ${match.games})`, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: '#2a1410' }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(x + w / 2, y + 218, 'Colours swap for the next game.', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#5a4a32' }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + objs.push(new Button(scene, x + w / 2 - 125, y + h - 62, 'Next Game', () => { hRef.close(); onNext(); }, { width: 220, height: 48, fontSize: 19, bg: 0x1f6a3a }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 125, y + h - 62, 'Leave', () => { hRef.close(); onLeave(); }, { width: 220, height: 48, fontSize: 19, bg: 0x7a1a14 }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} + +/** + * The match summary. `review` is a Promise of the engine's review of the + * human's moves (or null); notes fill in when it arrives. + */ +export function openEndScreen(scene, { gs, humanColor, oppName, match, record, depth, review, onPlayAgain, onMenu }) { + const objs = [blocker(scene, depth - 1, 0.55)]; + const w = 1260, h = 880; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + const add = (o) => { objs.push(o); return o; }; + const D1 = depth + 1; + let closed = false; + + // headline + let title, color; + const multi = match.games > 1; + if (multi) { + if (match.human > match.ai) { title = 'You take the match!'; color = '#1f6a3a'; } + else if (match.ai > match.human) { title = `${oppName} takes the match`; color = '#8e1c16'; } + else { title = 'The match is drawn'; color = '#2a1410'; } + } else { + const r = resultLine(gs, humanColor, oppName); + title = r.title; color = r.good === null ? '#2a1410' : r.good ? '#1f6a3a' : '#8e1c16'; + } + add(scene.add.text(x + w / 2, y + 72, title, { fontFamily: DISPLAY_FONT, fontSize: '38px', color }).setOrigin(0.5).setDepth(D1)); + const rules = `${VARIANTS[gs.variant].name} · ${SIZE_INFO[gs.size].name}${gs.opening ? ` · ${gs.opening.name}` : ''}`; + const sub = multi + ? `You ${half(match.human) || '0'} · ${oppName} ${half(match.ai) || '0'} · ${rules}` + : `${resultLine(gs, humanColor, oppName).why} · ${rules}`; + add(scene.add.text(x + w / 2, y + 116, sub, { fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 120 } }).setOrigin(0.5).setDepth(D1)); + + // ── left: numbers, graph, the Master's notes, record ── + const lx = x + 70; + let ly = y + 172; + const g = add(scene.add.graphics().setDepth(D1)); + add(scene.add.text(lx, ly, multi ? 'LAST GAME' : 'THE GAME', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#7a2414' }).setOrigin(0, 0.5).setDepth(D1)); + ly += 28; + const aiColor = other(humanColor); + const you = stats(gs, humanColor), them = stats(gs, aiColor); + const rows = [ + ['Discs at the end', you.discs, them.discs], + ['Discs flipped', you.flips, them.flips], + ['Biggest single flip', you.biggest || '—', them.biggest || '—'], + ['Corners taken', you.corners, them.corners], + ['Passes', you.passes, them.passes], + ]; + const c1 = lx + 300, c2 = lx + 440; + add(scene.add.text(c1, ly, `YOU (${humanColor.toUpperCase()})`, { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#2a1410' }).setOrigin(0.5).setDepth(D1)); + add(scene.add.text(c2, ly, oppName.toUpperCase().slice(0, 12), { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#2a1410' }).setOrigin(0.5).setDepth(D1)); + rows.forEach(([label, a, b], i) => { + const yy = ly + 28 + i * 27; + if (i % 2 === 0) g.fillStyle(0x8a5a2a, 0.08).fillRect(lx - 10, yy - 13, 540, 26); + add(scene.add.text(lx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: '#3a2a1a' }).setOrigin(0, 0.5).setDepth(D1)); + add(scene.add.text(c1, yy, String(a), { fontFamily: SERIF, fontSize: '16px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D1)); + add(scene.add.text(c2, yy, String(b), { fontFamily: SERIF, fontSize: '16px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D1)); + }); + ly += 28 + rows.length * 27 + 26; + + // disc difference graph (your side above the line) + const trace = discTrace(gs).map((v) => (humanColor === 'black' ? v : -v)); + const sw = 540, sh = 110, sx = lx - 10, sy = ly; + add(scene.add.text(lx, sy - 4, 'DISCS AHEAD (you above the line)', { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#7a2414' }).setOrigin(0, 1).setDepth(D1)); + g.fillStyle(0xffffff, 0.35).fillRect(sx, sy + 6, sw, sh); + const maxAbs = Math.max(4, ...trace.map(Math.abs)); + const mid = sy + 6 + sh / 2; + const px = (i) => sx + (i / Math.max(1, trace.length - 1)) * sw; + const py = (v) => mid - (v / maxAbs) * (sh / 2 - 6); + g.lineStyle(1, 0x8a6a3a, 0.6).lineBetween(sx, mid, sx + sw, mid); + if (trace.length > 1) { + g.fillStyle(humanColor === 'black' ? 0x1c1b22 : 0xb8ae96, 0.25); + g.beginPath(); g.moveTo(px(0), mid); + trace.forEach((v, i) => g.lineTo(px(i), py(v))); + g.lineTo(px(trace.length - 1), mid); g.closePath(); g.fillPath(); + g.lineStyle(2.5, 0xb8321e, 1); + g.beginPath(); + trace.forEach((v, i) => (i ? g.lineTo(px(i), py(v)) : g.moveTo(px(i), py(v)))); + g.strokePath(); + } + const cursorG = add(scene.add.graphics().setDepth(D1 + 1)); + ly = sy + sh + 40; + + // the Master's notes + add(scene.add.text(lx, ly, 'THE MASTER\'S NOTES', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#7a2414' }).setOrigin(0, 0.5).setDepth(D1)); + ly += 28; + const notesY = ly; + const waiting = add(scene.add.text(lx, notesY, review ? 'He is going over your moves with a fresh cup…' : 'No notes for this one.', { + fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#5a4a32', wordWrap: { width: 560 }, + }).setOrigin(0, 0).setDepth(D1)); + ly += 3 * 48 + 12; + if (record) { + add(scene.add.text(lx, Math.min(ly, y + h - 118), `Your record against ${oppName}: ${record.w} won · ${record.d} drawn · ${record.l} lost`, { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#3a2a1a' }).setOrigin(0, 0.5).setDepth(D1)); + } + + // ── right: replay board ── + const size = gs.size, RS = Math.floor(368 / size), BW = RS * size; + const rx = x + w - 70 - BW, ry = y + 172; + add(scene.add.text(rx + BW / 2, ry - 22, 'REPLAY', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#7a2414' }).setOrigin(0.5).setDepth(D1)); + const bg = add(scene.add.graphics().setDepth(D1)); + bg.fillStyle(0x140c0a, 1).fillRoundedRect(rx - 10, ry - 10, BW + 20, BW + 20, 6); + bg.fillStyle(0x1d6440, 1).fillRect(rx, ry, BW, BW); + bg.lineStyle(1.5, 0x06200e, 1); + for (let i = 0; i <= size; i++) { bg.lineBetween(rx + i * RS, ry, rx + i * RS, ry + BW); bg.lineBetween(rx, ry + i * RS, rx + BW, ry + i * RS); } + const pg = add(scene.add.graphics().setDepth(D1 + 1)); + const label = add(scene.add.text(rx + BW / 2, ry + BW + 30, '', { fontFamily: SERIF, fontSize: '17px', color: '#2a1a10', align: 'center' }).setOrigin(0.5).setDepth(D1)); + let n = gs.history.length; + let mark = null; // { best, played } shown on the board + const cell = (sq) => ({ x: rx + (sq % size) * RS + RS / 2, y: ry + Math.floor(sq / size) * RS + RS / 2 }); + const draw = () => { + pg.clear(); + const b = boardAfter(gs, n); + b.forEach((v, sq) => { + if (!v) return; + const p = cell(sq); + pg.fillStyle(0x000000, 0.35).fillCircle(p.x + 1.5, p.y + 2.5, RS * 0.4); + pg.fillStyle(v === 'black' ? 0x1c1b22 : 0xf2eee2, 1).fillCircle(p.x, p.y, RS * 0.4); + pg.lineStyle(1.2, v === 'black' ? 0x4a4858 : 0xb8ae96, 0.9).strokeCircle(p.x, p.y, RS * 0.3); + }); + let last = null; + for (let i = n - 1; i >= 0; i--) { if (!gs.history[i].pass) { last = gs.history[i]; break; } } + const lastEntry = n > 0 ? gs.history[n - 1] : null; + if (last && lastEntry && !lastEntry.pass) { const p = cell(last.sq); pg.fillStyle(0xd8402a, 1).fillCircle(p.x, p.y, Math.max(3, RS * 0.09)); } + if (mark && mark.at === n) { + const pb = cell(mark.best), pp = cell(mark.played); + pg.lineStyle(3, 0x40d070, 1).strokeCircle(pb.x, pb.y, RS * 0.42); + pg.lineStyle(3, 0xe04030, 1); + pg.lineBetween(pp.x - RS * 0.25, pp.y - RS * 0.25, pp.x + RS * 0.25, pp.y + RS * 0.25); + pg.lineBetween(pp.x + RS * 0.25, pp.y - RS * 0.25, pp.x - RS * 0.25, pp.y + RS * 0.25); + } + const desc = !lastEntry ? (gs.opening ? `Start · ${gs.opening.name}` : 'Starting position') + : lastEntry.pass ? `${cap(lastEntry.color)} passes` + : `${cap(lastEntry.color)} ${lastEntry.n}${lastEntry.book ? ' (card)' : ''} · flips ${lastEntry.flips.length}`; + const cc = (() => { const bb = boardAfter(gs, n); let k = 0, wh = 0; bb.forEach((v) => { if (v === 'black') k++; else if (v === 'white') wh++; }); return `${k}–${wh}`; })(); + label.setText(`Move ${n} of ${gs.history.length}: ${desc}\n${mark && mark.at === n ? 'green ring: the Master\'s move · red cross: yours' : `Black–White ${cc}`}`); + cursorG.clear(); + cursorG.lineStyle(2, 0x2a4a6a, 0.8).lineBetween(px(n), sy + 6, px(n), sy + 6 + sh); + }; + draw(); + const by = ry + BW + 84; + const step = (d) => { n = Math.max(0, Math.min(gs.history.length, n + d)); draw(); }; + const cxr = rx + BW / 2; + add(new Button(scene, cxr - 165, by, '|◀', () => { n = 0; draw(); }, { width: 70, height: 42, fontSize: 18, bg: 0x3a2216 }).setDepth(D1 + 1)); + add(new Button(scene, cxr - 80, by, '◀', () => step(-1), { width: 80, height: 42, fontSize: 18, bg: 0x3a2216 }).setDepth(D1 + 1)); + add(new Button(scene, cxr + 10, by, '▶', () => step(1), { width: 80, height: 42, fontSize: 18, bg: 0x3a2216 }).setDepth(D1 + 1)); + add(new Button(scene, cxr + 95, by, '▶|', () => { n = gs.history.length; draw(); }, { width: 70, height: 42, fontSize: 18, bg: 0x3a2216 }).setDepth(D1 + 1)); + const keys = (e) => { if (e.key === 'ArrowLeft') step(-1); else if (e.key === 'ArrowRight') step(1); }; + scene.input.keyboard?.on('keydown', keys); + + // the match, under the replay + if (multi) { + let my = by + 40; + add(scene.add.text(rx - 40, my, 'THE MATCH', { fontFamily: DISPLAY_FONT, fontSize: '15px', color: '#7a2414' }).setOrigin(0, 0.5).setDepth(D1)); + my += 22; + match.results.forEach((r, i) => { + const res = r.result === 'human' ? 'You won' : r.result === 'ai' ? `${oppName} won` : 'Draw'; + const col = r.result === 'human' ? '#1f6a3a' : r.result === 'ai' ? '#8e1c16' : '#3a2a1a'; + add(scene.add.text(rx - 40, my, `Game ${i + 1} · you ${r.humanColor} · ${res} · ${r.score}${r.opening ? ` · ${r.opening}` : ''}`, { fontFamily: SERIF, fontSize: '15px', color: col }).setOrigin(0, 0.5).setDepth(D1)); + my += 22; + }); + } + + // notes arrive from the engine + if (review) { + review.then((list) => { + if (closed) return; + const notes = (list ?? []).filter((r) => r.loss >= 150 || (r.exact && Math.sign(r.bestScore) !== Math.sign(r.playedScore))) + .sort((a, b) => b.loss - a.loss).slice(0, 3).sort((a, b) => a.i - b.i); + if (!notes.length) { waiting.setText('Not a move I would change. Clean game.'); return; } + waiting.setText(''); + notes.forEach((r, k) => { + const before = boardAfter(gs, r.i); + const turn = gs.history[r.i]?.color ?? humanColor; + const why = describeMistake({ size, variant: gs.variant, board: before, turn }, r.played, r.best); + const moveNo = gs.history.slice(0, r.i + 1).filter((h) => !h.pass).length; + const t = add(scene.add.text(lx, notesY + k * 48, `Move ${moveNo}: you played ${notate(r.played, size)}, I'd have played ${notate(r.best, size)}. ${cap(why)}.`, { + fontFamily: SERIF, fontSize: '16px', color: '#2a1a10', wordWrap: { width: 560 }, lineSpacing: 2, + }).setOrigin(0, 0).setDepth(D1).setInteractive({ useHandCursor: true })); + t.on('pointerover', () => t.setColor('#a0221c')); + t.on('pointerout', () => t.setColor('#2a1a10')); + t.on('pointerdown', () => { n = r.i; mark = { at: r.i, best: r.best, played: r.played }; draw(); }); + }); + }).catch(() => { if (!closed) waiting.setText('He lost his place in the notebook. No notes tonight.'); }); + } + + const bty = y + h - 60; + let hRef = null; + add(new Button(scene, x + w / 2 - 140, bty, multi ? 'New Match' : 'Play Again', () => { hRef.close(); onPlayAgain(); }, { width: 250, height: 52, fontSize: 20, bg: 0x1f6a3a }).setDepth(D1 + 1)); + add(new Button(scene, x + w / 2 + 140, bty, 'Leave the Kissa', () => { hRef.close(); onMenu(); }, { width: 250, height: 52, fontSize: 20, bg: 0x7a1a14 }).setDepth(D1 + 1)); + hRef = handle(objs, () => { closed = true; scene.input.keyboard?.off('keydown', keys); }); + return hRef; +} diff --git a/src/games/othello/OthelloEngine.js b/src/games/othello/OthelloEngine.js new file mode 100644 index 0000000..5d273c0 --- /dev/null +++ b/src/games/othello/OthelloEngine.js @@ -0,0 +1,79 @@ +// OthelloEngine.js: runs OthelloAI off the main thread so the kissa keeps +// moving (the record turning, rain on the glass) while an opponent thinks. +// +// handle(kind, payload) the actual work (shared by the worker and the +// synchronous fallback) +// class Engine main-thread client: request(kind, payload) → +// Promise. Uses a module Worker (OthelloWorker.js); +// if that can't start, runs the same code inline. +// +// Kinds (pos = { size, variant, board, turn }): +// move { pos, skill, line } → { sq, score, book, exact } +// hint { pos, ms } → { sq, score, exact, depth } +// rank { pos, depth, ms } → [{ sq, score }] best first +// review { size, variant, positions, ms } → [{ i, best, played, loss, … }] + +import * as AI from './OthelloAI.js'; + +export function handle(kind, p) { + switch (kind) { + case 'move': return AI.chooseMove(p.pos, p.skill, { line: p.line ?? null }); + case 'hint': return AI.hint(p.pos, { ms: p.ms ?? 700 }); + case 'rank': return AI.rankMoves(p.pos, { depth: p.depth ?? 4, ms: p.ms ?? 300 }); + case 'review': return AI.review(p.positions, { ms: p.ms ?? 140, size: p.size, variant: p.variant }); + default: return null; + } +} + +export class Engine { + constructor() { + this.seq = 0; + this.pending = new Map(); + this.worker = null; + try { + if (typeof Worker !== 'undefined') { + this.worker = new Worker(new URL('./OthelloWorker.js', import.meta.url), { type: 'module' }); + this.worker.onmessage = (e) => this.settle(e.data); + this.worker.onerror = (e) => { e?.preventDefault?.(); this.fallBack(); }; + } + } catch (_) { this.worker = null; } + } + + settle({ id, res, err }) { + const job = this.pending.get(id); + if (!job) return; + this.pending.delete(id); + if (err) job.reject(new Error(err)); else job.resolve(res); + } + + fallBack() { + // the worker couldn't start (or died): finish everything inline + try { this.worker?.terminate(); } catch (_) { /* */ } + this.worker = null; + for (const [id, job] of this.pending) this.runInline(id, job.kind, job.payload); + } + + runInline(id, kind, payload) { + setTimeout(() => { + let res = null, err = null; + try { res = handle(kind, payload); } catch (e) { err = String(e?.message ?? e); } + this.settle({ id, res, err }); + }, 0); + } + + request(kind, payload) { + const id = ++this.seq; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject, kind, payload }); + if (this.worker) { + try { this.worker.postMessage({ id, kind, payload }); } catch (_) { this.fallBack(); } + } else this.runInline(id, kind, payload); + }); + } + + destroy() { + try { this.worker?.terminate(); } catch (_) { /* */ } + this.worker = null; + this.pending.clear(); + } +} diff --git a/src/games/othello/OthelloGame.js b/src/games/othello/OthelloGame.js index 5f43513..add2d4b 100644 --- a/src/games/othello/OthelloGame.js +++ b/src/games/othello/OthelloGame.js @@ -1,504 +1,1066 @@ +// OthelloGame.js: "Kissa Kuro-Shiro", a jazz coffee house on a rainy +// Tokyo night. The scene only orchestrates: rules in OthelloLogic, the +// opponents in OthelloAI (run in a worker via OthelloEngine), the book in +// OthelloBook, geometry in OthelloLayout, art in OthelloArt, discs in +// OthelloPieces, furniture in OthelloHud, talk in OthelloTalk, sound in +// OthelloSound. +// +// Flow: the setup card (colour, match length, board size, rules, opening) +// → each game: the four discs drop, the side with the move plays. On your +// turn hover a marked square to preview the flips, click to play (or use +// the arrow keys and Enter). A disc is thrown from your tray and the +// captured lines turn over one after another. Undo rewinds your last turn; +// Hint asks the Master. If you have no move, a card says so and you pass. +// At the end the discs are counted out; after a match, a summary with the +// Master's notes and a replay board. Everything in progress is saved, so a +// reload resumes. +// +// Every async step carries the game's token: starting a new game, undoing +// or opening the setup card bumps it, and anything still in flight from +// before (animations, the engine's reply) is dropped. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { getGameSoundtrack } from '../../services/soundtrack.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { aiTiming, PACE } from '../../ui/cardtable/AITiming.js'; +import * as L from './OthelloLogic.js'; +import { clampSkill, describeIdea, givesCorner, exactMargin } from './OthelloAI.js'; +import { Engine } from './OthelloEngine.js'; +import { openingName, openingCard } from './OthelloBook.js'; import { - SIZE, other, createInitialState, getValidMoves, getFlips, applyMove, - mustPass, isGameOver, getScore, getWinner, -} from './OthelloLogic.js'; -import { chooseMove, nextThinkDelay } from './OthelloAI.js'; + BX, BY, BOARD, BCX, BANNER, WINDOW, NEON, PLATTER, SIPHON, CUP, geom, squareXY, cellAt, +} from './OthelloLayout.js'; +import { prepareOthelloArt, ensureBoard, DISPLAY_FONT, BOLD_FONT, BOARD_POS, RES } from './OthelloArt.js'; +import { DiscSet } from './OthelloPieces.js'; +import { Hud } from './OthelloHud.js'; +import { openPauseMenu, openSetup, confirmBox, toast } from './OthelloDialogs.js'; +import { openEndScreen, openBetween, resultLine } from './OthelloEndScreen.js'; +import { masterLine, opponentLine, tierOf } from './OthelloTalk.js'; +import { clack, flip as flipSnd, slide, deny, chime, sting, Ambience } from './OthelloSound.js'; -// ── Layout ───────────────────────────────────────────────────────────────────── -const SQ = 104; -const BOARD = SQ * SIZE; // 832 -const BX = Math.round(GAME_WIDTH / 2 - BOARD / 2); // 544 -const BY = Math.round(GAME_HEIGHT / 2 - BOARD / 2); // 124 -const FRAME = 30; -const CR = Math.round(SQ * 0.40); // disc radius ≈42 - -const DEPTH = { board: 0, piece: 10, hint: 8, overlay: 20, moving: 30, ui: 50, banner: 60 }; - -// ── Colors ───────────────────────────────────────────────────────────────────── -const C = { - felt: 0x1e6b3e, // classic Othello board green - feltDk: 0x185930, // grid lines - frame: 0x3a2414, - frameLt: 0x6b4423, - frameLn: 0x8b5c2a, - bFill: 0x1c1a26, - bRing: 0x3a3848, - bEdge: 0x0d0c14, - wFill: 0xf4f0e0, - wRing: 0xfffaf0, - wEdge: 0xc8b894, - hint: 0x80ff80, - selGold: 0xffd700, +const SETTINGS_KEY = 'othello-settings'; +const SAVE_KEY = 'othello-save-v1'; +const RECORD_KEY = 'othello-record'; +const DEFAULT_SETTINGS = { + pace: 'normal', skipAI: false, hints: true, preview: true, coach: true, + danger: false, mobility: false, stable: false, ambience: true, + setup: { color: 'black', games: 1, size: 8, start: 'standard', variant: 'standard' }, }; +const D = { bg: 0, board: 5, study: 7, mark: 8, piece: 10, over: 12, ghost: 13, cursor: 42, hud: 50, fx: 70, banner: 80, end: 95, modal: 110 }; export default class OthelloGame extends Phaser.Scene { constructor() { super('OthelloGame'); } init(data) { - this._initData = { ...data }; - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.gs = null; - this.animating = false; - this.discObjs = []; // discObjs[r][c] = Graphics | null - this.hintObjs = []; // hint dot graphics + zones - this.overlayObjs = []; - this.opponentPortrait = null; - this.scoreBlackText = null; - this.scoreWhiteText = null; - this.turnText = null; + this.initData = data ?? {}; + this.gameDef = this.initData.game; + this.opponents = this.initData.opponents ?? []; + this.playfield = this.initData.playfield ?? null; + this.opp = this.opponents[0] ?? { id: 'kissa-regular', name: 'Mr. Kato', skill: 3 }; + this.oppName = this.opp.name ?? 'Opponent'; + this.skill = clampSkill(this.opp.skill ?? 3); + this.tier = tierOf(this.skill); + this.ended = false; + this.busy = true; + this.modal = null; + this.phase = 'setup'; // setup | intro | human | ai | animating | over + this.token = 0; + this.undoStack = []; + this.gs = null; + this.match = null; + this.cursor = null; + this.hover = -1; + this.clocks = { human: 0, ai: 0 }; + this.turnStart = 0; + this.markObjs = []; + this.previewObjs = []; + this.hintObjs = []; + this.saidEndgame = false; + this.saidIllegal = false; + try { + const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + this.settings = { ...DEFAULT_SETTINGS, ...s, setup: { ...DEFAULT_SETTINGS.setup, ...(s.setup ?? {}) } }; + } catch (_) { this.settings = { ...DEFAULT_SETTINGS, setup: { ...DEFAULT_SETTINGS.setup } }; } } + get k() { return PACE[this.settings.pace] ?? 1; } + get humanColor() { return this.match?.humanColor ?? L.BLACK; } + get aiColor() { return L.other(this.humanColor); } + get size() { return this.gs?.size ?? this.settings.setup.size ?? 8; } + create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildParticleTexture(); - this.buildPlayfield(); - this.buildBoard(); - this.buildUI(); - this.buildPlayerCards(); - this.initGame(); + const { tracks, volume } = getGameSoundtrack(this); + if (tracks.length) new MusicPlayer(this, tracks, volume); + this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x0a0606).setDepth(-2); + prepareOthelloArt(this).then(() => { + if (!this.sys.isActive()) return; + this.build(); + this.begin(); + }); } - // ── Construction ────────────────────────────────────────────────────────────── - - buildParticleTexture() { - const g = this.make.graphics({ x: 0, y: 0, add: false }); - g.fillStyle(0xffffff, 1); - g.fillCircle(5, 5, 5); - g.generateTexture('othelloParticle', 10, 10); - g.destroy(); - } - - buildPlayfield() { + // ── build ─────────────────────────────────────────────────────────────────── + build() { const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(DEPTH.board - 2); - } else if (pf?.fallbackColor) { - const color = parseInt(pf.fallbackColor.replace('#', ''), 16); - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, color) - .setDepth(DEPTH.board - 2); + this.fullRoom = !(pf?.key && this.textures.exists(pf.key) && !pf.key.startsWith('playfield-colored-')); + if (!this.fullRoom) { + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg); + this.add.image(0, 0, 'ot-vignette').setOrigin(0).setDepth(D.bg + 1); + this.add.image(0, 0, 'ot-props').setOrigin(0).setDepth(D.bg + 2); + } else { + this.add.image(0, 0, 'ot-room').setOrigin(0).setDepth(D.bg); } + this.boardImg = this.add.image(BOARD_POS.x, BOARD_POS.y, ensureBoard(this, this.size)).setOrigin(0).setDepth(D.board); + + this.studyG = this.add.graphics().setDepth(D.study); + this.overG = this.add.graphics().setDepth(D.over); + this.lastG = this.add.graphics().setDepth(D.over + 0.5); + this.previewG = this.add.graphics().setDepth(D.ghost); + this.cursorG = this.add.graphics().setDepth(D.cursor); + + this.discs = new DiscSet(this, D.piece); + const name = auth.user?.username ?? 'You'; + this.hud = new Hud(this, D.hud, { + names: { top: this.oppName, bottom: name }, skill: this.skill, opponent: this.opp, + onButton: (k) => this.onButton(k), + }).build(); + + this.engine = new Engine(); + this.ambienceFx(); + this.ambience = new Ambience(this); + if (this.settings.ambience) this.ambience.start(); + + this.input.on('pointerdown', (p) => this.onPointerDown(p)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this.time.addEvent({ delay: 1000, loop: true, callback: () => { if (this.gs && !['over', 'setup'].includes(this.phase)) this.refreshHud(); } }); + this.events.once('shutdown', () => { + this.ended = true; + this.token++; + this.ambience?.stop(); + this.engine?.destroy(); + this.setCursor('default'); + }); } - buildBoard() { - const g = this.add.graphics().setDepth(DEPTH.board); - - // Wood frame - g.fillStyle(C.frame, 1); - g.fillRoundedRect(BX - FRAME, BY - FRAME, BOARD + FRAME * 2, BOARD + FRAME * 2, 12); - g.lineStyle(3, C.frameLt, 1); - g.strokeRoundedRect(BX - FRAME + 5, BY - FRAME + 5, BOARD + FRAME * 2 - 10, BOARD + FRAME * 2 - 10, 9); - g.lineStyle(1, C.frameLn, 0.6); - g.strokeRect(BX - 2, BY - 2, BOARD + 4, BOARD + 4); - - // Felt background - g.fillStyle(C.felt, 1); - g.fillRect(BX, BY, BOARD, BOARD); - - // Grid lines - g.lineStyle(1, C.feltDk, 0.7); - for (let i = 0; i <= SIZE; i++) { - g.lineBetween(BX + i * SQ, BY, BX + i * SQ, BY + BOARD); - g.lineBetween(BX, BY + i * SQ, BX + BOARD, BY + i * SQ); - } - - // Star dots at the four quadrant corners (traditional Othello marks) - g.fillStyle(C.feltDk, 0.9); - for (const [r, c] of [[2,2],[2,5],[5,2],[5,5]]) { - const { x, y } = this.sqToWorld(r, c); - g.fillCircle(x, y, 6); - } - - // Subtle center lines marking the 2×2 starting area - g.lineStyle(1, 0xffffff, 0.12); - const mid = BX + BOARD / 2; - g.lineBetween(mid, BY, mid, BY + BOARD); - g.lineBetween(BX, BY + BOARD / 2, BX + BOARD, BY + BOARD / 2); - - // Coordinate labels - for (let c = 0; c < SIZE; c++) { - this.add.text(BX + c * SQ + SQ / 2, BY + BOARD + 16, String.fromCharCode(65 + c), { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.board); - } - for (let r = 0; r < SIZE; r++) { - this.add.text(BX - 16, BY + r * SQ + SQ / 2, String(SIZE - r), { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.board); - } + ambienceFx() { + // the record turns and the siphon bubbles whatever the backdrop + this.record = this.add.image(PLATTER.x, PLATTER.y, 'ot-record').setDepth(D.bg + 3); + this.add.image(PLATTER.x, PLATTER.y, 'ot-record-sheen').setDepth(D.bg + 4); + const flame = this.add.image(SIPHON.x, SIPHON.y + 30, 'ot-flame').setDepth(D.bg + 3).setScale(0.7, 1).setBlendMode(Phaser.BlendModes.ADD); + this.tweens.add({ targets: flame, scaleY: { from: 0.8, to: 1.15 }, alpha: { from: 0.75, to: 1 }, duration: 140, yoyo: true, repeat: -1 }); + this.time.addEvent({ delay: 260, loop: true, callback: () => { + if (this.ended) return; + const b = this.add.image(SIPHON.x + (Math.random() - 0.5) * 30, SIPHON.y + 18, 'ot-bubble').setDepth(D.bg + 3).setScale(0.4 + Math.random() * 0.6).setAlpha(0.8); + this.tweens.add({ targets: b, y: SIPHON.y - 14 - Math.random() * 10, alpha: 0, duration: 700 + Math.random() * 500, ease: 'Sine.In', onComplete: () => b.destroy() }); + } }); + this.time.addEvent({ delay: 800, loop: true, callback: () => { + if (this.ended) return; + const st = this.add.image(CUP.x + (Math.random() - 0.5) * 12, CUP.y - 8, 'ot-steam').setDepth(D.bg + 3).setAlpha(0).setScale(0.3); + this.tweens.add({ targets: st, y: st.y - 90 - Math.random() * 30, x: st.x + (Math.random() - 0.5) * 40, alpha: { from: 0.3, to: 0 }, scale: 1.2, duration: 2600, ease: 'Sine.Out', onComplete: () => st.destroy() }); + } }); + if (!this.fullRoom) return; + // the sign across the street, buzzing + const neon = this.add.image(NEON.x, NEON.y + 44, 'ot-neon-glow').setScale(0.7, 1.4).setDepth(D.bg + 2).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.6); + this.tweens.add({ targets: neon, alpha: { from: 0.45, to: 0.7 }, duration: 1900, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.time.addEvent({ delay: 4200, loop: true, callback: () => { + if (this.ended || Math.random() < 0.5) return; + this.tweens.add({ targets: neon, alpha: 0.05, duration: 50, yoyo: true, repeat: 1 + Math.floor(Math.random() * 3) }); + } }); + // rain streaking down the glass + this.time.addEvent({ delay: 90, loop: true, callback: () => { + if (this.ended) return; + const x = WINDOW.x + 6 + Math.random() * (WINDOW.w - 12); + const y = WINDOW.y + Math.random() * WINDOW.h * 0.5; + const len = 40 + Math.random() * 120; + const d = this.add.image(x, y, 'ot-rain').setDepth(D.bg + 3).setAlpha(0.15 + Math.random() * 0.35).setScale(1, 0.6 + Math.random() * 0.8); + this.tweens.add({ targets: d, y: Math.min(WINDOW.y + WINDOW.h - 14, y + len), alpha: 0, duration: 380 + Math.random() * 500, ease: 'Quad.In', onComplete: () => d.destroy() }); + } }); } - buildUI() { - const cx = BX + BOARD / 2; - this.turnText = this.add.text(cx, BY + BOARD + 52, '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); - - new Button(this, BX + BOARD + FRAME + 90, BY + 60, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 150, height: 46, fontSize: 20 }).setDepth(DEPTH.ui); - - new Button(this, BX + BOARD + FRAME + 90, BY + 124, 'New', - () => this.initGame(), - { variant: 'ghost', width: 150, height: 46, fontSize: 20 }).setDepth(DEPTH.ui); + update(_t, dt) { + if (this.record) this.record.rotation += dt * 0.0035; // 33⅓ rpm } - buildPlayerCards() { - const opp = this.opponents[0]; - const r = 78; - const depth = DEPTH.ui; - const avatarX = BX / 2; - - // Opponent (white discs) — top card - const oppAY = BY + r + 20; - this.add.circle(avatarX, oppAY, r + 5, C.frame).setDepth(depth); - this.opponentPortrait = createOpponentPortrait(this, opp, avatarX, oppAY, r, depth + 1); - this.add.text(avatarX, oppAY + r + 14, opp?.name ?? 'CPU', { - fontFamily: '"Julius Sans One"', fontSize: '18px', - color: COLORS.textHex, wordWrap: { width: 230 }, align: 'center', - }).setOrigin(0.5, 0).setDepth(depth + 2); - - this.scoreWhiteText = this.add.text(avatarX, oppAY + r + 56, '2', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(depth + 2); - - // Player (black discs) — bottom card - const plrAY = BY + BOARD - r - 20; - this.add.circle(avatarX, plrAY, r + 5, COLORS.accent, 0.5).setDepth(depth); - createPlayerPortrait(this, avatarX, plrAY, r, depth + 1, 'Othello'); - this.add.text(avatarX, plrAY - r - 14, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '18px', - color: COLORS.textHex, wordWrap: { width: 230 }, align: 'center', - }).setOrigin(0.5, 1).setDepth(depth + 2); - - this.scoreBlackText = this.add.text(avatarX, plrAY - r - 56, '2', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(depth + 2); + // ── start / resume / save ─────────────────────────────────────────────────── + begin() { + const save = this.loadSave(); + if (save) { + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'Pick up where you left off?', + text: `There's a game in progress against ${this.oppName}. The discs are where you left them.`, + yes: 'Resume', no: 'Start Fresh', yesBg: 0x1f6a3a, depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); this.resume(save); }, + onNo: () => { this.modal = null; this.clearSave(); this.openSetupCard(); }, + }); + } else this.openSetupCard(); } - playOpponentEmotion(emotion) { this.opponentPortrait?.playEmotion(emotion); } + signature() { return `${this.opp.id ?? this.oppName}|${this.skill}`; } - // ── Game flow ───────────────────────────────────────────────────────────────── + loadSave() { + try { + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 1 || s.sig !== this.signature() || !s.gs || !s.match) return null; + return s; + } catch (_) { return null; } + } - initGame() { - this.clearDiscs(); - this.clearHints(); + save(between = false) { + if (!this.gs || !this.match) return; + try { + localStorage.setItem(SAVE_KEY, JSON.stringify({ + v: 1, sig: this.signature(), gs: this.gs, match: this.match, clocks: this.clocks, between, savedAt: Date.now(), + })); + } catch (_) { /* private mode */ } + } + + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + + resume(save) { + const tok = ++this.token; + this.held = null; + this.match = save.match; + this.gs = save.gs; + this.clocks = save.clocks ?? { human: 0, ai: 0 }; + this.undoStack = []; + this.boardImg.setTexture(ensureBoard(this, this.size)); + this.discs.build(this.gs.board, this.size); + this.hud.masterSays(masterLine('welcomeBack')); + if (save.between) { this.phase = 'over'; this.betweenGames(); return; } + this.refreshHud(); + this.drawLast(); + this.nextTurn(tok); + } + + openSetupCard() { + this.token++; + this.held = null; + this.phase = 'setup'; + this.busy = true; this.clearOverlays(); - this.animating = false; - this.gs = createInitialState(); - this.renderAll(); - this.showTurnBanner('Your Turn — Black'); + this.hud.hidePortraits(); + this.hud.setStatus('Kissa Kuro-Shiro', 'Choose your colour and sit down.'); + this.hud.masterSays(masterLine('welcome')); + this.modal = openSetup(this, { + prefs: this.settings.setup, depth: D.modal, opponentName: this.oppName, + onStart: (p) => { + this.modal = null; + this.hud.showPortraits(); + this.settings.setup = { ...p }; + this.persistSettings(); + this.startMatch(p); + }, + onLeave: () => this.scene.start('GameMenu'), + }); } - renderAll() { - this.clearDiscs(); - this.clearHints(); - this.renderDiscs(); - this.updateScore(); - this.updateTurnText(); - if (this.gs.phase === 'playing' && this.gs.turn === 'black' && !this.animating) { - this.showValidHints(); + startMatch(p) { + const color = p.color === 'random' ? (Math.random() < 0.5 ? L.BLACK : L.WHITE) : p.color; + this.match = { + games: p.games, size: p.size, variant: p.variant, card: p.start === 'card' && p.size === 8 && p.variant === 'standard', + firstColor: color, humanColor: color, results: [], cards: [], human: 0, ai: 0, + }; + this.hud.say(opponentLine('greet', this.tier)); + this.startGame(); + } + + async startGame() { + const tok = ++this.token; + this.held = null; + const m = this.match; + const idx = m.results.length; + m.humanColor = idx % 2 === 0 ? m.firstColor : L.other(m.firstColor); + let card = null; + if (m.card) { + const pair = Math.floor(idx / 2); + if (!m.cards[pair]) m.cards[pair] = openingCard(Math.random, m.cards.map((c) => c.name)); + card = m.cards[pair]; } - } - - updateTurnText() { - if (!this.turnText) return; - if (this.gs.phase === 'game_over') { this.turnText.setText(''); return; } - this.turnText.setText(this.gs.turn === 'black' ? 'Your move' : 'Opponent thinking…'); - } - - updateScore() { - const { black, white } = getScore(this.gs); - this.scoreBlackText?.setText(String(black)); - this.scoreWhiteText?.setText(String(white)); - } - - // ── Disc rendering ──────────────────────────────────────────────────────────── - - sqToWorld(r, c) { return { x: BX + c * SQ + SQ / 2, y: BY + r * SQ + SQ / 2 }; } - - clearDiscs() { - if (this.discObjs.length) { - for (const row of this.discObjs) - for (const g of row) { if (g) { this.tweens.killTweensOf(g); g.destroy(); } } - } - this.discObjs = Array.from({ length: SIZE }, () => Array(SIZE).fill(null)); - } - - renderDiscs() { - for (let r = 0; r < SIZE; r++) { - for (let c = 0; c < SIZE; c++) { - const cell = this.gs.board[r][c]; - if (!cell) continue; - const { x, y } = this.sqToWorld(r, c); - const g = this.add.graphics().setPosition(x, y).setDepth(DEPTH.piece); - this.drawDiscGraphics(g, cell); - this.discObjs[r][c] = g; + this.gs = L.createGame({ size: m.size, variant: m.variant }); + this.undoStack = []; + this.clocks = { human: 0, ai: 0 }; + this.saidEndgame = false; + this.cursor = null; + this.clearOverlays(); + this.boardImg.setTexture(ensureBoard(this, this.size)); + this.discs.build(Array(this.size * this.size).fill(null), this.size); + this.phase = 'intro'; + this.busy = true; + this.refreshHud(); + this.hud.setStatus('Setting up', `${L.VARIANTS[m.variant].name} · ${L.SIZE_INFO[m.size].name}${m.games > 1 ? ` · game ${idx + 1} of up to ${m.games}` : ''}`); + if (idx > 0) this.hud.masterSays(masterLine('newGame')); + // the starting four + const start = this.gs.board.map((v, sq) => [sq, v]).filter(([, v]) => v); + await Promise.all(start.map(([sq, v], i) => this.discs.drop(sq, v, { delay: i * 140 * this.k }).then(() => { if (!this.stale(tok)) clack(this, { vol: 0.07 }); }))); + if (this.stale(tok)) return; + const you = this.humanColor === L.BLACK ? 'Black' : 'White'; + this.banner(`You play ${you}`, this.humanColor === L.BLACK ? 0xc8c4d8 : 0xf6f2e6, 0.6, true); + await this.wait(900 * this.k); + if (this.stale(tok)) return; + if (card) { + this.hud.masterSays(masterLine('card', { name: card.name }), { hold: 9000 }); + this.banner(card.name, 0xf0d890, 0.55, true); + await this.wait(700 * this.k); + for (const n of card.moves) { + if (this.stale(tok)) return; + const sq = L.parseSq(n, 8); + await this.playMove(sq, tok, { fast: true, book: true, quiet: true }); } + if (this.stale(tok)) return; + this.gs.opening = { name: card.name }; + this.refreshHud(); + } else if (m.variant === 'anti') { + this.hud.masterSays(masterLine('anti')); + } else if (m.size !== 8) { + this.hud.masterSays(masterLine(m.size === 6 ? 'size6' : 'size10')); + } else if (idx === 0) { + this.hud.masterSays(this.humanColor === L.BLACK ? 'Black moves first. That\'s you.' : `${this.oppName} has black. They move first.`); } + this.save(); + this.nextTurn(tok); } - drawDiscGraphics(g, color) { - g.clear(); - const fill = color === 'black' ? C.bFill : C.wFill; - const ring = color === 'black' ? C.bRing : C.wRing; - const edge = color === 'black' ? C.bEdge : C.wEdge; - const hi = color === 'black' ? 0x5a5870 : 0xffffff; + stale(tok) { return this.ended || tok !== this.token; } - g.fillStyle(0x000000, 0.30); - g.fillCircle(3, 5, CR); - g.fillStyle(edge, 1); - g.fillCircle(0, 0, CR); - g.fillStyle(ring, 1); - g.fillCircle(0, 0, CR - 3); - g.fillStyle(fill, 1); - g.fillCircle(0, 0, CR - 8); - g.lineStyle(2, edge, 0.4); - g.strokeCircle(0, 0, CR - 14); - // Top-left sheen arc - g.lineStyle(3, hi, 0.55); - g.beginPath(); - g.arc(0, 0, CR - 12, Phaser.Math.DegToRad(200), Phaser.Math.DegToRad(320)); - g.strokePath(); + // ── HUD ───────────────────────────────────────────────────────────────────── + refreshHud(thinking = false) { + if (!this.gs) return; + const live = { ...this.clocks }; + if (this.phase === 'human') live.human += Date.now() - this.turnStart; + else if (this.phase === 'ai') live.ai += Date.now() - this.turnStart; + this.hud.refresh(this.gs, { + humanColor: this.humanColor, thinking: thinking || this.phase === 'ai', clocks: live, intro: this.phase === 'intro', + match: this.match ? { games: this.match.games, human: this.match.human, ai: this.match.ai } : null, + held: this.held ?? null, + }); + const mine = this.canMoveNow(); + this.hud.setButton('undo', mine && this.undoStack.length > 0); + this.hud.setButton('hint', mine); + this.hud.setButton('resign', mine && this.gs.ply >= 4); } - // ── Valid move hints ────────────────────────────────────────────────────────── + setStatus(a, b = '') { this.hud?.setStatus(a, b); } - clearHints() { - for (const o of this.hintObjs) o.destroy(); - this.hintObjs = []; + /** Book line so far (for the engine and the opening name). */ + bookLine() { + if (this.gs.size !== 8 || this.gs.variant !== 'standard') return null; + return L.placed(this.gs).map((h) => h.n); + } + + // ── board marks ───────────────────────────────────────────────────────────── + clearMarks() { + for (const o of this.markObjs) o.destroy(); + this.markObjs = []; } clearOverlays() { - for (const o of this.overlayObjs) o.destroy(); - this.overlayObjs = []; + this.clearMarks(); + this.clearPreview(); + this.clearHint(); + this.studyG?.clear(); + this.overG?.clear(); + this.lastG?.clear(); + this.cursorG?.clear(); } - showValidHints() { - const moves = getValidMoves(this.gs, 'black'); - for (const { r, c } of moves) { - const { x, y } = this.sqToWorld(r, c); - const dot = this.add.graphics().setDepth(DEPTH.hint); - dot.fillStyle(C.hint, 0.55); - dot.fillCircle(x, y, 16); - dot.lineStyle(2, 0xffffff, 0.35); - dot.strokeCircle(x, y, 16); - this.tweens.add({ targets: dot, alpha: { from: 0.55, to: 0.15 }, duration: 700, yoyo: true, repeat: -1 }); + drawMarks() { + this.clearMarks(); + if (this.phase !== 'human') return; + const { SQ } = geom(this.size); + const moves = L.legalMoves(this.gs); + moves.forEach((m, i) => { + const p = squareXY(m.sq, this.size); + if (this.settings.hints) { + const dot = this.add.image(p.x, p.y, 'ot-dot').setDepth(D.mark).setScale(SQ / 340).setTint(0xfff2c8).setAlpha(0); + this.tweens.add({ targets: dot, alpha: { from: 0, to: 0.55 }, duration: 260, delay: i * 25 }); + this.markObjs.push(dot); + } + if (this.settings.mobility) { + const after = L.applyMove(this.gs, m.sq); + const replies = after.phase === 'playing' && after.turn !== this.humanColor ? L.legalMoves(after).length : 0; + const col = replies <= 3 ? '#a8ffb8' : replies >= 8 ? '#ffb0a0' : '#f3ead2'; + const t = this.add.text(p.x + SQ / 2 - 6, p.y + SQ / 2 - 4, String(replies), { + fontFamily: BOLD_FONT, fontSize: `${Math.round(SQ / 5)}px`, color: col, stroke: '#061a0e', strokeThickness: 3, + }).setOrigin(1, 1).setDepth(D.mark + 1); + this.markObjs.push(t); + } + }); + } - const zone = this.add.zone(x, y, SQ, SQ).setInteractive({ useHandCursor: true }).setDepth(DEPTH.hint + 1); - zone.on('pointerdown', () => this.onSquareClick(r, c)); - this.hintObjs.push(dot, zone); + drawStudy() { + const g = this.studyG, o = this.overG; + g.clear(); o.clear(); + if (!this.gs || this.phase === 'over') return; + const { SQ, R } = geom(this.size); + const size = this.size, b = this.gs.board; + if (this.settings.danger && this.gs.variant === 'standard') { + for (const c of L.corners(size)) { + if (b[c] !== null) continue; + for (let sq = 0; sq < size * size; sq++) { + const x = L.xCorner(sq, size) === c, cc = L.cCorner(sq, size) === c; + if (!x && !cc) continue; + const p = squareXY(sq, size); + g.fillStyle(x ? 0xe04030 : 0xe0a030, x ? 0.22 : 0.13).fillRect(p.x - SQ / 2 + 2, p.y - SQ / 2 + 2, SQ - 4, SQ - 4); + g.lineStyle(2, x ? 0xff6a50 : 0xffc060, 0.5).strokeRect(p.x - SQ / 2 + 4, p.y - SQ / 2 + 4, SQ - 8, SQ - 8); + } + } + } + if (this.settings.stable) { + for (const sq of L.stableDiscs(b, size)) { + const p = squareXY(sq, size); + o.lineStyle(3, 0xe8c46a, 0.85).strokeCircle(p.x, p.y - 3, R * 0.5); + } } } - // ── Move execution ──────────────────────────────────────────────────────────── - - onSquareClick(r, c) { - if (this.animating || this.gs.phase !== 'playing' || this.gs.turn !== 'black') return; - const flips = getFlips(this.gs.board, r, c, 'black'); - if (flips.length === 0) return; - this.clearHints(); - this.executeMove(r, c, 'black', flips); + drawLast() { + const g = this.lastG; + g.clear(); + const h = this.gs ? [...this.gs.history].reverse().find((x) => !x.pass) : null; + if (!h || this.phase === 'over') return; + const p = squareXY(h.sq, this.size); + const { R } = geom(this.size); + g.fillStyle(0xd8402a, 1).fillCircle(p.x, p.y - 3, Math.max(4, R * 0.13)); + g.lineStyle(1.5, 0x000000, 0.4).strokeCircle(p.x, p.y - 3, Math.max(4, R * 0.13)); } - executeMove(r, c, color, flips) { - this.animating = true; - this.updateTurnText(); - - // Place new disc with spring scale-in - const { x, y } = this.sqToWorld(r, c); - const g = this.add.graphics().setPosition(x, y).setDepth(DEPTH.moving); - this.drawDiscGraphics(g, color); - g.setScale(0); - this.discObjs[r][c] = g; - - this.tweens.add({ - targets: g, scaleX: 1.18, scaleY: 1.18, duration: 90, ease: 'Quad.easeOut', - onComplete: () => { - this.tweens.add({ targets: g, scaleX: 1, scaleY: 1, duration: 70, ease: 'Quad.easeIn' }); - }, - }); - - playSound(this, SFX.PIECE_CLICK); - - // Cascade flip animation, then update state - this.animateFlips(r, c, flips, color, () => { - this.gs = applyMove(this.gs, { r, c }); - this.animating = false; - - if (flips.length > 0) { - this.playOpponentEmotion(color === 'black' ? 'upset' : 'happy'); - } - - this.renderAll(); - - if (isGameOver(this.gs)) { this.onGameOver(); return; } - - if (color === 'black' && this.gs.turn === 'black') { - // White AI has no valid moves — skip it, human goes again - const name = this.opponents[0]?.name ?? 'Opponent'; - this.showTurnBanner(`${name} has no moves — passing`); - // renderAll() already showed hints for black - } else if (color === 'white' && this.gs.turn === 'white') { - // Human has no valid moves — skip it, AI goes again - this.showTurnBanner('You have no valid moves — passing'); - this.time.delayedCall(1200, () => this.startAITurn()); - } else if (this.gs.turn === 'white') { - this.startAITurn(); - } - }); + clearPreview() { + for (const o of this.previewObjs) o.destroy(); + this.previewObjs = []; + this.previewG?.clear(); + this.hover = -1; } - // ── Flip cascade animation ──────────────────────────────────────────────────── - - animateFlips(placedR, placedC, flips, newColor, onAllDone) { - if (flips.length === 0) { this.time.delayedCall(90, onAllDone); return; } - - // Group flips by Manhattan distance (ripple outward from placed disc) - const byDist = new Map(); + /** Ghost disc + rings on every disc it would flip. */ + preview(sq) { + if (sq === this.hover) return; + this.clearPreview(); + if (sq < 0 || !this.canMoveNow()) return; + const flips = L.flipsFor(this.gs.board, this.size, sq, this.gs.turn); + if (!flips.length) return; + this.hover = sq; + if (!this.settings.preview) return; + const { SQ, R, scale } = geom(this.size); + const p = squareXY(sq, this.size); + const ghost = this.add.image(p.x, p.y, `ot-disc-${this.gs.turn}`).setScale(scale / RES).setAlpha(0.5).setDepth(D.ghost); + this.previewObjs.push(ghost); + const g = this.previewG; for (const f of flips) { - const d = Math.abs(f.r - placedR) + Math.abs(f.c - placedC); - if (!byDist.has(d)) byDist.set(d, []); - byDist.get(d).push(f); + const q = squareXY(f, this.size); + g.lineStyle(3, 0xffd060, 0.9).strokeCircle(q.x, q.y - 3, R * 0.92); } - const distances = [...byDist.keys()].sort((a, b) => a - b); - - let groupsDone = 0; - - distances.forEach((dist, idx) => { - const group = byDist.get(dist); - const delay = 90 + idx * 55; // stagger by distance rank - let discsDone = 0; - - for (const f of group) { - this.flipDisc(f.r, f.c, newColor, delay, () => { - discsDone++; - if (discsDone === group.length) { - groupsDone++; - if (groupsDone === distances.length) onAllDone(); - } - }); - } - }); + const t = this.add.text(p.x + SQ / 2 - 4, p.y - SQ / 2 + 2, `+${flips.length}`, { + fontFamily: BOLD_FONT, fontSize: `${Math.round(SQ / 4.2)}px`, color: '#ffe8a8', stroke: '#1a0c08', strokeThickness: 4, + }).setOrigin(1, 0).setDepth(D.ghost + 1); + this.previewObjs.push(t); } - flipDisc(r, c, newColor, delay, onDone) { - const g = this.discObjs[r][c]; - if (!g) { onDone?.(); return; } + // ── turns ─────────────────────────────────────────────────────────────────── + nextTurn(tok) { + if (this.stale(tok)) return; + this.clearPreview(); + if (this.gs.phase === 'game_over') { this.endGame(tok); return; } + this.turnStart = Date.now(); + if (this.gs.turn === this.humanColor) this.humanTurn(); + else this.aiTurn(tok); + } - this.time.delayedCall(delay, () => { - // Squeeze to flat (scaleX → 0) - this.tweens.add({ - targets: g, scaleX: 0, duration: 110, ease: 'Quad.easeIn', - onComplete: () => { - this.drawDiscGraphics(g, newColor); // swap color at the midpoint - // Expand back - this.tweens.add({ - targets: g, scaleX: 1, duration: 110, ease: 'Quad.easeOut', - onComplete: onDone, - }); - }, + canMoveNow() { return this.phase === 'human' && !this.busy && !this.modal && this.gs?.phase === 'playing'; } + + humanTurn() { + this.phase = 'human'; + this.busy = false; + const moves = L.legalMoves(this.gs); + const empty = L.counts(this.gs).empty; + let tip = 'Hover a marked square to see what flips; click to play.'; + if (moves.length === 1) tip = 'Only one move. Take it.'; + if (empty <= 12 && !this.saidEndgame) { this.saidEndgame = true; const l = masterLine('endgame'); if (l) this.hud.masterSays(l); } + this.setStatus('Your move', `${tip}\nYou have ${moves.length} move${moves.length === 1 ? '' : 's'}.`); + this.refreshHud(); + this.drawMarks(); + this.drawStudy(); + this.drawLast(); + this.drawCursor(); + const p = this.input.activePointer; + if (p) this.preview(cellAt(p.x, p.y, this.size)); + } + + // ── input ─────────────────────────────────────────────────────────────────── + setCursor(c) { const cv = this.game?.canvas; if (cv && cv.style.cursor !== c) cv.style.cursor = c; } + + onPointerDown(p) { + if (!this.canMoveNow()) return; + const sq = cellAt(p.x, p.y, this.size); + if (sq < 0) return; + this.tryPlay(sq); + } + + onPointerMove(p) { + if (!this.canMoveNow()) { if (this.hover >= 0) this.clearPreview(); return; } + const sq = cellAt(p.x, p.y, this.size); + this.preview(sq); + this.setCursor(this.hover >= 0 ? 'pointer' : 'default'); + } + + tryPlay(sq) { + if (!this.canMoveNow()) return; + if (!L.flipsFor(this.gs.board, this.size, sq, this.gs.turn).length) { + deny(this); + if (this.gs.board[sq] === null && !this.saidIllegal) { + this.saidIllegal = true; + this.hud.masterSays('Not there. A move has to trap at least one of their discs in a line.'); + } + return; + } + this.commit(sq); + } + + async commit(sq, { warned = false } = {}) { + // the Master's look before you leap + const pos = this.posOf(); + if (this.settings.coach && !warned && givesCorner(pos, sq)) { + const legal = L.legalMoves(this.gs); + const safe = legal.filter((m) => !givesCorner(pos, m.sq)); + if (safe.length) { + this.busy = true; + this.clearPreview(); + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'The Master leans over…', + text: `${masterLine('warnCorner')}\n\n${safe.length} of your ${legal.length} moves keep the corners shut.`, + yes: 'Play it anyway', no: 'Let me look again', depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); this.busy = false; this.commit(sq, { warned: true }); }, + onNo: () => { this.modal = null; this.hud.showPortraits(); this.busy = false; }, + }); + return; + } + } + const tok = this.token; + this.undoStack.push({ gs: this.gs, clocks: { ...this.clocks } }); + if (this.undoStack.length > 60) this.undoStack.shift(); + this.clocks.human += Date.now() - this.turnStart; + this.clearMarks(); + this.clearPreview(); + this.clearHint(); + this.cursorG.clear(); + this.busy = true; + this.phase = 'animating'; + this.setCursor('default'); + this.refreshHud(); + await this.playMove(sq, tok); + if (this.stale(tok)) return; + await this.afterMove(tok); + } + + posOf() { return { size: this.gs.size, variant: this.gs.variant, board: this.gs.board, turn: this.gs.turn }; } + + // ── a move, animated ──────────────────────────────────────────────────────── + async playMove(sq, tok, { fast = false, book = false, quiet = false } = {}) { + const gs = this.gs; + const mover = gs.turn; + const human = mover === this.humanColor; + const k = this.k * (fast ? 0.35 : 1); + const rays = L.flipRays(gs.board, gs.size, sq, mover); + const nFlips = rays.reduce((a, r) => a + r.sqs.length, 0); + // the disc comes out of the mover's tray (or the other one, if theirs is empty) + const sup = L.supply(gs); + const own = human ? 'bottom' : 'top', theirs = human ? 'top' : 'bottom'; + const fromSide = sup[mover] > 0 ? own : theirs; + const trayColor = fromSide === own ? mover : L.other(mover); + const from = this.hud.trayTarget(fromSide, sup[trayColor], sup.each); + this.held = { black: 0, white: 0, [trayColor]: -1 }; // the disc in hand has left the tray + this.hud.setTray(fromSide, trayColor, Math.max(0, sup[trayColor] - 1), sup.each); + this.lastG.clear(); + if (!fast) slide(this); + await this.discs.place(sq, mover, from, { dur: (fast ? 200 : 380) * this.k, arc: fast ? 50 : 90 }); + if (this.stale(tok)) return; + clack(this); + // the captured lines turn over, outward from the new disc + const step = 75 * k; + const jobs = []; + rays.forEach((ray) => ray.sqs.forEach((f, j) => { + jobs.push(this.discs.flip(f, mover, { + dr: ray.dr, dc: ray.dc, delay: 30 + j * step, dur: 300 * k, lift: 20, + onSwap: () => { if (!this.stale(tok)) flipSnd(this, { k: j }); }, + })); + })); + await Promise.all(jobs); + if (this.stale(tok)) return; + this.gs = L.applyMove(gs, sq, { book }); + this.held = null; + // flourishes and talk + const flipped = rays.flatMap((r) => r.sqs); + this.glowFlipped(flipped); + const p = squareXY(sq, this.size); + const corner = L.isCorner(sq, this.size); + if (!quiet) { + if (corner && this.gs.variant === 'standard') { + chime(this); + this.ringBurst(p.x, p.y); + if (human) { this.hud.masterSays(masterLine('humanCorner')); if (Math.random() < 0.6) this.hud.say(opponentLine('lostCorner', this.tier)); this.hud.emotion('upset'); } + else { const l = masterLine('aiCorner'); if (l) this.hud.masterSays(l); if (Math.random() < 0.5) this.hud.say(opponentLine('corner', this.tier)); this.hud.emotion('happy'); } + } else if (nFlips >= 6) { + this.callout(`×${nFlips}`, p.x, p.y - 50, human ? 0xffe8a8 : 0xff9a84); + if (human) { const l = masterLine('humanBig', { n: nFlips }); if (l) this.hud.masterSays(l); if (Math.random() < 0.5) this.hud.say(opponentLine('lostBig', this.tier)); this.hud.emotion('upset'); } + else { const l = masterLine('aiBig', { n: nFlips }); if (l) this.hud.masterSays(l); if (Math.random() < 0.5) this.hud.say(opponentLine('big', this.tier)); this.hud.emotion('happy'); } + } + // name the opening as it takes shape + const line = this.bookLine(); + if (line && !this.gs.opening?.card) { + const name = openingName(line); + if (name && name !== this.gs.opening?.name) { + this.gs.opening = { name }; + const l = masterLine('opening', { name }); + if (l) this.hud.masterSays(l); + } + } + } + this.drawLast(); + this.drawStudy(); + this.refreshHud(); + if (this.gs.phase === 'playing') this.save(); + } + + /** After a move: show any pass, then hand over. */ + async afterMove(tok) { + if (this.stale(tok)) return; + const last = this.gs.history[this.gs.history.length - 1]; + if (last?.pass && this.gs.phase === 'playing') { + if (last.color === this.humanColor) { + await this.humanPassCard(); + } else { + this.banner(`${this.oppName} passes`.toUpperCase(), 0xf0d890, 0.55, true); + this.hud.say(opponentLine('pass', this.tier)); + this.hud.masterSays(masterLine('aiPass')); + await this.wait(1100 * this.k); + } + if (this.stale(tok)) return; + } + this.nextTurn(tok); + } + + humanPassCard() { + return new Promise((res) => { + this.setStatus('No move for you', `${this.oppName} plays again.`); + this.hud.masterSays(masterLine('humanPass')); + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'You have to pass', + text: 'None of the empty squares would flip any of their discs, so you sit this turn out. They move again.', + yes: 'Pass', no: null, depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); res(); }, }); }); } - // ── AI turn ─────────────────────────────────────────────────────────────────── - - startAITurn() { - const name = this.opponents[0]?.name ?? 'Opponent'; - this.showTurnBanner(`${name}'s Turn`); - this.time.delayedCall(nextThinkDelay(this.opponents[0]?.skill ?? 3), () => this.aiStep()); - } - - aiStep() { - if (this.gs.phase !== 'playing' || this.gs.turn !== 'white') return; - const skill = this.opponents[0]?.skill ?? 3; - const move = chooseMove(this.gs, 'white', skill); - - if (!move) return; // applyMove already handled any pass; shouldn't reach here - - const flips = getFlips(this.gs.board, move.r, move.c, 'white'); - this.executeMove(move.r, move.c, 'white', flips); - } - - // ── Banners ─────────────────────────────────────────────────────────────────── - - showTurnBanner(text) { - const cx = BX + BOARD / 2; - const banner = this.add.text(cx, BY - 70, text, { - fontFamily: 'Righteous', fontSize: '36px', color: COLORS.textHex, - backgroundColor: '#111923ee', padding: { x: 28, y: 12 }, - }).setOrigin(0.5).setDepth(DEPTH.banner); - this.tweens.add({ - targets: banner, y: BY - 14, duration: 320, ease: 'Back.easeOut', - onComplete: () => { - this.time.delayedCall(1200, () => { - this.tweens.add({ targets: banner, y: BY - 70, alpha: 0, duration: 220, onComplete: () => banner.destroy() }); - }); - }, - }); - } - - // ── Game over ───────────────────────────────────────────────────────────────── - - onGameOver() { - const winner = getWinner(this.gs); - const isHuman = winner === 'black'; - const isDraw = winner === 'draw'; - const name = this.opponents[0]?.name ?? 'Opponent'; - const { black, white } = getScore(this.gs); - this.playOpponentEmotion(isHuman ? 'upset' : isDraw ? 'happy' : 'happy'); - this.recordResult(isHuman ? 'win' : isDraw ? 'draw' : 'loss'); - - const cx = BX + BOARD / 2, cy = BY + BOARD / 2; - - if (isHuman) { - const emitter = this.add.particles(cx, cy, 'othelloParticle', { - speed: { min: 150, max: 500 }, lifespan: 1400, - scale: { start: 1.5, end: 0 }, alpha: { start: 1, end: 0 }, - quantity: 5, frequency: 25, angle: { min: 0, max: 360 }, - tint: [C.selGold, 0xffffff, COLORS.accent], - }).setDepth(DEPTH.banner); - this.time.delayedCall(2000, () => emitter.destroy()); + glowFlipped(sqs) { + const { R } = geom(this.size); + for (const f of sqs) { + const q = squareXY(f, this.size); + const g = this.add.image(q.x, q.y, 'ot-glow').setDepth(D.piece - 2).setScale((R * 2.6) / 128).setAlpha(0.55); + this.tweens.add({ targets: g, alpha: 0, duration: 900, ease: 'Quad.In', onComplete: () => g.destroy() }); } + } - this.time.delayedCall(450, () => { - const msg = isDraw - ? `It's a draw!\nBlack ${black} · White ${white}` - : isHuman - ? `🎉 You win!\nBlack ${black} · White ${white}` - : `${name} wins!\nBlack ${black} · White ${white}`; + // ── undo / hint ───────────────────────────────────────────────────────────── + undo() { + if (!this.canMoveNow() || !this.undoStack.length) return; + const snap = this.undoStack.pop(); + const tok = ++this.token; + this.held = null; + this.clearOverlays(); + this.gs = snap.gs; + this.clocks = snap.clocks; + this.discs.build(this.gs.board, this.size); + slide(this); + const l = masterLine('undo'); + if (l) this.hud.masterSays(l); + this.save(); + this.nextTurn(tok); + } - const overlay = this.add.rectangle(cx, cy, 760, 310, 0x0a0e14, 0.9) - .setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.banner); - const txt = this.add.text(cx, cy - 44, msg, { - fontFamily: '"Julius Sans One"', fontSize: '30px', - color: isHuman ? '#ffd700' : isDraw ? COLORS.textHex : COLORS.textHex, - align: 'center', - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); - new Button(this, cx - 90, cy + 88, 'Play Again', () => { - overlay.destroy(); txt.destroy(); this.initGame(); - }, { width: 160, fontSize: 22 }).setDepth(DEPTH.banner + 1); - new Button(this, cx + 90, cy + 88, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 160, fontSize: 22 }).setDepth(DEPTH.banner + 1); + async showHint() { + if (!this.canMoveNow()) return; + const tok = this.token; + this.clearHint(); + this.busy = true; + this.setStatus('The Master looks…', 'He sets down the kettle and studies the board.'); + this.refreshHud(); + const pos = this.posOf(); + let h = null; + try { h = await this.engine.request('hint', { pos, ms: 700 }); } catch (_) { h = null; } + if (this.stale(tok) || this.phase !== 'human') return; + this.busy = false; + this.refreshHud(); + if (!h) { this.setStatus('Your move', 'The Master shrugs. Any move will do.'); return; } + const n = L.notate(h.sq, this.size); + const reason = describeIdea(pos, h.sq, h); + const p = squareXY(h.sq, this.size); + const { R } = geom(this.size); + const ring = this.add.image(p.x, p.y, 'ot-ring').setDepth(D.ghost + 2).setScale((R * 2.3) / 96); + this.tweens.add({ targets: ring, scale: { from: (R * 2.6) / 96, to: (R * 2.1) / 96 }, alpha: { from: 1, to: 0.5 }, duration: 620, yoyo: true, repeat: -1 }); + this.hintObjs.push(ring); + this.hud.masterSays(masterLine('hint', { move: n, reason }), { hold: 10000 }); + this.setStatus('The Master\'s hint', `${n}: it ${reason}. Play it or anything else.`); + if (h.exact) { + const m = exactMargin(h.score); + const line = h.score > 0 ? `you win by ${m}` : h.score < 0 ? `you lose by ${-m}` : 'a draw'; + const l = masterLine('solved', { line }); + if (l) this.time.delayedCall(2500, () => { if (!this.stale(tok) && this.phase === 'human') this.hud.masterSays(l, { hold: 8000 }); }); + } + } + + clearHint() { + for (const o of this.hintObjs ?? []) o.destroy(); + this.hintObjs = []; + } + + // ── AI ────────────────────────────────────────────────────────────────────── + async aiTurn(tok) { + if (this.stale(tok)) return; + this.phase = 'ai'; + this.busy = true; + this.clearMarks(); + const fast = this.settings.skipAI; + const t = aiTiming(this.skill, fast ? 0.25 : this.k); + this.setStatus(`${this.oppName} is thinking…`, this.gs.opening ? `${this.gs.opening.name}.` : ''); + this.refreshHud(true); + this.drawStudy(); + const started = Date.now(); + let res = null; + try { res = await this.engine.request('move', { pos: this.posOf(), skill: this.skill, line: this.bookLine() }); } catch (_) { res = null; } + if (this.stale(tok)) return; + const legal = L.legalMoves(this.gs); + if (!res || !legal.some((m) => m.sq === res.sq)) res = { sq: legal[Math.floor(Math.random() * legal.length)].sq }; + await this.wait(Math.max(0, (fast ? 60 : t.think) - (Date.now() - started))); + await this.untilNoModal(tok); + if (this.stale(tok)) return; + if (!fast) { + // their hand hovers over the square for a moment + const p = squareXY(res.sq, this.size); + const ghost = this.add.image(p.x, p.y - 10, `ot-disc-${this.aiColor}`).setScale(geom(this.size).scale / RES).setAlpha(0).setDepth(D.ghost); + this.tweens.add({ targets: ghost, alpha: 0.35, y: p.y, duration: 220 }); + await this.wait(t.hesitate * 0.5); + ghost.destroy(); + await this.untilNoModal(tok); + if (this.stale(tok)) return; + } + this.clocks.ai += Date.now() - this.turnStart; + this.phase = 'animating'; + await this.playMove(res.sq, tok, { fast }); + if (this.stale(tok)) return; + await this.wait(fast ? 40 : Math.min(220, t.between * 0.5)); + await this.afterMove(tok); + } + + /** Hold the opponent's hand while a menu is open. */ + async untilNoModal(tok) { + while (this.modal && !this.stale(tok)) await this.wait(120); + } + + resign() { + if (!this.canMoveNow()) return; + this.confirmThen('Resign this game?', `${this.oppName} gets the point.`, () => { + this.hud.masterSays(masterLine('resign')); + this.gs = L.resign(this.gs, this.humanColor); + this.endGame(this.token); }); } - async recordResult(result) { - try { - const { black, white } = getScore(this.gs); - const score = result === 'win' ? black * 2 : result === 'draw' ? 10 : 0; - await api.post('/history/single-player', { slug: 'othello', score, opponentScores: [], result }); - } catch { /* best effort */ } + // ── end of a game / match ─────────────────────────────────────────────────── + async endGame(tok) { + if (this.phase === 'over' || this.stale(tok)) return; + this.phase = 'over'; + this.busy = true; + this.clearOverlays(); + const gs = this.gs; + const m = this.match; + const result = gs.winner === 'draw' ? 'draw' : gs.winner === this.humanColor ? 'human' : 'ai'; + const c = L.counts(gs); + if (result === 'human') m.human += 1; else if (result === 'ai') m.ai += 1; else { m.human += 0.5; m.ai += 0.5; } + const mine = this.humanColor === L.BLACK ? c.black : c.white, theirs = this.humanColor === L.BLACK ? c.white : c.black; + m.results.push({ result, humanColor: this.humanColor, score: `${c.black}–${c.white}`, margin: mine - theirs, opening: gs.opening?.name ?? null, reason: gs.endReason }); + this.recordLifetime(result); + const over = m.human > m.games / 2 || m.ai > m.games / 2 || m.results.length >= m.games; + if (over) { this.clearSave(); this.postHistory().catch(() => {}); } else this.save(true); + this.refreshHud(); + const r = resultLine(gs, this.humanColor, this.oppName); + if (gs.endReason === 'wipeout') this.hud.masterSays(masterLine('wipeout')); + // count them out, tournament style: black from the top, white from the bottom + if (gs.endReason !== 'resign') { + this.setStatus('Counting…', `Black ${c.black} · White ${c.white}`); + if (gs.endReason !== 'wipeout') this.hud.masterSays(masterLine('count')); + await this.wait(700); + if (this.stale(tok)) return; + await this.countOut(tok); + if (this.stale(tok)) return; + } + this.setStatus(r.title, r.why); + if (result === 'human') { + sting(this, 'win'); playSound(this, SFX.CASINO_WIN); + this.banner('YOU WIN', 0xf0d890, 0.8); + this.confetti(); + this.hud.say(opponentLine('lose', this.tier)); this.hud.emotion('upset'); + this.hud.masterSays(masterLine('win')); + } else if (result === 'ai') { + sting(this, 'lose'); + this.banner(`${this.oppName} WINS`.toUpperCase(), 0xff9a84, 0.7); + this.hud.say(opponentLine('win', this.tier)); this.hud.emotion('happy'); + if (gs.endReason !== 'resign') this.hud.masterSays(masterLine('loss')); + } else { + sting(this, 'draw'); + this.banner('DRAW', 0xe8dcc0, 0.8); + this.hud.say(opponentLine('draw', this.tier)); + this.hud.masterSays(masterLine('draw')); + } + await this.wait(2600); + if (this.stale(tok)) return; + if (over) this.matchOver(); + else this.betweenGames(); } + + async countOut(tok) { + const size = this.size, N = size * size; + const b = this.gs.board; + const blacks = [], whites = []; + b.forEach((v, sq) => { if (v === L.BLACK) blacks.push(sq); else if (v === L.WHITE) whites.push(sq); }); + const moves = []; + blacks.forEach((sq, i) => moves.push([sq, i])); + whites.slice().reverse().forEach((sq, i) => moves.push([sq, N - 1 - i])); + // only discs that actually move need to (but the order still reads well) + const real = moves.filter(([a, t]) => a !== t); + let ticks = 0; + const tick = this.time.addEvent({ delay: 60, loop: true, callback: () => { if (ticks++ < real.length / 2) clack(this, { vol: 0.03 }); } }); + await this.discs.arrange(real, { stagger: Math.max(6, Math.round(900 / Math.max(1, real.length))), dur: 380 }); + tick.remove(); + if (this.stale(tok)) return; + const c = L.counts(this.gs); + this.callout(`${c.black} – ${c.white}`, BCX, BY + BOARD / 2, 0xf3ead2); + await this.wait(900); + } + + betweenGames() { + this.hud.hidePortraits(); + this.modal = openBetween(this, { + gs: this.gs, humanColor: this.humanColor, oppName: this.oppName, match: this.match, depth: D.end, + onNext: () => { this.modal = null; this.hud.showPortraits(); this.startGame(); }, + onLeave: () => this.scene.start('GameMenu'), + }); + } + + matchOver() { + const m = this.match; + if (m.games > 1) { + if (m.human > m.ai) this.hud.masterSays(masterLine('matchWin')); + else if (m.ai > m.human) this.hud.masterSays(masterLine('matchLoss')); + else this.hud.masterSays(masterLine('matchDraw')); + } + // the Master goes over the human's moves in the engine + const gs = this.gs; + const positions = []; + gs.history.forEach((h, i) => { + if (h.pass || h.book || h.color !== this.humanColor) return; + positions.push({ i, board: L.boardAfter(gs, i), turn: h.color, played: h.sq }); + }); + const review = gs.endReason === 'resign' && positions.length < 3 ? null + : this.engine.request('review', { size: gs.size, variant: gs.variant, positions, ms: gs.size === 10 ? 160 : 110 }); + this.hud.hidePortraits(); + this.modal = openEndScreen(this, { + gs, humanColor: this.humanColor, oppName: this.oppName, match: m, depth: D.end, + record: this.lifetime()?.vs?.[this.opp.id ?? this.oppName] ?? null, review, + onPlayAgain: () => { this.modal = null; this.hud.showPortraits(); this.openSetupCard(); }, + onMenu: () => this.scene.start('GameMenu'), + }); + } + + lifetime() { + try { return JSON.parse(localStorage.getItem(RECORD_KEY) || '{}'); } catch (_) { return {}; } + } + + recordLifetime(result) { + try { + const rec = this.lifetime(); + const key = result === 'human' ? 'w' : result === 'ai' ? 'l' : 'd'; + rec.kinds = rec.kinds ?? {}; + rec.vs = rec.vs ?? {}; + const kind = `${this.gs.variant}-${this.gs.size}`; + const v = (rec.kinds[kind] = rec.kinds[kind] ?? { w: 0, d: 0, l: 0 }); + const o = (rec.vs[this.opp.id ?? this.oppName] = rec.vs[this.opp.id ?? this.oppName] ?? { w: 0, d: 0, l: 0 }); + v[key]++; o[key]++; + localStorage.setItem(RECORD_KEY, JSON.stringify(rec)); + } catch (_) { /* private mode */ } + } + + async postHistory() { + const m = this.match; + const result = m.human > m.ai ? 'win' : m.ai > m.human ? 'loss' : 'draw'; + // match points ×100, plus the discs you won by (never below zero) + const margin = m.results.reduce((a, r) => a + Math.max(0, r.margin ?? 0), 0); + await api.post('/history/single-player', { + slug: 'othello', score: Math.round(m.human * 100 + margin), opponentScores: [Math.round(m.ai * 100)], result, + }); + } + + // ── buttons / keys / menu ─────────────────────────────────────────────────── + onButton(k) { + if (this.ended || this.modal) return; + if (k === 'undo') this.undo(); + else if (k === 'hint') this.showHint(); + else if (k === 'study') this.toggleStudy(); + else if (k === 'resign') this.resign(); + else if (k === 'menu') this.openMenu(); + } + + toggleStudy() { + const on = !(this.settings.danger || this.settings.mobility || this.settings.stable); + this.settings.danger = on; this.settings.mobility = on; this.settings.stable = on; + this.persistSettings(); + toast(this, on ? 'Study marks on: X/C-squares, reply counts, stable discs.' : 'Study marks off.', { depth: D.modal }); + this.drawStudy(); + if (this.phase === 'human') this.drawMarks(); + } + + onKey(e) { + if (this.ended || e.repeat) return; + const key = e.key; + if (key === 'Escape') { + if (this.modal) { if (this.escClosable) this.closeModal(); return; } + this.openMenu(); + return; + } + if (this.modal) return; + const lower = key.toLowerCase(); + if (lower === 'z') this.undo(); + else if (lower === 'h') this.showHint(); + else if (lower === 's') this.toggleStudy(); + else if (key.startsWith('Arrow')) this.moveCursor(key); + else if ((key === 'Enter' || key === ' ') && this.cursor && this.canMoveNow()) { + this.tryPlay(this.cursor[0] * this.size + this.cursor[1]); + } + } + + moveCursor(key) { + if (!this.canMoveNow()) return; + const n = this.size; + if (!this.cursor) { + const first = L.legalMoves(this.gs)[0]; + this.cursor = first ? [Math.floor(first.sq / n), first.sq % n] : [n / 2, n / 2]; + } else { + const d = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }[key]; + this.cursor = [Math.max(0, Math.min(n - 1, this.cursor[0] + d[0])), Math.max(0, Math.min(n - 1, this.cursor[1] + d[1]))]; + } + this.drawCursor(); + this.preview(this.cursor[0] * n + this.cursor[1]); + } + + drawCursor() { + const g = this.cursorG; + g.clear(); + if (!this.cursor || this.phase !== 'human') return; + const { SQ } = geom(this.size); + const [r, c] = this.cursor; + const x = BX + c * SQ, y = BY + r * SQ; + g.lineStyle(4, 0xd8b060, 1).strokeRect(x + 3, y + 3, SQ - 6, SQ - 6); + g.lineStyle(1.5, 0xffffff, 0.6).strokeRect(x + 8, y + 8, SQ - 16, SQ - 16); + } + + openMenu() { + if (this.modal || this.ended || this.phase === 'over' || this.phase === 'setup') return; + this.clearPreview(); + this.hud.hidePortraits(); + this.escClosable = true; + this.modal = openPauseMenu(this, { + settings: this.settings, depth: D.modal, + onChange: (key, value) => this.changeSetting(key, value), + onRules: () => new TutorialModal(this.gameDef).open(), + onNewMatch: () => this.confirmThen('Start a new match?', 'This game will be abandoned.', () => { this.clearSave(); this.openSetupCard(); }), + onLeave: () => this.confirmThen('Leave the kissa?', 'Your game is saved; you can pick it up next time.', () => this.scene.start('GameMenu')), + onClose: () => { this.modal = null; this.escClosable = false; this.hud.showPortraits(); this.refreshHud(); }, + }); + } + + confirmThen(heading, text, onYes) { + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading, text, depth: D.modal + 5, + onYes: () => { this.modal = null; this.hud.showPortraits(); onYes(); }, + onNo: () => { this.modal = null; this.hud.showPortraits(); this.refreshHud(); }, + }); + } + + closeModal() { this.modal?.close?.(); this.modal = null; this.escClosable = false; this.hud.showPortraits(); } + + persistSettings() { + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + } + + changeSetting(key, value) { + this.settings[key] = value; + this.persistSettings(); + if (key === 'ambience') this.ambience.setOn(value); + if (['danger', 'stable'].includes(key)) this.drawStudy(); + if (['hints', 'mobility'].includes(key) && this.phase === 'human') this.drawMarks(); + if (key === 'preview') this.clearPreview(); + } + + // ── flourishes ────────────────────────────────────────────────────────────── + ringBurst(x, y) { + for (let i = 0; i < 2; i++) { + const r = this.add.image(x, y, 'ot-ring').setDepth(D.fx).setScale(0.5).setAlpha(0.95); + this.tweens.add({ targets: r, scale: 2.4, alpha: 0, delay: i * 140, duration: 700, ease: 'Quad.Out', onComplete: () => r.destroy() }); + } + this.sparks(x, y, 12); + } + + sparks(x, y, n = 10) { + for (let i = 0; i < n; i++) { + const s = this.add.image(x, y, 'ot-spark').setDepth(D.fx).setScale(0.6 + Math.random() * 0.8).setTint(0xffe8a8); + const a = Math.random() * Math.PI * 2, r = 30 + Math.random() * 70; + this.tweens.add({ targets: s, x: x + Math.cos(a) * r, y: y + Math.sin(a) * r, alpha: 0, scale: 0.1, duration: 480 + Math.random() * 240, ease: 'Quad.Out', onComplete: () => s.destroy() }); + } + } + + confetti() { + const cols = [0xb8321e, 0xf6f2ea, 0x1c1b22, 0xf0d890]; + for (let i = 0; i < 90; i++) { + const x = BCX + (Math.random() - 0.5) * BOARD, y = BY - 40 - Math.random() * 200; + const r = this.add.rectangle(x, y, 8, 14, cols[i % cols.length]).setDepth(D.fx).setRotation(Math.random() * 6); + this.tweens.add({ + targets: r, y: y + 700 + Math.random() * 300, x: x + (Math.random() - 0.5) * 200, rotation: r.rotation + (Math.random() - 0.5) * 12, + alpha: { from: 1, to: 0 }, duration: 1800 + Math.random() * 1400, ease: 'Sine.In', onComplete: () => r.destroy(), + }); + } + } + + callout(text, x, y, color) { + const hex = Phaser.Display.Color.IntegerToColor(color).rgba; + const t = this.add.text(x, y, text, { + fontFamily: BOLD_FONT, fontSize: '38px', color: hex, stroke: '#1a0c08', strokeThickness: 7, + shadow: { offsetX: 0, offsetY: 4, color: '#000', blur: 10, fill: true }, + }).setOrigin(0.5).setDepth(D.fx + 2).setScale(0.3).setAlpha(0); + this.tweens.add({ targets: t, scale: 1, alpha: 1, duration: 260, ease: 'Back.Out' }); + this.tweens.add({ targets: t, y: y - 50, alpha: 0, delay: 1000, duration: 500, onComplete: () => t.destroy() }); + } + + banner(text, color, scale = 1, small = false) { + this.bannerObj?.destroy(); + const hex = Phaser.Display.Color.IntegerToColor(color).rgba; + const t = this.add.text(0, 0, text, { + fontFamily: DISPLAY_FONT, fontSize: small ? '60px' : '92px', color: hex, stroke: '#0a0606', strokeThickness: small ? 9 : 12, + shadow: { offsetX: 0, offsetY: 6, color: '#000', blur: 16, fill: true }, + }).setOrigin(0.5); + const cont = this.add.container(BANNER.x, BANNER.y - 110, [t]).setDepth(D.banner).setScale(scale * 0.4).setAlpha(0); + this.bannerObj = cont; + this.tweens.add({ targets: cont, y: BANNER.y, scale, alpha: 1, duration: 380, ease: 'Back.Out' }); + this.tweens.add({ targets: cont, alpha: 0, y: BANNER.y - 40, delay: small ? 1000 : 1900, duration: 420, onComplete: () => { cont.destroy(); if (this.bannerObj === cont) this.bannerObj = null; } }); + } + + wait(ms) { return new Promise((r) => this.time.delayedCall(Math.max(0, ms), r)); } } diff --git a/src/games/othello/OthelloHud.js b/src/games/othello/OthelloHud.js new file mode 100644 index 0000000..da3a347 --- /dev/null +++ b/src/games/othello/OthelloHud.js @@ -0,0 +1,259 @@ +// OthelloHud.js: the furniture around the table: a lacquer plaque per +// player (portrait, name, skill, a note line, discs / clock, the match +// tally, their colour), each player's disc tray, the tug-of-war disc bar, +// the status card, the move sheet, the buttons, the opponent's speech +// bubble and the Master's ribbon. + +import { Button } from '../../ui/Button.js'; +import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { + PLATES, plateParts, TRAYS, BUBBLE, STATUS, LOG, LOG_ROWS, BUTTONS, BTN, RIBBON, BAR, +} from './OthelloLayout.js'; +import { DISPLAY_FONT, SERIF, BOLD_FONT, RES } from './OthelloArt.js'; +import { countsOf, other, supply, VARIANTS, SIZE_INFO } from './OthelloLogic.js'; + +const short = (s, n = 14) => (s.length > n ? s.slice(0, n - 1) + '…' : s); +const clock = (ms) => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; }; +const half = (x) => (x % 1 ? `${Math.floor(x) || ''}½` : String(x)); +const SLICE_GAP = 7; + +export class Hud { + constructor(scene, depth, { names, skill, opponent, onButton }) { + this.scene = scene; + this.depth = depth; + this.names = names; // { top, bottom } + this.skill = skill; + this.opponent = opponent; + this.onButton = onButton; + this.plates = {}; + this.buttons = {}; + this.bubble = null; + this.trayObjs = { top: [], bottom: [] }; + this.barShown = 0.5; + } + + build() { + const s = this.scene, D = this.depth; + for (const side of ['top', 'bottom']) { + const P = PLATES[side], parts = plateParts(side); + const glow = s.add.image(P.x - 40, P.y - 40, 'ot-plate-glow').setOrigin(0).setDepth(D - 1).setAlpha(0); + s.add.image(P.x - 14, P.y - 14, 'ot-plate').setOrigin(0).setDepth(D); + const pp = parts.portrait; + const ring = s.add.circle(pp.x, pp.y, pp.r + 5, 0xd8b060, 1).setDepth(D + 1); + const portrait = side === 'bottom' + ? createPlayerPortrait(s, pp.x, pp.y, pp.r, D + 2, 'OthelloGame') + : createOpponentPortrait(s, this.opponent ?? { id: 'bot', spriteIndex: 0 }, pp.x, pp.y, pp.r, D + 2); + s.add.text(parts.name.x, parts.name.y, short(this.names[side], side === 'top' ? 13 : 16), { + fontFamily: DISPLAY_FONT, fontSize: '22px', color: '#f8ead0', + }).setOrigin(0, 0.5).setDepth(D + 1); + if (side === 'top') { + const k = this.skill; + s.add.text(parts.skill.x, parts.skill.y, '●'.repeat(k) + '○'.repeat(5 - k), { fontFamily: SERIF, fontSize: '13px', color: '#e8c46a' }) + .setOrigin(1, 0.5).setDepth(D + 1); + } + const note = s.add.text(parts.note.x, parts.note.y, '', { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#e0caa0' }) + .setOrigin(0, 0.5).setDepth(D + 1); + const line = s.add.text(parts.line.x, parts.line.y, '', { fontFamily: SERIF, fontSize: '15px', color: '#d8c4a0' }) + .setOrigin(0, 0.5).setDepth(D + 1); + const chip = s.add.image(parts.color.x, parts.color.y, 'ot-disc-black').setScale(0.11).setDepth(D + 1).setVisible(false); + const chipText = s.add.text(parts.color.x + 22, parts.color.y, '', { fontFamily: SERIF, fontSize: '14px', color: '#d8c4a0' }) + .setOrigin(0, 0.5).setDepth(D + 1); + const tally = s.add.text(parts.tally.x, parts.tally.y, '', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#f0d890' }) + .setOrigin(1, 0.5).setDepth(D + 1); + this.plates[side] = { glow, ring, portrait, note, line, chip, chipText, tally, active: false }; + // tray + const T = TRAYS[side]; + s.add.image(T.x - 8, T.y - 8, 'ot-tray').setOrigin(0).setDepth(D); + this.plates[side].trayCount = s.add.text(T.x + T.w - 32, T.y + T.h / 2, '', { + fontFamily: BOLD_FONT, fontSize: '18px', color: '#f0d890', + }).setOrigin(0.5).setDepth(D + 2); + } + // tug-of-war bar + s.add.image(BAR.x - 10, BAR.y - 10, 'ot-bar').setOrigin(0).setDepth(D); + this.barG = s.add.graphics().setDepth(D + 1); + this.barL = s.add.text(BAR.x + 22, BAR.y + BAR.h / 2, '', { fontFamily: BOLD_FONT, fontSize: '22px', color: '#f2eee2' }).setOrigin(0, 0.5).setDepth(D + 2); + this.barR = s.add.text(BAR.x + BAR.w - 22, BAR.y + BAR.h / 2, '', { fontFamily: BOLD_FONT, fontSize: '22px', color: '#1c1b22' }).setOrigin(1, 0.5).setDepth(D + 2); + this.barMid = s.add.text(BAR.x + BAR.w / 2, BAR.y + BAR.h + 14, '', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#d8c4a0' }).setOrigin(0.5).setDepth(D + 2); + // status card + s.add.image(STATUS.x - 14, STATUS.y - 14, 'ot-card-status').setOrigin(0).setDepth(D); + this.status = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 62, '', { + fontFamily: DISPLAY_FONT, fontSize: '27px', color: '#2a1410', align: 'center', wordWrap: { width: STATUS.w - 50 }, + }).setOrigin(0.5).setDepth(D + 1); + this.sub = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 134, '', { + fontFamily: SERIF, fontSize: '16px', color: '#3a2a1a', align: 'center', wordWrap: { width: STATUS.w - 56 }, lineSpacing: 3, + }).setOrigin(0.5).setDepth(D + 1); + // move sheet + s.add.image(LOG.x - 14, LOG.y - 14, 'ot-card-log').setOrigin(0).setDepth(D); + this.logTitle = s.add.text(LOG.x + 24, LOG.y + 34, 'MOVE SHEET', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#7a2414' }).setOrigin(0, 0.5).setDepth(D + 1); + this.logSub = s.add.text(LOG.x + LOG.w - 24, LOG.y + 34, '', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#5a2a12' }).setOrigin(1, 0.5).setDepth(D + 1); + const colA = LOG.x + 66 + (LOG.w - 66) / 4, colB = LOG.x + 66 + ((LOG.w - 66) * 3) / 4; + this.colHead = [ + s.add.text(colA, LOG.y + 62, 'BLACK', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#1c1b22' }).setOrigin(0.5).setDepth(D + 1), + s.add.text(colB, LOG.y + 62, 'WHITE', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#7a6a52' }).setOrigin(0.5).setDepth(D + 1), + ]; + this.rows = []; + for (let i = 0; i < LOG_ROWS; i++) { + const y = LOG.y + 96 + i * 31; + this.rows.push({ + n: s.add.text(LOG.x + 50, y, '', { fontFamily: SERIF, fontSize: '15px', color: '#7a5a3a' }).setOrigin(1, 0.5).setDepth(D + 1), + a: s.add.text(colA, y, '', { fontFamily: SERIF, fontSize: '17px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D + 1), + b: s.add.text(colB, y, '', { fontFamily: SERIF, fontSize: '17px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D + 1), + }); + } + // buttons + const label = { undo: 'Undo (Z)', hint: 'Hint (H)', study: 'Study (S)', resign: 'Resign', menu: 'Menu (Esc)' }; + const bg = { undo: 0x6a4a1a, hint: 0x2a4a6a, study: 0x2a5a3a, resign: 0x7a1a14, menu: 0x2a1a12 }; + for (const [k, b] of Object.entries(BUTTONS)) { + this.buttons[k] = new Button(s, b.x, b.y, label[k], () => this.onButton(k), { width: BTN.w, height: BTN.h, fontSize: 15, bg: bg[k] }).setDepth(D + 3); + if (!['menu', 'study'].includes(k)) this.buttons[k].setEnabled(false); + } + // the Master's ribbon + s.add.image(RIBBON.x - 12, RIBBON.y - 12, 'ot-ribbon').setOrigin(0).setDepth(D); + this.master = s.add.text(RIBBON.x + 84, RIBBON.y + RIBBON.h / 2, '', { + fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color: '#f3e4c0', wordWrap: { width: RIBBON.w - 110 }, + }).setOrigin(0, 0.5).setDepth(D + 1); + return this; + } + + /** gs, ctx: { humanColor, thinking, clocks: {human, ai}, match, held: {black, white} } */ + refresh(gs, ctx) { + const c = countsOf(gs.board); + const sides = { bottom: ctx.humanColor, top: other(ctx.humanColor) }; + const sup = supply(gs); + const held = ctx.held ?? { black: 0, white: 0 }; + for (const side of ['top', 'bottom']) { + const pl = this.plates[side], col = sides[side]; + const n = col === 'black' ? c.black : c.white; + const active = gs.phase === 'playing' && gs.turn === col && !ctx.intro; + if (active !== pl.active) { + pl.active = active; + this.scene.tweens.killTweensOf(pl.glow); + if (active) { + pl.glow.setAlpha(0.9); + this.scene.tweens.add({ targets: pl.glow, alpha: { from: 0.95, to: 0.45 }, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + } else pl.glow.setAlpha(0); + } + let note; + if (gs.phase !== 'playing' || ctx.intro) note = ''; + else if (active) note = side === 'bottom' ? 'Your move' : (ctx.thinking ? 'Thinking…' : 'To play'); + else note = side === 'bottom' ? 'Waiting' : 'Watching the board'; + pl.note.setText(note).setColor(active ? '#ffe0a0' : '#c8b490'); + const ms = side === 'bottom' ? ctx.clocks.human : ctx.clocks.ai; + pl.line.setText(`${n} disc${n === 1 ? '' : 's'} on the board ⏱ ${clock(ms)}`); + pl.chip.setTexture(`ot-disc-${col}`).setVisible(true); + pl.chipText.setText(col === 'black' ? 'Black (moves first)' : 'White'); + const m = ctx.match; + pl.tally.setText(m && m.games > 1 ? `Match ${half(side === 'bottom' ? m.human : m.ai) || '0'}` : ''); + pl.ring.setFillStyle(side === 'bottom' ? 0xd8b060 : (col === 'black' ? 0x3a3848 : 0xe8e2d0)); + this.setTray(side, col, Math.max(0, sup[col] + (held[col] ?? 0)), sup.each); + } + this.setBar(c.black, c.white, gs); + this.setLog(gs); + } + + setTray(side, color, n, each) { + const s = this.scene, T = TRAYS[side]; + const list = this.trayObjs[side]; + // a slice per disc in hand (reused between refreshes) + while (list.length < n) { + const i = list.length; + const im = s.add.image(T.x + 18 + i * (SLICE_GAP * 30 / Math.max(30, each)), T.y + T.h / 2, 'ot-slice').setScale(1 / RES).setDepth(this.depth + 1 + i * 0.001); + if (color === 'white') im.setFlipX(true); + list.push(im); + } + while (list.length > n) list.pop().destroy(); + list.forEach((im) => im.setFlipX(color === 'white')); + this.plates[side].trayCount.setText(`×${n}`); + } + + /** Screen point of the disc that leaves a tray next. */ + trayTarget(side, n, each = 30) { + const T = TRAYS[side]; + return { x: T.x + 18 + Math.max(0, n - 1) * (SLICE_GAP * 30 / Math.max(30, each)), y: T.y + T.h / 2 }; + } + + setBar(black, white, gs) { + const total = Math.max(1, black + white); + const target = black / total; + this.scene.tweens.killTweensOf(this); + this.scene.tweens.add({ targets: this, barShown: target, duration: 420, ease: 'Cubic.Out', onUpdate: () => this.drawBar() }); + this.barL.setText(String(black)); + this.barR.setText(String(white)); + const e = countsOf(gs.board).empty; + const v = VARIANTS[gs.variant]; + this.barMid.setText(gs.phase === 'playing' ? `${e} square${e === 1 ? '' : 's'} left${gs.variant === 'anti' ? ` · ${v.short}: fewest wins` : ''}` : ''); + this.drawBar(); + } + + drawBar() { + const g = this.barG, { x, y, w, h } = BAR; + g.clear(); + const bw = Math.max(h / 2, Math.min(w - h / 2, w * this.barShown)); + g.fillStyle(0xece6d6, 1).fillRoundedRect(x + 2, y + 2, w - 4, h - 4, (h - 4) / 2); + g.fillStyle(0x1c1b22, 1).fillRoundedRect(x + 2, y + 2, bw, h - 4, { tl: (h - 4) / 2, bl: (h - 4) / 2, tr: 0, br: 0 }); + g.fillStyle(0xffffff, 0.12).fillRect(x + h / 2, y + 5, w - h, 4); + g.lineStyle(2, 0xd8b060, 0.9).lineBetween(x + w / 2, y - 2, x + w / 2, y + h + 2); + } + + setLog(gs) { + const info = `${VARIANTS[gs.variant].short} · ${SIZE_INFO[gs.size].name.split(' ')[0]}`; + this.logSub.setText(gs.opening ? `${gs.opening.name} · ${info}` : info); + // pair up black / white turns (a pass takes a slot) + const pairs = []; + for (const h of gs.history) { + if (h.color === 'black' || !pairs.length) pairs.push({ a: null, b: null }); + const last = pairs[pairs.length - 1]; + if (h.color === 'black') last.a = h; else last.b = h; + } + const start = Math.max(0, pairs.length - LOG_ROWS); + const lastH = [...gs.history].reverse().find((h) => !h.pass); + this.rows.forEach((r, i) => { + const p = pairs[start + i]; + if (!p) { r.n.setText(''); r.a.setText(''); r.b.setText(''); return; } + r.n.setText(`${start + i + 1}.`); + for (const [t, h] of [[r.a, p.a], [r.b, p.b]]) { + if (!h) { t.setText(''); continue; } + if (h.pass) { t.setText('pass').setColor('#8a7a62').setFontStyle('italic'); continue; } + const extra = h.flips.length >= 6 ? ` ×${h.flips.length}` : ''; + t.setText(h.n + extra).setColor(h.book ? '#8a7a62' : h === lastH ? '#a0221c' : '#2a1a10') + .setFontStyle(h.book ? 'italic' : h === lastH ? 'bold' : 'normal'); + } + }); + } + + setStatus(main, sub = '') { this.status.setText(main); this.sub.setText(sub); } + setButton(k, on) { this.buttons[k]?.setEnabled(!!on); } + + masterSays(text, { hold = 7000 } = {}) { + if (!text) return; + const t = this.master; + this.scene.tweens.killTweensOf(t); + t.setText(`Master: “${text}”`).setAlpha(0); + this.scene.tweens.add({ targets: t, alpha: 1, duration: 220 }); + this.scene.tweens.add({ targets: t, alpha: 0.55, delay: hold, duration: 800 }); + } + + say(text, dur = 2600) { + if (!text) return; + const s = this.scene; + this.bubble?.destroy(); + const b = BUBBLE; + const t = s.add.text(b.x + b.w / 2, b.y + b.h / 2, text, { + fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#2a1a10', align: 'center', wordWrap: { width: b.w - 36 }, + }).setOrigin(0.5); + const g = s.add.graphics(); + g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, b.y + 4, b.w, b.h, 12); + g.fillStyle(0xf3ead2, 1).fillRoundedRect(b.x, b.y, b.w, b.h, 12); + g.lineStyle(2, 0xb8321e, 1).strokeRoundedRect(b.x, b.y, b.w, b.h, 12); + const tx = plateParts('top').portrait.x + 40; + g.fillStyle(0xf3ead2, 1).fillTriangle(tx - 10, b.y + 1, tx + 10, b.y + 1, tx, b.y - 14); + const cont = s.add.container(0, 0, [g, t]).setDepth(this.depth + 8).setAlpha(0); + this.bubble = cont; + s.tweens.add({ targets: cont, alpha: 1, duration: 160 }); + s.tweens.add({ targets: cont, alpha: 0, delay: dur, duration: 300, onComplete: () => { cont.destroy(); if (this.bubble === cont) this.bubble = null; } }); + } + + emotion(e) { this.plates.top?.portrait?.playEmotion?.(e); } + hidePortraits() { Object.values(this.plates).forEach((p) => p.portrait?.setVideoVisible?.(false)); } + showPortraits() { Object.values(this.plates).forEach((p) => p.portrait?.setVideoVisible?.(true)); } +} diff --git a/src/games/othello/OthelloLayout.js b/src/games/othello/OthelloLayout.js new file mode 100644 index 0000000..6528d61 --- /dev/null +++ b/src/games/othello/OthelloLayout.js @@ -0,0 +1,116 @@ +// OthelloLayout.js: geometry for Kissa Kuro-Shiro (1920 × 1080). No Phaser. +// +// top centre the disc-count bar (tug of war), over a shelf of LPs +// left column opponent plaque · their disc tray · speech bubble · the +// rainy window on the street · your tray · your plaque +// centre the board on the low table, the Master's ribbon beneath +// right column status card · move sheet · buttons · the counter +// (record player, coffee siphon, a cup) +// +// The playing area is always 800 px square; the square size depends on +// the board (6×6, 8×8 or 10×10). + +export const W = 1920; +export const H = 1080; + +export const BOARD = 800; +export const BX = 560; +export const BY = 140; +export const FRAME = 46; +export const BOARD_TEX = BOARD + FRAME * 2; // 892 +export const BCX = BX + BOARD / 2; // 960 +export const BCY = BY + BOARD / 2; // 540 +export const BOARD_RECT = { x: BX - FRAME, y: BY - FRAME, w: BOARD_TEX, h: BOARD_TEX }; + +/** Disc radius at the 8×8 reference size; textures are baked for this. */ +export const DISC_R = 42; + +export function geom(size) { + const SQ = BOARD / size; + return { SQ, R: SQ * 0.42, scale: (SQ * 0.42) / DISC_R }; +} + +// columns +const LX = 30, RX = 1430, CW = 460; + +export const BAR = { x: BX, y: 28, w: BOARD, h: 40 }; + +export const PLATE = { w: CW, h: 196 }; +export const PLATES = { + top: { x: LX, y: 30 }, + bottom: { x: LX, y: 854 }, +}; +export const TRAYS = { + top: { x: LX + 20, y: 240, w: CW - 40, h: 44 }, + bottom: { x: LX + 20, y: 794, w: CW - 40, h: 44 }, +}; +export const BUBBLE = { x: LX, y: 298, w: CW, h: 84 }; +export const WINDOW = { x: 70, y: 424, w: 380, h: 290 }; +export const SIGN = { x: LX + CW / 2, y: 402 }; +export const NEON = { x: 150, y: 470 }; // the flickering sign across the street + +export const STATUS = { x: RX, y: 30, w: CW, h: 196 }; +export const LOG = { x: RX, y: 246, w: CW, h: 452 }; +export const LOG_ROWS = 12; +export const BTN = { w: 146, h: 48 }; +export const BUTTON_ROWS = [['undo', 'hint', 'study'], ['resign', 'menu']]; +export const BUTTONS = {}; +BUTTON_ROWS.forEach((row, ri) => { + const off = (3 - row.length) * (BTN.w + 11) / 2; + row.forEach((k, ci) => { BUTTONS[k] = { x: RX + off + BTN.w / 2 + ci * (BTN.w + 11), y: 736 + ri * 60 }; }); +}); +export const COUNTER = { x: RX - 10, y: 868, w: W - RX + 10, h: H - 868 }; +export const PLATTER = { x: 1536, y: 962, r: 70 }; +export const SIPHON = { x: 1752, y: 960 }; // centre of the lower globe +export const CUP = { x: 1866, y: 1010 }; + +export const RIBBON = { x: BX, y: 1002, w: BOARD, h: 62 }; +export const BANNER = { x: BCX, y: BCY - 40 }; + +export function plateParts(side) { + const P = PLATES[side]; + return { + portrait: { x: P.x + 96, y: P.y + 98, r: 70 }, + name: { x: P.x + 190, y: P.y + 46 }, + skill: { x: P.x + PLATE.w - 24, y: P.y + 46 }, + note: { x: P.x + 190, y: P.y + 90 }, + line: { x: P.x + 190, y: P.y + 130 }, + tally: { x: P.x + PLATE.w - 24, y: P.y + 162 }, + color: { x: P.x + 190 + 12, y: P.y + 164 }, + }; +} + +// For the verify harness: every HUD rectangle. +export function HUD_RECTS() { + const btns = Object.values(BUTTONS); + const bx0 = Math.min(...btns.map((b) => b.x)) - BTN.w / 2, by0 = Math.min(...btns.map((b) => b.y)) - BTN.h / 2; + const bx1 = Math.max(...btns.map((b) => b.x)) + BTN.w / 2, by1 = Math.max(...btns.map((b) => b.y)) + BTN.h / 2; + return { + bar: BAR, + plateTop: { ...PLATES.top, ...PLATE }, + plateBottom: { ...PLATES.bottom, ...PLATE }, + trayTop: TRAYS.top, + trayBottom: TRAYS.bottom, + bubble: BUBBLE, + window: WINDOW, + status: STATUS, + log: LOG, + buttons: { x: bx0, y: by0, w: bx1 - bx0, h: by1 - by0 }, + ribbon: RIBBON, + }; +} + +/** Screen centre of square sq on a size×size board. */ +export function squareXY(sq, size) { + const { SQ } = geom(size); + const r = Math.floor(sq / size), c = sq % size; + return { x: BX + c * SQ + SQ / 2, y: BY + r * SQ + SQ / 2 }; +} + +/** Square under a screen point, or -1. */ +export function cellAt(x, y, size) { + const { SQ } = geom(size); + const c = Math.floor((x - BX) / SQ), r = Math.floor((y - BY) / SQ); + if (c < 0 || c >= size || r < 0 || r >= size) return -1; + return r * size + c; +} diff --git a/src/games/othello/OthelloLogic.js b/src/games/othello/OthelloLogic.js index be8225d..938c11a 100644 --- a/src/games/othello/OthelloLogic.js +++ b/src/games/othello/OthelloLogic.js @@ -1,115 +1,324 @@ -// Pure game logic for Othello (Reversi). -// Board: 8×8 array, each cell = null | 'black' | 'white'. -// Black moves first (human). White is the AI. +// OthelloLogic.js: the rules, Phaser-free. Used by the scene, the engine +// worker, the end screen and tools/verifyOthello.js. +// +// A game state (`gs`) is plain JSON so it can be saved and undone: +// { size, variant, board: [null|'black'|'white' …size²], start: board copy, +// turn, phase: 'playing'|'game_over', winner: null|'black'|'white'|'draw', +// endReason: null|'full'|'blocked'|'wipeout'|'resign', ply, +// history: [{ color, sq, flips: [sq…], n: 'f5', book? } | { color, pass: true }], +// opening: null | { name, moves } } +// +// Squares are indexed sq = r * size + c, with row 0 at the top. Notation +// follows the tournament convention: column letter then row number, a1 is +// the top-left corner, so Black's usual first move is f5. +// +// Variants: 'standard' (most discs wins) and 'anti' (fewest discs wins). -export const SIZE = 8; +export const BLACK = 'black'; +export const WHITE = 'white'; +export const SIZES = [6, 8, 10]; -const DIRS = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]; +export const VARIANTS = { + standard: { + name: 'Othello', short: 'Othello', + blurb: 'Most discs at the end wins. Corners can never be flipped.', + }, + anti: { + name: 'Anti-Othello', short: 'Anti', + blurb: 'Everything backwards: the FEWEST discs at the end wins. Corners become a burden.', + }, +}; +export const VARIANT_ORDER = ['standard', 'anti']; -export function other(color) { return color === 'black' ? 'white' : 'black'; } -function inBounds(r, c) { return r >= 0 && r < SIZE && c >= 0 && c < SIZE; } +export const SIZE_INFO = { + 6: { name: '6×6 Quick', blurb: 'A short game on a small board. Every square matters.' }, + 8: { name: '8×8 Standard', blurb: 'The tournament board.' }, + 10: { name: '10×10 Grand', blurb: 'A long game with room to manoeuvre.' }, +}; -export function cloneState(state) { +const DIRS = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]; + +export function other(color) { return color === BLACK ? WHITE : BLACK; } + +export function rc(sq, size) { return [Math.floor(sq / size), sq % size]; } +export function sqOf(r, c, size) { return r * size + c; } + +export function notate(sq, size) { + const [r, c] = rc(sq, size); + return `${String.fromCharCode(97 + c)}${r + 1}`; +} + +export function parseSq(n, size) { + const m = /^([a-z])(\d{1,2})$/.exec(String(n).trim().toLowerCase()); + if (!m) return -1; + const c = m[1].charCodeAt(0) - 97, r = Number(m[2]) - 1; + if (r < 0 || r >= size || c < 0 || c >= size) return -1; + return sqOf(r, c, size); +} + +export function startBoard(size) { + const b = Array(size * size).fill(null); + const m = size / 2; + b[sqOf(m - 1, m - 1, size)] = WHITE; + b[sqOf(m - 1, m, size)] = BLACK; + b[sqOf(m, m - 1, size)] = BLACK; + b[sqOf(m, m, size)] = WHITE; + return b; +} + +export function createGame({ size = 8, variant = 'standard' } = {}) { + const board = startBoard(size); return { - board: state.board.map(row => [...row]), - turn: state.turn, - phase: state.phase, - winner: state.winner, + size, variant, board, start: board.slice(), turn: BLACK, phase: 'playing', + winner: null, endReason: null, ply: 0, history: [], opening: null, }; } -export function createInitialState() { - const board = Array.from({ length: SIZE }, () => Array(SIZE).fill(null)); - const m = SIZE / 2; - board[m-1][m-1] = 'white'; - board[m-1][m] = 'black'; - board[m][m-1] = 'black'; - board[m][m] = 'white'; - return { board, turn: 'black', phase: 'playing', winner: null }; -} - -// Returns all disc positions [{r,c}] that would flip if `color` placed at (r,c). -export function getFlips(board, r, c, color) { - if (board[r][c] !== null) return []; +/** Squares `color` would flip by playing sq (empty array = illegal). */ +export function flipsFor(board, size, sq, color) { + if (board[sq] !== null) return []; const opp = other(color); - const flips = []; + const [r0, c0] = rc(sq, size); + const out = []; for (const [dr, dc] of DIRS) { + let r = r0 + dr, c = c0 + dc; const line = []; - let nr = r + dr, nc = c + dc; - while (inBounds(nr, nc) && board[nr][nc] === opp) { - line.push({ r: nr, c: nc }); - nr += dr; nc += dc; - } - if (line.length > 0 && inBounds(nr, nc) && board[nr][nc] === color) { - flips.push(...line); + while (r >= 0 && r < size && c >= 0 && c < size && board[r * size + c] === opp) { + line.push(r * size + c); + r += dr; c += dc; } + if (line.length && r >= 0 && r < size && c >= 0 && c < size && board[r * size + c] === color) out.push(...line); } - return flips; + return out; } -// Returns all valid placement positions [{r,c}] for `color`. -export function getValidMoves(state, color) { - if (state.phase === 'game_over') return []; - const moves = []; - for (let r = 0; r < SIZE; r++) { - for (let c = 0; c < SIZE; c++) { - if (state.board[r][c] !== null) continue; - if (getFlips(state.board, r, c, color).length > 0) moves.push({ r, c }); +/** Flips grouped by ray, each ray ordered outward from sq (for the cascade). */ +export function flipRays(board, size, sq, color) { + const opp = other(color); + const [r0, c0] = rc(sq, size); + const rays = []; + for (const [dr, dc] of DIRS) { + let r = r0 + dr, c = c0 + dc; + const line = []; + while (r >= 0 && r < size && c >= 0 && c < size && board[r * size + c] === opp) { + line.push(r * size + c); + r += dr; c += dc; } + if (line.length && r >= 0 && r < size && c >= 0 && c < size && board[r * size + c] === color) rays.push({ dr, dc, sqs: line }); } - return moves; + return rays; } -export function mustPass(state, color) { - return state.phase !== 'game_over' && getValidMoves(state, color).length === 0; +export function movesFor(board, size, color) { + const out = []; + for (let sq = 0; sq < board.length; sq++) { + if (board[sq] !== null) continue; + const f = flipsFor(board, size, sq, color); + if (f.length) out.push({ sq, flips: f }); + } + return out; } -export function applyMove(state, move) { - const s = cloneState(state); - const { r, c } = move; - const color = s.turn; +export function hasMove(board, size, color) { + for (let sq = 0; sq < board.length; sq++) { + if (board[sq] === null && flipsFor(board, size, sq, color).length) return true; + } + return false; +} - // Compute flips on the board before placing, then place + flip. - const flips = getFlips(s.board, r, c, color); - s.board[r][c] = color; - for (const f of flips) s.board[f.r][f.c] = color; +/** Legal moves for the side to move. */ +export function legalMoves(gs) { + if (gs.phase !== 'playing') return []; + return movesFor(gs.board, gs.size, gs.turn); +} +export function countsOf(board) { + let black = 0, white = 0, empty = 0; + for (const v of board) { if (v === BLACK) black++; else if (v === WHITE) white++; else empty++; } + return { black, white, empty }; +} +export function counts(gs) { return countsOf(gs.board); } + +export function winnerOf(board, variant) { + const { black, white } = countsOf(board); + if (black === white) return 'draw'; + const more = black > white ? BLACK : WHITE; + return variant === 'anti' ? other(more) : more; +} + +function finish(s, reason) { + s.phase = 'game_over'; + s.winner = winnerOf(s.board, s.variant); + const { black, white, empty } = countsOf(s.board); + s.endReason = reason ?? ((black === 0 || white === 0) ? 'wipeout' : empty === 0 ? 'full' : 'blocked'); +} + +function copy(gs) { + return { ...gs, board: gs.board.slice(), history: gs.history.slice() }; +} + +/** + * Play sq for the side to move. Records a pass for the next side when it + * has no reply, and ends the game when neither side can move. + */ +export function applyMove(gs, sq, { book = false } = {}) { + const color = gs.turn; + const flips = flipsFor(gs.board, gs.size, sq, color); + if (!flips.length) throw new Error(`illegal move ${notate(sq, gs.size)} for ${color}`); + const s = copy(gs); + s.board[sq] = color; + for (const f of flips) s.board[f] = color; + const h = { color, sq, flips, n: notate(sq, s.size) }; + if (book) h.book = true; + s.history.push(h); + s.ply = gs.ply + 1; const next = other(color); - const nextHasMoves = getValidMoves(s, next).length > 0; - const selfHasMoves = getValidMoves(s, color).length > 0; - - if (nextHasMoves) { - s.turn = next; - } else if (selfHasMoves) { - s.turn = color; // opponent must pass; same player continues - } else { - s.phase = 'game_over'; - s.winner = _winner(s.board); - } + if (hasMove(s.board, s.size, next)) s.turn = next; + else if (hasMove(s.board, s.size, color)) { + s.history.push({ color: next, pass: true }); + s.turn = color; + } else finish(s); return s; } -export function isGameOver(state) { return state.phase === 'game_over'; } +export function resign(gs, color) { + const s = copy(gs); + s.phase = 'game_over'; + s.winner = other(color); + s.endReason = 'resign'; + return s; +} -export function getScore(state) { - let black = 0, white = 0; - for (const row of state.board) - for (const cell of row) { - if (cell === 'black') black++; - else if (cell === 'white') white++; +/** Board after the first n history entries (passes count as entries). */ +export function boardAfter(gs, n) { + const b = (gs.start ?? startBoard(gs.size)).slice(); + for (let i = 0; i < Math.min(n, gs.history.length); i++) { + const h = gs.history[i]; + if (h.pass) continue; + b[h.sq] = h.color; + for (const f of h.flips) b[f] = h.color; + } + return b; +} + +/** Placed moves only (no passes). */ +export function placed(gs) { return gs.history.filter((h) => !h.pass); } + +/** Disc difference (black − white) after each history entry, starting position first. */ +export function discTrace(gs) { + const out = []; + const b = (gs.start ?? startBoard(gs.size)).slice(); + const diff = () => { const c = countsOf(b); return c.black - c.white; }; + out.push(diff()); + for (const h of gs.history) { + if (!h.pass) { + b[h.sq] = h.color; + for (const f of h.flips) b[f] = h.color; } - return { black, white }; + out.push(diff()); + } + return out; } -export function getWinner(state) { - if (state.phase !== 'game_over') return null; - return state.winner; +export function isCorner(sq, size) { + const [r, c] = rc(sq, size), e = size - 1; + return (r === 0 || r === e) && (c === 0 || c === e); } -function _winner(board) { - let b = 0, w = 0; - for (const row of board) for (const c of row) { if (c === 'black') b++; else if (c === 'white') w++; } - if (b > w) return 'black'; - if (w > b) return 'white'; - return 'draw'; +export function isEdge(sq, size) { + const [r, c] = rc(sq, size), e = size - 1; + return r === 0 || r === e || c === 0 || c === e; +} + +/** The corner an X-square (diagonal neighbour of a corner) guards, or -1. */ +export function xCorner(sq, size) { + const [r, c] = rc(sq, size), e = size - 1; + if ((r === 1 || r === e - 1) && (c === 1 || c === e - 1)) return sqOf(r === 1 ? 0 : e, c === 1 ? 0 : e, size); + return -1; +} + +/** The corner a C-square (edge neighbour of a corner) touches, or -1. */ +export function cCorner(sq, size) { + const [r, c] = rc(sq, size), e = size - 1; + if ((r === 0 || r === e) && (c === 1 || c === e - 1)) return sqOf(r, c === 1 ? 0 : e, size); + if ((c === 0 || c === e) && (r === 1 || r === e - 1)) return sqOf(r === 1 ? 0 : e, c, size); + return -1; +} + +export function corners(size) { + const e = size - 1; + return [0, e, e * size, e * size + e]; +} + +/** + * Discs that can never be flipped again: a disc is stable when, along each + * of the four lines through it, one neighbour is the edge or a stable disc + * of its colour, or the whole line is full. Conservative (it may miss some). + */ +export function stableDiscs(board, size) { + const N = size * size; + const stable = new Uint8Array(N); + const axes = [[0, 1], [1, 0], [1, 1], [1, -1]]; + const at = (r, c) => (r < 0 || r >= size || c < 0 || c >= size ? undefined : r * size + c); + // full lines + const lineFull = (r0, c0, dr, dc) => { + let r = r0, c = c0; + while (at(r - dr, c - dc) !== undefined) { r -= dr; c -= dc; } + for (; at(r, c) !== undefined; r += dr, c += dc) if (board[r * size + c] === null) return false; + return true; + }; + const full = axes.map(([dr, dc]) => { + const f = new Uint8Array(N); + for (let sq = 0; sq < N; sq++) { const [r, c] = rc(sq, size); f[sq] = lineFull(r, c, dr, dc) ? 1 : 0; } + return f; + }); + let changed = true; + while (changed) { + changed = false; + for (let sq = 0; sq < N; sq++) { + const v = board[sq]; + if (!v || stable[sq]) continue; + const [r, c] = rc(sq, size); + let ok = true; + for (let a = 0; a < 4 && ok; a++) { + if (full[a][sq]) continue; + const [dr, dc] = axes[a]; + const p = at(r - dr, c - dc), q = at(r + dr, c + dc); + const anchored = (x) => x === undefined || (board[x] === v && stable[x]); + if (!anchored(p) && !anchored(q)) ok = false; + } + if (ok) { stable[sq] = 1; changed = true; } + } + } + const out = []; + for (let sq = 0; sq < N; sq++) if (stable[sq]) out.push(sq); + return out; +} + +/** Per-colour totals for the end screen. */ +export function stats(gs, color) { + let moves = 0, flips = 0, biggest = 0, cornerCount = 0, passes = 0; + for (const h of gs.history) { + if (h.color !== color) continue; + if (h.pass) { passes++; continue; } + if (h.book) continue; + moves++; + flips += h.flips.length; + biggest = Math.max(biggest, h.flips.length); + if (isCorner(h.sq, gs.size)) cornerCount++; + } + const c = countsOf(gs.board); + return { moves, flips, biggest, corners: cornerCount, passes, discs: color === BLACK ? c.black : c.white }; +} + +/** Discs each colour still has in hand (the 64-disc set is split evenly; a + * player who runs out borrows from the other, as in the box rules). */ +export function supply(gs) { + const each = (gs.size * gs.size) / 2 - 2; + let pb = 0, pw = 0; + for (const h of gs.history) { if (h.pass) continue; if (h.color === BLACK) pb++; else pw++; } + let b = each - pb, w = each - pw; + if (b < 0) { w += b; b = 0; } + if (w < 0) { b += w; w = 0; } + return { black: Math.max(0, b), white: Math.max(0, w), each }; } diff --git a/src/games/othello/OthelloPieces.js b/src/games/othello/OthelloPieces.js new file mode 100644 index 0000000..afd1bf5 --- /dev/null +++ b/src/games/othello/OthelloPieces.js @@ -0,0 +1,205 @@ +// OthelloPieces.js: the discs on the felt. Each disc is a shadow, a +// container holding the face (and an edge band for the moment it stands on +// its side), and a highlight that never rotates. +// +// A flip squashes the container along the capture ray (the container is +// rotated to that ray and the face counter-rotated, so the art stays +// upright), shows the edge band at the half-way point, swaps the face, and +// lands with a small bounce. Placement throws a disc in from the tray. + +import { squareXY, geom } from './OthelloLayout.js'; +import { RES, EDGE_TEX } from './OthelloArt.js'; + +const EDGE_PX = 8; // the disc's thickness on screen at the 8×8 size + +export class DiscSet { + constructor(scene, depth) { + this.scene = scene; + this.depth = depth; + this.items = new Map(); // sq → item + this.size = 8; + this.live = new Set(); // running tweens, stopped when the board is cleared + } + + get base() { return geom(this.size).scale / RES; } + + build(board, size) { + this.clear(); + this.size = size; + board.forEach((v, sq) => { if (v) this.items.set(sq, this.make(sq, v)); }); + return this; + } + + make(sq, color, at = null) { + const s = this.scene; + const { x, y } = at ?? squareXY(sq, this.size); + const shadow = s.add.image(x, y, 'ot-shadow').setDepth(this.depth - 1); + const body = s.add.image(0, 0, `ot-disc-${color}`); + const edge = s.add.image(0, 0, 'ot-edge').setVisible(false); + const cont = s.add.container(x, y, [edge, body]); + const sheen = s.add.image(x, y, 'ot-sheen'); + const it = { sq, color, shadow, body, edge, cont, sheen, x, y, lift: 0, axis: 0, phi: 0, grow: 1 }; + this.render(it); + return it; + } + + destroyItem(it) { + it.dead = true; + it.shadow.destroy(); it.cont.destroy(); it.sheen.destroy(); + } + + clear() { + for (const t of this.live) t.stop(); + this.live.clear(); + for (const it of this.items.values()) this.destroyItem(it); + this.items.clear(); + } + + get(sq) { return this.items.get(sq); } + all() { return [...this.items.values()]; } + + /** Push an item's state (position, lift, flip angle) to its game objects. */ + render(it) { + if (it.dead) return; + const b = this.base * it.grow; + const s = Math.abs(Math.cos(it.phi)); + const lift = it.lift * geom(this.size).scale; + it.cont.setPosition(it.x, it.y - lift).setRotation(it.axis).setScale(b, b * Math.max(0.02, s)); + it.body.setRotation(-it.axis); + const side = Math.sin(it.phi); + if (side > 0.05) { + const want = side * EDGE_PX * geom(this.size).scale; + it.edge.setVisible(true).setScale(1, want / (EDGE_TEX.h * b * Math.max(0.02, s))); + } else it.edge.setVisible(false); + it.sheen.setPosition(it.x, it.y - lift).setScale(b).setAlpha(s * s * 0.9); + const sh = 1 + lift / 140; + it.shadow.setPosition(it.x + 3 + lift * 0.3, it.y + 6 + lift * 0.45).setScale(b * sh, b * sh * (0.4 + 0.6 * s)) + .setAlpha(0.75 - Math.min(0.45, lift / 110)); + const d = this.depth + (lift > 1 ? 20 : 0) + it.y / 2000; + it.cont.setDepth(d); it.sheen.setDepth(d + 0.0001); + } + + tween(cfg) { + return new Promise((res) => { + const t = this.scene.tweens.add({ ...cfg, onComplete: () => { this.live.delete(t); res(); } }); + this.live.add(t); + }); + } + + async bounce(it, amt = 0.1, dur = 120) { + const o = { t: 0 }; + await this.tween({ + targets: o, t: 1, duration: dur, ease: 'Sine.Out', + onUpdate: () => { it.grow = 1 + Math.sin(o.t * Math.PI) * amt; this.render(it); }, + }); + it.grow = 1; this.render(it); + } + + /** + * Flip the disc on sq to `color`, squashing along the ray (dr, dc). + * onSwap fires at the moment it stands on edge (for the sound). + */ + async flip(sq, color, { dr = 0, dc = 1, delay = 0, dur = 300, lift = 22, onSwap = null } = {}) { + const it = this.items.get(sq); + if (!it || it.dead) return; + it.axis = Math.atan2(dr, dc) - Math.PI / 2; + const o = { p: 0 }; + let swapped = false; + await this.tween({ + targets: o, p: 1, delay, duration: dur, ease: 'Sine.InOut', + onUpdate: () => { + it.phi = o.p * Math.PI; + it.lift = Math.sin(o.p * Math.PI) * lift; + if (it.dead) return; + if (!swapped && o.p >= 0.5) { + swapped = true; + it.color = color; + it.body.setTexture(`ot-disc-${color}`); + onSwap?.(); + } + this.render(it); + }, + }); + if (it.dead) return; + if (!swapped) { it.color = color; it.body.setTexture(`ot-disc-${color}`); } + it.phi = 0; it.lift = 0; it.axis = 0; + this.render(it); + await this.bounce(it, 0.06, 110); + } + + /** Set a disc's colour with no animation. */ + setColor(sq, color) { + const it = this.items.get(sq); + if (!it || it.dead) return; + it.color = color; + it.body.setTexture(`ot-disc-${color}`); + } + + /** Throw a disc from `from` (the tray) to sq, arcing over the table. */ + async place(sq, color, from, { dur = 380, arc = 90 } = {}) { + const to = squareXY(sq, this.size); + const it = this.make(sq, color, from); + this.items.set(sq, it); + it.grow = 0.7; + const o = { t: 0 }; + await this.tween({ + targets: o, t: 1, duration: dur, ease: 'Sine.InOut', + onUpdate: () => { + const t = o.t; + it.x = from.x + (to.x - from.x) * t; + it.y = from.y + (to.y - from.y) * t; + it.lift = Math.sin(Math.PI * t) * arc + (1 - t) * 10; + it.grow = 0.7 + 0.3 * t; + this.render(it); + }, + }); + it.x = to.x; it.y = to.y; it.lift = 0; it.grow = 1; + this.render(it); + await this.bounce(it, 0.12, 130); + return it; + } + + /** Drop a disc straight down onto sq (the starting four). */ + async drop(sq, color, { delay = 0, height = 160, dur = 260 } = {}) { + const it = this.make(sq, color); + this.items.set(sq, it); + it.lift = height; + it.cont.setAlpha(0); it.sheen.setAlpha(0); it.shadow.setAlpha(0); + this.render(it); + await new Promise((res) => this.scene.time.delayedCall(delay, res)); + if (it.dead) return; + it.cont.setAlpha(1); + const o = { l: height }; + await this.tween({ targets: o, l: 0, duration: dur, ease: 'Quad.In', onUpdate: () => { it.lift = o.l; this.render(it); } }); + it.lift = 0; this.render(it); + await this.bounce(it, 0.1, 110); + } + + /** Slide discs to new squares (the count-out). moves: [[fromSq, toSq]…]. */ + async arrange(moves, { stagger = 18, dur = 360 } = {}) { + const jobs = []; + const next = new Map(); + moves.forEach(([from, to], i) => { + const it = this.items.get(from); + if (!it) return; + next.set(to, it); + const a = { x: it.x, y: it.y }, b = squareXY(to, this.size); + it.sq = to; + const o = { t: 0 }; + jobs.push(this.tween({ + targets: o, t: 1, delay: i * stagger, duration: dur, ease: 'Cubic.InOut', + onUpdate: () => { + it.x = a.x + (b.x - a.x) * o.t; it.y = a.y + (b.y - a.y) * o.t; + it.lift = Math.sin(Math.PI * o.t) * 16; + this.render(it); + }, + })); + }); + // discs not mentioned stay where they are + for (const [sq, it] of this.items) if (!moves.some(([f]) => f === sq)) next.set(sq, it); + this.items = next; + await Promise.all(jobs); + } + + setVisible(v) { for (const it of this.items.values()) { it.cont.setVisible(v); it.sheen.setVisible(v); it.shadow.setVisible(v); } } +} diff --git a/src/games/othello/OthelloSound.js b/src/games/othello/OthelloSound.js new file mode 100644 index 0000000..cb4a5d7 --- /dev/null +++ b/src/games/othello/OthelloSound.js @@ -0,0 +1,215 @@ +// OthelloSound.js: little Web Audio synths for the kissa. No audio files; +// silent without Web Audio or when muted. +// +// clack(scene) a disc set down on the felt +// flip(scene, { k }) a disc turning over; the k-th along a run rings a +// step higher (a run of flips climbs a scale) +// slide(scene) a disc lifted out of the tray +// deny(scene) that square isn't a move +// chime(scene) a corner taken: a vibraphone note +// sting(scene, kind) 'win' / 'lose' / 'draw': a jazz voicing on vibes +// Ambience rain on the glass, record crackle, now and then the +// siphon burbling or a cup on a saucer + +function ctxOf(scene) { + const sm = scene?.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} +const noiseCache = new WeakMap(); +function noise(ac) { + if (noiseCache.has(ac)) return noiseCache.get(ac); + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + noiseCache.set(ac, buf); + return buf; +} +function out(scene, ac, gain) { + const sm = scene.sound; + const node = sm.masterVolumeNode ?? sm.destination ?? null; + const g = ac.createGain(); + g.gain.value = node ? gain : gain * (sm.volume ?? 1); + g.connect(node ?? ac.destination); + return g; +} +function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.003, trem = 0 } = {}) { + const o = ac.createOscillator(); o.type = type; + o.frequency.setValueAtTime(f, t0); + if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(a, t0 + attack); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + if (trem) { + // vibraphone motor: a slow wobble, multiplied into the note (not added) + const tg = ac.createGain(); tg.gain.value = 1 - trem; + const lfo = ac.createOscillator(); lfo.frequency.value = 5.5; + const lg = ac.createGain(); lg.gain.value = trem; + lfo.connect(lg); lg.connect(tg.gain); lfo.start(t0); lfo.stop(t0 + d + 0.05); + o.connect(tg); tg.connect(g); + } else o.connect(g); + g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03); +} +function tick(ac, dest, t0, f, vol = 1, d = 0.03, q = 3) { + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = f; bp.Q.value = q; + const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02); +} +const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } }; +const semi = (f, n) => f * Math.pow(2, n / 12); +const PENTA = [0, 2, 4, 7, 9, 12, 14, 16, 19, 21, 24]; + +/** A vibraphone bar: fundamental + the 4th partial, motor tremolo. */ +function vibe(ac, dest, t, f, a = 0.5, d = 1.4) { + tone(ac, dest, t, f, { type: 'sine', a, d, trem: 0.25 }); + tone(ac, dest, t, f * 4, { type: 'sine', a: a * 0.12, d: d * 0.35 }); + tick(ac, dest, t, f * 6, a * 0.25, 0.01); +} + +export function clack(scene, { vol = 0.12 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.003; + // a plastic disc on felt over wood: a soft thump with a little click + tone(ac, dest, t, 150, { a: 0.9, d: 0.08, glide: 0.7 }); + tick(ac, dest, t, 1300, 0.7, 0.03, 1.5); + tick(ac, dest, t + 0.002, 3600, 0.25, 0.012); + }); +} + +export function flip(scene, { k = 0, vol = 0.07 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.003; + const f = semi(520, PENTA[Math.min(k, PENTA.length - 1)]); + tick(ac, dest, t, 2600 + k * 120, 0.8, 0.018); + tone(ac, dest, t + 0.01, f, { type: 'triangle', a: 0.35, d: 0.09 }); + tick(ac, dest, t + 0.05, 1500, 0.5, 0.02); + }); +} + +export function slide(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003; + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.setValueAtTime(900, t); bp.frequency.linearRampToValueAtTime(2400, t + 0.12); bp.Q.value = 1.2; + const g = ac.createGain(); g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(0.7, t + 0.03); g.gain.exponentialRampToValueAtTime(0.0005, t + 0.16); + n.connect(bp); bp.connect(g); g.connect(dest); n.start(t, Math.random()); n.stop(t + 0.2); + }); +} + +export function deny(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.08), t = ac.currentTime + 0.003; + tone(ac, dest, t, 160, { a: 0.8, d: 0.12, glide: 0.7 }); + tick(ac, dest, t, 700, 0.5); + }); +} + +export function chime(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.09), t = ac.currentTime + 0.01; + vibe(ac, dest, t, 784, 0.5, 1.6); + vibe(ac, dest, t + 0.09, 1175, 0.35, 1.4); + }); +} + +export function sting(scene, kind = 'win') { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.08), t = ac.currentTime + 0.02; + if (kind === 'win') { + // ii–V–I: Dm9 → G13 → Cmaj9, rolled + [[0, [147, 175, 220, 262, 330]], [0.45, [98, 175, 247, 330, 440]], [0.95, [131, 165, 247, 294, 392]]].forEach(([at, ch]) => { + ch.forEach((f, i) => vibe(ac, dest, t + at + i * 0.035, f * 2, 0.32, at > 0.9 ? 2.4 : 0.8)); + }); + } else if (kind === 'lose') { + [[0, [110, 131, 165, 196]], [0.6, [104, 123, 156, 185]]].forEach(([at, ch]) => { + ch.forEach((f, i) => vibe(ac, dest, t + at + i * 0.05, f * 2, 0.3, at > 0.5 ? 2 : 0.9)); + }); + } else { + [131, 165, 196, 247, 294].forEach((f, i) => vibe(ac, dest, t + i * 0.06, f * 2, 0.3, 1.8)); + } + }); +} + +export class Ambience { + constructor(scene) { this.scene = scene; this.on = false; this.timer = null; this.beds = []; } + + start() { + if (this.on) return; + this.on = true; + const ac = ctxOf(this.scene); + if (ac) { + safe(() => { + // steady rain: band-limited noise, slowly breathing + const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true; + const hp = ac.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 900; + const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 5000; + const g = out(this.scene, ac, 0.0); + g.gain.setValueAtTime(0, ac.currentTime); + g.gain.linearRampToValueAtTime(0.014, ac.currentTime + 2.5); + const lfo = ac.createOscillator(); lfo.frequency.value = 0.07; + const lg = ac.createGain(); lg.gain.value = 0.005; + lfo.connect(lg); lg.connect(g.gain); + src.connect(hp); hp.connect(lp); lp.connect(g); + src.start(); lfo.start(); + this.beds.push({ src, lfo, g }); + }); + } + // record crackle: sparse clicks + const crackle = () => { + if (!this.on) return; + this.crackleTimer = setTimeout(crackle, 60 + Math.random() * 260); + const a = ctxOf(this.scene); if (!a) return; + safe(() => { + const dest = out(this.scene, a, 0.006 + Math.random() * 0.01), t = a.currentTime + 0.005; + tick(a, dest, t, 2000 + Math.random() * 5000, 0.8, 0.004 + Math.random() * 0.006, 0.8); + }); + }; + this.crackleTimer = setTimeout(crackle, 800); + const event = () => { + this.timer = setTimeout(event, 7000 + Math.random() * 9000); + const a = ctxOf(this.scene); if (!a) return; + safe(() => { + const dest = out(this.scene, a, 0.02), t = a.currentTime + 0.02; + const r = Math.random(); + if (r < 0.45) { + // the siphon burbles + for (let i = 0; i < 7; i++) tone(a, dest, t + i * 0.07 + Math.random() * 0.04, 280 + Math.random() * 220, { a: 0.4, d: 0.06, glide: 1.7 }); + } else if (r < 0.75) { + // a cup set down on a saucer, somewhere along the counter + tone(a, dest, t, 2400 + Math.random() * 400, { type: 'triangle', a: 0.25, d: 0.25 }); + tick(a, dest, t, 3200, 0.5, 0.02); + } else { + // a heavy drop off the eaves + tone(a, dest, t, 900 + Math.random() * 600, { a: 0.5, d: 0.08, glide: 0.5 }); + } + }); + }; + this.timer = setTimeout(event, 3000); + } + + stop() { + this.on = false; + clearTimeout(this.timer); this.timer = null; + clearTimeout(this.crackleTimer); this.crackleTimer = null; + for (const { src, lfo, g } of this.beds) { + safe(() => { + const ac = src.context; + g.gain.cancelScheduledValues(ac.currentTime); + g.gain.setValueAtTime(g.gain.value, ac.currentTime); + g.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6); + src.stop(ac.currentTime + 0.7); lfo.stop(ac.currentTime + 0.7); + }); + } + this.beds = []; + } + + setOn(on) { if (on) this.start(); else this.stop(); } +} diff --git a/src/games/othello/OthelloTalk.js b/src/games/othello/OthelloTalk.js new file mode 100644 index 0000000..977bdf7 --- /dev/null +++ b/src/games/othello/OthelloTalk.js @@ -0,0 +1,116 @@ +// OthelloTalk.js: table talk at Kissa Kuro-Shiro. Two voices: +// masterLine(kind, ctx) the Master: owner, barista, keeper of the +// board under the counter. Few words, all of +// them about coffee, jazz or the corners. +// opponentLine(kind, tier) whoever sits across the table: +// 'rookie' (skill 1–2) · 'regular' (3) · 'shark' (4–5) +// Each returns a line or null (some moments only get a remark now and then). + +const pick = (a) => a[Math.floor(Math.random() * a.length)]; +const fill = (s, ctx = {}) => s.replace(/\{(\w+)\}/g, (_, k) => (ctx[k] ?? '')); + +const MASTER = { + welcome: [ + 'Rain again. Good night for a slow record and a long game.', + 'Sit. The siphon\'s on. I\'ll bring the board.', + 'Black and white on the turntable, black and white on the felt.', + 'Coffee\'s brewing. Take your time with the first move.', + ], + welcomeBack: [ + 'The discs are where you left them. So is your coffee, I\'m afraid.', + 'Back. I kept the board as it was.', + ], + newGame: ['Turn the record over. New game.', 'Swap colours. Clear the felt.'], + card: [ + 'From the card box: the {name}. The first moves are already down.', + 'Tonight\'s card is the {name}. Play on from here.', + ], + opening: ['That is the {name}.', 'The {name}. An old friend.', null], + anti: ['Remember: tonight, the fewest discs wins. Everything you know, backwards.'], + size6: ['The small board. Every square counts double.'], + size10: ['The big board. Long games need a second cup.'], + humanCorner: ['A corner. Nobody can take that from you.', 'Corner. Good.', 'That disc will still be yours when the record ends.'], + aiCorner: ['They have a corner now. Careful along that edge.', 'Corner to them. Hm.', null], + humanBig: ['{n} discs. Big flips look strong, but count their replies.', 'Lots of discs. Lots of doors opened.', null], + aiBig: ['They took {n}. Don\'t worry; discs in the middle game are cheap.', null, null], + humanPass: ['You have no move. You pass, they go again.'], + aiPass: ['They have no move. Your turn again.', 'Nothing for them. Play on.'], + wipeout: ['Not a single disc left. That almost never happens.'], + hint: ['Look at {move}: it {reason}.', 'I would play {move}. It {reason}.', '{move}. It {reason}.'], + warnCorner: [ + 'Careful. That move lets them into a corner.', + 'Hm. After that, a corner opens for them.', + ], + endgame: ['Few squares left. Count the parity: who gets the last move in each region?', null], + solved: ['From here, the board is solved: {line}.', null], + undo: ['Take it back. The record doesn\'t mind.', 'One more look. Fine.', null], + resign: ['Tipping the board. Another cup, another game.'], + count: ['Now we count. Black from the top, white from the bottom.', 'Let\'s count them out.'], + win: [ + 'Well played. That one goes in the notebook behind the counter.', + 'Beautiful game. Like a good solo, it built slowly.', + 'You won. I\'ll put on something celebratory.', + ], + loss: [ + 'They had your number tonight. Another cup?', + 'Close. Corners decide these things.', + 'You\'ll get them. Watch the X-squares.', + ], + draw: ['Thirty-two each. Perfectly balanced, like a good blend.', 'A draw. Rare, and beautiful.'], + matchWin: ['The match is yours. This cup is on the house.', 'You took the match. Not bad at all.'], + matchLoss: ['The match goes to them. Come back Thursday.', 'They took the match. The board will be here.'], + matchDraw: ['An even match. I\'ll call it a draw and wash the cups.'], + review: ['I went over your game while you weren\'t looking.'], +}; + +const OPP = { + rookie: { + greet: ['I usually just play on my phone.', 'Black goes first? Or white? Kidding!', 'Go easy, OK?'], + big: ['Look at all those!', 'Wow, they all flipped!', 'Did I just do that?'], + corner: ['Ooh, a corner! That\'s good, right?'], + lostBig: ['Hey, those were mine!', 'Aw, all of them?'], + lostCorner: ['Wait, is the corner important?', 'Oh no, not the corner.'], + pass: ['I can\'t go anywhere?', 'Uh… pass, I guess.'], + win: ['I won? Really?', 'Beginner\'s luck!'], + lose: ['Good game! You\'re really good at this.', 'Rematch? I think I get it now.'], + draw: ['A tie! I\'ll take it.'], + }, + regular: { + greet: ['Same table as always.', 'Thursday night, rain, Othello. Perfect.', 'Let\'s see the corners tonight.'], + big: ['A nice row of them.', 'That\'ll do.'], + corner: ['Corner. Thank you.', 'I\'ll take that corner.'], + lostBig: ['Hm. Plenty of game left.', 'Discs come and go.'], + lostCorner: ['Should have seen that.', 'There goes my corner.'], + pass: ['Pass.', 'Nothing for me. Go ahead.'], + win: ['Good game. Another round?', 'That one\'s mine.'], + lose: ['Well played. You earned it.', 'You read that endgame well.'], + draw: ['Dead even. Honest result.'], + }, + shark: { + greet: ['I counted the endgame before you sat down.', 'Mobility first. Discs later.', 'Let\'s see if you know parity.'], + big: ['Calculated.', 'Fine.'], + corner: ['Corner. As planned.', 'And the corner.'], + lostBig: ['Take them. They\'ll be back.', 'Greedy. Good for me.'], + lostCorner: ['…Well found.', 'I underrated that.'], + pass: ['Pass. Go on.', 'You have the move.'], + win: ['Study your endgames.', 'Expected. Again?'], + lose: ['Well played. Truly.', 'You saw further tonight.'], + draw: ['A fair result.'], + }, +}; + +export function tierOf(skill) { return skill <= 2 ? 'rookie' : skill === 3 ? 'regular' : 'shark'; } + +export function masterLine(kind, ctx = {}) { + const list = MASTER[kind]; + if (!list) return null; + const s = pick(list); + return s ? fill(s, ctx) : null; +} + +export function opponentLine(kind, tier, ctx = {}) { + const list = OPP[tier]?.[kind]; + if (!list) return null; + const s = pick(list); + return s ? fill(s, ctx) : null; +} diff --git a/src/games/othello/OthelloWorker.js b/src/games/othello/OthelloWorker.js new file mode 100644 index 0000000..a407312 --- /dev/null +++ b/src/games/othello/OthelloWorker.js @@ -0,0 +1,11 @@ +// OthelloWorker.js: the module worker the kissa's engine runs in. +// See OthelloEngine.js for the message kinds. + +import { handle } from './OthelloEngine.js'; + +self.onmessage = (e) => { + const { id, kind, payload } = e.data ?? {}; + let res = null, err = null; + try { res = handle(kind, payload); } catch (ex) { err = String(ex?.message ?? ex); } + self.postMessage({ id, res, err }); +}; diff --git a/src/games/othello/tutorial.md b/src/games/othello/tutorial.md new file mode 100644 index 0000000..cc17770 --- /dev/null +++ b/src/games/othello/tutorial.md @@ -0,0 +1,69 @@ +# Welcome to Othello + +*By the Master: owner of Kissa Kuro-Shiro, maker of siphon coffee, keeper of the board under the counter since 1971* + +--- + +*Turns the record over, sets down two cups, and slides the green board onto the table* + +Sit. Rain like this, nobody's in a hurry. The game takes a minute to learn and the rest of your life to play well. I'll tell you the minute. + +## The Goal + +There are 64 discs, black on one side and white on the other. When the board is full, or nobody can move, **whoever has more discs showing their colour wins.** + +In **Anti-Othello** it's the other way round: **fewest discs wins.** + +## The Board + +Eight by eight, green felt. Four discs start in the middle, two of each colour, crossed. **Black always moves first.** In a match, colours swap every game. + +Squares are named like a map: a letter for the column (a to h, left to right) and a number for the row (1 to 8, top to bottom). Black's usual first move is **f5**. + +## Making a Move + +- Put a disc down, your colour up, so that it **traps a line of the other colour's discs** between it and another of your discs. The line can run across, up and down, or diagonally. +- **Every trapped disc turns over** to your colour. One disc can trap lines in several directions at once, and all of them flip. +- **A move has to flip at least one disc.** If it doesn't, it isn't a move. +- If you have no move at all, you **pass**, and the other player goes again. If neither of you can move, the game is over. + +Each of you has a tray of discs. If yours runs out, you borrow from the other tray, as the box rules say. + +## How to Play Here + +| Do this | And this happens | +|---|---| +| **Hover a marked square** | A ghost disc shows where you'd play, every disc it would flip gets a gold ring, and the number tells you how many. | +| **Click a marked square** (or arrow keys and Enter) | The disc comes out of your tray and the lines turn over, one after another. | +| **Z / Undo** | Takes back your last move (and the reply). | +| **H / Hint** | I'll point at a move and tell you why I like it. Near the end, I can see all the way to the last disc. | +| **S / Study** | Marks for learning: the dangerous X- and C-squares, how many replies each of your moves leaves them, and discs that can never be flipped again. | +| **Resign** | Ends the game. | +| **Esc / Menu** | Settings, these rules, a new match, or leaving. | + +If you're about to open a corner for the other player, I'll lean over and ask if you're sure. You can switch that off in the menu. + +## Setting Up + +| Option | Choices | +|---|---| +| **Your colour** | Black (moves first), White, or a coin toss. | +| **Match** | A single game, best of 3, or best of 5. A draw is worth half. | +| **Board** | 8×8 Standard, 6×6 Quick, or 10×10 Grand. | +| **Rules** | Othello, or Anti-Othello. | +| **Opening** | Standard start, or my **opening card**: a named opening like the *Tiger*, the *Buffalo* or the *Rabbit* is already played out, and you carry on from there. In a match each card is played twice, colours swapped. 8×8 Othello only. | + +## A Little Strategy + +- **Corners are everything.** A disc in a corner can never be flipped. Neither can a solid run along an edge that starts from a corner. +- **Stay off the X-squares**, the ones diagonally next to an empty corner. Put a disc there and you usually hand the corner over. +- **The C-squares**, on the edge right next to an empty corner, are risky for the same reason. +- **Fewer discs early is often better.** What matters in the middle of the game is how many moves you have, and how few you leave them. Big flips open doors for the other player. +- **Quiet moves** that flip one or two discs on the inside are usually the strong ones. +- **Parity**: near the end, try to make the last move in each empty region of the board. + +## The End of the Game + +When it's over, I count the discs out the tournament way: black from the top, white from the bottom, so you can see the difference at a glance. After a match you'll see how the lead swung back and forth, a board to replay every move, and my notes: the moves I'd have played differently, and why. Click a note to see it on the board. + +Your game is saved as you go. Leave in the middle and it'll be waiting when you come back, with your coffee, cold. diff --git a/tools/verifyOthello.js b/tools/verifyOthello.js new file mode 100644 index 0000000..3c35396 --- /dev/null +++ b/tools/verifyOthello.js @@ -0,0 +1,362 @@ +#!/usr/bin/env node +// verifyOthello.js: headless checks for Othello ("Kissa Kuro-Shiro"): +// • perft from the start position (published counts), on both the rules +// module and the engine's make/unmake, for 6×6, 8×8 and 10×10 +// • the engine agrees with OthelloLogic on legal moves and resulting boards +// across thousands of random positions; Zobrist hash restored +// • rules: passes recorded, game end, wipeout, Anti-Othello winner, stable +// discs, the disc supply, notation round-trip, replay (boardAfter) +// • the book: every line legal; names found in all four orientations; +// replies mapped back correctly; opening card lines play out +// • the endgame solver matches brute-force minimax on small positions +// • skills: each moves legally inside its time budget; the ladder holds +// (stronger beats weaker over mirrored pairs of games) +// • describeIdea / describeMistake / review produce sensible output +// • layout: HUD rectangles on screen and clear of the board and each other +// Usage: node tools/verifyOthello.js [--quick] + +import * as L from '../src/games/othello/OthelloLogic.js'; +import * as AI from '../src/games/othello/OthelloAI.js'; +import { LINES, openingName, bookReplies, openingCard } from '../src/games/othello/OthelloBook.js'; +import { handle } from '../src/games/othello/OthelloEngine.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.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}`); +const posOf = (gs) => ({ size: gs.size, variant: gs.variant, board: gs.board, turn: gs.turn }); + +// ── perft ──────────────────────────────────────────────────────────────────── +section('perft'); +function perftLogic(board, size, turn, d, passed = false) { + if (d === 0) return 1; + const moves = L.movesFor(board, size, turn); + if (!moves.length) { + if (passed) return 1; + return perftLogic(board, size, L.other(turn), d - 1, true); + } + let t = 0; + for (const m of moves) { + const b = board.slice(); + b[m.sq] = turn; + for (const f of m.flips) b[f] = turn; + t += perftLogic(b, size, L.other(turn), d - 1, false); + } + return t; +} +{ + const EXP8 = [4, 12, 56, 244, 1396, 8200, 55092, 390216, 3005288]; + const g = L.createGame({ size: 8 }); + const dl = QUICK ? 6 : 8, de = QUICK ? 7 : 9; + for (let d = 1; d <= dl; d++) ok(`logic perft 8×8 d${d}`, perftLogic(g.board, 8, L.BLACK, d) === EXP8[d - 1]); + for (let d = 1; d <= de; d++) { + const n = AI.perft(posOf(g), d); + ok(`engine perft 8×8 d${d}`, n === EXP8[d - 1], `${n} ≠ ${EXP8[d - 1]}`); + } + for (const size of [6, 10]) { + const gg = L.createGame({ size }); + for (let d = 1; d <= 6; d++) { + const a = perftLogic(gg.board, size, L.BLACK, d), b = AI.perft(posOf(gg), d); + ok(`perft ${size}×${size} d${d}: logic = engine`, a === b, `${a} vs ${b}`); + } + } +} + +// ── engine vs rules on random positions ────────────────────────────────────── +section('engine agrees with the rules'); +{ + const rnd = mulberry32(7); + let positions = 0, mismatches = 0, hashBad = 0; + const games = QUICK ? 40 : 160; + for (const size of [6, 8, 10]) { + for (let gi = 0; gi < games / 2; gi++) { + let gs = L.createGame({ size, variant: gi % 2 ? 'anti' : 'standard' }); + while (gs.phase === 'playing') { + const legal = L.legalMoves(gs); + const view = AI.engineView(posOf(gs)); + positions++; + if (!view.hashRestored) hashBad++; + const a = legal.map((m) => m.sq).sort((x, y) => x - y), b = view.moves.map((m) => m.sq); + if (a.join() !== b.join()) mismatches++; + else { + for (const m of view.moves) { + const ref = L.applyMove(gs, m.sq).board; + if (ref.join() !== m.board.join()) { mismatches++; break; } + } + } + gs = L.applyMove(gs, legal[Math.floor(rnd() * legal.length)].sq); + } + } + } + ok(`legal moves and boards match on ${positions} positions`, mismatches === 0, `${mismatches} mismatches`); + ok('hash restored after every make/unmake', hashBad === 0, `${hashBad}`); +} + +// ── rules ──────────────────────────────────────────────────────────────────── +section('rules'); +{ + const g = L.createGame({ size: 8 }); + ok('start: black to move, 4 legal', g.turn === 'black' && L.legalMoves(g).length === 4); + ok('f5 is legal first move', L.legalMoves(g).some((m) => L.notate(m.sq, 8) === 'f5')); + for (let sq = 0; sq < 64; sq++) ok(`notation round-trip ${sq}`, L.parseSq(L.notate(sq, 8), 8) === sq); + ok('notation a1 top-left, h8 bottom-right', L.notate(0, 8) === 'a1' && L.notate(63, 8) === 'h8'); + ok('10×10 notation j10', L.notate(99, 10) === 'j10' && L.parseSq('j10', 10) === 99); + let w = L.createGame({ size: 8 }); + for (const n of ['f5', 'f6', 'e6', 'f4', 'e3', 'c5', 'g5', 'g3', 'g4', 'f3', 'd6', 'e7', 'd3', 'e2', 'f2', 'c4']) { + if (w.phase !== 'playing') break; + const sq = L.parseSq(n, 8); + if (!L.legalMoves(w).some((m) => m.sq === sq)) break; + w = L.applyMove(w, sq); + } + ok('random line plays without errors', w.history.length > 0); + // a hand-built pass position: white has no move, black does + { + const b = Array(64).fill(null); + b[0] = 'black'; b[1] = 'white'; b[9] = 'white'; + // black at a1, white b1 & b2; black to move can play c1 (flips b1) or c3 (flips b2) + const gs = { ...L.createGame({ size: 8 }), board: b, start: b.slice() }; + const after = L.applyMove(gs, L.parseSq('c1', 8)); + // now white has b2 only; white cannot move (needs black beyond) → pass recorded or game over + ok('pass or end handled after a move', after.history.length >= 1); + const last = after.history[after.history.length - 1]; + ok('white has no reply: a pass is recorded and black moves again', last.pass && last.color === 'white' && after.turn === 'black'); + } + // a full board ends the game; anti flips the winner + { + const b = Array(64).fill('black'); b[63] = null; b[62] = 'white'; + const gs = { ...L.createGame({ size: 8 }), board: b, start: b.slice() }; + const legal = L.legalMoves(gs); + ok('one move left for black', legal.length === 1 && legal[0].sq === 63); + const end = L.applyMove(gs, 63); + ok('board full → game over, black wins', end.phase === 'game_over' && end.winner === 'black' && end.endReason === 'wipeout'); + const anti = L.applyMove({ ...gs, variant: 'anti' }, 63); + ok('Anti-Othello: same board, white wins', anti.winner === 'white'); + } + // stable discs + { + const b = Array(64).fill(null); + b[0] = 'black'; b[1] = 'black'; b[8] = 'black'; b[27] = 'white'; + const st = L.stableDiscs(b, 8); + ok('corner + edge-run discs are stable', st.includes(0) && st.includes(1) && st.includes(8)); + ok('a centre disc is not stable', !st.includes(27)); + const full = Array(64).fill('white'); + ok('full board: everything stable', L.stableDiscs(full, 8).length === 64); + } + // supply + { + const g2 = L.applyMove(L.createGame({ size: 8 }), L.parseSq('f5', 8)); + const s = L.supply(g2); + ok('supply 30 each, black 29 after one move', s.each === 30 && s.black === 29 && s.white === 30); + } + // replay + { + const rnd = mulberry32(3); + let gs = L.createGame({ size: 8 }); + while (gs.phase === 'playing') { const m = L.legalMoves(gs); gs = L.applyMove(gs, m[Math.floor(rnd() * m.length)].sq); } + ok('boardAfter(all) = final board', L.boardAfter(gs, gs.history.length).join() === gs.board.join()); + const tr = L.discTrace(gs); + const c = L.counts(gs); + ok('disc trace ends at the final difference', tr[tr.length - 1] === c.black - c.white && tr.length === gs.history.length + 1); + ok('resign', L.resign(gs, 'black').winner === 'white'); + } +} + +// ── book ───────────────────────────────────────────────────────────────────── +section('book'); +{ + for (const l of LINES) { + let gs = L.createGame({ size: 8 }); + let legal = true; + for (const n of l.list) { + const sq = L.parseSq(n, 8); + if (gs.phase !== 'playing' || !L.legalMoves(gs).some((m) => m.sq === sq)) { legal = false; break; } + gs = L.applyMove(gs, sq); + } + ok(`book line legal: ${l.name}`, legal); + ok(`openingName finds ${l.name}`, openingName(l.list) === l.name, openingName(l.list)); + } + const rnd = mulberry32(11); + for (let i = 0; i < 40; i++) { + const card = openingCard(rnd); + let gs = L.createGame({ size: 8 }); + let legal = true; + for (const n of card.moves) { + const sq = L.parseSq(n, 8); + if (!L.legalMoves(gs).some((m) => m.sq === sq)) { legal = false; break; } + gs = L.applyMove(gs, sq, { book: true }); + } + ok(`opening card ${card.name} (${card.moves[0]}) plays out`, legal); + ok(`mirrored card still named ${card.name}`, openingName(card.moves) === card.name, openingName(card.moves)); + } + ok('replies from the start are the four first moves', bookReplies([]).length === 4); + ok('after f5 the book knows d6, f6, f4', ['d6', 'f6', 'f4'].every((m) => bookReplies(['f5']).includes(m))); + ok('after c4 the replies are mirrored (c3 = d6 mirrored)', bookReplies(['c4']).includes('e3')); + ok('unknown line → no replies', bookReplies(['f5', 'd6', 'c3', 'd3', 'c4', 'f4', 'c5', 'b3', 'c2', 'a1']).length === 0); +} + +// ── endgame solver vs brute force ──────────────────────────────────────────── +section('endgame solver'); +function brute(board, size, turn, variant, passed = false) { + const moves = L.movesFor(board, size, turn); + if (!moves.length) { + if (passed) { + const c = L.countsOf(board); + let d = turn === 'black' ? c.black - c.white : c.white - c.black; + if (variant === 'anti') d = -d; + return d > 0 ? AI.WIN + d * 10 : d < 0 ? -AI.WIN + d * 10 : 0; + } + return -brute(board, size, L.other(turn), variant, true); + } + let best = -Infinity; + for (const m of moves) { + const b = board.slice(); b[m.sq] = turn; for (const f of m.flips) b[f] = turn; + best = Math.max(best, -brute(b, size, L.other(turn), variant, false)); + } + return best; +} +{ + const rnd = mulberry32(99); + const N = QUICK ? 12 : 40; + let tested = 0; + for (let i = 0; i < N * 3 && tested < N; i++) { + const size = i % 3 === 0 ? 6 : 8; + const variant = i % 4 === 3 ? 'anti' : 'standard'; + let gs = L.createGame({ size, variant }); + const stopAt = 7 + Math.floor(rnd() * 3); + while (gs.phase === 'playing' && L.counts(gs).empty > stopAt) { const m = L.legalMoves(gs); gs = L.applyMove(gs, m[Math.floor(rnd() * m.length)].sq); } + if (gs.phase !== 'playing') continue; + tested++; + const ref = brute(gs.board, size, gs.turn, variant); + const got = AI.solveExact(posOf(gs)); + ok(`solve ${size}×${size} ${variant} (${L.counts(gs).empty} empty)`, got && got.score === ref, `${got?.score} vs ${ref}`); + // the solver's move really achieves that score + if (got) { + const after = L.applyMove(gs, got.sq); + const v = after.phase === 'game_over' + ? (() => { const c = L.counts(after); let d = gs.turn === 'black' ? c.black - c.white : c.white - c.black; if (variant === 'anti') d = -d; return d > 0 ? AI.WIN + d * 10 : d < 0 ? -AI.WIN + d * 10 : 0; })() + : (after.turn === gs.turn ? brute(after.board, size, after.turn, variant) : -brute(after.board, size, after.turn, variant)); + ok(' …and its move achieves it', v === ref, `${v} vs ${ref}`); + } + } +} + +// ── skills: legality, timing, ladder ───────────────────────────────────────── +section('skills'); +function playGame(skillBlack, skillWhite, { size = 8, variant = 'standard', rnd, timing } = {}) { + let gs = L.createGame({ size, variant }); + const line = []; + while (gs.phase === 'playing') { + const skill = gs.turn === 'black' ? skillBlack : skillWhite; + const t0 = Date.now(); + const r = AI.chooseMove(posOf(gs), skill, { line: line.slice(), rnd }); + const dt = Date.now() - t0; + timing?.(skill, dt, L.counts(gs).empty); + if (!r || !L.legalMoves(gs).some((m) => m.sq === r.sq)) return { error: true, gs }; + line.push(L.notate(r.sq, size)); + gs = L.applyMove(gs, r.sq); + } + return { gs }; +} +{ + const rnd = mulberry32(5); + const worst = {}; + const timing = (skill, dt) => { worst[skill] = Math.max(worst[skill] ?? 0, dt); }; + for (const size of [6, 8, 10]) { + for (const skill of [1, 2, 3, 4, 5]) { + if (QUICK && size !== 8 && skill > 3) continue; + const r = playGame(skill, 3, { size, rnd, timing }); + ok(`skill ${skill} on ${size}×${size}: legal game to the end`, !r.error); + } + } + const BUDGET = { 1: 300, 2: 500, 3: 1100, 4: 2200, 5: 4500 }; + for (const [s, t] of Object.entries(worst)) ok(`skill ${s} worst think ${t} ms within ${BUDGET[s]} ms`, t <= BUDGET[s]); + console.log(' worst think times (ms):', worst); + + const ladder = QUICK ? [[1, 3, 4], [3, 5, 2]] : [[1, 3, 6], [2, 4, 6], [3, 5, 4], [1, 5, 4]]; + for (const [lo, hi, pairs] of ladder) { + let hiScore = 0, games = 0; + for (let p = 0; p < pairs; p++) { + for (const hiBlack of [true, false]) { + const r = playGame(hiBlack ? hi : lo, hiBlack ? lo : hi, { rnd }); + const w = r.gs.winner; + const hiColor = hiBlack ? 'black' : 'white'; + hiScore += w === 'draw' ? 0.5 : w === hiColor ? 1 : 0; + games++; + } + } + console.log(` skill ${hi} vs ${lo}: ${hiScore}/${games}`); + ok(`skill ${hi} beats skill ${lo} most of the time`, hiScore / games >= 0.7, `${hiScore}/${games}`); + } +} + +// ── coach words, review, worker handler ────────────────────────────────────── +section('coach & review'); +{ + // corner available → describeIdea says so + const b = Array(64).fill(null); + b[9] = 'white'; b[18] = 'black'; b[27] = 'black'; + const pos = { size: 8, variant: 'standard', board: b, turn: 'black' }; + ok('a1 legal here', L.flipsFor(b, 8, 0, 'black').length === 1); + ok('describeIdea: corner', /corner/.test(AI.describeIdea(pos, 0, {}))); + ok('describeIdea: exact win', /wins by 4 discs/.test(AI.describeIdea(pos, 0, { exact: true, score: AI.WIN + 40 }))); + const g = L.applyMove(L.createGame({ size: 8 }), L.parseSq('f5', 8)); + const h = handle('hint', { pos: posOf(g), ms: 200 }); + ok('worker hint returns a legal move', h && L.legalMoves(g).some((m) => m.sq === h.sq)); + const r = handle('rank', { pos: posOf(g), depth: 3, ms: 200 }); + ok('worker rank lists every move', r.length === L.legalMoves(g).length); + const mv = handle('move', { pos: posOf(g), skill: 5, line: ['f5'] }); + ok('skill 5 plays from the book after f5', mv.book && ['d6', 'f6', 'f4'].includes(L.notate(mv.sq, 8))); + // review: replay a game and review black's decisions + const rnd = mulberry32(21); + let gs = L.createGame({ size: 8 }); + const positions = []; + while (gs.phase === 'playing') { + const m = L.legalMoves(gs); + const pick = m[Math.floor(rnd() * m.length)].sq; + if (gs.turn === 'black') positions.push({ i: gs.history.length, board: gs.board.slice(), turn: 'black', played: pick }); + gs = L.applyMove(gs, pick); + } + const t0 = Date.now(); + const rev = handle('review', { size: 8, variant: 'standard', positions, ms: 60 }); + ok(`review of ${positions.length} moves in ${Date.now() - t0} ms`, Array.isArray(rev) && rev.length > 0 && Date.now() - t0 < 15000); + ok('review losses are ≥ 0', rev.every((x) => x.loss >= 0)); + const worst = rev.slice().sort((a, b2) => b2.loss - a.loss)[0]; + const at = positions.find((p) => p.i === worst.i); + const why = AI.describeMistake({ size: 8, variant: 'standard', board: at.board, turn: 'black' }, worst.played, worst.best); + ok('describeMistake gives words', typeof why === 'string' && why.length > 5, why); + console.log(` worst random move: ${L.notate(worst.played, 8)} (best ${L.notate(worst.best, 8)}): ${why}`); +} + +// ── layout ─────────────────────────────────────────────────────────────────── +section('layout'); +try { + const LY = await import('../src/games/othello/OthelloLayout.js'); + const R = LY.HUD_RECTS(); + const board = LY.BOARD_RECT; + const inter = (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; + for (const [k, r] of Object.entries(R)) { + ok(`${k} on screen`, r.x >= 0 && r.y >= 0 && r.x + r.w <= LY.W && r.y + r.h <= LY.H, JSON.stringify(r)); + ok(`${k} clear of the board`, !inter(r, board)); + } + const keys = Object.keys(R); + for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) { + ok(`${keys[i]} clear of ${keys[j]}`, !inter(R[keys[i]], R[keys[j]])); + } + for (const size of [6, 8, 10]) { + const g = LY.geom(size); + for (let sq = 0; sq < size * size; sq++) { + const { x, y } = LY.squareXY(sq, size); + if (LY.cellAt(x, y, size) !== sq) { ok(`cellAt(squareXY) ${size}×${size} sq ${sq}`, false); break; } + } + ok(`${size}×${size} board fills the felt`, Math.abs(g.SQ * size - LY.BOARD) < 1e-6); + } +} catch (e) { + ok('layout module loads', false, e.message); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);