From d7a873054cf151d02565d1800e86fb8722243adb Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Wed, 2 Dec 2026 08:18:04 -0700 Subject: [PATCH] Rebuild Go as Unkai-ji: full rules, MCTS AI, puzzles, SGF, review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace the basic 9×9 greedy-lookahead game with a complete Go experience: 9/13/19 boards, Japanese & Chinese scoring, handicap 2–9, byo-yomi clock, positional superko, nigiri, best-of matches, undo, hints, territory study - Swap the AI for a Michi-style MCTS (RAVE + heuristic priors + shape patterns) running in a dedicated module worker so the scene stays fluid - Add Hōun's life-and-death problem ladder (Elo-rated, generated & verified) plus a daily problem with streak tracking - Add SGF read/write, a post-game review with score graph and replay board, and a written tutorial - All art, sound, stones, and HUD are new procedural systems (temple at dawn, Web Audio koto/bell/pachi, animated stone placement and capture) - Register the game's tutorial flag, soundtrack override, and add tools/genGoPuzzles.js and tools/verifyGo.js for maintenance --- src/data/assetManifest.js | 2 + src/data/gamesRegistry.js | 2 +- src/games/go/GoAI.js | 1132 ++++++++++++++--- src/games/go/GoArt.js | 760 ++++++++++++ src/games/go/GoDialogs.js | 183 +++ src/games/go/GoEndScreen.js | 325 +++++ src/games/go/GoEngine.js | 95 ++ src/games/go/GoGame.js | 2246 +++++++++++++++++++++++++--------- src/games/go/GoHud.js | 301 +++++ src/games/go/GoLayout.js | 120 ++ src/games/go/GoLogic.js | 613 +++++++--- src/games/go/GoPuzzleData.js | 210 ++++ src/games/go/GoPuzzles.js | 149 +++ src/games/go/GoSgf.js | 224 ++++ src/games/go/GoSound.js | 258 ++++ src/games/go/GoStones.js | 237 ++++ src/games/go/GoTalk.js | 148 +++ src/games/go/GoTsumego.js | 334 +++++ src/games/go/GoWorker.js | 11 + src/games/go/tutorial.md | 95 ++ src/services/soundtrack.js | 1 + tools/genGoPuzzles.js | 248 ++++ tools/verifyGo.js | 499 ++++++++ 23 files changed, 7277 insertions(+), 916 deletions(-) create mode 100644 src/games/go/GoArt.js create mode 100644 src/games/go/GoDialogs.js create mode 100644 src/games/go/GoEndScreen.js create mode 100644 src/games/go/GoEngine.js create mode 100644 src/games/go/GoHud.js create mode 100644 src/games/go/GoLayout.js create mode 100644 src/games/go/GoPuzzleData.js create mode 100644 src/games/go/GoPuzzles.js create mode 100644 src/games/go/GoSgf.js create mode 100644 src/games/go/GoSound.js create mode 100644 src/games/go/GoStones.js create mode 100644 src/games/go/GoTalk.js create mode 100644 src/games/go/GoTsumego.js create mode 100644 src/games/go/GoWorker.js create mode 100644 src/games/go/tutorial.md create mode 100644 tools/genGoPuzzles.js create mode 100644 tools/verifyGo.js diff --git a/src/data/assetManifest.js b/src/data/assetManifest.js index 3215878..306a174 100644 --- a/src/data/assetManifest.js +++ b/src/data/assetManifest.js @@ -315,6 +315,8 @@ export const MANIFEST = { // Chinese Checkers art is all procedural (ChineseCheckersArt.js); only the // chinese soundtrack (see services/soundtrack.js) needs lazy-loading. chinesecheckers: [(scene) => musicFrom(scene, 'chinese-music')], + // Go (Unkai-ji) is all procedural art too; it borrows the same soundtrack. + go: [(scene) => musicFrom(scene, 'chinese-music')], mahjong: [ ...MAHJONG_TILES, // chinese soundtrack (see services/soundtrack.js) — lazy-loaded here so diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index 9735ba8..e9104d7 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -57,7 +57,7 @@ registerGame({ slug: 'wordsearch', name: 'Word Search', category: 'word', minPla 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, 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: 'go', name: 'Go', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 30, defaultPlayfield: 'dark', hasTutorial: true }); 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 }); registerGame({ slug: 'connect4', name: 'Connect 4', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 33 }); diff --git a/src/games/go/GoAI.js b/src/games/go/GoAI.js index a21518e..b7bd9ff 100644 --- a/src/games/go/GoAI.js +++ b/src/games/go/GoAI.js @@ -1,160 +1,1000 @@ -// Go AI — greedy heuristic with limited look-ahead (no full MCTS for simplicity). -// Suitable for casual 9×9 play. -import { - SIZE, getGroup, getLiberties, findCaptures, isValidMove, getValidMoves, - applyMove, applyPass, getFinalScore, boardHash, -} from './GoLogic.js'; +// GoAI.js: the opponents at Unkai-ji. Monte-Carlo tree search over a fast +// board, after the design of Petr Baudiš's Michi: RAVE (all-moves-as-first) +// statistics blended with heuristic priors (captures, atari escapes, 3×3 +// shape patterns, distance from the last move, first/second-line moves in +// empty areas), and playouts that capture, escape atari and answer shape +// near the last move before falling back to random moves that never fill +// a true eye and usually refuse self-atari. +// +// Exports (all pure, worker-safe): +// clampSkill(s), SKILL +// chooseMove(pos, skill, opts) → { sq (-1 = pass), resign, winrate, +// lead, ownership[], playouts, pv } +// analyse(pos, { playouts, ms }) → { best, winrate, lead, ownership, +// top: [{ sq, visits, winrate, lead }] } +// estimateDead(pos, opts) → { dead[], ownership[] } +// reviewPositions(list, opts) → [{ lead, winrate, best }] (black's view) +// describeIdea(gs, sq) a few words on what a move does +// classify(gs, sq) the tactical facts behind describeIdea +// +// pos = { size, board (GoLogic, 'black' | 'white' | null), turn, komi, +// ko (sq or -1), last (sq, -1 pass, null none), passes, +// forbidden: [sq] (superko-illegal at the root) } -function other(color) { return color === 'black' ? 'white' : 'black'; } +import * as L from './GoLogic.js'; -const SKILL_PROFILES = { - 1: { lookahead: 0, blunder: 0.70, topN: 1, delay: [900, 1500] }, - 2: { lookahead: 0, blunder: 0.45, topN: 3, delay: [800, 1300] }, - 3: { lookahead: 1, blunder: 0.20, topN: 5, delay: [650, 1100] }, - 4: { lookahead: 1, blunder: 0.05, topN: 8, delay: [500, 950] }, - 5: { lookahead: 2, blunder: 0.00, topN: 12, delay: [400, 800] }, +export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3))); + +/** Per skill: playouts, a time cap (ms, 9×9; bigger boards get more), the + * move-choice temperature, the chance of a plausible-but-loose move, and + * how far behind (points) a hopeless game has to be before it resigns. */ +export const SKILL = { + 1: { playouts: 220, ms: 450, temp: 1.4, loose: 0.18, resignAt: 35 }, + 2: { playouts: 900, ms: 800, temp: 0.9, loose: 0.07, resignAt: 25 }, + 3: { playouts: 2600, ms: 1300, temp: 0.45, loose: 0.02, resignAt: 15 }, + 4: { playouts: 7500, ms: 2200, temp: 0.15, loose: 0, resignAt: 12 }, + 5: { playouts: 26000, ms: 3600, temp: 0, loose: 0, resignAt: 10 }, }; +const SIZE_TIME = { 9: 1, 13: 1.25, 19: 1.5 }; -// 9×9 hoshi (star) positions for early-game bonus -const HOSHI = [[2,2],[2,6],[6,2],[6,6],[4,4]]; -const HOSHI_SET = new Set(HOSHI.map(([r,c]) => `${r},${c}`)); +// ── tuning (from Michi) ────────────────────────────────────────────────────── +const RAVE_EQUIV = 3500; +const PRIOR_EVEN = 10; +const PRIOR_SELFATARI = 10; +const PRIOR_CAPTURE_ONE = 15; +const PRIOR_CAPTURE_MANY = 30; +const PRIOR_PAT3 = 10; +const PRIOR_CFG = [24, 22, 8]; +const PRIOR_EMPTYAREA = 10; +const PROB_CAPTURE = 0.9; +const PROB_PAT3 = 0.95; +const PROB_SSAREJECT = 0.9; +const PROB_RSAREJECT = 0.5; +const MARGIN_W = 0.15; +const PRIOR_TACTIC = 50; +const PRIOR_OPENING = 24; -function profileFor(skill) { - return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; +const EMPTY = 0, BL = 1, WH = 2, EDGE = 3; +const PASS = 0; +const toC = (c) => (c === L.BLACK ? BL : c === L.WHITE ? WH : EMPTY); + +function xorshift(seed) { + let x = (seed >>> 0) || 0x9e3779b9; + return () => { + x ^= x << 13; x >>>= 0; + x ^= x >>> 17; + x ^= x << 5; x >>>= 0; + return x / 4294967296; + }; } -export function nextThinkDelay(skill) { - const [lo, hi] = profileFor(skill).delay; - return lo + Math.random() * (hi - lo); -} - -// Score a single candidate move for `color`. -function scoreMove(state, r, c, color) { - const opp = other(color); - const board = state.board; - let score = 0; - - // 1. Captures: very valuable - const caps = findCaptures(board, r, c, color); - const capCount = caps.reduce((n, g) => n + g.size, 0); - score += capCount * 120; - - // 2. Simulate board after placement to evaluate own/opponent liberties - const testBoard = board.map(row => [...row]); - testBoard[r][c] = color; - for (const g of caps) for (const k of g) { const [gr, gc] = k.split(',').map(Number); testBoard[gr][gc] = null; } - - // 3. Atari attack: put opponent group in atari (1 liberty) - const oppChecked = new Set(); - for (const dr of [-1,0,1]) for (const dc of [-1,0,1]) { - if (Math.abs(dr) + Math.abs(dc) !== 1) continue; - const nr = r + dr, nc = c + dc; - if (nr < 0 || nr >= SIZE || nc < 0 || nc >= SIZE) continue; - if (testBoard[nr][nc] !== opp) continue; - const key = `${nr},${nc}`; - if (oppChecked.has(key)) continue; - const g = getGroup(testBoard, nr, nc); - for (const k of g) oppChecked.add(k); - const libs = getLiberties(testBoard, g); - if (libs === 1) score += 60; // atari - else if (libs === 2) score += 15; // semi-threatening - } - - // 4. Own group defense: save own groups in atari - const ownGroup = getGroup(testBoard, r, c); - // Check own neighbors for groups that were in atari before this move - const ownChecked = new Set(); - for (const dr of [-1,0,1]) for (const dc of [-1,0,1]) { - if (Math.abs(dr) + Math.abs(dc) !== 1) continue; - const nr = r + dr, nc = c + dc; - if (nr < 0 || nr >= SIZE || nc < 0 || nc >= SIZE) continue; - if (board[nr][nc] !== color) continue; - const key = `${nr},${nc}`; - if (ownChecked.has(key)) continue; - const oldGroup = getGroup(board, nr, nc); - for (const k of oldGroup) ownChecked.add(k); - const oldLibs = getLiberties(board, oldGroup); - const newGroup = getGroup(testBoard, nr, nc); - const newLibs = getLiberties(testBoard, newGroup); - if (oldLibs === 1 && newLibs > 1) score += 80; // saved from capture - else if (oldLibs <= 2 && newLibs > oldLibs) score += 20; // improved breathing room - } - - // 5. Territory heuristic: connected empty space adjacent to own stone - const oppNeighbor = new Set(); - const ownNeighbor = new Set(); - for (const dr of [-1,0,1]) for (const dc of [-1,0,1]) { - if (Math.abs(dr)+Math.abs(dc) !== 1) continue; - const nr = r+dr, nc = c+dc; - if (nr<0||nr>=SIZE||nc<0||nc>=SIZE) continue; - if (testBoard[nr][nc] === opp) oppNeighbor.add(`${nr},${nc}`); - if (testBoard[nr][nc] === color) ownNeighbor.add(`${nr},${nc}`); - } - score += ownNeighbor.size * 8; - - // 6. Star point bonus early game - const totalStones = board.flat().filter(Boolean).length; - if (totalStones < 20 && HOSHI_SET.has(`${r},${c}`)) score += 30; - - // 7. Slight center preference early game - if (totalStones < 30) { - const dist = Math.abs(r - 4) + Math.abs(c - 4); - score += Math.max(0, 6 - dist); - } - - // 8. Avoid self-atari (placing in a position with 1 liberty after placement) - if (getLiberties(testBoard, ownGroup) <= 1) score -= 80; - - return score; -} - -export function chooseMove(state, aiColor, skill) { - const prof = profileFor(skill); - const moves = getValidMoves(state, aiColor); - if (moves.length === 0) return null; - - if (Math.random() < prof.blunder) return moves[Math.floor(Math.random() * moves.length)]; - - // Score all moves, pick topN candidates - const scored = moves.map(m => ({ m, score: scoreMove(state, m.r, m.c, aiColor) })); - scored.sort((a, b) => b.score - a.score); - const topN = Math.min(prof.topN, scored.length); - const candidates = scored.slice(0, topN).map(x => x.m); - - if (prof.lookahead === 0 || candidates.length === 0) { - return candidates[0] ?? null; - } - - // Limited look-ahead: for each candidate, score what the opponent plays next - let bestMove = candidates[0], bestFinal = -Infinity; - for (const m of candidates) { - const ns = applyMove(state, m.r, m.c); - const oppMoves = getValidMoves(ns, other(aiColor)); - let oppBest = -Infinity; - for (const om of oppMoves.slice(0, 6)) { - const ns2 = applyMove(ns, om.r, om.c); - // Evaluate final score delta as proxy - const finalScore = getFinalScore(ns2); - const delta = aiColor === 'black' - ? (ns2.captures.black - ns2.captures.white) - : (ns2.captures.white - ns2.captures.black); - if (delta > oppBest) oppBest = delta; +// ── 3×3 patterns (Michi's set) ─────────────────────────────────────────────── +// X, O: the two colours (both colourings are used); '.' empty; ' ' off the +// board; x: not X; o: not O; '?': anything. The centre is the move. +const PAT3_SRC = [ + ['XOX', '...', '???'], // hane, enclosing + ['XO.', '...', '?.?'], // hane, non-cutting + ['XO?', 'X..', 'x.?'], // hane, magari + ['.O.', 'X..', '...'], // katatsuke / diagonal attachment + ['XO?', 'O.o', '?o?'], // cut 1, unprotected + ['XO?', 'O.X', '???'], // cut 1, peeped + ['?X?', 'O.O', 'ooo'], // cut 2 + ['OX?', 'o.O', '???'], // cut keima + ['X.?', 'O.?', ' '], // side: chase + ['OX?', 'X.O', ' '], // side: block side cut + ['?X?', 'x.O', ' '], // side: block side connection + ['?XO', 'x.x', ' '], // side: sagari + ['?OX', 'X.O', ' '], // side: cut +]; +const PAT3 = (() => { + const table = new Uint8Array(65536); + const rot = (p) => [0, 1, 2].map((i) => [2, 1, 0].map((j) => p[j][i]).join('')); + const vflip = (p) => [p[2], p[1], p[0]]; + const hflip = (p) => p.map((l) => l.split('').reverse().join('')); + const swap = (p) => p.map((l) => l.replace(/X/g, 'Z').replace(/x/g, 'z').replace(/O/g, 'X').replace(/o/g, 'x').replace(/Z/g, 'O').replace(/z/g, 'o')); + const expand = (p) => { + const out = []; + const all = [p, rot(p), rot(rot(p)), rot(rot(rot(p)))]; + for (const q of all) out.push(q, vflip(q), hflip(q), vflip(hflip(q))); + return out.concat(out.map(swap)); + }; + const SET = { '.': [0], X: [1], O: [2], ' ': [3], x: [0, 2, 3], o: [0, 1, 3], '?': [0, 1, 2, 3] }; + // neighbour order: NW N NE W E SW S SE + const cells = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1], [2, 2]]; + for (const src of PAT3_SRC) { + for (const p of expand(src)) { + const opts = cells.map(([r, c]) => SET[p[r][c]]); + const rec = (i, code) => { + if (i === 8) { table[code] = 1; return; } + for (const v of opts[i]) rec(i + 1, code | (v << (i * 2))); + }; + rec(0, 0); } + } + return table; +})(); - if (prof.lookahead >= 2) { - // One more ply - const ns2 = applyMove(ns, oppMoves[0]?.r ?? m.r, oppMoves[0]?.c ?? m.c); - const myMoves2 = getValidMoves(ns2, aiColor); - let myBest2 = -Infinity; - for (const mm of myMoves2.slice(0, 4)) { - const s = scoreMove(ns2, mm.r, mm.c, aiColor); - if (s > myBest2) myBest2 = s; +// ── the fast board ─────────────────────────────────────────────────────────── +// A padded 1-D board (stride W = size + 2, an edge ring all round). Chains +// are circular linked lists with a head; each head keeps the pseudo- +// liberty count and the sum and sum of squares of its liberty indices: a +// chain is in atari exactly when plibs · lsq = lsum² (all its pseudo- +// liberties are the same point), which is lsum / plibs. +const GEO = new Map(); +function geo(size) { + let g = GEO.get(size); + if (g) return g; + const W = size + 2, LEN = W * W; + const D4 = [-1, 1, -W, W]; + const DIAG = [-W - 1, -W + 1, W - 1, W + 1]; + const N8 = [-W - 1, -W, -W + 1, -1, 1, W - 1, W, W + 1]; + const pts = []; + const height = new Int8Array(LEN); + const toSq = new Int16Array(LEN).fill(-1); + const toIdx = new Int16Array(size * size); + for (let r = 0; r < size; r++) for (let c = 0; c < size; c++) { + const p = (r + 1) * W + (c + 1); + pts.push(p); + toSq[p] = r * size + c; + toIdx[r * size + c] = p; + height[p] = Math.min(r, c, size - 1 - r, size - 1 - c); + } + // points within Manhattan distance 3 (for the empty-area prior) + const area3 = new Map(); + for (const p of pts) { + const r = Math.floor(p / W), c = p % W, list = []; + for (let dr = -3; dr <= 3; dr++) for (let dc = -3; dc <= 3; dc++) { + if (Math.abs(dr) + Math.abs(dc) > 3 || (!dr && !dc)) continue; + const rr = r + dr, cc = c + dc; + if (rr < 1 || rr > size || cc < 1 || cc > size) continue; + list.push(rr * W + cc); + } + area3.set(p, list); + } + g = { size, W, LEN, D4, DIAG, N8, pts, height, toSq, toIdx, area3 }; + GEO.set(size, g); + return g; +} + +class Board { + constructor(size) { + const g = geo(size); + this.g = g; + this.size = size; + const n = g.LEN; + this.color = new Uint8Array(n); + this.head = new Int16Array(n); + this.next = new Int16Array(n); + this.csize = new Int16Array(n); + this.plibs = new Int16Array(n); + this.lsum = new Int32Array(n); + this.lsq = new Int32Array(n); + this.empty = new Int16Array(n); + this.epos = new Int16Array(n); + this.mark = new Int32Array(n); + this.stamp = 1; + this.ne = 0; + this.color.fill(EDGE); + for (const p of g.pts) { this.color[p] = EMPTY; this.epos[p] = this.ne; this.empty[this.ne++] = p; } + this.ko = 0; + this.turn = BL; + this.last = -1; // -1 none, 0 pass, else a point + this.last2 = -1; + this.passes = 0; + this.komi = 6.5; + this.moves = 0; + } + + copyFrom(o) { + this.color.set(o.color); this.head.set(o.head); this.next.set(o.next); this.csize.set(o.csize); + this.plibs.set(o.plibs); this.lsum.set(o.lsum); this.lsq.set(o.lsq); + this.empty.set(o.empty); this.epos.set(o.epos); + this.ne = o.ne; this.ko = o.ko; this.turn = o.turn; this.last = o.last; this.last2 = o.last2; + this.passes = o.passes; this.komi = o.komi; this.moves = o.moves; + } + + removeEmpty(p) { + const i = this.epos[p], lastP = this.empty[--this.ne]; + this.empty[i] = lastP; this.epos[lastP] = i; + } + addEmpty(p) { this.epos[p] = this.ne; this.empty[this.ne++] = p; } + + inAtari(h) { const n = this.plibs[h]; return n > 0 && n * this.lsq[h] === this.lsum[h] * this.lsum[h]; } + atariLib(h) { return this.lsum[h] / this.plibs[h]; } + + /** Place colour col at p (assumed legal). Returns the number captured. */ + put(p, col) { + const { D4 } = this.g; + const color = this.color, head = this.head, plibs = this.plibs, lsum = this.lsum, lsq = this.lsq; + const opp = 3 - col; + this.removeEmpty(p); + color[p] = col; head[p] = p; this.next[p] = p; this.csize[p] = 1; + plibs[p] = 0; lsum[p] = 0; lsq[p] = 0; + for (let k = 0; k < 4; k++) { + const n = p + D4[k], c = color[n]; + if (c === EMPTY) { plibs[p]++; lsum[p] += n; lsq[p] += n * n; } else if (c !== EDGE) { + const h = head[n]; plibs[h]--; lsum[h] -= p; lsq[h] -= p * p; } - if (myBest2 > bestFinal) { bestFinal = myBest2; bestMove = m; } - } else { - if (-oppBest > bestFinal) { bestFinal = -oppBest; bestMove = m; } } + for (let k = 0; k < 4; k++) { + const n = p + D4[k]; + if (color[n] === col && head[n] !== head[p]) this.merge(head[p], head[n]); + } + let captured = 0, capAt = 0; + for (let k = 0; k < 4; k++) { + const n = p + D4[k]; + if (color[n] === opp && plibs[head[n]] === 0) { captured += this.csize[head[n]]; capAt = n; this.removeChain(head[n]); } + } + const h = head[p]; + this.ko = captured === 1 && this.csize[h] === 1 && plibs[h] === 1 ? capAt : 0; + return captured; } - return bestMove; + merge(a, b) { + if (this.csize[a] < this.csize[b]) { const t = a; a = b; b = t; } + const head = this.head, next = this.next; + let s = b; + do { head[s] = a; s = next[s]; } while (s !== b); + const t = next[a]; next[a] = next[b]; next[b] = t; + this.csize[a] += this.csize[b]; this.plibs[a] += this.plibs[b]; this.lsum[a] += this.lsum[b]; this.lsq[a] += this.lsq[b]; + } + + removeChain(h) { + const { D4 } = this.g; + const color = this.color, next = this.next, head = this.head; + let s = h; + do { color[s] = EMPTY; this.addEmpty(s); s = next[s]; } while (s !== h); + s = h; + do { + for (let k = 0; k < 4; k++) { + const n = s + D4[k], c = color[n]; + if (c === BL || c === WH) { const hh = head[n]; this.plibs[hh]++; this.lsum[hh] += s; this.lsq[hh] += s * s; } + } + s = next[s]; + } while (s !== h); + } + + play(p) { + this.put(p, this.turn); + this.turn = 3 - this.turn; + this.last2 = this.last; this.last = p; + this.passes = 0; + this.moves++; + } + + pass() { + this.ko = 0; + this.turn = 3 - this.turn; + this.last2 = this.last; this.last = PASS; + this.passes++; + this.moves++; + } + + legal(p, col) { + const color = this.color; + if (color[p] !== EMPTY || p === this.ko) return false; + const { D4 } = this.g; + for (let k = 0; k < 4; k++) if (color[p + D4[k]] === EMPTY) return true; + const opp = 3 - col; + for (let k = 0; k < 4; k++) { + const n = p + D4[k], c = color[n]; + if (c === col) { if (!this.inAtari(this.head[n])) return true; } else if (c === opp) { if (this.inAtari(this.head[n])) return true; } + } + return false; + } + + /** All four neighbours col (or edge): the colour whose eye this might be, or 0. */ + eyeish(p) { + const { D4 } = this.g; + let ec = 0; + for (let k = 0; k < 4; k++) { + const c = this.color[p + D4[k]]; + if (c === EDGE) continue; + if (c === EMPTY) return 0; + if (!ec) ec = c; else if (c !== ec) return 0; + } + return ec; + } + + /** A true eye of col (not false through its diagonals). */ + isEye(p, col) { + if (this.eyeish(p) !== col) return false; + const { DIAG } = this.g; + let bad = 0, edge = false; + for (let k = 0; k < 4; k++) { + const c = this.color[p + DIAG[k]]; + if (c === EDGE) edge = true; else if (c === 3 - col) bad++; + } + if (edge) bad++; + return bad < 2; + } + + /** Liberties (distinct, up to `limit`) of col's chain at p if col played there. */ + libsAfter(p, col, limit = 3) { + const { D4 } = this.g; + const color = this.color, mark = this.mark; + const st = ++this.stamp; + mark[p] = st; + let n = 0; + for (let k = 0; k < 4; k++) { + const q = p + D4[k]; + if (color[q] === EMPTY && mark[q] !== st) { mark[q] = st; if (++n >= limit) return n; } + } + const opp = 3 - col; + for (let k = 0; k < 4; k++) { + const q = p + D4[k]; + if (color[q] === opp && this.inAtari(this.head[q]) && mark[q] !== st) { mark[q] = st; if (++n >= limit) return n; } + } + for (let k = 0; k < 4; k++) { + const q = p + D4[k]; + if (color[q] !== col) continue; + const h = this.head[q]; + if (mark[h] === -st) continue; + mark[h] = -st; + let s = h; + do { + for (let j = 0; j < 4; j++) { + const t = s + D4[j]; + if (color[t] === EMPTY && mark[t] !== st) { mark[t] = st; if (++n >= limit) return n; } + } + s = this.next[s]; + } while (s !== h); + } + return n; + } + + selfAtari(p, col) { return this.libsAfter(p, col, 2) < 2; } + + pat3(p) { + const { N8 } = this.g; + const color = this.color; + let code = 0; + for (let k = 0; k < 8; k++) code |= color[p + N8[k]] << (k * 2); + return PAT3[code] === 1; + } + + /** Stones col would capture by playing p. */ + captureCount(p, col) { + const { D4 } = this.g; + const opp = 3 - col; + let n = 0, s0 = -1, s1 = -1, s2 = -1; + for (let k = 0; k < 4; k++) { + const q = p + D4[k]; + if (this.color[q] !== opp) continue; + const h = this.head[q]; + if (h === s0 || h === s1 || h === s2) continue; + if (s0 < 0) s0 = h; else if (s1 < 0) s1 = h; else s2 = h; + if (this.inAtari(h)) n += this.csize[h]; + } + return n; + } + + /** Area score for black (stones + one-colour empty points − komi); fills own[] if given. */ + score(own) { + const { pts, D4 } = this.g; + const color = this.color; + let s = 0; + for (let i = 0; i < pts.length; i++) { + const p = pts[i], c = color[p]; + let o = 0; + if (c === BL) o = 1; + else if (c === WH) o = -1; + else { + let ec = 0, ok = true; + for (let k = 0; k < 4; k++) { + const v = color[p + D4[k]]; + if (v === EDGE) continue; + if (v === EMPTY) { ok = false; break; } + if (!ec) ec = v; else if (v !== ec) { ok = false; break; } + } + if (ok && ec) o = ec === BL ? 1 : -1; + } + s += o; + if (own) own[i] += o; + } + return s - this.komi; + } } + +/** A fast board from a GoLogic position. */ +function fromPos(pos) { + const g = geo(pos.size); + const b = new Board(pos.size); + for (let sq = 0; sq < pos.board.length; sq++) { + const v = pos.board[sq]; + if (v) b.put(g.toIdx[sq], toC(v)); + } + b.ko = pos.ko >= 0 ? g.toIdx[pos.ko] : 0; + b.turn = toC(pos.turn); + b.komi = pos.komi ?? 6.5; + b.last = pos.last == null ? -1 : pos.last < 0 ? PASS : g.toIdx[pos.last]; + b.last2 = pos.last2 == null ? -1 : pos.last2 < 0 ? PASS : g.toIdx[pos.last2]; + b.passes = pos.passes ?? 0; + b.moves = pos.moveNo ?? 0; + return b; +} + +// ── playouts ───────────────────────────────────────────────────────────────── +const CAND = new Int16Array(64); + +/** Moves near the last one that capture, or rescue a chain from atari. */ +function fixAtariMoves(b, rnd) { + const last = b.last; + if (last <= 0) return 0; + const col = b.turn, opp = 3 - col; + const { D4 } = b.g; + let n = 0; + // the chain just played, if it is in atari: take it + if (b.color[last] === opp && b.inAtari(b.head[last])) CAND[n++] = b.atariLib(b.head[last]); + for (let k = 0; k < 4; k++) { + const q = last + D4[k]; + const c = b.color[q]; + if (c === opp) { + const h = b.head[q]; + if (b.inAtari(h) && n < 60) CAND[n++] = b.atariLib(h); + } else if (c === col) { + const h = b.head[q]; + if (!b.inAtari(h)) continue; + // ours, in atari: extend if that gives room, or capture a neighbour in atari + const lib = b.atariLib(h); + if (b.libsAfter(lib, col, 3) >= 2 && n < 60) CAND[n++] = lib; + let s = h; + do { + for (let j = 0; j < 4; j++) { + const t = s + D4[j]; + if (b.color[t] === opp && b.inAtari(b.head[t]) && n < 60) CAND[n++] = b.atariLib(b.head[t]); + } + s = b.next[s]; + } while (s !== h && n < 60); + } + } + if (!n) return 0; + const start = Math.floor(rnd() * n); + for (let i = 0; i < n; i++) { + const p = CAND[(start + i) % n]; + if (b.legal(p, col)) return p; + } + return 0; +} + +function patternMoves(b, rnd) { + const last = b.last; + if (last <= 0) return 0; + const { N8 } = b.g; + let n = 0; + for (let k = 0; k < 8; k++) { + const p = last + N8[k]; + if (b.color[p] === EMPTY && b.pat3(p)) CAND[n++] = p; + } + if (!n) return 0; + const col = b.turn; + const start = Math.floor(rnd() * n); + for (let i = 0; i < n; i++) { + const p = CAND[(start + i) % n]; + if (!b.legal(p, col)) continue; + if (rnd() < PROB_SSAREJECT && b.selfAtari(p, col)) continue; + return p; + } + return 0; +} + +function randomMove(b, rnd) { + const n = b.ne; + if (!n) return 0; + const col = b.turn; + const start = Math.floor(rnd() * n); + for (let i = 0; i < n; i++) { + const p = b.empty[(start + i) % n]; + if (b.isEye(p, col)) continue; + if (!b.legal(p, col)) continue; + if (rnd() < PROB_RSAREJECT && b.selfAtari(p, col)) continue; + return p; + } + return 0; +} + +function playoutMove(b, rnd) { + let p = 0; + if (b.last > 0) { + if (rnd() < PROB_CAPTURE) { + p = fixAtariMoves(b, rnd); + if (p && !(rnd() < PROB_SSAREJECT && b.selfAtari(p, b.turn))) return p; + } + if (rnd() < PROB_PAT3) { p = patternMoves(b, rnd); if (p) return p; } + } + return randomMove(b, rnd); +} + +/** Play out to the end; returns black's area score. amaf marks first-play colours. */ +function playout(b, rnd, amaf, own) { + const maxMoves = b.moves + b.size * b.size * 3; + let passes = b.passes; + while (passes < 2 && b.moves < maxMoves) { + const p = playoutMove(b, rnd); + if (!p) { b.pass(); passes++; continue; } + passes = 0; + if (amaf && amaf[p] === 0) amaf[p] = b.turn; + b.play(p); + } + return b.score(own); +} + +// ── the tree ───────────────────────────────────────────────────────────────── +class Node { + constructor(move, color) { + this.move = move; // board index, or PASS + this.color = color; // who played it (1 / 2), 0 at the root + this.n = 0; this.w = 0; + this.an = 0; this.aw = 0; + this.pn = 0; this.pw = 0; + this.ss = 0; // sum of black's scores through this node + this.children = null; + } + + urgency() { + const v = this.n + this.pn; + const exp = (this.w + this.pw) / v; + if (this.an === 0) return exp; + const rexp = this.aw / this.an; + const beta = this.an / (this.an + v + (v * this.an) / RAVE_EQUIV); + return beta * rexp + (1 - beta) * exp; + } +} + +/** Common-fate-graph distance from p (chains count as one step), capped at 3. */ +function cfgDistance(b, from, out) { + out.fill(-1); + if (from <= 0) return; + const { D4 } = b.g; + const color = b.color; + out[from] = 0; + const q = [from]; + for (let qi = 0; qi < q.length; qi++) { + const c = q[qi]; + for (let k = 0; k < 4; k++) { + const d = c + D4[k]; + if (color[d] === EDGE) continue; + const nd = color[d] !== EMPTY && color[d] === color[c] ? out[c] : out[c] + 1; + if (nd > 3) continue; + if (out[d] < 0 || out[d] > nd) { out[d] = nd; q.push(d); } + } + } +} + +function emptyArea(b, p) { + const list = b.g.area3.get(p); + for (let i = 0; i < list.length; i++) { const c = b.color[list[i]]; if (c === BL || c === WH) return false; } + return true; +} + +function expand(node, b, cfg, forbidden = null, root = false) { + const col = b.turn, opp = 3 - col; + const { D4 } = b.g; + const kids = []; + cfgDistance(b, b.last, cfg); + const opening = root && b.size >= 13 && (b.g.pts.length - b.ne) < b.size * 1.5; + for (let i = 0; i < b.ne; i++) { + const p = b.empty[i]; + if (forbidden && forbidden.has(p)) continue; + if (!b.legal(p, col) || b.isEye(p, col)) continue; + const ch = new Node(p, col); + ch.pn = PRIOR_EVEN; ch.pw = PRIOR_EVEN / 2; + const cap = b.captureCount(p, col); + if (cap) { const pr = cap > 1 ? PRIOR_CAPTURE_MANY : PRIOR_CAPTURE_ONE; ch.pn += pr; ch.pw += pr; } + if (b.pat3(p)) { ch.pn += PRIOR_PAT3; ch.pw += PRIOR_PAT3; } + const d = cfg[p]; + if (d >= 1 && d <= 3) { ch.pn += PRIOR_CFG[d - 1]; ch.pw += PRIOR_CFG[d - 1]; } + // rescuing a neighbouring chain in atari + for (let k = 0; k < 4; k++) { + const q = p + D4[k]; + if (b.color[q] === col && b.inAtari(b.head[q])) { + if (b.libsAfter(p, col, 3) >= 3) { ch.pn += PRIOR_CAPTURE_ONE; ch.pw += PRIOR_CAPTURE_ONE; } + break; + } + } + if (b.selfAtari(p, col)) ch.pn += PRIOR_SELFATARI; + const h = b.g.height[p]; + const open = emptyArea(b, p); + if (h <= 2 && open) { + if (h <= 1) ch.pn += PRIOR_EMPTYAREA; + else { ch.pn += PRIOR_EMPTYAREA; ch.pw += PRIOR_EMPTYAREA; } + } + if (root) { + // at the root, tactics the playouts are too lazy to see: take stones + // that could otherwise run, and run with ours while we can + if (cap) { + let urgent = cap >= 2; + if (!urgent) { + for (let k = 0; k < 4 && !urgent; k++) { + const q = p + D4[k]; + if (b.color[q] === opp && b.inAtari(b.head[q]) && b.libsAfter(p, opp, 3) >= 3) urgent = true; + } + } + if (urgent) { ch.pn += PRIOR_TACTIC; ch.pw += PRIOR_TACTIC; } + } + for (let k = 0; k < 4; k++) { + const q = p + D4[k]; + if (b.color[q] === col && b.inAtari(b.head[q]) && b.libsAfter(p, col, 3) >= 3) { + const big = b.csize[b.head[q]] >= 2; + ch.pn += big ? PRIOR_TACTIC : PRIOR_TACTIC / 2; ch.pw += big ? PRIOR_TACTIC : PRIOR_TACTIC / 2; + break; + } + } + if (opening && (h === 2 || h === 3)) { + const r = Math.floor(p / b.g.W) - 1, c = (p % b.g.W) - 1, n = b.size - 1; + const corner = Math.min(r, n - r) <= 4 && Math.min(c, n - c) <= 4; + let v = 0; + if (open) v = corner ? PRIOR_OPENING : PRIOR_OPENING / 3; + else if (corner) { + // approaches and the 3-3 invasion under a corner stone (the + // handicap openings): near stones, but not touching one + let touch = false; + for (let k = 0; k < 4; k++) { const q = p + D4[k]; if (b.color[q] === BL || b.color[q] === WH) touch = true; } + if (!touch) v = PRIOR_OPENING / 2; + } + if (v) { ch.pn += v; ch.pw += v; } + } else if (opening && h <= 1 && !cap) { + ch.pn += PRIOR_OPENING; // the first two lines are too low this early + } + } + kids.push(ch); + } + if (!kids.length) { + const ps = new Node(PASS, col); + ps.pn = PRIOR_EVEN; ps.pw = PRIOR_EVEN / 2; + kids.push(ps); + } + node.children = kids; +} + +function pickChild(node, rnd) { + const kids = node.children; + let best = null, bu = -1; + for (let i = 0; i < kids.length; i++) { + const u = kids[i].urgency() + rnd() * 1e-6; + if (u > bu) { bu = u; best = kids[i]; } + } + return best ?? kids[0]; +} + +const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now()); + +/** + * The search. opts: { playouts, ms, seed, expandAt }. + * → { root, rootBoard, ownership (per GoLogic point, black +1 … white −1), + * playouts, lead (mean black score), elapsed } + */ +export function search(pos, { playouts = 2000, ms = 2000, seed = null, expandAt = null } = {}) { + const t0 = now(); + const rnd = xorshift(seed ?? Math.floor(Math.random() * 2 ** 31)); + const rootB = fromPos(pos); + const g = rootB.g; + const b = new Board(pos.size); + const amaf = new Uint8Array(g.LEN); + const cfg = new Int8Array(g.LEN); + const own = new Float64Array(g.pts.length); + const EXPAND = expandAt ?? (pos.size >= 19 ? 14 : pos.size >= 13 ? 10 : 8); + const marginScale = pos.size * 0.6; + const root = new Node(PASS, 0); + const forbidden = new Set((pos.forbidden ?? []).map((sq) => g.toIdx[sq])); + expand(root, rootB, cfg, forbidden, true); + const path = []; + let done = 0; + const firstLen = root.children.length; + while (done < playouts) { + if ((done & 31) === 0 && done > 0 && now() - t0 > ms) break; + b.copyFrom(rootB); + amaf.fill(0); + path.length = 0; + path.push(root); + let node = root; + let passes = b.passes; + while (node.children && passes < 2) { + const ch = pickChild(node, rnd); + path.push(ch); + if (ch.move === PASS) { b.pass(); passes++; } else { + passes = 0; + if (amaf[ch.move] === 0) amaf[ch.move] = b.turn; + b.play(ch.move); + } + if (!ch.children && ch.n + 1 >= EXPAND && passes < 2) expand(ch, b, cfg); + node = ch; + } + const score = passes >= 2 ? b.score(own) : playout(b, rnd, amaf, own); + // mostly win/loss, with a little weight on the margin so a won game + // still takes the stones on offer and a lost one stays close + const blackWin = (score > 0 ? 1 : score < 0 ? 0 : 0.5) * (1 - MARGIN_W) + MARGIN_W * (0.5 + 0.5 * Math.tanh(score / marginScale)); + for (let i = path.length - 1; i >= 0; i--) { + const nd = path[i]; + nd.n++; + nd.ss += score; + if (nd.color) nd.w += nd.color === BL ? blackWin : 1 - blackWin; + if (nd.children) { + const kids = nd.children; + for (let k = 0; k < kids.length; k++) { + const c = kids[k]; + if (c.move !== PASS && amaf[c.move] === c.color) { c.an++; c.aw += c.color === BL ? blackWin : 1 - blackWin; } + } + } + } + done++; + } + const ownership = new Array(pos.size * pos.size).fill(0); + if (done) g.pts.forEach((p, i) => { ownership[g.toSq[p]] = own[i] / done; }); + return { root, rootB, ownership, playouts: done, lead: done ? root.ss / done : 0, elapsed: now() - t0, firstLen }; +} + +const sqOf = (pos, move) => (move === PASS ? -1 : geo(pos.size).toSq[move]); + +function rankChildren(res, color) { + const kids = res.root.children.filter((c) => c.n > 0).sort((a, b) => b.n - a.n); + return kids.map((c) => ({ + node: c, + visits: c.n, + winrate: c.w / c.n, + lead: (c.ss / c.n) * (color === BL ? 1 : -1), + })); +} + +/** Principal variation (most-visited line) from a node. */ +function pvFrom(node, pos, len = 8) { + const out = []; + let n = node; + while (n && out.length < len) { + out.push(sqOf(pos, n.move)); + if (!n.children) break; + let best = null; + for (const c of n.children) if (!best || c.n > best.n) best = c; + if (!best || best.n < 3) break; + n = best; + } + return out; +} + +/** Is a move at sq pointless: settled territory, nobody's chain short of liberties? */ +function pointless(pos, sq, ownership) { + if (sq < 0) return false; + if (Math.abs(ownership[sq]) < 0.88) return false; + const N = L.nbrs(pos.size); + for (const n of N[sq]) { + if (!pos.board[n]) { if (Math.abs(ownership[n]) < 0.8) return false; continue; } + const g = L.groupAt(pos.board, pos.size, n); + if (g.libs.length <= 2) return false; + } + return true; +} + +/** Score the position by the game's real rules with dead stones from ownership. */ +export function settledScore(pos, ownership) { + const dead = deadFromOwnership(pos, ownership); + const gs = { size: pos.size, board: pos.board, komi: pos.komi, rules: pos.rules ?? 'japanese', captures: pos.captures ?? { black: 0, white: 0 }, dead }; + const s = L.scoreGame(gs, dead); + return { ...s, dead }; +} + +function deadFromOwnership(pos, ownership, threshold = -0.3) { + const dead = []; + for (const g of L.allGroups(pos.board, pos.size)) { + const sign = g.color === L.BLACK ? 1 : -1; + const avg = g.stones.reduce((a, s) => a + ownership[s], 0) / g.stones.length; + if (avg * sign < threshold) dead.push(...g.stones); + } + return dead.sort((a, b) => a - b); +} + +/** The opponent's move. */ +export function chooseMove(pos, skill = 3, { seed = null, scale = 1 } = {}) { + const k = clampSkill(skill); + const prof = SKILL[k]; + const color = toC(pos.turn); + const ms = prof.ms * (SIZE_TIME[pos.size] ?? 1) * scale; + const res = search(pos, { playouts: Math.max(60, Math.round(prof.playouts * scale)), ms, seed }); + const rnd = xorshift((seed ?? Math.floor(Math.random() * 2 ** 31)) ^ 0x5bd1e995); + const ranked = rankChildren(res, color); + const out = { sq: -1, resign: false, winrate: 0.5, lead: 0, ownership: res.ownership, playouts: res.playouts, pv: [] }; + if (!ranked.length) return out; + const best = ranked[0]; + out.winrate = best.winrate; + out.lead = best.lead; + const settledNow = isSettled(pos, res.ownership); + // the game's last word: the other side passed, the board is settled and + // we're ahead → pass too + const lastPass = pos.last != null && pos.last < 0; + if (lastPass && settledNow) { + const s = settledScore(pos, res.ownership); + const ahead = color === BL ? s.black > s.white : s.white > s.black; + if (ahead) { out.sq = -1; return out; } + } + // resign a hopeless game, late + const filled = pos.board.filter(Boolean).length; + if (best.winrate < 0.06 && res.playouts >= 200 && filled > pos.size * pos.size * 0.3 && best.lead < -prof.resignAt) { + out.resign = true; + return out; + } + let pick = best; + if (prof.temp > 0 && ranked.length > 1) { + // sample among the moves the search took seriously, sharper with skill + const top = ranked.filter((r) => r.visits >= Math.max(2, best.visits * 0.08)).slice(0, 8); + const weights = top.map((r) => Math.pow(r.visits, 1 / prof.temp)); + const total = weights.reduce((a, x) => a + x, 0); + let x = rnd() * total; + for (let i = 0; i < top.length; i++) { x -= weights[i]; if (x <= 0) { pick = top[i]; break; } } + } + if (prof.loose > 0 && rnd() < prof.loose && !settledNow) { + // a plausible-looking but loose move: high prior, not much reading + const kids = res.root.children.filter((c) => c.move !== PASS).sort((a, b) => (b.pw / b.pn) - (a.pw / a.pn)).slice(0, 10); + if (kids.length) { + const c = kids[Math.floor(rnd() * kids.length)]; + pick = { node: c, visits: c.n, winrate: c.n ? c.w / c.n : 0.5, lead: c.n ? (c.ss / c.n) * (color === BL ? 1 : -1) : 0 }; + } + } + out.sq = sqOf(pos, pick.node.move); + // filling settled territory gains nothing (and costs a point under Japanese rules) + if (pointless(pos, out.sq, res.ownership)) { + const useful = ranked.find((r) => r.node.move !== PASS && !pointless(pos, sqOf(pos, r.node.move), res.ownership)); + if (useful && (useful.visits >= best.visits * 0.1 || !settledNow)) { out.sq = sqOf(pos, useful.node.move); pick = useful; } else out.sq = -1; + } + out.pv = out.sq >= 0 ? pvFrom(pick.node, pos) : []; + return out; +} + +/** Few contested points left: every empty point leans clearly one way, no chain is short of liberties. */ +export function isSettled(pos, ownership) { + let contested = 0; + for (let sq = 0; sq < pos.board.length; sq++) { + const v = pos.board[sq]; + if (!v) { if (Math.abs(ownership[sq]) < 0.7) contested++; continue; } + const want = v === L.BLACK ? 1 : -1; + if (Math.abs(ownership[sq]) < 0.6 && ownership[sq] * want < 0.6 && ownership[sq] * want > -0.6) contested++; + } + return contested <= Math.max(1, Math.round(pos.size * pos.size * 0.02)); +} + +/** A full-strength look at a position (hints, the score bar). */ +export function analyse(pos, { playouts = 6000, ms = 1200, seed = null } = {}) { + const res = search(pos, { playouts, ms, seed }); + const color = toC(pos.turn); + const ranked = rankChildren(res, color); + const top = ranked.slice(0, 5).map((r) => ({ sq: sqOf(pos, r.node.move), visits: r.visits, winrate: r.winrate, lead: r.lead })); + let best = top[0]?.sq ?? -1; + if (pointless(pos, best, res.ownership)) { + const alt = top.find((t) => !pointless(pos, t.sq, res.ownership) && t.visits >= (top[0]?.visits ?? 0) * 0.2); + best = alt ? alt.sq : -1; + } + return { + best, top, ownership: res.ownership, playouts: res.playouts, + winrate: top[0]?.winrate ?? 0.5, + lead: top[0]?.lead ?? 0, + blackLead: res.lead, + pv: ranked[0] ? pvFrom(ranked[0].node, pos) : [], + }; +} + +/** Which stones are dead at the end: playouts from the final position. */ +export function estimateDead(pos, { playouts = 3000, ms = 1500, seed = null } = {}) { + // both sides to move, averaged: a stone that only lives if its side + // gets the next move is not alive + const a = search({ ...pos, turn: L.BLACK, ko: -1, forbidden: [], last: null, passes: 0 }, { playouts: playouts / 2, ms: ms / 2, seed }); + const b = search({ ...pos, turn: L.WHITE, ko: -1, forbidden: [], last: null, passes: 0 }, { playouts: playouts / 2, ms: ms / 2, seed: seed == null ? null : seed + 1 }); + const ownership = a.ownership.map((v, i) => (v + b.ownership[i]) / 2); + return { dead: deadFromOwnership(pos, ownership, 0), ownership }; +} + +/** + * Review: for each position, the lead and win rate from black's side and + * the best move for the side to move. list: [pos…]. + */ +export function reviewPositions(list, { playouts = 500, ms = 250, seed = null } = {}) { + return list.map((pos, i) => { + if (!pos) return null; + const res = search(pos, { playouts, ms, seed: seed == null ? null : seed + i }); + const color = toC(pos.turn); + const ranked = rankChildren(res, color); + const top = ranked[0]; + const wrMover = top ? top.winrate : 0.5; + return { + lead: res.lead, + winrate: color === BL ? wrMover : 1 - wrMover, + best: top ? sqOf(pos, top.node.move) : -1, + }; + }); +} + +// ── words ──────────────────────────────────────────────────────────────────── +/** The tactical facts of playing the side to move at sq. */ +export function classify(gs, sq) { + const size = gs.size, color = gs.turn, opp = L.other(color); + const t = L.tryMove(gs, sq, color); + const f = { legal: t.ok, captured: t.captured?.length ?? 0, ko: false, saves: 0, ataris: 0, atariStones: 0, connects: false, cuts: false, line: L.lineOf(sq, size), emptyArea: false, corner: false, pressSmall: 0 }; + if (!t.ok) return f; + const N = L.nbrs(size); + const b0 = gs.board, b1 = t.board; + f.ko = f.captured === 1 && t.own.stones.length === 1 && t.own.libs.length === 1; + const seen = new Set(); + let ownChains = 0; + for (const n of N[sq]) { + if (b0[n] === color) { + const g = L.groupAt(b0, size, n); + const key = Math.min(...g.stones); + if (seen.has(key)) continue; + seen.add(key); + ownChains++; + if (g.libs.length === 1 && t.own.libs.length >= 2) f.saves += g.stones.length; + } + } + f.connects = ownChains >= 2; + const seenO = new Set(); + let oppChains = 0; + for (const n of N[sq]) { + if (b1[n] !== opp) continue; + const g = L.groupAt(b1, size, n); + const key = Math.min(...g.stones); + if (seenO.has(key)) continue; + seenO.add(key); + oppChains++; + if (g.libs.length === 1) { f.ataris++; f.atariStones += g.stones.length; } else if (g.libs.length === 2) f.pressSmall++; + } + // a cut: touching two of their chains that share a diagonal through sq + f.cuts = oppChains >= 2; + const [r, c] = L.rc(sq, size); + let near = false; + for (let dr = -3; dr <= 3 && !near; dr++) for (let dc = -3; dc <= 3; dc++) { + if (Math.abs(dr) + Math.abs(dc) > 3) continue; + const rr = r + dr, cc = c + dc; + if (rr < 0 || cc < 0 || rr >= size || cc >= size) continue; + if (b0[rr * size + cc]) { near = true; break; } + } + f.emptyArea = !near; + const lo = Math.min(r, size - 1 - r), lc = Math.min(c, size - 1 - c); + f.corner = lo <= (size >= 13 ? 5 : 3) && lc <= (size >= 13 ? 5 : 3); + return f; +} + +/** A few words on what a move does, finishing "It …". */ +export function describeIdea(gs, sq) { + if (sq < 0) return 'is time to pass: nothing on the board is worth a stone'; + const f = classify(gs, sq); + if (!f.legal) return 'is not a legal move'; + const s = (n, one, many) => (n === 1 ? one : many.replace('{n}', n)); + if (f.ko) return 'takes the ko'; + if (f.captured) return `captures ${s(f.captured, 'a stone', '{n} stones')}`; + if (f.saves) return `rescues ${s(f.saves, 'your stone', 'your {n} stones')} from atari`; + if (f.ataris) return `puts ${s(f.atariStones, 'a stone', '{n} stones')} of theirs in atari`; + if (f.cuts) return 'cuts their stones apart'; + if (f.connects) return 'joins your stones into one group'; + if (f.pressSmall) return 'takes a liberty from a weak group of theirs'; + if (f.emptyArea && f.corner && f.line >= 3 && f.line <= 4) return 'claims an empty corner'; + if (f.emptyArea && f.line >= 3 && f.line <= 4) return 'is a big point on open ground'; + if (f.line === 1) return 'is a small move on the edge that seals a border'; + if (f.line === 2) return 'secures the side'; + return 'strengthens your position where it is thin'; +} + +/** For the review: why the better move was better (and how much). */ +export function describeMistake(gs, played, best, loss) { + const idea = describeIdea(gs, best); + const pts = Math.max(1, Math.round(Math.abs(loss))); + return `${L.notate(best, gs.size)} ${idea}; about ${pts} point${pts === 1 ? '' : 's'} better`; +} + +/** A pos object for the engine from a GoLogic game state. */ +export function posOf(gs, extra = {}) { + const hist = gs.history; + const last = hist.length ? (hist[hist.length - 1].pass ? -1 : hist[hist.length - 1].sq) : null; + const last2 = hist.length > 1 ? (hist[hist.length - 2].pass ? -1 : hist[hist.length - 2].sq) : null; + const forbidden = []; + if (gs.phase === 'playing') { + for (let sq = 0; sq < gs.board.length; sq++) { + if (gs.board[sq]) continue; + const t = L.tryMove(gs, sq); + if (!t.ok && (t.reason === 'superko' || t.reason === 'ko')) forbidden.push(sq); + } + } + return { + size: gs.size, board: gs.board, turn: gs.turn, komi: gs.komi, rules: gs.rules, + ko: gs.ko, last, last2, passes: gs.passes, captures: gs.captures, forbidden, moveNo: hist.length, ...extra, + }; +} + +// exposed for the tests +export const _internals = { Board, fromPos, geo, playout, xorshift, PAT3 }; diff --git a/src/games/go/GoArt.js b/src/games/go/GoArt.js new file mode 100644 index 0000000..a02ae54 --- /dev/null +++ b/src/games/go/GoArt.js @@ -0,0 +1,760 @@ +// GoArt.js: baked canvas textures for Unkai-ji, a mountain temple at +// dawn. All procedural: no image files. +// +// go-sky the dawn sky seen through the open shoji (left column) +// go-ridges mountain ridges and mist banks over it (transparent +// sky, so the rising sun can sit between the two) +// go-room the room: tatami everywhere, the opening's frame (a +// pillar, the lintel, the veranda), a half-slid shoji +// panel, the plaster wall and the tokonoma (incense +// burner, a vase with the season's branch), the dawn +// light falling across the mats; the view is cut out +// go-props, go-vignette the furniture and the light alone (for a +// chosen playfield) +// go-board- the kaya board: straight grain, ink lines, star +// points, the slab's front edge, its shadow +// go-black, go-white-0…3 slate and clamshell stones (2× bake) +// go-shadow a stone's soft shadow +// go-bowl-black, go-bowl-white, go-lid the bowls and their lids +// go-plate, go-plate-glow, go-card-status, go-card-record, go-ribbon, +// go-bar HUD furniture +// go-glow, go-ring, go-spark, go-mist, go-smoke, go-sun, go-bird, +// go-p-, go-terr, go-x effects and marks + +import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { + W, H, BX, BY, BOARD, FACE, BCX, BCY, STONE_R, PLATE, STATUS, RECORD, RIBBON, BAR, + VIEW, ALCOVE, INCENSE, VASE, BOWLS, geom, +} from './GoLayout.js'; +import { starPoints } from './GoLogic.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 STONE_TEX = (STONE_R + 10) * 2 * RES; +export const WHITE_VARIANTS = 4; +export const PAD = 24; // board texture shadow padding +export const BOARD_POS = { x: BX - PAD, y: BY - PAD }; + +export const INK = '#20140c'; +export const GOLD = 0xd8b060; +export const VERMILION = 0xb83a24; +export const CREAM = '#f3ead6'; + +/** The season by the calendar: the petals at the window follow it. */ +export function season(d = new Date()) { + const m = d.getMonth(); + if (m <= 1 || m === 11) return 'winter'; + if (m <= 4) return 'spring'; + if (m <= 7) return 'summer'; + return 'autumn'; +} + +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 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 grain(ctx, rnd, x, y, w, h, { tone = 'rgba(20,8,2,0.3)', lines = 30, wave = 4, vertical = false, width = [0.5, 1.6] } = {}) { + ctx.save(); + ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); + ctx.strokeStyle = tone; + const Lr = 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.002 + rnd() * 0.008, ph = rnd() * 6; + ctx.lineWidth = width[0] + rnd() * (width[1] - width[0]); + ctx.beginPath(); + for (let t = 0; t <= Lr; t += 8) { + const d = o + Math.sin(t * f + ph) * amp + Math.sin(t * f * 3.1 + ph) * amp * 0.25; + 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 woodGrad(ctx, x0, y0, x1, y1, a = '#4a2c16', b = '#24140a') { + const g = ctx.createLinearGradient(x0, y0, x1, y1); + g.addColorStop(0, a); g.addColorStop(1, b); + return g; +} + +function goldGrad(ctx, x0, y0, x1, y1) { + const g = ctx.createLinearGradient(x0, y0, x1, y1); + g.addColorStop(0, '#f2d898'); g.addColorStop(0.45, '#b48a3a'); g.addColorStop(0.7, '#e8c478'); g.addColorStop(1, '#7a5620'); + return g; +} + +/** A brushed ink circle (ensō), open at the top right. */ +export function enso(ctx, cx, cy, r, { color = 'rgba(24,16,10,0.92)', width = 0.16, rnd = Math.random } = {}) { + const steps = 90; + const start = -0.9, end = start + Math.PI * 1.86; + for (let i = 0; i < steps; i++) { + const t = i / steps; + const a = start + (end - start) * t; + const press = Math.sin(Math.PI * Math.min(1, t * 1.25)) * (1 - t * 0.35); + const wdt = r * width * (0.35 + press) * (0.9 + rnd() * 0.2); + const rr2 = r * (1 + Math.sin(t * 9) * 0.015); + ctx.fillStyle = color; + ctx.globalAlpha = 0.55 + press * 0.45; + ctx.beginPath(); ctx.arc(cx + Math.cos(a) * rr2, cy + Math.sin(a) * rr2, wdt / 2, 0, Math.PI * 2); ctx.fill(); + if (t > 0.8 && rnd() < 0.5) { + // dry-brush flecks at the tail + ctx.globalAlpha = 0.3; + ctx.beginPath(); ctx.arc(cx + Math.cos(a) * (rr2 + (rnd() - 0.5) * wdt), cy + Math.sin(a) * (rr2 + (rnd() - 0.5) * wdt), wdt * 0.12, 0, Math.PI * 2); ctx.fill(); + } + } + ctx.globalAlpha = 1; +} + +// ── the view ───────────────────────────────────────────────────────────────── +const HORIZON = 640; + +function bakeSky(scene) { + const c = canvas(VIEW.w, H), ctx = c.getContext('2d'), rnd = seeded(11); + const g = ctx.createLinearGradient(0, 0, 0, H); + g.addColorStop(0, '#141a34'); g.addColorStop(0.25, '#2c2c58'); g.addColorStop(0.43, '#6a5282'); + g.addColorStop(0.53, '#c47c86'); g.addColorStop(0.6, '#eca684'); g.addColorStop(0.66, '#f6d29a'); g.addColorStop(1, '#f2c088'); + ctx.fillStyle = g; ctx.fillRect(0, 0, VIEW.w, H); + // the last stars + for (let i = 0; i < 70; i++) { + const x = rnd() * VIEW.w, y = rnd() * 300, r = rnd() * 1.3 + 0.2; + ctx.fillStyle = `rgba(255,250,235,${0.25 + rnd() * 0.5 * (1 - y / 320)})`; + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + } + // long thin clouds lit from below + for (let i = 0; i < 9; i++) { + const y = 300 + rnd() * 300, x = rnd() * VIEW.w, w = 120 + rnd() * 260, h = 6 + rnd() * 10; + const cg = ctx.createLinearGradient(0, y - h, 0, y + h); + cg.addColorStop(0, 'rgba(120,90,140,0)'); cg.addColorStop(0.5, `rgba(255,${170 + rnd() * 50},${150 + rnd() * 40},0.35)`); cg.addColorStop(1, 'rgba(120,90,140,0)'); + ctx.fillStyle = cg; + ctx.beginPath(); ctx.ellipse(x, y, w, h, 0, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, 'go-sky', c); +} + +function ridgeLine(rnd, base, amp, rough) { + const pts = []; + let y = base; + const ph = rnd() * 10, f1 = 0.006 + rnd() * 0.004, f2 = 0.02 + rnd() * 0.02; + for (let x = -10; x <= VIEW.w + 10; x += 6) { + y = base - Math.abs(Math.sin(x * f1 + ph)) * amp - Math.sin(x * f2 + ph * 2) * amp * 0.18 - (rnd() - 0.5) * rough; + pts.push([x, y]); + } + return pts; +} + +function bakeRidges(scene, seas) { + const c = canvas(VIEW.w, H), ctx = c.getContext('2d'), rnd = seeded(23); + const layers = [ + { base: 690, amp: 120, col: '#9c8fb2', mist: 0.55 }, + { base: 760, amp: 110, col: '#7a7496', mist: 0.5 }, + { base: 840, amp: 120, col: '#55587a', mist: 0.45 }, + { base: 930, amp: 110, col: '#36405a', mist: 0.35 }, + { base: 1040, amp: 120, col: '#1c2632', mist: 0.2 }, + ]; + layers.forEach((Ly, li) => { + const pts = ridgeLine(rnd, Ly.base, Ly.amp, li < 2 ? 2 : 4); + // body: lighter at the crest (lit by the dawn), darker below + const top = Math.min(...pts.map((p) => p[1])); + const g = ctx.createLinearGradient(0, top, 0, Ly.base + 140); + g.addColorStop(0, Ly.col); g.addColorStop(1, li > 3 ? '#0e141a' : '#2a2c44'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.moveTo(-10, H); + for (const [x, y] of pts) ctx.lineTo(x, y); + ctx.lineTo(VIEW.w + 10, H); ctx.closePath(); ctx.fill(); + // the rim light on the crest + ctx.strokeStyle = `rgba(255,200,160,${0.22 - li * 0.04})`; ctx.lineWidth = 2; + ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y + 1) : ctx.moveTo(x, y + 1))); ctx.stroke(); + if (seas === 'winter' && li < 3) { + // snow on the far crests + ctx.fillStyle = 'rgba(245,240,255,0.55)'; + ctx.beginPath(); + pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); + for (let i = pts.length - 1; i >= 0; i--) { const [x, y] = pts[i]; ctx.lineTo(x, y + 6 + Math.abs(Math.sin(x * 0.05)) * 10); } + ctx.closePath(); ctx.fill(); + } + // trees on the nearer ridges: little conifer spikes + if (li >= 2) { + ctx.fillStyle = li === 4 ? '#0a1016' : li === 3 ? '#1e2836' : '#3a4260'; + for (let i = 0; i < pts.length; i += 2) { + if (rnd() < 0.45) continue; + const [x, y] = pts[i], h = (6 + rnd() * 10) * (li - 1); + ctx.beginPath(); ctx.moveTo(x - h * 0.25, y + 3); ctx.lineTo(x, y - h); ctx.lineTo(x + h * 0.25, y + 3); ctx.closePath(); ctx.fill(); + } + } + // a pagoda on the third ridge + if (li === 2) { + const [px, py] = pts[Math.floor(pts.length * 0.68)]; + ctx.fillStyle = '#3a3c5a'; + for (let k = 0; k < 5; k++) { + const yy = py - 8 - k * 13, w = 30 - k * 4; + ctx.beginPath(); ctx.moveTo(px - w, yy); ctx.quadraticCurveTo(px, yy - 7, px + w, yy); ctx.lineTo(px + w * 0.6, yy + 3); ctx.lineTo(px - w * 0.6, yy + 3); ctx.closePath(); ctx.fill(); + ctx.fillRect(px - w * 0.45, yy, w * 0.9, 10); + } + ctx.fillRect(px - 1.5, py - 92, 3, 26); + } + // a mist bank at the foot of each ridge + const mg = ctx.createLinearGradient(0, Ly.base - 70, 0, Ly.base + 30); + mg.addColorStop(0, 'rgba(255,236,226,0)'); mg.addColorStop(0.6, `rgba(255,232,222,${Ly.mist})`); mg.addColorStop(1, `rgba(255,236,226,${Ly.mist * 0.6})`); + ctx.fillStyle = mg; ctx.fillRect(0, Ly.base - 70, VIEW.w, 100); + }); + // a pine bough reaching in at the top + ctx.save(); + ctx.strokeStyle = '#120c08'; ctx.lineCap = 'round'; + ctx.lineWidth = 16; + ctx.beginPath(); ctx.moveTo(-10, 120); ctx.bezierCurveTo(80, 100, 150, 150, 260, 128); ctx.stroke(); + ctx.lineWidth = 8; + ctx.beginPath(); ctx.moveTo(150, 140); ctx.quadraticCurveTo(190, 180, 250, 190); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(60, 110); ctx.quadraticCurveTo(90, 70, 150, 60); ctx.stroke(); + const tuft = (x, y, s) => { + for (let i = 0; i < 26; i++) { + const a = -Math.PI + (i / 25) * Math.PI * 2, l = s * (0.6 + rnd() * 0.5); + ctx.strokeStyle = `rgba(${14 + rnd() * 10},${22 + rnd() * 14},${16},0.95)`; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(a) * l, y + Math.sin(a) * l * 0.55); ctx.stroke(); + } + }; + for (const [x, y, s] of [[260, 128, 44], [250, 190, 36], [150, 60, 40], [200, 132, 38], [100, 116, 34], [30, 112, 40]]) tuft(x, y, s); + if (seas === 'winter') { + ctx.fillStyle = 'rgba(250,248,255,0.85)'; + for (const [x, y, w] of [[240, 116, 40], [140, 52, 34], [60, 104, 30], [236, 180, 30]]) { ctx.beginPath(); ctx.ellipse(x, y, w, 7, -0.05, Math.PI, Math.PI * 2); ctx.fill(); } + } + ctx.restore(); + addCanvas(scene, 'go-ridges', c); +} + +// ── the room ───────────────────────────────────────────────────────────────── +function tatami(ctx, rnd, x0, y0, w, h) { + const MW = 620, MH = 310; + let row = 0; + for (let y = y0 - 80; y < y0 + h; y += MH, row++) { + for (let x = x0 - (row % 2 ? MW / 2 : 0) - 40; x < x0 + w; x += MW) { + const tone = rnd() * 0.08; + const g = ctx.createLinearGradient(x, y, x + MW, y + MH); + g.addColorStop(0, `rgb(${196 - tone * 200},${180 - tone * 160},${118 - tone * 80})`); + g.addColorStop(1, `rgb(${176 - tone * 200},${160 - tone * 160},${98 - tone * 80})`); + ctx.fillStyle = g; ctx.fillRect(x, y, MW, MH); + // the weave: fine lines along the mat, cross-stitches every few px + ctx.save(); ctx.beginPath(); ctx.rect(x, y, MW, MH); ctx.clip(); + for (let yy = y + 2; yy < y + MH; yy += 3) { + ctx.strokeStyle = `rgba(${90 + rnd() * 40},${80 + rnd() * 30},${30},${0.1 + rnd() * 0.12})`; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(x, yy); ctx.lineTo(x + MW, yy + (rnd() - 0.5)); ctx.stroke(); + } + ctx.fillStyle = 'rgba(80,70,30,0.10)'; + for (let xx = x + 18; xx < x + MW; xx += 36) ctx.fillRect(xx, y, 1.5, MH); + ctx.restore(); + // the cloth border (heri) along the long edges + ctx.fillStyle = '#1a2018'; ctx.fillRect(x, y, MW, 9); ctx.fillRect(x, y + MH - 9, MW, 9); + ctx.fillStyle = 'rgba(200,190,140,0.18)'; ctx.fillRect(x, y + 3, MW, 1); ctx.fillRect(x, y + MH - 6, MW, 1); + ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(x + MW - 1, y, 2, MH); + } + } + ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(x0, y0, w, h); +} + +function frameOpening(ctx, rnd) { + const { w } = VIEW; + // lintel + ctx.fillStyle = woodGrad(ctx, 0, 0, 0, 26, '#3a2414', '#1c1008'); ctx.fillRect(0, 0, w + 10, 26); + grain(ctx, rnd, 0, 0, w + 10, 26, { tone: 'rgba(0,0,0,0.3)', lines: 6, wave: 1 }); + // veranda boards at the foot + const vy = H - 46; + ctx.fillStyle = woodGrad(ctx, 0, vy, 0, H, '#5a3a20', '#2a180c'); ctx.fillRect(0, vy, w + 10, 46); + for (let x = 0; x < w; x += 54) { ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(x, vy, 2, 46); } + grain(ctx, rnd, 0, vy, w + 10, 46, { tone: 'rgba(0,0,0,0.25)', lines: 8, wave: 1, vertical: true }); + // a railing + ctx.fillStyle = '#1e120a'; + ctx.fillRect(0, vy - 56, w, 8); + for (let x = 20; x < w; x += 72) ctx.fillRect(x, vy - 56, 7, 56); + // the half-slid shoji panel at the right of the opening + const sx = w - 92, sw = 76; + ctx.fillStyle = 'rgba(250,236,214,0.86)'; ctx.fillRect(sx, 26, sw, vy - 26 - 56); + const lit = ctx.createLinearGradient(sx, 0, sx + sw, 0); + lit.addColorStop(0, 'rgba(255,200,150,0.25)'); lit.addColorStop(1, 'rgba(255,200,150,0)'); + ctx.fillStyle = lit; ctx.fillRect(sx, 26, sw, vy - 26 - 56); + ctx.strokeStyle = '#3a2414'; ctx.lineWidth = 4; ctx.strokeRect(sx, 26, sw, vy - 26 - 56); + ctx.lineWidth = 2; + for (let y = 26 + 58; y < vy - 56; y += 58) { ctx.beginPath(); ctx.moveTo(sx, y); ctx.lineTo(sx + sw, y); ctx.stroke(); } + ctx.beginPath(); ctx.moveTo(sx + sw / 2, 26); ctx.lineTo(sx + sw / 2, vy - 56); ctx.stroke(); + // the pillar between the view and the room + const px = w - 16; + shadowed(ctx, () => { ctx.fillStyle = woodGrad(ctx, px, 0, px + 26, 0, '#4a2e18', '#1e1208'); ctx.fillRect(px, 0, 26, H); }, { blur: 18, dx: 6, dy: 0, alpha: 0.6 }); + grain(ctx, rnd, px, 0, 26, H, { tone: 'rgba(0,0,0,0.3)', lines: 8, wave: 2, vertical: true }); + ctx.fillStyle = 'rgba(255,190,130,0.18)'; ctx.fillRect(px, 0, 2, H); +} + +function alcove(ctx, rnd, seas) { + const x0 = 1430; + // plaster wall + const wg = ctx.createLinearGradient(x0, 0, W, 0); + wg.addColorStop(0, '#cbb894'); wg.addColorStop(1, '#a89470'); + ctx.fillStyle = wg; ctx.fillRect(x0, 0, W - x0, H); + for (let i = 0; i < 2600; i++) { + const x = x0 + rnd() * (W - x0), y = rnd() * H; + ctx.fillStyle = `rgba(${rnd() < 0.5 ? '255,250,230' : '80,60,30'},${0.04 + rnd() * 0.06})`; ctx.fillRect(x, y, 1.5, 1.5); + } + // posts and the nageshi beam + for (const px of [x0, W - 14]) { + ctx.fillStyle = woodGrad(ctx, px, 0, px + 14, 0, '#4a2e18', '#22140a'); ctx.fillRect(px, 0, 14, H); + } + ctx.fillStyle = woodGrad(ctx, 0, ALCOVE.y - 18, 0, ALCOVE.y, '#4a2e18', '#22140a'); ctx.fillRect(x0, ALCOVE.y - 18, W - x0, 18); + // the alcove: a darker recess, a polished floor + const ay = ALCOVE.y; + ctx.fillStyle = 'rgba(40,24,12,0.35)'; ctx.fillRect(x0 + 14, ay, W - x0 - 28, H - ay); + const fy = 1010; + ctx.fillStyle = woodGrad(ctx, 0, fy, 0, H, '#3a2210', '#180c04'); ctx.fillRect(x0 + 14, fy, W - x0 - 28, H - fy); + ctx.fillStyle = 'rgba(255,210,160,0.2)'; ctx.fillRect(x0 + 14, fy, W - x0 - 28, 2); + grain(ctx, rnd, x0 + 14, fy, W - x0 - 28, H - fy, { tone: 'rgba(0,0,0,0.3)', lines: 6, wave: 1 }); + // incense burner: a bronze bowl on three feet + const ix = INCENSE.x, iy = INCENSE.y; + shadowed(ctx, () => { + const bg = ctx.createLinearGradient(ix - 40, 0, ix + 40, 0); + bg.addColorStop(0, '#3a2c18'); bg.addColorStop(0.4, '#8a6a34'); bg.addColorStop(0.7, '#5a4420'); bg.addColorStop(1, '#2a1e10'); + ctx.fillStyle = bg; + ctx.beginPath(); ctx.moveTo(ix - 40, iy - 8); ctx.quadraticCurveTo(ix - 42, iy + 34, ix, iy + 36); ctx.quadraticCurveTo(ix + 42, iy + 34, ix + 40, iy - 8); ctx.closePath(); ctx.fill(); + ctx.fillRect(ix - 30, iy + 30, 6, 16); ctx.fillRect(ix + 24, iy + 30, 6, 16); ctx.fillRect(ix - 3, iy + 34, 6, 14); + }, { blur: 10, dx: 4, dy: 6, alpha: 0.6 }); + ctx.fillStyle = '#6a5228'; ctx.beginPath(); ctx.ellipse(ix, iy - 8, 40, 9, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#d8ccb0'; ctx.beginPath(); ctx.ellipse(ix, iy - 7, 34, 6, 0, 0, Math.PI * 2); ctx.fill(); // ash + ctx.strokeStyle = '#3a2a14'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(ix + 2, iy - 7); ctx.lineTo(ix + 6, iy - 60); ctx.stroke(); // the stick + ctx.fillStyle = '#ff7a3a'; ctx.beginPath(); ctx.arc(ix + 6, iy - 61, 2.2, 0, Math.PI * 2); ctx.fill(); + // vase with the season's branch + const vx = VASE.x, vy = VASE.y; + shadowed(ctx, () => { + const vg = ctx.createLinearGradient(vx - 26, 0, vx + 26, 0); + vg.addColorStop(0, '#1e2a30'); vg.addColorStop(0.45, '#4a6670'); vg.addColorStop(1, '#16202a'); + ctx.fillStyle = vg; + ctx.beginPath(); ctx.moveTo(vx - 9, vy - 40); ctx.quadraticCurveTo(vx - 30, vy + 10, vx - 22, vy + 56); ctx.lineTo(vx + 22, vy + 56); ctx.quadraticCurveTo(vx + 30, vy + 10, vx + 9, vy - 40); ctx.closePath(); ctx.fill(); + }, { blur: 10, dx: 4, dy: 6, alpha: 0.6 }); + ctx.strokeStyle = '#2a1a0c'; ctx.lineCap = 'round'; ctx.lineWidth = 4; + ctx.beginPath(); ctx.moveTo(vx, vy - 38); ctx.bezierCurveTo(vx - 10, vy - 90, vx - 60, vy - 110, vx - 80, vy - 150); ctx.stroke(); + ctx.lineWidth = 3; + ctx.beginPath(); ctx.moveTo(vx - 4, vy - 70); ctx.bezierCurveTo(vx + 20, vy - 100, vx + 30, vy - 130, vx + 50, vy - 140); ctx.stroke(); + const bloom = { winter: '#c8283a', spring: '#f4b8c8', summer: '#5a8a3a', autumn: '#d8501e' }[seas]; + for (const [bx, by, r] of [[vx - 80, vy - 150, 8], [vx - 52, vy - 112, 7], [vx - 28, vy - 92, 6], [vx + 50, vy - 140, 7], [vx + 22, vy - 112, 6], [vx - 66, vy - 132, 5]]) { + ctx.fillStyle = bloom; + if (seas === 'summer') { ctx.beginPath(); ctx.ellipse(bx, by, r * 1.6, r * 0.7, -0.6, 0, Math.PI * 2); ctx.fill(); continue; } + for (let k = 0; k < 5; k++) { const a = k * Math.PI * 0.4; ctx.beginPath(); ctx.arc(bx + Math.cos(a) * r * 0.6, by + Math.sin(a) * r * 0.6, r * 0.6, 0, Math.PI * 2); ctx.fill(); } + ctx.fillStyle = seas === 'winter' ? '#f0d040' : '#fff2c0'; ctx.beginPath(); ctx.arc(bx, by, r * 0.3, 0, Math.PI * 2); ctx.fill(); + } +} + +function dawnLight(ctx) { + // light from the opening, warm on the mats near it, the far side dimmer + const g = ctx.createLinearGradient(VIEW.w, 0, W, 0); + g.addColorStop(0, 'rgba(255,190,120,0.16)'); g.addColorStop(0.4, 'rgba(255,170,110,0.04)'); g.addColorStop(1, 'rgba(10,6,4,0.32)'); + ctx.fillStyle = g; ctx.fillRect(VIEW.w, 0, W - VIEW.w, H); + const v = ctx.createRadialGradient(BCX, BCY, 300, BCX, BCY, 1200); + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(0,0,0,0.42)'); + ctx.fillStyle = v; ctx.fillRect(0, 0, W, H); +} + +function bakeRoom(scene, seas) { + { + const c = canvas(W, H), ctx = c.getContext('2d'), rnd = seeded(1222); + tatami(ctx, rnd, 0, 0, W, H); + alcove(ctx, rnd, seas); + dawnLight(ctx); + ctx.clearRect(0, 0, VIEW.w, H); + frameOpening(ctx, rnd); + addCanvas(scene, 'go-room', c); + } + { + const c = canvas(W, H), ctx = c.getContext('2d'), rnd = seeded(1222); + ctx.save(); ctx.beginPath(); ctx.rect(ALCOVE.x, ALCOVE.y, ALCOVE.w, ALCOVE.h); ctx.clip(); + alcove(ctx, rnd, seas); + ctx.restore(); + addCanvas(scene, 'go-props', c); + } + { + const c = canvas(W, H), ctx = c.getContext('2d'); + const v = ctx.createRadialGradient(BCX, BCY, 300, BCX, BCY, 1200); + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(0,0,0,0.5)'); + ctx.fillStyle = v; ctx.fillRect(0, 0, W, H); + addCanvas(scene, 'go-vignette', c); + } +} + +// ── the board ──────────────────────────────────────────────────────────────── +export function ensureBoard(scene, size) { + const key = `go-board-${size}`; + if (scene.textures.exists(key)) return key; + const o = PAD, S = BOARD, c = canvas(S + o * 2, S + FACE + o * 2), ctx = c.getContext('2d'), rnd = seeded(300 + size); + // shadow on the mats + shadowed(ctx, () => { ctx.fillStyle = '#2a180a'; ctx.fillRect(o, o, S, S + FACE); }, { blur: 26, dx: 10, dy: 16, alpha: 0.7 }); + // the front edge of the slab + const fg = ctx.createLinearGradient(0, o + S, 0, o + S + FACE); + fg.addColorStop(0, '#b47a36'); fg.addColorStop(1, '#7a4c1e'); + ctx.fillStyle = fg; ctx.fillRect(o, o + S, S, FACE); + grain(ctx, rnd, o, o + S, S, FACE, { tone: 'rgba(60,30,8,0.35)', lines: 12, wave: 1 }); + ctx.fillStyle = 'rgba(255,230,180,0.25)'; ctx.fillRect(o, o + S, S, 1.5); + // the top: kaya, straight grain running away from you + const tg = ctx.createLinearGradient(o, o, o + S, o + S); + tg.addColorStop(0, '#f0c47a'); tg.addColorStop(0.5, '#e6b468'); tg.addColorStop(1, '#d8a458'); + ctx.fillStyle = tg; ctx.fillRect(o, o, S, S); + grain(ctx, rnd, o, o, S, S, { tone: 'rgba(150,92,30,0.20)', lines: 150, wave: 3, vertical: true, width: [0.4, 1.4] }); + grain(ctx, rnd, o, o, S, S, { tone: 'rgba(255,236,190,0.16)', lines: 60, wave: 3, vertical: true, width: [0.6, 2.2] }); + grain(ctx, rnd, o, o, S, S, { tone: 'rgba(120,70,20,0.10)', lines: 14, wave: 6, vertical: true, width: [3, 7] }); + // a soft sheen, and the corners a touch darker with handling + const sh = ctx.createLinearGradient(o, o, o + S, o + S); + sh.addColorStop(0, 'rgba(255,245,220,0.12)'); sh.addColorStop(0.35, 'rgba(255,245,220,0)'); sh.addColorStop(1, 'rgba(60,30,0,0.10)'); + ctx.fillStyle = sh; ctx.fillRect(o, o, S, S); + ctx.fillStyle = noisePattern(ctx, 96, 12); ctx.fillRect(o, o, S, S); + ctx.strokeStyle = 'rgba(90,50,14,0.5)'; ctx.lineWidth = 2; ctx.strokeRect(o + 1, o + 1, S - 2, S - 2); + // ink lines + const g = geom(size); + const lx = (i) => o + (g.x0 - BX) + i * g.SQ, ly = (i) => o + (g.y0 - BY) + i * g.SQ; + const lw = size === 9 ? 2.1 : size === 13 ? 1.8 : 1.4; + ctx.strokeStyle = 'rgba(26,16,8,0.88)'; ctx.lineWidth = lw; ctx.lineCap = 'square'; + for (let i = 0; i < size; i++) { + ctx.beginPath(); ctx.moveTo(lx(i), ly(0)); ctx.lineTo(lx(i), ly(size - 1)); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(lx(0), ly(i)); ctx.lineTo(lx(size - 1), ly(i)); ctx.stroke(); + } + ctx.lineWidth = lw * 1.7; + ctx.strokeRect(lx(0), ly(0), g.span, g.span); + const hr = size === 9 ? 6.5 : size === 13 ? 5.2 : 4.4; + ctx.fillStyle = 'rgba(26,16,8,0.92)'; + for (const sq of starPoints(size)) { + const r = Math.floor(sq / size), cc = sq % size; + ctx.beginPath(); ctx.arc(lx(cc), ly(r), hr, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, key, c); + return key; +} + +// ── stones ─────────────────────────────────────────────────────────────────── +function bakeStones(scene) { + const S = STONE_TEX, R = STONE_R * RES, cx = S / 2; + { + const c = canvas(S, S), ctx = c.getContext('2d'); + // slate: matte, very slightly blue, a dome's soft highlight + const g = ctx.createRadialGradient(cx - R * 0.35, cx - R * 0.4, R * 0.05, cx, cx, R); + g.addColorStop(0, '#4a4a52'); g.addColorStop(0.35, '#23232a'); g.addColorStop(0.8, '#121216'); g.addColorStop(1, '#060608'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cx, R, 0, Math.PI * 2); ctx.fill(); + ctx.save(); ctx.beginPath(); ctx.arc(cx, cx, R, 0, Math.PI * 2); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 10); ctx.fillRect(0, 0, S, S); + const hl = ctx.createRadialGradient(cx - R * 0.38, cx - R * 0.42, 0, cx - R * 0.38, cx - R * 0.42, R * 0.5); + hl.addColorStop(0, 'rgba(230,235,255,0.30)'); hl.addColorStop(1, 'rgba(230,235,255,0)'); + ctx.fillStyle = hl; ctx.fillRect(0, 0, S, S); + const bounce = ctx.createRadialGradient(cx + R * 0.5, cx + R * 0.55, 0, cx + R * 0.5, cx + R * 0.55, R * 0.6); + bounce.addColorStop(0, 'rgba(255,210,150,0.10)'); bounce.addColorStop(1, 'rgba(255,210,150,0)'); + ctx.fillStyle = bounce; ctx.fillRect(0, 0, S, S); + ctx.restore(); + addCanvas(scene, 'go-black', c); + } + for (let v = 0; v < WHITE_VARIANTS; v++) { + const c = canvas(S, S), ctx = c.getContext('2d'), rnd = seeded(77 + v * 13); + const warm = (rnd() - 0.5) * 8; + const g = ctx.createRadialGradient(cx - R * 0.35, cx - R * 0.4, R * 0.05, cx, cx, R); + g.addColorStop(0, '#ffffff'); g.addColorStop(0.5, `rgb(${246 + warm},${243},${234 - warm})`); g.addColorStop(0.88, `rgb(${226 + warm},${221},${208 - warm})`); g.addColorStop(1, '#b8b0a0'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cx, R, 0, Math.PI * 2); ctx.fill(); + ctx.save(); ctx.beginPath(); ctx.arc(cx, cx, R * 0.985, 0, Math.PI * 2); ctx.clip(); + // clamshell striations: fine parallel arcs, a little irregular + const curve = R * (3 + rnd() * 3); + const ox = cx + (rnd() - 0.5) * R * 0.4, oy = cx + curve; + for (let k = -R * 1.2; k < R * 1.2; k += 2.4 + rnd() * 3.2) { + ctx.strokeStyle = `rgba(${170 + rnd() * 30},${165 + rnd() * 25},${150 + rnd() * 20},${0.10 + rnd() * 0.14})`; + ctx.lineWidth = 0.6 + rnd() * 1.1; + ctx.beginPath(); ctx.arc(ox, oy, curve + k, Math.PI * 1.25, Math.PI * 1.75); ctx.stroke(); + } + const hl = ctx.createRadialGradient(cx - R * 0.36, cx - R * 0.42, 0, cx - R * 0.36, cx - R * 0.42, R * 0.55); + hl.addColorStop(0, 'rgba(255,255,255,0.75)'); hl.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = hl; ctx.fillRect(0, 0, S, S); + const edge = ctx.createRadialGradient(cx, cx, R * 0.75, cx, cx, R); + edge.addColorStop(0, 'rgba(120,110,90,0)'); edge.addColorStop(1, 'rgba(120,110,90,0.22)'); + ctx.fillStyle = edge; ctx.fillRect(0, 0, S, S); + ctx.restore(); + addCanvas(scene, `go-white-${v}`, c); + } + { + const c = canvas(S, S), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(cx, cx, R * 0.5, cx, cx, R * 1.12); + g.addColorStop(0, 'rgba(20,10,0,0.55)'); g.addColorStop(0.7, 'rgba(20,10,0,0.3)'); g.addColorStop(1, 'rgba(20,10,0,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, S, S); + addCanvas(scene, 'go-shadow', c); + } +} + +// ── bowls and lids ─────────────────────────────────────────────────────────── +function bakeBowls(scene) { + const { r } = BOWLS.top.bowl; + const S = (r + 14) * 2, cx = S / 2; + for (const col of ['black', 'white']) { + const c = canvas(S, S), ctx = c.getContext('2d'), rnd = seeded(col === 'black' ? 5 : 6); + shadowed(ctx, () => { ctx.fillStyle = '#3a2410'; ctx.beginPath(); ctx.arc(cx, cx, r, 0, Math.PI * 2); ctx.fill(); }, { blur: 14, dx: 5, dy: 8, alpha: 0.6 }); + // mulberry: warm gold with rings + const wg = ctx.createRadialGradient(cx - r * 0.3, cx - r * 0.3, r * 0.2, cx, cx, r); + wg.addColorStop(0, '#d8a050'); wg.addColorStop(0.7, '#a86c2a'); wg.addColorStop(1, '#6a3e14'); + ctx.fillStyle = wg; ctx.beginPath(); ctx.arc(cx, cx, r, 0, Math.PI * 2); ctx.fill(); + for (let k = 0; k < 9; k++) { + ctx.strokeStyle = `rgba(90,46,10,${0.12 + rnd() * 0.12})`; ctx.lineWidth = 1 + rnd(); + ctx.beginPath(); ctx.ellipse(cx + (rnd() - 0.5) * 8, cx + (rnd() - 0.5) * 8, r * (0.72 + k * 0.03), r * (0.7 + k * 0.03), rnd(), 0, Math.PI * 2); ctx.stroke(); + } + // the opening, and the stones heaped inside + const ir = r * 0.7; + ctx.fillStyle = '#1a0e06'; ctx.beginPath(); ctx.arc(cx, cx, ir, 0, Math.PI * 2); ctx.fill(); + ctx.save(); ctx.beginPath(); ctx.arc(cx, cx, ir - 1, 0, Math.PI * 2); ctx.clip(); + const sr = 12; + for (let i = 0; i < 70; i++) { + const a = rnd() * Math.PI * 2, d = Math.sqrt(rnd()) * ir; + const x = cx + Math.cos(a) * d, y = cx + Math.sin(a) * d; + const dim = 1 - (d / ir) * 0.45; + if (col === 'black') { + const g = ctx.createRadialGradient(x - sr * 0.3, y - sr * 0.35, 1, x, y, sr); + g.addColorStop(0, `rgba(${80 * dim},${80 * dim},${90 * dim},1)`); g.addColorStop(1, `rgba(${10},${10},${12},1)`); + ctx.fillStyle = g; + } else { + const g = ctx.createRadialGradient(x - sr * 0.3, y - sr * 0.35, 1, x, y, sr); + g.addColorStop(0, `rgba(${255 * dim},${255 * dim},${250 * dim},1)`); g.addColorStop(1, `rgba(${200 * dim},${192 * dim},${178 * dim},1)`); + ctx.fillStyle = g; + } + ctx.beginPath(); ctx.ellipse(x, y, sr, sr * 0.92, rnd() * 3, 0, Math.PI * 2); ctx.fill(); + } + const inner = ctx.createRadialGradient(cx, cx, ir * 0.6, cx, cx, ir); + inner.addColorStop(0, 'rgba(0,0,0,0)'); inner.addColorStop(1, 'rgba(0,0,0,0.5)'); + ctx.fillStyle = inner; ctx.fillRect(0, 0, S, S); + ctx.restore(); + ctx.strokeStyle = 'rgba(255,220,160,0.4)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(cx, cx, ir + 1, Math.PI * 0.9, Math.PI * 1.6); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,220,160,0.3)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(cx, cx, r - 2, Math.PI * 1.0, Math.PI * 1.6); ctx.stroke(); + addCanvas(scene, `go-bowl-${col}`, c); + } + { + const lr = BOWLS.top.lid.r, LS = (lr + 14) * 2, lc = LS / 2; + const c = canvas(LS, LS), ctx = c.getContext('2d'), rnd = seeded(8); + shadowed(ctx, () => { ctx.fillStyle = '#3a2410'; ctx.beginPath(); ctx.arc(lc, lc, lr, 0, Math.PI * 2); ctx.fill(); }, { blur: 12, dx: 4, dy: 6, alpha: 0.55 }); + const wg = ctx.createRadialGradient(lc + lr * 0.1, lc + lr * 0.15, lr * 0.1, lc, lc, lr); + wg.addColorStop(0, '#c48a44'); wg.addColorStop(0.75, '#8a5420'); wg.addColorStop(0.9, '#c08a48'); wg.addColorStop(1, '#5a3410'); + ctx.fillStyle = wg; ctx.beginPath(); ctx.arc(lc, lc, lr, 0, Math.PI * 2); ctx.fill(); + for (let k = 0; k < 7; k++) { + ctx.strokeStyle = `rgba(80,40,10,${0.1 + rnd() * 0.12})`; ctx.lineWidth = 1; + ctx.beginPath(); ctx.ellipse(lc, lc, lr * (0.2 + k * 0.1), lr * (0.18 + k * 0.1), 0.3, 0, Math.PI * 2); ctx.stroke(); + } + ctx.strokeStyle = 'rgba(40,20,4,0.5)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(lc, lc, lr * 0.86, 0, Math.PI * 2); ctx.stroke(); + addCanvas(scene, 'go-lid', c); + } +} + +// ── HUD furniture ──────────────────────────────────────────────────────────── +function asanoha(ctx, x, y, w, h, s, color) { + // the hemp-leaf pattern, faintly + ctx.save(); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); + ctx.strokeStyle = color; ctx.lineWidth = 1; + const hh = s * Math.sqrt(3) / 2; + for (let row = -1; row * hh < h + hh; row++) { + for (let col = -1; col * s < w + s; col++) { + const cx = x + col * s + (row % 2 ? s / 2 : 0), cy = y + row * hh; + const pts = [[cx, cy], [cx + s, cy], [cx + s / 2, cy + hh]]; + const mx = (pts[0][0] + pts[1][0] + pts[2][0]) / 3, my = (pts[0][1] + pts[1][1] + pts[2][1]) / 3; + ctx.beginPath(); + for (const [px, py] of pts) { ctx.moveTo(mx, my); ctx.lineTo(px, py); } + ctx.moveTo(pts[0][0], pts[0][1]); ctx.lineTo(pts[1][0], pts[1][1]); ctx.lineTo(pts[2][0], pts[2][1]); ctx.closePath(); + ctx.stroke(); + } + } + ctx.restore(); +} + +function bakePlate(scene) { + const { w, h } = PLATE, pad = 14, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(31); + shadowed(ctx, () => { ctx.fillStyle = '#1a0e06'; rr(ctx, pad, pad, w, h, 12); ctx.fill(); }, { blur: 16, dx: 4, dy: 9, alpha: 0.6 }); + ctx.fillStyle = woodGrad(ctx, pad, pad, pad, pad + h, '#3c2414', '#1e1008'); rr(ctx, pad, pad, w, h, 12); ctx.fill(); + grain(ctx, rnd, pad, pad, w, h, { tone: 'rgba(0,0,0,0.25)', lines: 18, wave: 2 }); + ctx.fillStyle = '#1b2130'; rr(ctx, pad + 9, pad + 9, w - 18, h - 18, 8); ctx.fill(); + asanoha(ctx, pad + 9, pad + 9, w - 18, h - 18, 34, 'rgba(216,176,96,0.07)'); + const sheen = ctx.createLinearGradient(0, pad, 0, pad + h); + sheen.addColorStop(0, 'rgba(255,255,255,0.05)'); sheen.addColorStop(1, 'rgba(0,0,0,0.2)'); + ctx.fillStyle = sheen; rr(ctx, pad + 9, pad + 9, w - 18, h - 18, 8); ctx.fill(); + ctx.strokeStyle = goldGrad(ctx, pad, pad, pad + w, pad + h); ctx.lineWidth = 1.6; rr(ctx, pad + 13, pad + 13, w - 26, h - 26, 6); ctx.stroke(); + addCanvas(scene, 'go-plate', c); + const gc = canvas(w + 80, h + 80), g = gc.getContext('2d'); + g.shadowColor = 'rgba(255,200,110,0.95)'; g.shadowBlur = 30; + g.strokeStyle = 'rgba(255,210,130,0.9)'; g.lineWidth = 6; rr(g, 40, 40, w, h, 12); g.stroke(); + addCanvas(scene, 'go-plate-glow', gc); +} + +function seal(ctx, x, y, s) { + // a vermilion hanko: a square seal with abstract carved strokes + ctx.save(); + ctx.translate(x, y); ctx.rotate(-0.05); + ctx.fillStyle = 'rgba(184,58,36,0.88)'; rr(ctx, -s / 2, -s / 2, s, s, 3); ctx.fill(); + ctx.strokeStyle = 'rgba(250,236,214,0.9)'; ctx.lineWidth = s * 0.07; ctx.lineCap = 'round'; + ctx.strokeRect(-s * 0.36, -s * 0.36, s * 0.72, s * 0.72); + ctx.beginPath(); + ctx.moveTo(-s * 0.2, -s * 0.22); ctx.lineTo(s * 0.2, -s * 0.22); + ctx.moveTo(0, -s * 0.22); ctx.lineTo(0, s * 0.24); + ctx.moveTo(-s * 0.22, s * 0.02); ctx.lineTo(s * 0.22, s * 0.02); + ctx.moveTo(-s * 0.16, s * 0.16); ctx.lineTo(-s * 0.04, s * 0.24); + ctx.moveTo(s * 0.16, s * 0.16); ctx.lineTo(s * 0.04, s * 0.24); + ctx.stroke(); + ctx.restore(); +} + +function bakeCard(scene, key, w, h, { ruled = false, withSeal = false } = {}) { + const pad = 14, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(key.length * 7); + shadowed(ctx, () => { ctx.fillStyle = '#1a0e06'; rr(ctx, pad, pad, w, h, 8); ctx.fill(); }, { blur: 16, dx: 4, dy: 9, alpha: 0.55 }); + ctx.fillStyle = woodGrad(ctx, pad, pad, pad, pad + h, '#4a2c16', '#24140a'); rr(ctx, pad, pad, w, h, 8); ctx.fill(); + // washi + const ix = pad + 10, iy = pad + 10, iw = w - 20, ih = h - 20; + const pg = ctx.createLinearGradient(ix, iy, ix, iy + ih); + pg.addColorStop(0, '#f6eedc'); pg.addColorStop(1, '#ebdfc4'); + ctx.fillStyle = pg; ctx.fillRect(ix, iy, iw, ih); + ctx.save(); ctx.beginPath(); ctx.rect(ix, iy, iw, ih); ctx.clip(); + for (let i = 0; i < 260; i++) { + const x = ix + rnd() * iw, y = iy + rnd() * ih, a = rnd() * Math.PI, l = 4 + rnd() * 18; + ctx.strokeStyle = `rgba(160,130,80,${0.06 + rnd() * 0.08})`; ctx.lineWidth = 0.6; + ctx.beginPath(); ctx.moveTo(x, y); ctx.quadraticCurveTo(x + Math.cos(a) * l * 0.5 + 3, y + Math.sin(a) * l * 0.5, x + Math.cos(a) * l, y + Math.sin(a) * l); ctx.stroke(); + } + if (ruled) { + ctx.strokeStyle = 'rgba(120,80,40,0.16)'; ctx.lineWidth = 1; + for (let y = iy + 92; y < iy + ih - 50; y += 28) { ctx.beginPath(); ctx.moveTo(ix + 12, y); ctx.lineTo(ix + iw - 12, y); ctx.stroke(); } + ctx.strokeStyle = 'rgba(184,58,36,0.25)'; + const colX = ix + 54; + ctx.beginPath(); ctx.moveTo(colX, iy + 56); ctx.lineTo(colX, iy + ih - 54); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(colX + (iw - 54) / 2, iy + 56); ctx.lineTo(colX + (iw - 54) / 2, iy + ih - 54); ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 64, 10); ctx.fillRect(ix, iy, iw, ih); + ctx.restore(); + ctx.fillStyle = 'rgba(184,58,36,0.9)'; ctx.fillRect(ix, iy, iw, 4); + if (withSeal) seal(ctx, ix + iw - 30, iy + 32, 30); + 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'), rnd = seeded(41); + shadowed(ctx, () => { ctx.fillStyle = '#0a0604'; rr(ctx, pad, pad, w, h, 10); ctx.fill(); }, { blur: 14, dx: 3, dy: 7, alpha: 0.6 }); + ctx.fillStyle = woodGrad(ctx, pad, pad, pad, pad + h, '#3a2214', '#1a0e06'); rr(ctx, pad, pad, w, h, 10); ctx.fill(); + grain(ctx, rnd, pad, pad, w, h, { tone: 'rgba(0,0,0,0.3)', lines: 10, wave: 1 }); + 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(); + // Hōun's badge: an ensō on a paper disc + const bx = pad + 40, by = pad + h / 2; + ctx.fillStyle = '#efe4c8'; ctx.beginPath(); ctx.arc(bx, by, 24, 0, Math.PI * 2); ctx.fill(); + enso(ctx, bx, by, 15, { rnd: seeded(9) }); + addCanvas(scene, 'go-ribbon', 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 = '#0a0604'; 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, 'go-bar', c); +} + +// ── bits ───────────────────────────────────────────────────────────────────── +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('go-glow', 128, [[0, 'rgba(255,226,150,0.9)'], [0.45, 'rgba(255,200,100,0.4)'], [1, 'rgba(255,190,90,0)']]); + radial('go-spark', 24, [[0, 'rgba(255,255,255,1)'], [0.35, 'rgba(255,240,200,0.8)'], [1, 'rgba(255,220,150,0)']]); + radial('go-smoke', 64, [[0, 'rgba(240,236,230,0.5)'], [1, 'rgba(240,236,230,0)']]); + radial('go-sun', 220, [[0, 'rgba(255,250,230,1)'], [0.12, 'rgba(255,240,200,1)'], [0.16, 'rgba(255,214,150,0.65)'], [0.4, 'rgba(255,170,110,0.22)'], [1, 'rgba(255,150,100,0)']]); + { + const c = canvas(300, 70), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(150, 35, 4, 150, 35, 150); + g.addColorStop(0, 'rgba(255,240,232,0.55)'); g.addColorStop(1, 'rgba(255,240,232,0)'); + ctx.save(); ctx.scale(1, 70 / 300); ctx.fillStyle = g; ctx.fillRect(0, 0, 300, 300); ctx.restore(); + addCanvas(scene, 'go-mist', 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, 'go-ring', c); + } + { + const c = canvas(22, 12), ctx = c.getContext('2d'); + ctx.strokeStyle = 'rgba(20,16,24,0.9)'; ctx.lineWidth = 2; ctx.lineCap = 'round'; + ctx.beginPath(); ctx.moveTo(1, 4); ctx.quadraticCurveTo(6, 0, 11, 6); ctx.quadraticCurveTo(16, 0, 21, 4); ctx.stroke(); + addCanvas(scene, 'go-bird', c); + } + { + // season particles + let c = canvas(16, 16), ctx = c.getContext('2d'); + let g = ctx.createRadialGradient(8, 8, 0, 8, 8, 8); + g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.5, 'rgba(250,250,255,0.7)'); g.addColorStop(1, 'rgba(240,240,255,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, 16, 16); + addCanvas(scene, 'go-p-winter', c); + c = canvas(18, 14); ctx = c.getContext('2d'); + ctx.fillStyle = '#f6c2d0'; + ctx.beginPath(); ctx.moveTo(1, 7); ctx.quadraticCurveTo(6, 0, 15, 3); ctx.lineTo(17, 7); ctx.lineTo(15, 11); ctx.quadraticCurveTo(6, 14, 1, 7); ctx.fill(); + ctx.fillStyle = 'rgba(255,255,255,0.5)'; ctx.beginPath(); ctx.ellipse(7, 6, 4, 1.5, -0.2, 0, Math.PI * 2); ctx.fill(); + addCanvas(scene, 'go-p-spring', c); + c = canvas(20, 12); ctx = c.getContext('2d'); + ctx.fillStyle = '#6a9a3e'; + ctx.beginPath(); ctx.moveTo(1, 6); ctx.quadraticCurveTo(10, -2, 19, 6); ctx.quadraticCurveTo(10, 14, 1, 6); ctx.fill(); + ctx.strokeStyle = 'rgba(30,60,10,0.6)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(2, 6); ctx.lineTo(18, 6); ctx.stroke(); + addCanvas(scene, 'go-p-summer', c); + c = canvas(22, 22); ctx = c.getContext('2d'); + ctx.fillStyle = '#d4481c'; + ctx.translate(11, 12); + ctx.beginPath(); + for (let k = 0; k < 5; k++) { + const a = -Math.PI / 2 + (k - 2) * 0.62; + ctx.lineTo(Math.cos(a) * 10, Math.sin(a) * 10); + ctx.lineTo(Math.cos(a + 0.31) * 4, Math.sin(a + 0.31) * 4); + } + ctx.closePath(); ctx.fill(); + ctx.strokeStyle = '#8a2a0a'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(0, 9); ctx.stroke(); + addCanvas(scene, 'go-p-autumn', c); + } + { + const c = canvas(32, 32), ctx = c.getContext('2d'); + ctx.fillStyle = '#ffffff'; rr(ctx, 4, 4, 24, 24, 4); ctx.fill(); + addCanvas(scene, 'go-terr', c); + } + { + const c = canvas(48, 48), ctx = c.getContext('2d'); + ctx.strokeStyle = '#ffffff'; ctx.lineWidth = 6; ctx.lineCap = 'round'; + ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(38, 38); ctx.moveTo(38, 10); ctx.lineTo(10, 38); ctx.stroke(); + addCanvas(scene, 'go-x', c); + } +} + +let bakedFor = null; +export async function prepareGoArt(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 */ } + const seas = season(); + if (bakedFor !== seas || !scene.textures.exists('go-room')) { + bakeSky(scene); bakeRidges(scene, seas); bakeRoom(scene, seas); + bakeStones(scene); bakeBowls(scene); bakePlate(scene); + bakeCard(scene, 'go-card-status', STATUS.w, STATUS.h, { withSeal: true }); + bakeCard(scene, 'go-card-record', RECORD.w, RECORD.h, { ruled: true }); + bakeRibbon(scene); bakeBar(scene); bakeBits(scene); + bakedFor = seas; + } + return seas; +} diff --git a/src/games/go/GoDialogs.js b/src/games/go/GoDialogs.js new file mode 100644 index 0000000..c5b75a6 --- /dev/null +++ b/src/games/go/GoDialogs.js @@ -0,0 +1,183 @@ +// GoDialogs.js: the temple's pop-ups: washi paper in a dark wooden frame +// with a vermilion rule and a seal. 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 './GoArt.js'; +import { SIZE_INFO, SIZES, RULES, RULE_ORDER, KOMI_CHOICES, defaultKomi, MAX_HANDICAP } from './GoLogic.js'; + +const INK = '#2a1810'; +const BTN_BG = 0x3a2416; + +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, 12); + g.fillStyle(0x2a1a0e, 1).fillRoundedRect(x, y, w, h, 12); + g.lineStyle(2, 0x5a3a20, 1).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 10); + g.fillStyle(0xf4ecd8, 1).fillRoundedRect(x + 14, y + 14, w - 28, h - 28, 4); + g.fillStyle(0xb83a24, 1).fillRect(x + 14, y + 14, w - 28, 6); + g.lineStyle(1.5, 0xa08050, 0.45).strokeRoundedRect(x + 26, y + 32, w - 52, h - 58, 3); + // the seal + const sx = x + w - 62, sy = y + 40; + g.fillStyle(0xb83a24, 0.9).fillRoundedRect(sx, sy, 30, 30, 3); + g.lineStyle(2, 0xf4ecd8, 0.9).strokeRect(sx + 5, sy + 5, 20, 20); + g.lineBetween(sx + 10, sy + 11, sx + 20, sy + 11); + g.lineBetween(sx + 15, sy + 11, sx + 15, sy + 22); + g.lineBetween(sx + 9, sy + 17, sx + 21, sy + 17); + 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, puzzle = false, onChange, onRules, onSave, onOpen, onPuzzles, onNewMatch, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.55)]; + const w = 640, h = 960; + 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 + 64, 'Unkai-ji', { 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)], + [() => `Coordinates on the board: ${onOff(settings.coords)}`, () => onChange('coords', !settings.coords)], + [() => `Move numbers on the stones: ${onOff(settings.numbers)}`, () => onChange('numbers', !settings.numbers)], + [() => `Hover: captures and liberties: ${onOff(settings.preview)}`, () => onChange('preview', !settings.preview)], + [() => `Hōun warns of atari and bad moves: ${onOff(settings.coach)}`, () => onChange('coach', !settings.coach)], + [() => `Study: territory and score estimate: ${onOff(settings.territory)}`, () => onChange('territory', !settings.territory)], + [() => `Wind, birds and the bell: ${onOff(settings.ambience)}`, () => onChange('ambience', !settings.ambience)], + ['How to Play', () => onRules()], + ...(puzzle ? [] : [['Save this game as SGF', () => onSave()]]), + ['Open a game record (SGF)…', () => { hRef.close(); onOpen(); }], + [puzzle ? 'Back to the board' : 'Hōun\'s problems', () => { hRef.close(); onPuzzles(); }, 0x2a5a3a], + ['New Match…', () => { hRef.close(); onNewMatch(); }, 0x6a4a1a], + ['Leave the Temple', () => { hRef.close(); onLeave(); }, 0x7a1a14], + ]; + rows.forEach(([label, fn, bg], i) => { + const text = typeof label === 'function' ? label() : label; + const btn = new Button(scene, cx, y + 120 + i * 51, text, () => { fn(); if (typeof label === 'function') btn.setLabel(label()); }, { + width: 560, height: 42, fontSize: 16, bg: bg ?? BTN_BG, + }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(scene.add.text(cx, y + h - 48, 'Click a point to play · P pass · Z undo · H hint · T territory · N numbers\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; +} + +const CLOCKS = { + off: { name: 'No clock', blurb: '' }, + relaxed: { name: 'Byo-yomi: 60 s × 5', blurb: 'You have sixty seconds a move; run over and you spend one of five periods. Lose them all and you lose on time.' }, + brisk: { name: 'Byo-yomi: 30 s × 3', blurb: 'Thirty seconds a move, three periods to spare.' }, +}; +export const CLOCK_SPEC = { off: null, relaxed: { secs: 60, periods: 5 }, brisk: { secs: 30, periods: 3 } }; + +/** The match setup card. prefs = { size, color, handicap, komi ('auto' | number), rules, games, clock }. */ +export function openSetup(scene, { prefs, depth, opponentName, puzzleInfo, onStart, onPuzzles, onDaily, onOpen, onLeave }) { + const objs = [blocker(scene, depth - 1, 0.6)]; + const w = 900, h = 940; + 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 Morning Game', { fontFamily: DISPLAY_FONT, fontSize: '34px', color: INK }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(cx, y + 110, `You against ${opponentName}. Hōun keeps the count.`, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#5a4a32' }).setOrigin(0.5).setDepth(depth + 1)); + + const labelX = x + 80, ctlX = x + 590; + const rowY = (i) => y + 168 + i * 70; + 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: 420, 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 maxH = (s) => (s === 9 ? 5 : MAX_HANDICAP); + const hcaps = (s) => [0, ...Array.from({ length: maxH(s) - 1 }, (_, i) => i + 2)]; + addRow(0, 'Board', () => SIZE_INFO[p.size].long, () => { p.size = cyc(SIZES, p.size); if (p.handicap > maxH(p.size)) p.handicap = 0; }); + addRow(1, 'Your colour', () => (p.color === 'random' ? 'Nigiri (draw lots)' : p.color === 'black' ? 'Black (moves first)' : 'White (receives komi)'), + () => { p.color = cyc(['black', 'white', 'random'], p.color); }); + addRow(2, 'Handicap', () => (p.handicap ? `${p.handicap} stones for Black` : 'Even game'), () => { p.handicap = cyc(hcaps(p.size), p.handicap); }); + addRow(3, 'Komi', () => (p.komi === 'auto' ? `Usual (${defaultKomi(p.rules, p.handicap)})` : `${p.komi} points`), () => { p.komi = cyc(['auto', ...KOMI_CHOICES], p.komi); }); + addRow(4, 'Rules', () => `${RULES[p.rules].name} (${RULES[p.rules].short.toLowerCase()} scoring)`, () => { p.rules = cyc(RULE_ORDER, p.rules); }); + addRow(5, 'Match', () => (p.games === 1 ? 'Single game' : `Best of ${p.games}`), () => { p.games = cyc([1, 3, 5], p.games); }); + addRow(6, 'Clock', () => CLOCKS[p.clock].name, () => { p.clock = cyc(['off', 'relaxed', 'brisk'], p.clock); }); + + const blurb = scene.add.text(cx, y + 680, '', { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 140 }, lineSpacing: 3 }) + .setOrigin(0.5).setDepth(depth + 1); + objs.push(blurb); + function refresh() { + rows.forEach((r) => r.btn.setLabel(r.get())); + let b = `${SIZE_INFO[p.size].blurb} ${RULES[p.rules].blurb}`; + if (p.handicap) b += ` Black starts with ${p.handicap} stones and White moves first.`; + if (p.games > 1) b += p.handicap ? ' With a handicap, you keep your colour every game.' : ' Colours swap every game.'; + if (p.clock !== 'off') b += ` ${CLOCKS[p.clock].blurb}`; + blurb.setText(b); + } + refresh(); + let hRef = null; + const by = y + h - 150; + objs.push(new Button(scene, cx, by, 'Sit Down and Bow', () => { + hRef.close(); + onStart({ ...p }); + }, { width: 380, height: 54, fontSize: 21, bg: 0x1f6a3a }).setDepth(depth + 2)); + const by2 = y + h - 76; + const bw = 178, gap = 14, x0 = cx - (bw * 4 + gap * 3) / 2 + bw / 2; + [ + ['Hōun\'s Problems', 0x2a4a6a, () => { hRef.close(); onPuzzles(); }], + [puzzleInfo?.dailyDone ? 'Daily ✓' : 'Daily Problem', 0x7a5a1a, () => { hRef.close(); onDaily(); }], + ['Open SGF…', 0x3a3a3a, () => { hRef.close(); onOpen(); }], + ['Leave', 0x7a1a14, () => { hRef.close(); onLeave(); }], + ].forEach(([label, bg, fn], i) => { + objs.push(new Button(scene, x0 + i * (bw + gap), by2, label, fn, { width: bw, height: 46, fontSize: 16, bg }).setDepth(depth + 2)); + }); + if (puzzleInfo) { + objs.push(scene.add.text(cx, by2 + 38, `Problems: rating ${puzzleInfo.rating} · ${puzzleInfo.solved} of ${puzzleInfo.total} solved · daily streak ${puzzleInfo.streak}`, { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#5a4a32', + }).setOrigin(0.5).setDepth(depth + 1)); + } + 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 = 600, h = 310; + 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 + 148, 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 - 130, y + h - 62, yes, () => { hRef.close(); onYes?.(); }, { width: 230, height: 46, fontSize: 18, bg: yesBg }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 130, y + h - 62, no, () => { hRef.close(); onNo?.(); }, { width: 230, 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: '#f4ecd8', padding: { x: 18, y: 10 }, align: 'center', wordWrap: { width: 900 } }) + .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/go/GoEndScreen.js b/src/games/go/GoEndScreen.js new file mode 100644 index 0000000..b8d561a --- /dev/null +++ b/src/games/go/GoEndScreen.js @@ -0,0 +1,325 @@ +// GoEndScreen.js: after a game: the between-games card (result, match +// tally, Next Game); after a match (or for an opened SGF record): the +// review: the result, the numbers, the score graph (Hōun's estimate of +// the lead after every move, filled in as the engine works through the +// game), his notes on the moves he'd have played differently, every game +// of the match, and a replay board you can step through. + +import { Button } from '../../ui/Button.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { DISPLAY_FONT, SERIF } from './GoArt.js'; +import { frame, blocker, handle } from './GoDialogs.js'; +import { positionAfter, stats, notate, other, RULES, SIZE_INFO, starPoints } from './GoLogic.js'; +import { describeIdea } from './GoAI.js'; + +const half = (x) => (x % 1 ? `${Math.floor(x) || ''}½` : String(x)); +const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1); +const fmt = (x) => (Number.isInteger(x) ? String(x) : x.toFixed(1)); + +export function resultLine(gs, humanColor, oppName) { + const sc = gs.score; + if (gs.winner === 'draw') { + return { title: 'Jigo: a draw', good: null, why: sc ? `Black ${fmt(sc.black)} · White ${fmt(sc.white)}: perfectly even.` : 'An even result.' }; + } + const names = { [humanColor]: 'you', [other(humanColor)]: oppName }; + const won = gs.winner === humanColor; + let why; + if (gs.endReason === 'resign') why = won ? `${oppName} resigned.` : 'You resigned.'; + else if (gs.endReason === 'time') why = won ? `${oppName} ran out of time.` : 'Your byo-yomi ran out.'; + else if (sc) why = `Black ${fmt(sc.black)} · White ${fmt(sc.white)} (komi ${gs.komi}). ${cap(names[gs.winner])} by ${fmt(sc.margin)}.`; + else why = ''; + return { title: won ? 'You win!' : `${oppName} wins`, good: won, 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 = 660, h = 370; + 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 + 80, `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 + 128, r.why, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 90 } }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(x + w / 2, y + 188, `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 + 224, match.handicap ? 'A handicap match: you keep your colour.' : '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 - 64, '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 - 64, 'Leave', () => { hRef.close(); onLeave(); }, { width: 220, height: 48, fontSize: 19, bg: 0x7a1a14 }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} + +/** + * The review. `review(onChunk)` starts the engine on every position of the + * game and calls onChunk(startIndex, results[]) as answers arrive; it may + * be null. For an imported record, humanColor is null and `names` are the + * players in the file. + */ +export function openEndScreen(scene, { + gs, humanColor = null, oppName = '', names = null, match = null, record = null, depth, review = null, title: forcedTitle = null, + onPlayAgain, onSave, onMenu, playAgainLabel = null, menuLabel = 'Leave the Temple', +}) { + const objs = [blocker(scene, depth - 1, 0.6)]; + const w = 1320, h = 920; + 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; + const size = gs.size; + const N = gs.history.length; + const imported = !humanColor; + const view = humanColor ?? 'black'; // whose side the graph is drawn for + const nameOf = (c) => (imported ? (c === 'black' ? names?.black : names?.white) ?? cap(c) : c === humanColor ? 'You' : oppName); + + // headline + let title, color = '#2a1410'; + const multi = match && match.games > 1; + if (forcedTitle) title = forcedTitle; + else 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'; + } else if (!imported) { + const r = resultLine(gs, humanColor, oppName); + title = r.title; color = r.good === null ? '#2a1410' : r.good ? '#1f6a3a' : '#8e1c16'; + } else title = `${names?.black ?? 'Black'} vs ${names?.white ?? 'White'}`; + add(scene.add.text(x + w / 2, y + 70, title, { fontFamily: DISPLAY_FONT, fontSize: '36px', color }).setOrigin(0.5).setDepth(D1)); + const rules = `${SIZE_INFO[size].name} · ${RULES[gs.rules].name} rules · komi ${gs.komi}${gs.handicap ? ` · ${gs.handicap} stones` : ''}`; + let sub; + if (multi) sub = `You ${half(match.human) || '0'} · ${oppName} ${half(match.ai) || '0'} · ${rules}`; + else if (!imported) sub = `${resultLine(gs, humanColor, oppName).why} · ${rules}`; + else sub = `${gs.recordResult || 'No result recorded'} · ${N} moves · ${rules}`; + add(scene.add.text(x + w / 2, y + 112, sub, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 140 } }).setOrigin(0.5).setDepth(D1)); + + // ── left: numbers, graph, notes ── + const lx = x + 64; + let ly = y + 162; + 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 A = imported ? 'black' : humanColor, B = other(A); + const sa = stats(gs, A), sb = stats(gs, B); + const sc = gs.score; + const rows = [ + ['Stones played', sa.moves, sb.moves], + ['Prisoners taken', sa.captured, sb.captured], + ['Biggest capture', sa.biggest || '—', sb.biggest || '—'], + ]; + if (sc) { + rows.push(['Territory', sc.territory[A], sc.territory[B]]); + rows.push(['Dead stones taken off', sc.deadCount[B], sc.deadCount[A]]); + rows.push(['Score', fmt(sc[A]), fmt(sc[B])]); + } + const c1 = lx + 330, c2 = lx + 470; + add(scene.add.text(c1, ly, `${nameOf(A).toUpperCase().slice(0, 12)} (${A === 'black' ? 'B' : 'W'})`, { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#2a1410' }).setOrigin(0.5).setDepth(D1)); + add(scene.add.text(c2, ly, `${nameOf(B).toUpperCase().slice(0, 12)} (${B === 'black' ? 'B' : 'W'})`, { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#2a1410' }).setOrigin(0.5).setDepth(D1)); + rows.forEach(([label, a, b], i) => { + const yy = ly + 26 + i * 25; + if (i % 2 === 0) g.fillStyle(0x8a5a2a, 0.08).fillRect(lx - 10, yy - 12, 570, 24); + 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 += 26 + rows.length * 25 + 34; + + // the score graph + const sw = 570, sh = 130, sx = lx - 10, sy = ly; + const graphTitle = add(scene.add.text(lx, sy - 4, `HŌUN'S COUNT: ${nameOf(view).toUpperCase()} AHEAD ABOVE THE LINE`, { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#7a2414' }).setOrigin(0, 1).setDepth(D1)); + void graphTitle; + g.fillStyle(0xffffff, 0.35).fillRect(sx, sy + 6, sw, sh); + const mid = sy + 6 + sh / 2; + g.lineStyle(1, 0x8a6a3a, 0.6).lineBetween(sx, mid, sx + sw, mid); + const graphG = add(scene.add.graphics().setDepth(D1)); + const cursorG = add(scene.add.graphics().setDepth(D1 + 1)); + const progress = add(scene.add.text(sx + sw - 6, sy + 12, review ? 'reading…' : '', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#7a6a52' }).setOrigin(1, 0).setDepth(D1 + 1)); + const leads = Array(N + 1).fill(null); // black's lead after n moves + const bests = Array(N + 1).fill(-1); + const px = (i) => sx + (i / Math.max(1, N)) * sw; + const drawGraph = () => { + graphG.clear(); + const vals = leads.map((v) => (v == null ? null : (view === 'black' ? v : -v))); + const known = vals.filter((v) => v != null); + if (known.length < 2) return; + const maxAbs = Math.max(8, ...known.map(Math.abs)); + const py = (v) => mid - (v / maxAbs) * (sh / 2 - 6); + // shade each segment on its own (split where it crosses the line), so + // the fill never folds over itself + const ahead = view === 'black' ? 0x1c1b22 : 0x8a826e, behind = 0xb83a24; + let prev = null; + vals.forEach((v, i) => { + if (v == null) return; + const cur = { x: px(i), y: py(v) }; + if (prev) { + const { x: xa, y: ya } = prev, { x: xb, y: yb } = cur; + const fillSide = (x1, y1, x2, y2) => { + graphG.fillStyle((y1 + y2) / 2 <= mid ? ahead : behind, 0.22); + graphG.fillTriangle(x1, mid, x1, y1, x2, y2); + graphG.fillTriangle(x1, mid, x2, y2, x2, mid); + }; + if ((ya - mid) * (yb - mid) < 0) { + const xc = xa + ((xb - xa) * (ya - mid)) / (ya - yb); + fillSide(xa, ya, xc, mid); fillSide(xc, mid, xb, yb); + } else fillSide(xa, ya, xb, yb); + } + prev = cur; + }); + graphG.lineStyle(2.5, 0xb83a24, 1); + graphG.beginPath(); + let started = false; + vals.forEach((v, i) => { if (v == null) return; if (!started) { graphG.moveTo(px(i), py(v)); started = true; } else graphG.lineTo(px(i), py(v)); }); + graphG.strokePath(); + }; + ly = sy + sh + 42; + + // the notes + add(scene.add.text(lx, ly, 'HŌUN\'S NOTES', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#7a2414' }).setOrigin(0, 0.5).setDepth(D1)); + ly += 24; + const notesY = ly; + const waiting = add(scene.add.text(lx, notesY, review ? 'He turns the stones over one by one…' : 'No notes for this one.', { + fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#5a4a32', wordWrap: { width: 580 }, + }).setOrigin(0, 0).setDepth(D1)); + const noteObjs = []; + if (record) { + add(scene.add.text(lx, y + h - 128, `Your record against ${oppName}: ${record.w} won · ${record.d} drawn · ${record.l} lost`, { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#3a2a1a' }).setOrigin(0, 0.5).setDepth(D1)); + } + + // ── right: replay board ── + const area = 430; + const RS = area / size, BW = RS * (size - 1); + const rx = x + w - 90 - area + RS / 2, ry = y + 176; + add(scene.add.text(rx + BW / 2, ry - RS * 0.8 - 24, 'REPLAY', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#7a2414' }).setOrigin(0.5).setDepth(D1)); + const bg = add(scene.add.graphics().setDepth(D1)); + bg.fillStyle(0x2a1a0e, 1).fillRoundedRect(rx - RS * 0.8 - 6, ry - RS * 0.8 - 6, BW + RS * 1.6 + 12, BW + RS * 1.6 + 12, 6); + bg.fillStyle(0xe2b064, 1).fillRect(rx - RS * 0.8, ry - RS * 0.8, BW + RS * 1.6, BW + RS * 1.6); + bg.lineStyle(1.2, 0x3a2410, 0.9); + 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); } + bg.fillStyle(0x3a2410, 1); + for (const s of starPoints(size)) bg.fillCircle(rx + (s % size) * RS, ry + Math.floor(s / size) * RS, Math.max(2, RS * 0.1)); + const pg = add(scene.add.graphics().setDepth(D1 + 1)); + const label = add(scene.add.text(rx + BW / 2, ry + BW + RS + 34, '', { fontFamily: SERIF, fontSize: '16px', color: '#2a1a10', align: 'center', wordWrap: { width: area + 40 } }).setOrigin(0.5).setDepth(D1)); + let n = N; + let mark = null; + const pt = (sq) => ({ x: rx + (sq % size) * RS, y: ry + Math.floor(sq / size) * RS }); + const draw = () => { + pg.clear(); + const pos = positionAfter(gs, n); + const R = RS * 0.47; + pos.board.forEach((v, sq) => { + if (!v) return; + const p = pt(sq); + pg.fillStyle(0x000000, 0.3).fillCircle(p.x + 1, p.y + 1.5, R); + pg.fillStyle(v === 'black' ? 0x1c1b22 : 0xf4f0e4, 1).fillCircle(p.x, p.y, R); + if (v === 'white') pg.lineStyle(1, 0x9a907a, 0.8).strokeCircle(p.x, p.y, R); + }); + const lastEntry = n > 0 ? gs.history[n - 1] : null; + if (lastEntry && !lastEntry.pass) { + const p = pt(lastEntry.sq); + pg.lineStyle(Math.max(1.5, RS * 0.08), lastEntry.color === 'black' ? 0xffffff : 0x000000, 0.9).strokeCircle(p.x, p.y, R * 0.5); + } + if (mark && mark.at === n) { + if (mark.best >= 0) { const pb = pt(mark.best); pg.lineStyle(3, 0x30a060, 1).strokeCircle(pb.x, pb.y, R * 0.95); } + if (mark.played >= 0) { + const pp = pt(mark.played); + pg.lineStyle(3, 0xd03020, 1); + pg.lineBetween(pp.x - R * 0.6, pp.y - R * 0.6, pp.x + R * 0.6, pp.y + R * 0.6); + pg.lineBetween(pp.x + R * 0.6, pp.y - R * 0.6, pp.x - R * 0.6, pp.y + R * 0.6); + } + } else if (bests[n] >= 0 && leads[n] != null && n < N) { + // the faint suggestion for the next move + const pb = pt(bests[n]); + pg.lineStyle(2, 0x30a060, 0.55).strokeCircle(pb.x, pb.y, R * 0.8); + } + const desc = !lastEntry ? 'The empty board' : lastEntry.pass ? `${cap(lastEntry.color)} passes` : `${cap(lastEntry.color)} ${lastEntry.n}${lastEntry.captured.length ? ` · takes ${lastEntry.captured.length}` : ''}`; + let extra = `Prisoners: B ${pos.captures.black} · W ${pos.captures.white}`; + if (leads[n] != null) extra += ` · Hōun: ${leads[n] >= 0 ? 'B' : 'W'}+${Math.abs(leads[n]).toFixed(1)}`; + if (mark && mark.at === n) extra = 'green ring: Hōun\'s move · red cross: the move played'; + else if (bests[n] >= 0 && n < N) extra += `\ngreen: Hōun would play ${notate(bests[n], size)} next`; + label.setText(`Move ${n} of ${N}: ${desc}\n${extra}`); + cursorG.clear(); + cursorG.lineStyle(2, 0x2a4a6a, 0.8).lineBetween(px(n), sy + 6, px(n), sy + 6 + sh); + }; + draw(); + const by = ry + BW + RS + 92; + const step = (d) => { n = Math.max(0, Math.min(N, n + d)); mark = null; draw(); }; + const cxr = rx + BW / 2; + [['|◀', -9999, 64], ['◀◀', -10, 64], ['◀', -1, 64], ['▶', 1, 64], ['▶▶', 10, 64], ['▶|', 9999, 64]].forEach(([t, d, bw], i) => { + add(new Button(scene, cxr + (i - 2.5) * 74, by, t, () => step(d), { width: bw, height: 42, fontSize: 17, bg: 0x3a2216 }).setDepth(D1 + 1)); + }); + // click the graph to jump + const hit = add(scene.add.zone(sx + sw / 2, sy + 6 + sh / 2, sw, sh).setDepth(D1 + 2).setInteractive({ useHandCursor: true })); + hit.on('pointerdown', (p) => { n = Math.max(0, Math.min(N, Math.round(((p.x - sx) / sw) * N))); mark = null; draw(); }); + const keys = (e) => { if (e.key === 'ArrowLeft') step(-1); else if (e.key === 'ArrowRight') step(1); else if (e.key === 'Home') step(-9999); else if (e.key === 'End') step(9999); }; + scene.input.keyboard?.on('keydown', keys); + + // the match, under the replay + if (multi) { + let my = by + 44; + add(scene.add.text(rx - 20, 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` : 'Jigo'; + const col = r.result === 'human' ? '#1f6a3a' : r.result === 'ai' ? '#8e1c16' : '#3a2a1a'; + add(scene.add.text(rx - 20, my, `Game ${i + 1} · you ${r.humanColor} · ${res} · ${r.score}`, { fontFamily: SERIF, fontSize: '15px', color: col }).setOrigin(0, 0.5).setDepth(D1)); + my += 21; + }); + } + + // the engine's reading arrives in chunks + const writeNotes = () => { + noteObjs.forEach((o) => o.destroy()); + noteObjs.length = 0; + const cand = []; + for (let i = 0; i < N; i++) { + const hst = gs.history[i]; + if (hst.pass || leads[i] == null || leads[i + 1] == null) continue; + if (!imported && hst.color !== humanColor) continue; + if (bests[i] < 0 || bests[i] === hst.sq) continue; + const sign = hst.color === 'black' ? 1 : -1; + const loss = (leads[i] - leads[i + 1]) * sign; + if (loss >= Math.max(4, size * 0.45)) cand.push({ i, loss, played: hst.sq, best: bests[i], color: hst.color }); + } + const notes = cand.sort((a, b) => b.loss - a.loss).slice(0, 4).sort((a, b) => a.i - b.i); + const doneAll = leads.every((v) => v != null); + if (!notes.length) { waiting.setText(doneAll ? 'Not a move I would change much. A clean game.' : 'He turns the stones over one by one…'); return; } + waiting.setText(''); + notes.forEach((r, k) => { + const pos = { size, board: positionAfter(gs, r.i).board, turn: r.color, ko: -1, phase: 'playing', captures: { black: 0, white: 0 }, history: [], seen: [], hash: [0, 0] }; + let idea; + try { idea = describeIdea(pos, r.best); } catch (_) { idea = 'was the bigger point'; } + const whose = `${cap(r.color)}'s`; + if (imported) idea = idea.replace(/\byour\b/g, whose).replace(/\btheirs\b/g, `${cap(other(r.color))}'s`).replace(/\btheir\b/g, `${cap(other(r.color))}'s`); + const pts = Math.max(1, Math.round(r.loss)); + const who = imported ? `${cap(r.color)} played` : 'you played'; + const t = scene.add.text(lx, notesY + k * 44, `Move ${r.i + 1}: ${who} ${notate(r.played, size)}. I'd have played ${notate(r.best, size)}, which ${idea}: about ${pts} point${pts === 1 ? '' : 's'} better.`, { + fontFamily: SERIF, fontSize: '15px', color: '#2a1a10', wordWrap: { width: 580 }, 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(); }); + noteObjs.push(t); + }); + }; + if (review) { + review((start, list) => { + if (closed) return; + list.forEach((r, k) => { if (r) { leads[start + k] = r.lead; bests[start + k] = r.best; } }); + const done = leads.filter((v) => v != null).length; + progress.setText(done > N ? '' : `reading… ${Math.round((done / (N + 1)) * 100)}%`); + drawGraph(); + draw(); + writeNotes(); + }).catch(() => { if (!closed) { progress.setText(''); waiting.setText('He lost his place in the record. No notes this time.'); } }); + } + + const bty = y + h - 62; + let hRef = null; + const btns = []; + if (onPlayAgain) btns.push([playAgainLabel ?? (multi ? 'New Match' : 'Play Again'), 0x1f6a3a, () => { hRef.close(); onPlayAgain(); }]); + if (onSave) btns.push(['Save as SGF', 0x2a4a6a, () => onSave()]); + btns.push([menuLabel, 0x7a1a14, () => { hRef.close(); onMenu(); }]); + const bw = 250, gap = 24, x0 = x + w / 2 - ((btns.length - 1) * (bw + gap)) / 2; + btns.forEach(([t, bgc, fn], i) => add(new Button(scene, x0 + i * (bw + gap), bty, t, fn, { width: bw, height: 52, fontSize: 19, bg: bgc }).setDepth(D1 + 1))); + hRef = handle(objs, () => { closed = true; noteObjs.forEach((o) => o.destroy()); scene.input.keyboard?.off('keydown', keys); }); + return hRef; +} diff --git a/src/games/go/GoEngine.js b/src/games/go/GoEngine.js new file mode 100644 index 0000000..ab95873 --- /dev/null +++ b/src/games/go/GoEngine.js @@ -0,0 +1,95 @@ +// GoEngine.js: runs the opponents (GoAI) and Hōun's problem solver +// (GoTsumego) off the main thread, so the temple keeps breathing (mist, +// petals, incense) while someone 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 (GoWorker.js); +// if that can't start, runs the same code inline. +// +// Kinds (pos: see GoAI.posOf): +// move { pos, skill } → { sq, resign, winrate, lead, ownership, pv } +// hint { pos, playouts, ms } → { best, top, winrate, lead, ownership, pv } +// estimate { pos, playouts, ms } → same as hint (cheaper budget; the score bar) +// dead { pos, playouts, ms } → { dead[], ownership[] } +// review { positions, playouts, ms } → [{ lead, winrate, best }] +// puzzleReply { prob } → { sq, refutes } +// puzzleCheck { prob, human } → { wins, settled, terminal } + +import * as AI from './GoAI.js'; +import * as T from './GoTsumego.js'; + +export function handle(kind, p) { + switch (kind) { + case 'move': return AI.chooseMove(p.pos, p.skill, { scale: p.scale ?? 1 }); + case 'hint': + case 'estimate': return AI.analyse(p.pos, { playouts: p.playouts ?? 6000, ms: p.ms ?? 1200 }); + case 'dead': return AI.estimateDead(p.pos, { playouts: p.playouts ?? 3000, ms: p.ms ?? 1500 }); + case 'review': return AI.reviewPositions(p.positions, { playouts: p.playouts ?? 500, ms: p.ms ?? 250 }); + case 'puzzleReply': return T.reply(p.prob, { maxNodes: 200000 }); + case 'puzzleCheck': { + const term = T.terminal(p.prob); + const wins = term ? (term === 'dead') === (p.human === p.prob.attacker) : T.wins(p.prob, p.human, { maxNodes: 200000 }); + const settled = wins && (term ? true : T.settled(p.prob, p.human, { maxNodes: 200000 })); + return { wins, settled, terminal: term }; + } + 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('./GoWorker.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); + }); + } + + /** Drop the answers to everything asked so far (a new game, an undo). */ + forget() { for (const job of this.pending.values()) job.stale = true; } + + destroy() { + try { this.worker?.terminate(); } catch (_) { /* */ } + this.worker = null; + this.pending.clear(); + } +} diff --git a/src/games/go/GoGame.js b/src/games/go/GoGame.js index dfb2f31..c97e78f 100644 --- a/src/games/go/GoGame.js +++ b/src/games/go/GoGame.js @@ -1,649 +1,1741 @@ +// GoGame.js: "Unkai-ji, the Temple Above the Clouds". A pavilion on a +// mountainside at dawn: the board sits on the tatami, the shoji are slid +// open onto a valley full of mist, and the sun comes up over the ridges as +// you play. The scene only orchestrates: rules in GoLogic, the opponents +// in GoAI (run in a worker via GoEngine, with Hōun's problem solver from +// GoTsumego), geometry in GoLayout, art in GoArt, stones in GoStones, +// furniture in GoHud, pop-ups in GoDialogs and GoEndScreen, words in +// GoTalk, sound in GoSound, records in GoSgf, the problems in GoPuzzles. +// +// Flow: the setup card (board size, colour or nigiri, handicap, komi, +// rules, match length, byo-yomi) → each game: any handicap stones go down, +// then the players alternate. On your turn hover a point to see what it +// would capture (or a group's liberties), click to play (or the arrow keys +// and Enter); P passes. A stone is lifted from your bowl and set down; +// captured stones fly into the capturer's lid. Two passes in a row start +// the count: Hōun marks the stones he thinks are dead, you click groups to +// change his mind, and accept (the opponent objects if you call its live +// stones dead, and play resumes). After a match: the review, with Hōun's +// count after every move, his notes and a replay board. Undo, hints, a +// study overlay (territory and the score), move numbers, coordinates. +// Hōun's problems (a rated ladder and a daily problem) and SGF records +// open from the setup card or the menu. Everything in progress is saved. +// +// Every async step carries the game's token: a new game, an undo, the +// setup card or a problem 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 { - SIZE, KOMI, createInitialState, getValidMoves, findCaptures, getGroup, - getLiberties, isValidMove, applyMove, applyPass, isGameOver, - scoreTerritory, getFinalScore, getWinner, -} from './GoLogic.js'; -import { chooseMove, nextThinkDelay } from './GoAI.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 './GoLogic.js'; +import { clampSkill, describeIdea, posOf } from './GoAI.js'; +import * as T from './GoTsumego.js'; +import { Engine } from './GoEngine.js'; +import { BX, BY, BCX, BANNER, VIEW, INCENSE, geom, pointXY, pointAt } from './GoLayout.js'; +import { prepareGoArt, ensureBoard, DISPLAY_FONT, SERIF, BOLD_FONT, BOARD_POS, RES } from './GoArt.js'; +import { StoneSet } from './GoStones.js'; +import { Hud } from './GoHud.js'; +import { openPauseMenu, openSetup, confirmBox, toast, CLOCK_SPEC } from './GoDialogs.js'; +import { openEndScreen, openBetween, resultLine } from './GoEndScreen.js'; +import { hounLine, opponentLine, tierOf } from './GoTalk.js'; +import { pachi, rustle, clatter, deny, tick, bell, sting, Ambience } from './GoSound.js'; +import { parseSgf, downloadSgf, pickSgfFile } from './GoSgf.js'; +import * as PZ from './GoPuzzles.js'; -// ── Layout ───────────────────────────────────────────────────────────────────── -const SQ = 86; // distance between grid lines -const MARGIN = 52; // padding inside frame to first line -const INNER = (SIZE - 1) * SQ + MARGIN * 2; // 688 + 104 = 792 -const FRAME = 30; -const FULL = INNER + FRAME * 2; // 852 -const BX = Math.round(GAME_WIDTH / 2 - FULL / 2); // 534 -const BY = Math.round(GAME_HEIGHT / 2 - FULL / 2); // 114 -const GX = BX + FRAME + MARGIN; // x of intersection (0,0) -const GY = BY + FRAME + MARGIN; // y of intersection (0,0) -const SR = Math.round(SQ * 0.42); // stone radius ≈36 - -const DEPTH = { board: 0, stone: 10, hint: 8, territory: 6, overlay: 20, ui: 50, banner: 60 }; - -// ── Colors ───────────────────────────────────────────────────────────────────── -const C = { - wood: 0xd4a84b, - woodDk: 0xb88c36, - grain: 0xc49840, - line: 0x4a3010, - frame: 0x3a2010, - frameLt: 0x6b3a1a, - frameLn: 0x8b5020, - bFill: 0x1c1a26, - bHi: 0x5a5870, - bEdge: 0x0d0c14, - wFill: 0xf8f4e8, - wHi: 0xffffff, - wEdge: 0xd8d0b8, - hint: 0xffd700, - selGold: 0xffd700, +const SETTINGS_KEY = 'go-settings'; +const SAVE_KEY = 'go-save-v1'; +const RECORD_KEY = 'go-record'; +const DEFAULT_SETUP = { size: 9, color: 'black', handicap: 0, komi: 'auto', rules: 'japanese', games: 1, clock: 'off' }; +const DEFAULT_SETTINGS = { + pace: 'normal', skipAI: false, coords: true, numbers: false, preview: true, coach: true, + territory: false, ambience: true, setup: { ...DEFAULT_SETUP }, }; - -// Traditional 9×9 hoshi (star points) -const HOSHI = [[2,2],[2,6],[6,2],[6,6],[4,4]]; +const D = { + sky: 0, sun: 0.4, ridges: 0.6, birds: 0.7, mist: 0.8, season: 0.9, room: 2, smoke: 3, + board: 5, coords: 6, terr: 7, mark: 8, piece: 10, over: 12, ghost: 13, cursor: 42, hud: 50, fx: 70, banner: 80, end: 95, modal: 110, +}; +const REASON_LINE = { ko: 'koIllegal', suicide: 'suicide', superko: 'superko' }; +const fmt = (x) => (Number.isInteger(x) ? String(x) : x.toFixed(1)); export default class GoGame extends Phaser.Scene { constructor() { super('GoGame'); } 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.stoneObjs = []; // stoneObjs[r][c] = Graphics | null - this.hintObjs = []; - this.overlayObjs = []; - this.terrObjs = []; // territory reveal graphics - this.opponentPortrait = null; - this.captureBlackText = null; - this.captureWhiteText = null; - this.turnText = null; - this.passCount = 0; + 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: 'unkai-monk', name: 'Brother Jun', 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 | scoring | over | puzzle | review + this.token = 0; + this.reviewTok = 0; + this.undoStack = []; + this.gs = null; + this.match = null; + this.puz = null; + this.dead = []; + this.engineDead = new Set(); + this.estimate = null; + this.estKey = null; + this.byo = null; + this.cursor = null; + this.hover = -1; + this.clocks = { human: 0, ai: 0 }; + this.turnStart = 0; + this.overObjs = []; + this.previewObjs = []; + this.hintObjs = []; + this.coordObjs = []; + this.atariSeen = new Set(); + this.saidKo = false; + this.saidEndgame = false; + this.saidRegion = false; + try { + const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + this.settings = { ...DEFAULT_SETTINGS, ...s, setup: { ...DEFAULT_SETUP, ...(s.setup ?? {}) } }; + } catch (_) { this.settings = { ...DEFAULT_SETTINGS, setup: { ...DEFAULT_SETUP } }; } } + get k() { return PACE[this.settings.pace] ?? 1; } + get humanColor() { return this.puz ? this.puz.human : (this.match?.humanColor ?? L.BLACK); } + get aiColor() { return L.other(this.humanColor); } + get size() { return this.gs?.size ?? this.settings.setup.size ?? 9; } + 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, 0x0a0806).setDepth(-2); + prepareGoArt(this).then((seas) => { + if (!this.sys.isActive()) return; + this.season = seas; + 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('goParticle', 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.sky); + this.add.image(0, 0, 'go-vignette').setOrigin(0).setDepth(D.room); + this.add.image(0, 0, 'go-props').setOrigin(0).setDepth(D.room + 0.1); + } else { + this.add.image(0, 0, 'go-sky').setOrigin(0).setDepth(D.sky); + this.skyShade = this.add.rectangle(VIEW.w / 2, GAME_HEIGHT / 2, VIEW.w, GAME_HEIGHT, 0x0c0e2a, 0.45).setDepth(D.sky + 0.1); + this.sun = this.add.image(VIEW.w * 0.4, 820, 'go-sun').setDepth(D.sun).setScale(1.3); + this.add.image(0, 0, 'go-ridges').setOrigin(0).setDepth(D.ridges); + this.add.image(0, 0, 'go-room').setOrigin(0).setDepth(D.room); + } + this.boardImg = this.add.image(BOARD_POS.x, BOARD_POS.y, ensureBoard(this, this.size)).setOrigin(0).setDepth(D.board); + + this.terrG = this.add.graphics().setDepth(D.terr); + this.markG = this.add.graphics().setDepth(D.mark); + this.overG = this.add.graphics().setDepth(D.over); + this.previewG = this.add.graphics().setDepth(D.ghost); + this.cursorG = this.add.graphics().setDepth(D.cursor); + + this.stones = new StoneSet(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.buildCoords(); + + 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', 'review'].includes(this.phase)) this.refreshHud(); } }); + this.events.once('shutdown', () => { + this.ended = true; + this.token++; + this.reviewTok++; + this.ambience?.stop(); + this.engine?.destroy(); + this.setCursor('default'); + }); + } + + ambienceFx() { + // incense smoke curls up from the alcove, whatever the backdrop + const sx = INCENSE.x + 6, sy = INCENSE.y - 62; + this.time.addEvent({ delay: 420, loop: true, callback: () => { + if (this.ended) return; + const s = this.add.image(sx, sy, 'go-smoke').setDepth(D.smoke).setAlpha(0).setScale(0.12); + this.tweens.add({ + targets: s, y: sy - 150 - Math.random() * 70, x: sx + (Math.random() - 0.5) * 46, scale: 0.8 + Math.random() * 0.5, + alpha: { from: 0.32, to: 0 }, duration: 3200 + Math.random() * 1400, ease: 'Sine.Out', onComplete: () => s.destroy(), + }); + } }); + if (!this.fullRoom) return; + const maskG = this.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff).fillRect(VIEW.x, VIEW.y, VIEW.w, VIEW.h); + this.viewMask = maskG.createGeometryMask(); + this.sun.setMask(this.viewMask); + // dawn: the sun climbs out of the valley and the sky pales over the session + this.tweens.add({ targets: this.sun, y: 430, duration: 26 * 60 * 1000, ease: 'Sine.Out' }); + this.tweens.add({ targets: this.skyShade, alpha: 0, duration: 20 * 60 * 1000, ease: 'Sine.Out' }); + this.tweens.add({ targets: this.sun, scale: { from: 1.25, to: 1.4 }, duration: 5000, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + // mist banks drifting in the valley + for (let i = 0; i < 6; i++) { + const m = this.add.image(Math.random() * VIEW.w, 640 + i * 62, 'go-mist').setDepth(D.mist).setScale(2 + Math.random() * 1.2, 1.4 + Math.random()) + .setAlpha(0.35 + Math.random() * 0.25).setMask(this.viewMask); + this.tweens.add({ targets: m, x: m.x + (Math.random() < 0.5 ? -1 : 1) * (100 + Math.random() * 120), duration: 18000 + Math.random() * 14000, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + } + // birds crossing the valley now and then + this.time.addEvent({ delay: 7000, loop: true, callback: () => { + if (this.ended || Math.random() < 0.45) return; + const n = 2 + Math.floor(Math.random() * 4); + const y0 = 160 + Math.random() * 300, dir = Math.random() < 0.5 ? 1 : -1; + for (let i = 0; i < n; i++) { + const x = dir > 0 ? -30 - i * 26 : VIEW.w + 30 + i * 26; + const b = this.add.image(x, y0 + (i % 2) * 14 + i * 6, 'go-bird').setDepth(D.birds).setScale(0.7 + Math.random() * 0.4).setMask(this.viewMask).setFlipX(dir < 0); + this.tweens.add({ targets: b, scaleY: { from: b.scaleX, to: b.scaleX * 0.3 }, duration: 160 + Math.random() * 60, yoyo: true, repeat: -1 }); + this.tweens.add({ targets: b, x: x + dir * (VIEW.w + 120), y: b.y - 40 + Math.random() * 60, duration: 9000 + Math.random() * 3000, ease: 'Linear', onComplete: () => b.destroy() }); + } + } }); + // the season at the window + const seas = this.season ?? 'winter'; + const key = `go-p-${seas}`; + const rate = seas === 'winter' ? 150 : seas === 'summer' ? 1400 : 520; + this.time.addEvent({ delay: rate, loop: true, callback: () => { + if (this.ended) return; + const x = -40 + Math.random() * (VIEW.w + 40), y = -20; + const sc = seas === 'winter' ? 0.3 + Math.random() * 0.7 : 0.8 + Math.random() * 0.5; + const p = this.add.image(x, y, key).setDepth(D.season).setScale(sc).setAlpha(seas === 'winter' ? 0.5 + Math.random() * 0.5 : 0.95).setMask(this.viewMask) + .setRotation(Math.random() * Math.PI * 2); + const dur = (seas === 'winter' ? 11000 : 9000) + Math.random() * 6000; + this.tweens.add({ targets: p, y: GAME_HEIGHT + 30, x: x + 60 + Math.random() * 160, duration: dur, ease: 'Linear', onComplete: () => p.destroy() }); + if (seas !== 'winter') this.tweens.add({ targets: p, rotation: p.rotation + (Math.random() - 0.5) * 12, scaleX: { from: sc, to: sc * 0.4 }, duration: 900 + Math.random() * 900, yoyo: true, repeat: -1 }); + } }); + } + + buildCoords() { + this.coordObjs.forEach((o) => o.destroy()); + this.coordObjs = []; + if (!this.settings.coords) return; + const size = this.size, { SQ, x0, y0, span } = geom(size); + const mx = x0 - BX, my = y0 - BY; + const fs = Math.round(Math.max(13, Math.min(20, SQ * 0.24))); + const st = { fontFamily: SERIF, fontSize: `${fs}px`, color: '#5a3410' }; + for (let i = 0; i < size; i++) { + const x = x0 + i * SQ, y = y0 + i * SQ, letter = L.COLS[i], num = String(size - i); + this.coordObjs.push( + this.add.text(x, BY + my * 0.42, letter, st).setOrigin(0.5).setDepth(D.coords).setAlpha(0.75), + this.add.text(x, y0 + span + my * 0.58, letter, st).setOrigin(0.5).setDepth(D.coords).setAlpha(0.75), + this.add.text(BX + mx * 0.42, y, num, st).setOrigin(0.5).setDepth(D.coords).setAlpha(0.75), + this.add.text(x0 + span + mx * 0.58, y, num, st).setOrigin(0.5).setDepth(D.coords).setAlpha(0.75), + ); } } - buildBoard() { - const g = this.add.graphics().setDepth(DEPTH.board); + setBoardSize(size) { + this.boardImg.setTexture(ensureBoard(this, size)); + this.stones.size = size; + this.buildCoords(); + } - // Wood frame - g.fillStyle(C.frame, 1); - g.fillRoundedRect(BX, BY, FULL, FULL, 12); - g.lineStyle(3, C.frameLt, 1); - g.strokeRoundedRect(BX + 5, BY + 5, FULL - 10, FULL - 10, 9); - g.lineStyle(1, C.frameLn, 0.6); - g.strokeRect(BX + FRAME - 2, BY + FRAME - 2, INNER + 4, INNER + 4); + // ── 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}. Hōun kept the board covered.`, + 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(); + } - // Wood board surface - g.fillStyle(C.wood, 1); - g.fillRect(BX + FRAME, BY + FRAME, INNER, INNER); + signature() { return `${this.opp.id ?? this.oppName}|${this.skill}`; } - // Subtle grain: a few lighter horizontal bands - g.fillStyle(C.grain, 0.18); - for (let i = 0; i < 6; i++) { - const gy = BY + FRAME + i * (INNER / 5.5); - g.fillRect(BX + FRAME, gy, INNER, 12); + 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; } + } + + save(between = false) { + if (!this.gs || !this.match || this.puz) return; + try { + localStorage.setItem(SAVE_KEY, JSON.stringify({ + v: 1, sig: this.signature(), gs: this.gs, match: this.match, clocks: this.clocks, byo: this.byo, dead: this.dead, + between, savedAt: Date.now(), + })); + } catch (_) { /* private mode */ } + } + + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + + resume(save) { + const tok = ++this.token; + this.engine.forget(); + this.puz = null; + this.hud.setTopName(this.oppName); + this.hud.setSkillVisible(true); + this.match = save.match; + this.gs = save.gs; + this.clocks = save.clocks ?? { human: 0, ai: 0 }; + this.byo = save.byo ?? null; + this.dead = []; + this.estimate = null; this.estKey = null; + this.undoStack = []; + this.clearOverlays(); + this.setBoardSize(this.size); + this.stones.build(this.gs.board, this.size); + this.hud.setMode('play'); + this.hud.hounSays(hounLine('welcomeBack')); + if (save.between || this.gs.phase === 'over') { this.phase = 'over'; this.refreshHud(); this.betweenGames(); return; } + this.refreshHud(); + this.drawOverlays(); + this.nextTurn(tok); + } + + puzzleInfo() { + const st = PZ.loadPuzzleState(); + return { rating: st.rating, solved: Object.keys(st.solved).length, total: PZ.PUZZLES.length, streak: PZ.dailyStreak(st), dailyDone: !!st.daily[PZ.dateKey()] }; + } + + openSetupCard() { + this.token++; + this.engine.forget(); + this.phase = 'setup'; + this.busy = true; + this.puz = null; + this.hud.setTopName(this.oppName); + this.hud.setSkillVisible(true); + this.hud.setMode('play'); + this.clearOverlays(); + if (!this.gs || this.gs.phase !== 'playing') { + this.gs = null; + this.stones.clear(); + this.setBoardSize(this.settings.setup.size); } + this.hud.hidePortraits(); + this.hud.setStatus('Unkai-ji', 'Choose the board and kneel.'); + this.hud.hounSays(hounLine('welcome')); + this.modal = openSetup(this, { + prefs: this.settings.setup, depth: D.modal, opponentName: this.oppName, puzzleInfo: this.puzzleInfo(), + onStart: (p) => { + this.modal = null; + this.hud.showPortraits(); + this.settings.setup = { ...p }; + this.persistSettings(); + this.clearSave(); + this.startMatch(p); + }, + onPuzzles: () => { this.modal = null; this.hud.showPortraits(); this.enterPuzzles(false); }, + onDaily: () => { this.modal = null; this.hud.showPortraits(); this.enterPuzzles(true); }, + onOpen: () => { this.modal = null; this.openSgf(); }, + onLeave: () => this.scene.start('GameMenu'), + }); + } - // Grid lines — thin inner, slightly thicker outer border - g.lineStyle(1, C.line, 0.75); - for (let i = 0; i < SIZE; i++) { - const x = GX + i * SQ, y = GY + i * SQ; - g.lineBetween(x, GY, x, GY + (SIZE - 1) * SQ); - g.lineBetween(GX, y, GX + (SIZE - 1) * SQ, y); + startMatch(p) { + const drawn = p.color === 'random' ? (Math.random() < 0.5 ? L.BLACK : L.WHITE) : p.color; + this.match = { + games: p.games, size: p.size, rules: p.rules, komi: p.komi, handicap: p.handicap, clock: p.clock, + firstColor: drawn, humanColor: drawn, results: [], human: 0, ai: 0, + }; + if (p.color === 'random') toast(this, `Nigiri: you drew ${drawn === L.BLACK ? 'Black' : 'White'}.`, { depth: D.modal }); + this.hud.say(opponentLine('greet', this.tier)); + this.startGame(); + } + + async startGame() { + const tok = ++this.token; + this.engine.forget(); + const m = this.match; + const idx = m.results.length; + m.humanColor = m.handicap ? m.firstColor : (idx % 2 === 0 ? m.firstColor : L.other(m.firstColor)); + this.gs = L.createGame({ size: m.size, rules: m.rules, komi: m.komi === 'auto' ? null : m.komi, handicap: m.handicap }); + this.undoStack = []; + this.clocks = { human: 0, ai: 0 }; + const spec = CLOCK_SPEC[m.clock]; + this.byo = spec ? { secs: spec.secs, periods: spec.periods, left: spec.secs * 1000 } : null; + this.dead = []; + this.estimate = null; this.estKey = null; + this.saidKo = false; this.saidEndgame = false; + this.atariSeen.clear(); + this.cursor = null; + this.clearOverlays(); + this.setBoardSize(this.size); + this.stones.build(Array(this.size * this.size).fill(null), this.size); + this.hud.setMode('play'); + this.phase = 'intro'; + this.busy = true; + this.refreshHud(); + this.setStatus('Setting up', `${L.SIZE_INFO[m.size].name} · ${L.RULES[m.rules].name} rules · komi ${this.gs.komi}${m.games > 1 ? ` · game ${idx + 1} of up to ${m.games}` : ''}`); + bell(this, 0.04); + const hs = this.gs.setup.black; + if (hs.length) { + this.hud.hounSays(hounLine('handicap', { n: hs.length })); + await Promise.all(hs.map((sq, i) => this.stones.drop(sq, L.BLACK, { delay: i * 170 * this.k }).then(() => { if (!this.stale(tok)) pachi(this, { vol: 0.1 }); }))); + if (this.stale(tok)) return; } - // Slightly thicker outer border - g.lineStyle(2, C.line, 0.9); - g.strokeRect(GX, GY, (SIZE - 1) * SQ, (SIZE - 1) * SQ); - - // Hoshi (star points) - g.fillStyle(C.line, 0.9); - for (const [r, c] of HOSHI) g.fillCircle(GX + c * SQ, GY + r * SQ, 5); - - // Coordinate labels: A–I along bottom, 9–1 along left - for (let c = 0; c < SIZE; c++) { - this.add.text(GX + c * SQ, BY + FRAME + INNER + 18, 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 + FRAME - 18, GY + r * SQ, String(SIZE - r), { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.board); + const you = this.humanColor === L.BLACK ? 'Black' : 'White'; + this.banner(`You play ${you}`, this.humanColor === L.BLACK ? 0xc8c4d8 : 0xf6f2e6, 0.6, true); + if (idx > 0) this.hud.hounSays(hounLine('newGame')); + else if (!hs.length) { + if (m.size !== 9 || Math.random() < 0.5) this.hud.hounSays(hounLine(`size${m.size}`)); + else this.hud.hounSays(this.humanColor === L.BLACK ? hounLine('youBlack') : hounLine('themBlack', { name: this.oppName })); } + await this.wait(900 * this.k); + if (this.stale(tok)) return; + this.save(); + this.nextTurn(tok); + } - // Invisible click zones for each intersection - for (let r = 0; r < SIZE; r++) { - for (let c = 0; c < SIZE; c++) { - const { x, y } = this.intToWorld(r, c); - const zone = this.add.zone(x, y, SQ - 4, SQ - 4) - .setInteractive({ useHandCursor: true }).setDepth(DEPTH.hint); - zone.on('pointerdown', () => this.onIntersectionClick(r, c)); - zone.on('pointerover', () => this.onIntersectionHover(r, c, true)); - zone.on('pointerout', () => this.onIntersectionHover(r, c, false)); + stale(tok) { return this.ended || tok !== this.token; } + + // ── 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; + let estimate = null; + if (this.phase === 'scoring' && this.scoreView) estimate = { lead: this.scoreView.black - this.scoreView.white }; + else if (this.settings.territory && this.estimate && !this.puz) estimate = this.estimate; + this.hud.refresh(this.gs, { + humanColor: this.humanColor, thinking: thinking || this.phase === 'ai', clocks: live, intro: this.phase === 'intro', + byo: this.puz ? null : this.byo, + match: this.match && !this.puz ? { games: this.match.games, human: this.match.human, ai: this.match.ai } : null, + estimate, puzzle: this.puz ? this.puzzleBar() : null, puzzleDone: !!this.puz && this.puz.state !== 'playing', + }); + const mode = this.hud.mode; + const H = (k, on) => this.hud.setButton(k, on); + if (mode === 'play') { + const mine = this.canMoveNow(); + H('b1', mine); H('b2', mine && this.undoStack.length > 0); H('b3', mine); + H('b4', true); H('b5', mine && this.gs.history.length >= 2); H('b6', true); + } else if (mode === 'scoring') { + const ok = this.phase === 'scoring' && !this.busy && !this.modal; + H('b1', ok); H('b2', ok); H('b3', false); H('b4', true); H('b5', ok); H('b6', true); + } else { + const free = !this.busy && !this.modal; + H('b1', free); H('b2', this.puzzleCanMove()); H('b3', free); H('b4', free && this.puz?.state !== 'shown'); H('b5', true); H('b6', true); + } + } + + setStatus(a, b = '') { this.hud?.setStatus(a, b); } + + // ── board marks ───────────────────────────────────────────────────────────── + clearOverlays() { + this.clearPreview(); + this.clearHint(); + this.overObjs.forEach((o) => o.destroy()); + this.overObjs = []; + this.terrG?.clear(); + this.markG?.clear(); + this.overG?.clear(); + this.cursorG?.clear(); + this.scoreView = null; + } + + /** Last move, the ko point, stones in atari, move numbers. */ + drawOverlays() { + const g = this.overG; + g.clear(); + this.overObjs.forEach((o) => o.destroy()); + this.overObjs = []; + if (!this.gs) return; + const gs = this.gs, size = gs.size, { R } = geom(size); + const lastEntry = gs.history[gs.history.length - 1]; + const lastSq = lastEntry && !lastEntry.pass && gs.board[lastEntry.sq] === lastEntry.color ? lastEntry.sq : -1; + if (this.settings.numbers) { + const at = new Map(); + gs.history.forEach((h, i) => { if (!h.pass) at.set(h.sq, i); }); + for (const [sq, i] of at) { + const v = gs.board[sq]; + if (!v || gs.history[i].color !== v) continue; + const p = this.stoneXY(sq); + const label = String(i + 1); + const fs = Math.round(R * (label.length >= 3 ? 0.62 : 0.8)); + const col = sq === lastSq ? '#e0402a' : v === L.BLACK ? '#f2eee2' : '#1c1b22'; + this.overObjs.push(this.add.text(p.x, p.y, label, { fontFamily: BOLD_FONT, fontSize: `${fs}px`, color: col }).setOrigin(0.5).setDepth(D.over)); + } + } else if (lastSq >= 0) { + const p = this.stoneXY(lastSq); + g.lineStyle(Math.max(2.5, R * 0.1), lastEntry.color === L.BLACK ? 0xf4f0e4 : 0x1c1b22, 0.95).strokeCircle(p.x, p.y, R * 0.42); + } + if (gs.ko >= 0 && gs.phase === 'playing') { + const p = pointXY(gs.ko, size); + g.lineStyle(3, 0xb83a24, 0.9).strokeRect(p.x - R * 0.45, p.y - R * 0.45, R * 0.9, R * 0.9); + } + if (this.settings.coach && !this.puz && gs.phase === 'playing') { + for (const grp of L.inAtari(gs.board, size, this.humanColor)) { + for (const s of grp.stones) { + const p = this.stoneXY(s); + g.lineStyle(3, 0xe04030, 0.85).strokeCircle(p.x, p.y, R * 1.04); + } } } + this.drawTerritory(); } - buildUI() { - const cx = BX + FULL / 2; - this.turnText = this.add.text(cx, BY + FULL + 14, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); - - const btnX = BX + FULL + FRAME + 90; - new Button(this, btnX, BY + 60, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 150, height: 46, fontSize: 20 }).setDepth(DEPTH.ui); - - new Button(this, btnX, BY + 124, 'New', - () => this.initGame(), - { variant: 'ghost', width: 150, height: 46, fontSize: 20 }).setDepth(DEPTH.ui); - - this.passBtn = new Button(this, btnX, BY + 200, 'Pass', - () => this.onPlayerPass(), - { variant: 'ghost', width: 150, height: 46, fontSize: 20 }); - this.passBtn.setDepth(DEPTH.ui); - - new Button(this, btnX, BY + 264, 'Resign', - () => this.onPlayerResign(), - { variant: 'ghost', width: 150, height: 46, fontSize: 20 }).setDepth(DEPTH.ui); + stoneXY(sq) { + const it = this.stones.get(sq); + return it ? { x: it.x, y: it.y } : pointXY(sq, this.size); } - buildPlayerCards() { - const opp = this.opponents[0]; - const r = 78; - const depth = DEPTH.ui; - const avatarX = BX / 2; - - // Opponent (white stones) - 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.add.text(avatarX, oppAY + r + 40, 'captures:', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5, 0).setDepth(depth + 2); - this.captureWhiteText = this.add.text(avatarX, oppAY + r + 58, '0', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(depth + 2); - - // Player (black stones) - const plrAY = BY + FULL - r - 20; - this.add.circle(avatarX, plrAY, r + 5, COLORS.accent, 0.5).setDepth(depth); - createPlayerPortrait(this, avatarX, plrAY, r, depth + 1, 'Go'); - 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.add.text(avatarX, plrAY - r - 40, 'captures:', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5, 1).setDepth(depth + 2); - this.captureBlackText = this.add.text(avatarX, plrAY - r - 58, '0', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(depth + 2); - } - - playOpponentEmotion(emotion) { this.opponentPortrait?.playEmotion(emotion); } - - // ── Game flow ───────────────────────────────────────────────────────────────── - - initGame() { - this.clearStones(); - this.clearHints(); - this.clearOverlays(); - this.clearTerritory(); - this.animating = false; - this.gs = createInitialState(); - this.renderAll(); - this.showTurnBanner('Your Turn — Black'); - if (this.passBtn) this.passBtn.setEnabled(true); - } - - renderAll() { - this.clearStones(); - this.clearHints(); - this.renderStones(); - this.updateCaptureDisplay(); - this.updateTurnText(); - } - - 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…'); - } - - updateCaptureDisplay() { - this.captureBlackText?.setText(String(this.gs.captures.black)); - this.captureWhiteText?.setText(String(this.gs.captures.white)); - } - - // ── Stone rendering ─────────────────────────────────────────────────────────── - - intToWorld(r, c) { return { x: GX + c * SQ, y: GY + r * SQ }; } - - clearStones() { - if (this.stoneObjs.length) { - for (const row of this.stoneObjs) - for (const g of row) { if (g) { this.tweens.killTweensOf(g); g.destroy(); } } + /** The study overlay (ownership) or the count (scoring). */ + drawTerritory() { + const g = this.terrG; + g.clear(); + if (!this.gs) return; + const size = this.size, { R } = geom(size); + if (this.puz) { this.drawRegion(); return; } + if (this.phase === 'scoring' || (this.gs.phase === 'over' && this.gs.score)) { + const sc = this.scoreView ?? this.gs.score; + if (!sc) return; + const dead = new Set(this.phase === 'scoring' ? this.dead : this.gs.dead); + sc.owner.forEach((o, sq) => { + if (!o) return; + if (this.gs.board[sq] && !dead.has(sq)) return; + const p = pointXY(sq, size), s = R * 0.5; + g.fillStyle(o === L.BLACK ? 0x16161c : 0xf4f0e6, 0.92).fillRect(p.x - s / 2, p.y - s / 2, s, s); + g.lineStyle(1, o === L.BLACK ? 0x000000 : 0x8a8270, 0.6).strokeRect(p.x - s / 2, p.y - s / 2, s, s); + }); + return; } - this.stoneObjs = Array.from({ length: SIZE }, () => Array(SIZE).fill(null)); + if (!this.settings.territory || !this.estimate || this.estimate.key !== this.gs.history.length) return; + const own = this.estimate.ownership; + this.gs.board.forEach((v, sq) => { + const o = own[sq]; + if (Math.abs(o) < 0.25) return; + const who = o > 0 ? L.BLACK : L.WHITE; + if (v === who) return; // a stone on its own side: nothing to show + const p = pointXY(sq, size), s = R * (v ? 0.55 : 0.45) * Math.min(1, Math.abs(o) + 0.2); + g.fillStyle(who === L.BLACK ? 0x16161c : 0xf4f0e6, 0.25 + Math.abs(o) * 0.6).fillRect(p.x - s / 2, p.y - s / 2, s, s); + }); } - clearHints() { - for (const o of this.hintObjs) o.destroy(); + requestEstimate() { + if (!this.settings.territory || this.puz || !this.gs || this.gs.phase !== 'playing') return; + const key = this.gs.history.length; + if (this.estKey === key) return; + this.estKey = key; + const tok = this.token; + const size = this.size; + this.engine.request('estimate', { pos: posOf(this.gs), playouts: size === 9 ? 2500 : size === 13 ? 1800 : 1400, ms: 500 }).then((res) => { + if (this.stale(tok) || !res || this.gs.history.length !== key) return; + this.estimate = { lead: res.blackLead, ownership: res.ownership, key }; + this.drawTerritory(); + this.refreshHud(); + }).catch(() => {}); + } + + clearPreview() { + for (const o of this.previewObjs) o.destroy(); + this.previewObjs = []; + this.previewG?.clear(); + this.hover = -1; + } + + /** Hover: a ghost stone with what it would capture, or a group's liberties. */ + preview(sq) { + if (sq === this.hover) return; + this.clearPreview(); + if (sq < 0 || !this.gs) return; + if (this.phase === 'scoring') { + if (this.gs.board[sq] && !this.busy && !this.modal) { + this.hover = sq; + const grp = L.groupAt(this.gs.board, this.size, sq); + const { R } = geom(this.size); + for (const s of grp.stones) { const p = this.stoneXY(s); this.previewG.lineStyle(3, 0xffd060, 0.9).strokeCircle(p.x, p.y, R * 0.98); } + } + return; + } + if (!(this.canMoveNow() || this.puzzleCanMove())) return; + const gs = this.gs, size = this.size, { R, SQ, scale } = geom(size); + this.hover = sq; + const g = this.previewG; + if (gs.board[sq]) { + if (!this.settings.preview) return; + const grp = L.groupAt(gs.board, size, sq); + const n = grp.libs.length; + const col = n === 1 ? 0xe04030 : n === 2 ? 0xe0a030 : 0x40a0d0; + for (const l of grp.libs) { const p = pointXY(l, size); g.fillStyle(col, 0.85).fillCircle(p.x, p.y, R * 0.2); } + const p = this.stoneXY(sq); + this.previewObjs.push(this.add.text(p.x + R * 0.7, p.y - R * 0.75, `${n} ${n === 1 ? 'liberty' : 'liberties'}`, { + fontFamily: SERIF, fontSize: `${Math.round(Math.max(14, SQ * 0.2))}px`, color: '#fff2d0', backgroundColor: '#2a1a10', padding: { x: 6, y: 2 }, + }).setOrigin(0, 1).setDepth(D.ghost + 1)); + return; + } + if (this.puz && !this.puz.regionSet.has(sq)) return; + const t = L.tryMove(gs, sq); + const p = pointXY(sq, size); + if (!t.ok) { + g.lineStyle(3, 0xb83a24, 0.7); + g.lineBetween(p.x - R * 0.3, p.y - R * 0.3, p.x + R * 0.3, p.y + R * 0.3); + g.lineBetween(p.x + R * 0.3, p.y - R * 0.3, p.x - R * 0.3, p.y + R * 0.3); + return; + } + const ghost = this.add.image(p.x, p.y, gs.turn === L.BLACK ? 'go-black' : 'go-white-0').setScale(scale / RES).setAlpha(0.5).setDepth(D.ghost); + this.previewObjs.push(ghost); + if (!this.settings.preview) return; + for (const c of t.captured) { const q = this.stoneXY(c); g.lineStyle(3, 0xe04030, 0.95).strokeCircle(q.x, q.y, R * 0.92); } + const libs = t.own.libs.length; + let label = t.captured.length ? `takes ${t.captured.length}` : ''; + if (libs === 1 && !t.captured.length) label = 'self-atari!'; + if (label) { + this.previewObjs.push(this.add.text(p.x, p.y - R * 1.1, label, { + fontFamily: BOLD_FONT, fontSize: `${Math.round(Math.max(15, SQ * 0.22))}px`, color: libs === 1 && !t.captured.length ? '#ffb0a0' : '#ffe8a8', + stroke: '#1a0c08', strokeThickness: 4, + }).setOrigin(0.5, 1).setDepth(D.ghost + 1)); + } + } + + // ── turns ─────────────────────────────────────────────────────────────────── + nextTurn(tok) { + if (this.stale(tok)) return; + this.clearPreview(); + if (this.gs.phase === 'scoring') { this.enterScoring(tok); return; } + if (this.gs.phase === 'over') { this.endGame(tok); return; } + this.turnStart = Date.now(); + if (this.gs.turn === this.humanColor) this.humanTurn(); + else this.aiTurn(tok); + } + + canMoveNow() { return this.phase === 'human' && !this.busy && !this.modal && this.gs?.phase === 'playing' && !this.puz; } + + humanTurn() { + this.phase = 'human'; + this.busy = false; + if (this.byo) this.byo.left = this.byo.secs * 1000; + const gs = this.gs, N = gs.size * gs.size; + const empty = L.counts(gs.board).empty; + if (!this.saidEndgame && empty < N * 0.35 && gs.history.length > N * 0.4) { + this.saidEndgame = true; + const l = hounLine('endgame'); + if (l) this.hud.hounSays(l); + } + const last = gs.history[gs.history.length - 1]; + let tip = 'Click a point to set down a stone. Hover to see what it would take.'; + if (last?.pass) tip = `${this.oppName} passed. Pass too (P) and we count, or play on.`; + else if (gs.history.length < 2) tip = gs.size === 9 ? 'The centre and the 3-3 and 4-4 points are all fine starts.' : 'Start in a corner: the 3-4, 4-4 or 3-3 point.'; + if (gs.ko >= 0) tip += `\nKo at ${L.notate(gs.ko, gs.size)}: you can't retake it yet.`; + this.setStatus('Your move', tip); + this.refreshHud(); + this.drawOverlays(); + this.drawCursor(); + this.requestEstimate(); + const p = this.input.activePointer; + if (p) this.preview(pointAt(p.x, p.y, this.size)); + } + + update(_t, dt) { + if (this.phase !== 'human' || !this.byo || this.modal || this.puz || this.gs?.phase !== 'playing') return; + const b = this.byo; + const s0 = Math.ceil(b.left / 1000); + b.left -= Math.min(dt, 250); + const s1 = Math.ceil(b.left / 1000); + if (s1 !== s0 && s1 <= 10 && s1 > 0) tick(this, s1 <= 5); + if (b.left <= 0) { + b.periods -= 1; + if (b.periods <= 0) { this.timeOut(); return; } + b.left = b.secs * 1000; + tick(this, true); + if (b.periods === 1) this.hud.hounSays(hounLine('lastPeriod')); + else toast(this, `A period used: ${b.periods} left.`, { depth: D.modal }); + this.refreshHud(); + } + } + + timeOut() { + const tok = this.token; + this.busy = true; + this.gs = L.timeLoss(this.gs, this.humanColor); + this.hud.hounSays(hounLine('timeLoss')); + this.endGame(tok); + } + + // ── input ─────────────────────────────────────────────────────────────────── + setCursor(c) { const cv = this.game?.canvas; if (cv && cv.style.cursor !== c) cv.style.cursor = c; } + + onPointerDown(p) { + if (this.ended || this.modal) return; + const sq = pointAt(p.x, p.y, this.size); + if (sq < 0) return; + if (this.phase === 'scoring') { this.toggleGroup(sq); return; } + if (this.puz) { this.puzzleClick(sq); return; } + if (!this.canMoveNow()) return; + this.cursor = null; + this.cursorG.clear(); + this.tryPlay(sq); + } + + onPointerMove(p) { + if (this.ended) return; + const active = this.canMoveNow() || this.puzzleCanMove() || (this.phase === 'scoring' && !this.busy && !this.modal); + if (!active) { if (this.hover >= 0) this.clearPreview(); return; } + const sq = pointAt(p.x, p.y, this.size); + this.preview(sq); + this.setCursor(sq >= 0 ? 'pointer' : 'default'); + } + + tryPlay(sq) { + if (!this.canMoveNow()) return; + const t = L.tryMove(this.gs, sq); + if (!t.ok) { + deny(this); + const kind = REASON_LINE[t.reason]; + if (kind) this.hud.hounSays(hounLine(kind)); + return; + } + this.commit(sq); + } + + /** A real eye: every neighbour ours, and the diagonals not held against us. */ + realEye(sq, color) { + const { board, size } = this.gs; + if (!L.eyeLike(board, size, sq, color)) return false; + const [r, c] = L.rc(sq, size); + let bad = 0, edge = false; + for (const [dr, dc] of [[-1, -1], [-1, 1], [1, -1], [1, 1]]) { + const rr = r + dr, cc = c + dc; + if (rr < 0 || cc < 0 || rr >= size || cc >= size) { edge = true; continue; } + if (board[rr * size + cc] === L.other(color)) bad++; + } + return edge ? bad === 0 : bad <= 1; + } + + async commit(sq, { warned = false } = {}) { + // Hōun's look before you leap + if (this.settings.coach && !warned) { + const t = L.tryMove(this.gs, sq); + let warn = null; + if (!t.captured.length && this.realEye(sq, this.gs.turn)) warn = hounLine('warnFillEye'); + else if (!t.captured.length && t.own.libs.length === 1 && t.own.stones.length >= 3) warn = hounLine('warnSelfAtari', { n: t.own.stones.length }); + if (warn) { + this.busy = true; + this.clearPreview(); + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'Hōun clears his throat…', text: warn, + 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; this.refreshHud(); }, + }); + return; + } + } + const tok = this.token; + this.pushUndo(); + this.clocks.human += Date.now() - this.turnStart; + 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; + this.nextTurn(tok); + } + + pushUndo() { + this.undoStack.push({ gs: this.gs, clocks: { ...this.clocks }, byo: this.byo ? { ...this.byo } : null }); + if (this.undoStack.length > 80) this.undoStack.shift(); + } + + humanPass() { + if (!this.canMoveNow()) return; + const tok = this.token; + this.pushUndo(); + this.clocks.human += Date.now() - this.turnStart; + this.clearPreview(); + this.clearHint(); + this.cursorG.clear(); + this.busy = true; + this.phase = 'animating'; + this.gs = L.pass(this.gs); + this.banner('You pass', 0xf0d890, 0.55, true); + const l = hounLine('humanPass'); + if (l && this.gs.phase === 'playing') this.hud.hounSays(l); + this.drawOverlays(); + this.refreshHud(); + this.save(); + this.wait(600 * this.k).then(() => this.nextTurn(tok)); + } + + // ── a move, animated ──────────────────────────────────────────────────────── + async playMove(sq, tok, { fast = false, quiet = false } = {}) { + const gs = this.gs; + const mover = gs.turn; + const human = mover === this.humanColor; + const side = human ? 'bottom' : 'top'; + const t = L.tryMove(gs, sq, mover); + if (!t.ok) return; + const from = this.hud.bowlPoint(side); + if (!fast) rustle(this); + this.overG.clear(); + this.overObjs.forEach((o) => o.destroy()); + this.overObjs = []; + await this.stones.place(sq, mover, from, { dur: (fast ? 220 : 380) * this.k, arc: fast ? 40 : 70 }); + if (this.stale(tok)) return; + pachi(this); + this.gs = L.play(gs, sq); + if (t.captured.length) { + const lid = this.hud.lids[side]; + const n = t.captured.length; + await this.stones.capture(t.captured, lid, { + stagger: Math.max(22, 70 - n * 4) * this.k, dur: 420 * this.k, + onLand: (i) => { if (this.stale(tok)) return; lid.add(1, L.other(mover)); if (i % 2 === 0) clatter(this, 1); }, + }); + if (this.stale(tok)) return; + if (!quiet) this.afterCapture(n, human, sq); + } + if (!quiet && !this.puz) { + if (this.gs.ko >= 0 && !this.saidKo) { + this.saidKo = true; + this.hud.hounSays(hounLine('ko')); + const ol = opponentLine('ko', this.tier); + if (ol) this.hud.say(ol); + } + if (!human) this.checkAtari(); + } + this.drawOverlays(); + this.refreshHud(); + if (this.gs.phase === 'playing') this.save(); + } + + afterCapture(n, human, sq) { + const p = pointXY(sq, this.size); + if (n >= 2) this.callout(`×${n}`, p.x, p.y - 50, human ? 0xffe8a8 : 0xff9a84); + this.sparks(p.x, p.y, Math.min(18, 6 + n * 2)); + if (this.puz) return; + if (human) { + const l = n >= 5 ? hounLine('humanBigCapture', { n }) : Math.random() < 0.6 ? hounLine('humanCapture', { n }) : null; + if (l) this.hud.hounSays(l); + if (Math.random() < 0.5) this.hud.say(opponentLine('lost', this.tier)); + this.hud.emotion('upset'); + } else { + const l = n >= 5 ? hounLine('aiBigCapture', { n }) : hounLine('aiCapture', { n }); + if (l) this.hud.hounSays(l); + if (Math.random() < 0.5) this.hud.say(opponentLine('capture', this.tier)); + this.hud.emotion('happy'); + } + } + + /** Warn (once per group) when the opponent's move puts your stones in atari. */ + checkAtari() { + if (!this.settings.coach) return; + const groups = L.inAtari(this.gs.board, this.size, this.humanColor); + const fresh = groups.filter((g) => !this.atariSeen.has(`${Math.min(...g.stones)}:${g.stones.length}`)); + groups.forEach((g) => this.atariSeen.add(`${Math.min(...g.stones)}:${g.stones.length}`)); + if (!fresh.length) return; + const big = fresh.sort((a, b) => b.stones.length - a.stones.length)[0]; + this.hud.hounSays(hounLine('atariYou', { n: big.stones.length, move: L.notate(big.stones[0], this.size) })); + } + + // ── undo / hint ───────────────────────────────────────────────────────────── + undo() { + if (!this.canMoveNow() || !this.undoStack.length) return; + const snap = this.undoStack.pop(); + const tok = ++this.token; + this.engine.forget(); + this.clearOverlays(); + this.gs = snap.gs; + this.clocks = snap.clocks; + if (snap.byo) this.byo = snap.byo; + this.stones.sync(this.gs.board); + this.estKey = null; + rustle(this); + const l = hounLine('undo'); + if (l) this.hud.hounSays(l); + this.save(); + this.nextTurn(tok); + } + + async showHint() { + if (!this.canMoveNow()) return; + const tok = this.token; + this.clearHint(); + this.busy = true; + this.setStatus('Hōun looks…', 'He sets down his tea and studies the board.'); + this.refreshHud(); + const size = this.size; + let h = null; + try { h = await this.engine.request('hint', { pos: posOf(this.gs), playouts: size === 9 ? 9000 : size === 13 ? 7000 : 5000, ms: 1300 }); } catch (_) { h = null; } + if (this.stale(tok) || this.phase !== 'human') return; + this.busy = false; + this.refreshHud(); + if (!h) { this.setStatus('Your move', 'Hōun shrugs. Trust your eyes.'); return; } + const standing = Math.abs(h.lead) < 1.5 ? 'He reckons it is close.' : `He reckons you are ${h.lead > 0 ? 'ahead' : 'behind'} by about ${Math.round(Math.abs(h.lead))}.`; + if (h.best < 0) { + this.hud.hounSays(hounLine('hintPass')); + this.setStatus('Hōun\'s hint', `Pass. ${standing}`); + return; + } + const n = L.notate(h.best, size); + const reason = describeIdea(this.gs, h.best); + const p = pointXY(h.best, size); + const { R } = geom(size); + const ring = this.add.image(p.x, p.y, 'go-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.hounSays(hounLine('hint', { move: n, reason }), { hold: 10000 }); + this.setStatus('Hōun\'s hint', `${n}: it ${reason}. ${standing}`); + } + + clearHint() { + for (const o of this.hintObjs ?? []) o.destroy(); this.hintObjs = []; } - clearOverlays() { - for (const o of this.overlayObjs) o.destroy(); - this.overlayObjs = []; - } - - clearTerritory() { - for (const o of this.terrObjs) o.destroy(); - this.terrObjs = []; - } - - renderStones() { - 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.intToWorld(r, c); - const g = this.add.graphics().setPosition(x, y).setDepth(DEPTH.stone); - this.drawStoneGraphics(g, cell); - this.stoneObjs[r][c] = g; - } + // ── the opponent ──────────────────────────────────────────────────────────── + async aiTurn(tok) { + if (this.stale(tok)) return; + this.phase = 'ai'; + this.busy = true; + const fast = this.settings.skipAI; + const t = aiTiming(this.skill, fast ? 0.25 : this.k); + this.setStatus(`${this.oppName} is thinking…`, this.gs.history.length ? '' : 'They settle on their cushion and look at the empty board.'); + this.refreshHud(true); + this.drawOverlays(); + const started = Date.now(); + let res = null; + try { res = await this.engine.request('move', { pos: posOf(this.gs), skill: this.skill }); } catch (_) { res = null; } + if (this.stale(tok)) return; + await this.wait(Math.max(0, (fast ? 60 : t.think) - (Date.now() - started))); + await this.untilNoModal(tok); + if (this.stale(tok)) return; + if (res?.resign) { this.aiResigns(tok); return; } + let sq = res ? res.sq : -1; + if (sq >= 0 && !L.isLegal(this.gs, sq)) sq = -1; + if (!res) { + // the engine failed: any legal move that doesn't fill its own eye + const legal = L.legalMoves(this.gs).filter((s) => !L.eyeLike(this.gs.board, this.size, s, this.gs.turn)); + sq = legal.length ? legal[Math.floor(Math.random() * legal.length)] : -1; } - } - - drawStoneGraphics(g, color) { - g.clear(); - const fill = color === 'black' ? C.bFill : C.wFill; - const edge = color === 'black' ? C.bEdge : C.wEdge; - const hi = color === 'black' ? C.bHi : C.wHi; - - // Shadow - g.fillStyle(0x000000, 0.32); - g.fillCircle(3, 5, SR); - // Edge ring - g.fillStyle(edge, 1); - g.fillCircle(0, 0, SR); - // Main fill - g.fillStyle(fill, 1); - g.fillCircle(0, 0, SR - 2); - // Top-left highlight arc - g.lineStyle(4, hi, color === 'black' ? 0.38 : 0.72); - g.beginPath(); - g.arc(0, 0, SR - 7, Phaser.Math.DegToRad(205), Phaser.Math.DegToRad(315)); - g.strokePath(); - } - - // ── Hover ghost stone ───────────────────────────────────────────────────────── - - onIntersectionHover(r, c, entering) { - if (this.animating || this.gs.phase !== 'playing' || this.gs.turn !== 'black') return; - if (this._ghostGfx) { this._ghostGfx.destroy(); this._ghostGfx = null; } - if (!entering || !isValidMove(this.gs, r, c, 'black')) return; - const { x, y } = this.intToWorld(r, c); - const g = this.add.graphics().setPosition(x, y).setDepth(DEPTH.hint); - g.fillStyle(C.bFill, 0.38); - g.fillCircle(0, 0, SR); - this._ghostGfx = g; - } - - // ── Move placement ──────────────────────────────────────────────────────────── - - onIntersectionClick(r, c) { - if (this.animating || this.gs.phase !== 'playing' || this.gs.turn !== 'black') return; - if (!isValidMove(this.gs, r, c, 'black')) return; - - if (this._ghostGfx) { this._ghostGfx.destroy(); this._ghostGfx = null; } - this.placeStone(r, c, 'black'); - } - - placeStone(r, c, color) { - this.animating = true; - this.updateTurnText(); - - // Identify captures before applying state (for animation) - const caps = findCaptures(this.gs.board, r, c, color); - const capturedKeys = new Set(); - for (const g of caps) for (const k of g) capturedKeys.add(k); - - // Update game state - this.gs = applyMove(this.gs, r, c); - - // Animate capture removals (burst) - for (const key of capturedKeys) { - const [cr, cc] = key.split(',').map(Number); - const existing = this.stoneObjs[cr][cc]; - if (existing) this.animateCaptureStone(existing, cr, cc); - } - - // Place new stone with bounce - const { x, y } = this.intToWorld(r, c); - const g = this.add.graphics().setPosition(x, y).setDepth(DEPTH.stone); - this.drawStoneGraphics(g, color); - g.setScale(0.1); - this.stoneObjs[r][c] = g; - - // Two-step spring bounce - this.tweens.add({ - targets: g, scaleX: 1.18, scaleY: 1.18, duration: 80, ease: 'Quad.easeOut', - onComplete: () => { - this.tweens.add({ - targets: g, scaleX: 1, scaleY: 1, duration: 60, ease: 'Quad.easeIn', - onComplete: () => { - playSound(this, SFX.PIECE_CLICK); - this.animating = false; - this.updateCaptureDisplay(); - this.clearHints(); - - if (capturedKeys.size > 0) this.playOpponentEmotion(color === 'black' ? 'upset' : 'happy'); - if (isGameOver(this.gs)) { this.onGameOver(); return; } - - if (this.gs.turn === 'white') { - this.startAITurn(); - } - // else: human gets another turn (opponent passed — handled via applyPass path) - }, - }); - }, - }); - } - - animateCaptureStone(gfx, r, c) { - this.stoneObjs[r][c] = null; - const baseDelay = 30 * (Math.abs(r - 4) + Math.abs(c - 4)); - this.time.delayedCall(baseDelay, () => { - this.tweens.add({ - targets: gfx, - scaleX: 1.6, scaleY: 1.6, alpha: 0, - duration: 260, ease: 'Back.easeIn', - onComplete: () => gfx.destroy(), - }); - }); - } - - // ── Pass / Resign ───────────────────────────────────────────────────────────── - - onPlayerPass() { - if (this.animating || this.gs.phase !== 'playing' || this.gs.turn !== 'black') return; - this.showPassStamp('You passed'); - this.gs = applyPass(this.gs); - this.updateCaptureDisplay(); - if (isGameOver(this.gs)) { this.onGameOver(); return; } - this.startAITurn(); - } - - onPlayerResign() { - if (this.gs.phase !== 'playing') return; - this.gs.phase = 'game_over'; - this.gs.winner = 'white'; - this.onGameOver(); - } - - showPassStamp(text) { - const cx = BX + FULL / 2; - const stamp = this.add.text(cx, BY + FULL / 2, text, { - fontFamily: 'Righteous', fontSize: '52px', - color: '#c0392b', alpha: 0, - }).setOrigin(0.5).setDepth(DEPTH.banner).setAngle(-12); - this.tweens.add({ - targets: stamp, alpha: 0.85, scaleX: 1, scaleY: 1, duration: 180, - onComplete: () => { - this.time.delayedCall(900, () => { - this.tweens.add({ targets: stamp, alpha: 0, duration: 280, onComplete: () => stamp.destroy() }); - }); - }, - }); - } - - // ── 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) { - // AI passes - this.showPassStamp(`${this.opponents[0]?.name ?? 'Opponent'} passed`); - this.gs = applyPass(this.gs); - this.updateCaptureDisplay(); - if (isGameOver(this.gs)) { this.onGameOver(); return; } - this.showTurnBanner('Your Turn'); - this.updateTurnText(); + this.clocks.ai += Date.now() - this.turnStart; + if (sq < 0) { + this.gs = L.pass(this.gs); + this.banner(`${this.oppName} passes`.toUpperCase(), 0xf0d890, 0.55, true); + this.hud.say(opponentLine('pass', this.tier)); + if (this.gs.phase === 'playing') this.hud.hounSays(hounLine('aiPass', { name: this.oppName })); + this.drawOverlays(); + this.refreshHud(); + this.save(); + await this.wait(1000 * this.k); + this.nextTurn(tok); return; } - - // Identify captures for animation - const caps = findCaptures(this.gs.board, move.r, move.c, 'white'); - const capturedKeys = new Set(); - for (const g of caps) for (const k of g) capturedKeys.add(k); - - this.gs = applyMove(this.gs, move.r, move.c); - - // Animate capture removals - for (const key of capturedKeys) { - const [cr, cc] = key.split(',').map(Number); - const existing = this.stoneObjs[cr][cc]; - if (existing) this.animateCaptureStone(existing, cr, cc); + if (!fast) { + // their hand hovers over the point for a moment + const p = pointXY(sq, this.size); + const ghost = this.add.image(p.x, p.y - 10, this.aiColor === L.BLACK ? 'go-black' : 'go-white-0').setScale(geom(this.size).scale / RES).setAlpha(0).setDepth(D.ghost); + this.tweens.add({ targets: ghost, alpha: 0.3, y: p.y, duration: 220 }); + await this.wait(t.hesitate * 0.5); + ghost.destroy(); + await this.untilNoModal(tok); + if (this.stale(tok)) return; } + this.phase = 'animating'; + await this.playMove(sq, tok, { fast }); + if (this.stale(tok)) return; + await this.wait(fast ? 40 : Math.min(220, t.between * 0.5)); + this.nextTurn(tok); + } - // Place AI stone with bounce - const { x, y } = this.intToWorld(move.r, move.c); - const g = this.add.graphics().setPosition(x, y).setDepth(DEPTH.stone); - this.drawStoneGraphics(g, 'white'); - g.setScale(0.1); - this.stoneObjs[move.r][move.c] = g; + aiResigns(tok) { + if (this.stale(tok)) return; + this.gs = L.resign(this.gs, this.aiColor); + this.hud.say(opponentLine('resign', this.tier)); + this.hud.hounSays(hounLine('aiResign', { name: this.oppName })); + this.endGame(tok); + } - this.tweens.add({ - targets: g, scaleX: 1.18, scaleY: 1.18, duration: 80, ease: 'Quad.easeOut', - onComplete: () => { - this.tweens.add({ - targets: g, scaleX: 1, scaleY: 1, duration: 60, ease: 'Quad.easeIn', - onComplete: () => { - playSound(this, SFX.PIECE_CLICK); - this.updateCaptureDisplay(); - if (capturedKeys.size > 0) this.playOpponentEmotion('happy'); - if (isGameOver(this.gs)) { this.onGameOver(); return; } - this.showTurnBanner('Your Turn'); - this.updateTurnText(); - }, - }); - }, + async untilNoModal(tok) { + while (this.modal && !this.stale(tok)) await this.wait(120); + } + + resign() { + if (!(this.canMoveNow() || (this.phase === 'scoring' && !this.busy))) return; + this.confirmThen('Resign this game?', `${this.oppName} takes the game.`, () => { + this.hud.hounSays(hounLine('resign')); + if (this.gs.phase === 'scoring') this.gs = L.resumePlay(this.gs); + this.stones.setDead([]); + this.gs = L.resign(this.gs, this.humanColor); + this.endGame(this.token); }); } - // ── Banners ─────────────────────────────────────────────────────────────────── - - showTurnBanner(text) { - const cx = BX + FULL / 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(1100, () => { - this.tweens.add({ targets: banner, y: BY - 70, alpha: 0, duration: 220, onComplete: () => banner.destroy() }); - }); - }, - }); + // ── the count ─────────────────────────────────────────────────────────────── + async enterScoring(tok) { + this.phase = 'scoring'; + this.busy = true; + this.hud.setMode('scoring'); + this.clearPreview(); + this.clearHint(); + this.cursorG.clear(); + this.setStatus('Counting', 'Hōun is looking over the groups…'); + this.refreshHud(); + const size = this.size; + let res = null; + try { res = await this.engine.request('dead', { pos: posOf(this.gs), playouts: size === 9 ? 4000 : size === 13 ? 3200 : 2600, ms: size === 9 ? 1200 : 1800 }); } catch (_) { res = null; } + if (this.stale(tok)) return; + this.dead = res?.dead ?? []; + this.engineDead = new Set(this.dead); + this.busy = false; + bell(this, 0.035); + this.hud.hounSays(hounLine('scoring'), { hold: 14000 }); + this.drawScoring(); + this.save(); } - // ── Game over + territory reveal ────────────────────────────────────────────── + drawScoring() { + this.stones.setDead(this.dead); + this.scoreView = L.scoreGame(this.gs, this.dead); + const sc = this.scoreView; + this.drawOverlays(); + const lead = sc.black === sc.white ? 'Even: jigo.' : `${sc.black > sc.white ? 'Black' : 'White'} by ${fmt(sc.margin)}.`; + const how = this.gs.rules === 'chinese' ? 'stones + territory' : 'territory + prisoners'; + this.setStatus(`B ${fmt(sc.black)} · W ${fmt(sc.white)}`, `${lead} (${how}, komi ${this.gs.komi})\nClick a group to mark it dead or alive, then Accept.`); + this.refreshHud(); + } - onGameOver() { - if (this.passBtn) this.passBtn.setEnabled(false); - const winner = getWinner(this.gs); - const isHuman = winner === 'black'; - const name = this.opponents[0]?.name ?? 'Opponent'; - this.playOpponentEmotion(isHuman ? 'upset' : 'happy'); - this.recordResult(isHuman ? 'win' : 'loss'); + toggleGroup(sq) { + if (this.phase !== 'scoring' || this.busy || this.modal || !this.gs.board[sq]) return; + this.dead = L.toggleDead(this.gs, this.dead, sq); + pachi(this, { vol: 0.06 }); + this.clearPreview(); + this.drawScoring(); + } - const final = getFinalScore(this.gs); - - // Territory reveal animation, then show result panel - this.time.delayedCall(300, () => { - this.animateTerritoryReveal(() => { - this.time.delayedCall(500, () => this.showEndPanel(winner, final)); - }); - }); - - if (isHuman) { - const cx = GX + (SIZE - 1) * SQ / 2; - const cy = GY + (SIZE - 1) * SQ / 2; - const emitter = this.add.particles(cx, cy, 'goParticle', { - speed: { min: 120, max: 450 }, lifespan: 1400, - scale: { start: 1.4, end: 0 }, alpha: { start: 1, end: 0 }, - quantity: 4, frequency: 30, angle: { min: 0, max: 360 }, - tint: [C.selGold, 0xffffff, COLORS.accent], - }).setDepth(DEPTH.banner); - this.time.delayedCall(2000, () => emitter.destroy()); + acceptScore() { + if (this.phase !== 'scoring' || this.busy) return; + // the opponent won't agree that its living stones are dead + const disputed = this.dead.filter((sq) => this.gs.board[sq] === this.aiColor && !this.engineDead.has(sq)); + if (disputed.length) { + this.hud.say(this.tier === 'novice' ? 'Hey, those are alive!' : 'Those stones are not dead.'); + this.hud.hounSays(hounLine('dispute', { name: this.oppName })); + this.resumeFromScoring(); + return; } + this.gs = L.finish(this.gs, this.dead); + this.endGame(this.token); } - animateTerritoryReveal(onDone) { - const board = this.gs.board; - const visited = Array.from({ length: SIZE }, () => Array(SIZE).fill(false)); - const regions = []; + resumeFromScoring() { + if (this.phase !== 'scoring') return; + const tok = ++this.token; + this.engine.forget(); + this.gs = L.resumePlay(this.gs); + this.dead = []; + this.stones.setDead([]); + this.scoreView = null; + this.hud.setMode('play'); + this.clearOverlays(); + this.hud.hounSays(hounLine('resume')); + this.save(); + this.nextTurn(tok); + } - for (let r = 0; r < SIZE; r++) { - for (let c = 0; c < SIZE; c++) { - if (board[r][c] !== null || visited[r][c]) continue; - const region = []; - const stack = [[r, c]]; - let touchesB = false, touchesW = false; - while (stack.length) { - const [cr, cc] = stack.pop(); - if (cr < 0 || cr >= SIZE || cc < 0 || cc >= SIZE || visited[cr][cc]) continue; - visited[cr][cc] = true; - if (board[cr][cc] === 'black') { touchesB = true; continue; } - if (board[cr][cc] === 'white') { touchesW = true; continue; } - region.push([cr, cc]); - stack.push([cr-1,cc],[cr+1,cc],[cr,cc-1],[cr,cc+1]); - } - let owner = null; - if (touchesB && !touchesW) owner = 'black'; - else if (touchesW && !touchesB) owner = 'white'; - if (owner) regions.push({ owner, cells: region }); + // ── end of a game / match ─────────────────────────────────────────────────── + async endGame(tok) { + if (this.phase === 'over' || this.stale(tok)) return; + this.phase = 'over'; + this.busy = true; + this.clearPreview(); + this.clearHint(); + this.cursorG.clear(); + this.hud.setMode('play'); + const gs = this.gs; + const m = this.match; + const result = gs.winner === 'draw' ? 'draw' : gs.winner === this.humanColor ? 'human' : 'ai'; + if (result === 'human') m.human += 1; else if (result === 'ai') m.ai += 1; else { m.human += 0.5; m.ai += 0.5; } + const sc = gs.score; + const margin = sc ? sc[this.humanColor] - sc[this.aiColor] : (result === 'human' ? 1 : result === 'ai' ? -1 : 0); + m.results.push({ result, humanColor: this.humanColor, score: L.resultString(gs), margin, 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 === 'score') { + this.hud.hounSays(hounLine('count')); + await this.countOut(tok); + if (this.stale(tok)) return; + } + this.setStatus(r.title, r.why); + this.stones.setDead([]); + if (result === 'human') { + sting(this, 'win'); playSound(this, SFX.CASINO_WIN); + this.banner('YOU WIN', 0xf0d890, 0.8); + this.petalBurst(); + this.hud.say(opponentLine('lose', this.tier)); this.hud.emotion('upset'); + this.hud.hounSays(hounLine('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.hounSays(hounLine('loss')); + } else { + sting(this, 'draw'); + this.banner('JIGO', 0xe8dcc0, 0.8); + this.hud.say(opponentLine('draw', this.tier)); + this.hud.hounSays(hounLine('draw')); + } + await this.wait(2800); + if (this.stale(tok)) return; + if (over) this.matchOver(); + else this.betweenGames(); + } + + /** Dead stones into the lids, then the territory, then the totals. */ + async countOut(tok) { + const gs = this.gs; + const sideOf = (c) => (c === this.humanColor ? 'bottom' : 'top'); + // the lids show captures only until the dead stones land + for (const c of [L.BLACK, L.WHITE]) this.hud.lids[sideOf(c)].set(gs.captures[c], L.other(c)); + for (const col of [L.BLACK, L.WHITE]) { + const ds = gs.dead.filter((sq) => gs.board[sq] === col); + if (!ds.length) continue; + const lid = this.hud.lids[sideOf(L.other(col))]; + await this.stones.capture(ds, lid, { stagger: 45, dur: 380, onLand: (i) => { lid.add(1, col); if (i % 2 === 0) clatter(this, 1); } }); + if (this.stale(tok)) return; + } + this.scoreView = gs.score; + this.terrG.setAlpha(0); + this.drawTerritory(); + this.tweens.add({ targets: this.terrG, alpha: 1, duration: 700 }); + await this.wait(800); + if (this.stale(tok)) return; + const sc = gs.score; + this.callout(`${fmt(sc.black)} – ${fmt(sc.white)}`, BCX, BY + 420, 0xf3ead2); + await this.wait(1000); + } + + 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.hounSays(hounLine('matchWin')); + else if (m.ai > m.human) this.hud.hounSays(hounLine('matchLoss')); + else this.hud.hounSays(hounLine('matchDraw')); + } + const gs = this.gs; + const short = gs.history.filter((h) => !h.pass).length < 6; + this.hud.hidePortraits(); + this.phase = 'review'; + 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: short ? null : this.makeReview(gs), + onPlayAgain: () => { this.reviewTok++; this.modal = null; this.hud.showPortraits(); this.openSetupCard(); }, + onSave: () => this.saveSgf(gs), + onMenu: () => { this.reviewTok++; this.scene.start('GameMenu'); }, + }); + } + + /** The engine's position at move n of a game (for the review). */ + reviewPos(gs, n) { + const N = gs.history.length; + const pos = L.positionAfter(gs, n); + const turn = n < N ? gs.history[n].color : (N ? L.other(gs.history[N - 1].color) : gs.turn); + return { + size: gs.size, board: pos.board, turn, komi: gs.komi, rules: gs.rules, ko: -1, last: null, last2: null, + passes: 0, captures: pos.captures, forbidden: [], moveNo: n, + }; + } + + makeReview(gs) { + const myTok = ++this.reviewTok; + return async (onChunk) => { + const N = gs.history.length; + const positions = []; + for (let n = 0; n <= N; n++) positions.push(this.reviewPos(gs, n)); + const [playouts, ms] = { 9: [800, 160], 13: [650, 190], 19: [500, 220] }[gs.size] ?? [600, 200]; + const chunk = 6; + for (let s = 0; s < positions.length; s += chunk) { + if (this.ended || myTok !== this.reviewTok) return; + const list = await this.engine.request('review', { positions: positions.slice(s, s + chunk), playouts, ms }); + if (this.ended || myTok !== this.reviewTok) return; + onChunk(s, list ?? []); } + }; + } + + 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.sizes = rec.sizes ?? {}; + rec.vs = rec.vs ?? {}; + const v = (rec.sizes[this.gs.size] = rec.sizes[this.gs.size] ?? { 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'; + const margin = m.results.reduce((a, r) => a + Math.max(0, Math.round(r.margin ?? 0)), 0); + await api.post('/history/single-player', { + slug: 'go', score: Math.round(m.human * 100 + margin), opponentScores: [Math.round(m.ai * 100)], result, + }); + } + + // ── records ───────────────────────────────────────────────────────────────── + sgfNames() { + const me = auth.user?.username ?? 'You'; + return this.humanColor === L.BLACK ? { black: me, white: this.oppName } : { black: this.oppName, white: me }; + } + + saveSgf(gs = this.gs) { + if (!gs) return; + const ok = downloadSgf(gs, this.sgfNames()); + toast(this, ok ? 'The record is saved as an SGF file.' : 'The record could not be saved.', { depth: D.modal + 10 }); + } + + async openSgf() { + const tok = ++this.token; + this.engine.forget(); + this.busy = true; + this.hud.hidePortraits(); + const text = await pickSgfFile(); + if (this.stale(tok)) return; + if (!text) { this.hud.showPortraits(); this.backToBoard(); return; } + let parsed; + try { parsed = parseSgf(text); } catch (e) { + toast(this, `Hōun squints at the file: ${e?.message ?? 'it is not a game record he can read'}.`, { depth: D.modal }); + this.hud.showPortraits(); + this.backToBoard(); + return; } + this.showImported(parsed); + } - if (regions.length === 0) { onDone(); return; } + showImported({ gs, info }) { + this.token++; + this.phase = 'review'; + this.busy = true; + this.puz = null; + this.clearOverlays(); + this.setBoardSize(gs.size); + this.stones.build(gs.board, gs.size); + gs.recordResult = info.result ? `Result ${info.result}` : ''; + this.hud.hidePortraits(); + this.modal = openEndScreen(this, { + gs, names: { black: info.black, white: info.white }, depth: D.end, review: gs.history.length > 1 ? this.makeReview(gs) : null, + onMenu: () => { this.reviewTok++; this.modal = null; this.hud.showPortraits(); this.backToBoard(); }, menuLabel: 'Close the Record', + }); + } - // Flatten and sort left-to-right for the sweep animation - const allCells = regions.flatMap(({ owner, cells }) => cells.map(([r, c]) => ({ r, c, owner }))); - allCells.sort((a, b) => a.c !== b.c ? a.c - b.c : a.r - b.r); + /** Back to whatever was going on: a saved game, or the setup card. */ + backToBoard() { + const save = this.loadSave(); + if (save) this.resume(save); else this.openSetupCard(); + } - let revealed = 0; - for (let i = 0; i < allCells.length; i++) { - const { r, c, owner } = allCells[i]; - const { x, y } = this.intToWorld(r, c); - const gfx = this.add.graphics().setDepth(DEPTH.territory); - gfx.fillStyle(owner === 'black' ? C.bFill : C.wFill, 0.0); - gfx.fillCircle(x, y, SR * 0.65); - this.terrObjs.push(gfx); + // ── Hōun's problems ───────────────────────────────────────────────────────── + enterPuzzles(daily = false) { + if (this.match && this.gs && !this.puz && ['human', 'ai', 'animating', 'scoring'].includes(this.phase)) this.save(); + const st = PZ.loadPuzzleState(); + if (daily) { + const d = PZ.dailyPuzzle(); + this.startPuzzle(d.puzzle, { daily: true, number: d.number, key: d.key }); + } else this.startPuzzle(PZ.nextLadderPuzzle(st)); + } - this.time.delayedCall(i * 18, () => { - this.tweens.add({ - targets: gfx, alpha: owner === 'black' ? 0.6 : 0.5, - duration: 220, ease: 'Quad.easeOut', - onComplete: () => { - revealed++; - if (revealed === allCells.length) onDone(); - }, - }); - // Recolor the graphics properly - gfx.clear(); - gfx.fillStyle(owner === 'black' ? C.bFill : C.wFill, 1); - gfx.fillCircle(x, y, SR * 0.65); - gfx.setAlpha(0); + puzzleGame(setup) { + const black = [], white = []; + setup.board.forEach((v, sq) => { if (v === L.BLACK) black.push(sq); else if (v === L.WHITE) white.push(sq); }); + return L.createGame({ size: setup.size, setup: { black, white }, turn: L.BLACK, komi: 0 }); + } + + startPuzzle(p, { daily = false, number = null, key = null } = {}) { + this.token++; + this.engine.forget(); + const setup = PZ.puzzleSetup(p); + const st = PZ.loadPuzzleState(); + this.puz = { + p, setup, prob: PZ.toProb(setup, setup.board, L.BLACK), human: L.BLACK, state: 'playing', + rated: daily ? !!st.daily[key] : false, assisted: false, daily, number, key, regionSet: new Set(setup.region), moves: [], + }; + this.gs = this.puzzleGame(setup); + this.phase = 'puzzle'; + this.busy = false; + this.undoStack = []; + this.clearOverlays(); + this.setBoardSize(setup.size); + this.stones.build(setup.board, setup.size); + this.hud.setMode('puzzle'); + this.hud.setSkillVisible(false); + this.drawOverlays(); + this.hud.hounSays(hounLine(p.goal === 'kill' ? 'puzzleKill' : 'puzzleLive'), { hold: 12000 }); + this.puzzleStatus(); + this.refreshHud(); + } + + puzzleBar() { + const z = this.puz; + if (!z) return null; + const head = z.daily ? `Problem of the day #${z.number}` : `Hōun's problem · rating ${z.p.rating}`; + return `${head} · ${z.p.goal === 'kill' ? 'Black to kill' : 'Black to live'}`; + } + + puzzleStatus(extra = '') { + const z = this.puz; + const st = PZ.loadPuzzleState(); + const goal = z.p.goal === 'kill' ? 'Black to kill' : 'Black to live'; + const what = z.p.goal === 'kill' ? `White's group can't be allowed two eyes.` : `Your group needs two eyes, or seki.`; + const sub = `${what} ${z.p.kind === 'corner' ? 'In the corner' : 'On the side'}: ${z.p.shape}.\nYour rating ${st.rating} · solved ${Object.keys(st.solved).length} of ${PZ.PUZZLES.length}${extra ? `\n${extra}` : ''}`; + this.setStatus(goal, sub); + } + + puzzleCanMove() { + const z = this.puz; + return !!z && this.phase === 'puzzle' && z.state === 'playing' && !this.busy && !this.modal && this.gs?.turn === z.human; + } + + /** The problem's points, softly lit. */ + drawRegion() { + const z = this.puz, g = this.terrG; + if (!z) return; + const { SQ } = geom(this.size); + for (const sq of z.setup.region) { + const p = pointXY(sq, this.size); + g.fillStyle(0xfff2c0, 0.22).fillRoundedRect(p.x - SQ * 0.46, p.y - SQ * 0.46, SQ * 0.92, SQ * 0.92, 6); + } + } + + async puzzleClick(sq) { + const z = this.puz; + if (!this.puzzleCanMove() || sq < 0) return; + if (!z.regionSet.has(sq)) { + deny(this); + if (!this.saidRegion) { this.saidRegion = true; toast(this, 'Play inside the problem: the lit points.', { depth: D.modal }); } + return; + } + const nextProb = T.play(z.prob, sq); + if (!nextProb || !L.isLegal(this.gs, sq)) { deny(this); return; } + const tok = this.token; + this.busy = true; + this.clearPreview(); + this.clearHint(); + this.cursorG.clear(); + this.refreshHud(); + z.prob = nextProb; + z.moves.push(sq); + await this.playMove(sq, tok); + if (this.stale(tok)) return; + this.setStatus('Hōun reads…', 'He follows every answer to the end.'); + let chk = null; + try { chk = await this.engine.request('puzzleCheck', { prob: z.prob, human: z.human }); } catch (_) { chk = null; } + if (this.stale(tok)) return; + if (!chk) chk = { wins: true, settled: false, terminal: null }; + if (!chk.wins) { await this.puzzleWrong(tok); return; } + if (chk.settled || chk.terminal) { this.puzzleSolved(tok); return; } + if (Math.random() < 0.6) this.hud.hounSays(hounLine('puzzleGood')); + await this.puzzleReply(tok); + if (this.stale(tok)) return; + const term = T.terminal(z.prob); + if (term) { + if ((term === 'dead') === (z.human === z.prob.attacker)) this.puzzleSolved(tok); + else await this.puzzleWrong(tok, { replied: true }); + return; + } + this.busy = false; + this.puzzleStatus(); + this.refreshHud(); + } + + /** The computer answers in a problem. */ + async puzzleReply(tok) { + const z = this.puz; + let r = null; + try { r = await this.engine.request('puzzleReply', { prob: z.prob }); } catch (_) { r = null; } + if (this.stale(tok)) return; + await this.wait(320 * this.k); + if (this.stale(tok)) return; + const sq = r?.sq ?? -1; + const np = sq >= 0 && L.isLegal(this.gs, sq) ? T.play(z.prob, sq) : null; + if (np) { + z.prob = np; + z.moves.push(sq); + await this.playMove(sq, tok); + } else { + z.prob = T.play(z.prob, T.PASS); + this.gs = { ...this.gs, turn: L.other(this.gs.turn), ko: -1 }; + toast(this, 'White passes: nothing it can do there.', { depth: D.modal }); + } + } + + async puzzleWrong(tok, { replied = false } = {}) { + const z = this.puz; + sting(this, 'wrong'); + this.hud.hounSays(hounLine('puzzleWrong')); + if (!replied) { + await this.puzzleReply(tok); + if (this.stale(tok)) return; + } + z.state = 'failed'; + let delta = ''; + if (!z.rated) { + const st = PZ.loadPuzzleState(); + const d = PZ.ratePuzzle(st, z.p, z.assisted ? 'assisted' : 'failed'); + if (z.daily) st.daily[z.key] = 'failed'; + PZ.savePuzzleState(st); + z.rated = true; + delta = d ? ` (${d > 0 ? '+' : ''}${d})` : ''; + } + this.busy = false; + this.setStatus('Not this time', `That line fails: White's answer holds.\nRetry, or see the solution.${delta ? `\nRating${delta}` : ''}`); + this.time.delayedCall(1600, () => { if (!this.stale(tok)) this.hud.hounSays(hounLine('puzzleFailed')); }); + this.refreshHud(); + } + + puzzleSolved(tok) { + const z = this.puz; + z.state = 'solved'; + sting(this, 'solved'); + const last = z.moves[z.moves.length - 1]; + if (last != null) { const p = pointXY(last, this.size); this.ringBurst(p.x, p.y); } + let line = ''; + if (!z.rated) { + const st = PZ.loadPuzzleState(); + const d = PZ.ratePuzzle(st, z.p, z.assisted ? 'assisted' : 'solved'); + if (z.daily) st.daily[z.key] = z.assisted ? 'assisted' : 'solved'; + PZ.savePuzzleState(st); + z.rated = true; + line = `Rating ${st.rating}${d ? ` (${d > 0 ? '+' : ''}${d})` : ''}${z.daily ? ` · daily streak ${PZ.dailyStreak(st)}` : ` · streak ${st.streak}`}`; + } + this.banner('SOLVED', 0xf0d890, 0.6, true); + this.hud.hounSays(hounLine(z.daily && !z.assisted ? 'dailySolved' : 'puzzleSolved')); + this.busy = false; + this.setStatus('Solved', `${z.p.goal === 'kill' ? 'White cannot live.' : 'Your group lives.'} Theme: ${(PZ.THEME_LABEL[z.p.theme] ?? z.p.theme).toLowerCase()}.\n${line}`); + this.refreshHud(); + void tok; + } + + async puzzleHint() { + const z = this.puz; + if (!this.puzzleCanMove()) return; + const tok = this.token; + z.assisted = true; + this.clearHint(); + let sq = -1; + const onLine = z.moves.every((m, i) => z.setup.line[i] === m); + if (onLine && z.setup.line[z.moves.length] != null && z.moves.length % 2 === 0) sq = z.setup.line[z.moves.length]; + else { + this.busy = true; + this.refreshHud(); + try { const r = await this.engine.request('puzzleReply', { prob: z.prob }); if (r?.refutes) sq = r.sq; } catch (_) { /* */ } + if (this.stale(tok)) return; + this.busy = false; + } + if (sq < 0) { this.hud.hounSays('Nothing saves it now. Retry.'); this.refreshHud(); return; } + const p = pointXY(sq, this.size), { R } = geom(this.size); + const ring = this.add.image(p.x, p.y, 'go-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.hounSays(hounLine('puzzleHint')); + this.refreshHud(); + } + + resetPuzzleBoard() { + const z = this.puz; + this.token++; + this.engine.forget(); + this.gs = this.puzzleGame(z.setup); + z.prob = PZ.toProb(z.setup, z.setup.board, L.BLACK); + z.moves = []; + this.clearOverlays(); + this.stones.build(z.setup.board, z.setup.size); + this.drawOverlays(); + } + + retryPuzzle() { + if (!this.puz || this.busy) return; + this.resetPuzzleBoard(); + this.puz.state = 'playing'; + this.busy = false; + rustle(this); + this.puzzleStatus(); + this.refreshHud(); + } + + async showSolution() { + const z = this.puz; + if (!z || this.busy) return; + if (!z.rated) { + const st = PZ.loadPuzzleState(); + PZ.ratePuzzle(st, z.p, 'assisted'); + if (z.daily) st.daily[z.key] = 'assisted'; + PZ.savePuzzleState(st); + z.rated = true; + } + z.assisted = true; + this.resetPuzzleBoard(); + const tok = this.token; + z.state = 'shown'; + this.busy = true; + this.refreshHud(); + this.setStatus('The solution', 'Watch where the first stone goes.'); + await this.wait(400); + for (const sq of z.setup.line) { + if (this.stale(tok)) return; + if (!L.isLegal(this.gs, sq)) break; + const np = T.play(z.prob, sq); + if (!np) break; + z.prob = np; + z.moves.push(sq); + await this.playMove(sq, tok); + if (this.stale(tok)) return; + await this.wait(650 * this.k); + } + if (this.stale(tok)) return; + const first = z.setup.first; + this.busy = false; + this.setStatus('The solution', `The key is ${L.notate(first, this.size)}. ${z.p.goal === 'kill' ? 'After it, White cannot make two eyes.' : 'After it, Black has room for two eyes.'}\nRetry it yourself, or go on to the next.`); + this.refreshHud(); + } + + nextPuzzle() { + if (!this.puz || this.busy) return; + const st = PZ.loadPuzzleState(); + this.startPuzzle(PZ.nextLadderPuzzle(st, Math.random, this.puz.p.id)); + } + + leavePuzzle() { + if (!this.puz) return; + this.puz = null; + this.gs = null; + this.hud.setTopName(this.oppName); + this.hud.setSkillVisible(true); + this.clearOverlays(); + this.backToBoard(); + } + + // ── buttons / keys / menu ─────────────────────────────────────────────────── + onButton(k) { + if (this.ended || this.modal) return; + const mode = this.hud.mode; + if (k === 'b6') { this.openMenu(); return; } + if (mode === 'play') { + if (k === 'b1') this.humanPass(); + else if (k === 'b2') this.undo(); + else if (k === 'b3') this.showHint(); + else if (k === 'b4') this.toggleStudy(); + else if (k === 'b5') this.resign(); + } else if (mode === 'scoring') { + if (k === 'b1') this.acceptScore(); + else if (k === 'b2') this.resumeFromScoring(); + else if (k === 'b4') this.toggleStudy(); + else if (k === 'b5') this.resign(); + } else { + if (k === 'b1') this.retryPuzzle(); + else if (k === 'b2') this.puzzleHint(); + else if (k === 'b3') this.nextPuzzle(); + else if (k === 'b4') this.showSolution(); + else if (k === 'b5') this.leavePuzzle(); + } + } + + toggleStudy() { + this.changeSetting('territory', !this.settings.territory); + toast(this, this.settings.territory ? 'Study on: Hōun shades the territory and keeps the count above the board.' : 'Study off.', { depth: D.modal }); + } + + 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 (this.puz) { + if (lower === 'r') this.retryPuzzle(); + else if (lower === 'h') this.puzzleHint(); + else if (lower === 'n' && !this.busy) this.nextPuzzle(); + } else if (lower === 'z') this.undo(); + else if (lower === 'h') this.showHint(); + else if (lower === 'p') this.humanPass(); + else if (lower === 'n') { this.changeSetting('numbers', !this.settings.numbers); } + if (lower === 't' && !this.puz) this.toggleStudy(); + else if (key.startsWith('Arrow')) { e.preventDefault?.(); this.moveCursor(key); } + else if ((key === 'Enter' || key === ' ') && this.cursor) { + const sq = this.cursor[0] * this.size + this.cursor[1]; + if (this.puz) this.puzzleClick(sq); + else if (this.phase === 'scoring') this.toggleGroup(sq); + else if (this.canMoveNow()) this.tryPlay(sq); + } + } + + moveCursor(key) { + if (!(this.canMoveNow() || this.puzzleCanMove() || (this.phase === 'scoring' && !this.busy))) return; + const n = this.size; + if (!this.cursor) { + const last = this.gs.history.filter((h) => !h.pass).pop(); + const s = this.puz ? this.puz.setup.region[0] : last ? last.sq : Math.floor((n * n) / 2); + this.cursor = [Math.floor(s / n), s % n]; + } 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' || this.phase === 'puzzle' || this.phase === 'scoring')) return; + const { R } = geom(this.size); + const p = pointXY(this.cursor[0] * this.size + this.cursor[1], this.size); + g.lineStyle(4, 0xd8b060, 1).strokeCircle(p.x, p.y, R * 1.08); + g.lineStyle(1.5, 0xffffff, 0.7).strokeCircle(p.x, p.y, R * 0.9); + } + + openMenu() { + if (this.modal || this.ended || ['over', 'setup', 'review'].includes(this.phase)) return; + this.clearPreview(); + this.hud.hidePortraits(); + this.escClosable = true; + const inPuzzle = !!this.puz; + this.modal = openPauseMenu(this, { + settings: this.settings, depth: D.modal, puzzle: inPuzzle, + onChange: (key, value) => this.changeSetting(key, value), + onRules: () => new TutorialModal(this.gameDef).open(), + onSave: () => this.saveSgf(), + onOpen: () => { this.save(); this.openSgf(); }, + onPuzzles: () => { if (inPuzzle) this.leavePuzzle(); else this.enterPuzzles(false); }, + onNewMatch: () => this.confirmThen('Start a new match?', 'This game will be set aside for good.', () => { this.clearSave(); this.match = null; this.gs = null; this.puz = null; this.openSetupCard(); }), + onLeave: () => this.confirmThen('Leave the temple?', '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 (key === 'coords') this.buildCoords(); + if (key === 'numbers' || key === 'coach') this.drawOverlays(); + if (key === 'territory') { + if (value) { this.estKey = null; if (this.phase === 'human') this.requestEstimate(); } else { this.estimate = null; } + this.drawTerritory(); + this.refreshHud(); + } + if (key === 'preview') this.clearPreview(); + } + + // ── flourishes ────────────────────────────────────────────────────────────── + ringBurst(x, y) { + for (let i = 0; i < 2; i++) { + const r = this.add.image(x, y, 'go-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, 'go-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() }); + } + } + + /** A gust of the season's petals across the board for a win. */ + petalBurst() { + const key = `go-p-${this.season ?? 'spring'}`; + for (let i = 0; i < 70; i++) { + const x = BX - 200 + Math.random() * 400, y = 80 + Math.random() * 800; + const p = this.add.image(x, y, key).setDepth(D.fx).setScale(1 + Math.random()).setRotation(Math.random() * 6).setAlpha(0); + this.tweens.add({ + targets: p, x: x + 900 + Math.random() * 600, y: y + (Math.random() - 0.3) * 300, rotation: p.rotation + (Math.random() - 0.5) * 14, + alpha: { from: 1, to: 0 }, delay: Math.random() * 900, duration: 2600 + Math.random() * 1600, ease: 'Sine.InOut', onComplete: () => p.destroy(), }); } } - showEndPanel(winner, final) { - const isHuman = winner === 'black'; - const name = this.opponents[0]?.name ?? 'Opponent'; - const cx = GX + (SIZE - 1) * SQ / 2, cy = GY + (SIZE - 1) * SQ / 2; - - const msg = isHuman - ? `🎉 You win!\nBlack: ${final.black.toFixed(1)} · White: ${final.white.toFixed(1)}\n(incl. ${KOMI} komi)` - : `${name} wins!\nBlack: ${final.black.toFixed(1)} · White: ${final.white.toFixed(1)}\n(incl. ${KOMI} komi)`; - - const overlay = this.add.rectangle(cx, cy, 780, 320, 0x0a0e14, 0.92) - .setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.banner); - const txt = this.add.text(cx, cy - 50, msg, { - fontFamily: '"Julius Sans One"', fontSize: '28px', - color: isHuman ? '#ffd700' : COLORS.textHex, align: 'center', - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); - new Button(this, cx - 95, cy + 100, 'Play Again', () => { - overlay.destroy(); txt.destroy(); this.initGame(); - }, { width: 170, fontSize: 22 }).setDepth(DEPTH.banner + 1); - new Button(this, cx + 95, cy + 100, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 170, fontSize: 22 }).setDepth(DEPTH.banner + 1); + 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: '40px', 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: 1100, duration: 500, onComplete: () => t.destroy() }); } - async recordResult(result) { - try { - const final = getFinalScore(this.gs); - const score = result === 'win' ? Math.round(final.black) : 0; - await api.post('/history/single-player', { slug: 'go', score, opponentScores: [], result }); - } catch { /* best effort */ } + 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/go/GoHud.js b/src/games/go/GoHud.js new file mode 100644 index 0000000..8a1b5b4 --- /dev/null +++ b/src/games/go/GoHud.js @@ -0,0 +1,301 @@ +// GoHud.js: the furniture round the board: a plaque per player +// (portrait, name, skill, a note line, prisoners and clock, their colour, +// the match tally), each player's bowl and the lid holding their +// prisoners, the balance bar (Hōun's estimate of the score), the status +// card, the kifu (the game record), the buttons, the opponent's speech +// bubble and Hōun's ribbon. + +import { Button } from '../../ui/Button.js'; +import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { + PLATES, plateParts, BOWLS, BUBBLE, STATUS, RECORD, RECORD_ROWS, BUTTONS, BTN, RIBBON, BAR, +} from './GoLayout.js'; +import { DISPLAY_FONT, SERIF, BOLD_FONT, RES } from './GoArt.js'; +import { LidPile } from './GoStones.js'; +import { other, RULES, notate } from './GoLogic.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)); + +export const MODES = { + play: { + b1: ['Pass (P)', 0x2a4a6a], b2: ['Undo (Z)', 0x6a4a1a], b3: ['Hint (H)', 0x2a5a3a], + b4: ['Study (T)', 0x3a3a52], b5: ['Resign', 0x7a1a14], b6: ['Menu (Esc)', 0x2a1a12], + }, + scoring: { + b1: ['Accept', 0x1f6a3a], b2: ['Resume Play', 0x6a4a1a], b3: ['Hint (H)', 0x2a5a3a], + b4: ['Study (T)', 0x3a3a52], b5: ['Resign', 0x7a1a14], b6: ['Menu (Esc)', 0x2a1a12], + }, + puzzle: { + b1: ['Retry (R)', 0x6a4a1a], b2: ['Hint (H)', 0x2a5a3a], b3: ['Next ▶', 0x2a4a6a], + b4: ['Solution', 0x3a3a52], b5: ['To the Board', 0x7a1a14], b6: ['Menu (Esc)', 0x2a1a12], + }, +}; + +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.lids = {}; + this.bowls = {}; + this.bubble = null; + this.barShown = 0.5; + this.mode = 'play'; + } + + 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, 'go-plate-glow').setOrigin(0).setDepth(D - 1).setAlpha(0); + s.add.image(P.x - 14, P.y - 14, 'go-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, 'GoGame') + : createOpponentPortrait(s, this.opponent ?? { id: 'bot', spriteIndex: 0 }, pp.x, pp.y, pp.r, D + 2); + const name = 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); + let skillT = null; + if (side === 'top') { + const k = this.skill; + skillT = 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, 'go-black').setScale(0.1).setDepth(D + 1).setVisible(false); + const chipText = s.add.text(parts.color.x + 20, 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, name, skillT, note, line, chip, chipText, tally, active: false }; + // bowl and lid + const B = BOWLS[side]; + this.bowls[side] = s.add.image(B.bowl.x, B.bowl.y, 'go-bowl-black').setDepth(D - 2); + s.add.image(B.lid.x, B.lid.y, 'go-lid').setDepth(D - 2); + this.lids[side] = new LidPile(s, B.lid, D - 2); + } + // the balance + s.add.image(BAR.x - 10, BAR.y - 10, 'go-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: '18px', 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: '18px', color: '#1c1b22' }).setOrigin(1, 0.5).setDepth(D + 2); + this.barMid = s.add.text(BAR.x + BAR.w / 2, BAR.y + BAR.h / 2, '', { + fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#f8ecd0', stroke: '#1a0e06', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D + 2); + // status card + s.add.image(STATUS.x - 14, STATUS.y - 14, 'go-card-status').setOrigin(0).setDepth(D); + this.status = s.add.text(STATUS.x + STATUS.w / 2 - 14, STATUS.y + 66, '', { + fontFamily: DISPLAY_FONT, fontSize: '26px', color: '#2a1810', align: 'center', wordWrap: { width: STATUS.w - 110 }, + }).setOrigin(0.5).setDepth(D + 1); + this.sub = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 136, '', { + fontFamily: SERIF, fontSize: '16px', color: '#3a2a1a', align: 'center', wordWrap: { width: STATUS.w - 56 }, lineSpacing: 3, + }).setOrigin(0.5).setDepth(D + 1); + // the kifu + s.add.image(RECORD.x - 14, RECORD.y - 14, 'go-card-record').setOrigin(0).setDepth(D); + this.recTitle = s.add.text(RECORD.x + 26, RECORD.y + 34, 'KIFU', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#8a2a14' }).setOrigin(0, 0.5).setDepth(D + 1); + this.recSub = s.add.text(RECORD.x + RECORD.w - 24, RECORD.y + 34, '', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#5a2a12' }).setOrigin(1, 0.5).setDepth(D + 1); + const ix = RECORD.x + 10, iw = RECORD.w - 20; + const colA = ix + 54 + (iw - 54) / 4, colB = ix + 54 + ((iw - 54) * 3) / 4; + this.colHead = [ + s.add.text(colA, RECORD.y + 70, 'BLACK', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#1c1b22' }).setOrigin(0.5).setDepth(D + 1), + s.add.text(colB, RECORD.y + 70, 'WHITE', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#7a6a52' }).setOrigin(0.5).setDepth(D + 1), + ]; + this.rows = []; + for (let i = 0; i < RECORD_ROWS; i++) { + const y = RECORD.y + 102 + 10 + i * 28; + this.rows.push({ + n: s.add.text(ix + 44, y, '', { fontFamily: SERIF, fontSize: '14px', color: '#7a5a3a' }).setOrigin(1, 0.5).setDepth(D + 1), + a: s.add.text(colA, y, '', { fontFamily: SERIF, fontSize: '16px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D + 1), + b: s.add.text(colB, y, '', { fontFamily: SERIF, fontSize: '16px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D + 1), + }); + } + this.recFoot = s.add.text(RECORD.x + RECORD.w / 2, RECORD.y + RECORD.h - 34, '', { + fontFamily: SERIF, fontSize: '14px', color: '#4a3020', align: 'center', wordWrap: { width: RECORD.w - 50 }, + }).setOrigin(0.5).setDepth(D + 1); + // buttons + for (const [k, b] of Object.entries(BUTTONS)) { + const [label, bg] = MODES.play[k]; + this.buttons[k] = new Button(s, b.x, b.y, label, () => this.onButton(k), { width: BTN.w, height: BTN.h, fontSize: 15, bg }).setDepth(D + 3); + } + // Hōun's ribbon + s.add.image(RIBBON.x - 12, RIBBON.y - 12, 'go-ribbon').setOrigin(0).setDepth(D); + this.houn = s.add.text(RIBBON.x + 84, RIBBON.y + RIBBON.h / 2, '', { + fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: '#f3e4c0', wordWrap: { width: RIBBON.w - 110 }, + }).setOrigin(0, 0.5).setDepth(D + 1); + return this; + } + + /** Relabel the six buttons for a mode ('play' | 'scoring' | 'puzzle'). */ + setMode(mode) { + if (mode === this.mode) return; + this.mode = mode; + for (const [k, [label, bg]] of Object.entries(MODES[mode])) { + const b = this.buttons[k]; + b.setLabel(label); + b.options.bg = bg; + b._drawBg(bg, 1); + } + } + + /** gs, ctx: { humanColor, thinking, clocks, byo, match, intro, estimate, puzzle } */ + refresh(gs, ctx) { + const sides = { bottom: ctx.humanColor, top: other(ctx.humanColor) }; + for (const side of ['top', 'bottom']) { + const pl = this.plates[side], col = sides[side]; + const active = gs.phase === 'playing' && gs.turn === col && !ctx.intro && !ctx.puzzleDone; + 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 (ctx.puzzle) note = ctx.puzzleDone ? '' : side === 'bottom' ? (active ? 'Your move' : '') : (active ? 'Answering…' : 'Holding White'); + else if (gs.phase === 'scoring') note = 'Counting'; + else 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 prisoners = gs.score ? gs.score.prisoners[col] : gs.captures[col]; + let ln = `Prisoners ${prisoners}`; + if (!ctx.puzzle) { + if (side === 'bottom' && ctx.byo) { + const b = ctx.byo; + ln += ` ⏱ ${Math.max(0, Math.ceil(b.left / 1000))}s ×${b.periods}`; + } else ln += ` ⏱ ${clock(side === 'bottom' ? ctx.clocks.human : ctx.clocks.ai)}`; + } + pl.line.setText(ln).setColor(side === 'bottom' && ctx.byo && ctx.byo.left < 10000 && active ? '#ff9a7a' : '#d8c4a0'); + pl.chip.setTexture(col === 'black' ? 'go-black' : 'go-white-0').setVisible(true); + pl.chipText.setText(col === 'black' ? (gs.handicap ? `Black · ${gs.handicap} stones` : 'Black · moves first') : `White · komi ${gs.komi}`); + 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.bowls[side].setTexture(`go-bowl-${col}`); + this.lids[side].set(prisoners, other(col)); + } + this.setBar(gs, ctx.estimate, ctx.puzzle); + this.setRecord(gs, ctx.puzzle); + } + + setBar(gs, est, puzzle) { + let target = 0.5; + if (est && !puzzle) { + // lead in points from black's side, squashed onto the bar + target = 0.5 + 0.5 * Math.tanh(est.lead / (gs.size * 1.2)); + const who = est.lead >= 0 ? 'B' : 'W'; + this.barMid.setText(`Hōun's estimate: ${who}+${Math.abs(est.lead).toFixed(1)}`); + this.barL.setText(''); this.barR.setText(''); + } else { + this.barMid.setText(puzzle ? puzzle : `Move ${gs.history.length + 1} · ${RULES[gs.rules].name} · komi ${gs.komi}`); + this.barL.setText(String(gs.captures.black)); + this.barR.setText(String(gs.captures.white)); + } + this.scene.tweens.killTweensOf(this); + this.scene.tweens.add({ targets: this, barShown: target, duration: 500, ease: 'Cubic.Out', onUpdate: () => this.drawBar() }); + 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); + } + + setRecord(gs, puzzle) { + const hc = gs.handicap ? ` · H${gs.handicap}` : ''; + this.recTitle.setText(puzzle ? 'PROBLEM' : 'KIFU'); + this.recSub.setText(puzzle ? `${gs.size}×${gs.size}` : `${gs.size}×${gs.size} · ${RULES[gs.rules].short} · komi ${gs.komi}${hc}`); + // pair the moves up by turn (whoever moved first) + const pairs = []; + const first = gs.history[0]?.color ?? 'black'; + gs.history.forEach((h, i) => { + if (h.color === first || !pairs.length) pairs.push({ a: null, b: null, n: i }); + const last = pairs[pairs.length - 1]; + if (h.color === 'black') last.a = { h, i }; else last.b = { h, i }; + }); + const start = Math.max(0, pairs.length - RECORD_ROWS); + const lastI = gs.history.length - 1; + this.rows.forEach((r, k) => { + const p = pairs[start + k]; + if (!p) { r.n.setText(''); r.a.setText(''); r.b.setText(''); return; } + r.n.setText(`${p.n + 1}.`); + for (const [t, e] of [[r.a, p.a], [r.b, p.b]]) { + if (!e) { t.setText(''); continue; } + const { h, i } = e; + if (h.pass) { t.setText('pass').setColor('#8a7a62').setFontStyle('italic'); continue; } + const cap = h.captured.length ? ` ×${h.captured.length}` : ''; + t.setText(h.n + cap).setColor(i === lastI ? '#a0221c' : '#2a1a10').setFontStyle(i === lastI ? 'bold' : 'normal'); + } + }); + let foot = `Prisoners: Black ${gs.captures.black} · White ${gs.captures.white}`; + if (gs.ko >= 0 && gs.phase === 'playing') foot += `\nKo at ${notate(gs.ko, gs.size)}: ${gs.turn === 'black' ? 'Black' : 'White'} may not retake yet`; + else if (gs.phase === 'scoring') foot += '\nCounting: click a group to mark it dead or alive'; + this.recFoot.setText(foot); + } + + setStatus(main, sub = '') { this.status.setText(main); this.sub.setText(sub); } + setButton(k, on) { this.buttons[k]?.setEnabled(!!on); } + + hounSays(text, { hold = 7000 } = {}) { + if (!text) return; + const t = this.houn; + this.scene.tweens.killTweensOf(t); + t.setText(`Hōun: “${text}”`).setAlpha(0); + this.scene.tweens.add({ targets: t, alpha: 1, duration: 220 }); + this.scene.tweens.add({ targets: t, alpha: 0.6, 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(0xf4ecd8, 1).fillRoundedRect(b.x, b.y, b.w, b.h, 12); + g.lineStyle(2, 0xb83a24, 1).strokeRoundedRect(b.x, b.y, b.w, b.h, 12); + const tx = BOWLS.top.lid.x; + g.fillStyle(0xf4ecd8, 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; } }); + } + + /** Where a stone leaves the bowl (a random spot in the heap). */ + bowlPoint(side) { + const b = BOWLS[side].bowl; + const a = Math.random() * Math.PI * 2, d = Math.random() * b.r * 0.4; + return { x: b.x + Math.cos(a) * d, y: b.y + Math.sin(a) * d }; + } + + 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)); } + + setTopName(name) { this.plates.top.name.setText(short(name, 13)); } + setSkillVisible(v) { this.plates.top.skillT?.setVisible(v); } +} + +export { RES }; diff --git a/src/games/go/GoLayout.js b/src/games/go/GoLayout.js new file mode 100644 index 0000000..9fa1c45 --- /dev/null +++ b/src/games/go/GoLayout.js @@ -0,0 +1,120 @@ +// GoLayout.js: geometry for Unkai-ji (1920 × 1080). No Phaser. +// +// left column the open shoji onto the valley at dawn; over it the +// opponent's plaque, their bowl and lid, a speech bubble, +// your bowl and lid, your plaque +// centre the kaya board on the tatami: the balance (score) bar +// above, Hōun's ribbon beneath +// right column the status card, the kifu (game record), the buttons, +// and the tokonoma: incense, a vase +// +// The board's top face is always 900 px square; the grid spacing depends +// on the size (9, 13 or 19 lines). + +export const W = 1920; +export const H = 1080; + +export const BOARD = 900; // the board's top face +export const BX = 510; +export const BY = 58; +export const FACE = 30; // the front edge of the slab +export const BCX = BX + BOARD / 2; // 960 +export const BCY = BY + BOARD / 2; // 508 +export const BOARD_RECT = { x: BX, y: BY, w: BOARD, h: BOARD + FACE }; + +/** Stone radius the textures are baked for (the 9×9 size). */ +export const STONE_R = 46; + +export function geom(size) { + const SQ = 844 / size; + const span = SQ * (size - 1); + return { SQ, span, R: SQ * 0.485, x0: BCX - span / 2, y0: BCY - span / 2, scale: (SQ * 0.485) / STONE_R }; +} + +/** Screen centre of point sq on a size×size board. */ +export function pointXY(sq, size) { + const { SQ, x0, y0 } = geom(size); + const r = Math.floor(sq / size), c = sq % size; + return { x: x0 + c * SQ, y: y0 + r * SQ }; +} + +/** The point under a screen position (within half a spacing), or -1. */ +export function pointAt(x, y, size) { + const { SQ, x0, y0 } = geom(size); + const c = Math.round((x - x0) / SQ), r = Math.round((y - y0) / SQ); + if (c < 0 || c >= size || r < 0 || r >= size) return -1; + const dx = x - (x0 + c * SQ), dy = y - (y0 + r * SQ); + if (Math.abs(dx) > SQ * 0.55 || Math.abs(dy) > SQ * 0.55) return -1; + return r * size + c; +} + +// columns +const LX = 30, RX = 1450, CW = 440; + +export const BAR = { x: BX + 40, y: 12, w: BOARD - 80, h: 34 }; + +export const PLATE = { w: CW, h: 196 }; +export const PLATES = { + top: { x: LX, y: 30 }, + bottom: { x: LX, y: 854 }, +}; +/** Each player's bowl (goke) and the lid that holds their prisoners. */ +export const BOWLS = { + top: { bowl: { x: 128, y: 318, r: 76 }, lid: { x: 330, y: 318, r: 70 } }, + bottom: { bowl: { x: 128, y: 762, r: 76 }, lid: { x: 330, y: 762, r: 70 } }, +}; +export const BUBBLE = { x: LX, y: 410, w: CW, h: 84 }; +export const VIEW = { x: 0, y: 0, w: 488, h: H }; // the open shoji + +export const STATUS = { x: RX, y: 30, w: CW, h: 196 }; +export const RECORD = { x: RX, y: 246, w: CW, h: 420 }; +export const RECORD_ROWS = 10; +export const BTN = { w: 138, h: 48 }; +export const BUTTON_ROWS = [['b1', 'b2', 'b3'], ['b4', 'b5', 'b6']]; +export const BUTTONS = {}; +BUTTON_ROWS.forEach((row, ri) => { + row.forEach((k, ci) => { BUTTONS[k] = { x: RX + BTN.w / 2 + ci * (BTN.w + 13), y: 706 + ri * 60 }; }); +}); +export const ALCOVE = { x: RX - 14, y: 836, w: W - RX + 14, h: H - 836 }; +export const INCENSE = { x: 1560, y: 968 }; +export const VASE = { x: 1800, y: 952 }; + +export const RIBBON = { x: BX, y: 1004, w: BOARD, h: 62 }; +export const BANNER = { x: BCX, y: BCY - 30 }; +export const CLOCK_BIG = { x: BCX, y: BCY }; + +export function plateParts(side) { + const P = PLATES[side]; + return { + portrait: { x: P.x + 94, y: P.y + 98, r: 70 }, + name: { x: P.x + 186, y: P.y + 44 }, + skill: { x: P.x + PLATE.w - 22, y: P.y + 44 }, + note: { x: P.x + 186, y: P.y + 86 }, + line: { x: P.x + 186, y: P.y + 124 }, + tally: { x: P.x + PLATE.w - 22, y: P.y + 162 }, + color: { x: P.x + 186 + 12, y: P.y + 162 }, + }; +} + +// 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; + const circ = (c) => ({ x: c.x - c.r, y: c.y - c.r, w: c.r * 2, h: c.r * 2 }); + return { + bar: BAR, + plateTop: { ...PLATES.top, ...PLATE }, + plateBottom: { ...PLATES.bottom, ...PLATE }, + bowlTop: circ(BOWLS.top.bowl), + lidTop: circ(BOWLS.top.lid), + bowlBottom: circ(BOWLS.bottom.bowl), + lidBottom: circ(BOWLS.bottom.lid), + bubble: BUBBLE, + status: STATUS, + record: RECORD, + buttons: { x: bx0, y: by0, w: bx1 - bx0, h: by1 - by0 }, + ribbon: RIBBON, + board: BOARD_RECT, + }; +} diff --git a/src/games/go/GoLogic.js b/src/games/go/GoLogic.js index ebcc400..d233d0c 100644 --- a/src/games/go/GoLogic.js +++ b/src/games/go/GoLogic.js @@ -1,229 +1,458 @@ -// Pure game logic for Go (9×9, Japanese rules). -// Board: 9×9 array, each cell = null | 'black' | 'white'. -// Stones placed on intersections. Black moves first (human). +// GoLogic.js: the rules of Go for Unkai-ji. Pure functions, no Phaser. +// +// A position (gs) is plain JSON so it can be saved and sent to the worker: +// { v, size, komi, rules, handicap, board[N·N] (null | 'black' | 'white'), +// turn, phase ('playing' | 'scoring' | 'over'), captures {black, white} +// (prisoners each colour has taken), ko (the point the side to move may +// not retake, or -1), hash [h1, h2] (Zobrist), seen [position keys] (for +// positional superko), history [{ color, sq, pass, captured[], n }], +// setup { black[], white[] } (handicap or puzzle stones), passes, +// winner, endReason ('score' | 'resign' | 'time'), score (see scoreGame), +// dead[] } +// +// Points are numbered sq = row · size + col, row 0 at the top. Notation is +// the usual one: a column letter (A–T, no I) and a row number counted up +// from the bottom, so the top-left corner of a 9×9 board is A9. +// +// Rules: stones with no liberties are removed; suicide is illegal; no move +// may recreate an earlier whole-board position (positional superko, which +// includes the simple ko). Two passes in a row end play; then dead stones +// are agreed and the game is scored by territory (Japanese) or by area +// (Chinese). -export const SIZE = 9; -export const KOMI = 6.5; // white compensation for moving second +export const BLACK = 'black'; +export const WHITE = 'white'; +export const other = (c) => (c === BLACK ? WHITE : BLACK); +export const SIZES = [9, 13, 19]; +export const COLS = 'ABCDEFGHJKLMNOPQRST'; -const ADJ = [[-1,0],[1,0],[0,-1],[0,1]]; -function inBounds(r, c) { return r >= 0 && r < SIZE && c >= 0 && c < SIZE; } -function other(color) { return color === 'black' ? 'white' : 'black'; } +export const SIZE_INFO = { + 9: { name: '9×9', long: '9×9 · the quick board', blurb: 'The 9×9 board: games of twenty minutes, fighting from the first stone.' }, + 13: { name: '13×13', long: '13×13 · the middle board', blurb: 'The 13×13 board: room for corners and walls, still over within the hour.' }, + 19: { name: '19×19', long: '19×19 · the full board', blurb: 'The full 19×19 board: the game as it has been played for centuries. Bring patience.' }, +}; -export function cloneState(state) { - return { - board: state.board.map(row => [...row]), - turn: state.turn, - phase: state.phase, - winner: state.winner, - captures: { ...state.captures }, - consecutivePasses: state.consecutivePasses, - koPoint: state.koPoint ? [...state.koPoint] : null, - prevHash: state.prevHash, - }; +export const RULES = { + japanese: { name: 'Japanese', short: 'Territory', blurb: 'Japanese rules: you score the empty points you surround plus the stones you capture.' }, + chinese: { name: 'Chinese', short: 'Area', blurb: 'Chinese rules: you score your stones on the board plus the empty points they surround.' }, +}; +export const RULE_ORDER = ['japanese', 'chinese']; +export const KOMI_CHOICES = [6.5, 7.5, 5.5, 0.5, 0]; + +/** The usual komi for a ruleset and handicap. */ +export function defaultKomi(rules, handicap) { + if (handicap >= 2) return 0.5; + return rules === 'chinese' ? 7.5 : 6.5; } -export function createInitialState() { - return { - board: Array.from({ length: SIZE }, () => Array(SIZE).fill(null)), - turn: 'black', - phase: 'playing', - winner: null, - captures: { black: 0, white: 0 }, // stones captured BY each color - consecutivePasses: 0, - koPoint: null, - prevHash: null, - }; +// ── geometry ───────────────────────────────────────────────────────────────── +const NBR_CACHE = new Map(); +/** nbrs(size)[sq] → the orthogonal neighbours of sq. */ +export function nbrs(size) { + let t = NBR_CACHE.get(size); + if (t) return t; + t = []; + for (let sq = 0; sq < size * size; sq++) { + const r = Math.floor(sq / size), c = sq % size, n = []; + if (r > 0) n.push(sq - size); + if (r < size - 1) n.push(sq + size); + if (c > 0) n.push(sq - 1); + if (c < size - 1) n.push(sq + 1); + t.push(n); + } + NBR_CACHE.set(size, t); + return t; } -// Returns the Set of "r,c" keys forming the connected group containing (r,c). -export function getGroup(board, r, c) { - const color = board[r][c]; - if (!color) return new Set(); - const group = new Set(); - const stack = [[r, c]]; +export const rc = (sq, size) => [Math.floor(sq / size), sq % size]; +export const at = (r, c, size) => r * size + c; + +/** Distance to the nearest edge, counting the edge line as line 1. */ +export function lineOf(sq, size) { + const [r, c] = rc(sq, size); + return Math.min(r, c, size - 1 - r, size - 1 - c) + 1; +} + +/** Star points (hoshi) drawn on the board. */ +export function starPoints(size) { + if (size === 9) return [[2, 2], [2, 6], [6, 2], [6, 6], [4, 4]].map(([r, c]) => at(r, c, size)); + const lo = 3, hi = size - 4, mid = (size - 1) / 2; + const pts = [[lo, lo], [lo, hi], [hi, lo], [hi, hi], [mid, mid]]; + if (size === 19) pts.push([lo, mid], [mid, lo], [mid, hi], [hi, mid]); + return pts.map(([r, c]) => at(r, c, size)); +} + +export const MAX_HANDICAP = 9; + +/** Where n handicap stones go, in the traditional order. */ +export function handicapPoints(size, n) { + if (n < 2) return []; + const lo = size === 9 ? 2 : 3, hi = size - 1 - lo, mid = (size - 1) / 2; + const UR = [lo, hi], LL = [hi, lo], LR = [hi, hi], UL = [lo, lo]; + const L = [mid, lo], R = [mid, hi], T = [lo, mid], B = [hi, mid], C = [mid, mid]; + const sets = { + 2: [UR, LL], 3: [UR, LL, LR], 4: [UR, LL, LR, UL], 5: [UR, LL, LR, UL, C], + 6: [UR, LL, LR, UL, L, R], 7: [UR, LL, LR, UL, L, R, C], + 8: [UR, LL, LR, UL, L, R, T, B], 9: [UR, LL, LR, UL, L, R, T, B, C], + }; + return (sets[Math.min(MAX_HANDICAP, n)] ?? []).map(([r, c]) => at(r, c, size)); +} + +export function notate(sq, size) { + if (sq == null || sq < 0) return 'pass'; + const [r, c] = rc(sq, size); + return `${COLS[c]}${size - r}`; +} + +export function parseSq(s, size) { + if (!s) return -1; + const m = /^([A-HJ-T])(\d{1,2})$/i.exec(String(s).trim()); + if (!m) return -1; + const c = COLS.indexOf(m[1].toUpperCase()), r = size - Number(m[2]); + if (c < 0 || c >= size || r < 0 || r >= size) return -1; + return at(r, c, size); +} + +// ── hashing ────────────────────────────────────────────────────────────────── +function mulberry(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; + }; +} +const ZOB = (() => { + const rnd = mulberry(0x60ba11); + const t = new Uint32Array(19 * 19 * 4); + for (let i = 0; i < t.length; i++) t[i] = rnd(); + return t; +})(); +const zi = (sq, color) => (sq * 2 + (color === BLACK ? 0 : 1)) * 2; +export function zobristOf(board) { + let a = 0, b = 0; + for (let sq = 0; sq < board.length; sq++) { + const v = board[sq]; + if (!v) continue; + const i = zi(sq, v); + a ^= ZOB[i]; b ^= ZOB[i + 1]; + } + return [a >>> 0, b >>> 0]; +} +export const hashKey = (h) => `${h[0].toString(36)}.${h[1].toString(36)}`; + +// ── groups ─────────────────────────────────────────────────────────────────── +/** The chain at sq: { color, stones[], libs[] } (empty arrays on an empty point). */ +export function groupAt(board, size, sq) { + const color = board[sq]; + if (!color) return { color: null, stones: [], libs: [] }; + const N = nbrs(size); + const seen = new Uint8Array(board.length); + const stones = [], libs = []; + const stack = [sq]; + seen[sq] = 1; while (stack.length) { - const [cr, cc] = stack.pop(); - const key = `${cr},${cc}`; - if (group.has(key)) continue; - if (board[cr][cc] !== color) continue; - group.add(key); - for (const [dr, dc] of ADJ) { - const nr = cr + dr, nc = cc + dc; - if (inBounds(nr, nc) && !group.has(`${nr},${nc}`)) stack.push([nr, nc]); + const p = stack.pop(); + stones.push(p); + for (const n of N[p]) { + if (seen[n]) continue; + const v = board[n]; + if (v === color) { seen[n] = 1; stack.push(n); } else if (!v) { seen[n] = 2; libs.push(n); } } } - return group; + return { color, stones, libs }; } -// Count liberties (adjacent empty intersections) of a group (Set of "r,c" keys). -export function getLiberties(board, group) { - const libs = new Set(); - for (const key of group) { - const [r, c] = key.split(',').map(Number); - for (const [dr, dc] of ADJ) { - const nr = r + dr, nc = c + dc; - if (inBounds(nr, nc) && board[nr][nc] === null) libs.add(`${nr},${nc}`); - } +/** Every chain on the board. */ +export function allGroups(board, size) { + const done = new Uint8Array(board.length); + const out = []; + for (let sq = 0; sq < board.length; sq++) { + if (!board[sq] || done[sq]) continue; + const g = groupAt(board, size, sq); + for (const s of g.stones) done[s] = 1; + out.push(g); } - return libs.size; + return out; } -// Returns array of groups (as Set) of `color` that would be captured -// after placing a stone of `stoneColor` at (r, c). -export function findCaptures(board, r, c, stoneColor) { - const opp = other(stoneColor); - const checked = new Set(); +// ── setting up ─────────────────────────────────────────────────────────────── +export function createGame({ size = 9, komi = null, rules = 'japanese', handicap = 0, setup = null, turn = null } = {}) { + const N = size * size; + const board = Array(N).fill(null); + const hcap = handicap >= 2 ? Math.min(MAX_HANDICAP, handicap) : 0; + const st = { black: [], white: [] }; + if (setup) { + for (const s of setup.black ?? []) { board[s] = BLACK; st.black.push(s); } + for (const s of setup.white ?? []) { board[s] = WHITE; st.white.push(s); } + } else if (hcap) { + for (const s of handicapPoints(size, hcap)) { board[s] = BLACK; st.black.push(s); } + } + const hash = zobristOf(board); + return { + v: 1, size, rules, handicap: hcap, + komi: komi ?? defaultKomi(rules, hcap), + board, turn: turn ?? (hcap ? WHITE : BLACK), phase: 'playing', + captures: { black: 0, white: 0 }, ko: -1, hash, seen: [hashKey(hash)], + history: [], setup: st, passes: 0, + winner: null, endReason: null, score: null, dead: [], + }; +} + +function clone(gs) { + return { + ...gs, board: gs.board.slice(), captures: { ...gs.captures }, hash: gs.hash.slice(), + seen: gs.seen.slice(), history: gs.history.slice(), dead: gs.dead.slice(), + }; +} + +// ── moves ──────────────────────────────────────────────────────────────────── +/** + * What playing `color` at sq would do: { ok, reason, captured[], board, hash }. + * reason: 'occupied' | 'ko' | 'suicide' | 'superko' | 'over' when not ok. + */ +export function tryMove(gs, sq, color = gs.turn) { + const { size, board } = gs; + if (gs.phase !== 'playing') return { ok: false, reason: 'over', captured: [] }; + if (sq < 0 || sq >= board.length || board[sq]) return { ok: false, reason: 'occupied', captured: [] }; + if (sq === gs.ko && color === gs.turn) return { ok: false, reason: 'ko', captured: [] }; + const opp = other(color); + const b = board.slice(); + b[sq] = color; const captured = []; - for (const [dr, dc] of ADJ) { - const nr = r + dr, nc = c + dc; - if (!inBounds(nr, nc) || board[nr][nc] !== opp) continue; - const key = `${nr},${nc}`; - if (checked.has(key)) continue; - const group = getGroup(board, nr, nc); - for (const k of group) checked.add(k); - // Count liberties excluding (r, c) since we're placing there - let libs = 0; - for (const k of group) { - const [gr, gc] = k.split(',').map(Number); - for (const [dr2, dc2] of ADJ) { - const lr = gr + dr2, lc = gc + dc2; - if (!inBounds(lr, lc)) continue; - if (board[lr][lc] === null && !(lr === r && lc === c)) libs++; - // deduplicate - } - } - // Recount properly - const libSet = new Set(); - for (const k of group) { - const [gr, gc] = k.split(',').map(Number); - for (const [dr2, dc2] of ADJ) { - const lr = gr + dr2, lc = gc + dc2; - if (inBounds(lr, lc) && board[lr][lc] === null && !(lr === r && lc === c)) { - libSet.add(`${lr},${lc}`); - } - } - } - if (libSet.size === 0) captured.push(group); + for (const n of nbrs(size)[sq]) { + if (b[n] !== opp) continue; + const g = groupAt(b, size, n); + if (g.libs.length === 0) for (const s of g.stones) { b[s] = null; captured.push(s); } } - return captured; + const own = groupAt(b, size, sq); + if (own.libs.length === 0) return { ok: false, reason: 'suicide', captured: [] }; + let h0 = gs.hash[0], h1 = gs.hash[1]; + let i = zi(sq, color); h0 ^= ZOB[i]; h1 ^= ZOB[i + 1]; + for (const s of captured) { i = zi(s, opp); h0 ^= ZOB[i]; h1 ^= ZOB[i + 1]; } + const hash = [h0 >>> 0, h1 >>> 0]; + if (gs.seen.includes(hashKey(hash))) return { ok: false, reason: 'superko', captured }; + return { ok: true, reason: null, captured, board: b, hash, own }; } -export function isValidMove(state, r, c, color) { - if (state.phase === 'game_over') return false; - if (state.turn !== color) return false; - if (!inBounds(r, c)) return false; - if (state.board[r][c] !== null) return false; - // Ko: forbidden point - if (state.koPoint && state.koPoint[0] === r && state.koPoint[1] === c) return false; +export const isLegal = (gs, sq, color = gs.turn) => tryMove(gs, sq, color).ok; - // Suicide check: after placing, does own group have liberties? - const testBoard = state.board.map(row => [...row]); - testBoard[r][c] = color; - // First remove any captured opponent groups (they free up liberties) - const caps = findCaptures(state.board, r, c, color); - for (const g of caps) for (const k of g) { const [gr, gc] = k.split(',').map(Number); testBoard[gr][gc] = null; } - const ownGroup = getGroup(testBoard, r, c); - if (getLiberties(testBoard, ownGroup) === 0) return false; - - return true; +export function legalMoves(gs, color = gs.turn) { + const out = []; + if (gs.phase !== 'playing') return out; + for (let sq = 0; sq < gs.board.length; sq++) if (!gs.board[sq] && tryMove(gs, sq, color).ok) out.push(sq); + return out; } -export function boardHash(board) { - return board.map(row => row.map(c => c === 'black' ? 'B' : c === 'white' ? 'W' : '.').join('')).join('|'); -} - -export function applyMove(state, r, c) { - const s = cloneState(state); - const color = s.turn; - - s.prevHash = boardHash(s.board); - s.board[r][c] = color; - s.consecutivePasses = 0; - - // Capture opponent groups - const caps = findCaptures(state.board, r, c, color); - let captureCount = 0; - let singleCapturePos = null; - for (const g of caps) { - captureCount += g.size; - if (g.size === 1) singleCapturePos = [...g][0].split(',').map(Number); - for (const k of g) { const [gr, gc] = k.split(',').map(Number); s.board[gr][gc] = null; } - } - s.captures[color] += captureCount; - - // Ko: if exactly one stone was captured and the placement was a single-stone group, set ko point - const ownGroupAfter = getGroup(s.board, r, c); - if (captureCount === 1 && ownGroupAfter.size === 1 && singleCapturePos) { - s.koPoint = singleCapturePos; - } else { - s.koPoint = null; - } - +/** Play the side to move at sq. Returns a new position (or null if illegal). */ +export function play(gs, sq, extra = null) { + const color = gs.turn; + const t = tryMove(gs, sq, color); + if (!t.ok) return null; + const s = clone(gs); + s.board = t.board; + s.hash = t.hash; + s.seen.push(hashKey(t.hash)); + s.captures[color] += t.captured.length; + s.ko = t.captured.length === 1 && t.own.stones.length === 1 && t.own.libs.length === 1 ? t.captured[0] : -1; + s.passes = 0; + s.history.push({ color, sq, pass: false, captured: t.captured, n: notate(sq, gs.size), ...(extra ?? {}) }); s.turn = other(color); return s; } -export function applyPass(state) { - const s = cloneState(state); - s.consecutivePasses += 1; - s.koPoint = null; - if (s.consecutivePasses >= 2) { - s.phase = 'game_over'; - const final = getFinalScore(s); - s.winner = final.black > final.white ? 'black' : 'white'; +export function pass(gs) { + if (gs.phase !== 'playing') return gs; + const s = clone(gs); + s.history.push({ color: gs.turn, sq: -1, pass: true, captured: [], n: 'pass' }); + s.passes = gs.passes + 1; + s.ko = -1; + s.turn = other(gs.turn); + if (s.passes >= 2) s.phase = 'scoring'; + return s; +} + +/** Back to play from the scoring phase (a dispute). The side to move keeps the move. */ +export function resumePlay(gs) { + const s = clone(gs); + s.phase = 'playing'; + s.passes = 0; + s.dead = []; + return s; +} + +export function resign(gs, color) { + const s = clone(gs); + s.phase = 'over'; + s.winner = other(color); + s.endReason = 'resign'; + return s; +} + +export function timeLoss(gs, color) { + const s = resign(gs, color); + s.endReason = 'time'; + return s; +} + +// ── scoring ────────────────────────────────────────────────────────────────── +/** + * Score the board with the given dead stones removed. + * → { black, white, margin, winner, owner[] ('black' | 'white' | null per + * point), territory {black, white}, stones {black, white}, prisoners + * {black, white} (captures plus dead stones taken off), deadCount + * {black, white}, komi, rules, dame[] } + */ +export function scoreGame(gs, dead = gs.dead ?? []) { + const { size } = gs; + const deadSet = new Set(dead); + const b = gs.board.map((v, sq) => (deadSet.has(sq) ? null : v)); + const N = nbrs(size); + const owner = Array(b.length).fill(null); + const seen = new Uint8Array(b.length); + const territory = { black: 0, white: 0 }, stones = { black: 0, white: 0 }; + const deadCount = { black: 0, white: 0 }; + const dame = []; + for (const s of deadSet) if (gs.board[s]) deadCount[gs.board[s]]++; + for (let sq = 0; sq < b.length; sq++) { + if (b[sq]) { stones[b[sq]]++; owner[sq] = b[sq]; continue; } + if (seen[sq]) continue; + const region = [], stack = [sq]; + let tb = false, tw = false; + seen[sq] = 1; + while (stack.length) { + const p = stack.pop(); + region.push(p); + for (const n of N[p]) { + const v = b[n]; + if (v === BLACK) tb = true; + else if (v === WHITE) tw = true; + else if (!seen[n]) { seen[n] = 1; stack.push(n); } + } + } + const who = tb && !tw ? BLACK : tw && !tb ? WHITE : null; + for (const p of region) { owner[p] = who; if (!who) dame.push(p); } + if (who) territory[who] += region.length; + } + // stones are owned by their colour; territory points above are the empty ones + for (let sq = 0; sq < b.length; sq++) if (b[sq]) owner[sq] = b[sq]; + const prisoners = { black: gs.captures.black + deadCount.white, white: gs.captures.white + deadCount.black }; + let black, white; + if (gs.rules === 'chinese') { + black = stones.black + territory.black; + white = stones.white + territory.white + gs.komi; } else { - s.turn = other(s.turn); + black = territory.black + prisoners.black; + white = territory.white + prisoners.white + gs.komi; + } + const margin = Math.abs(black - white); + const winner = black > white ? BLACK : white > black ? WHITE : 'draw'; + return { black, white, margin, winner, owner, territory, stones, prisoners, deadCount, komi: gs.komi, rules: gs.rules, dame }; +} + +/** End the game with these dead stones. */ +export function finish(gs, dead = []) { + const s = clone(gs); + s.dead = dead.slice(); + s.score = scoreGame(s, s.dead); + s.winner = s.score.winner; + s.phase = 'over'; + s.endReason = 'score'; + return s; +} + +/** A result string in the SGF style: B+3.5, W+R, W+T, 0 (jigo). */ +export function resultString(gs) { + if (gs.phase !== 'over' || !gs.winner) return ''; + if (gs.winner === 'draw') return '0'; + const w = gs.winner === BLACK ? 'B' : 'W'; + if (gs.endReason === 'resign') return `${w}+R`; + if (gs.endReason === 'time') return `${w}+T`; + return `${w}+${gs.score?.margin ?? '?'}`; +} + +/** Toggle the dead/alive mark on the whole chain at sq. */ +export function toggleDead(gs, dead, sq) { + if (!gs.board[sq]) return dead.slice(); + const g = groupAt(gs.board, gs.size, sq); + const set = new Set(dead); + const isDead = set.has(sq); + for (const s of g.stones) { if (isDead) set.delete(s); else set.add(s); } + return [...set].sort((a, b) => a - b); +} + +// ── replay ─────────────────────────────────────────────────────────────────── +/** The board (and prisoner counts) after the first n entries of the history. */ +export function positionAfter(gs, n) { + const size = gs.size, N = nbrs(size); + const b = Array(size * size).fill(null); + for (const s of gs.setup.black) b[s] = BLACK; + for (const s of gs.setup.white) b[s] = WHITE; + const captures = { black: 0, white: 0 }; + const hist = gs.history.slice(0, Math.max(0, Math.min(n, gs.history.length))); + for (const h of hist) { + if (h.pass) continue; + b[h.sq] = h.color; + const opp = other(h.color); + for (const nb of N[h.sq]) { + if (b[nb] !== opp) continue; + const g = groupAt(b, size, nb); + if (!g.libs.length) { for (const s of g.stones) b[s] = null; captures[h.color] += g.stones.length; } + } + } + return { board: b, captures }; +} +export const boardAfter = (gs, n) => positionAfter(gs, n).board; + +/** Rebuild a playable position at history index n (for undo and review). */ +export function rewind(gs, n) { + let s = createGame({ size: gs.size, komi: gs.komi, rules: gs.rules, setup: gs.setup, turn: firstTurn(gs) }); + s.handicap = gs.handicap; + for (const h of gs.history.slice(0, n)) { + const extra = {}; + for (const k of Object.keys(h)) if (!['color', 'sq', 'pass', 'captured', 'n'].includes(k)) extra[k] = h[k]; + s = h.pass ? pass(s) : (play(s, h.sq, extra) ?? s); + if (s.phase === 'scoring') s = resumePlay(s); } return s; } -export function isGameOver(state) { return state.phase === 'game_over'; } +/** Who moved first in this game. */ +export function firstTurn(gs) { + if (gs.history.length) return gs.history[0].color; + return gs.turn; +} -// Territory scoring: flood-fill empty regions; if only one color borders → territory. -export function scoreTerritory(state) { - const board = state.board; - const visited = Array.from({ length: SIZE }, () => Array(SIZE).fill(false)); - let black = 0, white = 0; +// ── facts ──────────────────────────────────────────────────────────────────── +export function counts(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 }; +} - for (let r = 0; r < SIZE; r++) { - for (let c = 0; c < SIZE; c++) { - if (board[r][c] !== null || visited[r][c]) continue; - // BFS the empty region - const region = []; - const stack = [[r, c]]; - let touchesBlack = false, touchesWhite = false; - while (stack.length) { - const [cr, cc] = stack.pop(); - if (!inBounds(cr, cc) || visited[cr][cc]) continue; - visited[cr][cc] = true; - if (board[cr][cc] === 'black') { touchesBlack = true; continue; } - if (board[cr][cc] === 'white') { touchesWhite = true; continue; } - region.push([cr, cc]); - for (const [dr, dc] of ADJ) stack.push([cr + dr, cc + dc]); - } - if (touchesBlack && !touchesWhite) black += region.length; - else if (touchesWhite && !touchesBlack) white += region.length; - } +export function moveNumber(gs) { return gs.history.length + 1; } + +/** Chains of `color` in atari (one liberty). */ +export function inAtari(board, size, color) { + return allGroups(board, size).filter((g) => g.color === color && g.libs.length === 1); +} + +/** Per-colour numbers for the end screen. */ +export function stats(gs, color) { + let moves = 0, passes = 0, biggest = 0, ataris = 0; + for (const h of gs.history) { + if (h.color !== color) continue; + if (h.pass) { passes++; continue; } + moves++; + biggest = Math.max(biggest, h.captured.length); } - return { black, white }; + return { moves, passes, captured: gs.captures[color], biggest, ataris }; } -export function getFinalScore(state) { - const terr = scoreTerritory(state); - return { - black: terr.black + state.captures.black, - white: terr.white + state.captures.white + KOMI, - }; -} - -export function getWinner(state) { return state.winner; } - -// Returns all valid placement positions 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 (isValidMove(state, r, c, color)) moves.push({ r, c }); - return moves; +/** Is the point an eye-like point for colour (all neighbours that colour)? */ +export function eyeLike(board, size, sq, color) { + if (board[sq]) return false; + return nbrs(size)[sq].every((n) => board[n] === color); } diff --git a/src/games/go/GoPuzzleData.js b/src/games/go/GoPuzzleData.js new file mode 100644 index 0000000..9150d37 --- /dev/null +++ b/src/games/go/GoPuzzleData.js @@ -0,0 +1,210 @@ +// GoPuzzleData.js: Hōun's life-and-death problems, generated by +// tools/genGoPuzzles.js (do not edit by hand; re-run the generator). +// Points are SGF-style pairs: column letter then row letter, 'aa' top-left. +// Black always plays first. goal: 'kill' (Black attacks) or 'live'. +// region: the points either side may play. first: the one correct move. +// line: a main line (Black, White, Black, …) ending when the result is sure. + +export const PUZZLE_SIZE = 9; +export const PUZZLES = [ + {"id":"T62CIT","rating":600,"goal":"kill","shape":"a straight three","kind":"corner","theme":"capture","attacker":"black","b":"aaeaebacbcccdcec","w":"cadaabbbcbdb","region":"aabacaabbbcbdadb","first":"ba","line":"ba"}, + {"id":"T1MDOX","rating":610,"goal":"kill","shape":"a bent three","kind":"corner","theme":"capture","attacker":"black","b":"badadbccdcadbdcd","w":"caabbbcbacbc","region":"aabaabbbcacbacbc","first":"aa","line":"aa"}, + {"id":"TP5NKJ","rating":610,"goal":"live","shape":"a bent three","kind":"corner","theme":"capture","attacker":"white","b":"cabbcbacbc","w":"daabdbccdcadbdcd","region":"aabaabbbcacbacbc","first":"aa","line":"aa"}, + {"id":"T7PF4G","rating":620,"goal":"live","shape":"a bent three","kind":"corner","theme":"capture","attacker":"white","b":"cabbcbacbc","w":"badadbccdcadbdcd","region":"aabaabbbcacbacbc","first":"aa","line":"aa"}, + {"id":"TLDPIG","rating":630,"goal":"live","shape":"a square four","kind":"corner","theme":"capture","attacker":"white","b":"aacacbacbccc","w":"daabdbdcadbdcddd","region":"aabaabbbcacbacbccc","first":"bb","line":"bb"}, + {"id":"T1N34P","rating":630,"goal":"live","shape":"a straight three","kind":"corner","theme":"capture","attacker":"white","b":"baabbbcbdb","w":"caeaebacbcccdcec","region":"aabacaabbbcbdadb","first":"da","line":"da"}, + {"id":"T1ISLK","rating":640,"goal":"live","shape":"a bent three","kind":"corner","theme":"capture","attacker":"white","b":"bacacbacbc","w":"aadadbccdcadbdcd","region":"aabaabbbcacbacbc","first":"ab","line":"ab"}, + {"id":"T1HZRL","rating":650,"goal":"live","shape":"a straight three","kind":"corner","theme":"capture","attacker":"white","b":"daabbbcbdb","w":"aaeaebacbcccdcec","region":"aabacaabbbcbdadb","first":"ba","line":"ba"}, + {"id":"T1AL34","rating":650,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"capture","attacker":"white","b":"daabcbdbacbccc","w":"caeaebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"TQXS7Q","rating":660,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"capture","attacker":"white","b":"daabcbdbacbccc","w":"eabbebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"T1ALUR","rating":670,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadaabdbacccdcadbdcd","w":"baeaebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T1MV1A","rating":670,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"capture","attacker":"white","b":"daabcbacbccc","w":"caeaebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"TAKUFZ","rating":680,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadadbacccdcadbdcd","w":"eaabebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"THKMED","rating":680,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"capture","attacker":"white","b":"baabcbdbaccc","w":"eabbebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"bc","line":"bc"}, + {"id":"TTD4HT","rating":690,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadadbacccdcadbdcd","w":"eaebbcecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T6QV68","rating":700,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadaabdbacccdcbdcd","w":"eaebbcecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T1LE2A","rating":700,"goal":"kill","shape":"a straight three","kind":"side","theme":"capture","attacker":"black","b":"aadagaabgbacbcccdcecfcgc","w":"bacafabbcbdbebfb","region":"cadaeababbcbdbebfafb","first":"ea","line":"ea"}, + {"id":"T1RTK3","rating":710,"goal":"live","shape":"a straight three","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbdbebfb","w":"aaeagaabgbacbcccdcecfcgc","region":"cadaeababbcbdbebfafb","first":"da","line":"da"}, + {"id":"T1LI4C","rating":720,"goal":"live","shape":"a straight three","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbdbebfb","w":"aacagaabgbacbcccdcecfcgc","region":"cadaeababbcbdbebfafb","first":"da","line":"da"}, + {"id":"TUP6FR","rating":720,"goal":"live","shape":"a pyramid four","kind":"side","theme":"capture","attacker":"white","b":"bacafabbcbebfbccdcec","w":"aagaabdbgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"T15AZS","rating":730,"goal":"live","shape":"a pyramid four","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbdbebfbccdcec","w":"aaeagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"TOVMNS","rating":740,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"capture","attacker":"white","b":"daabcbdbbc","w":"eabbebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"TMDQE9","rating":740,"goal":"live","shape":"a pyramid four","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbebfbccdcec","w":"aaeagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"T5ZSCR","rating":750,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadadbacbcccdcadbdcd","w":"eaabebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T11IMB","rating":760,"goal":"live","shape":"a square four","kind":"corner","theme":"vital point","attacker":"white","b":"aacacbacbccc","w":"dadbdcadbdcddd","region":"aabaabbbcacbacbccc","first":"bb","line":"bb"}, + {"id":"T1YQVC","rating":760,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadbacbcccdcadbdcd","w":"baeacbebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"TCBNXG","rating":770,"goal":"live","shape":"a straight three","kind":"corner","theme":"edge","attacker":"white","b":"daabbbcbdb","w":"eaebacbcccdcec","region":"aabacaabbbcbdadb","first":"ba","line":"ba"}, + {"id":"T1OVO2","rating":780,"goal":"live","shape":"a straight three","kind":"corner","theme":"vital point","attacker":"white","b":"badaabcbdb","w":"eaebacbcccdcec","region":"aabacaabbbcbdadb","first":"bb","line":"bb"}, + {"id":"TZ1BPS","rating":780,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadbacccdcadbd","w":"eaebbcecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T10TBG","rating":790,"goal":"live","shape":"a pyramid four","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbebfbccdcec","w":"aagaabdbgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"TSANGL","rating":800,"goal":"live","shape":"a bulky five","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbebfbbcccdcec","w":"aacagaabgbacfcgcadbdcdddedfd","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"da"}, + {"id":"T1XP1L","rating":800,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadadbacccdcadbd","w":"baeacbebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T1C52L","rating":810,"goal":"live","shape":"a straight four","kind":"corner","theme":"edge","attacker":"white","b":"baeabbcbdbeb","w":"fafbacbcccdcecfc","region":"aabacadaabbbcbdbeaeb","first":"ab","line":"ab"}, + {"id":"TRUYYS","rating":820,"goal":"live","shape":"a pyramid four","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbebccdcec","w":"aaeagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"TKEHVQ","rating":820,"goal":"live","shape":"a bulky five","kind":"side","theme":"capture","attacker":"white","b":"bafabbdbebfbbcccdcec","w":"aacagaabcbgbacfcgcadbdcdddedfd","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"da"}, + {"id":"T1TOF1","rating":830,"goal":"live","shape":"a crossed five","kind":"corner","theme":"capture","attacker":"white","b":"aacadadbccadbdcd","w":"baeacbebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T1GDTO","rating":840,"goal":"live","shape":"a straight four","kind":"side","theme":"edge","attacker":"white","b":"bacagabbcbdbebfbgb","w":"aahaabhbacbcccdcecfcgchc","region":"cadaeafababbcbdbebfbgagb","first":"ea","line":"ea"}, + {"id":"T1TJ3Q","rating":840,"goal":"live","shape":"a straight three","kind":"side","theme":"edge","attacker":"white","b":"bafabbcbdbebfb","w":"aagaabgbacbcccdcecfcgc","region":"cadaeababbcbdbebfafb","first":"da","line":"da"}, + {"id":"TDO716","rating":850,"goal":"live","shape":"a straight four","kind":"corner","theme":"edge","attacker":"white","b":"eaabbbcbdbeb","w":"bafafbacbcccdcecfc","region":"aabacadaabbbcbdbeaeb","first":"ca","line":"ca"}, + {"id":"TVCI12","rating":850,"goal":"live","shape":"a bent four","kind":"corner","theme":"vital point","attacker":"white","b":"aadabbdbacbc","w":"caeaebccdcecadbdcd","region":"aabacaabbbcbdadbacbc","first":"cb","line":"cb"}, + {"id":"TTS5YC","rating":860,"goal":"live","shape":"a straight four","kind":"side","theme":"edge","attacker":"white","b":"bafagabbcbdbebfbgb","w":"aahaabhbacbcccdcecfcgchc","region":"cadaeafababbcbdbebfbgagb","first":"da","line":"da"}, + {"id":"TST1BW","rating":870,"goal":"live","shape":"a crossed five","kind":"corner","theme":"edge","attacker":"white","b":"aacadadbbcccdcadbdcd","w":"eabbebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"ab","line":"ab"}, + {"id":"TPEE6M","rating":870,"goal":"live","shape":"a straight four","kind":"side","theme":"edge","attacker":"white","b":"baeabbcbdbebfbgb","w":"aahaabhbacbcccdcecfcgchc","region":"cadaeafababbcbdbebfbgagb","first":"ga","line":"ga"}, + {"id":"TIDPWP","rating":880,"goal":"live","shape":"a pyramid four","kind":"side","theme":"edge","attacker":"white","b":"bafabbcbdbebfbccdc","w":"aagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"T1FAS4","rating":890,"goal":"live","shape":"a straight four","kind":"side","theme":"edge","attacker":"white","b":"bagabbcbdbebfbgb","w":"aadahaabhbacbcccdcecfcgchc","region":"cadaeafababbcbdbebfbgagb","first":"ea","line":"ea"}, + {"id":"T197I2","rating":890,"goal":"live","shape":"a straight four","kind":"side","theme":"edge","attacker":"white","b":"bagabbcbdbebfbgb","w":"aaeahaabhbacbcccdcecfcgchc","region":"cadaeafababbcbdbebfbgagb","first":"da","line":"da"}, + {"id":"TQCPAN","rating":900,"goal":"live","shape":"a straight five","kind":"corner","theme":"edge","attacker":"white","b":"abbbcbdbebfb","w":"baeagagbacbcccdcecfcgc","region":"aabacadaeaabbbcbdbebfafb","first":"fa","line":"fa"}, + {"id":"T1EPST","rating":910,"goal":"live","shape":"a straight five","kind":"corner","theme":"vital point","attacker":"white","b":"faabbbdbebfb","w":"badagagbacbcccdcecfcgc","region":"aabacadaeaabbbcbdbebfafb","first":"cb","line":"cb"}, + {"id":"T8KHSL","rating":910,"goal":"live","shape":"a straight five","kind":"side","theme":"vital point","attacker":"white","b":"bahabbcbdbebgbhb","w":"aaeafaiaabibacbcccdcecfcgchcic","region":"cadaeafagababbcbdbebfbgbhahb","first":"fb","line":"fb"}, + {"id":"T1NZBO","rating":920,"goal":"live","shape":"a straight five","kind":"side","theme":"vital point","attacker":"white","b":"bahabbcbdbfbgbhb","w":"aadafaiaabibacbcccdcecfcgchcic","region":"cadaeafagababbcbdbebfbgbhahb","first":"eb","line":"eb"}, + {"id":"TX8Y9B","rating":930,"goal":"live","shape":"a rabbity six","kind":"side","theme":"vital point","attacker":"white","b":"bafabbfbbcccdcecfc","w":"aadaeagaabgbacgcadbdcdddedfdgd","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"db","line":"db"}, + {"id":"T1IMH8","rating":930,"goal":"kill","shape":"a straight five","kind":"side","theme":"vital point","attacker":"black","b":"aadafaiaabibacbcccdcecfcgchcic","w":"bahabbcbdbfbgbhb","region":"cadaeafagababbcbdbebfbgbhahb","first":"eb","line":"eb"}, + {"id":"T1JJS2","rating":940,"goal":"kill","shape":"a bent three","kind":"corner","theme":"edge","attacker":"black","b":"dadbccdcadbdcd","w":"aabbcbacbc","region":"aabaabbbcacbacbc","first":"ca","line":"cabaab"}, + {"id":"T1VDSR","rating":950,"goal":"live","shape":"a bulky five","kind":"corner","theme":"capture","attacker":"white","b":"dabbcbdbacbccc","w":"bacaeaebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"aa","line":"aabaca"}, + {"id":"T186JJ","rating":950,"goal":"live","shape":"a bulky five","kind":"corner","theme":"capture","attacker":"white","b":"dacbacbccc","w":"caeaebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"badbab"}, + {"id":"TWNFEV","rating":960,"goal":"live","shape":"a bent three","kind":"corner","theme":"placement","attacker":"white","b":"cabbcbacbc","w":"dadbccdcadbdcd","region":"aabaabbbcacbacbc","first":"aa","line":"aa"}, + {"id":"T1LBQI","rating":970,"goal":"live","shape":"a straight five","kind":"side","theme":"vital point","attacker":"white","b":"bahabbcbdbfbgbhb","w":"aagaiaabibacbcccdcecfcgchcic","region":"cadaeafagababbcbdbebfbgbhahb","first":"eb","line":"eb"}, + {"id":"TURSTM","rating":970,"goal":"live","shape":"a bulky five","kind":"corner","theme":"capture","attacker":"white","b":"cacbbcccadbd","w":"aadadbacdccdddaebece","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbbba"}, + {"id":"T1E2QN","rating":980,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"white","b":"daabcbdbacbccc","w":"eaebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"TQB00J","rating":990,"goal":"live","shape":"a bulky five","kind":"corner","theme":"capture","attacker":"white","b":"cacbbcadbd","w":"dabbdbacdccdddaebece","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abccba"}, + {"id":"T1X5PB","rating":990,"goal":"kill","shape":"a straight five","kind":"corner","theme":"capture","attacker":"black","b":"aacagagbacbcccdcecfcgc","w":"faabcbdbebfb","region":"aabacadaeaabbbcbdbebfafb","first":"bb","line":"bbdaea"}, + {"id":"TZOI9U","rating":1000,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"white","b":"daabcbdbbccc","w":"eaebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"T1L4QU","rating":1010,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"white","b":"daabcbacbccc","w":"eaebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"T18SEO","rating":1010,"goal":"live","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"white","b":"aacadadbacccdcadbdcd","w":"eaebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T1DR7X","rating":1020,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"white","b":"daabcbdbacbc","w":"eaebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"ba"}, + {"id":"TL0WM6","rating":1020,"goal":"live","shape":"a straight four","kind":"corner","theme":"vital point","attacker":"white","b":"eaabbbdbeb","w":"fafbacbcccdcecfc","region":"aabacadaabbbcbdbeaeb","first":"cb","line":"cbbaca"}, + {"id":"TIC7QA","rating":1030,"goal":"live","shape":"a straight four","kind":"corner","theme":"edge","attacker":"white","b":"baeabbcbdb","w":"fafbacbcccdcecfc","region":"aabacadaabbbcbdbeaeb","first":"ab","line":"abebda"}, + {"id":"TW94F1","rating":1040,"goal":"live","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"white","b":"aacadbacccdcadbdcd","w":"eaebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"TW29UI","rating":1040,"goal":"live","shape":"a rabbity six","kind":"side","theme":"capture","attacker":"white","b":"bafabbcbfbbcccdcecfc","w":"aacaeagaabgbacgcadbdcdddedfdgd","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"da","line":"dadbeb"}, + {"id":"T2R6YD","rating":1050,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"edge","attacker":"black","b":"caeaebdcecadbdcddd","w":"daabcbdbacbccc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"babbaa"}, + {"id":"T5ZUXA","rating":1060,"goal":"kill","shape":"a straight four","kind":"corner","theme":"edge","attacker":"black","b":"bafafbacbcccdcecfc","w":"eaabbbcbdbeb","region":"aabacadaabbbcbdbeaeb","first":"ca","line":"cadaaa"}, + {"id":"T1QEB5","rating":1060,"goal":"kill","shape":"an L-shaped five","kind":"corner","theme":"edge","attacker":"black","b":"cafafbccdcecfcadbdcd","w":"eaabbbcbdbebacbc","region":"aabacadaabbbcbdbeaebacbc","first":"ba","line":"badaaa"}, + {"id":"TFF4T0","rating":1070,"goal":"kill","shape":"a straight four","kind":"corner","theme":"edge","attacker":"black","b":"cafafbacbcccdcecfc","w":"eaabbbcbdbeb","region":"aabacadaabbbcbdbeaeb","first":"ba","line":"badaaa"}, + {"id":"T1UEGR","rating":1080,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"edge","attacker":"black","b":"eabbebdcecadbdcddd","w":"daabcbdbacbccc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"bacaaa"}, + {"id":"TQATRD","rating":1080,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"vital point","attacker":"black","b":"eaabebecddedaebecede","w":"aabacadadbacccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbbc"}, + {"id":"TD5WN9","rating":1090,"goal":"kill","shape":"a bent four","kind":"corner","theme":"edge","attacker":"black","b":"aaeaebccdcecadbdcd","w":"dabbcbdbacbc","region":"aabacaabbbcbdadbacbc","first":"ba","line":"bacaab"}, + {"id":"T1HUPQ","rating":1100,"goal":"live","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"white","b":"aacadbacccdcadcd","w":"eaebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T1CORO","rating":1100,"goal":"kill","shape":"a straight three","kind":"side","theme":"edge","attacker":"black","b":"aacagaabgbacbcccdcecfcgc","w":"baeabbcbdbebfb","region":"cadaeababbcbdbebfafb","first":"fa","line":"fadaca"}, + {"id":"T1O7N9","rating":1110,"goal":"kill","shape":"a bulky five","kind":"corner","theme":"edge","attacker":"black","b":"dadbacdccdddaebece","w":"cacbbcccadbd","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbbba"}, + {"id":"T16VY9","rating":1120,"goal":"kill","shape":"a long six","kind":"corner","theme":"edge","attacker":"black","b":"cafafbdcecfcadbdcddd","w":"daeacbdbebacbccc","region":"aabacadaabbbcbdbeaebacbccc","first":"ba","line":"babbab"}, + {"id":"T1AG8G","rating":1120,"goal":"live","shape":"a straight four","kind":"corner","theme":"edge","attacker":"white","b":"abbbcbdbeb","w":"cafafbacbcccdcecfc","region":"aabacadaabbbcbdbeaeb","first":"ba","line":"baeada"}, + {"id":"TS6RNV","rating":1130,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"vital point","attacker":"black","b":"baeaebecddedaebecede","w":"aacadadbacccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbab"}, + {"id":"TG7F41","rating":1140,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"edge","attacker":"black","b":"caeaebdcecadbdcddd","w":"daabcbacbccc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"babbdb"}, + {"id":"TO3EGB","rating":1140,"goal":"live","shape":"a bent four","kind":"corner","theme":"edge","attacker":"white","b":"dabbcbdbac","w":"aaeaebccdcecadbdcd","region":"aabacaabbbcbdadbacbc","first":"ba","line":"babcab"}, + {"id":"T1CSVL","rating":1150,"goal":"kill","shape":"a straight three","kind":"side","theme":"vital point","attacker":"black","b":"aaeagaabgbacbcccdcecfcgc","w":"bacafacbdbebfb","region":"cadaeababbcbdbebfafb","first":"bb","line":"bbdaea"}, + {"id":"T406UU","rating":1160,"goal":"kill","shape":"a straight four","kind":"side","theme":"edge","attacker":"black","b":"aadahaabhbacbcccdcecfcgchc","w":"baeabbcbdbebfbgb","region":"cadaeafababbcbdbebfbgagb","first":"ga","line":"gacafa"}, + {"id":"T1P6QV","rating":1160,"goal":"live","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"white","b":"babbcbebfbccdcec","w":"aagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"T1QFCS","rating":1170,"goal":"live","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"white","b":"bafacbebfbccdcec","w":"aagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"TSIUGE","rating":1170,"goal":"live","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"white","b":"bafabbcbebccdcec","w":"aagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"da"}, + {"id":"T1IJUU","rating":1180,"goal":"live","shape":"a straight four","kind":"side","theme":"vital point","attacker":"white","b":"bagabbcbdbfbgb","w":"aahaabhbacbcccdcecfcgchc","region":"cadaeafababbcbdbebfbgagb","first":"eb","line":"ebdaea"}, + {"id":"T1VU98","rating":1190,"goal":"live","shape":"a pyramid four","kind":"side","theme":"edge","attacker":"white","b":"fabbcbdbfbccdcec","w":"aagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"ea","line":"eadaca"}, + {"id":"TC255C","rating":1190,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"cacbbcccadbd","w":"aabadadbdccdddaebece","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"ab"}, + {"id":"T1JNK8","rating":1200,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"edge","attacker":"black","b":"aagaabdbgbacbcfcgcbdcdddedfd","w":"bafabbcbebfbccdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"dacaea"}, + {"id":"TCZWX6","rating":1210,"goal":"kill","shape":"a straight four","kind":"side","theme":"edge","attacker":"black","b":"aaeahaabhbacbcccdcecfcgchc","w":"bagabbcbdbebfbgb","region":"cadaeafababbcbdbebfbgagb","first":"da","line":"dacafa"}, + {"id":"T1OD4J","rating":1210,"goal":"kill","shape":"a bulky five","kind":"corner","theme":"edge","attacker":"black","b":"aabadadbdccdddaebece","w":"cacbbcccadbd","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbbac"}, + {"id":"TWGBQX","rating":1220,"goal":"kill","shape":"a straight four","kind":"side","theme":"edge","attacker":"black","b":"aadahaabhbacbcccdcecfcgchc","w":"bagabbcbdbebfbgb","region":"cadaeafababbcbdbebfbgagb","first":"ea","line":"eacafa"}, + {"id":"T1TQI0","rating":1230,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"edge","attacker":"black","b":"aaeagaabgbacbcfcgcbdcdddedfd","w":"bafabbcbebfbccdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"dadbca"}, + {"id":"TLT1IE","rating":1230,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"edge","attacker":"black","b":"aacagaabgbacbcfcgcbdcdddedfd","w":"bafabbcbebfbccdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"dadbea"}, + {"id":"T1H7PC","rating":1240,"goal":"live","shape":"an L-shaped five","kind":"corner","theme":"vital point","attacker":"white","b":"eabbdbebacbc","w":"aafaabfbccdcecfcadbdcd","region":"aabacadaabbbcbdbeaebacbc","first":"cb","line":"cbcaba"}, + {"id":"T1R950","rating":1250,"goal":"kill","shape":"a bulky five","kind":"corner","theme":"edge","attacker":"black","b":"caeaebdcecadbdcddd","w":"dacbdbacbccc","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"babbab"}, + {"id":"T1E1K3","rating":1250,"goal":"live","shape":"a straight four","kind":"side","theme":"edge","attacker":"white","b":"bagacbdbebfbgb","w":"aadahaabhbacbcccdcecfcgchc","region":"cadaeafababbcbdbebfbgagb","first":"ea","line":"eabbca"}, + {"id":"TP1365","rating":1260,"goal":"live","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"white","b":"aacadaacccdcadbdcd","w":"eacbebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bb"}, + {"id":"T1FF9L","rating":1270,"goal":"live","shape":"a straight five","kind":"side","theme":"vital point","attacker":"white","b":"babbdbebfbgbhb","w":"aaeaiaabibacbcccdcecfcgchcic","region":"cadaeafagababbcbdbebfbgbhahb","first":"cb","line":"cbdaha"}, + {"id":"T19IYE","rating":1270,"goal":"live","shape":"a two-by-four","kind":"corner","theme":"vital point","attacker":"white","b":"baeaebacbcdcec","w":"dafacbfbfcadbdcdddedfd","region":"aabacadaabbbcbdbeaebacbcccdcec","first":"cc","line":"ccabbb"}, + {"id":"T1XOAW","rating":1280,"goal":"live","shape":"a bulky five","kind":"corner","theme":"capture","attacker":"white","b":"badadbaccc","w":"caeaebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"cb","line":"cbabbcbbaa"}, + {"id":"T1LUNN","rating":1290,"goal":"kill","shape":"a straight three","kind":"corner","theme":"placement","attacker":"black","b":"eaebacbcccdcec","w":"daabbbcbdb","region":"aabacaabbbcbdadb","first":"ba","line":"bacaaa"}, + {"id":"TWA2R9","rating":1290,"goal":"kill","shape":"a bent three","kind":"corner","theme":"placement","attacker":"black","b":"dadbccdcadbdcd","w":"cabbcbacbc","region":"aabaabbbcacbacbc","first":"aa","line":"aabaab"}, + {"id":"TSIZLQ","rating":1300,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"white","b":"daabcbdbaccc","w":"eaebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"babcbb"}, + {"id":"T167OC","rating":1310,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacbcfcgcbdcdddedfd","w":"baeafabbcbebfbccdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"dadbca"}, + {"id":"T1VEZN","rating":1310,"goal":"kill","shape":"a straight three","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacbcccdcecfcgc","w":"bafabbcbdbebfb","region":"cadaeababbcbdbebfafb","first":"da","line":"dacaea"}, + {"id":"T1TY99","rating":1320,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"cacbbcccadbd","w":"aadadbdccdddaebece","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbbba"}, + {"id":"T1IJAY","rating":1330,"goal":"live","shape":"a rabbity six","kind":"corner","theme":"placement","attacker":"white","b":"daabacbccc","w":"eaebecadbdcddded","region":"aabacaabbbcbdadbacbcccdc","first":"ba","line":"badbcb"}, + {"id":"T9SHK3","rating":1330,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"dacbdbacbccc","w":"eabbebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"baabaa"}, + {"id":"TWW9O8","rating":1340,"goal":"live","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"white","b":"daabdbacbccc","w":"eabbebdcecadbdcddd","region":"aabacabbabcbdadbacbccc","first":"ba","line":"bacbca"}, + {"id":"T18FX6","rating":1340,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"dacbdbacbccc","w":"aaeaebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"babbab"}, + {"id":"TCMKY3","rating":1350,"goal":"live","shape":"a long six","kind":"corner","theme":"placement","attacker":"white","b":"daeacbdbebacbccc","w":"fabbfbdcecfcadbdcddd","region":"aabacadaabbbcbdbeaebacbccc","first":"ba","line":"baabaa"}, + {"id":"T1BLD3","rating":1360,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"vital point","attacker":"black","b":"eacbebecddedaebecede","w":"aacadbacccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbbcdabaab"}, + {"id":"TEB0XI","rating":1360,"goal":"kill","shape":"a corner seven","kind":"corner","theme":"vital point","attacker":"black","b":"eaabebeccdddedaebece","w":"cadadbbcccdcadbd","region":"aabacaabbbcbacdadbbcccdcadbd","first":"bb","line":"bbbaaccbaa"}, + {"id":"T1C8YB","rating":1370,"goal":"live","shape":"a straight five","kind":"corner","theme":"vital point","attacker":"white","b":"faabbbdbeb","w":"dagagbacbcccdcecfcgc","region":"aabacadaeaabbbcbdbebfafb","first":"cb","line":"cbfbeabaca"}, + {"id":"T1FRLT","rating":1380,"goal":"live","shape":"a bulky five","kind":"side","theme":"placement","attacker":"white","b":"bafabbebfbbcccdcec","w":"aagaabdbgbacfcgcadbdcdddedfd","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dacacb"}, + {"id":"THGU1T","rating":1380,"goal":"live","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"white","b":"aadadbacccdcadbdcd","w":"baeacbebecddedaebecede","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbabca"}, + {"id":"T1MW13","rating":1390,"goal":"live","shape":"a bulky five","kind":"side","theme":"placement","attacker":"white","b":"bafabbebfbbcccdcec","w":"aacagaabgbacfcgcadbdcdddedfd","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dadbcb"}, + {"id":"T1T7ZZ","rating":1400,"goal":"live","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"white","b":"bbcbebfbccdcec","w":"aacagaabgbacbcfcgcbdcdddedfd","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"dafaba"}, + {"id":"TF4GKD","rating":1400,"goal":"live","shape":"a bulky five","kind":"side","theme":"placement","attacker":"white","b":"babbebfbbcccdcec","w":"aacagaabgbacfcgcadbdcdddedfd","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dafacb"}, + {"id":"T17A07","rating":1410,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"dacbdbacbc","w":"aaeaebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"babbab"}, + {"id":"T19GAM","rating":1420,"goal":"live","shape":"a bulky five","kind":"side","theme":"placement","attacker":"white","b":"bafabbebfbccdcec","w":"aacagaabgbacfcgcadbdcdddedfd","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dabccb"}, + {"id":"TLY13D","rating":1420,"goal":"kill","shape":"a straight five","kind":"corner","theme":"edge","attacker":"black","b":"bagagbacbcccdcecfcgc","w":"fabbcbdbebfb","region":"aabacadaeaabbbcbdbebfafb","first":"ab","line":"abcaaadaea"}, + {"id":"TL2V6D","rating":1430,"goal":"kill","shape":"a carpenter's square","kind":"corner","theme":"edge","attacker":"black","b":"faabfbacccdcecfccdaebece","w":"eabbcbdbebbcbd","region":"aabacadaabacbbcbdbeaebbcadbd","first":"ad","line":"adcaaabada"}, + {"id":"TL7X7O","rating":1440,"goal":"kill","shape":"a corner seven","kind":"corner","theme":"vital point","attacker":"black","b":"aaeaabebeccdddedaebece","w":"dadbbcccdcadbd","region":"aabacaabbbcbacdadbbcccdcadbd","first":"bb","line":"bbcbbacaac"}, + {"id":"TQ071D","rating":1440,"goal":"live","shape":"a bulky five","kind":"side","theme":"placement","attacker":"white","b":"bafabbebfbdcec","w":"aagaabdbgbacfcgcadbdcdddedfd","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dacccb"}, + {"id":"T19INU","rating":1450,"goal":"live","shape":"a corner seven","kind":"corner","theme":"vital point","attacker":"white","b":"dabcccdcadbd","w":"eacbebaceccdddedaebece","region":"aabacaabbbcbacdadbbcccdcadbd","first":"db","line":"dbbbabcaba"}, + {"id":"T52487","rating":1460,"goal":"kill","shape":"a straight five","kind":"corner","theme":"capture","attacker":"black","b":"eagagbacbcccdcecfcgc","w":"faabbbcbdbfb","region":"aabacadaeaabbbcbdbebfafb","first":"eb","line":"ebbadafbfacaaa"}, + {"id":"T1D82M","rating":1460,"goal":"kill","shape":"a bent four","kind":"corner","theme":"sacrifice","attacker":"black","b":"eaabebccdcecadbdcd","w":"cadabbcbacbc","region":"aabacaabbbcbdadbacbc","first":"aa","line":"aadbba"}, + {"id":"T16G1Q","rating":1470,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"black","b":"eaebdcecadbdcddd","w":"aadaabcbdbacbc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"babbcccaba"}, + {"id":"T1FYGH","rating":1480,"goal":"kill","shape":"a square four","kind":"corner","theme":"placement","attacker":"black","b":"dadbdcadbdcddd","w":"caabcbacbc","region":"aabaabbbcacbacbccc","first":"ba","line":"babbccaaba"}, + {"id":"T1O2CJ","rating":1480,"goal":"kill","shape":"a square four","kind":"corner","theme":"placement","attacker":"black","b":"dadbdcadbdcddd","w":"bacbacbccc","region":"aabaabbbcacbacbccc","first":"ab","line":"abbbcaaaab"}, + {"id":"T1FC4N","rating":1490,"goal":"kill","shape":"a square four","kind":"corner","theme":"placement","attacker":"black","b":"dadbdcadbdcddd","w":"caabcbbccc","region":"aabaabbbcacbacbccc","first":"ba","line":"babbacaaba"}, + {"id":"T1G3ZO","rating":1490,"goal":"kill","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"black","b":"dadbdccdddaebece","w":"cacbbcccadbd","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbbaabaac"}, + {"id":"T153O0","rating":1500,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aacadadbacccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbbabcab"}, + {"id":"TO3EQC","rating":1510,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"black","b":"eaebdcecadbdcddd","w":"abcbdbacbccc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"bacadabbaa"}, + {"id":"T16G8R","rating":1510,"goal":"kill","shape":"a rabbity six","kind":"corner","theme":"placement","attacker":"black","b":"eaebecadbdcddded","w":"dacbdbacbcccdc","region":"aabacaabbbcbdadbacbcccdc","first":"ba","line":"babbaacaab"}, + {"id":"TDV27V","rating":1520,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aacadadbacbcccdcadcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbbabdab"}, + {"id":"TFIS8U","rating":1530,"goal":"kill","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"black","b":"eaebdcecadbdcddd","w":"dacbdbacbccc","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"babbaacaab"}, + {"id":"T1I7HR","rating":1530,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"black","b":"eaebdcecadbdcddd","w":"daabcbdbacbc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"baccbbcaaa"}, + {"id":"TVCAEK","rating":1540,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"placement","attacker":"black","b":"eaebdcecadbdcddd","w":"daabcbacbccc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"badbbbcaaa"}, + {"id":"T17F43","rating":1550,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aabacadadbacccdcbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbadbcab"}, + {"id":"T1S79B","rating":1550,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"sacrifice","attacker":"black","b":"aacagaabgbacbcfcgcbdcdddedfd","w":"bafabbcbdbebfbdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"daccea"}, + {"id":"TSSL2A","rating":1560,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aacadadbacccdcadbd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcdbacbab"}, + {"id":"T1LC7Z","rating":1570,"goal":"live","shape":"a long six","kind":"corner","theme":"placement","attacker":"white","b":"daeacbdbebbccc","w":"fafbdcecfcadbdcddd","region":"aabacadaabbbcbdbeaebacbccc","first":"ba","line":"baabacbbaa"}, + {"id":"TM9OWA","rating":1570,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"dacbdbbccc","w":"eaebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"baabacbbaa"}, + {"id":"TO8UFG","rating":1580,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"cacbbcccbd","w":"dadbdccdddaebece","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbaadbbaa"}, + {"id":"T13111","rating":1590,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"cbbcadbd","w":"dadbdccdddaebece","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbacaccbb"}, + {"id":"T1SWB3","rating":1590,"goal":"live","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"white","b":"cbdbacbc","w":"eaebdcecadbdcddd","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"baabdaccbb"}, + {"id":"T14WV4","rating":1600,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"vital point","attacker":"black","b":"eacbebecddedaebecede","w":"aacadadbacccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbbcbaabbbcbba"}, + {"id":"TG3XRD","rating":1610,"goal":"kill","shape":"a bulky five","kind":"corner","theme":"edge","attacker":"black","b":"aadadbdccdddaebece","w":"bacbbcccadbd","region":"aabaabbbaccacbbcccadbd","first":"ab","line":"abbbcaacabaaab"}, + {"id":"T1JNV0","rating":1610,"goal":"kill","shape":"an L-shaped five","kind":"corner","theme":"edge","attacker":"black","b":"cafafbccdcecfcadbdcd","w":"eaabcbdbebacbc","region":"aabacadaabbbcbdbeaebacbc","first":"ba","line":"babbdaaacabada"}, + {"id":"TR2JL0","rating":1620,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"edge","attacker":"black","b":"aaeaebdcecadbdcddd","w":"daabcbacbccc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"babbdbcabaaaba"}, + {"id":"T1HD8B","rating":1630,"goal":"kill","shape":"a rabbity six","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacgcadbdcdddedfdgd","w":"bafabbcbfbbcccdcecfc","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"da","line":"dadbeaebca"}, + {"id":"T1V705","rating":1630,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacbcfcgcbdcdddedfd","w":"bafabbcbebfbdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"daccdbcaea"}, + {"id":"T8M2VK","rating":1640,"goal":"kill","shape":"a bulky five","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacfcgcadbdcdddedfd","w":"bafabbebfbbcccdcec","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dadbcacbea"}, + {"id":"T1E9Q9","rating":1650,"goal":"kill","shape":"a rabbity six","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacgcadbdcdddedfdgd","w":"bacafabbfbbcccdcecfc","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"db","line":"dbebdacbea"}, + {"id":"T14S9F","rating":1650,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacbcfcgcbdcdddedfd","w":"babbcbebfbccdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"daeafadbca"}, + {"id":"T1HL26","rating":1660,"goal":"kill","shape":"a bulky five","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacfcgcadbdcdddedfd","w":"babbcbebbcccdcec","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dafafbdbea"}, + {"id":"T17EJR","rating":1660,"goal":"kill","shape":"a rabbity six","kind":"side","theme":"placement","attacker":"black","b":"aacagaabgbacgcadbdcdddedfdgd","w":"bafabbfbbcccdcecfc","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"db","line":"dbcbdaebea"}, + {"id":"T1X3FJ","rating":1670,"goal":"kill","shape":"a rabbity six","kind":"side","theme":"placement","attacker":"black","b":"aaeagaabgbacgcadbdcdddedfdgd","w":"bafabbfbbcccdcecfc","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"db","line":"dbebdacbca"}, + {"id":"T3V3LD","rating":1680,"goal":"kill","shape":"a straight five","kind":"side","theme":"vital point","attacker":"black","b":"aafaiaabibacbcccdcecfcgchcic","w":"bahabbdbebfbgbhb","region":"cadaeafagababbcbdbebfbgbhahb","first":"cb","line":"cbeacabbbagada"}, + {"id":"T1WZBM","rating":1680,"goal":"kill","shape":"a carpenter's square","kind":"corner","theme":"edge","attacker":"black","b":"aafafbacccdcecfccdaebece","w":"bbcbdbebbcbd","region":"aabacadaabacbbcbdbeaebbcadbd","first":"ad","line":"adabeabadacaaa"}, + {"id":"TEDACO","rating":1690,"goal":"kill","shape":"a straight three","kind":"corner","theme":"sacrifice","attacker":"black","b":"aaeaebacbcccdcec","w":"daabbbcbdb","region":"aabacaabbbcbdadb","first":"ba","line":"bacabaaaba"}, + {"id":"T1EULA","rating":1700,"goal":"kill","shape":"a straight three","kind":"corner","theme":"sacrifice","attacker":"black","b":"caeaebacbcccdcec","w":"daabbbcbdb","region":"aabacaabbbcbdadb","first":"ba","line":"baaabacaba"}, + {"id":"T12WVF","rating":1700,"goal":"kill","shape":"a straight four","kind":"corner","theme":"sacrifice","attacker":"black","b":"cafafbacbcccdcecfc","w":"daeaabbbcbdbeb","region":"aabacadaabbbcbdbeaeb","first":"ba","line":"baaabacaba"}, + {"id":"T1H2UZ","rating":1710,"goal":"kill","shape":"a straight four","kind":"corner","theme":"sacrifice","attacker":"black","b":"aafafbacbcccdcecfc","w":"daeaabbbcbdbeb","region":"aabacadaabbbcbdbeaeb","first":"ba","line":"bacabaaaba"}, + {"id":"TFIAZO","rating":1720,"goal":"kill","shape":"a bulky five","kind":"corner","theme":"placement","attacker":"black","b":"eaebdcecadbdcddd","w":"daabcbdbacbccc","region":"aabacaabbbcbdadbacbccc","first":"ba","line":"babbcaaabacaba"}, + {"id":"TVIOC9","rating":1720,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aabacadadbacccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbbcabbbbcbb"}, + {"id":"T14VN0","rating":1730,"goal":"kill","shape":"a straight three","kind":"side","theme":"sacrifice","attacker":"black","b":"aacagaabgbacbcccdcecfcgc","w":"bafabbcbdbebfb","region":"cadaeababbcbdbebfafb","first":"da","line":"daeacadaca"}, + {"id":"T10M2B","rating":1740,"goal":"kill","shape":"a straight three","kind":"side","theme":"sacrifice","attacker":"black","b":"aaeagaabgbacbcccdcecfcgc","w":"bafabbcbdbebfb","region":"cadaeababbcbdbebfafb","first":"da","line":"dacadaeada"}, + {"id":"T1J82O","rating":1740,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacbcfcgcbdcdddedfd","w":"bafabbcbebfbccdcec","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"dadbcaeacadaca"}, + {"id":"TWSE0T","rating":1750,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aacadadbacccdcad","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbbdbacdabcbbc"}, + {"id":"T1NDZF","rating":1760,"goal":"kill","shape":"a pyramid four","kind":"corner","theme":"edge","attacker":"black","b":"eabbebdcecadbdcddd","w":"daabcbdbbccc","region":"aabacabbabcbdadbacbccc","first":"ba","line":"bacaaccbaadadbccca"}, + {"id":"T126DZ","rating":1760,"goal":"kill","shape":"a straight five","kind":"side","theme":"sacrifice","attacker":"black","b":"aaeagaiaabibacbcccdcecfcgchcic","w":"bacahabbcbdbebfbgbhb","region":"cadaeafagababbcbdbebfbgbhahb","first":"fa","line":"fadafaeaga"}, + {"id":"T9B08R","rating":1770,"goal":"kill","shape":"a straight five","kind":"corner","theme":"vital point","attacker":"black","b":"bagagbacbcccdcecfcgc","w":"faabbbcbebfb","region":"aabacadaeaabbbcbdbebfafb","first":"db","line":"dbcaeafbebaafadaba"}, + {"id":"TT30NZ","rating":1780,"goal":"kill","shape":"a rabbity six","kind":"side","theme":"placement","attacker":"black","b":"aacagaabgbacgcadbdcdddedfdgd","w":"baeafabbfbbcccdcecfc","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"db","line":"dbcbdaebdadbca"}, + {"id":"TP2VL4","rating":1780,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"vital point","attacker":"black","b":"eaabcbebecddedaebecede","w":"aacadadbacccdcadcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbbcbaaabbcbbabdab"}, + {"id":"TWJ3W8","rating":1790,"goal":"kill","shape":"a carpenter's square","kind":"corner","theme":"placement","attacker":"black","b":"aadafafbccdcecfccdaebece","w":"eacbdbebbcadbd","region":"aabacadaabacbbcbdbeaebbcadbd","first":"bb","line":"bbcaacbcbdbada"}, + {"id":"T7B773","rating":1800,"goal":"kill","shape":"a straight four","kind":"corner","theme":"vital point","attacker":"black","b":"fafbacbcccdcecfc","w":"caeaabbbcbeb","region":"aabacadaabbbcbdbeaeb","first":"db","line":"dbbadaebaabaeaabbbcaaa"}, + {"id":"T1CTHZ","rating":1800,"goal":"kill","shape":"an L-shaped five","kind":"corner","theme":"sacrifice","attacker":"black","b":"aacafafbccdcecfcadbdcd","w":"daeabbcbdbacbc","region":"aabacadaabbbcbdbeaebacbc","first":"ba","line":"baabbacaebaaba"}, + {"id":"T15XGY","rating":1810,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aacadbacccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbbaabdabcbbbabb"}, + {"id":"TCW2LZ","rating":1820,"goal":"kill","shape":"a rabbity six","kind":"corner","theme":"placement","attacker":"black","b":"eaebecadbdcddded","w":"cadbacbcccdc","region":"aabacaabbbcbdadbacbcccdc","first":"bb","line":"bbbaabcbdaaabbabbb"}, + {"id":"T1V4BG","rating":1820,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aacadadbacccdcbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbcbbaabadbcbbbabb"}, + {"id":"T7S6RE","rating":1830,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"placement","attacker":"black","b":"eaebecddedaebecede","w":"aacadadbacccdcadcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbbcbaabbdcbbbbabb"}, + {"id":"T12SAX","rating":1830,"goal":"kill","shape":"a straight four","kind":"side","theme":"vital point","attacker":"black","b":"aahaabhbacbcccdcecfcgchc","w":"badagabbcbdbfbgb","region":"cadaeafababbcbdbebfbgagb","first":"eb","line":"ebeafafbcabbgbdbcbeada"}, + {"id":"T1KZUA","rating":1840,"goal":"kill","shape":"a bulky five","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacfcgcadbdcdddedfd","w":"bafabbebfbccdcec","region":"cadaeacbdbbabbebfafbbcccdcec","first":"da","line":"dadbcacbbceacadaca"}, + {"id":"TC31LO","rating":1850,"goal":"kill","shape":"a crossed five","kind":"corner","theme":"vital point","attacker":"black","b":"eacbebbcecddedaebecede","w":"aacadadbccdcadbdcd","region":"baabbbcbbcaacaacccdadbdcadbdcd","first":"bb","line":"bbabbaacbbcbbcbabbbcbb"}, + {"id":"TUZDYI","rating":1850,"goal":"kill","shape":"a rabbity six","kind":"side","theme":"vital point","attacker":"black","b":"aacadagaabgbacgcadbdcdddedfdgd","w":"bafabbfbbcccdcecfc","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"db","line":"dbeacbebcbdbcadacbcacb"}, + {"id":"T1F5D2","rating":1860,"goal":"kill","shape":"a rabbity six","kind":"side","theme":"vital point","attacker":"black","b":"aadaeagaabgbacgcadbdcdddedfdgd","w":"bafabbfbbcccdcecfc","region":"cadaeacbdbebbabbfafbbcccdcecfc","first":"db","line":"dbcaebcbdbebdaeadbdadb"}, + {"id":"TMRRRK","rating":1870,"goal":"kill","shape":"a straight five","kind":"corner","theme":"vital point","attacker":"black","b":"gagbacbcccdcecfcgc","w":"cafaabbbdbebfb","region":"aabacadaeaabbbcbdbebfafb","first":"cb","line":"cbbadaeadaeaaabaebabfabbca"}, + {"id":"TPGOM1","rating":1870,"goal":"kill","shape":"a straight five","kind":"side","theme":"capture","attacker":"black","b":"aafagaiaabibacbcccdcecfcgchcic","w":"bahabbcbdbebfbhb","region":"cadaeafagababbcbdbebfbgbhahb","first":"gb","line":"gbdaeahbcadbhabbcbebbafbda"}, + {"id":"TAPVM6","rating":1880,"goal":"kill","shape":"a straight five","kind":"side","theme":"capture","attacker":"black","b":"aafagaiaabibacbcccdcecfcgchcic","w":"bahabbcbdbfbgbhb","region":"cadaeafagababbcbdbebfbgbhahb","first":"eb","line":"ebdaeagbcabbcbhbbadbdafbha"}, + {"id":"T18A9W","rating":1890,"goal":"kill","shape":"a straight five","kind":"corner","theme":"vital point","attacker":"black","b":"aagagbacbcccdcecfcgc","w":"faabbbcbdbfb","region":"aabacadaeaabbbcbdbebfafb","first":"eb","line":"ebbadacaaabaeaabbbcbaafbca"}, + {"id":"T1DJ24","rating":1890,"goal":"kill","shape":"a pyramid four","kind":"side","theme":"placement","attacker":"black","b":"aagaabgbacbcfcgcbdcdddedfd","w":"bafabbcbebfbdc","region":"cadaeadbbabbcbebfafbccdcec","first":"da","line":"daccdbcaeccbeafbebbafaccbbdcca"}, + {"id":"T13J9A","rating":1900,"goal":"kill","shape":"a straight six","kind":"side","theme":"vital point","attacker":"black","b":"aafagaabacbcccdcecfcgchcic","w":"baiabbcbdbebgbhbib","region":"cadaeafagahababbcbdbebfbgbhbiaib","first":"fb","line":"fbdahahbeaibcadbgbbbiaebcbhbdadbeb"}, +]; diff --git a/src/games/go/GoPuzzles.js b/src/games/go/GoPuzzles.js new file mode 100644 index 0000000..76e7353 --- /dev/null +++ b/src/games/go/GoPuzzles.js @@ -0,0 +1,149 @@ +// GoPuzzles.js: Hōun's lacquer box: the life-and-death ladder and the +// daily problem. The problems live in GoPuzzleData.js (generated and +// checked by tools/genGoPuzzles.js). +// +// loadPuzzleState() / savePuzzleState(st) +// nextLadderPuzzle(st, rng, exclude) an unsolved problem near your rating +// dailyPuzzle(date) { puzzle, number, key }: the same for everyone that day +// ratePuzzle(st, puzzle, result) Elo-style ('solved' | 'failed' | 'assisted') +// dailyStreak(st, date), lastWeek(st, date) +// puzzleSetup(puzzle) → { size, board, region, attacker, goal, +// first, line, map(sq) } with a symmetry +// chosen from the id, so the corner it +// sits in varies +// toProb(setup, board, toMove) a GoTsumego problem + +import { PUZZLES, PUZZLE_SIZE } from './GoPuzzleData.js'; + +export { PUZZLES, PUZZLE_SIZE }; +const KEY = 'go-puzzles'; +const DEFAULT = { rating: 800, solved: {}, failed: {}, streak: 0, best: 0, played: 0, daily: {} }; + +export function loadPuzzleState() { + try { + const s = JSON.parse(localStorage.getItem(KEY) || '{}'); + return { ...DEFAULT, ...s, solved: { ...(s.solved ?? {}) }, failed: { ...(s.failed ?? {}) }, daily: { ...(s.daily ?? {}) } }; + } catch (_) { return { ...DEFAULT, solved: {}, failed: {}, daily: {} }; } +} + +export function savePuzzleState(st) { + try { localStorage.setItem(KEY, JSON.stringify(st)); } catch (_) { /* private mode */ } +} + +export function dateKey(d = new Date()) { + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '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; + }; +} + +let DAILY_ORDER = null; +function dailyPool() { + const pool = PUZZLES.filter((p) => p.rating >= 800); + return pool.length >= 20 ? pool : PUZZLES; +} + +export function dailyPuzzle(date = new Date()) { + const pool = dailyPool(); + if (!DAILY_ORDER || DAILY_ORDER.length !== pool.length) { + const rnd = seeded(20261201 ^ 0x60); + DAILY_ORDER = pool.map((_, i) => i); + for (let i = DAILY_ORDER.length - 1; i > 0; i--) { + const j = Math.floor(rnd() * (i + 1)); + [DAILY_ORDER[i], DAILY_ORDER[j]] = [DAILY_ORDER[j], DAILY_ORDER[i]]; + } + } + const day = Math.floor((Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(2026, 0, 1)) / 86400000); + const n = ((day % pool.length) + pool.length) % pool.length; + return { puzzle: pool[DAILY_ORDER[n]], number: day + 1, key: dateKey(date) }; +} + +export function nextLadderPuzzle(st, rng = Math.random, exclude = null) { + let pool = PUZZLES.filter((p) => !st.solved[p.id] && p.id !== exclude); + if (!pool.length) pool = PUZZLES.filter((p) => p.id !== exclude); + const target = st.rating + (rng() - 0.4) * 160; + const near = pool.slice().sort((a, b) => Math.abs(a.rating - target) - Math.abs(b.rating - target)).slice(0, 8); + return near[Math.floor(rng() * near.length)] ?? PUZZLES[0]; +} + +export function ratePuzzle(st, puzzle, result) { + if (result === 'assisted') { st.played++; st.streak = 0; return 0; } + const exp = 1 / (1 + Math.pow(10, (puzzle.rating - st.rating) / 400)); + const k = st.played < 10 ? 48 : 28; + const score = result === 'solved' ? 1 : 0; + const d = Math.round(k * (score - exp)); + st.rating = Math.max(300, Math.min(2600, st.rating + d)); + st.played++; + if (result === 'solved') { st.solved[puzzle.id] = true; st.streak++; st.best = Math.max(st.best, st.streak); } + else { st.failed[puzzle.id] = true; st.streak = 0; } + return d; +} + +export function dailyStreak(st, date = new Date()) { + let n = 0; + const d = new Date(date); + if (st.daily[dateKey(d)] !== 'solved') d.setDate(d.getDate() - 1); + while (st.daily[dateKey(d)] === 'solved') { n++; d.setDate(d.getDate() - 1); } + return n; +} + +export function lastWeek(st, date = new Date()) { + const out = []; + for (let i = 6; i >= 0; i--) { + const d = new Date(date); + d.setDate(d.getDate() - i); + out.push({ key: dateKey(d), label: 'SMTWTFS'[d.getDay()], state: st.daily[dateKey(d)] ?? null, today: i === 0 }); + } + return out; +} + +export const THEME_LABEL = { + capture: 'Capture', sacrifice: 'Sacrifice', placement: 'Placement', edge: 'On the edge', 'vital point': 'Vital point', +}; + +// ── the board ──────────────────────────────────────────────────────────────── +const A = 'abcdefghijklmnopqrs'; +const pairs = (s) => { const out = []; for (let i = 0; i + 1 < (s?.length ?? 0); i += 2) out.push([A.indexOf(s[i]), A.indexOf(s[i + 1])]); return out; }; + +function hashId(id) { + let h = 2166136261; + for (const ch of id) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); } + return h >>> 0; +} + +/** One of the board's eight symmetries, picked by the puzzle's id. */ +export function symmetryOf(id, size = PUZZLE_SIZE) { + const k = hashId(id) % 8; + const n = size - 1; + return ([c, r]) => { + let x = c, y = r; + if (k & 4) [x, y] = [y, x]; + if (k & 1) x = n - x; + if (k & 2) y = n - y; + return y * size + x; + }; +} + +export function puzzleSetup(p, { sym = true } = {}) { + const size = PUZZLE_SIZE; + const map = sym ? symmetryOf(p.id, size) : ([c, r]) => r * size + c; + const board = Array(size * size).fill(null); + for (const cr of pairs(p.b)) board[map(cr)] = 'black'; + for (const cr of pairs(p.w)) board[map(cr)] = 'white'; + const region = pairs(p.region).map(map); + const first = map(pairs(p.first)[0]); + const line = pairs(p.line).map(map); + return { size, board, region, attacker: p.attacker, goal: p.goal, first, line, id: p.id }; +} + +export function toProb(setup, board, toMove, extra = {}) { + return { size: setup.size, board: board.slice(), region: setup.region, attacker: setup.attacker, toMove, ko: -1, passed: false, ...extra }; +} diff --git a/src/games/go/GoSgf.js b/src/games/go/GoSgf.js new file mode 100644 index 0000000..ce825f8 --- /dev/null +++ b/src/games/go/GoSgf.js @@ -0,0 +1,224 @@ +// GoSgf.js: game records in SGF (FF[4], GM[1]), the format every Go +// program and server reads. +// +// toSgf(gs, { black, white, date }) → string +// parseSgf(text) → { gs, info } (the main line; a +// replayable GoLogic game) or throws +// downloadSgf(gs, names) saves a .sgf file +// pickSgfFile() → Promise (file picker) + +import { createGame, play, pass, finish, resign, timeLoss, resumePlay, BLACK, WHITE, SIZES } from './GoLogic.js'; + +const A = 'abcdefghijklmnopqrs'; +const pt = (sq, size) => A[sq % size] + A[Math.floor(sq / size)]; +const esc = (s) => String(s ?? '').replace(/\\/g, '\\\\').replace(/]/g, '\\]'); + +export function toSgf(gs, { black = 'Black', white = 'White', date = new Date(), comments = {} } = {}) { + const size = gs.size; + const d = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; + let head = `;GM[1]FF[4]CA[UTF-8]AP[Unkai-ji:1]SZ[${size}]KM[${gs.komi}]RU[${gs.rules === 'chinese' ? 'Chinese' : 'Japanese'}]`; + head += `PB[${esc(black)}]PW[${esc(white)}]DT[${d}]`; + if (gs.handicap) head += `HA[${gs.handicap}]`; + const res = resultOf(gs); + if (res) head += `RE[${res}]`; + if (gs.setup.black.length) head += `AB${gs.setup.black.map((s) => `[${pt(s, size)}]`).join('')}`; + if (gs.setup.white.length) head += `AW${gs.setup.white.map((s) => `[${pt(s, size)}]`).join('')}`; + if (gs.setup.black.length || gs.setup.white.length) head += `PL[${(gs.history[0]?.color ?? gs.turn) === BLACK ? 'B' : 'W'}]`; + const nodes = gs.history.map((h, i) => { + const c = h.color === BLACK ? 'B' : 'W'; + let s = `;${c}[${h.pass ? '' : pt(h.sq, size)}]`; + if (comments[i]) s += `C[${esc(comments[i])}]`; + return s; + }); + if (gs.phase === 'over' && gs.endReason === 'score' && gs.dead?.length) { + // the agreed dead stones, as territory marks on a final node (common practice) + const tb = [], tw = []; + gs.score?.owner?.forEach((o, sq) => { if (!gs.board[sq] || gs.dead.includes(sq)) { if (o === BLACK) tb.push(sq); else if (o === WHITE) tw.push(sq); } }); + let f = ';'; + if (tb.length) f += `TB${tb.map((s) => `[${pt(s, size)}]`).join('')}`; + if (tw.length) f += `TW${tw.map((s) => `[${pt(s, size)}]`).join('')}`; + if (f.length > 1) nodes.push(f); + } + // wrap long lines a little for readability + const lines = []; + let cur = ''; + for (const n of nodes) { if (cur.length + n.length > 72) { lines.push(cur); cur = ''; } cur += n; } + if (cur) lines.push(cur); + return `(${head}\n${lines.join('\n')})\n`; +} + +function resultOf(gs) { + if (gs.phase !== 'over' || !gs.winner) return ''; + if (gs.winner === 'draw') return '0'; + const w = gs.winner === BLACK ? 'B' : 'W'; + if (gs.endReason === 'resign') return `${w}+R`; + if (gs.endReason === 'time') return `${w}+T`; + return `${w}+${gs.score?.margin ?? ''}`; +} + +/** Tokenise an SGF into the main line's nodes: [{ PROP: [values] }]. */ +function mainLine(text) { + const nodes = []; + let i = text.indexOf('('); + if (i < 0) throw new Error('Not an SGF file'); + // the main line follows the first variation at every branch: it ends at + // the first ')' we meet + let cur = null, done = false; + const n = text.length; + for (; i < n && !done; i++) { + const ch = text[i]; + if (ch === ')') { + done = true; + } else if (ch === ';') { + cur = {}; + nodes.push(cur); + } else if (/[A-Z]/.test(ch)) { + let id = ''; + while (i < n && /[A-Za-z]/.test(text[i])) { if (/[A-Z]/.test(text[i])) id += text[i]; i++; } + const vals = []; + while (i < n) { + while (i < n && /\s/.test(text[i])) i++; + if (text[i] !== '[') break; + i++; + let v = ''; + while (i < n && text[i] !== ']') { + if (text[i] === '\\') { i++; if (text[i] === '\n') { i++; continue; } } + v += text[i]; i++; + } + vals.push(v); + i++; + } + i--; + if (cur) cur[id] = (cur[id] ?? []).concat(vals); + } + } + return nodes; +} + +const sqOfPt = (v, size) => { + if (!v || v.length < 2) return -1; + const c = A.indexOf(v[0]), r = A.indexOf(v[1]); + if (c < 0 || r < 0 || c >= size || r >= size) return -1; // 'tt' is a pass on ≤19 + return r * size + c; +}; +const expand = (vals, size) => { + // compressed point lists: 'aa:cc' is a rectangle + const out = []; + for (const v of vals ?? []) { + if (v.includes(':')) { + const [a, b] = v.split(':'); + const c0 = A.indexOf(a[0]), r0 = A.indexOf(a[1]), c1 = A.indexOf(b[0]), r1 = A.indexOf(b[1]); + for (let r = Math.min(r0, r1); r <= Math.max(r0, r1); r++) for (let c = Math.min(c0, c1); c <= Math.max(c0, c1); c++) out.push(r * size + c); + } else { + const s = sqOfPt(v, size); + if (s >= 0) out.push(s); + } + } + return out; +}; + +export function parseSgf(text) { + const nodes = mainLine(String(text)); + if (!nodes.length) throw new Error('The file has no game in it'); + const root = nodes[0]; + if (root.GM && root.GM[0] !== '1') throw new Error('That record is not a Go game'); + const size = parseInt(root.SZ?.[0] ?? '19', 10); + if (!SIZES.includes(size)) throw new Error(`Only 9, 13 and 19 line boards are supported (this is ${size}×${size})`); + const komi = parseFloat(root.KM?.[0] ?? '6.5'); + const rules = /chin|aga|area|nz/i.test(root.RU?.[0] ?? '') ? 'chinese' : 'japanese'; + const ab = expand(root.AB, size), aw = expand(root.AW, size); + const handicap = parseInt(root.HA?.[0] ?? '0', 10) || 0; + // who moves first: PL, else the first move's colour, else white with a handicap + let first = root.PL?.[0] === 'W' ? WHITE : root.PL?.[0] === 'B' ? BLACK : null; + if (!first) { + const m = nodes.find((nd) => nd.B || nd.W); + first = m ? (m.B ? BLACK : WHITE) : (ab.length ? WHITE : BLACK); + } + let gs = createGame({ size, komi: Number.isFinite(komi) ? komi : 6.5, rules, setup: { black: ab, white: aw }, turn: first }); + gs.handicap = handicap >= 2 ? handicap : 0; + const comments = {}; + let skipped = 0; + for (let k = 1; k < nodes.length; k++) { + const nd = nodes[k]; + const col = nd.B ? BLACK : nd.W ? WHITE : null; + if (!col) continue; + if (gs.phase === 'scoring') gs = resumePlay(gs); // play went on after two passes + if (gs.turn !== col) { + // out-of-turn moves (some records do this): insert a pass to keep going + gs = pass(gs); + if (gs.phase === 'scoring') gs = resumePlay(gs); + } + const v = (nd.B ?? nd.W)[0]; + const sq = sqOfPt(v, size); + const next = sq < 0 ? pass(gs) : play(gs, sq); + if (!next) { skipped++; break; } + gs = next; + if (nd.C) comments[gs.history.length - 1] = nd.C[0]; + } + // the result, if recorded + const re = root.RE?.[0] ?? ''; + const m = /^([BW])\+(R|Resign|T|Time|[\d.]+)?/i.exec(re); + if (m) { + const winner = m[1].toUpperCase() === 'B' ? BLACK : WHITE; + const how = (m[2] ?? '').toUpperCase(); + if (how.startsWith('R')) gs = resign({ ...gs, phase: 'playing' }, winner === BLACK ? WHITE : BLACK); + else if (how.startsWith('T')) gs = timeLoss({ ...gs, phase: 'playing' }, winner === BLACK ? WHITE : BLACK); + else if (gs.phase === 'scoring') gs = finish(gs, []); + else { gs = { ...gs, phase: 'over', winner, endReason: 'record', score: null }; } + if (how && !isNaN(parseFloat(how))) gs.recordMargin = parseFloat(how); + } else if (/^(0|Draw|Jigo)/i.test(re)) { + gs = { ...gs, phase: 'over', winner: 'draw', endReason: 'record' }; + } else if (gs.phase === 'scoring') { + gs = finish(gs, []); + } + return { + gs, + info: { + black: root.PB?.[0] ?? 'Black', white: root.PW?.[0] ?? 'White', + result: re, event: root.EV?.[0] ?? root.GN?.[0] ?? '', date: root.DT?.[0] ?? '', + comments, skipped, moves: gs.history.length, + }, + }; +} + +export function downloadSgf(gs, names = {}) { + try { + const text = toSgf(gs, names); + const blob = new Blob([text], { type: 'application/x-go-sgf' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + const d = new Date(); + a.href = url; + a.download = `unkai-ji-${gs.size}x${gs.size}-${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}.sgf`; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 2000); + return true; + } catch (_) { return false; } +} + +export function pickSgfFile() { + return new Promise((resolve) => { + try { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = '.sgf,application/x-go-sgf,text/plain'; + input.style.display = 'none'; + let settled = false; + const done = (v) => { if (settled) return; settled = true; input.remove(); resolve(v); }; + input.addEventListener('change', () => { + const f = input.files?.[0]; + if (!f) { done(null); return; } + if (f.size > 2_000_000) { done(null); return; } + f.text().then(done, () => done(null)); + }); + input.addEventListener('cancel', () => done(null)); + // browsers without a cancel event: when the window gets focus back and + // no file came, give up + window.addEventListener('focus', () => setTimeout(() => { if (!input.files?.length) done(null); }, 1200), { once: true }); + document.body.appendChild(input); + input.click(); + } catch (_) { resolve(null); } + }); +} diff --git a/src/games/go/GoSound.js b/src/games/go/GoSound.js new file mode 100644 index 0000000..ee74a48 --- /dev/null +++ b/src/games/go/GoSound.js @@ -0,0 +1,258 @@ +// GoSound.js: Web Audio synths for Unkai-ji. No audio files; silent +// without Web Audio or when muted. +// +// pachi(scene) slate on kaya: the sharp click of a stone set +// down, the board's wooden ring under it +// rustle(scene) fingers in the bowl, picking out a stone +// clatter(scene, n) captured stones dropped into a lid +// deny(scene) not a legal point +// tick(scene, urgent) the byo-yomi count +// bell(scene, vol) the temple bell (bonshō), far down the valley +// chime(scene) a glass wind-bell (fūrin) on the veranda +// sting(scene, kind) 'win' / 'lose' / 'draw' / 'solved' / 'wrong': +// a plucked koto phrase in a pentatonic mode +// Ambience mountain wind, birds at dawn, now and then the +// bell or the wind-bell + +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 } = {}) { + 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); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03); +} +function burst(ac, dest, t0, f, vol = 1, d = 0.03, q = 3, type = 'bandpass') { + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = type; 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 */ } }; + +// a plucked string (Karplus–Strong), cached per pitch +const pluckCache = new WeakMap(); +function pluckBuf(ac, f, dur = 1.6) { + let m = pluckCache.get(ac); + if (!m) { m = new Map(); pluckCache.set(ac, m); } + const key = Math.round(f * 10); + if (m.has(key)) return m.get(key); + const sr = ac.sampleRate, n = Math.ceil(sr * dur), p = Math.max(2, Math.round(sr / f)); + const buf = ac.createBuffer(1, n, sr), d = buf.getChannelData(0); + const ring = new Float32Array(p); + for (let i = 0; i < p; i++) ring[i] = Math.random() * 2 - 1; + let idx = 0; + const decay = 0.996; + for (let i = 0; i < n; i++) { + const a = ring[idx], b = ring[(idx + 1) % p]; + const v = (a + b) * 0.5 * decay; + d[i] = a; + ring[idx] = v; + idx = (idx + 1) % p; + } + m.set(key, buf); + return buf; +} +function pluck(ac, dest, t, f, a = 0.5) { + const src = ac.createBufferSource(); src.buffer = pluckBuf(ac, f); + const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = Math.min(9000, f * 9); + const g = ac.createGain(); g.gain.setValueAtTime(a, t); g.gain.exponentialRampToValueAtTime(0.001, t + 1.55); + src.connect(lp); lp.connect(g); g.connect(dest); src.start(t); src.stop(t + 1.6); +} +const semi = (f, n) => f * Math.pow(2, n / 12); +// miyako-bushi / in scale (a koto's): 0 1 5 7 8 +const IN = [0, 1, 5, 7, 8, 12, 13, 17, 19, 20, 24]; +const YO = [0, 2, 5, 7, 9, 12, 14, 17, 19, 21, 24]; + +export function pachi(scene, { vol = 0.16 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.003; + const v = 0.9 + Math.random() * 0.2; + // the stone's crack: a very short bright transient + burst(ac, dest, t, 3600 * v, 1.0, 0.012, 1.4); + burst(ac, dest, t, 7000, 0.5, 0.006, 0.8, 'highpass'); + // the board answers: a dry wooden ring with a short body + tone(ac, dest, t + 0.001, 920 * v, { type: 'triangle', a: 0.35, d: 0.07 }); + tone(ac, dest, t + 0.001, 1480 * v, { type: 'sine', a: 0.18, d: 0.05 }); + tone(ac, dest, t, 190, { a: 0.6, d: 0.09, glide: 0.8 }); + }); +} + +export function rustle(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003; + for (let i = 0; i < 6; i++) burst(ac, dest, t + i * 0.018 + Math.random() * 0.012, 2600 + Math.random() * 3000, 0.5 + Math.random() * 0.4, 0.012, 3); + }); +} + +export function clatter(scene, n = 1) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.003; + const k = Math.min(14, 2 + n * 2); + for (let i = 0; i < k; i++) { + const at = t + i * (0.03 + Math.random() * 0.04); + burst(ac, dest, at, 2200 + Math.random() * 2600, 0.6 + Math.random() * 0.4, 0.015, 2.5); + tone(ac, dest, at, 700 + Math.random() * 400, { type: 'triangle', a: 0.12, d: 0.04 }); + } + }); +} + +export function deny(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.003; + tone(ac, dest, t, 180, { a: 0.7, d: 0.12, glide: 0.75 }); + burst(ac, dest, t, 600, 0.4, 0.03); + }); +} + +export function tick(scene, urgent = false) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, urgent ? 0.09 : 0.05), t = ac.currentTime + 0.003; + // a wooden clapper (hyōshigi) + burst(ac, dest, t, urgent ? 2400 : 1800, 1, 0.02, 6); + tone(ac, dest, t, urgent ? 1250 : 980, { type: 'triangle', a: 0.4, d: 0.05 }); + }); +} + +/** The temple bell: inharmonic partials, a slow beat, a long tail. */ +export function bell(scene, vol = 0.05) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.02; + const f = 82 + Math.random() * 6; + const parts = [[1, 1, 7.5], [1.003, 0.6, 7.5], [2.02, 0.45, 5.5], [2.76, 0.4, 4.2], [3.4, 0.22, 3.2], [5.4, 0.12, 2], [8.9, 0.05, 1.2]]; + for (const [m, a, d] of parts) tone(ac, dest, t, f * m, { a, d, attack: 0.01 }); + burst(ac, dest, t, 400, 0.4, 0.15, 1); // the log striking + }); +} + +export function chime(scene, vol = 0.025) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.01; + const f = 2400 + Math.random() * 900; + const n = 2 + Math.floor(Math.random() * 3); + for (let i = 0; i < n; i++) { + const at = t + i * (0.18 + Math.random() * 0.25), ff = f * (0.97 + Math.random() * 0.06); + tone(ac, dest, at, ff, { a: 0.5, d: 1.6, attack: 0.002 }); + tone(ac, dest, at, ff * 2.76, { a: 0.12, d: 0.6, attack: 0.002 }); + } + }); +} + +export function sting(scene, kind = 'win') { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.1), t = ac.currentTime + 0.02; + const root = 293.66; // D + let phrase; + if (kind === 'win') phrase = [[0, YO, 0], [0.16, YO, 2], [0.32, YO, 3], [0.48, YO, 4], [0.68, YO, 5], [0.7, YO, 3], [0.72, YO, 0]]; + else if (kind === 'solved') phrase = [[0, YO, 3], [0.12, YO, 4], [0.26, YO, 5], [0.28, YO, 7]]; + else if (kind === 'lose') phrase = [[0, IN, 5], [0.2, IN, 4], [0.4, IN, 2], [0.65, IN, 1], [0.95, IN, 0]]; + else if (kind === 'wrong') phrase = [[0, IN, 3], [0.18, IN, 1]]; + else phrase = [[0, YO, 0], [0.2, YO, 3], [0.4, YO, 1], [0.62, YO, 0], [0.64, YO, 3]]; + for (const [at, scale, deg] of phrase) { + const f = semi(root, scale[Math.min(deg, scale.length - 1)]); + pluck(ac, dest, t + at, f, 0.55); + } + }); +} + +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(() => { + // mountain wind: low band-limited noise, slowly gusting + const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true; + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 420; bp.Q.value = 0.6; + const g = out(this.scene, ac, 0.0); + g.gain.setValueAtTime(0, ac.currentTime); + g.gain.linearRampToValueAtTime(0.012, ac.currentTime + 3); + const lfo = ac.createOscillator(); lfo.frequency.value = 0.05; + const lg = ac.createGain(); lg.gain.value = 0.007; + lfo.connect(lg); lg.connect(g.gain); + const lfo2 = ac.createOscillator(); lfo2.frequency.value = 0.13; + const lg2 = ac.createGain(); lg2.gain.value = 160; + lfo2.connect(lg2); lg2.connect(bp.frequency); + src.connect(bp); bp.connect(g); + src.start(); lfo.start(); lfo2.start(); + this.beds.push({ src, lfos: [lfo, lfo2], g }); + }); + } + const birds = () => { + if (!this.on) return; + this.birdTimer = setTimeout(birds, 2500 + Math.random() * 6000); + const a = ctxOf(this.scene); if (!a) return; + safe(() => { + const dest = out(this.scene, a, 0.012 + Math.random() * 0.01), t = a.currentTime + 0.01; + const f = 2600 + Math.random() * 1800; + const n = 2 + Math.floor(Math.random() * 4); + for (let i = 0; i < n; i++) { + const at = t + i * (0.09 + Math.random() * 0.07); + tone(a, dest, at, f * (0.9 + Math.random() * 0.25), { a: 0.6, d: 0.07 + Math.random() * 0.05, glide: Math.random() < 0.5 ? 1.25 : 0.8 }); + } + }); + }; + this.birdTimer = setTimeout(birds, 1500); + const event = () => { + this.timer = setTimeout(event, 14000 + Math.random() * 16000); + if (!this.on) return; + if (Math.random() < 0.35) bell(this.scene, 0.03); + else chime(this.scene, 0.018); + }; + this.timer = setTimeout(event, 6000); + } + + stop() { + this.on = false; + clearTimeout(this.timer); this.timer = null; + clearTimeout(this.birdTimer); this.birdTimer = null; + for (const { src, lfos, 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); + for (const l of lfos) l.stop(ac.currentTime + 0.7); + }); + } + this.beds = []; + } + + setOn(on) { if (on) this.start(); else this.stop(); } +} diff --git a/src/games/go/GoStones.js b/src/games/go/GoStones.js new file mode 100644 index 0000000..34f84af --- /dev/null +++ b/src/games/go/GoStones.js @@ -0,0 +1,237 @@ +// GoStones.js: the stones on the kaya. Each stone is a soft shadow and a +// face (slate, or one of four clamshells turned at random, so no two white +// stones look alike), set down a hair off the exact point the way real +// stones never sit quite true. +// +// StoneSet build(board, size) · place(sq, color, from) (a throw from the +// bowl that lands with a little slide) · capture(sqs, lid) +// (the stones lift and fly into the capturer's lid) · +// remove(sq) · setDead(sqs) (dimmed, for the count) · clear() +// LidPile the prisoners heaped in a bowl's lid: set(n, color), +// add(n, color), target() (where the next one lands) + +import { pointXY, geom, STONE_R } from './GoLayout.js'; +import { RES, WHITE_VARIANTS } from './GoArt.js'; + +function hash(n) { + let x = (n * 2654435761) >>> 0; + x ^= x >>> 15; x = Math.imul(x, 2246822519) >>> 0; x ^= x >>> 13; + return (x >>> 0) / 4294967296; +} + +export class StoneSet { + constructor(scene, depth) { + this.scene = scene; + this.depth = depth; + this.items = new Map(); // sq → item + this.size = 9; + this.live = new Set(); + this.serial = 0; + } + + 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; + } + + /** Where a stone on sq actually rests (a little off the point). */ + rest(sq, salt) { + const p = pointXY(sq, this.size); + const { SQ } = geom(this.size); + const j = SQ * 0.035; + return { x: p.x + (hash(sq * 31 + salt) - 0.5) * 2 * j, y: p.y + (hash(sq * 17 + salt * 7) - 0.5) * 2 * j }; + } + + make(sq, color, at = null) { + const s = this.scene; + const salt = ++this.serial; + const r = at ?? this.rest(sq, salt); + const variant = Math.floor(hash(sq * 13 + salt * 3) * WHITE_VARIANTS); + const key = color === 'black' ? 'go-black' : `go-white-${variant}`; + const shadow = s.add.image(r.x, r.y, 'go-shadow'); + const face = s.add.image(r.x, r.y, key).setRotation(color === 'white' ? hash(sq + salt * 5) * Math.PI * 2 : 0); + const it = { sq, color, salt, shadow, face, x: r.x, y: r.y, lift: 0, grow: 1, alpha: 1, dead: false, gone: false }; + this.render(it); + return it; + } + + render(it) { + if (it.gone) return; + const b = this.base * it.grow; + const lift = it.lift * geom(this.size).scale; + it.face.setPosition(it.x, it.y - lift).setScale(b).setAlpha(it.alpha * (it.dead ? 0.5 : 1)); + const sh = 1 + lift / 120; + it.shadow.setPosition(it.x + 3 * this.base * RES + lift * 0.35, it.y + 5 * this.base * RES + lift * 0.5) + .setScale(b * sh).setAlpha(it.alpha * (0.7 - Math.min(0.45, lift / 120)) * (it.dead ? 0.4 : 1)); + const d = this.depth + (lift > 1 ? 52 : 0) + it.y / 4000; + it.face.setDepth(d); it.shadow.setDepth(this.depth - 1); + } + + destroyItem(it) { + it.gone = true; + it.face.destroy(); it.shadow.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()]; } + + tween(cfg) { + return new Promise((res) => { + const t = this.scene.tweens.add({ ...cfg, onComplete: () => { this.live.delete(t); res(); } }); + this.live.add(t); + }); + } + + /** Bring the sprites in line with a board (after undo, resume, review). */ + sync(board) { + for (const [sq, it] of [...this.items]) { + if (board[sq] !== it.color) { this.destroyItem(it); this.items.delete(sq); } + } + board.forEach((v, sq) => { if (v && !this.items.has(sq)) this.items.set(sq, this.make(sq, v)); }); + } + + /** Throw a stone from `from` to sq: an arc, a touch down, a short slide into place. */ + async place(sq, color, from, { dur = 360, arc = 70 } = {}) { + const old = this.items.get(sq); + if (old) { this.destroyItem(old); this.items.delete(sq); } + const it = this.make(sq, color, from); + this.items.set(sq, it); + const to = this.rest(sq, it.salt); + // land a little short, then slide the last bit, as a hand does + const dx = to.x - from.x, dy = to.y - from.y, len = Math.hypot(dx, dy) || 1; + const slide = Math.min(geom(this.size).SQ * 0.22, 14); + const touch = { x: to.x - (dx / len) * slide, y: to.y - (dy / len) * slide }; + it.grow = 0.92; + 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 + (touch.x - from.x) * t; + it.y = from.y + (touch.y - from.y) * t; + it.lift = Math.sin(Math.PI * t) * arc + (1 - t) * 6; + it.grow = 0.92 + 0.08 * t; + this.render(it); + }, + }); + if (it.gone) return it; + it.lift = 0; it.grow = 1; + const s = { t: 0 }, sx = it.x, sy = it.y; + await this.tween({ + targets: s, t: 1, duration: 110, ease: 'Quad.Out', + onUpdate: () => { it.x = sx + (to.x - sx) * s.t; it.y = sy + (to.y - sy) * s.t; this.render(it); }, + }); + it.x = to.x; it.y = to.y; + this.render(it); + return it; + } + + /** Put a stone straight down (handicap stones, puzzles). */ + async drop(sq, color, { delay = 0, dur = 220 } = {}) { + const it = this.make(sq, color); + this.items.set(sq, it); + it.lift = 70; it.alpha = 0; + this.render(it); + await new Promise((res) => this.scene.time.delayedCall(delay, res)); + if (it.gone) return; + const o = { l: 70 }; + await this.tween({ targets: o, l: 0, duration: dur, ease: 'Quad.In', onUpdate: () => { it.lift = o.l; it.alpha = 1 - o.l / 70; this.render(it); } }); + it.lift = 0; it.alpha = 1; this.render(it); + } + + /** Lift captured stones and fly them into a lid, one after another. */ + async capture(sqs, lid, { stagger = 70, dur = 420, onLand = null } = {}) { + const jobs = sqs.map((sq, i) => { + const it = this.items.get(sq); + if (!it) return Promise.resolve(); + this.items.delete(sq); + const from = { x: it.x, y: it.y }; + const to = lid.target(); + const o = { t: 0 }; + return this.tween({ + targets: o, t: 1, delay: i * stagger, 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) * 60 + (t < 0.2 ? t * 60 : 0); + it.grow = 1 - 0.5 * t; + this.render(it); + }, + }).then(() => { this.destroyItem(it); onLand?.(i); }); + }); + await Promise.all(jobs); + } + + remove(sq) { + const it = this.items.get(sq); + if (!it) return; + this.destroyItem(it); + this.items.delete(sq); + } + + setDead(sqs) { + const set = new Set(sqs); + for (const it of this.items.values()) { it.dead = set.has(it.sq); this.render(it); } + } + + setVisible(v) { for (const it of this.items.values()) { it.face.setVisible(v); it.shadow.setVisible(v); } } +} + +/** The prisoners in a lid. */ +export class LidPile { + constructor(scene, lid, depth) { + this.scene = scene; + this.lid = lid; // { x, y, r } + this.depth = depth; + this.objs = []; + this.color = 'black'; + this.n = 0; + this.label = scene.add.text(lid.x + lid.r * 0.72, lid.y + lid.r * 0.72, '', { + fontFamily: 'Righteous, Georgia, serif', fontSize: '20px', color: '#f8e8c0', stroke: '#1a0c04', strokeThickness: 5, + }).setOrigin(0.5).setDepth(depth + 3); + } + + spot(i) { + // stones spiral outward from the middle of the lid + const a = i * 2.399963 + hash(i + 5) * 0.6; + const d = Math.min(this.lid.r * 0.68, Math.sqrt(i + 0.5) * this.lid.r * 0.15); + return { x: this.lid.x + Math.cos(a) * d, y: this.lid.y + Math.sin(a) * d }; + } + + target() { return this.spot(Math.min(this.n, 40)); } + + stone(i) { + const p = this.spot(i); + const s = this.scene; + const key = this.color === 'black' ? 'go-black' : `go-white-${i % WHITE_VARIANTS}`; + const sc = (STONE_R * 0.34) / STONE_R / RES; + const sh = s.add.image(p.x + 2, p.y + 3, 'go-shadow').setScale(sc).setDepth(this.depth).setAlpha(0.6); + const im = s.add.image(p.x, p.y, key).setScale(sc).setRotation(hash(i) * 6.28).setDepth(this.depth + 1 + i * 0.001); + return [sh, im]; + } + + /** Show n prisoners of `color` (the opponent's colour). */ + set(n, color) { + if (color !== this.color) { this.objs.forEach((o) => o.destroy()); this.objs = []; } + this.color = color; + const shown = Math.min(n, 41); + while (this.objs.length / 2 > shown) { const [a, b] = this.objs.splice(-2); a.destroy(); b.destroy(); } + while (this.objs.length / 2 < shown) this.objs.push(...this.stone(this.objs.length / 2)); + this.n = n; + this.label.setText(n ? `×${n}` : ''); + } + + add(k, color) { this.set(this.n + k, color); } +} diff --git a/src/games/go/GoTalk.js b/src/games/go/GoTalk.js new file mode 100644 index 0000000..139748f --- /dev/null +++ b/src/games/go/GoTalk.js @@ -0,0 +1,148 @@ +// GoTalk.js: words at Unkai-ji. Two voices: +// hounLine(kind, ctx) Hōun, the old monk who keeps the board in the +// pavilion and the problems in a lacquer box. +// Unhurried, fond of proverbs, kind about +// mistakes and blunt about bad shape. +// opponentLine(kind, tier) whoever sits across the board: +// 'novice' (skill 1–2) · 'regular' (3) · 'master' (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] ?? '')); + +export const PROVERBS = [ + 'Play away from strength.', + 'Don\'t go fishing while your house is on fire.', + 'The enemy\'s key point is your own.', + 'Hane at the head of two stones.', + 'There is death in the hane.', + 'On the second line, six die and eight live.', + 'Strike at the waist of the knight\'s move.', + 'Big eye beats small eye.', + 'Make a fist before you strike.', + 'Don\'t touch the stones you want to attack.', + 'The empty triangle is bad shape.', + 'Corners first, then the sides, then the centre.', + 'Answer the attachment with a hane.', + 'From a two-stone wall, extend two. From three, extend three.', + 'Even a fool connects against a peep.', + 'Lose your first fifty games as quickly as you can.', + 'Learn the proverbs, then forget them.', + 'Beware of going back to patch up.', +]; + +const HOUN = { + welcome: [ + 'The mist is still in the valley. Good. Sit, and we\'ll play until the sun clears the ridge.', + 'Kneel, warm your hands on the tea. The stones are cold at this hour.', + 'The bell has rung for morning practice. The board is ready.', + 'Every game is a little sunrise. Shall we see how this one goes?', + ], + welcomeBack: [ + 'The stones are as you left them. So is the tea, which is a pity.', + 'Back again. I kept the board covered.', + ], + newGame: ['Clear the board. The bowls are full again.', 'A fresh board. Bow, and begin.'], + handicap: ['{n} stones on the star points. Black starts with the wind behind it; White moves first.'], + size9: ['The small board. Every stone touches every other. Fight from the first move.'], + size13: ['Thirteen lines: room for a corner and a wall, and still a quick game.'], + size19: ['The full board. Corners first, then the sides, then the centre. Take your time.'], + youBlack: ['You hold Black. Black moves first. Put your first stone where it counts.'], + themBlack: ['{name} has Black and moves first. Watch where they lean.'], + humanCapture: ['{n} stones into your lid. Good.', 'Taken. Those stones were short of breath.', 'A fine capture. Count them in your lid, they are worth a point each.'], + humanBigCapture: ['{n} stones! That will be felt at the count.', 'A great harvest. {n} stones.'], + aiCapture: ['They took {n}. Look at what is still connected, not what is gone.', null, null], + aiBigCapture: ['{n} stones lost. Sit up straight; the game is long.', 'That hurts. Find the next big point.'], + atariYou: ['Careful: your {n} stone{s} near {move} have one liberty left.', 'Atari on your stones at {move}. Run, or let them go and take something bigger.'], + ko: ['A ko. Neither of you may retake at once: play a threat elsewhere first.', 'Ko! Find a threat they must answer.'], + koIllegal: ['Not yet. That would retake the ko at once. Play a threat somewhere else first.'], + suicide: ['That point has no liberties for you. A stone there would be captured as you put it down.'], + superko: ['That would bring back an earlier position exactly. Not allowed here.'], + humanPass: ['You pass. If they pass too, we count.', null], + aiPass: ['{name} passes. If you pass as well, the game is over and we count.', 'They pass. Is anything left worth a stone? If not, pass.'], + endgame: ['The borders are nearly drawn. Close the open ones, the small moves add up.', 'Endgame now. Sente moves first: the ones they have to answer.', null], + scoring: ['Two passes. I\'ve dimmed the stones I think are dead. Click a group to change my mind, then accept.'], + dispute: ['{name} does not agree those stones are dead. Then we play it out.'], + resume: ['Back to the board, then. The stones will decide.'], + hint: ['{move}. It {reason}.', 'Look at {move}: it {reason}.', 'I would play {move}. It {reason}.'], + hintPass: ['Nothing left worth a stone. Pass, and let us count.'], + warnSelfAtari: ['That leaves your {n} stones with a single liberty. They could be taken next move.'], + warnFillEye: ['That fills one of your own eyes. A group needs two to live.'], + undo: ['Take it back. The stones don\'t mind.', 'Look again, then.', null], + resign: ['You bow out. There is no shame in a clean resignation.'], + aiResign: ['{name} resigns. They bow; bow back.', '{name} has resigned. Well played.'], + count: ['Now we count. Dead stones into the lids, then the territory, region by region.'], + win: ['Well played. I\'ll write this one in the temple record.', 'A fine game. Your stones worked together.', 'You won, and you won calmly. That is the harder thing.'], + loss: ['A loss teaches more than a win. We\'ll look at the board together.', 'Close, at times. Look at where your groups got heavy.', 'They read further today. Tomorrow you will.'], + draw: ['Jigo. A perfect tie. The monks say it is the most polite result.'], + matchWin: ['The match is yours. Ring the bell on your way out.', 'You took the match. The valley heard it.'], + matchLoss: ['They take the match. Come back at dawn.', 'Their match. But you\'re reading deeper than when you came in.'], + matchDraw: ['An even match. Perfectly balanced, like the two bowls.'], + byoyomi: ['Byo-yomi. You have {s} seconds a move.'], + lastPeriod: ['Your last period. Play inside the count or the game is lost.'], + timeLoss: ['Time. The count ran out.'], + puzzleKill: ['Black to kill. Find the move that leaves them one eye.', 'Black to play and kill. Look for the vital point.'], + puzzleLive: ['Black to live. Make two eyes, or make the eye space too wide to spoil.', 'Black to play and live. Where is your eye space widest?'], + puzzleGood: ['Good. Keep going.', 'Yes. And now?', 'Correct. They resist.'], + puzzleWrong: ['Not that one. See how they answer.', 'Hm. Watch what happens now.'], + puzzleSolved: ['Solved. The status is sure now.', 'That\'s it. Nothing more to read.', 'Well read.'], + dailySolved: ['Today\'s problem, solved. Come back tomorrow for the next.'], + puzzleFailed: ['Not this time. I\'ll show you the answer.', 'Let me show you. Look where the first stone goes.'], + puzzleHint: ['The first stone goes here. The rest is up to you.'], + proverb: ['As we say: {p}', 'An old saying: {p}', '{p}'], +}; + +const OPP = { + novice: { + greet: ['Please go easy on me!', 'I\'ve only learned the rules this week.', 'Onegaishimasu! I think that\'s right?'], + capture: ['I got some!', 'Oh, are those mine now?', 'Yay!'], + lost: ['Oh no, my stones!', 'Wait, they had no liberties?', 'I should have counted.'], + pass: ['I don\'t know where else to play…', 'Pass?'], + resign: ['I think I\'m losing. I resign!'], + win: ['I won? I won!', 'Lucky!'], + lose: ['Thank you for the game! I learned a lot.', 'You\'re really good.'], + draw: ['A tie! Is that allowed?'], + ko: ['Ko? Oh, the back-and-forth thing.'], + }, + regular: { + greet: ['Onegaishimasu.', 'A fine morning for a game.', 'Shall we?'], + capture: ['Those were in trouble.', 'Into the lid.', 'Mm.'], + lost: ['Ah. Overextended.', 'I saw that too late.', 'Fair enough.'], + pass: ['I have nothing more.', 'Pass.'], + resign: ['I can\'t make it up. I resign. Thank you.'], + win: ['Thank you for the game.', 'That was close in the middle.'], + lose: ['Well played. Thank you.', 'You read that fight better.'], + draw: ['Jigo. How rare.'], + ko: ['Ko. Let\'s see whose threats are bigger.'], + }, + master: { + greet: ['Onegaishimasu.', 'Show me your shape.', 'Let us begin.'], + capture: ['Necessary.', 'Those could not live.', null], + lost: ['A fair exchange.', 'Interesting.', null], + pass: ['Pass.', 'It is finished.'], + resign: ['I resign. You played well.'], + win: ['Thank you for the game.', 'Review it later. Move forty.'], + lose: ['Well played. You were stronger today.', 'I resign myself to it. Thank you.'], + draw: ['Jigo. Balanced.'], + ko: ['A ko. I have threats.', null], + }, +}; + +export const tierOf = (skill) => (skill <= 2 ? 'novice' : skill === 3 ? 'regular' : 'master'); + +export function hounLine(kind, ctx = {}) { + const list = HOUN[kind]; + if (!list) return null; + const s = pick(list); + if (!s) return null; + const c = { ...ctx }; + if (kind === 'proverb' && !c.p) c.p = pick(PROVERBS); + if (c.n !== undefined && c.s === undefined) c.s = c.n === 1 ? '' : 's'; + return fill(s, c); +} + +export function opponentLine(kind, tier) { + const list = OPP[tier]?.[kind]; + if (!list) return null; + return pick(list); +} diff --git a/src/games/go/GoTsumego.js b/src/games/go/GoTsumego.js new file mode 100644 index 0000000..69c6750 --- /dev/null +++ b/src/games/go/GoTsumego.js @@ -0,0 +1,334 @@ +// GoTsumego.js: a life-and-death solver for Hōun's problems. Pure, no +// Phaser; shared by the puzzle generator (tools/genGoPuzzles.js) and the +// scene (through the worker) to answer the player's moves. +// +// A problem: { size, board (GoLogic: 'black' | 'white' | null per point), +// region [sq] (the only points either side may play), attacker (colour), +// toMove (colour) }. The attacker's surrounding wall reaches outside the +// region, so it can never be captured; the defender's stones all lie +// inside it. +// +// The attacker wins when every defender stone is gone. The defender wins +// when one of its chains is unconditionally alive (Benson), or when both +// sides pass with defender stones still on the board (life or seki), or +// when a position repeats. Kos: `koWinner` ('attacker' | 'defender' | +// null) may retake a ko at once; the other side must wait a move. Solving +// a problem both ways tells whether its answer hangs on a ko. +// +// solve(prob, opts) → { attackerWins, nodes, limit } +// winningMoves(prob, opts) → { moves: [sq | -1], status } for toMove +// reply(prob, opts) → the computer's answer in a puzzle +// settled(prob, human, opts) → the human's side wins even if it passes +// play(prob, sq) → the problem after a move (or null) + +import { BLACK, WHITE, other, nbrs } from './GoLogic.js'; + +const C = { [BLACK]: 1, [WHITE]: 2 }; +const PASS = -1; + +function zob(n) { + let a = 0x2545f491; + const t = new Uint32Array(n * 4); + for (let i = 0; i < t.length; i++) { + a ^= a << 13; a >>>= 0; a ^= a >>> 17; a ^= a << 5; a >>>= 0; + t[i] = a; + } + return t; +} +const ZOB = zob(19 * 19); + +class Ctx { + constructor(prob, { koWinner = null, maxNodes = 400000, maxDepth = null } = {}) { + this.size = prob.size; + this.N = nbrs(prob.size); + this.region = prob.region.slice(); + this.inRegion = new Uint8Array(prob.size * prob.size); + for (const s of this.region) this.inRegion[s] = 1; + this.att = C[prob.attacker]; + this.def = 3 - this.att; + this.koWinner = koWinner === 'attacker' ? this.att : koWinner === 'defender' ? this.def : 0; + this.maxNodes = maxNodes; + this.maxDepth = maxDepth ?? this.region.length * 2 + 8; + this.tt = new Map(); + this.path = new Set(); + this.nodes = 0; + this.aborted = false; + this.limit = false; + const n = prob.size * prob.size; + this.mark = new Int32Array(n); + this.stamp = 1; + } + + key(b, ko, turn, passed) { + let h0 = 0, h1 = 0; + for (const s of this.region) { + const v = b[s]; + if (!v) continue; + const i = (s * 2 + v - 1) * 2; + h0 ^= ZOB[i]; h1 ^= ZOB[i + 1]; + } + return `${h0 >>> 0}.${h1 >>> 0}.${ko}.${turn}.${passed ? 1 : 0}`; + } + + /** Stones and liberty count of the chain at s (libs capped at `cap`). */ + chain(b, s, cap = 99) { + const col = b[s]; + const st = ++this.stamp; + const mark = this.mark, N = this.N; + const stones = [s]; + mark[s] = st; + let libs = 0; + const libMark = -st; + for (let i = 0; i < stones.length; i++) { + const p = stones[i]; + for (const q of N[p]) { + const v = b[q]; + if (v === col) { if (mark[q] !== st) { mark[q] = st; stones.push(q); } } else if (v === 0) { + if (mark[q] !== libMark && mark[q] !== st) { mark[q] = libMark; libs++; } + } + } + if (libs >= cap && cap < 99) return { stones, libs }; + } + return { stones, libs }; + } + + /** Play col at s on b. → { b, captured, ko } or null when illegal. */ + move(b, s, col, ko) { + if (b[s] !== 0) return null; + if (s === ko && col !== this.koWinner) return null; + const nb = b.slice(); + nb[s] = col; + const opp = 3 - col; + let captured = 0, capAt = -1; + for (const q of this.N[s]) { + if (nb[q] !== opp) continue; + const g = this.chain(nb, q); + if (g.libs === 0) { for (const t of g.stones) nb[t] = 0; captured += g.stones.length; capAt = q; } + } + const own = this.chain(nb, s); + if (own.libs === 0) return null; + const nko = captured === 1 && own.stones.length === 1 && own.libs === 1 ? capAt : -1; + return { b: nb, captured, ko: nko }; + } + + defStones(b) { + let n = 0; + for (const s of this.region) if (b[s] === this.def) n++; + return n; + } + + /** Benson: does colour col have an unconditionally alive chain? */ + benson(b, col) { + const size = this.size, n = size * size, N = this.N; + const chainId = new Int32Array(n).fill(-1); + const chains = []; + for (let s = 0; s < n; s++) { + if (b[s] !== col || chainId[s] >= 0) continue; + const id = chains.length; + const stones = [s]; + chainId[s] = id; + for (let i = 0; i < stones.length; i++) for (const q of N[stones[i]]) if (b[q] === col && chainId[q] < 0) { chainId[q] = id; stones.push(q); } + chains.push(stones); + } + if (!chains.length) return false; + const regId = new Int32Array(n).fill(-1); + const regions = []; + for (let s = 0; s < n; s++) { + if (b[s] === col || regId[s] >= 0) continue; + const id = regions.length; + const cells = [s]; + regId[s] = id; + const border = new Set(); + for (let i = 0; i < cells.length; i++) { + for (const q of N[cells[i]]) { + if (b[q] === col) border.add(chainId[q]); + else if (regId[q] < 0) { regId[q] = id; cells.push(q); } + } + } + // vital to chain c: every empty cell of the region is a liberty of c + const vital = new Set(); + for (const c of border) { + let all = true; + for (const p of cells) { + if (b[p] !== 0) continue; + let adj = false; + for (const q of N[p]) if (chainId[q] === c) { adj = true; break; } + if (!adj) { all = false; break; } + } + if (all) vital.add(c); + } + regions.push({ border, vital }); + } + const aliveC = new Set(chains.map((_, i) => i)); + const aliveR = new Set(regions.map((_, i) => i)); + for (;;) { + let changed = false; + for (const c of [...aliveC]) { + let v = 0; + for (const r of aliveR) if (regions[r].vital.has(c)) v++; + if (v < 2) { aliveC.delete(c); changed = true; } + } + for (const r of [...aliveR]) { + for (const c of regions[r].border) if (!aliveC.has(c)) { aliveR.delete(r); changed = true; break; } + } + if (!changed) break; + } + for (const c of aliveC) { + if (chains[c].some((s) => this.inRegion[s])) return true; + } + return false; + } + + /** Candidate moves for col, most promising first. */ + moves(b, col, ko) { + const out = []; + const N = this.N; + for (const s of this.region) { + if (b[s] !== 0) continue; + const r = this.move(b, s, col, ko); + if (!r) continue; + let score = r.captured * 50; + let empt = 0, ownAdj = 0, oppAdj = 0; + for (const q of N[s]) { if (b[q] === 0 && this.inRegion[q]) empt++; else if (b[q] === col) ownAdj++; else if (b[q] === 3 - col) oppAdj++; } + // atari on a neighbour + for (const q of N[s]) { + if (r.b[q] === 3 - col) { const g = this.chain(r.b, q, 2); if (g.libs === 1) score += 20; } + } + const own = this.chain(r.b, s, 3); + if (own.libs === 1 && !r.captured) score -= 15; + score += empt * 6 + oppAdj * 3 + ownAdj; + out.push({ s, r, score }); + } + out.sort((a, b2) => b2.score - a.score); + return out; + } + + /** 1: the attacker wins from here; 0: the defender does. */ + search(b, turn, ko, passed, depth) { + if (this.aborted) return 0; + if (++this.nodes > this.maxNodes) { this.aborted = true; return 0; } + if (this.defStones(b) === 0) return 1; + if (this.benson(b, this.def)) return 0; + const key = this.key(b, ko, turn, passed); + const hit = this.tt.get(key); + if (hit !== undefined) return hit; + if (this.path.has(key)) return 0; + if (depth >= this.maxDepth) { this.limit = true; return 0; } + this.path.add(key); + const att = turn === this.att; + let result = att ? 0 : 1; + const ms = this.moves(b, turn, ko); + for (const m of ms) { + const v = this.search(m.r.b, 3 - turn, m.r.ko, false, depth + 1); + if (att ? v === 1 : v === 0) { result = v; break; } + } + if (att ? result === 0 : result === 1) { + // pass + const v = passed ? (this.defStones(b) === 0 ? 1 : 0) : this.search(b, 3 - turn, -1, true, depth + 1); + if (att ? v === 1 : v === 0) result = v; + } + this.path.delete(key); + if (!this.aborted) this.tt.set(key, result); + return result; + } +} + +function toArr(prob) { + const b = new Int8Array(prob.size * prob.size); + prob.board.forEach((v, i) => { b[i] = v ? C[v] : 0; }); + return b; +} + +export function solve(prob, opts = {}) { + const ctx = new Ctx(prob, opts); + const v = ctx.search(toArr(prob), C[prob.toMove], prob.ko ?? -1, !!prob.passed, 0); + return { attackerWins: v === 1, nodes: ctx.nodes, limit: ctx.limit, aborted: ctx.aborted }; +} + +/** Every first move (−1 = pass) that wins for the side to move. */ +export function winningMoves(prob, opts = {}) { + const ctx = new Ctx(prob, opts); + const b = toArr(prob); + const turn = C[prob.toMove]; + const att = turn === ctx.att; + const ko = prob.ko ?? -1; + const wins = [], all = []; + for (const m of ctx.moves(b, turn, ko)) { + const v = ctx.search(m.r.b, 3 - turn, m.r.ko, false, 1); + all.push(m.s); + if (att ? v === 1 : v === 0) wins.push(m.s); + } + const pv = prob.passed ? (ctx.defStones(b) === 0 ? 1 : 0) : ctx.search(b, 3 - turn, -1, true, 1); + const passWins = att ? pv === 1 : pv === 0; + if (passWins) wins.push(PASS); + return { moves: wins, tried: all, passWins, nodes: ctx.nodes, limit: ctx.limit, aborted: ctx.aborted }; +} + +/** The problem after the side to move plays sq (−1 passes). null if illegal. */ +export function play(prob, sq, { koWinner = null } = {}) { + if (sq === PASS) return { ...prob, toMove: other(prob.toMove), ko: -1, passed: true }; + const ctx = new Ctx(prob, { koWinner }); + if (!ctx.inRegion[sq]) return null; + const r = ctx.move(toArr(prob), sq, C[prob.toMove], prob.ko ?? -1); + if (!r) return null; + const board = Array.from(r.b, (v) => (v === 1 ? BLACK : v === 2 ? WHITE : null)); + return { ...prob, board, toMove: other(prob.toMove), ko: r.ko, passed: false, lastCaptured: r.captured }; +} + +/** Status words for the side to move: is it won for them? */ +export function wins(prob, side, opts = {}) { + const r = solve(prob, opts); + return side === prob.attacker ? r.attackerWins : !r.attackerWins; +} + +/** Has the defender been wiped out, or made unconditional life? */ +export function terminal(prob) { + const ctx = new Ctx(prob); + const b = toArr(prob); + if (ctx.defStones(b) === 0) return 'dead'; + if (ctx.benson(b, ctx.def)) return 'alive'; + return null; +} + +/** + * The puzzle's settled when the human's side wins even after a free pass + * (the computer moving twice in a row): no more reading needed. + */ +export function settled(prob, human, opts = {}) { + const t = terminal(prob); + if (t) return (t === 'dead') === (human === prob.attacker); + // prob has the computer to move; give it an extra move + const comp = prob.toMove; + const ctx = new Ctx(prob, opts); + const b = toArr(prob); + for (const m of ctx.moves(b, C[comp], prob.ko ?? -1)) { + // after the computer's first move, the human "passes": computer again + const v = ctx.search(m.r.b, C[comp], -1, true, 1); + const humanWins = human === prob.attacker ? v === 1 : v === 0; + if (!humanWins) return false; + } + return true; +} + +/** + * The computer's reply in a puzzle (prob.toMove is the computer): + * a winning move if the human went wrong (the refutation), otherwise the + * stubbornest move: the one that leaves the human fewest winning answers. + */ +export function reply(prob, opts = {}) { + const w = winningMoves(prob, opts); + if (w.moves.length) { + const real = w.moves.filter((m) => m !== PASS); + return { sq: real.length ? real[0] : PASS, refutes: true }; + } + let best = null, bestN = Infinity; + for (const s of w.tried) { + const next = play(prob, s, opts); + if (!next) continue; + const answers = winningMoves(next, opts).moves.filter((m) => m !== PASS).length; + if (answers > 0 && answers < bestN) { bestN = answers; best = s; } + } + return { sq: best ?? (w.tried[0] ?? PASS), refutes: false }; +} + +export { PASS }; diff --git a/src/games/go/GoWorker.js b/src/games/go/GoWorker.js new file mode 100644 index 0000000..abaf7ff --- /dev/null +++ b/src/games/go/GoWorker.js @@ -0,0 +1,11 @@ +// GoWorker.js: the module worker Unkai-ji's engine runs in. +// See GoEngine.js for the message kinds. + +import { handle } from './GoEngine.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/go/tutorial.md b/src/games/go/tutorial.md new file mode 100644 index 0000000..8776853 --- /dev/null +++ b/src/games/go/tutorial.md @@ -0,0 +1,95 @@ +# Welcome to Go + +*By Hōun: old monk of Unkai-ji, keeper of the pavilion board and the lacquer box of problems* + +--- + +*Slides the lids off the two bowls, pours the tea, and nods at the empty board* + +The mist is still down in the valley, so we have time. Go has very few rules. You can learn them before the tea cools. Playing well takes a lifetime, which is good: it means you never run out of game. + +## The Goal + +Two players, black stones and white, take turns putting stones on the **points where the lines cross**. Stones never move once they are down. **Whoever surrounds more of the board wins.** At the end you score: + +- **Japanese rules** (territory): the empty points you surround, plus every stone you captured. +- **Chinese rules** (area): the empty points you surround, plus your stones on the board. + +The two almost always give the same winner. White gets **komi**, a few points (6.5 or 7.5) to make up for Black moving first. The half point means there are no ties. + +## Liberties and Capture + +The empty points next to a stone, along the lines, are its **liberties**. Stones of one colour that touch along the lines are a **group** and share their liberties. + +- When you take a group's **last liberty**, it is **captured**. Its stones come off the board and go into your lid as **prisoners**. +- A group with only one liberty left is in **atari**: it can be taken on the next move. +- You may not play where your stone would have no liberties (**suicide**), unless the move captures something and so makes room. + +## Ko + +Sometimes one stone captures one stone, and the other side could capture straight back, forever. That is **ko**. After a ko capture **you may not retake at once**. Play somewhere else first (a "ko threat"), and if they answer it, you may retake. Here we also use **superko**: no move may bring back a whole-board position that has already happened. + +## Life and Death + +A group with **two separate eyes** (two empty points or areas inside it that the opponent cannot fill) **can never be captured**. A group with only one eye, or none, can be surrounded and taken in the end. Most of the art of Go is making your groups live and keeping theirs from it. My problems teach exactly this. + +## The End and the Count + +When neither of you sees a useful move, **pass**. **Two passes in a row end the game.** Then we count: + +1. I dim the stones I think are **dead**: groups that could not avoid capture if play went on. +2. **Click a group** to mark it dead or alive if you disagree. The score updates as you click. +3. **Accept** when you are content. If you have marked your opponent's living stones dead, they will object, and play resumes so the board can decide. **Resume Play** does the same from your side. + +Dead stones are taken off as prisoners, the territory is marked, and the totals are read out. + +## How to Play Here + +| Do this | And this happens | +|---|---| +| **Hover an empty point** | A ghost stone shows where you would play. Stones it would capture get a red ring; "self-atari!" warns you if it would leave you with one liberty. | +| **Hover a stone** | Its group's liberties are marked, and the count is shown. | +| **Click a point** (or arrow keys and Enter) | A stone comes out of your bowl and goes down. Anything captured flies into your lid. | +| **P / Pass** | Pass your turn. Two passes in a row and we count. | +| **Z / Undo** | Takes back your last move (and the reply). | +| **H / Hint** | I point at the move I would play and tell you why, and how the game stands. | +| **T / Study** | I shade who owns what, and the bar above the board shows my count. | +| **N** | Move numbers on the stones. | +| **Esc / Menu** | Settings, saving and opening SGF records, my problems, a new match. | + +The bar above the board shows prisoners, or my running count when Study is on. A red ring around your stones means they are in atari. A red square marks a ko point that cannot be retaken yet. + +## Setting Up + +- **Board:** 9×9 (quick and sharp), 13×13, or the full 19×19. +- **Colour:** Black, White, or **nigiri** (draw lots). +- **Handicap:** 2 to 9 stones for Black on the star points. White then moves first, and komi drops to half a point. A good way to give a stronger opponent a fair game. +- **Komi, rules, match length** (best of 3 or 5; colours swap unless there is a handicap). +- **Clock:** byo-yomi. You get a fixed time for each move (60 or 30 seconds). Go over and you use up one of your periods. Lose them all and you lose on time. The wooden clapper counts down the last ten seconds. + +## Hōun's Problems + +From the setup card or the menu. Each is a corner or side **life-and-death** problem: **Black to kill** or **Black to live**. Only the lit points count. + +- Play your move. I answer with the strongest reply. +- A problem is **solved** once the group's fate is certain, however I answer. +- A wrong move? I show you why. Then **Retry**, or see the **Solution**. +- Your **problem rating** goes up and down like a ladder. Using a hint or the solution doesn't count as solved. +- The **Daily Problem** is the same for everyone each day. Solve it on consecutive days for a streak. + +## After the Game + +At the end of a match I go back over the game: a **graph of the count after every move**, my notes on the moves I'd have changed (click one to see it on the board), and a replay board. **Save as SGF** writes the game record for any Go program. **Open SGF** from the menu reads one back in for review. + +## Hōun's Advice + +- **Corners first, then the sides, then the centre.** Corners are the cheapest places to make a living group. +- **Make your groups strong before you attack.** A weak group of your own is a debt the opponent collects later. +- **Don't fill your own eyes.** I will warn you if you try. +- **When in atari, ask whether the stones are worth saving.** Sometimes letting two stones go buys you a wall. +- **Big moves before small ones.** At the end, play the moves your opponent must answer first. +- Above all: **lose your first fifty games as quickly as you can.** Every one teaches you something. + +*Bows over the board* + +Onegaishimasu. Please, let us play. diff --git a/src/services/soundtrack.js b/src/services/soundtrack.js index d2c98a2..9822745 100644 --- a/src/services/soundtrack.js +++ b/src/services/soundtrack.js @@ -36,6 +36,7 @@ export const GAME_SOUNDTRACK_OVERRIDES = { mahjong: 'chinese', mahjongmatch: 'chinese', chinesecheckers: 'chinese', + go: 'chinese', zuma: 'zuma', mastervega: 'masterofvega', }; diff --git a/tools/genGoPuzzles.js b/tools/genGoPuzzles.js new file mode 100644 index 0000000..e705dd8 --- /dev/null +++ b/tools/genGoPuzzles.js @@ -0,0 +1,248 @@ +#!/usr/bin/env node +// genGoPuzzles.js: builds Hōun's life-and-death problems for Go +// (src/games/go/GoPuzzleData.js). +// +// Each problem starts from a classic eye-space shape in the top-left +// corner or along the top edge (straight three, bent four, bulky five, +// rabbity six, …). The defender's wall is every point touching that space +// (diagonals too, so walls are solid); the attacker's wall wraps that, +// reaching into open board so it can never be captured. Then the shape is +// roughed up at random: wall stones knocked out, attacker stones dropped +// inside, a defender stone added. The solver (GoTsumego.js) keeps a +// problem only when +// • Black, to play, has exactly one move that works (to kill, or to live), +// • passing would not do (the problem is real), +// • the answer is the same whoever is given the kos (no ko problems), +// • the search finished inside its budget. +// Ratings come from how deep the answer goes, how many first moves look +// plausible, and whether the key move is a sacrifice. Duplicates (same +// stones) are dropped. +// +// Usage: node tools/genGoPuzzles.js [--target 200] [--seed 7] + +import { writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, join } from 'node:path'; +import * as L from '../src/games/go/GoLogic.js'; +import * as T from '../src/games/go/GoTsumego.js'; + +const args = process.argv.slice(2); +const arg = (k, d) => { const i = args.indexOf(k); return i >= 0 ? Number(args[i + 1]) : d; }; +const TARGET = arg('--target', 200); +const SEED = arg('--seed', 7); +const SIZE = 9; +const BUDGET = 60000; + +function mulberry32(seed) { + let a = (seed >>> 0) || 1; + 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; + }; +} +const rnd = mulberry32(SEED); +const pick = (a) => a[Math.floor(rnd() * a.length)]; + +// ── shapes: [name, cells (row, col) from the corner, 'corner' | 'side'] ────── +const rect = (h, w, r0 = 0, c0 = 0) => { const o = []; for (let r = 0; r < h; r++) for (let c = 0; c < w; c++) o.push([r0 + r, c0 + c]); return o; }; +const SHAPES = [ + ['a straight three', [[0, 0], [0, 1], [0, 2]], 'corner'], + ['a bent three', [[0, 0], [0, 1], [1, 0]], 'corner'], + ['a square four', rect(2, 2), 'corner'], + ['a straight four', [[0, 0], [0, 1], [0, 2], [0, 3]], 'corner'], + ['a bent four', [[0, 0], [0, 1], [0, 2], [1, 0]], 'corner'], + ['a pyramid four', [[0, 0], [0, 1], [0, 2], [1, 1]], 'corner'], + ['a bulky five', [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], 'corner'], + ['a bulky five', [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0]], 'corner'], + ['a straight five', [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]], 'corner'], + ['an L-shaped five', [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0]], 'corner'], + ['a crossed five', [[0, 1], [1, 0], [1, 1], [1, 2], [2, 1]], 'corner'], + ['a rabbity six', rect(2, 3), 'corner'], + ['a long six', [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1]], 'corner'], + ['a corner seven', [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0]], 'corner'], + ['a two-by-four', rect(2, 4), 'corner'], + ['a carpenter\'s square', [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [2, 0]], 'corner'], + ['a straight three', [[0, 0], [0, 1], [0, 2]], 'side'], + ['a straight four', [[0, 0], [0, 1], [0, 2], [0, 3]], 'side'], + ['a straight five', [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]], 'side'], + ['a bulky five', [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], 'side'], + ['a pyramid four', [[0, 0], [0, 1], [0, 2], [1, 1]], 'side'], + ['a rabbity six', rect(2, 3), 'side'], + ['a straight six', [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5]], 'side'], + ['a two-by-four', rect(2, 4), 'side'], +]; + +const inB = (r, c) => r >= 0 && c >= 0 && r < SIZE && c < SIZE; +const sq = (r, c) => r * SIZE + c; + +function ring(set) { + // every point (8-neighbourhood) touching the set, not in it + const out = new Set(); + for (const p of set) { + const r = Math.floor(p / SIZE), c = p % SIZE; + for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) { + const rr = r + dr, cc = c + dc; + if (!inB(rr, cc)) continue; + const q = sq(rr, cc); + if (!set.has(q)) out.add(q); + } + } + return out; +} + +function build(cells, kind, def, perturb) { + const att = L.other(def); + const c0 = kind === 'side' ? 2 : 0; + const E = new Set(cells.map(([r, c]) => sq(r, c + c0))); + const Dw = ring(E); + const both = new Set([...E, ...Dw]); + const Aw = [...ring(both)]; + const board = Array(SIZE * SIZE).fill(null); + for (const p of Dw) board[p] = def; + for (const p of Aw) board[p] = att; + const region = [...both]; + // rough it up + const dw = [...Dw]; + const eArr = [...E]; + for (let i = 0; i < perturb.cutWall; i++) { const p = pick(dw); board[p] = null; } + for (let i = 0; i < perturb.inside; i++) { const p = pick(eArr); board[p] = att; } + for (let i = 0; i < perturb.helper; i++) { const p = pick(eArr); if (!board[p]) board[p] = def; } + return { size: SIZE, board, region, attacker: att }; +} + +function legalPosition(prob) { + const inR = new Set(prob.region); + for (const g of L.allGroups(prob.board, SIZE)) { + if (!g.libs.length) return false; + // attacker chains that reach outside must keep a liberty out there + if (g.color === prob.attacker && g.stones.some((s) => !inR.has(s)) && !g.libs.some((l) => !inR.has(l))) return false; + // defender stones only inside + if (g.color !== prob.attacker && g.stones.some((s) => !inR.has(s))) return false; + } + const defN = prob.board.filter((v, i) => v && v !== prob.attacker && inR.has(i)).length; + return defN >= 3; +} + +const coord = (s) => String.fromCharCode(97 + (s % SIZE)) + String.fromCharCode(97 + Math.floor(s / SIZE)); + +function selfAtari(prob, s) { + const t = L.tryMove({ ...L.createGame({ size: SIZE }), board: prob.board, turn: prob.toMove, seen: [] }, s, prob.toMove); + return t.ok && t.own.libs.length === 1 && t.captured.length === 0; +} + +function theme(prob, s) { + const r = Math.floor(s / SIZE), c = s % SIZE; + const t = L.tryMove({ ...L.createGame({ size: SIZE }), board: prob.board, turn: prob.toMove, seen: [] }, s, prob.toMove); + if (t.captured?.length) return 'capture'; + if (selfAtari(prob, s)) return 'sacrifice'; + const N = L.nbrs(SIZE)[s]; + const touchOwn = N.some((q) => prob.board[q] === prob.toMove); + if (!touchOwn) return 'placement'; + if (r === 0 || c === 0) return 'edge'; + return 'vital point'; +} + +/** Play out the main line: the human's first winning move, the computer's stubbornest reply. */ +function mainLine(prob, first) { + let p = T.play(prob, first); + const line = [first]; + for (let i = 0; i < 14 && p; i++) { + if (T.settled(p, 'black', { maxNodes: BUDGET })) break; + const rep = T.reply(p, { maxNodes: BUDGET }); + if (rep.sq === T.PASS || rep.refutes) break; + p = T.play(p, rep.sq); + line.push(rep.sq); + if (!p) break; + const w = T.winningMoves(p, { maxNodes: BUDGET }).moves.filter((m) => m !== T.PASS); + if (!w.length) break; + p = T.play(p, w[0]); + line.push(w[0]); + } + return line; +} + +const out = []; +const seenKeys = new Set(); +const t0 = Date.now(); +let tried = 0; +const perShape = new Map(); +const maxPerShape = Math.ceil(TARGET / SHAPES.length) + 6; +while (out.length < TARGET && tried < TARGET * 120) { + tried++; + const [name, cells, kind] = pick(SHAPES); + const goal = rnd() < 0.55 ? 'kill' : 'live'; + const def = goal === 'kill' ? L.WHITE : L.BLACK; + const perturb = { + cutWall: Math.floor(rnd() * 3), + inside: Math.floor(rnd() * (cells.length >= 5 ? 3 : 2)), + helper: rnd() < 0.25 ? 1 : 0, + }; + const shapeKey = `${name}|${kind}|${goal}`; + if ((perShape.get(shapeKey) ?? 0) >= maxPerShape) continue; + const base = build(cells, kind, def, perturb); + const prob = { ...base, toMove: L.BLACK, ko: -1 }; + if (!legalPosition(prob)) continue; + const key = prob.board.map((v) => (v ? v[0] : '.')).join('') + goal; + if (seenKeys.has(key)) continue; + seenKeys.add(key); + const a = T.winningMoves(prob, { maxNodes: BUDGET, koWinner: 'attacker' }); + if (a.aborted || a.limit || a.passWins || a.moves.length !== 1) continue; + const d = T.winningMoves(prob, { maxNodes: BUDGET, koWinner: 'defender' }); + if (d.aborted || d.limit || d.passWins || d.moves.length !== 1 || d.moves[0] !== a.moves[0]) continue; + const first = a.moves[0]; + const line = mainLine(prob, first); + const th = theme(prob, first); + const plausible = a.tried.length; + let rating = 520 + line.length * 75 + plausible * 14 + (th === 'sacrifice' ? 260 : th === 'placement' ? 150 : th === 'capture' ? -80 : 0) + + (kind === 'side' ? 40 : 0) + perturb.inside * 40; + rating = Math.max(450, Math.min(2300, Math.round(rating / 10) * 10)); + const black = [], white = []; + prob.board.forEach((v, s) => { if (v === L.BLACK) black.push(coord(s)); else if (v === L.WHITE) white.push(coord(s)); }); + out.push({ + goal, shape: name, kind, theme: th, rating, + b: black.join(''), w: white.join(''), + region: prob.region.map(coord).join(''), + attacker: prob.attacker, + first: coord(first), + line: line.map(coord).join(''), + }); + perShape.set(shapeKey, (perShape.get(shapeKey) ?? 0) + 1); + if (out.length % 10 === 0) console.log(`${out.length} puzzles (${tried} tried, ${Math.round((Date.now() - t0) / 1000)}s)`); +} + +// spread the ratings evenly over 600–1900 by rank, keeping the order +out.sort((x, y) => x.rating - y.rating || x.line.length - y.line.length); +out.forEach((p, i) => { p.rating = Math.round((600 + (1300 * i) / Math.max(1, out.length - 1)) / 10) * 10; }); +// stable ids by content +const ids = new Set(); +for (const p of out) { + let h = 2166136261; + for (const ch of p.b + '|' + p.w + '|' + p.goal) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619) >>> 0; } + let id = 'T' + h.toString(36).slice(0, 5).toUpperCase(); + while (ids.has(id)) id += 'X'; + ids.add(id); + p.id = id; +} + +const here = dirname(fileURLToPath(import.meta.url)); +const file = join(here, '..', 'src', 'games', 'go', 'GoPuzzleData.js'); +const body = out.map((p) => ` ${JSON.stringify({ id: p.id, rating: p.rating, goal: p.goal, shape: p.shape, kind: p.kind, theme: p.theme, attacker: p.attacker, b: p.b, w: p.w, region: p.region, first: p.first, line: p.line })},`).join('\n'); +writeFileSync(file, `// GoPuzzleData.js: Hōun's life-and-death problems, generated by +// tools/genGoPuzzles.js (do not edit by hand; re-run the generator). +// Points are SGF-style pairs: column letter then row letter, 'aa' top-left. +// Black always plays first. goal: 'kill' (Black attacks) or 'live'. +// region: the points either side may play. first: the one correct move. +// line: a main line (Black, White, Black, …) ending when the result is sure. + +export const PUZZLE_SIZE = ${SIZE}; +export const PUZZLES = [ +${body} +]; +`); +console.log(`wrote ${out.length} puzzles to ${file} in ${Math.round((Date.now() - t0) / 1000)}s (${tried} candidates)`); +const by = {}; +for (const p of out) by[p.theme] = (by[p.theme] ?? 0) + 1; +console.log('themes', by, 'kill', out.filter((p) => p.goal === 'kill').length, 'live', out.filter((p) => p.goal === 'live').length); diff --git a/tools/verifyGo.js b/tools/verifyGo.js new file mode 100644 index 0000000..734d875 --- /dev/null +++ b/tools/verifyGo.js @@ -0,0 +1,499 @@ +#!/usr/bin/env node +// verifyGo.js: headless checks for Go ("Unkai-ji, the Temple Above the +// Clouds"): +// • rules: notation, star and handicap points, captures, suicide, simple +// ko and positional superko, passes into scoring, resign, replay/rewind +// • scoring: territory (Japanese) and area (Chinese) on hand-built boards, +// dead stones, prisoners, komi, jigo +// • the fast board agrees with GoLogic on legality and on the board after +// every move, across random games on all three sizes +// • the engine: legal moves only, never fills its own true eyes, passes +// once the board is settled, finds captures and escapes; the skill +// ladder holds (stronger beats weaker over colour-swapped games) +// • dead-stone estimation on settled boards; review output +// • tsumego: the solver on classic shapes; every shipped puzzle is legal, +// solvable and has a unique first move +// • SGF: write → parse round-trip, handicap/setup stones, comments +// • layout: HUD rectangles on screen and clear of the board and each other +// Usage: node tools/verifyGo.js [--quick] + +import * as L from '../src/games/go/GoLogic.js'; +import * as AI from '../src/games/go/GoAI.js'; +import * as T from '../src/games/go/GoTsumego.js'; +import * as PZ from '../src/games/go/GoPuzzles.js'; +import { toSgf, parseSgf } from '../src/games/go/GoSgf.js'; +import { hounLine, opponentLine } from '../src/games/go/GoTalk.js'; +import { HUD_RECTS, W, H, pointAt, pointXY } from '../src/games/go/GoLayout.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` (${detail})` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +function mulberry32(seed) { + let a = (seed >>> 0) || 1; + 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; + }; +} + +/** Build a board from rows of '.', 'X' (black), 'O' (white). */ +function boardFrom(rows) { + const size = rows.length; + const b = []; + for (const row of rows) for (const ch of row.replace(/\s/g, '')) b.push(ch === 'X' ? L.BLACK : ch === 'O' ? L.WHITE : null); + return { size, board: b }; +} +function gameFrom(rows, { turn = L.BLACK, rules = 'japanese', komi = 6.5, captures = null } = {}) { + const { size, board } = boardFrom(rows); + const gs = L.createGame({ size, rules, komi, setup: { black: board.map((v, i) => (v === L.BLACK ? i : -1)).filter((i) => i >= 0), white: board.map((v, i) => (v === L.WHITE ? i : -1)).filter((i) => i >= 0) }, turn }); + if (captures) gs.captures = { ...captures }; + return gs; +} +const P = (n, size) => L.parseSq(n, size); + +// ── rules ──────────────────────────────────────────────────────────────────── +section('rules'); +{ + for (const size of L.SIZES) { + let rt = true; + for (let sq = 0; sq < size * size; sq++) if (L.parseSq(L.notate(sq, size), size) !== sq) rt = false; + ok(`notation round-trip ${size}×${size}`, rt); + } + ok('A9 is the top-left of 9×9, J1 bottom-right', L.notate(0, 9) === 'A9' && L.notate(80, 9) === 'J1'); + ok('no I column', !L.COLS.includes('I') && L.notate(8, 19) === 'J19'); + ok('9×9 has five star points', L.starPoints(9).length === 5); + ok('19×19 has nine star points incl. tengen', L.starPoints(19).length === 9 && L.starPoints(19).includes(P('K10', 19))); + for (const size of L.SIZES) { + for (let n = 2; n <= 9; n++) { + const pts = L.handicapPoints(size, n); + ok(`handicap ${n} on ${size}: ${n} distinct points`, pts.length === n && new Set(pts).size === n); + } + } + ok('handicap 2 on 19 is D4 + Q16', ['Q16', 'D4'].every((x) => L.handicapPoints(19, 2).includes(P(x, 19)))); + const h = L.createGame({ size: 19, handicap: 4 }); + ok('handicap game: white to move, komi 0.5', h.turn === L.WHITE && h.komi === 0.5 && h.board.filter(Boolean).length === 4); + + // a capture in the middle + let g = gameFrom([ + '.........', + '.........', + '....X....', + '...XO....', + '....X....', + '.........', + '.........', + '.........', + '.........', + ]); + const t = L.tryMove(g, P('F6', 9)); + ok('capture: one white stone taken', t.ok && t.captured.length === 1 && t.captured[0] === P('E6', 9)); + g = L.play(g, P('F6', 9)); + ok('capture: prisoners counted, point empty', g.captures.black === 1 && g.board[P('E6', 9)] === null); + ok('capture of a single stone sets no ko here', g.ko === -1); + + // suicide + const s = gameFrom([ + '.X.......', + 'X........', + '.........', '.........', '.........', '.........', '.........', '.........', '.........', + ], { turn: L.WHITE }); + ok('suicide is illegal', L.tryMove(s, P('A9', 9)).reason === 'suicide'); + ok('the suicide point is not a legal move', !L.legalMoves(s).includes(P('A9', 9))); + + // ko + let k = gameFrom([ + '.........', + '...XO....', + '..X.XO...', + '...XO....', + '.........', '.........', '.........', '.........', '.........', + ], { turn: L.WHITE }); + const before = k.board.slice(); + k = L.play(k, P('D7', 9)); // white takes at D7, capturing E7 + ok('ko: white captures one stone', k && k.captures.white === 1 && k.board[P('E7', 9)] === null); + ok('ko: the ko point is marked', k.ko === P('E7', 9)); + ok('ko: black may not retake at once', L.tryMove(k, P('E7', 9)).reason === 'ko'); + k = L.play(k, P('A1', 9)); // a ko threat + k = L.play(k, P('A2', 9)); // answered + ok('ko: after an exchange black may retake', L.tryMove(k, P('E7', 9)).ok); + k = L.play(k, P('E7', 9)); + ok('ko: retaking captures the white stone', k.board[P('D7', 9)] === null); + ok('position keys recorded for superko', k.seen.length === k.history.length + 1); + ok('setup board restored by replay', L.boardAfter(k, 0).join() === before.join()); + ok('rewind gives the same board', L.rewind(k, k.history.length).board.join() === k.board.join()); + + // positional superko: a position that repeats without being a simple ko + { + const base = gameFrom([ + '.........', '.........', '.........', '.........', '.........', '.........', '.........', '.........', '.........', + ]); + // play a stone, pass dance can't repeat a position; check seen-lookup directly + let q = L.play(base, P('E5', 9)); + const forged = { ...q, seen: q.seen.concat([L.hashKey(L.zobristOf([...q.board.slice(0, P('A1', 9)), L.WHITE, ...q.board.slice(P('A1', 9) + 1)]))]) }; + ok('superko: a repeated whole-board position is refused', L.tryMove(forged, P('A1', 9)).reason === 'superko'); + } + + // passes and the end + let p = L.createGame({ size: 9 }); + p = L.pass(p); + ok('one pass: still playing, white to move', p.phase === 'playing' && p.turn === L.WHITE && p.passes === 1); + p = L.play(p, P('E5', 9)); + ok('a move resets the pass count', p.passes === 0); + p = L.pass(L.pass(p)); + ok('two passes in a row: scoring', p.phase === 'scoring'); + ok('no legal moves while scoring', L.legalMoves(p).length === 0); + const r = L.resumePlay(p); + ok('resume play returns to playing', r.phase === 'playing' && r.passes === 0); + const rg = L.resign(L.createGame({ size: 9 }), L.BLACK); + ok('resign: the other side wins', rg.phase === 'over' && rg.winner === L.WHITE && L.resultString(rg) === 'W+R'); +} + +// ── scoring ────────────────────────────────────────────────────────────────── +section('scoring'); +{ + // a split board: black owns columns A–D, white F–J, the E column is the wall + const rows = []; + for (let i = 0; i < 9; i++) rows.push('...XO....'); + const gj = gameFrom(rows, { komi: 6.5 }); + const sj = L.scoreGame(gj, []); + ok('territory: black 27 points', sj.territory.black === 27, `${sj.territory.black}`); + ok('territory: white 36 points', sj.territory.white === 36, `${sj.territory.white}`); + ok('Japanese: B 27 · W 42.5', sj.black === 27 && sj.white === 42.5, `${sj.black} ${sj.white}`); + const gc = gameFrom(rows, { rules: 'chinese', komi: 7.5 }); + const sc = L.scoreGame(gc, []); + ok('Chinese: B 36 · W 52.5', sc.black === 36 && sc.white === 52.5, `${sc.black} ${sc.white}`); + ok('winner white, margin 15.5 (Japanese)', sj.winner === L.WHITE && sj.margin === 15.5); + // a dead white stone inside black's area + const rows2 = rows.slice(); + rows2[4] = '.O.XO....'; + const gd = gameFrom(rows2, { komi: 6.5 }); + const alive = L.scoreGame(gd, []); + ok('an unremoved invader spoils the territory', alive.territory.black < 27); + const dead = [P('B5', 9)]; + const sd = L.scoreGame(gd, dead); + ok('dead stone removed: black territory back to 27', sd.territory.black === 27); + ok('dead stone counts as a prisoner (Japanese)', sd.prisoners.black === 1 && sd.black === 28); + const gdc = gameFrom(rows2, { rules: 'chinese', komi: 7.5 }); + ok('Chinese: dead stone just becomes black area', L.scoreGame(gdc, dead).black === 36); + // toggling dead marks the whole chain + const rows3 = rows.slice(); + rows3[4] = '.OO.XO....'.slice(0, 9); + const gt = gameFrom(['.OO.X....', ...rows.slice(1)]); + const td = L.toggleDead(gt, [], P('B9', 9)); + ok('toggleDead marks the whole chain', td.length === 2 && td.includes(P('C9', 9))); + ok('toggleDead again clears it', L.toggleDead(gt, td, P('C9', 9)).length === 0); + // jigo + const gz = gameFrom(Array(9).fill('...X.O...'), { komi: 0 }); + const fz = L.finish(gz, []); + ok('equal score with no komi: jigo', fz.winner === 'draw' && L.resultString(fz) === '0'); + const fw = L.finish(gj, []); + ok('result string W+15.5', L.resultString(fw) === 'W+15.5'); +} + +// ── the fast board vs the rules ────────────────────────────────────────────── +section('engine board agrees with the rules'); +{ + const { fromPos, geo } = AI._internals; + const rnd = mulberry32(11); + let positions = 0, legalBad = 0, boardBad = 0, koBad = 0; + const games = QUICK ? 6 : 24; + for (const size of L.SIZES) { + const gg = geo(size); + for (let gi = 0; gi < games; gi++) { + let gs = L.createGame({ size, handicap: gi % 3 === 0 ? 3 : 0 }); + const maxMoves = size * size * (size === 19 ? 1 : 2); + while (gs.phase === 'playing' && gs.history.length < maxMoves) { + const b = fromPos(AI.posOf(gs)); + positions++; + // legality: the fast board ignores only superko + for (let sq = 0; sq < size * size; sq++) { + const t = L.tryMove(gs, sq); + const fast = b.legal(gg.toIdx[sq], b.turn); + const ref = t.ok || t.reason === 'superko'; + if (fast !== ref) { legalBad++; break; } + } + const legal = L.legalMoves(gs); + // prefer non-eye-filling moves so games last + const good = legal.filter((sq) => !L.eyeLike(gs.board, size, sq, gs.turn)); + if (!good.length || rnd() < 0.02) { gs = L.pass(gs); continue; } + const sq = good[Math.floor(rnd() * good.length)]; + const next = L.play(gs, sq); + b.play(gg.toIdx[sq]); + const fb = Array(size * size).fill(null); + for (const p of gg.pts) { const c = b.color[p]; if (c === 1) fb[gg.toSq[p]] = L.BLACK; else if (c === 2) fb[gg.toSq[p]] = L.WHITE; } + if (fb.join() !== next.board.join()) boardBad++; + const fk = b.ko ? gg.toSq[b.ko] : -1; + if (fk !== next.ko) koBad++; + gs = next; + } + } + } + ok(`legality matches on ${positions} positions`, legalBad === 0, `${legalBad} mismatches`); + ok('boards match after every move', boardBad === 0, `${boardBad}`); + ok('ko point matches', koBad === 0, `${koBad}`); +} + + +// ── the engine ─────────────────────────────────────────────────────────────── +section('engine: legal, eyes, passing, tactics'); +{ + // legal moves only, on random positions of every size + const rnd = mulberry32(99); + let bad = 0, tried = 0; + for (const size of L.SIZES) { + for (let g = 0; g < (QUICK ? 2 : 4); g++) { + let gs = L.createGame({ size }); + const n = Math.floor(rnd() * size * size * 0.5); + for (let i = 0; i < n; i++) { + const legal = L.legalMoves(gs).filter((sq) => !L.eyeLike(gs.board, size, sq, gs.turn)); + if (!legal.length) break; + gs = L.play(gs, legal[Math.floor(rnd() * legal.length)]); + } + const r = AI.chooseMove(AI.posOf(gs), 1 + (g % 3), { seed: 7 + g, scale: 0.08 }); + tried++; + if (r.sq >= 0 && !L.isLegal(gs, r.sq)) bad++; + } + } + ok(`the engine plays legal moves (${tried} positions)`, bad === 0, `${bad} illegal`); + + // a finished board: two eyes for every group, nothing left to play + const fin = [ + 'XXXXOOOOO', + 'X.XXOO.OO', + 'XXXXOOOOO', + 'XXXXOOOOO', + 'XX.XOOO.O', + 'XXXXOOOOO', + 'XXXXOOOOO', + 'X.XXOO.OO', + 'XXXXOOOOO', + ]; + const eyesB = [P('B8', 9), P('C5', 9), P('B2', 9)]; + { + const gs = gameFrom(fin, { turn: L.BLACK, komi: 0.5 }); + gs.history.push({ color: L.WHITE, sq: -1, pass: true, captured: [], n: 'pass' }); + gs.passes = 1; + const r = AI.chooseMove(AI.posOf(gs), 3, { seed: 3, scale: 0.4 }); + ok('never fills its own true eye on a finished board', !eyesB.includes(r.sq), `played ${L.notate(r.sq, 9)}`); + ok('passes (or resigns) when nothing is left', r.sq === -1 || r.resign); + } + { + const gs = gameFrom(fin, { turn: L.WHITE, komi: 0.5 }); + gs.history.push({ color: L.BLACK, sq: -1, pass: true, captured: [], n: 'pass' }); + gs.passes = 1; + const r = AI.chooseMove(AI.posOf(gs), 4, { seed: 4, scale: 0.4 }); + ok('passes back when settled and ahead', r.sq === -1 && !r.resign, `played ${r.sq >= 0 ? L.notate(r.sq, 9) : 'resign'}`); + } + { + const gs = gameFrom([ + '.........', + '.........', + '...OOO...', + '..OXXXO..', + '..OXXX...', + '...OOO...', + '.........', + '.........', + '.........', + ], { turn: L.WHITE }); + const r = AI.chooseMove(AI.posOf(gs), 4, { seed: 5, scale: 0.3 }); + ok('captures six stones in atari', r.sq === P('G5', 9), `played ${L.notate(r.sq, 9)}`); + } + { + const gs = gameFrom([ + '.........', + '.........', + '.........', + '....OO...', + '...OXX...', + '....OO...', + '.........', + '.........', + '.........', + ], { turn: L.BLACK }); + const r = AI.analyse(AI.posOf(gs), { playouts: 3000, ms: 800, seed: 6 }); + ok('runs two stones out of atari', r.best === P('G5', 9), `best ${L.notate(r.best, 9)}`); + } +} + +section('engine: dead stones and review'); +{ + const gs = gameFrom([ + '....XO...', + '.O..XO...', + '....XO...', + '....XO...', + '....XO.X.', + '....XO...', + '....XO...', + '....XO...', + '....XO...', + ], { komi: 6.5 }); + const r = AI.estimateDead(AI.posOf(gs), { playouts: 3000, ms: 1500, seed: 11 }); + ok('a lone invader in black\'s area is dead', r.dead.includes(P('B8', 9)), `dead ${r.dead.map((s) => L.notate(s, 9)).join(' ')}`); + ok('a lone invader in white\'s area is dead', r.dead.includes(P('H5', 9))); + ok('the walls are alive', !r.dead.some((s) => [P('E5', 9), P('F5', 9)].includes(s))); + const sc = L.scoreGame(gs, r.dead); + ok('the count after removing them is right (B 36+1 · W 27+1+6.5)', sc.black === 37 && sc.white === 34.5, `${sc.black}–${sc.white}`); + // review output + let g2 = L.createGame({ size: 9 }); + for (const n of ['E5', 'C3', 'G7']) g2 = L.play(g2, P(n, 9)); + const list = [0, 1, 2, 3].map((n) => { + const pos = L.positionAfter(g2, n); + return { size: 9, board: pos.board, turn: n % 2 ? L.WHITE : L.BLACK, komi: 6.5, rules: 'japanese', ko: -1, last: null, last2: null, passes: 0, captures: pos.captures, forbidden: [], moveNo: n }; + }); + const rev = AI.reviewPositions(list, { playouts: 300, ms: 150, seed: 2 }); + ok('review: one answer per position', rev.length === 4 && rev.every((x) => x && Number.isFinite(x.lead) && x.winrate >= 0 && x.winrate <= 1)); + ok('review: best moves are empty points', rev.every((x, i) => x.best < 0 || !list[i].board[x.best])); +} + +if (!QUICK) { + section('engine: skill ladder and time budgets'); + const playOut = (skB, skW, seed, scale) => { + let gs = L.createGame({ size: 9, komi: 6.5 }); + for (let i = 0; i < 160 && gs.phase === 'playing'; i++) { + const sk = gs.turn === L.BLACK ? skB : skW; + const r = AI.chooseMove(AI.posOf(gs), sk, { seed: seed + i, scale }); + if (r.resign) return L.other(gs.turn); + gs = r.sq < 0 ? L.pass(gs) : (L.play(gs, r.sq) ?? L.pass(gs)); + } + const d = AI.estimateDead(AI.posOf(gs), { playouts: 3000, ms: 1200, seed }); + return L.scoreGame(gs, d.dead).winner; + }; + let strong = 0; + const games = 2; + for (let g = 0; g < games; g++) { + const strongBlack = g % 2 === 0; + const w = playOut(strongBlack ? 5 : 1, strongBlack ? 1 : 5, 100 + g * 1000, 0.15); + if (w === (strongBlack ? L.BLACK : L.WHITE)) strong++; + } + ok(`skill 5 beats skill 1 (${strong}/${games}, colours swapped)`, strong === games); + for (const size of [9, 19]) { + let gs = L.createGame({ size }); + for (const n of size === 9 ? ['E5', 'C3'] : ['Q16', 'D4', 'Q4']) gs = L.play(gs, P(n, size)); + for (const sk of [1, 3, 5]) { + const t0 = Date.now(); + AI.chooseMove(AI.posOf(gs), sk, { seed: 1 }); + const ms = Date.now() - t0; + const budget = AI.SKILL[sk].ms * ({ 9: 1, 13: 1.25, 19: 1.5 }[size]); + ok(`skill ${sk} on ${size}×${size} within its time budget (${ms} ms of ${Math.round(budget)})`, ms <= budget * 1.25 + 150); + } + } +} + +// ── tsumego ────────────────────────────────────────────────────────────────── +section('tsumego: shipped problems'); +{ + const ids = new Set(PZ.PUZZLES.map((p) => p.id)); + ok(`${PZ.PUZZLES.length} problems, ids unique`, ids.size === PZ.PUZZLES.length && PZ.PUZZLES.length >= 150); + ok('kill and live problems both present', PZ.PUZZLES.some((p) => p.goal === 'kill') && PZ.PUZZLES.some((p) => p.goal === 'live')); + ok('ratings sorted within 600–1900', PZ.PUZZLES.every((p, i) => p.rating >= 600 && p.rating <= 1900 && (i === 0 || p.rating >= PZ.PUZZLES[i - 1].rating))); + const sample = QUICK ? PZ.PUZZLES.filter((_, i) => i % 7 === 0) : PZ.PUZZLES; + let badSetup = 0, notUnique = 0, badLine = 0, badSym = 0, aborted = 0; + for (const p of sample) { + const raw = PZ.puzzleSetup(p, { sym: false }); + const st = PZ.puzzleSetup(p); + // stones don't overlap, the first move is an empty point in the region + const nB = p.b.length / 2, nW = p.w.length / 2; + const cnt = L.counts(st.board); + if (cnt.black !== nB || cnt.white !== nW || st.board[st.first] || !st.region.includes(st.first)) badSetup++; + const prob = PZ.toProb(st, st.board, L.BLACK); + const w = T.winningMoves(prob, { maxNodes: 400000 }); + if (w.aborted) aborted++; + const real = w.moves.filter((m) => m !== T.PASS); + if (real.length !== 1 || real[0] !== st.first || w.passWins) notUnique++; + // the symmetry is a true symmetry: the unmapped problem has the unmapped answer + const w0 = T.winningMoves(PZ.toProb(raw, raw.board, L.BLACK), { maxNodes: 400000 }).moves.filter((m) => m !== T.PASS); + if (w0.length !== 1 || w0[0] !== raw.first) badSym++; + // the main line is playable and Black still wins at its end + let pr = prob, okLine = true; + for (const sq of st.line) { pr = T.play(pr, sq); if (!pr) { okLine = false; break; } } + if (okLine && !T.terminal(pr) && !T.wins(pr, L.BLACK, { maxNodes: 400000 })) okLine = false; + if (!okLine) badLine++; + } + ok(`setups sound (${sample.length} checked)`, badSetup === 0, `${badSetup}`); + ok('each has exactly one winning first move, and passing loses', notUnique === 0, `${notUnique}`); + ok('the board symmetry keeps the answer', badSym === 0, `${badSym}`); + ok('every main line is legal and ends won for Black', badLine === 0, `${badLine}`); + ok('the solver finished every search', aborted === 0, `${aborted}`); + // ladder and daily picks + const stt = { rating: 800, solved: {}, failed: {}, streak: 0, best: 0, played: 0, daily: {} }; + const pick = PZ.nextLadderPuzzle(stt, mulberry32(1)); + ok('the ladder picks near your rating', Math.abs(pick.rating - 800) < 400); + const d1 = PZ.dailyPuzzle(new Date(2026, 11, 1)), d2 = PZ.dailyPuzzle(new Date(2026, 11, 2)); + ok('the daily problem changes by the day', d1.puzzle.id !== d2.puzzle.id && d2.number === d1.number + 1); + const before = stt.rating; + PZ.ratePuzzle(stt, pick, 'solved'); + ok('solving raises the rating', stt.rating > before && stt.solved[pick.id]); + stt.daily[PZ.dateKey(new Date(2026, 11, 1))] = 'solved'; + stt.daily[PZ.dateKey(new Date(2026, 11, 2))] = 'solved'; + ok('the daily streak counts consecutive days', PZ.dailyStreak(stt, new Date(2026, 11, 2)) === 2 && PZ.dailyStreak(stt, new Date(2026, 11, 3)) === 2 && PZ.dailyStreak(stt, new Date(2026, 11, 4)) === 0); +} + +// ── SGF ────────────────────────────────────────────────────────────────────── +section('SGF'); +{ + const rnd = mulberry32(5); + let gs = L.createGame({ size: 13, handicap: 3, rules: 'chinese' }); + for (let i = 0; i < 60; i++) { + const legal = L.legalMoves(gs).filter((sq) => !L.eyeLike(gs.board, 13, sq, gs.turn)); + if (!legal.length || rnd() < 0.03) { gs = L.pass(gs); if (gs.phase !== 'playing') break; continue; } + gs = L.play(gs, legal[Math.floor(rnd() * legal.length)]); + } + if (gs.phase === 'playing') gs = L.pass(L.pass(gs)); + gs = L.finish(gs, []); + const text = toSgf(gs, { black: 'Hōun [the monk]', white: 'Jun' }); + const { gs: back, info } = parseSgf(text); + ok('round trip: size, komi, rules, handicap', back.size === 13 && back.komi === gs.komi && back.rules === 'chinese' && back.handicap === 3); + ok('round trip: setup stones', back.setup.black.join() === gs.setup.black.join()); + ok('round trip: every move', back.history.length === gs.history.length && back.history.every((h, i) => h.sq === gs.history[i].sq && h.color === gs.history[i].color)); + ok('round trip: final board', back.board.join() === gs.board.join()); + ok('round trip: names with brackets escaped', info.black === 'Hōun [the monk]' && info.white === 'Jun'); + ok('round trip: result', info.result === L.resultString(gs), `${info.result} vs ${L.resultString(gs)}`); + const hand = parseSgf('(;GM[1]FF[4]SZ[9]KM[6.5]PB[A]PW[B]RE[W+R];B[ee]C[a \\] bracket];W[cc](;B[gg];W[gc])(;B[cg]))'); + ok('main line follows the first variation', hand.gs.history.map((h) => h.n).join(' ') === 'E5 C7 G3 G7', hand.gs.history.map((h) => h.n).join(' ')); + ok('comments with escaped brackets', hand.info.comments[0] === 'a ] bracket'); + ok('a resignation result is kept', hand.gs.winner === L.WHITE && hand.gs.endReason === 'resign'); + let threw = false; + try { parseSgf('(;GM[1]SZ[7];B[aa])'); } catch (_) { threw = true; } + ok('odd board sizes are refused', threw); + const passes = parseSgf('(;SZ[9];B[];W[tt];B[ee])'); + ok('B[] and tt are passes, and play can go on after them', passes.gs.history[0].pass && passes.gs.history[1].pass && passes.gs.history[2].n === 'E5' && passes.gs.phase === 'playing'); +} + +// ── words and layout ───────────────────────────────────────────────────────── +section('talk and layout'); +{ + const kinds = ['welcome', 'handicap', 'humanCapture', 'atariYou', 'ko', 'aiPass', 'scoring', 'hint', 'warnSelfAtari', 'dispute', 'puzzleKill', 'proverb', 'byoyomi']; + let leftover = 0; + for (const k of kinds) for (let i = 0; i < 20; i++) { + const l = hounLine(k, { n: 3, move: 'D4', name: 'Jun', reason: 'claims a corner', s: 30 }); + if (l && /[{}]/.test(l)) leftover++; + } + ok('Hōun\'s lines fill every blank', leftover === 0, `${leftover}`); + ok('every tier has a greeting', ['novice', 'regular', 'master'].every((t) => opponentLine('greet', t))); + const R = HUD_RECTS(); + const names = Object.keys(R); + ok('every HUD rectangle on screen', names.every((n) => R[n].x >= 0 && R[n].y >= 0 && R[n].x + R[n].w <= W && R[n].y + R[n].h <= H), names.filter((n) => !(R[n].x >= 0 && R[n].y >= 0 && R[n].x + R[n].w <= W && R[n].y + R[n].h <= H)).join(' ')); + const hit = []; + for (let i = 0; i < names.length; i++) for (let j = i + 1; j < names.length; j++) { + const a = R[names[i]], b = R[names[j]]; + if (a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h) hit.push(`${names[i]}/${names[j]}`); + } + ok('no two HUD rectangles overlap', hit.length === 0, hit.join(' ')); + let round = true; + for (const size of L.SIZES) for (let sq = 0; sq < size * size; sq++) { const p = pointXY(sq, size); if (pointAt(p.x, p.y, size) !== sq) round = false; } + ok('point ↔ screen round trip on every size', round); +} + +// @@END-OF-SECTIONS@@ + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);