Skip to content

Without a board ​

The game core doesn't need a browser. It imports nothing from the board or the DOM, so the same rules run in Node, in workers, and on servers.

In Node ​

js
import { newGame, play, saveSgf } from '@kiranpg/goban';

let game = newGame({ size: 9 });

for (const point of [{ x: 2, y: 2 }, { x: 6, y: 6 }, { x: 2, y: 6 }]) {
  const result = play(game, point);
  if (!result.ok) throw new Error(result.error.message);
  game = result.game;
}

console.log(saveSgf(game));

The package entry point also exports createBoard, but importing it does nothing until you call it, so it's safe to load in Node.

For agents ​

Game values and actions are plain data, which makes them a good fit for programs that play:

  • Try before you commit. A refused move changes nothing, so an agent can test candidate points freely and keep only the result it wants.
  • Speak in actions. An Action such as { type: 'play', point: { x: 3, y: 3 } } is easy to produce, log, and send. apply runs it.
  • Branch on codes. Refusals have stable codes (occupied, ko, suicide and so on), so an agent can react to why a move failed rather than parse text.

This plays a random legal move, or passes if there isn't one:

js
import { pass, play } from '@kiranpg/goban';

function randomMove(game) {
  const points = Array.from({ length: game.size ** 2 }, (_, i) => ({
    x: i % game.size,
    y: Math.floor(i / game.size),
  })).sort(() => Math.random() - 0.5);

  for (const point of points) {
    const result = play(game, point);
    if (result.ok) return result.game;
  }
  return pass(game).game;
}

On a server ​

A server can hold the authoritative game and check every move with the same rules the board uses:

js
import { apply, openSgf, saveSgf } from '@kiranpg/goban';

function handleMove(storedSgf, action) {
  const opened = openSgf(storedSgf, { mode: 'play' });
  if (!opened.ok) return opened;

  const result = apply(opened.game, action);
  if (result.ok) save(saveSgf(result.game));
  return result;
}

Store games as SGF, not JSON. Game functions only accept values they made themselves, so an object rebuilt from JSON isn't a game. See Games as values.

Pair this with a controlled board on the page: the board sends actions, the server checks them, and the page shows what comes back.

Released under the MIT License.