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