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