Rebuild Go as Unkai-ji: full rules, MCTS AI, puzzles, SGF, review

- 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
This commit is contained in:
Brian Fertig 2026-12-02 08:18:04 -07:00
parent 5ef0a7c848
commit d7a873054c
23 changed files with 7277 additions and 916 deletions

View File

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

View File

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

File diff suppressed because it is too large Load Diff

760
src/games/go/GoArt.js Normal file
View File

@ -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-<n> 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-<season>, 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;
}

183
src/games/go/GoDialogs.js Normal file
View File

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

325
src/games/go/GoEndScreen.js Normal file
View File

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

95
src/games/go/GoEngine.js Normal file
View File

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

File diff suppressed because it is too large Load Diff

301
src/games/go/GoHud.js Normal file
View File

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

120
src/games/go/GoLayout.js Normal file
View File

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

View File

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

View File

@ -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"},
];

149
src/games/go/GoPuzzles.js Normal file
View File

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

224
src/games/go/GoSgf.js Normal file
View File

@ -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<string | null> (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); }
});
}

258
src/games/go/GoSound.js Normal file
View File

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

237
src/games/go/GoStones.js Normal file
View File

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

148
src/games/go/GoTalk.js Normal file
View File

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

334
src/games/go/GoTsumego.js Normal file
View File

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

11
src/games/go/GoWorker.js Normal file
View File

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

95
src/games/go/tutorial.md Normal file
View File

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

View File

@ -36,6 +36,7 @@ export const GAME_SOUNDTRACK_OVERRIDES = {
mahjong: 'chinese',
mahjongmatch: 'chinese',
chinesecheckers: 'chinese',
go: 'chinese',
zuma: 'zuma',
mastervega: 'masterofvega',
};

248
tools/genGoPuzzles.js Normal file
View File

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

499
tools/verifyGo.js Normal file
View File

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