Elo: Add EAV_BEST support
[pachi.git] / board.h
blobb1af743556185ac14d988c6609514e96d3104044
1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
3 #include "probdist.h"
5 #ifndef ZZGO_BOARD_H
6 #define ZZGO_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 features_gamma;
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_GAMMA 1 // incremental probability distribution (requires BOARD_TRAITS, BOARD_PAT3)
39 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
40 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
43 /* Some engines might normalize their reading and skip symmetrical
44 * moves. We will tell them how can they do it. */
45 struct board_symmetry {
46 /* Playground is in this rectangle. */
47 int x1, x2, y1, y2;
48 /* d == 0: Full rectangle
49 * d == 1: Top triangle */
50 int d;
51 /* General symmetry type. */
52 /* Note that the above is redundant to this, but just provided
53 * for easier usage. */
54 enum {
55 SYM_FULL,
56 SYM_DIAG_UP,
57 SYM_DIAG_DOWN,
58 SYM_HORIZ,
59 SYM_VERT,
60 SYM_NONE
61 } type;
65 typedef uint64_t hash_t;
66 #define PRIhash PRIx64
68 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
69 * a dependency hell. */
70 typedef uint16_t hash3_t; // 3x3 pattern hash
73 /* Note that "group" is only chain of stones that is solidly
74 * connected for us. */
75 typedef coord_t group_t;
77 struct group {
78 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
79 * don't care. */
80 /* _Combination_ of these two values can make some difference
81 * in performance - fine-tune. */
82 #define GROUP_KEEP_LIBS 10
83 // refill lib[] only when we hit this; this must be at least 2!
84 // Moggy requires at least 3 - see below for semantic impact.
85 #define GROUP_REFILL_LIBS 5
86 coord_t lib[GROUP_KEEP_LIBS];
87 /* libs is only LOWER BOUND for the number of real liberties!!!
88 * It denotes only number of items in lib[], thus you can rely
89 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
90 int libs;
93 struct neighbor_colors {
94 char colors[S_MAX];
98 /* Point traits bitmap; we update this information incrementally,
99 * it can be used e.g. for fast pattern.h features matching. */
100 struct btraits {
101 /* Number of neighbors we can capture. 0=this move is
102 * not capturing, 1..4=this many neighbors we can capture
103 * (can be multiple neighbors of same group). */
104 unsigned cap:3;
105 /* Number of 1-stone neighbors we can capture. */
106 unsigned cap1:3;
107 /* Whether it is SAFE to play here. This is essentially just
108 * cached result of board_safe_to_play(). (Of course the concept
109 * of "safety" is not perfect here, but it's the cheapest
110 * reasonable thing we can do.) */
111 bool safe:1;
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 float 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;
140 /* Iterator offsets for foreach_neighbor*() */
141 int nei8[8], dnei[4];
143 int moves;
144 struct move last_move;
145 struct move last_move2; /* second-to-last move */
146 /* Whether we tried to add a hash twice; board_play*() can
147 * set this, but it will still carry out the move as well! */
148 bool superko_violation;
150 /* The following two structures are goban maps and are indexed by
151 * coord.pos. The map is surrounded by a one-point margin from
152 * S_OFFBOARD stones in order to speed up some internal loops.
153 * Some of the foreach iterators below might include these points;
154 * you need to handle them yourselves, if you need to. */
156 /* Stones played on the board */
157 enum stone *b; /* enum stone */
158 /* Group id the stones are part of; 0 == no group */
159 group_t *g;
160 /* Positions of next stones in the stone group; 0 == last stone */
161 coord_t *p;
162 /* Neighboring colors; numbers of neighbors of index color */
163 struct neighbor_colors *n;
164 /* Zobrist hash for each position */
165 hash_t *h;
166 #ifdef BOARD_SPATHASH
167 /* For spatial hashes, we use only 24 bits. */
168 /* [0] is d==1, we don't keep hash for d==0. */
169 /* We keep hashes for black-to-play ([][0]) and white-to-play
170 * ([][1], reversed stone colors since we match all patterns as
171 * black-to-play). */
172 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
173 #endif
174 #ifdef BOARD_PAT3
175 /* 3x3 pattern code for each position; see pattern3.h for encoding
176 * specification. The information is only valid for empty points. */
177 hash3_t *pat3;
178 #endif
179 #ifdef BOARD_TRAITS
180 /* Incrementally matched point traits information, black-to-play
181 * ([][0]) and white-to-play ([][1]). */
182 /* The information is only valid for empty points. */
183 struct btraits (*t)[2];
184 #endif
185 #ifdef BOARD_GAMMA
186 /* Relative probabilities of moves being played next, computed by
187 * multiplying gammas of the appropriate pattern features based on
188 * pat3 and traits (see pattern.h). The probability distribution
189 * is maintained over the full board grid. */
190 /* - Always invalid moves are guaranteed to have zero probability.
191 * - Self-eye-filling moves will always have zero probability.
192 * - Ko-prohibited moves might have non-zero probability.
193 * - FEAT_CONTIGUITY is not accounted for in the probability. */
194 struct probdist prob[2];
195 #endif
196 /* Cached information on x-y coordinates so that we avoid division. */
197 uint8_t (*coord)[2];
199 /* Group information - indexed by gid (which is coord of base group stone) */
200 struct group *gi;
202 /* Positions of free positions - queue (not map) */
203 /* Note that free position here is any valid move; including single-point eyes!
204 * However, pass is not included. */
205 coord_t *f; int flen;
207 #ifdef WANT_BOARD_C
208 /* Queue of capturable groups */
209 group_t *c; int clen;
210 #endif
212 #ifdef BOARD_TRAITS
213 /* Queue of positions that need their traits updated */
214 coord_t *tq; int tqlen;
215 #endif
217 /* Symmetry information */
218 struct board_symmetry symmetry;
220 /* Last ko played on the board. */
221 struct move last_ko;
222 int last_ko_age;
224 /* Basic ko check */
225 struct move ko;
227 /* Engine-specific state; persistent through board development,
228 * is reset only at clear_board. */
229 void *es;
231 /* Playout-specific state; persistent through board development,
232 * but its lifetime is maintained in play_random_game(); it should
233 * not be set outside of it. */
234 void *ps;
236 #ifdef BOARD_GAMMA
237 /* Gamma values for probability distribution; user must setup
238 * this pointer before any move is played, using board_gamma_set(). */
239 struct features_gamma *gamma;
240 /* Whether to compute the 'safe' trait using board_safe_to_play()
241 * (false) or is_bad_selfatari() (true, much slower). */
242 bool precise_selfatari;
243 #endif
246 /* --- PRIVATE DATA --- */
248 /* For superko check: */
250 /* Board "history" - hashes encountered. Size of the hash should be
251 * >> board_size^2. */
252 #define history_hash_bits 12
253 #define history_hash_mask ((1 << history_hash_bits) - 1)
254 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
255 #define history_hash_next(i) ((i + 1) & history_hash_mask)
256 hash_t history_hash[1 << history_hash_bits];
257 /* Hash of current board position. */
258 hash_t hash;
261 #ifdef BOARD_SIZE
262 /* Avoid unused variable warnings */
263 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
264 #define board_size2(b_) (board_size(b_) * board_size(b_))
265 #else
266 #define board_size(b_) ((b_)->size)
267 #define board_size2(b_) ((b_)->size2)
268 #endif
270 #if BOARD_SIZE == 19
271 # define board_bits2(b_) 9
272 #elif BOARD_SIZE == 13
273 # define board_bits2(b_) 8
274 #elif BOARD_SIZE == 9
275 # define board_bits2(b_) 7
276 #else
277 # define board_bits2(b_) ((b_)->bits2)
278 #endif
280 #define board_at(b_, c) ((b_)->b[c])
281 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
283 #define group_at(b_, c) ((b_)->g[c])
284 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
286 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
287 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
288 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
289 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
290 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
291 #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))
293 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
295 #define groupnext_at(b_, c) ((b_)->p[c])
296 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
298 #define group_base(g_) (g_)
299 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
300 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
301 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
302 /* board_group_other_lib() makes sense only for groups with two liberties. */
303 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
305 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
307 struct board *board_init(void);
308 struct board *board_copy(struct board *board2, struct board *board1);
309 void board_done_noalloc(struct board *board);
310 void board_done(struct board *board);
311 /* size here is without the S_OFFBOARD margin. */
312 void board_resize(struct board *board, int size);
313 void board_clear(struct board *board);
315 struct FILE;
316 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
317 void board_print(struct board *board, FILE *f);
318 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
320 /* Place given handicap on the board; coordinates are printed to f. */
321 void board_handicap(struct board *board, int stones, FILE *f);
323 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
324 int board_play(struct board *board, struct move *m);
325 /* Like above, but plays random move; the move coordinate is recorded
326 * to *coord. This method will never fill your own eye. pass is played
327 * when no move can be played. You can impose extra restrictions if you
328 * supply your own permit function; the permit function can also modify
329 * the move coordinate to redirect the move elsewhere. */
330 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
331 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
333 /* Returns true if given move can be played. */
334 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
335 static bool board_is_valid_move(struct board *b, struct move *m);
336 /* Returns true if ko was just taken. */
337 static bool board_playing_ko_threat(struct board *b);
338 /* Returns 0 or ID of neighboring group in atari. */
339 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
340 /* Returns true if the move is not obvious self-atari. */
341 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
343 /* Adjust symmetry information as if given coordinate has been played. */
344 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
345 /* Associate a set of feature gamma values (for pd building) with the board. */
346 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
347 /* Force re-compute of a probability distribution item. */
348 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
350 /* Returns true if given coordinate has all neighbors of given color or the edge. */
351 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
352 /* Returns true if given coordinate could be a false eye; this check makes
353 * sense only if you already know the coordinate is_eyelike(). */
354 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
355 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
356 * at least tries to). */
357 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
358 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
359 enum stone board_get_one_point_eye(struct board *board, coord_t c);
361 /* board_official_score() is the scoring method for yielding score suitable
362 * for external presentation. For fast scoring of entirely filled boards
363 * (e.g. playouts), use board_fast_score(). */
364 /* Positive: W wins */
365 /* Compare number of stones + 1pt eyes. */
366 float board_fast_score(struct board *board);
367 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
368 struct move_queue;
369 float board_official_score(struct board *board, struct move_queue *mq);
371 /** Iterators */
373 #define foreach_point(board_) \
374 do { \
375 coord_t c = 0; \
376 for (; c < board_size(board_) * board_size(board_); c++)
377 #define foreach_point_and_pass(board_) \
378 do { \
379 coord_t c = pass; \
380 for (; c < board_size(board_) * board_size(board_); c++)
381 #define foreach_point_end \
382 } while (0)
384 #define foreach_free_point(board_) \
385 do { \
386 int fmax__ = (board_)->flen; \
387 for (int f__ = 0; f__ < fmax__; f__++) { \
388 coord_t c = (board_)->f[f__];
389 #define foreach_free_point_end \
391 } while (0)
393 #define foreach_in_group(board_, group_) \
394 do { \
395 struct board *board__ = board_; \
396 coord_t c = group_base(group_); \
397 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
398 do {
399 #define foreach_in_group_end \
400 c = c2; c2 = groupnext_at(board__, c2); \
401 } while (c != 0); \
402 } while (0)
404 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
405 * on S_OFFBOARD coordinates. */
406 #define foreach_neighbor(board_, coord_, loop_body) \
407 do { \
408 struct board *board__ = board_; \
409 coord_t coord__ = coord_; \
410 coord_t c; \
411 c = coord__ - 1; do { loop_body } while (0); \
412 c = coord__ - board_size(board__); do { loop_body } while (0); \
413 c = coord__ + 1; do { loop_body } while (0); \
414 c = coord__ + board_size(board__); do { loop_body } while (0); \
415 } while (0)
417 #define foreach_8neighbor(board_, coord_) \
418 do { \
419 int fn__i; \
420 coord_t c = (coord_); \
421 for (fn__i = 0; fn__i < 8; fn__i++) { \
422 c += (board_)->nei8[fn__i];
423 #define foreach_8neighbor_end \
425 } while (0)
427 #define foreach_diag_neighbor(board_, coord_) \
428 do { \
429 int fn__i; \
430 coord_t c = (coord_); \
431 for (fn__i = 0; fn__i < 4; fn__i++) { \
432 c += (board_)->dnei[fn__i];
433 #define foreach_diag_neighbor_end \
435 } while (0)
438 static inline bool
439 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
441 return (neighbor_count_at(board, coord, eye_color)
442 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
445 static inline bool
446 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
448 if (board_at(board, coord) != S_NONE)
449 return false;
450 if (!board_is_eyelike(board, coord, stone_other(color)))
451 return true;
452 /* Play within {true,false} eye-ish formation */
453 if (board->ko.coord == coord && board->ko.color == color)
454 return false;
455 #ifdef BOARD_TRAITS
456 /* XXX: Disallows suicide. */
457 return trait_at(board, coord, color).cap > 0;
458 #else
459 int groups_in_atari = 0;
460 foreach_neighbor(board, coord, {
461 group_t g = group_at(board, c);
462 groups_in_atari += (board_group_info(board, g).libs == 1);
464 return !!groups_in_atari;
465 #endif
468 static inline bool
469 board_is_valid_move(struct board *board, struct move *m)
471 return board_is_valid_play(board, m->color, m->coord);
474 static inline bool
475 board_playing_ko_threat(struct board *b)
477 return !is_pass(b->ko.coord);
480 static inline group_t
481 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
483 #ifdef BOARD_TRAITS
484 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
485 #endif
486 foreach_neighbor(b, coord, {
487 group_t g = group_at(b, c);
488 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
489 return g;
490 /* We return first match. */
492 return 0;
495 static inline bool
496 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
498 /* number of free neighbors */
499 int libs = immediate_liberty_count(b, coord);
500 if (libs > 1)
501 return true;
503 #ifdef BOARD_TRAITS
504 /* number of capturable enemy groups */
505 if (trait_at(b, coord, color).cap > 0)
506 return true; // XXX: We don't account for snapback.
507 /* number of non-capturable friendly groups */
508 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
509 if (noncap_ours < 1)
510 return false;
511 /*#else see below */
512 #endif
514 /* ok, but we need to check if they don't have just two libs. */
515 coord_t onelib = -1;
516 foreach_neighbor(b, coord, {
517 #ifndef BOARD_TRAITS
518 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
519 return true; // can capture; no snapback check
520 #endif
521 if (board_at(b, c) != color) continue;
522 group_t g = group_at(b, c);
523 if (board_group_info(b, g).libs == 1) continue; // in atari
524 if (board_group_info(b, g).libs == 2) { // two liberties
525 if (libs > 0) return true; // we already have one real liberty
526 /* we might be connecting two 2-lib groups, which is ok;
527 * so remember the other liberty and just make sure it's
528 * not the same one */
529 if (onelib >= 0 && c != onelib) return true;
530 onelib = board_group_other_lib(b, g, c);
531 continue;
533 // many liberties
534 return true;
536 // no good support group
537 return false;
540 #endif