(Introduction to toSGF method)
The toSGF method allows you to convert a used-defined object into SGF.
This method is invoked implicitly as a method on the object when you generate a SGF string:
Code:
SGFGrove.stringify([[
[
{ FF: 4 },
{
B: {
toSGF: function () {
return "pd";
}
}
}
],
[]
]]);
// => "(;FF[4];B[pd])"
What happened? The B property (black move) of the second node was replaced with the return value of the toSGF method ("pd").
Since B/W property (black/white move) is frequently used in SGF, it's a good idea to define a Move class:
Code:
var Move = function (x, y) {
this.x = x; // => "p"
this.y = y; // => "d"
};
Move.prototype.toSGF = function () {
return this.x + this.y; // => "p"+"d" => "pd"
};
The Move class has "x" and "y" attributes and implements an object method "toSGF".
While the "x" or "y" attribute in the above definition is-a string, you can also define them as a number.
You can use any coordinate system in your JavaScript if you define how to convert your Move object into SGF.
Using the Move class, the above example can be rewritten as follows:
Code:
SGFGrove.stringify([[
[
{ FF: 4 },
{
B: new Move("p", "d")
}
],
[]
]]);
// => "(;FF[4];B[pd])"
You can also add toSGF methods to SGF collection/game tree/node to absract those data.
The toSGF method helps you write reusable code.