UCT dynkomi: Clean up helper routine definitions
[pachi/derm.git] / board.h
blob141ee754e56b233571e1b573a7b37b196887e572
1 #ifndef ZZGO_BOARD_H
2 #define ZZGO_BOARD_H
4 #include <inttypes.h>
5 #include <stdbool.h>
6 #include <stdint.h>
8 #include "stone.h"
9 #include "move.h"
10 #include "probdist.h"
11 #include "util.h"
13 struct features_gamma;
16 /* The board implementation has bunch of optional features.
17 * Turn them on below: */
19 #define WANT_BOARD_C // capturable groups queue
21 //#define BOARD_SIZE 9 // constant board size, allows better optimization
23 //#define BOARD_SPATHASH // incremental patternsp.h hashes
24 #define BOARD_SPATHASH_MAXD 3 // maximal diameter
26 #define BOARD_PAT3 // incremental 3x3 pattern codes
28 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
29 //#define BOARD_GAMMA 1 // incremental probability distribution (requires BOARD_TRAITS, BOARD_PAT3)
32 /* Allow board_play_random_move() to return pass even when
33 * there are other moves available. */
34 extern bool random_pass;
37 /* Some engines might normalize their reading and skip symmetrical
38 * moves. We will tell them how can they do it. */
39 struct board_symmetry {
40 /* Playground is in this rectangle. */
41 int x1, x2, y1, y2;
42 /* d == 0: Full rectangle
43 * d == 1: Top triangle */
44 int d;
45 /* General symmetry type. */
46 /* Note that the above is redundant to this, but just provided
47 * for easier usage. */
48 enum {
49 SYM_FULL,
50 SYM_DIAG_UP,
51 SYM_DIAG_DOWN,
52 SYM_HORIZ,
53 SYM_VERT,
54 SYM_NONE
55 } type;
59 typedef uint64_t hash_t;
60 #define PRIhash PRIx64
63 /* Note that "group" is only chain of stones that is solidly
64 * connected for us. */
65 typedef coord_t group_t;
67 struct group {
68 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
69 * don't care. */
70 /* _Combination_ of these two values can make some difference
71 * in performance - fine-tune. */
72 #define GROUP_KEEP_LIBS 10
73 // refill lib[] only when we hit this; this must be at least 2!
74 // Moggy requires at least 3 - see below for semantic impact.
75 #define GROUP_REFILL_LIBS 5
76 coord_t lib[GROUP_KEEP_LIBS];
77 /* libs is only LOWER BOUND for the number of real liberties!!!
78 * It denotes only number of items in lib[], thus you can rely
79 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
80 int libs;
83 struct neighbor_colors {
84 char colors[S_MAX];
88 /* Point traits bitmap; we update this information incrementally,
89 * it can be used e.g. for fast pattern.h features matching. */
90 struct btraits {
91 /* Number of neighbors we can capture. 0=this move is
92 * not capturing, 1..4=this many neighbors we can capture
93 * (can be multiple neighbors of same group). */
94 unsigned cap:3;
95 /* Whether it is SAFE to play here. This is essentially just
96 * cached result of board_safe_to_play(). (Of course the concept
97 * of "safety" is not perfect here, but it's the cheapest
98 * reasonable thing we can do.) */
99 bool safe:1;
100 /* Whether we need to re-compute this coordinate; used to
101 * weed out duplicates. Maintained only for S_BLACK. */
102 bool dirty:1;
106 /* You should treat this struct as read-only. Always call functions below if
107 * you want to change it. */
109 struct board {
110 int size; /* Including S_OFFBOARD margin - see below. */
111 int size2; /* size^2 */
112 int captures[S_MAX];
113 float komi;
114 int handicap;
115 enum {
116 RULES_AGA,
117 RULES_CHINESE,
118 RULES_NEW_ZEALAND,
119 RULES_JAPANESE,
120 } rules;
122 /* Iterator offsets for foreach_neighbor*() */
123 int nei8[8], dnei[4];
125 int moves;
126 struct move last_move;
127 struct move last_move2; /* second-to-last move */
128 /* Whether we tried to add a hash twice; board_play*() can
129 * set this, but it will still carry out the move as well! */
130 bool superko_violation;
132 /* The following two structures are goban maps and are indexed by
133 * coord.pos. The map is surrounded by a one-point margin from
134 * S_OFFBOARD stones in order to speed up some internal loops.
135 * Some of the foreach iterators below might include these points;
136 * you need to handle them yourselves, if you need to. */
138 /* Stones played on the board */
139 enum stone *b; /* enum stone */
140 /* Group id the stones are part of; 0 == no group */
141 group_t *g;
142 /* Positions of next stones in the stone group; 0 == last stone */
143 coord_t *p;
144 /* Neighboring colors; numbers of neighbors of index color */
145 struct neighbor_colors *n;
146 /* Zobrist hash for each position */
147 hash_t *h;
148 #ifdef BOARD_SPATHASH
149 /* For spatial hashes, we use only 24 bits. */
150 /* [0] is d==1, we don't keep hash for d==0. */
151 /* We keep hashes for black-to-play ([][0]) and white-to-play
152 * ([][1], reversed stone colors since we match all patterns as
153 * black-to-play). */
154 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
155 #endif
156 #ifdef BOARD_PAT3
157 /* 3x3 pattern code for each position; see pattern3.h for encoding
158 * specification. The information is only valid for empty points. */
159 uint16_t *pat3;
160 #endif
161 #ifdef BOARD_TRAITS
162 /* Incrementally matched point traits information, black-to-play
163 * ([][0]) and white-to-play ([][1]). */
164 /* The information is only valid for empty points. */
165 struct btraits (*t)[2];
166 #endif
167 #ifdef BOARD_GAMMA
168 /* Relative probabilities of moves being played next, computed by
169 * multiplying gammas of the appropriate pattern features based on
170 * pat3 and traits (see pattern.h). The probability distribution
171 * is maintained over the full board grid. */
172 /* - Always invalid moves are guaranteed to have zero probability.
173 * - Self-eye-filling moves will always have zero probability.
174 * - Ko-prohibited moves might have non-zero probability.
175 * - FEAT_CONTIGUITY is not accounted for in the probability. */
176 struct probdist prob[2];
177 #endif
179 /* Group information - indexed by gid (which is coord of base group stone) */
180 struct group *gi;
182 /* Positions of free positions - queue (not map) */
183 /* Note that free position here is any valid move; including single-point eyes! */
184 coord_t *f; int flen;
186 #ifdef WANT_BOARD_C
187 /* Queue of capturable groups */
188 group_t *c; int clen;
189 #endif
191 #ifdef BOARD_TRAITS
192 /* Queue of positions that need their traits updated */
193 coord_t *tq; int tqlen;
194 #endif
196 /* Symmetry information */
197 struct board_symmetry symmetry;
199 /* Last ko played on the board. */
200 struct move last_ko;
201 int last_ko_age;
203 /* Basic ko check */
204 struct move ko;
206 /* Engine-specific state; persistent through board development,
207 * is reset only at clear_board. */
208 void *es;
210 /* Playout-specific state; persistent through board development,
211 * but its lifetime is maintained in play_random_game(); it should
212 * not be set outside of it. */
213 void *ps;
215 #ifdef BOARD_GAMMA
216 /* Gamma values for probability distribution; user must setup
217 * this pointer before any move is played, using board_gamma_set(). */
218 struct features_gamma *gamma;
219 /* Whether to compute the 'safe' trait using board_safe_to_play()
220 * (false) or is_bad_selfatari() (true, much slower). */
221 bool precise_selfatari;
222 #endif
225 /* --- PRIVATE DATA --- */
227 /* For superko check: */
229 /* Board "history" - hashes encountered. Size of the hash should be
230 * >> board_size^2. */
231 #define history_hash_bits 12
232 #define history_hash_mask ((1 << history_hash_bits) - 1)
233 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
234 #define history_hash_next(i) ((i + 1) & history_hash_mask)
235 hash_t history_hash[1 << history_hash_bits];
236 /* Hash of current board position. */
237 hash_t hash;
240 #ifdef BOARD_SIZE
241 /* Avoid unused variable warnings */
242 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
243 #define board_size2(b_) (board_size(b_) * board_size(b_))
244 #else
245 #define board_size(b_) ((b_)->size)
246 #define board_size2(b_) ((b_)->size2)
247 #endif
249 #define board_at(b_, c) ((b_)->b[coord_raw(c)])
250 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
252 #define group_at(b_, c) ((b_)->g[coord_raw(c)])
253 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
255 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
256 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord_raw(coord)].colors[(enum stone) color])
257 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
258 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
259 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
260 #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))
262 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
264 #define groupnext_at(b_, c) ((b_)->p[coord_raw(c)])
265 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
267 #define group_base(g_) (g_)
268 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
269 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
270 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
272 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord_raw(coord)])
274 struct board *board_init(void);
275 struct board *board_copy(struct board *board2, struct board *board1);
276 void board_done_noalloc(struct board *board);
277 void board_done(struct board *board);
278 /* size here is without the S_OFFBOARD margin. */
279 void board_resize(struct board *board, int size);
280 void board_clear(struct board *board);
282 struct FILE;
283 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
284 void board_print(struct board *board, FILE *f);
285 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
287 /* Place given handicap on the board; coordinates are printed to f. */
288 void board_handicap(struct board *board, int stones, FILE *f);
290 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
291 int board_play(struct board *board, struct move *m);
292 /* Like above, but plays random move; the move coordinate is recorded
293 * to *coord. This method will never fill your own eye. pass is played
294 * when no move can be played. You can impose extra restrictions if you
295 * supply your own permit function. */
296 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
297 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
299 /* Returns true if given move can be played. */
300 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
301 static bool board_is_valid_move(struct board *b, struct move *m);
302 /* Returns true if ko was just taken. */
303 static bool board_playing_ko_threat(struct board *b);
304 /* Returns 0 or ID of neighboring group in atari. */
305 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
306 /* Returns true if the move is not obvious self-atari. */
307 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
309 /* Adjust symmetry information as if given coordinate has been played. */
310 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
311 /* Associate a set of feature gamma values (for pd building) with the board. */
312 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
313 /* Force re-compute of a probability distribution item. */
314 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
316 /* Returns true if given coordinate has all neighbors of given color or the edge. */
317 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
318 /* Returns true if given coordinate could be a false eye; this check makes
319 * sense only if you already know the coordinate is_eyelike(). */
320 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
321 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
322 * at least tries to). */
323 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
324 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
325 enum stone board_get_one_point_eye(struct board *board, coord_t c);
327 /* board_official_score() is the scoring method for yielding score suitable
328 * for external presentation. For fast scoring of entirely filled boards
329 * (e.g. playouts), use board_fast_score(). */
330 /* Positive: W wins */
331 /* Compare number of stones + 1pt eyes. */
332 float board_fast_score(struct board *board);
333 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
334 struct move_queue;
335 float board_official_score(struct board *board, struct move_queue *mq);
337 /** Iterators */
339 #define foreach_point(board_) \
340 do { \
341 coord_t c; coord_pos(c, 0, (board_)); \
342 for (; coord_raw(c) < board_size(board_) * board_size(board_); coord_raw(c)++)
343 #define foreach_point_and_pass(board_) \
344 do { \
345 coord_t c; coord_pos(c, -1, (board_)); \
346 for (; coord_raw(c) < board_size(board_) * board_size(board_); coord_raw(c)++)
347 #define foreach_point_end \
348 } while (0)
350 #define foreach_in_group(board_, group_) \
351 do { \
352 struct board *board__ = board_; \
353 coord_t c = group_base(group_); \
354 coord_t c2 = c; coord_raw(c2) = groupnext_at(board__, c2); \
355 do {
356 #define foreach_in_group_end \
357 c = c2; coord_raw(c2) = groupnext_at(board__, c2); \
358 } while (coord_raw(c) != 0); \
359 } while (0)
361 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
362 * on S_OFFBOARD coordinates. */
363 #define foreach_neighbor(board_, coord_, loop_body) \
364 do { \
365 struct board *board__ = board_; \
366 coord_t coord__ = coord_; \
367 coord_t c; \
368 coord_pos(c, coord_raw(coord__) - 1, (board__)); do { loop_body } while (0); \
369 coord_pos(c, coord_raw(coord__) - board_size(board__), (board__)); do { loop_body } while (0); \
370 coord_pos(c, coord_raw(coord__) + 1, (board__)); do { loop_body } while (0); \
371 coord_pos(c, coord_raw(coord__) + board_size(board__), (board__)); do { loop_body } while (0); \
372 } while (0)
374 #define foreach_8neighbor(board_, coord_) \
375 do { \
376 int fn__i; \
377 coord_t c = (coord_); \
378 for (fn__i = 0; fn__i < 8; fn__i++) { \
379 c += (board_)->nei8[fn__i];
380 #define foreach_8neighbor_end \
382 } while (0)
384 #define foreach_diag_neighbor(board_, coord_) \
385 do { \
386 int fn__i; \
387 coord_t c = (coord_); \
388 for (fn__i = 0; fn__i < 4; fn__i++) { \
389 c += (board_)->dnei[fn__i];
390 #define foreach_diag_neighbor_end \
392 } while (0)
395 static inline bool
396 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
398 return (neighbor_count_at(board, coord, eye_color)
399 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
402 static inline bool
403 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
405 if (board_at(board, coord) != S_NONE)
406 return false;
407 if (!board_is_eyelike(board, coord, stone_other(color)))
408 return true;
409 /* Play within {true,false} eye-ish formation */
410 if (board->ko.coord == coord && board->ko.color == color)
411 return false;
412 #ifdef BOARD_TRAITS
413 /* XXX: Disallows suicide. */
414 return trait_at(board, coord, color).cap > 0;
415 #else
416 int groups_in_atari = 0;
417 foreach_neighbor(board, coord, {
418 group_t g = group_at(board, c);
419 groups_in_atari += (board_group_info(board, g).libs == 1);
421 return !!groups_in_atari;
422 #endif
425 static inline bool
426 board_is_valid_move(struct board *board, struct move *m)
428 return board_is_valid_play(board, m->color, m->coord);
431 static inline bool
432 board_playing_ko_threat(struct board *b)
434 return !is_pass(b->ko.coord);
437 static inline group_t
438 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
440 #ifdef BOARD_TRAITS
441 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
442 #endif
443 foreach_neighbor(b, coord, {
444 group_t g = group_at(b, c);
445 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
446 return g;
447 /* We return first match. */
449 return 0;
452 static inline bool
453 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
455 /* number of free neighbors */
456 int libs = immediate_liberty_count(b, coord);
457 if (libs > 1)
458 return true;
460 #ifdef BOARD_TRAITS
461 /* number of capturable enemy groups */
462 if (trait_at(b, coord, color).cap > 0)
463 return true; // XXX: We don't account for snapback.
464 /* number of non-capturable friendly groups */
465 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
466 if (noncap_ours < 1)
467 return false;
468 /*#else see below */
469 #endif
471 /* ok, but we need to check if they don't have just two libs. */
472 coord_t onelib = -1;
473 foreach_neighbor(b, coord, {
474 #ifndef BOARD_TRAITS
475 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
476 return true; // can capture; no snapback check
477 #endif
478 if (board_at(b, c) != color) continue;
479 group_t g = group_at(b, c);
480 if (board_group_info(b, g).libs == 1) continue; // in atari
481 if (board_group_info(b, g).libs == 2) { // two liberties
482 if (libs > 0) return true; // we already have one real liberty
483 // get the other liberty
484 coord_t lib = board_group_info(b, g).lib[0];
485 if (lib == coord) lib = board_group_info(b, g).lib[0];
486 /* we might be connecting two 2-lib groups, which is ok;
487 * so remember the other liberty and just make sure it's
488 * not the same one */
489 if (onelib >= 0 && lib != onelib) return true;
490 onelib = lib;
491 continue;
493 // many liberties
494 return true;
496 // no good support group
497 return false;
500 #endif