Skip to content

SGF files ​

SGF (Smart Game Format) is the standard file format for Go games. Goban reads and writes it, including variations, marks, labels, and comments.

Open a file ​

openSgf takes the file's text, or its raw bytes as a Uint8Array:

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

const text = await (await fetch('/games/example.sgf')).text();
const result = openSgf(text);

if (result.ok) board.show(result.game);
else console.log(result.error.code, result.error.message);

Files open in review mode at the start of the game. To continue a game instead, open it in play mode, which goes to the latest move of the main line:

js
openSgf(text, { mode: 'play' });

Other encodings ​

Pass bytes rather than text when you don't know a file's encoding. Goban reads the encoding the file declares, so older records in encodings such as GBK open correctly:

js
const bytes = new Uint8Array(await (await fetch(url)).arrayBuffer());
const result = openSgf(bytes);

When a file can't be opened ​

CodeMeaning
invalid-sgfThe text isn't an SGF record. error.at is the character position where it stopped making sense.
unplayable-sgfThe record is readable, but holds a move the rules don't allow. error.move counts nodes from the start of the file.

Save a game ​

saveSgf returns the game as SGF text:

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

const text = saveSgf(board.state);

A UTF-8 file that you open and don't change comes back byte for byte. Anything else, such as a changed game or a file in another encoding, is written out again and declares UTF-8.

Review a game ​

In review mode you can walk through a record and annotate it:

ToUse
Step through movesnextMove, previousMove. nextMove follows the first continuation.
Jump to a movegoToMove(game, id), with an ID from game.moves
Start a variationplay at an earlier move
Mark a pointmarkPoint(game, point, shape): 'circle', 'triangle', 'square', 'cross', or 'dot'
Label a pointlabelPoint(game, point, text)
Remove a mark or labelclearMark(game, point)
Comment on a movesetComment(game, text)

The board's review sidebar does all of this with buttons, including Open and Save SGF. Everything ends up in the saved file.

The move tree ​

game.moves lists every move in the record, parents before children, with variations in order. Each entry has an id, a parentId, the move itself, and its moveNumber. The first entry is the start of the game, with move: null.

game.current is the move being viewed, with its children, marks, and comment. Move IDs are never reused within a game's history, so an ID names the same move in every value that contains it.

Released under the MIT License.