This is gnugo.info, produced by makeinfo version 4.0b from gnugo.texi.

INFO-DIR-SECTION GNU games
START-INFO-DIR-ENTRY
* GNU go: (gnugo).          The GNU Go program
END-INFO-DIR-ENTRY


File: gnugo.info,  Node: Decide string,  Next: Decide dragon,  Prev: Output File,  Up: Analyzing

Checking the reading code
=========================

   The `--decide-string' option is used to check the tactical reading
code (*note Tactical Reading::). This option takes an argument, which
is a location on the board in the usual algebraic notation (e.g.
`--decide-string C17'). This will tell you whether the reading code (in
`engine/reading.c') believes the string can be captured, and if so,
whether it believes it can be defended, which moves it finds to attack
or defend the move, how many nodes it searched in coming to these
conclusions. Note that when GNU Go runs normally (not with
`--decide-string') the points of attack and defense are computed when
`make_worms()' runs and cached in `worm.attack' and `worm.defend'.

   If used with an output file (`-o FILENAME') `--decide-string' will
produce a variation tree showing all the variations which are
considered. This is a useful way of debugging the reading code, and
also of educating yourself with the way it works. The variation tree
can be displayed graphically using CGoban.

   At each node, the comment contains some information. For example you
may find a comment:


     attack4-B at D12 (variation 6, hash 51180fdf)
     break_chain D12: 0
     defend3 D12: 1 G12 (trivial extension)

   This is to be interpreted as follows. The node in question was
generated by the function `attack3()' in `engine/reading.c', which was
called on the string at `D12'. The data in parentheses tell you the
values of `count_variations' and `hashdata.hashval'.

   The second value ("hash") you probably will not need to know unless
you are debugging the hash code, and we will not discuss it.  But the
first value ("variation") is useful when using the debugger `gdb'. You
can first make an output file using the `-o' option, then walk through
the reading with `gdb', and to coordinate the SGF file with the
debugger, display the value of `count_variations'. Specifically, from
the debugger you can find out where you are as follows:

     (gdb) set dump_stack()
     B:D13 W:E12 B:E13 W:F12 B:F11  (variation 6)

   If you place yourself right after the call to `trymove()' which
generated the move in question, then the variation number in the SGF
file should match the variation number displayed by `dump_stack()', and
the move in question will be the last move played (F11 in this example).

   This displays the sequence of moves leading up to the variation in
question, and it also prints `count_variations-1'.

   The second two lines tell you that from this node, the function
`break_chain()' was called at D12 and returned 0 meaning that no way
was found of rescuing the string by attacking an element of the
surrounding chain, and the function `defend3()' was called also at D12
and returned 1, meaning that the string can be defended, and that G12
is the move that defends it. If you have trouble finding the function
calls which generate these comments, try setting `sgf_dumptree=1' and
setting a breakpoint in `sgf_trace'.


File: gnugo.info,  Node: Decide dragon,  Next: GTP and GDB techniques,  Prev: Decide string,  Up: Analyzing

Checking the Owl code
=====================

   You can similarly debug the Owl code using the option
`--decide-dragon'. Usage is entirely similar to `--decide-string', and
it can be used similarly to produce variation trees. These should be
typically much smaller than the variation trees produced by
`--decide-string'.


File: gnugo.info,  Node: GTP and GDB techniques,  Next: Debugboard,  Prev: Decide dragon,  Up: Analyzing

GTP and GDB techniques
======================

   You can use the Go Text Protocol (*note GTP::) to determine the
statuses of dragons and other information needed for debugging. The GTP
command `dragon_data P12' will list the dragon data of the dragon at
`P12' and `worm_data' will list the worm data; other GTP commands may
be useful as well.

   You can also conveniently get such information from GDB.  A
suggested `.gdbinit' file may be found in *Note Debugging::. Assuming
this file is loaded, you can list the dragon data with the command:

     (gdb) dragon P12

   Similarly you can get the worm data with `worm P12'.


File: gnugo.info,  Node: Debugboard,  Next: Scoring,  Prev: GTP and GDB techniques,  Up: Analyzing

Debugboard
==========

   A useful utility called `debugboard' is made in the
`interface/debugboard/' directory. This can be run in an Xterm. Use a
smaller font since it requires 50 rows and 80 columns. This runs
`examine_position()', then makes a graphical display of the board.
Using the cursor movement keys, you can move around the board and find
out the contents of the worm, dragon and eye arrays.


File: gnugo.info,  Node: Scoring,  Next: Colored Display,  Prev: Debugboard,  Up: Analyzing

Scoring the game
================

   GNU Go can score the game. If done at the last move, this is usually
accurate unless there is a seki. Normally GNU Go will report its
opinion about the score at the end of the game, but if you want this
information about a game stored in a file, use the `--score' option.

     gnugo --score last -l filename

loads the sgf file to the end of the file and estimates the winner
after the last stored move by estimating the territory.

     gnugo --score end -l filename

loads the sgf file and GNU Go continues to play after the last stored
move by itself up to the very end.  Then the winner is determined by
estimating the territory.

     gnugo --score aftermath -l filename

loads the sgf file and GNU Go continues to play after the last stored
move by itself up to the very end. Then the winner is determined by the
most accurate algorithm available. Slower but more accurate than
`--score end'.

     gnugo --score L10 -l filename

loads the sgf file until a stone is placed on L10. Now the winner will
be estimated as with `gnugo --score last'.

   Any of these commands may be combined with `--chinese-rules' if you
want to use Chinese (area) counting.

     gnugo --score 100 -l filename

loads the sgf file until move number 100. Now the winner will be
estimated as with `gnugo --score last'.

   If the option `-o OUTPUTFILENAME' is provided, the results will also
be written as comment at the end of the output file.


File: gnugo.info,  Node: Colored Display,  Prev: Scoring,  Up: Analyzing

Colored Display
===============

   Various colored displays of the board may be obtained in a color
`xterm' or `rxvt' window. Xterm will only work if xterm is not compiled
with color support. If the colors are not displayed on your xterm, try
`rxvt'.  You may also use the Linux console. The colored display will
work best if the background color is black; if this is not the case you
may want to edit your `.Xdefaults' file or add the options `-bg black
-fg white' to `xterm' or `rxvt'.

Dragon Display
--------------

   You can get a colored ASCII display of the board in which each dragon
is assigned a different letter; and the different `matcher_status'
values (`ALIVE', `DEAD', `UNKNOWN', `CRITICAL') have different colors.
This is very handy for debugging. Actually two diagrams are generated.
The reason for this is concerns the way the matcher status is computed.
The dragon_status (*note Dragons::) is computed first, then for some,
but not all dragons, a more accurate owl status is computed. The
matcher status is the owl status if available; otherwise it is the
dragon_status. Both the dragon_status and the owl_status are displayed.
The color scheme is as follows:

     green = alive
     cyan = dead
     red = critical
     yellow = unknown
     magenta = unchecked

   To get the colored display, save a game in sgf format using CGoban,
or using the `-o' option with GNU Go itself.

   Open an `xterm' or `rxvt' window.

   Execute `gnugo -l [filename] -L [movenum] -T' to get the colored
display.

   Other useful colored displays may be obtained by using instead:

Eye Space Display
-----------------

   Instead of `-T', try this with `-E'. This gives a colored display of
the eyespaces, with marginal eye spaces marked `!' (*note Eyes::).

Moyo Display
------------

   The option `-m LEVEL' can give colored displays of the various
quantities which are computed in `engine/moyo.c'.

   The regions found by Bouzy's algorithm (*note Moyo::) can be
displayed with the following options:

     `-m LEVEL'
      use or (hexadecimal)   cumulative values for printing these reports :
         1       0x01         ascii printing of territorial evaluation (5/21)
         2       0x02         ascii printing of moyo evaluation (5/10)
         4       0x04         ascii printing of area (4/0)

   These data are today only used in the score estimation.

   The rest of the engine uses instead the new influence algorithm
explained in *Note Influence::.  To get a colored display of the
influence regions found by this module, use `-m 0x18' to see the
initial influence, and e.g. `-m 0x10 --debug-influence D5' to see the
influence after having made the move D5. There are various other
options available for numerical displays influence; for a detailed
description see *Note Influential Display::.

These options can be combined by adding the levels.


File: gnugo.info,  Node: API,  Next: SGF,  Prev: Analyzing,  Up: Top

Application Programmers Interface to GNU Go
*******************************************

   If you want to write your own interface to GNU Go, or if you want to
create a go application using the GNU Go engine, this chapter is of
interest to you.

   First an overview: GNU Go consists of two parts: the GNU Go engine
and a program (user interface) which uses this engine. These are linked
together into one binary. The current program implements the following
user modes:

   * An interactive board playable on ASCII terminals

   * solo play - GNU Go plays against itself

   * replay - a mode which lets the user investigate moves in an
     existing SGF file.

   * GMP - Go Modem Protocol, a protocol for automatic play between two
     computers.

   * GTP - Go Text Protocol, a more general go protocol, *note GTP::.

   The GNU Go engine can be used in other applications. For example,
supplied with GNU Go is another program using the engine, called
`debugboard', in the directory `interface/debugboard/'. The program
debugboard lets the user load SGF files and can then interactively look
at different properties of the position such as group status and eye
status.

   The purpose of this Chapter is to show how to interface your own
program such as `debugboard' with the GNU Go engine.

   Figure 1 describes the structure of a program using the GNU Go
engine.

                      +-----------------------------------+
                      |                                   |
                      |          Go application           |
                      |                                   |
                      +-----+----------+------+           |
                      |     |          |      |           |
                      |     |   Game   |      |           |
                      |     | handling |      |           |
                      |     |          |      |           |
                      |     +----+-----+      |           |
                      |   SGF    |    Move    |           |
                      | handling | generation |           |
                      |          |            |           |
                      +----------+------------+-----------+
                      |                                   |
                      |           Board handling          |
                      |                                   |
                      +-----------------------------------+
     
             Figure 1: The structure of a program using the GNU Go engine

   The foundation is a library called `libboard.a' which provides
efficient handling of a go board with rule checks for moves, with
incremental handling of connected strings of stones and with methods to
efficiently hash go positions.

   On top of this, there is a library which helps the application use
smart go files, SGF files, with complete handling of game trees in
memory and in files. This library is called `libsgf.a'

   The main part of the code within GNU Go is the move generation
library which given a position generates a move. This part of the
engine can also be used to manipulate a go position, add or remove
stones, do tactical and strategic reading and to query the engine for
legal moves. These functions are collected into `libengine.a'.

   The game handling code helps the application programmer keep tracks
of the moves in a game. Games can be saved to SGF files and then later
be read back again. These are also within `libengine.a'.

   The responsibility of the application is to provide the user with a
user interface, graphical or not, and let the user interact with the
engine.

* Menu:

* Getting Started::          How to use the engine in your program
* Basic Data Structures::    Basic Data Structures in the Engine
* The Board State::          The board_state `struct'
* Positional Functions::     Functions which manipulate a Position


File: gnugo.info,  Node: Getting Started,  Next: Basic Data Structures,  Prev: API,  Up: API

How to use the engine in your own program: getting started
==========================================================

   To use the GNU Go engine in your own program you must include the
file `gnugo.h'. This file describes the whole public API. There is
another file, `liberty.h', which describes the internal interface within
the engine. If you want to make a new module within the engine, e.g.
for suggesting moves you will have to include this file also. In this
section we will only describe the public interface.

   Before you do anything else, you have to call the function
`init_gnugo()'. This function initializes everything within the engine.
It takes one parameter: the number of megabytes the engine can use for
the internal hash table. In addition to this the engine will use a few
megabytes for other purposes such as data describing groups (liberties,
life status, etc), eyes and so on.


File: gnugo.info,  Node: Basic Data Structures,  Next: The Board State,  Prev: Getting Started,  Up: API

Basic Data Structures in the Engine
===================================

   There are some basic definitions in gnugo.h which are used
everywhere. The most important of these are the numeric declarations of
colors. Each intersection on the board is represented by one of these:


          color              value
          EMPTY                0
          WHITE                1
          BLACK                2

   In addition to these, the following values can be used in special
places, such as describing the borders of eyes:


          color                     value
          GRAY (GRAY_BORDER)          3
          WHITE_BORDER                4
          BLACK_BORDER                5

   There is a macro, `OTHER_COLOR(color)' which can be used to get the
other color than the parameter. This macro can only be used on `WHITE'
or `BLACK', but not on `EMPTY' or one of the border colors.

   GNU Go uses two different representations of the board, for most
purposes a one-dimensional one, but for a few purposes a two
dimensional one (*note Libboard::). The one-dimensional board was
introduced before GNU Go 3.2, while the two-dimensional board dates
back to the ancestral program written by Man Lung Li before 1995. The
API still uses the one-dimensional board, so the API functions have not
changed much since GNU Go 3.0.


File: gnugo.info,  Node: The Board State,  Next: Positional Functions,  Prev: Basic Data Structures,  Up: API

The board_state struct
======================

   A basic data structure in the engine is the `board_state' struct.
This structure is internal to the engine and is defined in `liberty.h'.


          typedef unsigned char Intersection;
     
          struct board_state {
            int board_size;
     
            Intersection board[BOARDSIZE];
            int board_ko_pos;
            int black_captured;
            int white_captured;
     
            Intersection initial_board[BOARDSIZE];
            int initial_board_ko_pos;
            int initial_white_captured;
            int initial_black_captured;
            int move_history_color[MAX_MOVE_HISTORY];
            int move_history_pos[MAX_MOVE_HISTORY];
            int move_history_pointer;
     
            float komi;
            int move_number;
          };

   Here `Intersection' stores `EMPTY', `WHITE' or `BLACK'. It is
currently defined as an `unsigned char' to make it reasonably efficient
in both storage and access time. The board state contains an array of
`Intersection''s representing the board.  The move history is contained
in the struct. Also contained in the struct is the location of a ko
(`EMPTY') if the last move was not a ko capture, the komi, the number
of captures, and corresponding data for the initial position at the
beginning of the move history.


File: gnugo.info,  Node: Positional Functions,  Prev: The Board State,  Up: API

Functions which manipulate a Position
=====================================

   All the functions in the engine that manipulate Positions have names
prefixed by `gnugo_'. These functions still use the two-dimensional
representation of the board (*note The Board::). Here is a complete
list, as prototyped in `gnugo.h':

   * `void init_gnugo(float memory)'
          Initialize the gnugo engine. This needs to be called once
          only.

   * `void gnugo_clear_board(int boardsize)'
          Clear the board.

   * `void gnugo_set_komi(float new_komi)'
          Set the komi.

   * `void gnugo_add_stone(int i, int j, int color)'
          Place a stone on the board

   * `void gnugo_remove_stone(int i, int j)'
          Remove a stone from the board

   * `int gnugo_is_pass(int i, int j)'
          Return true if (i,j) is PASS_MOVE

   * `void gnugo_play_move(int i, int j, int color)'
          Play a move and start the clock

   * `int gnugo_undo_move(int n)'
          Undo n permanent moves. Returns 1 if successful and 0 if it
          fails.  If n moves cannot be undone, no move is undone.

   * `int gnugo_play_sgfnode(SGFNode *node, int to_move)'
          Perform the moves and place the stones from the SGF node on
          the board. Return the color of the player whose turn it is to
          move.

   * `int gnugo_play_sgftree(SGFNode *root, int *until, SGFNode
     **curnode)'
          Play the moves in ROOT UNTIL movenumber is reached.  Return
          the color of the player whose turn it is to move.

   * `int gnugo_is_legal(int i, int j, int color)'
          Interface to `is_legal()'.

   * `int gnugo_is_suicide(int i, int j, int color)'
          Interface to `is_suicide()'.

   * `int gnugo_placehand(int handicap)'
          Interface to placehand. Sets up handicap pieces and returns
          the number of placed handicap stones.

   * `void gnugo_recordboard(SGFNode *root)'
          Interface to `sgffile_recordboard()'

   * `int gnugo_sethand(int handicap, SGFNode *node)'
          Interface to placehand. Sets up handicap stones and returns
          the number of placed handicap stones, updating the sgf file

   * `int gnugo_genmove(int *i, int *j, int color)'
          Interface to `genmove()'.

   * `int gnugo_attack(int m, int n, int *i, int *j)'
          Interface to `attack()'.

   * `int gnugo_find_defense(int m, int n, int *i, int *j)'
          Interface to `find_defense()'.

   * `void gnugo_who_wins(int color, FILE *outfile)'
          Interface to `who_wins()'.

   * `float gnugo_estimate_score(float *upper, float *lower)'
          Put upper and lower score estimates into `*upper', `*lower'
          and return the average. A positive score favors white. In
          computing the upper bound, `CRITICAL' dragons are awarded to
          white; in computing the lower bound, they are awarded to
          black.

   * `void gnugo_examine_position(int color, int how_much)'
          Interface to `examine_position'.

   * `int gnugo_get_komi()'
          Report the komi.

   * `void gnugo_get_board(int b[MAX_BOARD][MAX_BOARD])'
          Place the board into the `b' array.

   * `int gnugo_get_boardsize()'
          Report the board size.

   * `int gnugo_get_move_number()'
          Report the move number.

Game handling
=============

   The functions (in *note Positional Functions::) are all that are
needed to create a fully functional go program.  But to make the life
easier for the programmer, there is a small set of functions specially
designed for handling ongoing games.

   The data structure describing an ongoing game is the `Gameinfo'. It
is defined as follows:


     typedef struct {
       int       handicap;
     
       int       to_move;            /* whose move it currently is */
       SGFTree   game_record;        /* Game record in sgf format. */
     
       int       computer_player;    /* BLACK, WHITE, or EMPTY (used as BOTH) */
     
       char      outfilename[128];   /* Trickle file */
       FILE      *outfile;
     } Gameinfo;

   The meaning of `handicap' should be obvious. `to_move' is the color
of the side whose turn it is to move.

   The SGF tree `game_record' is used to store all the moves in the
entire game, including a header node which contains, among other
things, komi and handicap.

   If one or both of the opponents is the computer, the field
`computer_player' is used. Otherwise it can be ignored.

   GNU Go can use a trickle file to continuously save all the moves of
an ongoing game. This file can also contain information about internal
state of the engine such as move reasons for various locations or move
valuations. The name of this file should be stored in `outfilename' and
the file pointer to the open file is stored in `outfile'. If no trickle
file is used, `outfilename[0]' will contain a null character and
`outfile' will be set to `NULL'.

Functions which manipulate a Gameinfo
-------------------------------------

   All the functions in the engine that manipulate Gameinfos have names
prefixed by `gameinfo_'.  Here is a complete list, as prototyped in
`gnugo.h':

   * `void gameinfo_clear(Gameinfo *ginfo, int boardsize, float komi)'
          Initialize the `Gameinfo' structure.

   * `void gameinfo_print(Gameinfo *ginfo)'
          Print a gameinfo.

   * `void gameinfo_load_sgfheader(Gameinfo *gameinfo, SGFNode *head)'
          Reads header info from sgf structure and sets the appropriate
          variables.

   * `void gameinfo_play_move(Gameinfo *ginfo, int i, int j, int color)'
          Make a move in the game. Return 1 if the move was legal. In
          that case the move is actually done. Otherwise return 0.

   * `int gameinfo_play_sgftree_rot(Gameinfo *gameinfo, SGFNode *head,
     const char *untilstr, int orientation)'
          Play the moves in an SGF tree. Walk the main variation,
          actioning the properties into the playing board. Returns the
          color of the next move to be made. Head is an sgf tree.
          Untilstr is an optional string of the form either 'L12' or
          '120' which tells it to stop playing at that move or move
          number. When debugging, this is the location of the move
          being examined.

   * `int gameinfo_play_sgftree(Gameinfo *gameinfo, SGFNode *head,
     const char *untilstr)'
          Same as previous function, using standard orientation.


File: gnugo.info,  Node: SGF,  Next: Libboard,  Prev: API,  Up: Top

Handling SGF trees in memory
****************************

   "SGF" - Smart Game Format - is a file format which is used for
storing game records for a number of different games, among them chess
and go. The format is a framework with special adaptions to each game.
This is not a description of the file format standard. Too see the exact
definition of the file format, see <http://www.red-bean.com/sgf/>.

   GNU Go contains a library to handle go game records in the SGF
format in memory and to read and write SGF files. This library -
`libsgf.a' - is in the `sgf' subdirectory. To use the SGF routines,
include the file `sgftree.h'.

   Each game record is stored as a tree of "nodes", where each node
represents a state of the game, often after some move is made. Each node
contains zero or more "properties", which gives meaning to the node.
There can also be a number of "child nodes" which are different
variations of the game tree. The first child node is the main variation.

   Here is the definition of `SGFNode', and `SGFProperty', the data
structures which are used to encode the game tree.


     typedef struct SGFProperty_t {
       struct SGFProperty_t *next;
       short  name;
       char   value[1];
     } SGFProperty;
     
     typedef struct SGFNode_t {
       SGFProperty      *props;
       struct SGFNode_t *parent;
       struct SGFNode_t *child;
       struct SGFNode_t *next;
     } SGFNode;

   Each node of the SGF tree is stored in an `SGFNode' struct. It has a
pointer to a linked list of properties (see below) called `props'. It
also has a pointer to a linked list of children, where each child is a
variation which starts at this node. The variations are linked through
the `next' pointer and each variation continues through the `child'
pointer. Each and every node also has a pointer to its parent node (the
`parent' field), except the top node whose parent pointer is `NULL'.

   An SGF property is encoded in the `SGFPoperty' struct. It is linked
in a list through the `next' field.  A property has a `name' which is
encoded in a short int.  Symbolic names of properties can be found in
`sgf_properties.h'.

   Some properties also have a value, which could be an integer, a
floating point value, a character or a string. These values can be
accessed or set through special functions (see below).

Functions which manipulate SGF nodes and properties
===================================================

   All the functions which create and manipulate SGF trees are prefixed
by `sgf'.  The SGF code was donated to us by Thomas Traber, so they
don't follow the naming conventions of GNU Go perfectly.

Low level functions
-------------------

   These functions let the caller create nodes or access nodes easier.

   * `SGFNode *sgfNewNode(void)'
          Allocate and return a new instance of `SGFNode'. The node is
          cleared.

   * `SGFProperty *sgfMkProperty(const char *name, const  char *value,
      SGFNode *node, SGFProperty *last)'
          Allocate and return a new instance of `SGFProperty'. The
          `name' should be 1 or 2 characters long.  This function should
          probably not be used directly. Instead, use the
          `sgfAddProperty' functions.

   * `SGFNode *sgfPrev(SGFNode *node)'
          Return the previous node in a chain. This is done by going to
          the parent node and then search through the children until
          the same node is found.  If there is no previous node, `NULL'
          is returned.

   * `SGFNode *sgfRoot(SGFNode *node)'
          Return the root of the tree.  If `node' already is the root,
          `node' itself is returned.


Functions which manipulate SGF properties
-----------------------------------------

   * `int sgfGetIntProperty(SGFNode *node, const char *name, int
     *value)'
          Get the property `name' in `node' as an integer. The value is
          returned in `value'. Returns 1 if successful, otherwise
          returns 0.

   * `int sgfGetFloatProperty(SGFNode *node, const char *name, float
     *value)'
          Get the property `name' in `node' as a floating point value.
          The value is returned in `value'. Returns 1 if successful,
          otherwise returns 0.

   * `int sgfGetCharProperty(SGFNode *node, const char *name, char
     **value)'
          Get the property `name' in `node' as a string of characters.
          The value is returned in `value'. Returns 1 if successful,
          otherwise returns 0.

   * `void sgfAddProperty(SGFNode *node, const char *name, const char
     *value)'
          Add a new property to `node'. There is no check to see if
          there already is a property with the same name. The property
          value has to be a character string.

   * `void sgfAddPropertyInt(SGFNode *node, const char *name, long val)'
          Add an integer property to `node'. This function converts the
          value to a string and calls `sgfAddProperty'.

   * `void sgfAddPropertyFloat(SGFNode *node, const char *name, float
     val)'
          Add a floating point property to `node'. This function
          converts the value to a string and calls `sgfAddProperty'.

   * `void sgfOverwriteProperty(SGFNode *node, const char *name, const
     char *text)'
          Overwrite the property `name' in `node' with the string
          `text'.  If the property does not yet exist in `node', it is
          added using `sgfAddProperty'.

   * `void sgfOverwritePropertyInt(SGFNode *node, const char *name, int
     value)'
          Overwrite the property `name' in `node' with the integer
          `value'.  If the property does not yet exist in `node', it is
          added using `sgfAddPropertyInt'.

   * `void sgfOverwritePropertyFloat(SGFNode *node, const char *name,
     float value)'
          Overwrite the property `name' in `node' with the floating
          point number `value'.  If the property does not yet exist in
          `node', it is added using `sgfAddPropertyFloat'.


Functions which manipulate SGF nodes
------------------------------------

   * `SGFNode *sgfAddStone(SGFNode *node, int color, int movex, int
     movey)'
          Add a stone to `node'. Properties added is either `AB' (black
          stone) or `AW' (white stone).

   * `SGFNode *sgfAddPlay(SGFNode *node, int who, int movex, int movey)'

          Add a child node with a move to `node'. Properties added is
          either `B' (black move) or `W' (white move).  A pass is coded
          by `(-1, -1)'.

          This function does not add a property to the node itself, but
          adds a child node instead. If there are previous child nodes,
          the new node is placed before the other ones, so this
          function should be used if you want to add a main branch to
          the tree. To add a variation, use `sgfAddPlayLast' instead.

   * `SGFNode *sgfAddPlayLast(SGFNode *node, int who, int movex, int
     movey)'

          Add a child node with a move to `node'. Properties added is
          either `B' (black move) or `W' (white move).  A pass is coded
          by `(-1, -1)'.

          If there are previous child nodes in `node', the move is
          added by adding the child node last, so this function should
          be used when you want to add a variation to the game tree.

   * `int sgfPrintCharProperty(FILE *file, SGFNode *node, const char
     *name)'
          Print the properties of type `name' in `node' on `file'.

   * `int sgfPrintCommentProperty(FILE *file, SGFNode *node, const char
     *name)'
          Print the comment properties of type `name' in `node' on
          `file'.

   * `void sgfWriteResult(SGFNode *node, float score, int overwrite)'
          Add a `RE' (result) property to `node'. This property will
          contain the game result. If `overwrite' is zero the result is
          written only if no previous result property exists.

   * `SGFNode *sgfCircle(SGFNode *node, int i, int j)'
          Add a `CR' (circle) property at `(i, j)' to `node'.

   * `SGFNode *sgfSquare(SGFNode *node, int i, int j)'
          Calls `sgfMark' to add a `MA' (mark) property at `(i, j)' to
          `node'.

   * `SGFNode *sgfTriangle(SGFNode *node, int i, int j)'
          Add a `TR' (triangle) property at `(i, j)' to `node'.

   * `SGFNode *sgfMark(SGFNode *node, int i, int j)'
          Add a `MA' (mark) property at `(i, j)' to `node'.

   * `SGFNode *sgfAddComment(SGFNode *node, const char *comment)'
          Add a `C' (comment) property to `node'.

   * `SGFNode *sgfBoardText(SGFNode *node, int i, int j, const char
     *text)'
          Add a `LB' (label) property at `(i, j)' to `node'.

   * `SGFNode *sgfBoardChar(SGFNode *node, int i, int j, char c)'
          Add a `LB' (label) property at `(i, j)' to `node'. This
          functions is a utility function that converts the character
          to a string and calls `sgfBoardText'.

   * `SGFNode *sgfBoardNumber(SGFNode *node, int i, int j, int number)'
          Add a numeric label at `(i, j)' by calling `sgfBoardText'.

   * `SGFNode *sgfStartVariant(SGFNode *node)'

          Start a new variation in the game tree. This means that the
          `next' pointer of `node' is followed to the end of the list
          and a new node is inserted there. A pointer to the new node
          is returned.

   * `SGFNode *sgfStartVariantFirst(SGFNode *node)'

          Same as `sgfStartVariant', except that the node is placed
          first in the list. This means that the new variation will be
          the main variation of the game tree. Returns a pointer to the
          new node.

   * `SGFNode *sgfAddChild(SGFNode *node)'
          Adds a child node to `node'. If there already are children,
          the new node is placed last in the list. Returns a pointer to
          the new node.


High level functions
--------------------

   * `SGFNode *sgfCreateHeaderNode(int boardsize, float komi)'
          Create a new SGF node with the two properties `SZ' (size) and
          `KM' (komi).  More properties, like `HA' (handicap), can later
          be added to it.

          The idea with this node is to store the game info and to use
          as a root node for the game.

   * `SGFNode *readsgffile(const char *filename)'
          Read an SGF file and return the resulting tree.

   * `void sgf_write_header(SGFNode *root, int overwrite, int seed,
     float komi)'
          Write random seed, date, ruleset, komi and SGF file version
          to the header node `root'. If `overwrite' is non-zero, it
          overwrites the values in the node, otherwise it just writes
          those that are missing.

          Ruleset is always set to "Japanese", date is set to the
          current date.

   * `int writesgf(SGFNode *root, const char *filename)'
          Write the tree starting in `root' to the file `filename'.  If
          `filename' is `-', the tree is written to `stdout'. Returns 1
          if successful, otherwise returns 0.


The SGFTree datatype
====================

   Sometimes we just want to record an ongoing game or something
similarly simple and not do any sofisticated tree manipulation.  In
that case we can use the simplified interface provided by `SGFTree'
below.


     typedef struct SGFTree_t {
       SGFNode *root;
       SGFNode *lastnode;
     } SGFTree;

   An `SGFTree' contains a pointer to the root node of an SGF tree and
a pointer to the node that we last accessed. Most of the time this will
be the last move of an ongoing game.

   Most of the functions which manipulate an `SGFTree' work exactly
like their `SGFNode' counterparts, except that they work on the current
node of the tree.

   All the functions below that take arguments `tree' and `node' will
work on:

  1. `node' if non-`NULL'

  2. `tree->lastnode' if non-`NULL'

  3. The current end of the game tree.
        in that order.

Functions that manipulate sgftrees
----------------------------------

   * `void sgftree_clear(SGFTree *tree)'
          Clear the `root' and `lastnode' pointers of `tree'. `NOTE:'
          This function does not free any memory. That has to be done
          separately.

   * `int sgftree_readfile(SGFTree *tree, const char *infilename)'
          Read an SGF file with the name `infilename' and store it in
          `tree'. Return 1 if successful, otherwise return 0. `lastnode'
          will be set to `NULL'.

   * `SGFNode *sgftreeNodeCheck(SGFTree *tree, SGFNode *node)'
          Return the node to work on as described above. This is:
            1. `node' if non-`NULL'

            2. `tree->lastnode' if non-`NULL'

            3. The current end of the tree.
               in that order.


   * `SGFNode *sgftreeAddPlay(SGFTree *tree, SGFNode *node, int color
     int movex, int movey)'
          Add a move of `color' at `(movex,movey)' to the tree. *Note
          sgfAddPlay: sgfAddPlay.

   * `SGFNode *sgftreeAddPlayLast(SGFTree *tree, SGFNode *node, int
     color, int movex, int movey)'
          Add a variation of `color' at `(movex,movey)' to the tree.
          *Note sgfAddPlayLast: sgfAddPlayLast.

   * `SGFNode *sgftreeAddStone(SGFTree *tree, SGFNode *node, int color,
     int movex, int movey)'
          Add a stone of `color' at `(movex,movey)' to the tree.

   * `void sgftreeWriteResult(SGFTree *tree, float score, int
     overwrite)'
          Add the result to the tree. If there already is a result,
          only overwrite it if `overwrite' is non-zero.

   * `SGFNode *sgftreeCircle  (SGFTree *tree, SGFNode *node, int i, int
     j)'
          Add a circle property at `(i, j)' to the tree.

   * `SGFNode *sgftreeSquare  (SGFTree *tree, SGFNode *node, int i, int
     j)'
          Add a square property at `(i, j)' to the tree.

   * `SGFNode *sgftreeTriangle(SGFTree *tree, SGFNode *node, int i, int
     j)'
          Add a triangle property at `(i, j)' to the tree.

   * `SGFNode *sgftreeMark(SGFTree *tree, SGFNode *node, int i, int j)'
          Add a mark property at `(i, j)' to the tree.

   * `SGFNode *sgftreeAddComment(SGFTree *tree, SGFNode *node, const
     char *comment)'
          Add a comment property to the tree. This is a property of the
          node itself, and has no position on the board.

   * `SGFNode *sgftreeBoardText(SGFTree *tree, SGFNode *node, int i,
     int j, const char *text)'
          Add a text property at `(i, j)' to the tree.

   * `SGFNode *sgftreeBoardChar(SGFTree *tree, SGFNode *node, int i,
     int j, char c)'
          Add a character at `(i, j)' to the tree.

   * `SGFNode *sgftreeBoardNumber(SGFTree *tree, SGFNode *node, int i,
     int j, int number)'
          Add a number at `(i, j)' to the tree.

   * `SGFNode *sgftreeStartVariant(SGFTree *tree, SGFNode *node)'
          Start a new variation in the tree. *Note sgfStartVariant:
          sgfStartVariant.

   * `SGFNode *sgftreeStartVariantFirst(SGFTree *tree, SGFNode *node)'
          Start a new main variation in the tree. *Note
          sgfStartVariantFirst: sgfStartVariantFirst.

   * `SGFNode *sgftreeCreateHeaderNode(SGFTree *tree, int boardsize,
     float komi)'
          Add a header node first in `tree'.

   * `void sgftreeSetLastNode(SGFTree *tree, SGFNode *last_node)'
          Explicitly set the last accessed node in `tree' to
          `last_node'.



File: gnugo.info,  Node: Libboard,  Next: Move Generation,  Prev: SGF,  Up: Top

The Board Library
*****************

* Menu:

* Board Data Structures::      Board Data Structures
* Board Setup Functions::      Board Setup Functions
* Move Functions::             Move Functions
* Status Functions::           Status Functions
* String Functions::           String and Miscellaneous Functions

   The foundation of the GNU Go engine is a library of very efficient
routines for handling go boards.  This board library, called
`libboard', can be used for those programs that only need a basic go
board but no AI capability. One such program is `patterns/joseki.c',
which compiles joseki pattern databases from SGF files.

   The library consists of the following files:

   * `board.c'
          The basic board code.  It uses incremental algorithms for
          keeping track of strings and liberties on the go board.

   * `hash.c'
          Code for hashing go positions.

   * `globals.c'
          Global variables needed in the rest of the files.  This file
          also contains global variables needed in the rest of the
          engine.

   * `sgffile.c'
          Implementation of output file in SGF format.

   * `showbord.c'
          Print go boards.

   * `printutils.c'
          Utilities for printing go boards and other things.


   To use the board library, you must include `liberty.h' just like
when you use the whole engine, but of course you cannot use all the
functions declared in it, i.e. the functions that are part of the
engine, but not part of the board library.  You must link your
application with `libboard.a'.


File: gnugo.info,  Node: Board Data Structures,  Next: Board Setup Functions,  Up: Libboard

Board Data structures
=====================

   The basic data structures of the board correspond tightly to the
`board_state' struct described in *Note The Board State::. They are all
stored in global variables for efficiency reasons, the most important
of which are:


     int           board_size;
     Intersection  board[MAXSIZE];
     int           board_ko_pos;
     
     float         komi;
     int           white_captured;
     int           black_captured;
     
     Hash_data     hashdata;

   The description of the `Position' struct is applicable to these
variables also, so we won't duplicate it here.  All these variables are
globals for performance reasons.  Behind these variables, there are a
number of other private data structures.  These implement incremental
handling of strings, liberties and other properties (*note Incremental
Board::). The variable `hashdata' contains information about the hash
value for the current position (*note Hashing::).

   These variables should never be manipulated directly, since they are
only the front end for the incremental machinery. They can be read, but
should only be written by using the functions described in the next
section. If you write directly to them, the incremental data structures
will become out of sync with each other, and a crash is the likely
result.


File: gnugo.info,  Node: Board Setup Functions,  Next: Move Functions,  Prev: Board Data Structures,  Up: Libboard

Board Functions
===============

   These functions are all the public functions in `engine/board.c'.

Setup Functions
---------------

   These functions are used when you want to set up a new position
without actually playing out moves.

   * `void clear_board()'
          Clears the internal board (`board[]'), resets the ko position,
          captured stones and recalculates the hash value.

   * `void setup_board(Intersection new_board[MAX_BOARD][MAX_BOARD],
     int ko_pos, int *last, float new_komi, int w_captured, int
     b_captured)'
          Set up a new board position using the parameters.

   * `void add_stone(int pos, int color)'
          Place a stone on the board and update the hashdata.  No
          captures are done.

   * `void remove_stone(int pos)'
          Remove a stone from the board and update the hashdata.


File: gnugo.info,  Node: Move Functions,  Next: Status Functions,  Prev: Board Setup Functions,  Up: Libboard

Move Functions
--------------

   *Reading*, often called *search* in computer game theory, is a
fundamental process in GNU Go. This is the process of generating
hypothetical future boards in order to determine the answer to some
question, for example "can these stones live."  Since these are
hypothetical future positions, it is important to be able to undo them,
ultimately returning to the present board. Thus a move stack is
maintained during reading. When a move is tried, by the function
`trymove', or its variant `tryko'. This function pushes the current
board on the stack and plays a move. The stack pointer `stackp', which
keeps track of the position, is incremented. The function `popgo()'
pops the move stack, decrementing `stackp' and undoing the last move
made.

   Every successful `trymove()' must be matched with a `popgo()'.  Thus
the correct way of using this function is:


       if (trymove(pos, color, ... )) {
            ...    [potentially lots of code here]
            popgo();
       }

Here the `komaster' is only set if a conditional ko capture has been
made at an earlier move. This feature of the tactical and owl reading
code in GNU Go is used to prevent redundant reading when there is a ko
on the board (*note Ko::).

   * `void play_move(int pos, int color)'
          Play a move at `(pos)'. If you want to test for legality you
          should first call `is_legal()'. This function strictly
          follows the algorithm:
            1. Place a stone of given color on the board.

            2. If there are any adjacent opponent strings without
               liberties, remove them and increase the prisoner count.

            3. If the newly placed stone is part of a string without
               liberties, remove it and increase the prisoner count.

   * `int trymove(int pos, int color, const char *message, int str, int
     komaster, int kom_pos)'
          Returns true if `(pos)' is a legal move for `color'. In that
          case, it pushes the board on the stack and makes the move,
          incrementing `stackp'. If the reading code is recording
          reading variations (as with `--decide-string' or with `-o'),
          the string `*message' will be inserted in the SGF file as a
          comment. The comment will also refer to the string at `str'
          if this is not `0'. The komaster and ko position variables
          are described elsewhere (*note Ko::)

   * `int TRY_MOVE()'
          Wrapper around trymove which suppresses `*message' and
          `(k,l)'.  Used in `helpers.c'

   * `int tryko(int pos, int color, const char *message, int komaster,
     int kom_pos)'
          `tryko()' pushes the position onto the stack, and makes a move
          `pos' of `color'. The move is allowed even if it is an
          illegal ko capture. It is to be imagined that `color' has
          made an intervening ko threat which was answered and now the
          continuation is to be explored. Return 1 if the move is legal
          with the above caveat. Returns zero if it is not legal
          because of suicide.

   * `void popgo()'
          Pops the move stack. This function must (eventually) be
          called after a succesful `trymove' or `tryko' to restore the
          board position. It undoes all the changes done by the call to
          `trymove/tryko' and leaves the board in the same state as it
          was before the call.

          *NOTE*: If `trymove/tryko' returns `0', i.e. the tried move
          was not legal, you must *not* call `popgo'.

   * `int komaster_trymove(int pos, int color, const char *message, int
     str, int komaster, int kom_pos, int *new_komaster, int
     *new_kom_pos, int *is_conditional_ko, int consider_conditional_ko)'
          Variation of `trymove'/`tryko' where ko captures (both
          conditional and unconditional) must follow a komaster scheme
          (*note Ko::).

   * `int move_in_stack(int pos, int cutoff)'
          Returns true if at least one move been played at `(pos)' at
          deeper than level 'cutoff' in the reading tree.

   * `void void get_move_from_stack(int k, int *move, int *color)'
          Retrieve the move number `k' from the move stack.  The move
          location is returned in `(*move)', and the color that made the
          move is returned in `*color'.

   * `void dump_stack(void)'
          Handy for debugging the reading code under GDB. Prints the
          move stack.  Usage: `(gdb) set dump_stack()'.

   * `void reset_trymove_counter()'
          Reset the trymove counter.  This counter is incremented every
          time that a variant of `trymove' or `tryko' is called.

   * `int get_trymove_counter()'
          Retrieve the trymove counter.


File: gnugo.info,  Node: Status Functions,  Next: String Functions,  Prev: Move Functions,  Up: Libboard

Status Functions
----------------

   These functions are used for inquiring about properties of the
current position or of potential moves.

   * `int is_pass(int pos)'
          Returns true if the move `(pos)' is PASS_MOVE, that is, 0.

   * `int is_legal(int pos, int color)'
          Returns true if a move at `pos' is legal for `color'.

   * `int is_ko(int pos, int color, int *ko_pos)'
          Return true if the move `pos' by `color' is a ko capture
          whether capture is a legal ko capture on this move or not. If
          `*ko_pos' are non-`NULL', then the location of the captured
          ko stone are returned through `*ko_pos'. If the move is not a
          ko capture, `*ko_pos' is set to 0.

   * `int is_illegal_ko_capture(int pos, int color)'
          Return true if the move `POS' by `color' would be an illegal
          ko capture.  There is no need to call both `is_ko' and
          `is_illegal_ko_capture'.

   * `int is_self_atari(int pos, int color)'
          Return true if a move by `color' at `pos' would be a self
          atari, i.e. whether it would get only one liberty. This
          function returns true also for the case of a suicide move.

   * `int is_suicide(int pos, int color)'
          Returns true if a move at `pos' is suicide for `color'.

   * `int does_capture_something(int pos, int color)'
          Returns true if a move at `pos' does capture any stone for the
          other side.

   * `int stones_on_board(int color)'
          Return the number of stones of the indicated color(s) on the
          board. This only count stones in the permanent position, not
          stones placed by `trymove()' or `tryko()'. Use
          `stones_on_board(BLACK | WHITE)' to get the total number of
          stones on the board.

