t-regress/README: Introdce description and SGF syntax
[pachi/t.git] / board.h
blob7af701b1c3be33c1be02871168d7f1ea85ef9445
1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
3 #include "probdist.h"
5 #ifndef PACHI_BOARD_H
6 #define PACHI_BOARD_H
8 #include <inttypes.h>
9 #include <stdbool.h>
10 #include <stdint.h>
12 #include "util.h"
13 #include "stone.h"
14 #include "move.h"
16 struct fbook;
19 /* Maximum supported board size. (Without the S_OFFBOARD edges.) */
20 #define BOARD_MAX_SIZE 19
23 /* The board implementation has bunch of optional features.
24 * Turn them on below: */
26 #define WANT_BOARD_C // capturable groups queue
28 //#define BOARD_SIZE 9 // constant board size, allows better optimization
30 #define BOARD_PAT3 // incremental 3x3 pattern codes
32 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
33 //#define BOARD_TRAIT_SAFE 1 // include btraits.safe (rather expensive, unused)
34 //#define BOARD_TRAIT_SAFE 2 // include btraits.safe based on full is_bad_selfatari()
37 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
38 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
41 /* Some engines might normalize their reading and skip symmetrical
42 * moves. We will tell them how can they do it. */
43 struct board_symmetry {
44 /* Playground is in this rectangle. */
45 int x1, x2, y1, y2;
46 /* d == 0: Full rectangle
47 * d == 1: Top triangle */
48 int d;
49 /* General symmetry type. */
50 /* Note that the above is redundant to this, but just provided
51 * for easier usage. */
52 enum {
53 SYM_FULL,
54 SYM_DIAG_UP,
55 SYM_DIAG_DOWN,
56 SYM_HORIZ,
57 SYM_VERT,
58 SYM_NONE
59 } type;
63 typedef uint64_t hash_t;
64 #define PRIhash PRIx64
66 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
67 * a dependency hell. */
68 typedef uint32_t hash3_t; // 3x3 pattern hash
71 /* Note that "group" is only chain of stones that is solidly
72 * connected for us. */
73 typedef coord_t group_t;
75 struct group {
76 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
77 * don't care. */
78 /* _Combination_ of these two values can make some difference
79 * in performance - fine-tune. */
80 #define GROUP_KEEP_LIBS 10
81 // refill lib[] only when we hit this; this must be at least 2!
82 // Moggy requires at least 3 - see below for semantic impact.
83 #define GROUP_REFILL_LIBS 5
84 coord_t lib[GROUP_KEEP_LIBS];
85 /* libs is only LOWER BOUND for the number of real liberties!!!
86 * It denotes only number of items in lib[], thus you can rely
87 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
88 int libs;
91 struct neighbor_colors {
92 char colors[S_MAX];
96 /* Point traits bitmap; we update this information incrementally,
97 * it can be used e.g. for fast pattern features matching. */
98 struct btraits {
99 /* Number of neighbors we can capture. 0=this move is
100 * not capturing, 1..4=this many neighbors we can capture
101 * (can be multiple neighbors of same group). */
102 unsigned cap:3;
103 /* Number of 1-stone neighbors we can capture. */
104 unsigned cap1:3;
105 #ifdef BOARD_TRAIT_SAFE
106 /* Whether it is SAFE to play here. This is essentially just
107 * cached result of board_safe_to_play(). (Of course the concept
108 * of "safety" is not perfect here, but it's the cheapest
109 * reasonable thing we can do.) */
110 bool safe:1;
111 #endif
112 /* Whether we need to re-compute this coordinate; used to
113 * weed out duplicates. Maintained only for S_BLACK. */
114 bool dirty:1;
118 /* You should treat this struct as read-only. Always call functions below if
119 * you want to change it. */
121 struct board {
122 int size; /* Including S_OFFBOARD margin - see below. */
123 int size2; /* size^2 */
124 int bits2; /* ceiling(log2(size2)) */
125 int captures[S_MAX];
126 floating_t komi;
127 int handicap;
128 /* The ruleset is currently almost never taken into account;
129 * the board implementation is basically Chinese rules (handicap
130 * stones compensation) w/ suicide (or you can look at it as
131 * New Zealand w/o handi stones compensation), while the engine
132 * enforces no-suicide, making for real Chinese rules. */
133 enum {
134 RULES_CHINESE, /* default value */
135 RULES_AGA,
136 RULES_NEW_ZEALAND,
137 RULES_JAPANESE,
138 RULES_STONES_ONLY, /* do not count eyes */
139 } rules;
141 char *fbookfile;
142 struct fbook *fbook;
144 /* Iterator offsets for foreach_neighbor*() */
145 int nei8[8], dnei[4];
147 int moves;
148 struct move last_move;
149 struct move last_move2; /* second-to-last move */
150 struct move last_move3; /* just before last_move2, only set if last_move is pass */
151 struct move last_move4; /* just before last_move3, only set if last_move & last_move2 are pass */
152 /* Whether we tried to add a hash twice; board_play*() can
153 * set this, but it will still carry out the move as well! */
154 bool superko_violation;
156 /* The following two structures are goban maps and are indexed by
157 * coord.pos. The map is surrounded by a one-point margin from
158 * S_OFFBOARD stones in order to speed up some internal loops.
159 * Some of the foreach iterators below might include these points;
160 * you need to handle them yourselves, if you need to. */
162 /* Stones played on the board */
163 enum stone *b; /* enum stone */
164 /* Group id the stones are part of; 0 == no group */
165 group_t *g;
166 /* Positions of next stones in the stone group; 0 == last stone */
167 coord_t *p;
168 /* Neighboring colors; numbers of neighbors of index color */
169 struct neighbor_colors *n;
170 /* Zobrist hash for each position */
171 hash_t *h;
172 #ifdef BOARD_PAT3
173 /* 3x3 pattern code for each position; see pattern3.h for encoding
174 * specification. The information is only valid for empty points. */
175 hash3_t *pat3;
176 #endif
177 #ifdef BOARD_TRAITS
178 /* Incrementally matched point traits information, black-to-play
179 * ([][0]) and white-to-play ([][1]). */
180 /* The information is only valid for empty points. */
181 struct btraits (*t)[2];
182 #endif
183 /* Cached information on x-y coordinates so that we avoid division. */
184 uint8_t (*coord)[2];
186 /* Group information - indexed by gid (which is coord of base group stone) */
187 struct group *gi;
189 /* Positions of free positions - queue (not map) */
190 /* Note that free position here is any valid move; including single-point eyes!
191 * However, pass is not included. */
192 coord_t *f; int flen;
194 #ifdef WANT_BOARD_C
195 /* Queue of capturable groups */
196 group_t *c; int clen;
197 #endif
199 #ifdef BOARD_TRAITS
200 /* Queue of positions that need their traits updated */
201 coord_t *tq; int tqlen;
202 #endif
204 /* Symmetry information */
205 struct board_symmetry symmetry;
207 /* Last ko played on the board. */
208 struct move last_ko;
209 int last_ko_age;
211 /* Basic ko check */
212 struct move ko;
214 /* Engine-specific state; persistent through board development,
215 * is reset only at clear_board. */
216 void *es;
218 /* Playout-specific state; persistent through board development,
219 * but its lifetime is maintained in play_random_game(); it should
220 * not be set outside of it. */
221 void *ps;
224 /* --- PRIVATE DATA --- */
226 /* For superko check: */
228 /* Board "history" - hashes encountered. Size of the hash should be
229 * >> board_size^2. */
230 #define history_hash_bits 12
231 #define history_hash_mask ((1 << history_hash_bits) - 1)
232 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
233 #define history_hash_next(i) ((i + 1) & history_hash_mask)
234 hash_t history_hash[1 << history_hash_bits];
235 /* Hash of current board position. */
236 hash_t hash;
237 /* Hash of current board position quadrants. */
238 hash_t qhash[4];
241 #ifdef BOARD_SIZE
242 /* Avoid unused variable warnings */
243 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
244 #define board_size2(b_) (board_size(b_) * board_size(b_))
245 #else
246 #define board_size(b_) ((b_)->size)
247 #define board_size2(b_) ((b_)->size2)
248 #endif
250 /* This is a shortcut for taking different action on smaller
251 * and large boards (e.g. picking different variable defaults).
252 * This is of course less optimal than fine-tuning dependency
253 * function of values on board size, but that is difficult and
254 * possibly not very rewarding if you are interested just in
255 * 9x9 and 19x19. */
256 #define board_large(b_) (board_size(b_)-2 >= 15)
258 #if BOARD_SIZE == 19
259 # define board_bits2(b_) 9
260 #elif BOARD_SIZE == 13
261 # define board_bits2(b_) 8
262 #elif BOARD_SIZE == 9
263 # define board_bits2(b_) 7
264 #else
265 # define board_bits2(b_) ((b_)->bits2)
266 #endif
268 #define board_at(b_, c) ((b_)->b[c])
269 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
271 #define group_at(b_, c) ((b_)->g[c])
272 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
274 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
275 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
276 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
277 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
278 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
279 #define immediate_liberty_count(b_, coord) (4 - neighbor_count_at(b_, coord, S_BLACK) - neighbor_count_at(b_, coord, S_WHITE) - neighbor_count_at(b_, coord, S_OFFBOARD))
281 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
283 #define groupnext_at(b_, c) ((b_)->p[c])
284 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
286 #define group_base(g_) (g_)
287 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
288 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
289 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
290 /* board_group_other_lib() makes sense only for groups with two liberties. */
291 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
293 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
295 struct board *board_init(char *fbookfile);
296 struct board *board_copy(struct board *board2, struct board *board1);
297 void board_done_noalloc(struct board *board);
298 void board_done(struct board *board);
299 /* size here is without the S_OFFBOARD margin. */
300 void board_resize(struct board *board, int size);
301 void board_clear(struct board *board);
303 struct FILE;
304 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
305 void board_print(struct board *board, FILE *f);
306 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
308 /* Place given handicap on the board; coordinates are printed to f. */
309 void board_handicap(struct board *board, int stones, FILE *f);
311 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
312 int board_play(struct board *board, struct move *m);
313 /* Like above, but plays random move; the move coordinate is recorded
314 * to *coord. This method will never fill your own eye. pass is played
315 * when no move can be played. You can impose extra restrictions if you
316 * supply your own permit function; the permit function can also modify
317 * the move coordinate to redirect the move elsewhere. */
318 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
319 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
321 /*Undo, supported only for pass moves. Returns -1 on error, 0 otherwise. */
322 int board_undo(struct board *board);
324 /* Returns true if given move can be played. */
325 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
326 static bool board_is_valid_move(struct board *b, struct move *m);
327 /* Returns true if ko was just taken. */
328 static bool board_playing_ko_threat(struct board *b);
329 /* Returns 0 or ID of neighboring group in atari. */
330 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
331 /* Returns true if the move is not obvious self-atari. */
332 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
334 /* Determine number of stones in a group, up to @max stones. */
335 static int group_stone_count(struct board *b, group_t group, int max);
337 /* Adjust symmetry information as if given coordinate has been played. */
338 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
339 /* Check if coordinates are within symmetry base. (If false, they can
340 * be derived from the base.) */
341 static bool board_coord_in_symmetry(struct board *b, coord_t c);
343 /* Returns true if given coordinate has all neighbors of given color or the edge. */
344 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
345 /* Returns true if given coordinate could be a false eye; this check makes
346 * sense only if you already know the coordinate is_eyelike(). */
347 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
348 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
349 * at least tries to). */
350 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
351 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
352 enum stone board_get_one_point_eye(struct board *board, coord_t c);
354 /* board_official_score() is the scoring method for yielding score suitable
355 * for external presentation. For fast scoring of entirely filled boards
356 * (e.g. playouts), use board_fast_score(). */
357 /* Positive: W wins */
358 /* Compare number of stones + 1pt eyes. */
359 floating_t board_fast_score(struct board *board);
360 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
361 struct move_queue;
362 floating_t board_official_score(struct board *board, struct move_queue *mq);
364 /** Iterators */
366 #define foreach_point(board_) \
367 do { \
368 coord_t c = 0; \
369 for (; c < board_size(board_) * board_size(board_); c++)
370 #define foreach_point_and_pass(board_) \
371 do { \
372 coord_t c = pass; \
373 for (; c < board_size(board_) * board_size(board_); c++)
374 #define foreach_point_end \
375 } while (0)
377 #define foreach_free_point(board_) \
378 do { \
379 int fmax__ = (board_)->flen; \
380 for (int f__ = 0; f__ < fmax__; f__++) { \
381 coord_t c = (board_)->f[f__];
382 #define foreach_free_point_end \
384 } while (0)
386 #define foreach_in_group(board_, group_) \
387 do { \
388 struct board *board__ = board_; \
389 coord_t c = group_base(group_); \
390 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
391 do {
392 #define foreach_in_group_end \
393 c = c2; c2 = groupnext_at(board__, c2); \
394 } while (c != 0); \
395 } while (0)
397 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
398 * on S_OFFBOARD coordinates. */
399 #define foreach_neighbor(board_, coord_, loop_body) \
400 do { \
401 struct board *board__ = board_; \
402 coord_t coord__ = coord_; \
403 coord_t c; \
404 c = coord__ - board_size(board__); do { loop_body } while (0); \
405 c = coord__ - 1; do { loop_body } while (0); \
406 c = coord__ + 1; do { loop_body } while (0); \
407 c = coord__ + board_size(board__); do { loop_body } while (0); \
408 } while (0)
410 #define foreach_8neighbor(board_, coord_) \
411 do { \
412 int fn__i; \
413 coord_t c = (coord_); \
414 for (fn__i = 0; fn__i < 8; fn__i++) { \
415 c += (board_)->nei8[fn__i];
416 #define foreach_8neighbor_end \
418 } while (0)
420 #define foreach_diag_neighbor(board_, coord_) \
421 do { \
422 int fn__i; \
423 coord_t c = (coord_); \
424 for (fn__i = 0; fn__i < 4; fn__i++) { \
425 c += (board_)->dnei[fn__i];
426 #define foreach_diag_neighbor_end \
428 } while (0)
431 static inline bool
432 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
434 return (neighbor_count_at(board, coord, eye_color)
435 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
438 static inline bool
439 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
441 if (board_at(board, coord) != S_NONE)
442 return false;
443 if (!board_is_eyelike(board, coord, stone_other(color)))
444 return true;
445 /* Play within {true,false} eye-ish formation */
446 if (board->ko.coord == coord && board->ko.color == color)
447 return false;
448 #ifdef BOARD_TRAITS
449 /* XXX: Disallows suicide. */
450 return trait_at(board, coord, color).cap > 0;
451 #else
452 int groups_in_atari = 0;
453 foreach_neighbor(board, coord, {
454 group_t g = group_at(board, c);
455 groups_in_atari += (board_group_info(board, g).libs == 1);
457 return !!groups_in_atari;
458 #endif
461 static inline bool
462 board_is_valid_move(struct board *board, struct move *m)
464 return board_is_valid_play(board, m->color, m->coord);
467 static inline bool
468 board_playing_ko_threat(struct board *b)
470 return !is_pass(b->ko.coord);
473 static inline group_t
474 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
476 #ifdef BOARD_TRAITS
477 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
478 #endif
479 foreach_neighbor(b, coord, {
480 group_t g = group_at(b, c);
481 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
482 return g;
483 /* We return first match. */
485 return 0;
488 static inline bool
489 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
491 /* number of free neighbors */
492 int libs = immediate_liberty_count(b, coord);
493 if (libs > 1)
494 return true;
496 #ifdef BOARD_TRAITS
497 /* number of capturable enemy groups */
498 if (trait_at(b, coord, color).cap > 0)
499 return true; // XXX: We don't account for snapback.
500 /* number of non-capturable friendly groups */
501 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
502 if (noncap_ours < 1)
503 return false;
504 /*#else see below */
505 #endif
507 /* ok, but we need to check if they don't have just two libs. */
508 coord_t onelib = -1;
509 foreach_neighbor(b, coord, {
510 #ifndef BOARD_TRAITS
511 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
512 return true; // can capture; no snapback check
513 #endif
514 if (board_at(b, c) != color) continue;
515 group_t g = group_at(b, c);
516 if (board_group_info(b, g).libs == 1) continue; // in atari
517 if (board_group_info(b, g).libs == 2) { // two liberties
518 if (libs > 0) return true; // we already have one real liberty
519 /* we might be connecting two 2-lib groups, which is ok;
520 * so remember the other liberty and just make sure it's
521 * not the same one */
522 if (onelib >= 0 && c != onelib) return true;
523 onelib = board_group_other_lib(b, g, c);
524 continue;
526 // many liberties
527 return true;
529 // no good support group
530 return false;
533 static inline int
534 group_stone_count(struct board *b, group_t group, int max)
536 int n = 0;
537 foreach_in_group(b, group) {
538 n++;
539 if (n >= max) return max;
540 } foreach_in_group_end;
541 return n;
544 static inline bool
545 board_coord_in_symmetry(struct board *b, coord_t c)
547 if (coord_y(c, b) < b->symmetry.y1 || coord_y(c, b) > b->symmetry.y2)
548 return false;
549 if (coord_x(c, b) < b->symmetry.x1 || coord_x(c, b) > b->symmetry.x2)
550 return false;
551 if (b->symmetry.d) {
552 int x = coord_x(c, b);
553 if (b->symmetry.type == SYM_DIAG_DOWN)
554 x = board_size(b) - 1 - x;
555 if (x > coord_y(c, b))
556 return false;
558 return true;
562 #endif