1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
21 /* Maximum supported board size. (Without the S_OFFBOARD edges.) */
22 #define BOARD_MAX_SIZE 19
25 /* The board implementation has bunch of optional features.
26 * Turn them on below: */
28 #define WANT_BOARD_C // capturable groups queue
30 //#define BOARD_SIZE 9 // constant board size, allows better optimization
32 //#define BOARD_SPATHASH // incremental patternsp.h hashes
33 #define BOARD_SPATHASH_MAXD 3 // maximal diameter
35 #define BOARD_PAT3 // incremental 3x3 pattern codes
37 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
38 //#define BOARD_TRAIT_SAFE 1 // include btraits.safe (rather expensive, unused)
39 //#define BOARD_TRAIT_SAFE 2 // include btraits.safe based on full is_bad_selfatari()
42 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
43 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
46 /* Some engines might normalize their reading and skip symmetrical
47 * moves. We will tell them how can they do it. */
48 struct board_symmetry
{
49 /* Playground is in this rectangle. */
51 /* d == 0: Full rectangle
52 * d == 1: Top triangle */
54 /* General symmetry type. */
55 /* Note that the above is redundant to this, but just provided
56 * for easier usage. */
68 typedef uint64_t hash_t
;
69 #define PRIhash PRIx64
71 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
72 * a dependency hell. */
73 typedef uint32_t hash3_t
; // 3x3 pattern hash
76 /* Note that "group" is only chain of stones that is solidly
77 * connected for us. */
78 typedef coord_t group_t
;
81 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
83 /* _Combination_ of these two values can make some difference
84 * in performance - fine-tune. */
85 #define GROUP_KEEP_LIBS 10
86 // refill lib[] only when we hit this; this must be at least 2!
87 // Moggy requires at least 3 - see below for semantic impact.
88 #define GROUP_REFILL_LIBS 5
89 coord_t lib
[GROUP_KEEP_LIBS
];
90 /* libs is only LOWER BOUND for the number of real liberties!!!
91 * It denotes only number of items in lib[], thus you can rely
92 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
96 struct neighbor_colors
{
101 /* Point traits bitmap; we update this information incrementally,
102 * it can be used e.g. for fast pattern features matching. */
104 /* Number of neighbors we can capture. 0=this move is
105 * not capturing, 1..4=this many neighbors we can capture
106 * (can be multiple neighbors of same group). */
108 /* Number of 1-stone neighbors we can capture. */
110 #ifdef BOARD_TRAIT_SAFE
111 /* Whether it is SAFE to play here. This is essentially just
112 * cached result of board_safe_to_play(). (Of course the concept
113 * of "safety" is not perfect here, but it's the cheapest
114 * reasonable thing we can do.) */
117 /* Whether we need to re-compute this coordinate; used to
118 * weed out duplicates. Maintained only for S_BLACK. */
123 /* You should treat this struct as read-only. Always call functions below if
124 * you want to change it. */
127 int size
; /* Including S_OFFBOARD margin - see below. */
128 int size2
; /* size^2 */
129 int bits2
; /* ceiling(log2(size2)) */
133 /* The ruleset is currently almost never taken into account;
134 * the board implementation is basically Chinese rules (handicap
135 * stones compensation) w/ suicide (or you can look at it as
136 * New Zealand w/o handi stones compensation), while the engine
137 * enforces no-suicide, making for real Chinese rules.
138 * However, we accept suicide moves by the opponent, so we
139 * should work with rules allowing suicide, just not taking
140 * full advantage of them. */
142 RULES_CHINESE
, /* default value */
146 RULES_STONES_ONLY
, /* do not count eyes */
147 /* http://home.snafu.de/jasiek/siming.html */
148 /* Simplified ING rules - RULES_CHINESE with handicaps
149 * counting as points and pass stones. Also should
150 * allow suicide, but Pachi will never suicide
152 /* XXX: I couldn't find the point about pass stones
153 * in the rule text, but it is Robert Jasiek's
154 * interpretation of them... These rules were
155 * used e.g. at the EGC2012 13x13 tournament.
156 * They are not supported by KGS. */
162 struct libmap_hash
*libmap
;
163 /* Whether to add new groups to the libmap as they pop up. */
164 bool libmap_init_groups
;
165 /* Queue of moves to store in libmap_hash with their goal value
166 * at the game end. */
167 struct libmap_mq
*lmqueue
;
169 /* Iterator offsets for foreach_neighbor*() */
170 int nei8
[8], dnei
[4];
173 struct move last_move
;
174 struct move last_move2
; /* second-to-last move */
175 struct move last_move3
; /* just before last_move2, only set if last_move is pass */
176 struct move last_move4
; /* just before last_move3, only set if last_move & last_move2 are pass */
177 /* Whether we tried to add a hash twice; board_play*() can
178 * set this, but it will still carry out the move as well! */
179 bool superko_violation
;
181 /* The following two structures are goban maps and are indexed by
182 * coord.pos. The map is surrounded by a one-point margin from
183 * S_OFFBOARD stones in order to speed up some internal loops.
184 * Some of the foreach iterators below might include these points;
185 * you need to handle them yourselves, if you need to. */
187 /* Stones played on the board */
188 enum stone
*b
; /* enum stone */
189 /* Group id the stones are part of; 0 == no group */
191 /* Positions of next stones in the stone group; 0 == last stone */
193 /* Neighboring colors; numbers of neighbors of index color */
194 struct neighbor_colors
*n
;
195 /* Zobrist hash for each position */
197 #ifdef BOARD_SPATHASH
198 /* For spatial hashes, we use only 24 bits. */
199 /* [0] is d==1, we don't keep hash for d==0. */
200 /* We keep hashes for black-to-play ([][0]) and white-to-play
201 * ([][1], reversed stone colors since we match all patterns as
203 uint32_t (*spathash
)[BOARD_SPATHASH_MAXD
][2];
206 /* 3x3 pattern code for each position; see pattern3.h for encoding
207 * specification. The information is only valid for empty points. */
211 /* Incrementally matched point traits information, black-to-play
212 * ([][0]) and white-to-play ([][1]). */
213 /* The information is only valid for empty points. */
214 struct btraits (*t
)[2];
216 /* Cached information on x-y coordinates so that we avoid division. */
219 /* Group information - indexed by gid (which is coord of base group stone) */
222 /* Positions of free positions - queue (not map) */
223 /* Note that free position here is any valid move; including single-point eyes!
224 * However, pass is not included. */
225 coord_t
*f
; int flen
;
228 /* Queue of capturable groups */
229 group_t
*c
; int clen
;
233 /* Queue of positions that need their traits updated */
234 coord_t
*tq
; int tqlen
;
237 /* Symmetry information */
238 struct board_symmetry symmetry
;
240 /* Last ko played on the board. */
247 /* Engine-specific state; persistent through board development,
248 * is reset only at clear_board. */
251 /* Playout-specific state; persistent through board development,
252 * but its lifetime is maintained in play_random_game(); it should
253 * not be set outside of it. */
257 /* --- PRIVATE DATA --- */
259 /* For superko check: */
261 /* Board "history" - hashes encountered. Size of the hash should be
262 * >> board_size^2. */
263 #define history_hash_bits 12
264 #define history_hash_mask ((1 << history_hash_bits) - 1)
265 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
266 #define history_hash_next(i) ((i + 1) & history_hash_mask)
267 hash_t history_hash
[1 << history_hash_bits
];
268 /* Hash of current board position. */
270 /* Hash of current board position quadrants. */
275 /* Avoid unused variable warnings */
276 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
277 #define board_size2(b_) (board_size(b_) * board_size(b_))
279 #define board_size(b_) ((b_)->size)
280 #define board_size2(b_) ((b_)->size2)
283 /* This is a shortcut for taking different action on smaller
284 * and large boards (e.g. picking different variable defaults).
285 * This is of course less optimal than fine-tuning dependency
286 * function of values on board size, but that is difficult and
287 * possibly not very rewarding if you are interested just in
289 #define board_large(b_) (board_size(b_)-2 >= 15)
290 #define board_small(b_) (board_size(b_)-2 <= 9)
293 # define board_bits2(b_) 9
294 #elif BOARD_SIZE == 13
295 # define board_bits2(b_) 8
296 #elif BOARD_SIZE == 9
297 # define board_bits2(b_) 7
299 # define board_bits2(b_) ((b_)->bits2)
302 #define board_at(b_, c) ((b_)->b[c])
303 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
305 #define group_at(b_, c) ((b_)->g[c])
306 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
308 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
309 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
310 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
311 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
312 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
313 #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))
315 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
317 #define groupnext_at(b_, c) ((b_)->p[c])
318 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
320 #define group_base(g_) (g_)
321 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
322 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
323 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
324 /* board_group_other_lib() makes sense only for groups with two liberties. */
325 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
327 #define neighboring_groups_list(b_, filter_, coord_, groups, groups_n, groupsbycolor) \
328 group_t groups[4]; int groups_n = 0; \
329 int groupsbycolor[S_MAX] = {0, 0, 0, 0}; \
330 foreach_neighbor((b_), (coord_), { \
331 if (!(filter_)) continue; \
332 enum stone s = board_at(b, c); \
333 group_t g_ = group_at((b_), c); \
334 if (board_group_info((b_), g_).libs == 2) { \
335 groups[groups_n++] = g_; \
336 groupsbycolor[s]++; \
340 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
342 struct board
*board_init(char *fbookfile
);
343 struct board
*board_copy(struct board
*board2
, struct board
*board1
);
344 void board_done_noalloc(struct board
*board
);
345 void board_done(struct board
*board
);
346 /* size here is without the S_OFFBOARD margin. */
347 void board_resize(struct board
*board
, int size
);
348 void board_clear(struct board
*board
);
351 typedef char *(*board_cprint
)(struct board
*b
, coord_t c
, char *s
, char *end
);
352 void board_print(struct board
*board
, FILE *f
);
353 void board_print_custom(struct board
*board
, FILE *f
, board_cprint cprint
);
355 /* Place given handicap on the board; coordinates are printed to f. */
356 void board_handicap(struct board
*board
, int stones
, FILE *f
);
358 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
359 int board_play(struct board
*board
, struct move
*m
);
360 /* Like above, but plays random move; the move coordinate is recorded
361 * to *coord. This method will never fill your own eye. pass is played
362 * when no move can be played. You can impose extra restrictions if you
363 * supply your own permit function; the permit function can also modify
364 * the move coordinate to redirect the move elsewhere. */
365 typedef bool (*ppr_permit
)(void *data
, struct board
*b
, struct move
*m
);
366 void board_play_random(struct board
*b
, enum stone color
, coord_t
*coord
, ppr_permit permit
, void *permit_data
);
368 /*Undo, supported only for pass moves. Returns -1 on error, 0 otherwise. */
369 int board_undo(struct board
*board
);
371 /* Returns true if given move can be played. */
372 static bool board_is_valid_play(struct board
*b
, enum stone color
, coord_t coord
);
373 static bool board_is_valid_move(struct board
*b
, struct move
*m
);
374 /* Returns true if ko was just taken. */
375 static bool board_playing_ko_threat(struct board
*b
);
376 /* Returns 0 or ID of neighboring group in atari. */
377 static group_t
board_get_atari_neighbor(struct board
*b
, coord_t coord
, enum stone group_color
);
378 /* Returns true if the move is not obvious self-atari. */
379 static bool board_safe_to_play(struct board
*b
, coord_t coord
, enum stone color
);
381 /* Determine number of stones in a group, up to @max stones. */
382 static int group_stone_count(struct board
*b
, group_t group
, int max
);
384 /* Adjust symmetry information as if given coordinate has been played. */
385 void board_symmetry_update(struct board
*b
, struct board_symmetry
*symmetry
, coord_t c
);
386 /* Check if coordinates are within symmetry base. (If false, they can
387 * be derived from the base.) */
388 static bool board_coord_in_symmetry(struct board
*b
, coord_t c
);
390 /* Returns true if given coordinate has all neighbors of given color or the edge. */
391 static bool board_is_eyelike(struct board
*board
, coord_t coord
, enum stone eye_color
);
392 /* Returns true if given coordinate could be a false eye; this check makes
393 * sense only if you already know the coordinate is_eyelike(). */
394 bool board_is_false_eyelike(struct board
*board
, coord_t coord
, enum stone eye_color
);
395 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
396 * at least tries to). */
397 bool board_is_one_point_eye(struct board
*board
, coord_t c
, enum stone eye_color
);
398 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
399 enum stone
board_get_one_point_eye(struct board
*board
, coord_t c
);
401 /* board_official_score() is the scoring method for yielding score suitable
402 * for external presentation. For fast scoring of entirely filled boards
403 * (e.g. playouts), use board_fast_score(). */
404 /* Positive: W wins */
405 /* Compare number of stones + 1pt eyes. */
406 floating_t
board_fast_score(struct board
*board
);
407 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
409 floating_t
board_official_score(struct board
*board
, struct move_queue
*mq
);
411 /* Set board rules according to given string. Returns false in case
412 * of unknown ruleset name. */
413 bool board_set_rules(struct board
*board
, char *name
);
417 #define foreach_point(board_) \
420 for (; c < board_size(board_) * board_size(board_); c++)
421 #define foreach_point_and_pass(board_) \
424 for (; c < board_size(board_) * board_size(board_); c++)
425 #define foreach_point_end \
428 #define foreach_free_point(board_) \
430 int fmax__ = (board_)->flen; \
431 for (int f__ = 0; f__ < fmax__; f__++) { \
432 coord_t c = (board_)->f[f__];
433 #define foreach_free_point_end \
437 #define foreach_in_group(board_, group_) \
439 struct board *board__ = board_; \
440 coord_t c = group_base(group_); \
441 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
443 #define foreach_in_group_end \
444 c = c2; c2 = groupnext_at(board__, c2); \
448 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
449 * on S_OFFBOARD coordinates. */
450 #define foreach_neighbor(board_, coord_, loop_body) \
452 struct board *board__ = board_; \
453 coord_t coord__ = coord_; \
455 c = coord__ - board_size(board__); do { loop_body } while (0); \
456 c = coord__ - 1; do { loop_body } while (0); \
457 c = coord__ + 1; do { loop_body } while (0); \
458 c = coord__ + board_size(board__); do { loop_body } while (0); \
461 #define foreach_8neighbor(board_, coord_) \
464 coord_t c = (coord_); \
465 for (fn__i = 0; fn__i < 8; fn__i++) { \
466 c += (board_)->nei8[fn__i];
467 #define foreach_8neighbor_end \
471 #define foreach_diag_neighbor(board_, coord_) \
474 coord_t c = (coord_); \
475 for (fn__i = 0; fn__i < 4; fn__i++) { \
476 c += (board_)->dnei[fn__i];
477 #define foreach_diag_neighbor_end \
483 board_is_eyelike(struct board
*board
, coord_t coord
, enum stone eye_color
)
485 return (neighbor_count_at(board
, coord
, eye_color
)
486 + neighbor_count_at(board
, coord
, S_OFFBOARD
)) == 4;
490 board_is_valid_play(struct board
*board
, enum stone color
, coord_t coord
)
492 if (board_at(board
, coord
) != S_NONE
)
494 if (!board_is_eyelike(board
, coord
, stone_other(color
)))
496 /* Play within {true,false} eye-ish formation */
497 if (board
->ko
.coord
== coord
&& board
->ko
.color
== color
)
500 /* XXX: Disallows suicide. */
501 return trait_at(board
, coord
, color
).cap
> 0;
503 int groups_in_atari
= 0;
504 foreach_neighbor(board
, coord
, {
505 group_t g
= group_at(board
, c
);
506 groups_in_atari
+= (board_group_info(board
, g
).libs
== 1);
508 return !!groups_in_atari
;
513 board_is_valid_move(struct board
*board
, struct move
*m
)
515 return board_is_valid_play(board
, m
->color
, m
->coord
);
519 board_playing_ko_threat(struct board
*b
)
521 return !is_pass(b
->ko
.coord
);
524 static inline group_t
525 board_get_atari_neighbor(struct board
*b
, coord_t coord
, enum stone group_color
)
528 if (!trait_at(b
, coord
, stone_other(group_color
)).cap
) return 0;
530 foreach_neighbor(b
, coord
, {
531 group_t g
= group_at(b
, c
);
532 if (g
&& board_at(b
, c
) == group_color
&& board_group_info(b
, g
).libs
== 1)
534 /* We return first match. */
540 board_safe_to_play(struct board
*b
, coord_t coord
, enum stone color
)
542 /* number of free neighbors */
543 int libs
= immediate_liberty_count(b
, coord
);
548 /* number of capturable enemy groups */
549 if (trait_at(b
, coord
, color
).cap
> 0)
550 return true; // XXX: We don't account for snapback.
551 /* number of non-capturable friendly groups */
552 int noncap_ours
= neighbor_count_at(b
, coord
, color
) - trait_at(b
, coord
, stone_other(color
)).cap
;
558 /* ok, but we need to check if they don't have just two libs. */
560 foreach_neighbor(b
, coord
, {
562 if (board_at(b
, c
) == stone_other(color
) && board_group_info(b
, group_at(b
, c
)).libs
== 1)
563 return true; // can capture; no snapback check
565 if (board_at(b
, c
) != color
) continue;
566 group_t g
= group_at(b
, c
);
567 if (board_group_info(b
, g
).libs
== 1) continue; // in atari
568 if (board_group_info(b
, g
).libs
== 2) { // two liberties
569 if (libs
> 0) return true; // we already have one real liberty
570 /* we might be connecting two 2-lib groups, which is ok;
571 * so remember the other liberty and just make sure it's
572 * not the same one */
573 if (onelib
>= 0 && c
!= onelib
) return true;
574 onelib
= board_group_other_lib(b
, g
, c
);
580 // no good support group
585 group_stone_count(struct board
*b
, group_t group
, int max
)
588 foreach_in_group(b
, group
) {
590 if (n
>= max
) return max
;
591 } foreach_in_group_end
;
596 board_coord_in_symmetry(struct board
*b
, coord_t c
)
598 if (coord_y(c
, b
) < b
->symmetry
.y1
|| coord_y(c
, b
) > b
->symmetry
.y2
)
600 if (coord_x(c
, b
) < b
->symmetry
.x1
|| coord_x(c
, b
) > b
->symmetry
.x2
)
603 int x
= coord_x(c
, b
);
604 if (b
->symmetry
.type
== SYM_DIAG_DOWN
)
605 x
= board_size(b
) - 1 - x
;
606 if (x
> coord_y(c
, b
))