[PATCH] board_handicap(): Correct placement for three-stone handicaps
[pachi/json.git] / board.h
blobe1546e7f569e83a976b96b1d0fc721d3ae1f3f05
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_PAT3 // incremental 3x3 pattern codes
32 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
35 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
36 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
39 /* Some engines might normalize their reading and skip symmetrical
40 * moves. We will tell them how can they do it. */
41 struct board_symmetry {
42 /* Playground is in this rectangle. */
43 int x1, x2, y1, y2;
44 /* d == 0: Full rectangle
45 * d == 1: Top triangle */
46 int d;
47 /* General symmetry type. */
48 /* Note that the above is redundant to this, but just provided
49 * for easier usage. */
50 enum {
51 SYM_FULL,
52 SYM_DIAG_UP,
53 SYM_DIAG_DOWN,
54 SYM_HORIZ,
55 SYM_VERT,
56 SYM_NONE
57 } type;
61 typedef uint64_t hash_t;
62 #define PRIhash PRIx64
64 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
65 * a dependency hell. */
66 typedef uint32_t hash3_t; // 3x3 pattern hash
69 /* Note that "group" is only chain of stones that is solidly
70 * connected for us. */
71 typedef coord_t group_t;
73 struct group {
74 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
75 * don't care. */
76 /* _Combination_ of these two values can make some difference
77 * in performance - fine-tune. */
78 #define GROUP_KEEP_LIBS 10
79 // refill lib[] only when we hit this; this must be at least 2!
80 // Moggy requires at least 3 - see below for semantic impact.
81 #define GROUP_REFILL_LIBS 5
82 coord_t lib[GROUP_KEEP_LIBS];
83 /* libs is only LOWER BOUND for the number of real liberties!!!
84 * It denotes only number of items in lib[], thus you can rely
85 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
86 int libs;
89 struct neighbor_colors {
90 char colors[S_MAX];
94 /* Point traits bitmap; we update this information incrementally,
95 * it can be used e.g. for fast pattern features matching. */
96 struct btraits {
97 /* Number of neighbors we can capture. 0=this move is
98 * not capturing, 1..4=this many neighbors we can capture
99 * (can be multiple neighbors of same group). */
100 unsigned cap:3;
101 /* Number of 1-stone neighbors we can capture. */
102 unsigned cap1:3;
103 /* Whether it is SAFE to play here. This is essentially just
104 * cached result of board_safe_to_play(). (Of course the concept
105 * of "safety" is not perfect here, but it's the cheapest
106 * reasonable thing we can do.) */
107 bool safe:1;
108 /* Whether we need to re-compute this coordinate; used to
109 * weed out duplicates. Maintained only for S_BLACK. */
110 bool dirty:1;
114 /* You should treat this struct as read-only. Always call functions below if
115 * you want to change it. */
117 struct board {
118 int size; /* Including S_OFFBOARD margin - see below. */
119 int size2; /* size^2 */
120 int bits2; /* ceiling(log2(size2)) */
121 int captures[S_MAX];
122 floating_t komi;
123 int handicap;
124 /* The ruleset is currently almost never taken into account;
125 * the board implementation is basically Chinese rules (handicap
126 * stones compensation) w/ suicide (or you can look at it as
127 * New Zealand w/o handi stones compensation), while the engine
128 * enforces no-suicide, making for real Chinese rules. */
129 enum {
130 RULES_CHINESE, /* default value */
131 RULES_AGA,
132 RULES_NEW_ZEALAND,
133 RULES_JAPANESE,
134 } rules;
136 char *fbookfile;
137 struct fbook *fbook;
139 /* Iterator offsets for foreach_neighbor*() */
140 int nei8[8], dnei[4];
142 int moves;
143 struct move last_move;
144 struct move last_move2; /* second-to-last move */
145 struct move last_move3; /* just before last_move2, only set if last_move is pass */
146 struct move last_move4; /* just before last_move3, only set if last_move & last_move2 are pass */
147 /* Whether we tried to add a hash twice; board_play*() can
148 * set this, but it will still carry out the move as well! */
149 bool superko_violation;
151 /* The following two structures are goban maps and are indexed by
152 * coord.pos. The map is surrounded by a one-point margin from
153 * S_OFFBOARD stones in order to speed up some internal loops.
154 * Some of the foreach iterators below might include these points;
155 * you need to handle them yourselves, if you need to. */
157 /* Stones played on the board */
158 enum stone *b; /* enum stone */
159 /* Group id the stones are part of; 0 == no group */
160 group_t *g;
161 /* Positions of next stones in the stone group; 0 == last stone */
162 coord_t *p;
163 /* Neighboring colors; numbers of neighbors of index color */
164 struct neighbor_colors *n;
165 /* Zobrist hash for each position */
166 hash_t *h;
167 #ifdef BOARD_PAT3
168 /* 3x3 pattern code for each position; see pattern3.h for encoding
169 * specification. The information is only valid for empty points. */
170 hash3_t *pat3;
171 #endif
172 #ifdef BOARD_TRAITS
173 /* Incrementally matched point traits information, black-to-play
174 * ([][0]) and white-to-play ([][1]). */
175 /* The information is only valid for empty points. */
176 struct btraits (*t)[2];
177 #endif
178 /* Cached information on x-y coordinates so that we avoid division. */
179 uint8_t (*coord)[2];
181 /* Group information - indexed by gid (which is coord of base group stone) */
182 struct group *gi;
184 /* Positions of free positions - queue (not map) */
185 /* Note that free position here is any valid move; including single-point eyes!
186 * However, pass is not included. */
187 coord_t *f; int flen;
189 #ifdef WANT_BOARD_C
190 /* Queue of capturable groups */
191 group_t *c; int clen;
192 #endif
194 #ifdef BOARD_TRAITS
195 /* Queue of positions that need their traits updated */
196 coord_t *tq; int tqlen;
197 #endif
199 /* Symmetry information */
200 struct board_symmetry symmetry;
202 /* Last ko played on the board. */
203 struct move last_ko;
204 int last_ko_age;
206 /* Basic ko check */
207 struct move ko;
209 /* Engine-specific state; persistent through board development,
210 * is reset only at clear_board. */
211 void *es;
213 /* Playout-specific state; persistent through board development,
214 * but its lifetime is maintained in play_random_game(); it should
215 * not be set outside of it. */
216 void *ps;
219 /* --- PRIVATE DATA --- */
221 /* For superko check: */
223 /* Board "history" - hashes encountered. Size of the hash should be
224 * >> board_size^2. */
225 #define history_hash_bits 12
226 #define history_hash_mask ((1 << history_hash_bits) - 1)
227 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
228 #define history_hash_next(i) ((i + 1) & history_hash_mask)
229 hash_t history_hash[1 << history_hash_bits];
230 /* Hash of current board position. */
231 hash_t hash;
232 /* Hash of current board position quadrants. */
233 hash_t qhash[4];
236 #ifdef BOARD_SIZE
237 /* Avoid unused variable warnings */
238 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
239 #define board_size2(b_) (board_size(b_) * board_size(b_))
240 #else
241 #define board_size(b_) ((b_)->size)
242 #define board_size2(b_) ((b_)->size2)
243 #endif
245 /* This is a shortcut for taking different action on smaller
246 * and large boards (e.g. picking different variable defaults).
247 * This is of course less optimal than fine-tuning dependency
248 * function of values on board size, but that is difficult and
249 * possibly not very rewarding if you are interested just in
250 * 9x9 and 19x19. */
251 #define board_large(b_) (board_size(b_)-2 >= 15)
253 #if BOARD_SIZE == 19
254 # define board_bits2(b_) 9
255 #elif BOARD_SIZE == 13
256 # define board_bits2(b_) 8
257 #elif BOARD_SIZE == 9
258 # define board_bits2(b_) 7
259 #else
260 # define board_bits2(b_) ((b_)->bits2)
261 #endif
263 #define board_at(b_, c) ((b_)->b[c])
264 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
266 #define group_at(b_, c) ((b_)->g[c])
267 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
269 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
270 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
271 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
272 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
273 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
274 #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))
276 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
278 #define groupnext_at(b_, c) ((b_)->p[c])
279 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
281 #define group_base(g_) (g_)
282 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
283 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
284 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
285 /* board_group_other_lib() makes sense only for groups with two liberties. */
286 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
288 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
290 struct board *board_init(char *fbookfile);
291 struct board *board_copy(struct board *board2, struct board *board1);
292 void board_done_noalloc(struct board *board);
293 void board_done(struct board *board);
294 /* size here is without the S_OFFBOARD margin. */
295 void board_resize(struct board *board, int size);
296 void board_clear(struct board *board);
298 struct FILE;
299 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
300 void board_print(struct board *board, FILE *f);
301 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
303 /* Place given handicap on the board; coordinates are printed to f. */
304 void board_handicap(struct board *board, int stones, FILE *f);
306 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
307 int board_play(struct board *board, struct move *m);
308 /* Like above, but plays random move; the move coordinate is recorded
309 * to *coord. This method will never fill your own eye. pass is played
310 * when no move can be played. You can impose extra restrictions if you
311 * supply your own permit function; the permit function can also modify
312 * the move coordinate to redirect the move elsewhere. */
313 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
314 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
316 /*Undo, supported only for pass moves. Returns -1 on error, 0 otherwise. */
317 int board_undo(struct board *board);
319 /* Returns true if given move can be played. */
320 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
321 static bool board_is_valid_move(struct board *b, struct move *m);
322 /* Returns true if ko was just taken. */
323 static bool board_playing_ko_threat(struct board *b);
324 /* Returns 0 or ID of neighboring group in atari. */
325 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
326 /* Returns true if the move is not obvious self-atari. */
327 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
329 /* Determine number of stones in a group, up to @max stones. */
330 static int group_stone_count(struct board *b, group_t group, int max);
332 /* Adjust symmetry information as if given coordinate has been played. */
333 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
335 /* Returns true if given coordinate has all neighbors of given color or the edge. */
336 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
337 /* Returns true if given coordinate could be a false eye; this check makes
338 * sense only if you already know the coordinate is_eyelike(). */
339 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
340 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
341 * at least tries to). */
342 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
343 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
344 enum stone board_get_one_point_eye(struct board *board, coord_t c);
346 /* board_official_score() is the scoring method for yielding score suitable
347 * for external presentation. For fast scoring of entirely filled boards
348 * (e.g. playouts), use board_fast_score(). */
349 /* Positive: W wins */
350 /* Compare number of stones + 1pt eyes. */
351 floating_t board_fast_score(struct board *board);
352 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
353 struct move_queue;
354 floating_t board_official_score(struct board *board, struct move_queue *mq);
356 /** Iterators */
358 #define foreach_point(board_) \
359 do { \
360 coord_t c = 0; \
361 for (; c < board_size(board_) * board_size(board_); c++)
362 #define foreach_point_and_pass(board_) \
363 do { \
364 coord_t c = pass; \
365 for (; c < board_size(board_) * board_size(board_); c++)
366 #define foreach_point_end \
367 } while (0)
369 #define foreach_free_point(board_) \
370 do { \
371 int fmax__ = (board_)->flen; \
372 for (int f__ = 0; f__ < fmax__; f__++) { \
373 coord_t c = (board_)->f[f__];
374 #define foreach_free_point_end \
376 } while (0)
378 #define foreach_in_group(board_, group_) \
379 do { \
380 struct board *board__ = board_; \
381 coord_t c = group_base(group_); \
382 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
383 do {
384 #define foreach_in_group_end \
385 c = c2; c2 = groupnext_at(board__, c2); \
386 } while (c != 0); \
387 } while (0)
389 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
390 * on S_OFFBOARD coordinates. */
391 #define foreach_neighbor(board_, coord_, loop_body) \
392 do { \
393 struct board *board__ = board_; \
394 coord_t coord__ = coord_; \
395 coord_t c; \
396 c = coord__ - board_size(board__); do { loop_body } while (0); \
397 c = coord__ - 1; do { loop_body } while (0); \
398 c = coord__ + 1; do { loop_body } while (0); \
399 c = coord__ + board_size(board__); do { loop_body } while (0); \
400 } while (0)
402 #define foreach_8neighbor(board_, coord_) \
403 do { \
404 int fn__i; \
405 coord_t c = (coord_); \
406 for (fn__i = 0; fn__i < 8; fn__i++) { \
407 c += (board_)->nei8[fn__i];
408 #define foreach_8neighbor_end \
410 } while (0)
412 #define foreach_diag_neighbor(board_, coord_) \
413 do { \
414 int fn__i; \
415 coord_t c = (coord_); \
416 for (fn__i = 0; fn__i < 4; fn__i++) { \
417 c += (board_)->dnei[fn__i];
418 #define foreach_diag_neighbor_end \
420 } while (0)
423 static inline bool
424 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
426 return (neighbor_count_at(board, coord, eye_color)
427 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
430 static inline bool
431 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
433 if (board_at(board, coord) != S_NONE)
434 return false;
435 if (!board_is_eyelike(board, coord, stone_other(color)))
436 return true;
437 /* Play within {true,false} eye-ish formation */
438 if (board->ko.coord == coord && board->ko.color == color)
439 return false;
440 #ifdef BOARD_TRAITS
441 /* XXX: Disallows suicide. */
442 return trait_at(board, coord, color).cap > 0;
443 #else
444 int groups_in_atari = 0;
445 foreach_neighbor(board, coord, {
446 group_t g = group_at(board, c);
447 groups_in_atari += (board_group_info(board, g).libs == 1);
449 return !!groups_in_atari;
450 #endif
453 static inline bool
454 board_is_valid_move(struct board *board, struct move *m)
456 return board_is_valid_play(board, m->color, m->coord);
459 static inline bool
460 board_playing_ko_threat(struct board *b)
462 return !is_pass(b->ko.coord);
465 static inline group_t
466 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
468 #ifdef BOARD_TRAITS
469 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
470 #endif
471 foreach_neighbor(b, coord, {
472 group_t g = group_at(b, c);
473 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
474 return g;
475 /* We return first match. */
477 return 0;
480 static inline bool
481 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
483 /* number of free neighbors */
484 int libs = immediate_liberty_count(b, coord);
485 if (libs > 1)
486 return true;
488 #ifdef BOARD_TRAITS
489 /* number of capturable enemy groups */
490 if (trait_at(b, coord, color).cap > 0)
491 return true; // XXX: We don't account for snapback.
492 /* number of non-capturable friendly groups */
493 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
494 if (noncap_ours < 1)
495 return false;
496 /*#else see below */
497 #endif
499 /* ok, but we need to check if they don't have just two libs. */
500 coord_t onelib = -1;
501 foreach_neighbor(b, coord, {
502 #ifndef BOARD_TRAITS
503 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
504 return true; // can capture; no snapback check
505 #endif
506 if (board_at(b, c) != color) continue;
507 group_t g = group_at(b, c);
508 if (board_group_info(b, g).libs == 1) continue; // in atari
509 if (board_group_info(b, g).libs == 2) { // two liberties
510 if (libs > 0) return true; // we already have one real liberty
511 /* we might be connecting two 2-lib groups, which is ok;
512 * so remember the other liberty and just make sure it's
513 * not the same one */
514 if (onelib >= 0 && c != onelib) return true;
515 onelib = board_group_other_lib(b, g, c);
516 continue;
518 // many liberties
519 return true;
521 // no good support group
522 return false;
525 static inline int
526 group_stone_count(struct board *b, group_t group, int max)
528 int n = 0;
529 foreach_in_group(b, group) {
530 n++;
531 if (n >= max) return max;
532 } foreach_in_group_end;
533 return n;
536 #endif