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