Elo: Do not debug-print non-matcheable neighbors
[pachi.git] / board.h
blob1dc98fc6d0bd5a808ea4f54a631fade9bde12af6
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 /* The board implementation has bunch of optional features.
20 * Turn them on below: */
22 #define WANT_BOARD_C // capturable groups queue
24 //#define BOARD_SIZE 9 // constant board size, allows better optimization
26 //#define BOARD_SPATHASH // incremental patternsp.h hashes
27 #define BOARD_SPATHASH_MAXD 3 // maximal diameter
29 #define BOARD_PAT3 // incremental 3x3 pattern codes
31 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
32 //#define BOARD_GAMMA 1 // incremental probability distribution (requires BOARD_TRAITS, BOARD_PAT3)
35 /* Some engines might normalize their reading and skip symmetrical
36 * moves. We will tell them how can they do it. */
37 struct board_symmetry {
38 /* Playground is in this rectangle. */
39 int x1, x2, y1, y2;
40 /* d == 0: Full rectangle
41 * d == 1: Top triangle */
42 int d;
43 /* General symmetry type. */
44 /* Note that the above is redundant to this, but just provided
45 * for easier usage. */
46 enum {
47 SYM_FULL,
48 SYM_DIAG_UP,
49 SYM_DIAG_DOWN,
50 SYM_HORIZ,
51 SYM_VERT,
52 SYM_NONE
53 } type;
57 typedef uint64_t hash_t;
58 #define PRIhash PRIx64
60 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
61 * a dependency hell. */
62 typedef uint16_t hash3_t; // 3x3 pattern hash
65 /* Note that "group" is only chain of stones that is solidly
66 * connected for us. */
67 typedef coord_t group_t;
69 struct group {
70 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
71 * don't care. */
72 /* _Combination_ of these two values can make some difference
73 * in performance - fine-tune. */
74 #define GROUP_KEEP_LIBS 10
75 // refill lib[] only when we hit this; this must be at least 2!
76 // Moggy requires at least 3 - see below for semantic impact.
77 #define GROUP_REFILL_LIBS 5
78 coord_t lib[GROUP_KEEP_LIBS];
79 /* libs is only LOWER BOUND for the number of real liberties!!!
80 * It denotes only number of items in lib[], thus you can rely
81 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
82 int libs;
85 struct neighbor_colors {
86 char colors[S_MAX];
90 /* Point traits bitmap; we update this information incrementally,
91 * it can be used e.g. for fast pattern.h features matching. */
92 struct btraits {
93 /* Number of neighbors we can capture. 0=this move is
94 * not capturing, 1..4=this many neighbors we can capture
95 * (can be multiple neighbors of same group). */
96 unsigned cap:3;
97 /* Whether it is SAFE to play here. This is essentially just
98 * cached result of board_safe_to_play(). (Of course the concept
99 * of "safety" is not perfect here, but it's the cheapest
100 * reasonable thing we can do.) */
101 bool safe:1;
102 /* Whether we need to re-compute this coordinate; used to
103 * weed out duplicates. Maintained only for S_BLACK. */
104 bool dirty:1;
108 /* You should treat this struct as read-only. Always call functions below if
109 * you want to change it. */
111 struct board {
112 int size; /* Including S_OFFBOARD margin - see below. */
113 int size2; /* size^2 */
114 int bits2; /* ceiling(log2(size2)) */
115 int captures[S_MAX];
116 float komi;
117 int handicap;
118 /* The ruleset is currently almost never taken into account;
119 * the board implementation is basically Chinese rules (handicap
120 * stones compensation) w/ suicide (or you can look at it as
121 * New Zealand w/o handi stones compensation), while the engine
122 * enforces no-suicide, making for real Chinese rules. */
123 enum {
124 RULES_CHINESE, /* default value */
125 RULES_AGA,
126 RULES_NEW_ZEALAND,
127 RULES_JAPANESE,
128 } rules;
130 /* Iterator offsets for foreach_neighbor*() */
131 int nei8[8], dnei[4];
133 int moves;
134 struct move last_move;
135 struct move last_move2; /* second-to-last move */
136 /* Whether we tried to add a hash twice; board_play*() can
137 * set this, but it will still carry out the move as well! */
138 bool superko_violation;
140 /* The following two structures are goban maps and are indexed by
141 * coord.pos. The map is surrounded by a one-point margin from
142 * S_OFFBOARD stones in order to speed up some internal loops.
143 * Some of the foreach iterators below might include these points;
144 * you need to handle them yourselves, if you need to. */
146 /* Stones played on the board */
147 enum stone *b; /* enum stone */
148 /* Group id the stones are part of; 0 == no group */
149 group_t *g;
150 /* Positions of next stones in the stone group; 0 == last stone */
151 coord_t *p;
152 /* Neighboring colors; numbers of neighbors of index color */
153 struct neighbor_colors *n;
154 /* Zobrist hash for each position */
155 hash_t *h;
156 #ifdef BOARD_SPATHASH
157 /* For spatial hashes, we use only 24 bits. */
158 /* [0] is d==1, we don't keep hash for d==0. */
159 /* We keep hashes for black-to-play ([][0]) and white-to-play
160 * ([][1], reversed stone colors since we match all patterns as
161 * black-to-play). */
162 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
163 #endif
164 #ifdef BOARD_PAT3
165 /* 3x3 pattern code for each position; see pattern3.h for encoding
166 * specification. The information is only valid for empty points. */
167 hash3_t *pat3;
168 #endif
169 #ifdef BOARD_TRAITS
170 /* Incrementally matched point traits information, black-to-play
171 * ([][0]) and white-to-play ([][1]). */
172 /* The information is only valid for empty points. */
173 struct btraits (*t)[2];
174 #endif
175 #ifdef BOARD_GAMMA
176 /* Relative probabilities of moves being played next, computed by
177 * multiplying gammas of the appropriate pattern features based on
178 * pat3 and traits (see pattern.h). The probability distribution
179 * is maintained over the full board grid. */
180 /* - Always invalid moves are guaranteed to have zero probability.
181 * - Self-eye-filling moves will always have zero probability.
182 * - Ko-prohibited moves might have non-zero probability.
183 * - FEAT_CONTIGUITY is not accounted for in the probability. */
184 struct probdist prob[2];
185 #endif
186 /* Cached information on x-y coordinates so that we avoid division. */
187 uint8_t (*coord)[2];
189 /* Group information - indexed by gid (which is coord of base group stone) */
190 struct group *gi;
192 /* Positions of free positions - queue (not map) */
193 /* Note that free position here is any valid move; including single-point eyes!
194 * However, pass is not included. */
195 coord_t *f; int flen;
197 #ifdef WANT_BOARD_C
198 /* Queue of capturable groups */
199 group_t *c; int clen;
200 #endif
202 #ifdef BOARD_TRAITS
203 /* Queue of positions that need their traits updated */
204 coord_t *tq; int tqlen;
205 #endif
207 /* Symmetry information */
208 struct board_symmetry symmetry;
210 /* Last ko played on the board. */
211 struct move last_ko;
212 int last_ko_age;
214 /* Basic ko check */
215 struct move ko;
217 /* Engine-specific state; persistent through board development,
218 * is reset only at clear_board. */
219 void *es;
221 /* Playout-specific state; persistent through board development,
222 * but its lifetime is maintained in play_random_game(); it should
223 * not be set outside of it. */
224 void *ps;
226 #ifdef BOARD_GAMMA
227 /* Gamma values for probability distribution; user must setup
228 * this pointer before any move is played, using board_gamma_set(). */
229 struct features_gamma *gamma;
230 /* Whether to compute the 'safe' trait using board_safe_to_play()
231 * (false) or is_bad_selfatari() (true, much slower). */
232 bool precise_selfatari;
233 #endif
236 /* --- PRIVATE DATA --- */
238 /* For superko check: */
240 /* Board "history" - hashes encountered. Size of the hash should be
241 * >> board_size^2. */
242 #define history_hash_bits 12
243 #define history_hash_mask ((1 << history_hash_bits) - 1)
244 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
245 #define history_hash_next(i) ((i + 1) & history_hash_mask)
246 hash_t history_hash[1 << history_hash_bits];
247 /* Hash of current board position. */
248 hash_t hash;
251 #ifdef BOARD_SIZE
252 /* Avoid unused variable warnings */
253 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
254 #define board_size2(b_) (board_size(b_) * board_size(b_))
255 #else
256 #define board_size(b_) ((b_)->size)
257 #define board_size2(b_) ((b_)->size2)
258 #endif
260 #if BOARD_SIZE == 19
261 # define board_bits2(b_) 9
262 #elif BOARD_SIZE == 13
263 # define board_bits2(b_) 8
264 #elif BOARD_SIZE == 9
265 # define board_bits2(b_) 7
266 #else
267 # define board_bits2(b_) ((b_)->bits2)
268 #endif
270 #define board_at(b_, c) ((b_)->b[c])
271 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
273 #define group_at(b_, c) ((b_)->g[c])
274 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
276 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
277 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
278 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
279 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
280 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
281 #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))
283 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
285 #define groupnext_at(b_, c) ((b_)->p[c])
286 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
288 #define group_base(g_) (g_)
289 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
290 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
291 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
293 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
295 struct board *board_init(void);
296 struct board *board_copy(struct board *board2, struct board *board1);
297 void board_done_noalloc(struct board *board);
298 void board_done(struct board *board);
299 /* size here is without the S_OFFBOARD margin. */
300 void board_resize(struct board *board, int size);
301 void board_clear(struct board *board);
303 struct FILE;
304 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
305 void board_print(struct board *board, FILE *f);
306 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
308 /* Place given handicap on the board; coordinates are printed to f. */
309 void board_handicap(struct board *board, int stones, FILE *f);
311 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
312 int board_play(struct board *board, struct move *m);
313 /* Like above, but plays random move; the move coordinate is recorded
314 * to *coord. This method will never fill your own eye. pass is played
315 * when no move can be played. You can impose extra restrictions if you
316 * supply your own permit function; the permit function can also modify
317 * the move coordinate to redirect the move elsewhere. */
318 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
319 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
321 /* Returns true if given move can be played. */
322 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
323 static bool board_is_valid_move(struct board *b, struct move *m);
324 /* Returns true if ko was just taken. */
325 static bool board_playing_ko_threat(struct board *b);
326 /* Returns 0 or ID of neighboring group in atari. */
327 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
328 /* Returns true if the move is not obvious self-atari. */
329 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
331 /* Adjust symmetry information as if given coordinate has been played. */
332 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
333 /* Associate a set of feature gamma values (for pd building) with the board. */
334 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
335 /* Force re-compute of a probability distribution item. */
336 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
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 float board_fast_score(struct board *board);
355 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
356 struct move_queue;
357 float 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_in_group(board_, group_) \
373 do { \
374 struct board *board__ = board_; \
375 coord_t c = group_base(group_); \
376 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
377 do {
378 #define foreach_in_group_end \
379 c = c2; c2 = groupnext_at(board__, c2); \
380 } while (c != 0); \
381 } while (0)
383 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
384 * on S_OFFBOARD coordinates. */
385 #define foreach_neighbor(board_, coord_, loop_body) \
386 do { \
387 struct board *board__ = board_; \
388 coord_t coord__ = coord_; \
389 coord_t c; \
390 c = coord__ - 1; do { loop_body } while (0); \
391 c = coord__ - board_size(board__); do { loop_body } while (0); \
392 c = coord__ + 1; do { loop_body } while (0); \
393 c = coord__ + board_size(board__); do { loop_body } while (0); \
394 } while (0)
396 #define foreach_8neighbor(board_, coord_) \
397 do { \
398 int fn__i; \
399 coord_t c = (coord_); \
400 for (fn__i = 0; fn__i < 8; fn__i++) { \
401 c += (board_)->nei8[fn__i];
402 #define foreach_8neighbor_end \
404 } while (0)
406 #define foreach_diag_neighbor(board_, coord_) \
407 do { \
408 int fn__i; \
409 coord_t c = (coord_); \
410 for (fn__i = 0; fn__i < 4; fn__i++) { \
411 c += (board_)->dnei[fn__i];
412 #define foreach_diag_neighbor_end \
414 } while (0)
417 static inline bool
418 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
420 return (neighbor_count_at(board, coord, eye_color)
421 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
424 static inline bool
425 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
427 if (board_at(board, coord) != S_NONE)
428 return false;
429 if (!board_is_eyelike(board, coord, stone_other(color)))
430 return true;
431 /* Play within {true,false} eye-ish formation */
432 if (board->ko.coord == coord && board->ko.color == color)
433 return false;
434 #ifdef BOARD_TRAITS
435 /* XXX: Disallows suicide. */
436 return trait_at(board, coord, color).cap > 0;
437 #else
438 int groups_in_atari = 0;
439 foreach_neighbor(board, coord, {
440 group_t g = group_at(board, c);
441 groups_in_atari += (board_group_info(board, g).libs == 1);
443 return !!groups_in_atari;
444 #endif
447 static inline bool
448 board_is_valid_move(struct board *board, struct move *m)
450 return board_is_valid_play(board, m->color, m->coord);
453 static inline bool
454 board_playing_ko_threat(struct board *b)
456 return !is_pass(b->ko.coord);
459 static inline group_t
460 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
462 #ifdef BOARD_TRAITS
463 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
464 #endif
465 foreach_neighbor(b, coord, {
466 group_t g = group_at(b, c);
467 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
468 return g;
469 /* We return first match. */
471 return 0;
474 static inline bool
475 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
477 /* number of free neighbors */
478 int libs = immediate_liberty_count(b, coord);
479 if (libs > 1)
480 return true;
482 #ifdef BOARD_TRAITS
483 /* number of capturable enemy groups */
484 if (trait_at(b, coord, color).cap > 0)
485 return true; // XXX: We don't account for snapback.
486 /* number of non-capturable friendly groups */
487 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
488 if (noncap_ours < 1)
489 return false;
490 /*#else see below */
491 #endif
493 /* ok, but we need to check if they don't have just two libs. */
494 coord_t onelib = -1;
495 foreach_neighbor(b, coord, {
496 #ifndef BOARD_TRAITS
497 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
498 return true; // can capture; no snapback check
499 #endif
500 if (board_at(b, c) != color) continue;
501 group_t g = group_at(b, c);
502 if (board_group_info(b, g).libs == 1) continue; // in atari
503 if (board_group_info(b, g).libs == 2) { // two liberties
504 if (libs > 0) return true; // we already have one real liberty
505 // get the other liberty
506 coord_t lib = board_group_info(b, g).lib[0];
507 if (lib == coord) lib = board_group_info(b, g).lib[0];
508 /* we might be connecting two 2-lib groups, which is ok;
509 * so remember the other liberty and just make sure it's
510 * not the same one */
511 if (onelib >= 0 && lib != onelib) return true;
512 onelib = lib;
513 continue;
515 // many liberties
516 return true;
518 // no good support group
519 return false;
522 #endif