Autotest show: Color lines based on their status
[pachi.git] / board.h
blob11dc23f0d467d0b54d2b2c9ba309d727b5ca91ce
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;
17 struct fbook;
20 /* Maximum supported board size. (Without the S_OFFBOARD edges.) */
21 #define BOARD_MAX_SIZE 19
24 /* The board implementation has bunch of optional features.
25 * Turn them on below: */
27 #define WANT_BOARD_C // capturable groups queue
29 //#define BOARD_SIZE 9 // constant board size, allows better optimization
31 //#define BOARD_SPATHASH // incremental patternsp.h hashes
32 #define BOARD_SPATHASH_MAXD 3 // maximal diameter
34 #define BOARD_PAT3 // incremental 3x3 pattern codes
36 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
37 //#define BOARD_GAMMA 1 // incremental probability distribution; either defined with BOARD_TRAITS, or keeping just pat3 stuff with BOARD_PAT3
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.h 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 /* Whether it is SAFE to play here. This is essentially just
109 * cached result of board_safe_to_play(). (Of course the concept
110 * of "safety" is not perfect here, but it's the cheapest
111 * reasonable thing we can do.) */
112 bool safe:1;
113 /* Whether we need to re-compute this coordinate; used to
114 * weed out duplicates. Maintained only for S_BLACK. */
115 bool dirty:1;
119 /* You should treat this struct as read-only. Always call functions below if
120 * you want to change it. */
122 struct board {
123 int size; /* Including S_OFFBOARD margin - see below. */
124 int size2; /* size^2 */
125 int bits2; /* ceiling(log2(size2)) */
126 int captures[S_MAX];
127 float komi;
128 int handicap;
129 /* The ruleset is currently almost never taken into account;
130 * the board implementation is basically Chinese rules (handicap
131 * stones compensation) w/ suicide (or you can look at it as
132 * New Zealand w/o handi stones compensation), while the engine
133 * enforces no-suicide, making for real Chinese rules. */
134 enum {
135 RULES_CHINESE, /* default value */
136 RULES_AGA,
137 RULES_NEW_ZEALAND,
138 RULES_JAPANESE,
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 /* Whether we tried to add a hash twice; board_play*() can
151 * set this, but it will still carry out the move as well! */
152 bool superko_violation;
154 /* The following two structures are goban maps and are indexed by
155 * coord.pos. The map is surrounded by a one-point margin from
156 * S_OFFBOARD stones in order to speed up some internal loops.
157 * Some of the foreach iterators below might include these points;
158 * you need to handle them yourselves, if you need to. */
160 /* Stones played on the board */
161 enum stone *b; /* enum stone */
162 /* Group id the stones are part of; 0 == no group */
163 group_t *g;
164 /* Positions of next stones in the stone group; 0 == last stone */
165 coord_t *p;
166 /* Neighboring colors; numbers of neighbors of index color */
167 struct neighbor_colors *n;
168 /* Zobrist hash for each position */
169 hash_t *h;
170 #ifdef BOARD_SPATHASH
171 /* For spatial hashes, we use only 24 bits. */
172 /* [0] is d==1, we don't keep hash for d==0. */
173 /* We keep hashes for black-to-play ([][0]) and white-to-play
174 * ([][1], reversed stone colors since we match all patterns as
175 * black-to-play). */
176 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
177 #endif
178 #ifdef BOARD_PAT3
179 /* 3x3 pattern code for each position; see pattern3.h for encoding
180 * specification. The information is only valid for empty points. */
181 hash3_t *pat3;
182 #endif
183 #ifdef BOARD_TRAITS
184 /* Incrementally matched point traits information, black-to-play
185 * ([][0]) and white-to-play ([][1]). */
186 /* The information is only valid for empty points. */
187 struct btraits (*t)[2];
188 #endif
189 #ifdef BOARD_GAMMA
190 /* Relative probabilities of moves being played next, computed by
191 * multiplying gammas of the appropriate pattern features based on
192 * pat3 and traits (see pattern.h). The probability distribution
193 * is maintained over the full board grid. */
194 /* - Always invalid moves are guaranteed to have zero probability.
195 * - Self-eye-filling moves will always have zero probability.
196 * - Ko-prohibited moves might have non-zero probability.
197 * - FEAT_CONTIGUITY is not accounted for in the probability. */
198 struct probdist prob[2];
199 #endif
200 /* Cached information on x-y coordinates so that we avoid division. */
201 uint8_t (*coord)[2];
203 /* Group information - indexed by gid (which is coord of base group stone) */
204 struct group *gi;
206 /* Positions of free positions - queue (not map) */
207 /* Note that free position here is any valid move; including single-point eyes!
208 * However, pass is not included. */
209 coord_t *f; int flen;
211 #ifdef WANT_BOARD_C
212 /* Queue of capturable groups */
213 group_t *c; int clen;
214 #endif
216 #ifdef BOARD_TRAITS
217 /* Queue of positions that need their traits updated */
218 coord_t *tq; int tqlen;
219 #endif
221 /* Symmetry information */
222 struct board_symmetry symmetry;
224 /* Last ko played on the board. */
225 struct move last_ko;
226 int last_ko_age;
228 /* Basic ko check */
229 struct move ko;
231 /* Engine-specific state; persistent through board development,
232 * is reset only at clear_board. */
233 void *es;
235 /* Playout-specific state; persistent through board development,
236 * but its lifetime is maintained in play_random_game(); it should
237 * not be set outside of it. */
238 void *ps;
240 #ifdef BOARD_GAMMA
241 /* Gamma values for probability distribution; user must setup
242 * this pointer before any move is played, using board_gamma_set(). */
243 struct features_gamma *gamma;
244 /* Whether to compute the 'safe' trait using board_safe_to_play()
245 * (false) or is_bad_selfatari() (true, much slower). */
246 bool precise_selfatari;
247 #endif
250 /* --- PRIVATE DATA --- */
252 /* For superko check: */
254 /* Board "history" - hashes encountered. Size of the hash should be
255 * >> board_size^2. */
256 #define history_hash_bits 12
257 #define history_hash_mask ((1 << history_hash_bits) - 1)
258 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
259 #define history_hash_next(i) ((i + 1) & history_hash_mask)
260 hash_t history_hash[1 << history_hash_bits];
261 /* Hash of current board position. */
262 hash_t hash;
263 /* Hash of current board position quadrants. */
264 hash_t qhash[4];
267 #ifdef BOARD_SIZE
268 /* Avoid unused variable warnings */
269 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
270 #define board_size2(b_) (board_size(b_) * board_size(b_))
271 #else
272 #define board_size(b_) ((b_)->size)
273 #define board_size2(b_) ((b_)->size2)
274 #endif
276 #if BOARD_SIZE == 19
277 # define board_bits2(b_) 9
278 #elif BOARD_SIZE == 13
279 # define board_bits2(b_) 8
280 #elif BOARD_SIZE == 9
281 # define board_bits2(b_) 7
282 #else
283 # define board_bits2(b_) ((b_)->bits2)
284 #endif
286 #define board_at(b_, c) ((b_)->b[c])
287 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
289 #define group_at(b_, c) ((b_)->g[c])
290 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
292 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
293 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
294 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
295 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
296 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
297 #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))
299 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
301 #define groupnext_at(b_, c) ((b_)->p[c])
302 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
304 #define group_base(g_) (g_)
305 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
306 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
307 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
308 /* board_group_other_lib() makes sense only for groups with two liberties. */
309 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
311 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
313 struct board *board_init(char *fbookfile);
314 struct board *board_copy(struct board *board2, struct board *board1);
315 void board_done_noalloc(struct board *board);
316 void board_done(struct board *board);
317 /* size here is without the S_OFFBOARD margin. */
318 void board_resize(struct board *board, int size);
319 void board_clear(struct board *board);
321 struct FILE;
322 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
323 void board_print(struct board *board, FILE *f);
324 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
326 /* Place given handicap on the board; coordinates are printed to f. */
327 void board_handicap(struct board *board, int stones, FILE *f);
329 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
330 int board_play(struct board *board, struct move *m);
331 /* Like above, but plays random move; the move coordinate is recorded
332 * to *coord. This method will never fill your own eye. pass is played
333 * when no move can be played. You can impose extra restrictions if you
334 * supply your own permit function; the permit function can also modify
335 * the move coordinate to redirect the move elsewhere. */
336 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
337 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
339 /* Returns true if given move can be played. */
340 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
341 static bool board_is_valid_move(struct board *b, struct move *m);
342 /* Returns true if ko was just taken. */
343 static bool board_playing_ko_threat(struct board *b);
344 /* Returns 0 or ID of neighboring group in atari. */
345 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
346 /* Returns true if the move is not obvious self-atari. */
347 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
349 /* Adjust symmetry information as if given coordinate has been played. */
350 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
351 /* Associate a set of feature gamma values (for pd building) with the board. */
352 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
353 /* Force re-compute of a probability distribution item. */
354 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
356 /* Returns true if given coordinate has all neighbors of given color or the edge. */
357 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
358 /* Returns true if given coordinate could be a false eye; this check makes
359 * sense only if you already know the coordinate is_eyelike(). */
360 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
361 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
362 * at least tries to). */
363 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
364 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
365 enum stone board_get_one_point_eye(struct board *board, coord_t c);
367 /* board_official_score() is the scoring method for yielding score suitable
368 * for external presentation. For fast scoring of entirely filled boards
369 * (e.g. playouts), use board_fast_score(). */
370 /* Positive: W wins */
371 /* Compare number of stones + 1pt eyes. */
372 float board_fast_score(struct board *board);
373 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
374 struct move_queue;
375 float board_official_score(struct board *board, struct move_queue *mq);
377 /** Iterators */
379 #define foreach_point(board_) \
380 do { \
381 coord_t c = 0; \
382 for (; c < board_size(board_) * board_size(board_); c++)
383 #define foreach_point_and_pass(board_) \
384 do { \
385 coord_t c = pass; \
386 for (; c < board_size(board_) * board_size(board_); c++)
387 #define foreach_point_end \
388 } while (0)
390 #define foreach_free_point(board_) \
391 do { \
392 int fmax__ = (board_)->flen; \
393 for (int f__ = 0; f__ < fmax__; f__++) { \
394 coord_t c = (board_)->f[f__];
395 #define foreach_free_point_end \
397 } while (0)
399 #define foreach_in_group(board_, group_) \
400 do { \
401 struct board *board__ = board_; \
402 coord_t c = group_base(group_); \
403 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
404 do {
405 #define foreach_in_group_end \
406 c = c2; c2 = groupnext_at(board__, c2); \
407 } while (c != 0); \
408 } while (0)
410 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
411 * on S_OFFBOARD coordinates. */
412 #define foreach_neighbor(board_, coord_, loop_body) \
413 do { \
414 struct board *board__ = board_; \
415 coord_t coord__ = coord_; \
416 coord_t c; \
417 c = coord__ - board_size(board__); do { loop_body } while (0); \
418 c = coord__ - 1; do { loop_body } while (0); \
419 c = coord__ + 1; do { loop_body } while (0); \
420 c = coord__ + board_size(board__); do { loop_body } while (0); \
421 } while (0)
423 #define foreach_8neighbor(board_, coord_) \
424 do { \
425 int fn__i; \
426 coord_t c = (coord_); \
427 for (fn__i = 0; fn__i < 8; fn__i++) { \
428 c += (board_)->nei8[fn__i];
429 #define foreach_8neighbor_end \
431 } while (0)
433 #define foreach_diag_neighbor(board_, coord_) \
434 do { \
435 int fn__i; \
436 coord_t c = (coord_); \
437 for (fn__i = 0; fn__i < 4; fn__i++) { \
438 c += (board_)->dnei[fn__i];
439 #define foreach_diag_neighbor_end \
441 } while (0)
444 static inline bool
445 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
447 return (neighbor_count_at(board, coord, eye_color)
448 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
451 static inline bool
452 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
454 if (board_at(board, coord) != S_NONE)
455 return false;
456 if (!board_is_eyelike(board, coord, stone_other(color)))
457 return true;
458 /* Play within {true,false} eye-ish formation */
459 if (board->ko.coord == coord && board->ko.color == color)
460 return false;
461 #ifdef BOARD_TRAITS
462 /* XXX: Disallows suicide. */
463 return trait_at(board, coord, color).cap > 0;
464 #else
465 int groups_in_atari = 0;
466 foreach_neighbor(board, coord, {
467 group_t g = group_at(board, c);
468 groups_in_atari += (board_group_info(board, g).libs == 1);
470 return !!groups_in_atari;
471 #endif
474 static inline bool
475 board_is_valid_move(struct board *board, struct move *m)
477 return board_is_valid_play(board, m->color, m->coord);
480 static inline bool
481 board_playing_ko_threat(struct board *b)
483 return !is_pass(b->ko.coord);
486 static inline group_t
487 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
489 #ifdef BOARD_TRAITS
490 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
491 #endif
492 foreach_neighbor(b, coord, {
493 group_t g = group_at(b, c);
494 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
495 return g;
496 /* We return first match. */
498 return 0;
501 static inline bool
502 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
504 /* number of free neighbors */
505 int libs = immediate_liberty_count(b, coord);
506 if (libs > 1)
507 return true;
509 #ifdef BOARD_TRAITS
510 /* number of capturable enemy groups */
511 if (trait_at(b, coord, color).cap > 0)
512 return true; // XXX: We don't account for snapback.
513 /* number of non-capturable friendly groups */
514 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
515 if (noncap_ours < 1)
516 return false;
517 /*#else see below */
518 #endif
520 /* ok, but we need to check if they don't have just two libs. */
521 coord_t onelib = -1;
522 foreach_neighbor(b, coord, {
523 #ifndef BOARD_TRAITS
524 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
525 return true; // can capture; no snapback check
526 #endif
527 if (board_at(b, c) != color) continue;
528 group_t g = group_at(b, c);
529 if (board_group_info(b, g).libs == 1) continue; // in atari
530 if (board_group_info(b, g).libs == 2) { // two liberties
531 if (libs > 0) return true; // we already have one real liberty
532 /* we might be connecting two 2-lib groups, which is ok;
533 * so remember the other liberty and just make sure it's
534 * not the same one */
535 if (onelib >= 0 && c != onelib) return true;
536 onelib = board_group_other_lib(b, g, c);
537 continue;
539 // many liberties
540 return true;
542 // no good support group
543 return false;
546 #endif