Preserve rules over board_clear()
[pachi/peepo.git] / board.h
blobf10fc558f1149888be8032ac0008b6a921f43970
1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
3 #include "probdist.h"
5 #ifndef PACHI_BOARD_H
6 #define PACHI_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 fbook;
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_TRAIT_SAFE 1 // include btraits.safe (rather expensive, unused)
37 //#define BOARD_TRAIT_SAFE 2 // include btraits.safe based on full is_bad_selfatari()
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 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 #ifdef BOARD_TRAIT_SAFE
109 /* Whether it is SAFE to play here. This is essentially just
110 * cached result of board_safe_to_play(). (Of course the concept
111 * of "safety" is not perfect here, but it's the cheapest
112 * reasonable thing we can do.) */
113 bool safe:1;
114 #endif
115 /* Whether we need to re-compute this coordinate; used to
116 * weed out duplicates. Maintained only for S_BLACK. */
117 bool dirty:1;
121 /* You should treat this struct as read-only. Always call functions below if
122 * you want to change it. */
124 struct board {
125 int size; /* Including S_OFFBOARD margin - see below. */
126 int size2; /* size^2 */
127 int bits2; /* ceiling(log2(size2)) */
128 int captures[S_MAX];
129 floating_t komi;
130 int handicap;
131 /* The ruleset is currently almost never taken into account;
132 * the board implementation is basically Chinese rules (handicap
133 * stones compensation) w/ suicide (or you can look at it as
134 * New Zealand w/o handi stones compensation), while the engine
135 * enforces no-suicide, making for real Chinese rules.
136 * However, we accept suicide moves by the opponent, so we
137 * should work with rules allowing suicide, just not taking
138 * full advantage of them. */
139 enum go_ruleset {
140 RULES_CHINESE, /* default value */
141 RULES_AGA,
142 RULES_NEW_ZEALAND,
143 RULES_JAPANESE,
144 RULES_STONES_ONLY, /* do not count eyes */
145 RULES_PASS_STONES, /* RULES_CHINESE + pass stones */
146 } rules;
148 char *fbookfile;
149 struct fbook *fbook;
151 /* Iterator offsets for foreach_neighbor*() */
152 int nei8[8], dnei[4];
154 int moves;
155 struct move last_move;
156 struct move last_move2; /* second-to-last move */
157 struct move last_move3; /* just before last_move2, only set if last_move is pass */
158 struct move last_move4; /* just before last_move3, only set if last_move & last_move2 are pass */
159 /* Whether we tried to add a hash twice; board_play*() can
160 * set this, but it will still carry out the move as well! */
161 bool superko_violation;
163 /* The following two structures are goban maps and are indexed by
164 * coord.pos. The map is surrounded by a one-point margin from
165 * S_OFFBOARD stones in order to speed up some internal loops.
166 * Some of the foreach iterators below might include these points;
167 * you need to handle them yourselves, if you need to. */
169 /* Stones played on the board */
170 enum stone *b; /* enum stone */
171 /* Group id the stones are part of; 0 == no group */
172 group_t *g;
173 /* Positions of next stones in the stone group; 0 == last stone */
174 coord_t *p;
175 /* Neighboring colors; numbers of neighbors of index color */
176 struct neighbor_colors *n;
177 /* Zobrist hash for each position */
178 hash_t *h;
179 #ifdef BOARD_SPATHASH
180 /* For spatial hashes, we use only 24 bits. */
181 /* [0] is d==1, we don't keep hash for d==0. */
182 /* We keep hashes for black-to-play ([][0]) and white-to-play
183 * ([][1], reversed stone colors since we match all patterns as
184 * black-to-play). */
185 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
186 #endif
187 #ifdef BOARD_PAT3
188 /* 3x3 pattern code for each position; see pattern3.h for encoding
189 * specification. The information is only valid for empty points. */
190 hash3_t *pat3;
191 #endif
192 #ifdef BOARD_TRAITS
193 /* Incrementally matched point traits information, black-to-play
194 * ([][0]) and white-to-play ([][1]). */
195 /* The information is only valid for empty points. */
196 struct btraits (*t)[2];
197 #endif
198 /* Cached information on x-y coordinates so that we avoid division. */
199 uint8_t (*coord)[2];
201 /* Group information - indexed by gid (which is coord of base group stone) */
202 struct group *gi;
204 /* Positions of free positions - queue (not map) */
205 /* Note that free position here is any valid move; including single-point eyes!
206 * However, pass is not included. */
207 coord_t *f; int flen;
209 #ifdef WANT_BOARD_C
210 /* Queue of capturable groups */
211 group_t *c; int clen;
212 #endif
214 #ifdef BOARD_TRAITS
215 /* Queue of positions that need their traits updated */
216 coord_t *tq; int tqlen;
217 #endif
219 /* Symmetry information */
220 struct board_symmetry symmetry;
222 /* Last ko played on the board. */
223 struct move last_ko;
224 int last_ko_age;
226 /* Basic ko check */
227 struct move ko;
229 /* Engine-specific state; persistent through board development,
230 * is reset only at clear_board. */
231 void *es;
233 /* Playout-specific state; persistent through board development,
234 * but its lifetime is maintained in play_random_game(); it should
235 * not be set outside of it. */
236 void *ps;
239 /* --- PRIVATE DATA --- */
241 /* For superko check: */
243 /* Board "history" - hashes encountered. Size of the hash should be
244 * >> board_size^2. */
245 #define history_hash_bits 12
246 #define history_hash_mask ((1 << history_hash_bits) - 1)
247 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
248 #define history_hash_next(i) ((i + 1) & history_hash_mask)
249 hash_t history_hash[1 << history_hash_bits];
250 /* Hash of current board position. */
251 hash_t hash;
252 /* Hash of current board position quadrants. */
253 hash_t qhash[4];
256 #ifdef BOARD_SIZE
257 /* Avoid unused variable warnings */
258 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
259 #define board_size2(b_) (board_size(b_) * board_size(b_))
260 #else
261 #define board_size(b_) ((b_)->size)
262 #define board_size2(b_) ((b_)->size2)
263 #endif
265 /* This is a shortcut for taking different action on smaller
266 * and large boards (e.g. picking different variable defaults).
267 * This is of course less optimal than fine-tuning dependency
268 * function of values on board size, but that is difficult and
269 * possibly not very rewarding if you are interested just in
270 * 9x9 and 19x19. */
271 #define board_large(b_) (board_size(b_)-2 >= 15)
273 #if BOARD_SIZE == 19
274 # define board_bits2(b_) 9
275 #elif BOARD_SIZE == 13
276 # define board_bits2(b_) 8
277 #elif BOARD_SIZE == 9
278 # define board_bits2(b_) 7
279 #else
280 # define board_bits2(b_) ((b_)->bits2)
281 #endif
283 #define board_at(b_, c) ((b_)->b[c])
284 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
286 #define group_at(b_, c) ((b_)->g[c])
287 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
289 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
290 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
291 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
292 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
293 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
294 #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))
296 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
298 #define groupnext_at(b_, c) ((b_)->p[c])
299 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
301 #define group_base(g_) (g_)
302 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
303 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
304 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
305 /* board_group_other_lib() makes sense only for groups with two liberties. */
306 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
308 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
310 struct board *board_init(char *fbookfile);
311 struct board *board_copy(struct board *board2, struct board *board1);
312 void board_done_noalloc(struct board *board);
313 void board_done(struct board *board);
314 /* size here is without the S_OFFBOARD margin. */
315 void board_resize(struct board *board, int size);
316 void board_clear(struct board *board);
318 struct FILE;
319 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
320 void board_print(struct board *board, FILE *f);
321 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
323 /* Place given handicap on the board; coordinates are printed to f. */
324 void board_handicap(struct board *board, int stones, FILE *f);
326 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
327 int board_play(struct board *board, struct move *m);
328 /* Like above, but plays random move; the move coordinate is recorded
329 * to *coord. This method will never fill your own eye. pass is played
330 * when no move can be played. You can impose extra restrictions if you
331 * supply your own permit function; the permit function can also modify
332 * the move coordinate to redirect the move elsewhere. */
333 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
334 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
336 /*Undo, supported only for pass moves. Returns -1 on error, 0 otherwise. */
337 int board_undo(struct board *board);
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 /* Determine number of stones in a group, up to @max stones. */
350 static int group_stone_count(struct board *b, group_t group, int max);
352 /* Adjust symmetry information as if given coordinate has been played. */
353 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
354 /* Check if coordinates are within symmetry base. (If false, they can
355 * be derived from the base.) */
356 static bool board_coord_in_symmetry(struct board *b, coord_t c);
358 /* Returns true if given coordinate has all neighbors of given color or the edge. */
359 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
360 /* Returns true if given coordinate could be a false eye; this check makes
361 * sense only if you already know the coordinate is_eyelike(). */
362 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
363 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
364 * at least tries to). */
365 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
366 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
367 enum stone board_get_one_point_eye(struct board *board, coord_t c);
369 /* board_official_score() is the scoring method for yielding score suitable
370 * for external presentation. For fast scoring of entirely filled boards
371 * (e.g. playouts), use board_fast_score(). */
372 /* Positive: W wins */
373 /* Compare number of stones + 1pt eyes. */
374 floating_t board_fast_score(struct board *board);
375 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
376 struct move_queue;
377 floating_t board_official_score(struct board *board, struct move_queue *mq);
379 /* Set board rules according to given string. Returns false in case
380 * of unknown ruleset name. */
381 bool board_set_rules(struct board *board, char *name);
383 /** Iterators */
385 #define foreach_point(board_) \
386 do { \
387 coord_t c = 0; \
388 for (; c < board_size(board_) * board_size(board_); c++)
389 #define foreach_point_and_pass(board_) \
390 do { \
391 coord_t c = pass; \
392 for (; c < board_size(board_) * board_size(board_); c++)
393 #define foreach_point_end \
394 } while (0)
396 #define foreach_free_point(board_) \
397 do { \
398 int fmax__ = (board_)->flen; \
399 for (int f__ = 0; f__ < fmax__; f__++) { \
400 coord_t c = (board_)->f[f__];
401 #define foreach_free_point_end \
403 } while (0)
405 #define foreach_in_group(board_, group_) \
406 do { \
407 struct board *board__ = board_; \
408 coord_t c = group_base(group_); \
409 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
410 do {
411 #define foreach_in_group_end \
412 c = c2; c2 = groupnext_at(board__, c2); \
413 } while (c != 0); \
414 } while (0)
416 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
417 * on S_OFFBOARD coordinates. */
418 #define foreach_neighbor(board_, coord_, loop_body) \
419 do { \
420 struct board *board__ = board_; \
421 coord_t coord__ = coord_; \
422 coord_t c; \
423 c = coord__ - board_size(board__); do { loop_body } while (0); \
424 c = coord__ - 1; do { loop_body } while (0); \
425 c = coord__ + 1; do { loop_body } while (0); \
426 c = coord__ + board_size(board__); do { loop_body } while (0); \
427 } while (0)
429 #define foreach_8neighbor(board_, coord_) \
430 do { \
431 int fn__i; \
432 coord_t c = (coord_); \
433 for (fn__i = 0; fn__i < 8; fn__i++) { \
434 c += (board_)->nei8[fn__i];
435 #define foreach_8neighbor_end \
437 } while (0)
439 #define foreach_diag_neighbor(board_, coord_) \
440 do { \
441 int fn__i; \
442 coord_t c = (coord_); \
443 for (fn__i = 0; fn__i < 4; fn__i++) { \
444 c += (board_)->dnei[fn__i];
445 #define foreach_diag_neighbor_end \
447 } while (0)
450 static inline bool
451 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
453 return (neighbor_count_at(board, coord, eye_color)
454 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
457 static inline bool
458 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
460 if (board_at(board, coord) != S_NONE)
461 return false;
462 if (!board_is_eyelike(board, coord, stone_other(color)))
463 return true;
464 /* Play within {true,false} eye-ish formation */
465 if (board->ko.coord == coord && board->ko.color == color)
466 return false;
467 #ifdef BOARD_TRAITS
468 /* XXX: Disallows suicide. */
469 return trait_at(board, coord, color).cap > 0;
470 #else
471 int groups_in_atari = 0;
472 foreach_neighbor(board, coord, {
473 group_t g = group_at(board, c);
474 groups_in_atari += (board_group_info(board, g).libs == 1);
476 return !!groups_in_atari;
477 #endif
480 static inline bool
481 board_is_valid_move(struct board *board, struct move *m)
483 return board_is_valid_play(board, m->color, m->coord);
486 static inline bool
487 board_playing_ko_threat(struct board *b)
489 return !is_pass(b->ko.coord);
492 static inline group_t
493 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
495 #ifdef BOARD_TRAITS
496 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
497 #endif
498 foreach_neighbor(b, coord, {
499 group_t g = group_at(b, c);
500 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
501 return g;
502 /* We return first match. */
504 return 0;
507 static inline bool
508 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
510 /* number of free neighbors */
511 int libs = immediate_liberty_count(b, coord);
512 if (libs > 1)
513 return true;
515 #ifdef BOARD_TRAITS
516 /* number of capturable enemy groups */
517 if (trait_at(b, coord, color).cap > 0)
518 return true; // XXX: We don't account for snapback.
519 /* number of non-capturable friendly groups */
520 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
521 if (noncap_ours < 1)
522 return false;
523 /*#else see below */
524 #endif
526 /* ok, but we need to check if they don't have just two libs. */
527 coord_t onelib = -1;
528 foreach_neighbor(b, coord, {
529 #ifndef BOARD_TRAITS
530 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
531 return true; // can capture; no snapback check
532 #endif
533 if (board_at(b, c) != color) continue;
534 group_t g = group_at(b, c);
535 if (board_group_info(b, g).libs == 1) continue; // in atari
536 if (board_group_info(b, g).libs == 2) { // two liberties
537 if (libs > 0) return true; // we already have one real liberty
538 /* we might be connecting two 2-lib groups, which is ok;
539 * so remember the other liberty and just make sure it's
540 * not the same one */
541 if (onelib >= 0 && c != onelib) return true;
542 onelib = board_group_other_lib(b, g, c);
543 continue;
545 // many liberties
546 return true;
548 // no good support group
549 return false;
552 static inline int
553 group_stone_count(struct board *b, group_t group, int max)
555 int n = 0;
556 foreach_in_group(b, group) {
557 n++;
558 if (n >= max) return max;
559 } foreach_in_group_end;
560 return n;
563 static inline bool
564 board_coord_in_symmetry(struct board *b, coord_t c)
566 if (coord_y(c, b) < b->symmetry.y1 || coord_y(c, b) > b->symmetry.y2)
567 return false;
568 if (coord_x(c, b) < b->symmetry.x1 || coord_x(c, b) > b->symmetry.x2)
569 return false;
570 if (b->symmetry.d) {
571 int x = coord_x(c, b);
572 if (b->symmetry.type == SYM_DIAG_DOWN)
573 x = board_size(b) - 1 - x;
574 if (x > coord_y(c, b))
575 return false;
577 return true;
581 #endif