sgf2go
An SGF File Format FF[4] compliant SGF file parser and generator.
Installation
npm install sgf2go
Introduction
I used to use a regular expression to extract what I needed from an sgf
file, specifically this one:
/;[BW]\[\w{2}]|A[BWE](\[(\w|:)+]|\s)+|PL\[[BW]]/gi
until I found myself naïve when dealing with an sgf
file with
variations. most of, if not all, the time, I don't care about the variations. However, my regular expression could not
differentiate the nodes belong to the main stream from the nodes belong to a variation. This library serves the purpose
of solving this problem.
Essentially, an sgf
file contains lists of lists of nodes. A list is enclosed in a pair of curly brackets, while a
node starts with a semi-colon ;
.
With sgf2go
, an sgf
file with no variations: will be converted to the following json
format:
sgf
:
(;FF[4]GM[1]SZ[19];B[aa];W[bb];B[cc];W[dd];B[ad];W[bd])
json
:
One with variation will yield the following result:
sgf
:
(;FF[4]GM[1]SZ[19];B[aa];W[bb](;B[cc];W[dd];B[ad];W[bd])(;B[hh];W[hg]))
json
:
Usage
With Nodejs
const sgf2go = ;
With browser
sgf
file into json
:
Parse an const sgf = `(;FF[4]GM[1]SZ[19];B[aa];W[bb](;B[cc];W[dd];B[ad];W[bd])(;B[hh];W[hg]))`;const parsed = sgf2go;// in browser, const parsed = sgf2json(sgf);console;
The output will be:
sgf
file into json
, but only get the main stream, ignoring any variations:
Parse an const sgf = `(;FF[4]GM[1]SZ[19];B[aa];W[bb](;B[cc];W[dd];B[ad];W[bd])(;B[hh];W[hg]))`;const parsed = sgf2go;// in browser, const parsed = sgf2jsonMain(sgf);console;
The output will be:
sgf
from json
:
Generate const json = "key":"FF""value":"4" "key":"GM""value":"1" "key":"SZ""value":"19" "key":"B""value":"aa" "key":"W""value":"bb" "key":"B""value":"cc" "key":"W""value":"dd" "key":"B""value":"ad" "key":"W""value":"bd" "key":"B""value":"hh" "key":"W""value":"hg" ; const generated = sgf2go;// in browser, const generated = json2sgf(json);console;
The output will be:
(;FF[4]GM[1]SZ[19];B[aa];W[bb](;B[cc];W[dd];B[ad];W[bd])(;B[hh];W[hg]))
Hope it helps.