Introduce Fuego-compatible forcing opening book (fbook)
[pachi/ann.git] / board.c
blobd94e10cc75012d0752a06d45ac67a50c8d7d1e95
1 #include <alloca.h>
2 #include <assert.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 //#define DEBUG
9 #include "board.h"
10 #include "debug.h"
11 #include "fbook.h"
12 #include "mq.h"
13 #include "random.h"
15 #ifdef BOARD_SPATHASH
16 #include "patternsp.h"
17 #endif
18 #ifdef BOARD_PAT3
19 #include "pattern3.h"
20 #endif
21 #ifdef BOARD_TRAITS
22 static void board_trait_recompute(struct board *board, coord_t coord);
23 #include "tactics/selfatari.h"
24 #endif
25 #ifdef BOARD_GAMMA
26 #include "pattern.h"
27 #endif
30 #if 0
31 #define profiling_noinline __attribute__((noinline))
32 #else
33 #define profiling_noinline
34 #endif
36 #define gi_granularity 4
37 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
40 static void
41 board_setup(struct board *b)
43 char *fbookfile = b->fbookfile;
45 memset(b, 0, sizeof(*b));
47 b->fbookfile = fbookfile;
49 struct move m = { pass, S_NONE };
50 b->last_move = b->last_move2 = b->last_ko = b->ko = m;
53 struct board *
54 board_init(char *fbookfile)
56 struct board *b = malloc2(sizeof(struct board));
57 board_setup(b);
59 b->fbookfile = fbookfile;
61 // Default setup
62 b->size = 9 + 2;
63 board_clear(b);
65 return b;
68 static size_t
69 board_alloc(struct board *board)
71 /* We do not allocate the board structure itself but we allocate
72 * all the arrays with board contents. */
74 int bsize = board_size2(board) * sizeof(*board->b);
75 int gsize = board_size2(board) * sizeof(*board->g);
76 int fsize = board_size2(board) * sizeof(*board->f);
77 int nsize = board_size2(board) * sizeof(*board->n);
78 int psize = board_size2(board) * sizeof(*board->p);
79 int hsize = board_size2(board) * 2 * sizeof(*board->h);
80 int gisize = board_size2(board) * sizeof(*board->gi);
81 #ifdef WANT_BOARD_C
82 int csize = board_size2(board) * sizeof(*board->c);
83 #else
84 int csize = 0;
85 #endif
86 #ifdef BOARD_SPATHASH
87 int ssize = board_size2(board) * sizeof(*board->spathash);
88 #else
89 int ssize = 0;
90 #endif
91 #ifdef BOARD_PAT3
92 int p3size = board_size2(board) * sizeof(*board->pat3);
93 #else
94 int p3size = 0;
95 #endif
96 #ifdef BOARD_TRAITS
97 int tsize = board_size2(board) * sizeof(*board->t);
98 int tqsize = board_size2(board) * sizeof(*board->t);
99 #else
100 int tsize = 0;
101 int tqsize = 0;
102 #endif
103 #ifdef BOARD_GAMMA
104 int pbsize = board_size2(board) * sizeof(*board->prob[0].items);
105 int rowpbsize = board_size(board) * sizeof(*board->prob[0].rowtotals);
106 #else
107 int pbsize = 0;
108 int rowpbsize = 0;
109 #endif
110 int cdsize = board_size2(board) * sizeof(*board->coord);
112 size_t size = bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + (pbsize + rowpbsize) * 2 + cdsize;
113 void *x = malloc2(size);
115 /* board->b must come first */
116 board->b = x; x += bsize;
117 board->g = x; x += gsize;
118 board->f = x; x += fsize;
119 board->p = x; x += psize;
120 board->n = x; x += nsize;
121 board->h = x; x += hsize;
122 board->gi = x; x += gisize;
123 #ifdef WANT_BOARD_C
124 board->c = x; x += csize;
125 #endif
126 #ifdef BOARD_SPATHASH
127 board->spathash = x; x += ssize;
128 #endif
129 #ifdef BOARD_PAT3
130 board->pat3 = x; x += p3size;
131 #endif
132 #ifdef BOARD_TRAITS
133 board->t = x; x += tsize;
134 board->tq = x; x += tqsize;
135 #endif
136 #ifdef BOARD_GAMMA
137 board->prob[0].items = x; x += pbsize;
138 board->prob[1].items = x; x += pbsize;
139 board->prob[0].rowtotals = x; x += rowpbsize;
140 board->prob[1].rowtotals = x; x += rowpbsize;
141 #endif
142 board->coord = x; x += cdsize;
144 return size;
147 struct board *
148 board_copy(struct board *b2, struct board *b1)
150 memcpy(b2, b1, sizeof(struct board));
152 size_t size = board_alloc(b2);
153 memcpy(b2->b, b1->b, size);
155 return b2;
158 void
159 board_done_noalloc(struct board *board)
161 if (board->b) free(board->b);
162 if (board->fbook) fbook_done(board->fbook);
165 void
166 board_done(struct board *board)
168 board_done_noalloc(board);
169 free(board);
172 void
173 board_resize(struct board *board, int size)
175 #ifdef BOARD_SIZE
176 assert(board_size(board) == size + 2);
177 #endif
178 assert(size <= BOARD_MAX_SIZE);
179 board->size = size + 2 /* S_OFFBOARD margin */;
180 board->size2 = board_size(board) * board_size(board);
182 board->bits2 = 1;
183 while ((1 << board->bits2) < board->size2) board->bits2++;
185 if (board->b)
186 free(board->b);
188 size_t asize = board_alloc(board);
189 memset(board->b, 0, asize);
192 void
193 board_clear(struct board *board)
195 int size = board_size(board);
196 float komi = board->komi;
198 board_done_noalloc(board);
199 board_setup(board);
200 board_resize(board, size - 2 /* S_OFFBOARD margin */);
202 board->komi = komi;
204 /* Setup neighborhood iterators */
205 board->nei8[0] = -size - 1; // (-1,-1)
206 board->nei8[1] = 1;
207 board->nei8[2] = 1;
208 board->nei8[3] = size - 2; // (-1,0)
209 board->nei8[4] = 2;
210 board->nei8[5] = size - 2; // (-1,1)
211 board->nei8[6] = 1;
212 board->nei8[7] = 1;
213 board->dnei[0] = -size - 1;
214 board->dnei[1] = 2;
215 board->dnei[2] = size*2 - 2;
216 board->dnei[3] = 2;
218 /* Setup initial symmetry */
219 board->symmetry.d = 1;
220 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
221 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
222 board->symmetry.type = SYM_FULL;
224 /* Set up coordinate cache */
225 foreach_point(board) {
226 board->coord[c][0] = c % board_size(board);
227 board->coord[c][1] = c / board_size(board);
228 } foreach_point_end;
230 /* Draw the offboard margin */
231 int top_row = board_size2(board) - board_size(board);
232 int i;
233 for (i = 0; i < board_size(board); i++)
234 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
235 for (i = 0; i <= top_row; i += board_size(board))
236 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
238 foreach_point(board) {
239 coord_t coord = c;
240 if (board_at(board, coord) == S_OFFBOARD)
241 continue;
242 foreach_neighbor(board, c, {
243 inc_neighbor_count_at(board, coord, board_at(board, c));
244 } );
245 } foreach_point_end;
247 /* All positions are free! Except the margin. */
248 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
249 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
250 board->f[board->flen++] = i;
252 /* Initialize zobrist hashtable. */
253 /* We will need these to be stable across Pachi runs for
254 * certain kinds of pattern matching, thus we do not use
255 * fast_random() for this. */
256 hash_t hseed = 0x3121110101112131;
257 foreach_point(board) {
258 board->h[c * 2] = (hseed *= 16807);
259 if (!board->h[c * 2])
260 board->h[c * 2] = 1;
261 /* And once again for white */
262 board->h[c * 2 + 1] = (hseed *= 16807);
263 if (!board->h[c * 2 + 1])
264 board->h[c * 2 + 1] = 1;
265 } foreach_point_end;
267 #ifdef BOARD_SPATHASH
268 /* Initialize spatial hashes. */
269 foreach_point(board) {
270 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
271 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
272 ptcoords_at(x, y, c, board, j);
273 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
274 pthashes[0][j][board_at(board, c)];
275 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
276 pthashes[0][j][stone_other(board_at(board, c))];
279 } foreach_point_end;
280 #endif
281 #ifdef BOARD_PAT3
282 /* Initialize 3x3 pattern codes. */
283 foreach_point(board) {
284 if (board_at(board, c) == S_NONE)
285 board->pat3[c] = pattern3_hash(board, c);
286 } foreach_point_end;
287 #endif
288 #ifdef BOARD_TRAITS
289 /* Initialize traits. */
290 foreach_point(board) {
291 trait_at(board, c, S_BLACK).cap = 0;
292 trait_at(board, c, S_BLACK).cap1 = 0;
293 trait_at(board, c, S_BLACK).safe = true;
294 trait_at(board, c, S_WHITE).cap = 0;
295 trait_at(board, c, S_WHITE).cap1 = 0;
296 trait_at(board, c, S_WHITE).safe = true;
297 } foreach_point_end;
298 #endif
299 #ifdef BOARD_GAMMA
300 board->prob[0].b = board->prob[1].b = board;
301 foreach_point(board) {
302 probdist_set(&board->prob[0], c, double_to_fixp((board_at(board, c) == S_NONE) * 1.0f));
303 probdist_set(&board->prob[1], c, double_to_fixp((board_at(board, c) == S_NONE) * 1.0f));
304 } foreach_point_end;
305 #endif
307 if (board->fbookfile) {
308 board->fbook = fbook_init(board->fbookfile, board);
312 static char *
313 board_print_top(struct board *board, char *s, char *end, int c)
315 for (int i = 0; i < c; i++) {
316 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
317 s += snprintf(s, end - s, " ");
318 for (int x = 1; x < board_size(board) - 1; x++)
319 s += snprintf(s, end - s, "%c ", asdf[x - 1]);
320 s += snprintf(s, end -s, " ");
322 s += snprintf(s, end - s, "\n");
323 for (int i = 0; i < c; i++) {
324 s += snprintf(s, end - s, " +-");
325 for (int x = 1; x < board_size(board) - 1; x++)
326 s += snprintf(s, end - s, "--");
327 s += snprintf(s, end - s, "+");
329 s += snprintf(s, end - s, "\n");
330 return s;
333 static char *
334 board_print_bottom(struct board *board, char *s, char *end, int c)
336 for (int i = 0; i < c; i++) {
337 s += snprintf(s, end - s, " +-");
338 for (int x = 1; x < board_size(board) - 1; x++)
339 s += snprintf(s, end - s, "--");
340 s += snprintf(s, end - s, "+");
342 s += snprintf(s, end - s, "\n");
343 return s;
346 static char *
347 board_print_row(struct board *board, int y, char *s, char *end, board_cprint cprint)
349 s += snprintf(s, end - s, " %2d | ", y);
350 for (int x = 1; x < board_size(board) - 1; x++) {
351 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
352 s += snprintf(s, end - s, "%c)", stone2char(board_atxy(board, x, y)));
353 else
354 s += snprintf(s, end - s, "%c ", stone2char(board_atxy(board, x, y)));
356 s += snprintf(s, end - s, "|");
357 if (cprint) {
358 s += snprintf(s, end - s, " %2d | ", y);
359 for (int x = 1; x < board_size(board) - 1; x++) {
360 s = cprint(board, coord_xy(board, x, y), s, end);
362 s += snprintf(s, end - s, "|");
364 s += snprintf(s, end - s, "\n");
365 return s;
368 void
369 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
371 char buf[10240];
372 char *s = buf;
373 char *end = buf + sizeof(buf);
374 s += snprintf(s, end - s, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
375 board->moves, board->komi, board->handicap,
376 board->captures[S_BLACK], board->captures[S_WHITE]);
377 s = board_print_top(board, s, end, 1 + !!cprint);
378 for (int y = board_size(board) - 2; y >= 1; y--)
379 s = board_print_row(board, y, s, end, cprint);
380 board_print_bottom(board, s, end, 1 + !!cprint);
381 fprintf(f, "%s\n", buf);
384 static char *
385 cprint_group(struct board *board, coord_t c, char *s, char *end)
387 s += snprintf(s, end - s, "%d ", group_base(group_at(board, c)));
388 return s;
391 void
392 board_print(struct board *board, FILE *f)
394 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
397 void
398 board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari)
400 #ifdef BOARD_GAMMA
401 b->gamma = gamma;
402 b->precise_selfatari = precise_selfatari;
403 #ifdef BOARD_TRAITS
404 for (int i = 0; i < b->flen; i++) {
405 board_trait_recompute(b, b->f[i]);
407 #endif
408 #endif
412 /* Update the probability distribution we maintain incrementally. */
413 void
414 board_gamma_update(struct board *board, coord_t coord, enum stone color)
416 #if defined(BOARD_GAMMA) && defined(BOARD_TRAITS)
417 if (!board->gamma)
418 return;
420 /* Punch out invalid moves and moves filling our own eyes. */
421 if (board_at(board, coord) != S_NONE
422 || (board_is_eyelike(board, coord, stone_other(color))
423 && !trait_at(board, coord, color).cap)
424 || (board_is_one_point_eye(board, coord, color))) {
425 probdist_set(&board->prob[color - 1], coord, 0);
426 return;
429 hash3_t pat = board->pat3[coord];
430 if (color == S_WHITE) {
431 /* We work with the pattern3s as black-to-play. */
432 pat = pattern3_reverse(pat);
435 /* We just quickly replicate the general pattern matcher stuff
436 * here in the most bare-bone way. */
437 double value = board->gamma->gamma[FEAT_PATTERN3][pat];
438 if (trait_at(board, coord, color).cap) {
439 int i = 0;
440 i |= (trait_at(board, coord, color).cap1 == trait_at(board, coord, color).cap) << PF_CAPTURE_1STONE;
441 i |= (!trait_at(board, coord, stone_other(color)).safe) << PF_CAPTURE_TRAPPED;
442 i |= (trait_at(board, coord, color).cap < neighbor_count_at(board, coord, stone_other(color))) << PF_CAPTURE_CONNECTION;
443 value *= board->gamma->gamma[FEAT_CAPTURE][i];
445 if (trait_at(board, coord, stone_other(color)).cap) {
446 int i = 0;
447 i |= (trait_at(board, coord, stone_other(color)).cap1 == trait_at(board, coord, stone_other(color)).cap) << PF_AESCAPE_1STONE;
448 i |= (!trait_at(board, coord, color).safe) << PF_AESCAPE_TRAPPED;
449 i |= (trait_at(board, coord, stone_other(color)).cap < neighbor_count_at(board, coord, color)) << PF_AESCAPE_CONNECTION;
450 value *= board->gamma->gamma[FEAT_AESCAPE][i];
452 if (!trait_at(board, coord, color).safe)
453 value *= board->gamma->gamma[FEAT_SELFATARI][1 + board->precise_selfatari];
454 probdist_set(&board->prob[color - 1], coord, double_to_fixp(value));
455 #endif
458 #ifdef BOARD_TRAITS
459 static bool
460 board_trait_safe(struct board *board, coord_t coord, enum stone color)
462 if (board->precise_selfatari)
463 return !is_bad_selfatari(board, color, coord);
464 else
465 return board_safe_to_play(board, coord, color);
468 static void
469 board_trait_recompute(struct board *board, coord_t coord)
471 trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);;
472 trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
473 if (DEBUGL(8)) {
474 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d cap1=%d safe=%d) (white cap=%d cap1=%d safe=%d)\n",
475 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
476 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).cap1, trait_at(board, coord, S_BLACK).safe,
477 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).cap1, trait_at(board, coord, S_WHITE).safe);
479 board_gamma_update(board, coord, S_BLACK);
480 board_gamma_update(board, coord, S_WHITE);
482 #endif
484 /* Recompute traits for dirty points that we have previously touched
485 * somehow (libs of their neighbors changed or so). */
486 static void
487 board_traits_recompute(struct board *board)
489 #ifdef BOARD_TRAITS
490 for (int i = 0; i < board->tqlen; i++) {
491 coord_t coord = board->tq[i];
492 trait_at(board, coord, S_BLACK).dirty = false;
493 if (board_at(board, coord) != S_NONE)
494 continue;
495 board_trait_recompute(board, coord);
497 board->tqlen = 0;
498 #endif
501 /* Queue traits of given point for recomputing. */
502 static void
503 board_trait_queue(struct board *board, coord_t coord)
505 #ifdef BOARD_TRAITS
506 if (trait_at(board, coord, S_BLACK).dirty)
507 return;
508 board->tq[board->tqlen++] = coord;
509 trait_at(board, coord, S_BLACK).dirty = true;
510 #endif
514 /* Update board hash with given coordinate. */
515 static void profiling_noinline
516 board_hash_update(struct board *board, coord_t coord, enum stone color)
518 board->hash ^= hash_at(board, coord, color);
519 board->qhash[coord_quadrant(coord, board)] ^= hash_at(board, coord, color);
520 if (DEBUGL(8))
521 fprintf(stderr, "board_hash_update(%d,%d,%d) ^ %"PRIhash" -> %"PRIhash"\n", color, coord_x(coord, board), coord_y(coord, board), hash_at(board, coord, color), board->hash);
523 #ifdef BOARD_SPATHASH
524 /* Gridcular metric is reflective, so we update all hashes
525 * of appropriate ditance in OUR circle. */
526 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
527 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
528 ptcoords_at(x, y, coord, board, j);
529 /* We either changed from S_NONE to color
530 * or vice versa; doesn't matter. */
531 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
532 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
533 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
534 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
537 #endif
539 #if defined(BOARD_PAT3)
540 /* @color is not what we need in case of capture. */
541 static const int ataribits[8] = { -1, 0, -1, 1, 2, -1, 3, -1 };
542 enum stone new_color = board_at(board, coord);
543 bool in_atari = false;
544 if (new_color == S_NONE) {
545 board->pat3[coord] = pattern3_hash(board, coord);
546 } else {
547 in_atari = (board_group_info(board, group_at(board, coord)).libs == 1);
549 foreach_8neighbor(board, coord) {
550 /* Internally, the loop uses fn__i=[0..7]. We can use
551 * it directly to address bits within the bitmap of the
552 * neighbors since the bitmap order is reverse to the
553 * loop order. */
554 if (board_at(board, c) != S_NONE)
555 continue;
556 board->pat3[c] &= ~(3 << (fn__i*2));
557 board->pat3[c] |= new_color << (fn__i*2);
558 if (ataribits[fn__i] >= 0) {
559 board->pat3[c] &= ~(1 << (16 + ataribits[fn__i]));
560 board->pat3[c] |= in_atari << (16 + ataribits[fn__i]);
562 #if defined(BOARD_TRAITS)
563 board_trait_queue(board, c);
564 #elif defined(BOARD_GAMMA)
565 if (board->gamma) {
566 hash3_t pat = board->pat3[c];
567 if (color == S_WHITE) pat = pattern3_reverse(pat);
568 double value = board->gamma->gamma[FEAT_PATTERN3][pat];
569 probdist_set(&board->prob[color - 1], c, double_to_fixp(value));
571 #endif
572 } foreach_8neighbor_end;
573 #endif
576 /* Commit current board hash to history. */
577 static void profiling_noinline
578 board_hash_commit(struct board *board)
580 if (DEBUGL(8))
581 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
582 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
583 board->history_hash[board->hash & history_hash_mask] = board->hash;
584 } else {
585 hash_t i = board->hash;
586 while (board->history_hash[i & history_hash_mask]) {
587 if (board->history_hash[i & history_hash_mask] == board->hash) {
588 if (DEBUGL(5))
589 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
590 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
591 board->superko_violation = true;
592 return;
594 i = history_hash_next(i);
596 board->history_hash[i & history_hash_mask] = board->hash;
601 void
602 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
604 if (likely(symmetry->type == SYM_NONE)) {
605 /* Fully degenerated already. We do not support detection
606 * of restoring of symmetry, assuming that this is too rare
607 * a case to handle. */
608 return;
611 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
612 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
613 if (DEBUGL(6)) {
614 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
615 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
616 symmetry->d, symmetry->type, x, y);
619 switch (symmetry->type) {
620 case SYM_FULL:
621 if (x == t && y == t) {
622 /* Tengen keeps full symmetry. */
623 return;
625 /* New symmetry now? */
626 if (x == y) {
627 symmetry->type = SYM_DIAG_UP;
628 symmetry->x1 = symmetry->y1 = 1;
629 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
630 symmetry->d = 1;
631 } else if (dx == y) {
632 symmetry->type = SYM_DIAG_DOWN;
633 symmetry->x1 = symmetry->y1 = 1;
634 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
635 symmetry->d = 1;
636 } else if (x == t) {
637 symmetry->type = SYM_HORIZ;
638 symmetry->y1 = 1;
639 symmetry->y2 = board_size(b) - 1;
640 symmetry->d = 0;
641 } else if (y == t) {
642 symmetry->type = SYM_VERT;
643 symmetry->x1 = 1;
644 symmetry->x2 = board_size(b) - 1;
645 symmetry->d = 0;
646 } else {
647 break_symmetry:
648 symmetry->type = SYM_NONE;
649 symmetry->x1 = symmetry->y1 = 1;
650 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
651 symmetry->d = 0;
653 break;
654 case SYM_DIAG_UP:
655 if (x == y)
656 return;
657 goto break_symmetry;
658 case SYM_DIAG_DOWN:
659 if (dx == y)
660 return;
661 goto break_symmetry;
662 case SYM_HORIZ:
663 if (x == t)
664 return;
665 goto break_symmetry;
666 case SYM_VERT:
667 if (y == t)
668 return;
669 goto break_symmetry;
670 case SYM_NONE:
671 assert(0);
672 break;
675 if (DEBUGL(6)) {
676 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
677 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
678 symmetry->d, symmetry->type);
680 /* Whew. */
684 void
685 board_handicap_stone(struct board *board, int x, int y, FILE *f)
687 struct move m;
688 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
690 board_play(board, &m);
691 /* Simulate white passing; otherwise, UCT search can get confused since
692 * tree depth parity won't match the color to move. */
693 board->moves++;
695 char *str = coord2str(m.coord, board);
696 if (DEBUGL(1))
697 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
698 if (f) fprintf(f, "%s ", str);
699 free(str);
702 void
703 board_handicap(struct board *board, int stones, FILE *f)
705 int margin = 3 + (board_size(board) >= 13);
706 int min = margin;
707 int mid = board_size(board) / 2;
708 int max = board_size(board) - 1 - margin;
709 const int places[][2] = {
710 { min, min }, { max, max }, { max, min }, { min, max },
711 { min, mid }, { max, mid },
712 { mid, min }, { mid, max },
713 { mid, mid },
716 board->handicap = stones;
718 if (stones == 5 || stones == 7) {
719 board_handicap_stone(board, mid, mid, f);
720 stones--;
723 int i;
724 for (i = 0; i < stones; i++)
725 board_handicap_stone(board, places[i][0], places[i][1], f);
729 static void __attribute__((noinline))
730 check_libs_consistency(struct board *board, group_t g)
732 #ifdef DEBUG
733 if (!g) return;
734 struct group *gi = &board_group_info(board, g);
735 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
736 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
737 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
738 assert(0);
740 #endif
743 static void
744 check_pat3_consistency(struct board *board, coord_t coord)
746 #ifdef DEBUG
747 foreach_8neighbor(board, coord) {
748 if (board_at(board, c) == S_NONE && pattern3_hash(board, c) != board->pat3[c]) {
749 board_print(board, stderr);
750 fprintf(stderr, "%s(%d)->%s(%d) computed %x != stored %x (%d)\n", coord2sstr(coord, board), coord, coord2sstr(c, board), c, pattern3_hash(board, c), board->pat3[c], fn__i);
751 assert(0);
753 } foreach_8neighbor_end;
754 #endif
757 static void
758 board_capturable_add(struct board *board, group_t group, coord_t lib, bool onestone)
760 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
761 #ifdef BOARD_TRAITS
762 /* Increase capturable count trait of my last lib. */
763 enum stone capturing_color = stone_other(board_at(board, group));
764 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
765 foreach_neighbor(board, lib, {
766 if (DEBUGL(8) && group_at(board, c) == group)
767 fprintf(stderr, "%s[%d] %s cap bump bc of %s(%d) member %s onestone %d\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap, stone2str(capturing_color), coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board), onestone);
768 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
769 trait_at(board, lib, capturing_color).cap1 += (group_at(board, c) == group && onestone);
771 board_trait_queue(board, lib);
772 #endif
774 #ifdef BOARD_PAT3
775 int fn__i = 0;
776 foreach_neighbor(board, lib, {
777 board->pat3[lib] |= (group_at(board, c) == group) << (16 + 3 - fn__i);
778 fn__i++;
780 #endif
782 #ifdef WANT_BOARD_C
783 /* Update the list of capturable groups. */
784 assert(group);
785 assert(board->clen < board_size2(board));
786 board->c[board->clen++] = group;
787 #endif
789 static void
790 board_capturable_rm(struct board *board, group_t group, coord_t lib, bool onestone)
792 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
793 #ifdef BOARD_TRAITS
794 /* Decrease capturable count trait of my previously-last lib. */
795 enum stone capturing_color = stone_other(board_at(board, group));
796 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
797 foreach_neighbor(board, lib, {
798 if (DEBUGL(8) && group_at(board, c) == group)
799 fprintf(stderr, "%s[%d] cap dump bc of %s(%d) member %s onestone %d\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap, coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board), onestone);
800 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
801 trait_at(board, lib, capturing_color).cap1 -= (group_at(board, c) == group && onestone);
803 board_trait_queue(board, lib);
804 #endif
806 #ifdef BOARD_PAT3
807 int fn__i = 0;
808 foreach_neighbor(board, lib, {
809 board->pat3[lib] &= ~((group_at(board, c) == group) << (16 + 3 - fn__i));
810 fn__i++;
812 #endif
814 #ifdef WANT_BOARD_C
815 /* Update the list of capturable groups. */
816 for (int i = 0; i < board->clen; i++) {
817 if (unlikely(board->c[i] == group)) {
818 board->c[i] = board->c[--board->clen];
819 return;
822 fprintf(stderr, "rm of bad group %d\n", group_base(group));
823 assert(0);
824 #endif
827 static void
828 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
830 #ifdef BOARD_TRAITS
831 board_trait_queue(board, lib1);
832 board_trait_queue(board, lib2);
833 #endif
835 static void
836 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
838 #ifdef BOARD_TRAITS
839 board_trait_queue(board, lib1);
840 board_trait_queue(board, lib2);
841 #endif
844 static void
845 board_group_addlib(struct board *board, group_t group, coord_t coord)
847 if (DEBUGL(7)) {
848 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
849 group_base(group), coord2sstr(group_base(group), board),
850 board_group_info(board, group).libs, coord2sstr(coord, board));
853 check_libs_consistency(board, group);
855 struct group *gi = &board_group_info(board, group);
856 bool onestone = group_is_onestone(board, group);
857 if (gi->libs < GROUP_KEEP_LIBS) {
858 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
859 #if 0
860 /* Seems extra branch just slows it down */
861 if (!gi->lib[i])
862 break;
863 #endif
864 if (unlikely(gi->lib[i] == coord))
865 return;
867 if (gi->libs == 0) {
868 board_capturable_add(board, group, coord, onestone);
869 } else if (gi->libs == 1) {
870 board_capturable_rm(board, group, gi->lib[0], onestone);
871 board_atariable_add(board, group, gi->lib[0], coord);
872 } else if (gi->libs == 2) {
873 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
875 gi->lib[gi->libs++] = coord;
878 check_libs_consistency(board, group);
881 static void
882 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
884 /* Add extra liberty from the board to our liberty list. */
885 unsigned char watermark[board_size2(board) / 8];
886 memset(watermark, 0, sizeof(watermark));
887 #define watermark_get(c) (watermark[c >> 3] & (1 << (c & 7)))
888 #define watermark_set(c) watermark[c >> 3] |= (1 << (c & 7))
890 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
891 watermark_set(gi->lib[i]);
892 watermark_set(avoid);
894 foreach_in_group(board, group) {
895 coord_t coord2 = c;
896 foreach_neighbor(board, coord2, {
897 if (board_at(board, c) + watermark_get(c) != S_NONE)
898 continue;
899 watermark_set(c);
900 gi->lib[gi->libs++] = c;
901 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
902 return;
903 } );
904 } foreach_in_group_end;
905 #undef watermark_get
906 #undef watermark_set
909 static void
910 board_group_rmlib(struct board *board, group_t group, coord_t coord)
912 if (DEBUGL(7)) {
913 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
914 group_base(group), coord2sstr(group_base(group), board),
915 board_group_info(board, group).libs, coord2sstr(coord, board));
918 struct group *gi = &board_group_info(board, group);
919 bool onestone = group_is_onestone(board, group);
920 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
921 #if 0
922 /* Seems extra branch just slows it down */
923 if (!gi->lib[i])
924 break;
925 #endif
926 if (likely(gi->lib[i] != coord))
927 continue;
929 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
930 gi->lib[gi->libs] = 0;
932 check_libs_consistency(board, group);
934 /* Postpone refilling lib[] until we need to. */
935 assert(GROUP_REFILL_LIBS > 1);
936 if (gi->libs > GROUP_REFILL_LIBS)
937 return;
938 if (gi->libs == GROUP_REFILL_LIBS)
939 board_group_find_extra_libs(board, group, gi, coord);
941 if (gi->libs == 2) {
942 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
943 } else if (gi->libs == 1) {
944 board_capturable_add(board, group, gi->lib[0], onestone);
945 board_atariable_rm(board, group, gi->lib[0], lib);
946 } else if (gi->libs == 0)
947 board_capturable_rm(board, group, lib, onestone);
948 return;
951 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
952 * can call this multiple times per coord. */
953 check_libs_consistency(board, group);
954 return;
958 /* This is a low-level routine that doesn't maintain consistency
959 * of all the board data structures. */
960 static void
961 board_remove_stone(struct board *board, group_t group, coord_t c)
963 enum stone color = board_at(board, c);
964 board_at(board, c) = S_NONE;
965 group_at(board, c) = 0;
966 board_hash_update(board, c, color);
967 #ifdef BOARD_TRAITS
968 /* We mark as cannot-capture now. If this is a ko/snapback,
969 * we will get incremented later in board_group_addlib(). */
970 trait_at(board, c, S_BLACK).cap = trait_at(board, c, S_BLACK).cap1 = 0;
971 trait_at(board, c, S_WHITE).cap = trait_at(board, c, S_WHITE).cap1 = 0;
972 board_trait_queue(board, c);
973 #endif
975 /* Increase liberties of surrounding groups */
976 coord_t coord = c;
977 foreach_neighbor(board, coord, {
978 dec_neighbor_count_at(board, c, color);
979 board_trait_queue(board, c);
980 group_t g = group_at(board, c);
981 if (g && g != group)
982 board_group_addlib(board, g, coord);
985 #ifdef BOARD_PAT3
986 /* board_hash_update() might have seen the freed up point as able
987 * to capture another group in atari that only after the loop
988 * above gained enough liberties. Reset pat3 again. */
989 board->pat3[c] = pattern3_hash(board, c);
990 #endif
992 if (DEBUGL(6))
993 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
994 board->f[board->flen++] = c;
997 static int profiling_noinline
998 board_group_capture(struct board *board, group_t group)
1000 int stones = 0;
1002 foreach_in_group(board, group) {
1003 board->captures[stone_other(board_at(board, c))]++;
1004 board_remove_stone(board, group, c);
1005 stones++;
1006 } foreach_in_group_end;
1008 struct group *gi = &board_group_info(board, group);
1009 assert(gi->libs == 0);
1010 memset(gi, 0, sizeof(*gi));
1012 return stones;
1016 static void profiling_noinline
1017 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
1019 #ifdef BOARD_TRAITS
1020 struct group *gi = &board_group_info(board, group);
1021 bool onestone = group_is_onestone(board, group);
1023 if (gi->libs == 1) {
1024 /* Our group is temporarily in atari; make sure the capturable
1025 * counts also correspond to the newly added stone before we
1026 * start adding liberties again so bump-dump ops match. */
1027 enum stone capturing_color = stone_other(board_at(board, group));
1028 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1030 coord_t lib = board_group_info(board, group).lib[0];
1031 if (coord_is_adjecent(lib, coord, board)) {
1032 if (DEBUGL(8))
1033 fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1034 trait_at(board, lib, capturing_color).cap++;
1035 /* This is never a 1-stone group, obviously. */
1036 board_trait_queue(board, lib);
1039 if (onestone) {
1040 /* We are not 1-stone group anymore, update the cap1
1041 * counter specifically. */
1042 foreach_neighbor(board, group, {
1043 if (board_at(board, c) != S_NONE) continue;
1044 trait_at(board, c, capturing_color).cap1--;
1045 board_trait_queue(board, c);
1049 #endif
1051 group_at(board, coord) = group;
1052 groupnext_at(board, coord) = groupnext_at(board, prevstone);
1053 groupnext_at(board, prevstone) = coord;
1055 foreach_neighbor(board, coord, {
1056 if (board_at(board, c) == S_NONE)
1057 board_group_addlib(board, group, c);
1060 if (DEBUGL(8))
1061 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
1062 coord_x(prevstone, board), coord_y(prevstone, board),
1063 coord_x(coord, board), coord_y(coord, board),
1064 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
1065 group_base(group));
1068 static void profiling_noinline
1069 merge_groups(struct board *board, group_t group_to, group_t group_from)
1071 if (DEBUGL(7))
1072 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
1073 group_base(group_from), group_base(group_to));
1074 struct group *gi_from = &board_group_info(board, group_from);
1075 struct group *gi_to = &board_group_info(board, group_to);
1076 bool onestone_from = group_is_onestone(board, group_from);
1077 bool onestone_to = group_is_onestone(board, group_to);
1079 /* We do this early before the group info is rewritten. */
1080 if (gi_from->libs == 2)
1081 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1082 else if (gi_from->libs == 1)
1083 board_capturable_rm(board, group_from, gi_from->lib[0], onestone_from);
1085 if (DEBUGL(7))
1086 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1088 if (gi_to->libs < GROUP_KEEP_LIBS) {
1089 for (int i = 0; i < gi_from->libs; i++) {
1090 for (int j = 0; j < gi_to->libs; j++)
1091 if (gi_to->lib[j] == gi_from->lib[i])
1092 goto next_from_lib;
1093 if (gi_to->libs == 0) {
1094 board_capturable_add(board, group_to, gi_from->lib[i], onestone_to);
1095 } else if (gi_to->libs == 1) {
1096 board_capturable_rm(board, group_to, gi_to->lib[0], onestone_to);
1097 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1098 } else if (gi_to->libs == 2) {
1099 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1101 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1102 if (gi_to->libs >= GROUP_KEEP_LIBS)
1103 break;
1104 next_from_lib:;
1108 if (gi_to->libs == 1) {
1109 coord_t lib = board_group_info(board, group_to).lib[0];
1110 #ifdef BOARD_TRAITS
1111 enum stone capturing_color = stone_other(board_at(board, group_to));
1112 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1114 /* Our group is currently in atari; make sure we properly
1115 * count in even the neighbors from the other group in the
1116 * capturable counter. */
1117 foreach_neighbor(board, lib, {
1118 if (DEBUGL(8) && group_at(board, c) == group_from)
1119 fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1120 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1121 /* This is never a 1-stone group, obviously. */
1123 board_trait_queue(board, lib);
1125 if (onestone_to) {
1126 /* We are not 1-stone group anymore, update the cap1
1127 * counter specifically. */
1128 foreach_neighbor(board, group_to, {
1129 if (board_at(board, c) != S_NONE) continue;
1130 trait_at(board, c, capturing_color).cap1--;
1131 board_trait_queue(board, c);
1134 #endif
1135 #ifdef BOARD_PAT3
1136 if (gi_from->libs == 1) {
1137 /* We removed group_from from capturable groups,
1138 * therefore switching the atari flag off.
1139 * We need to set it again since group_to is also
1140 * capturable. */
1141 int fn__i = 0;
1142 foreach_neighbor(board, lib, {
1143 board->pat3[lib] |= (group_at(board, c) == group_from) << (16 + 3 - fn__i);
1144 fn__i++;
1147 #endif
1150 coord_t last_in_group;
1151 foreach_in_group(board, group_from) {
1152 last_in_group = c;
1153 group_at(board, c) = group_to;
1154 } foreach_in_group_end;
1155 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1156 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1157 memset(gi_from, 0, sizeof(struct group));
1159 if (DEBUGL(7))
1160 fprintf(stderr, "board_play_raw: merged group: %d\n",
1161 group_base(group_to));
1164 static group_t profiling_noinline
1165 new_group(struct board *board, coord_t coord)
1167 group_t group = coord;
1168 struct group *gi = &board_group_info(board, group);
1169 foreach_neighbor(board, coord, {
1170 if (board_at(board, c) == S_NONE)
1171 /* board_group_addlib is ridiculously expensive for us */
1172 #if GROUP_KEEP_LIBS < 4
1173 if (gi->libs < GROUP_KEEP_LIBS)
1174 #endif
1175 gi->lib[gi->libs++] = c;
1178 group_at(board, coord) = group;
1179 groupnext_at(board, coord) = 0;
1181 if (gi->libs == 2)
1182 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1183 else if (gi->libs == 1)
1184 board_capturable_add(board, group, gi->lib[0], true);
1185 check_libs_consistency(board, group);
1187 if (DEBUGL(8))
1188 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1189 coord_x(coord, board), coord_y(coord, board),
1190 group_base(group));
1192 return group;
1195 static inline group_t
1196 play_one_neighbor(struct board *board,
1197 coord_t coord, enum stone color, enum stone other_color,
1198 coord_t c, group_t group)
1200 enum stone ncolor = board_at(board, c);
1201 group_t ngroup = group_at(board, c);
1203 inc_neighbor_count_at(board, c, color);
1204 /* We can be S_NONE, in that case we need to update the safety
1205 * trait since we might be left with only one liberty. */
1206 board_trait_queue(board, c);
1208 if (!ngroup)
1209 return group;
1211 board_group_rmlib(board, ngroup, coord);
1212 if (DEBUGL(7))
1213 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1214 group_base(ngroup), ncolor, color, other_color);
1216 if (ncolor == color && ngroup != group) {
1217 if (!group) {
1218 group = ngroup;
1219 add_to_group(board, group, c, coord);
1220 } else {
1221 merge_groups(board, group, ngroup);
1223 } else if (ncolor == other_color) {
1224 if (DEBUGL(8)) {
1225 struct group *gi = &board_group_info(board, ngroup);
1226 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1227 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1228 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1229 fprintf(stderr, "\n");
1231 if (unlikely(board_group_captured(board, ngroup)))
1232 board_group_capture(board, ngroup);
1234 return group;
1237 /* We played on a place with at least one liberty. We will become a member of
1238 * some group for sure. */
1239 static group_t profiling_noinline
1240 board_play_outside(struct board *board, struct move *m, int f)
1242 coord_t coord = m->coord;
1243 enum stone color = m->color;
1244 enum stone other_color = stone_other(color);
1245 group_t group = 0;
1247 board->f[f] = board->f[--board->flen];
1248 if (DEBUGL(6))
1249 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1251 #if defined(BOARD_TRAITS) && defined(DEBUG)
1252 /* Sanity check that cap matches reality. */
1254 int a = 0, b = 0;
1255 foreach_neighbor(board, coord, {
1256 group_t g = group_at(board, c);
1257 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1258 b += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1) && group_is_onestone(board, g);
1260 assert(a == trait_at(board, coord, color).cap);
1261 assert(b == trait_at(board, coord, color).cap1);
1262 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1264 #endif
1265 foreach_neighbor(board, coord, {
1266 group = play_one_neighbor(board, coord, color, other_color, c, group);
1269 board_at(board, coord) = color;
1270 if (unlikely(!group))
1271 group = new_group(board, coord);
1272 board_gamma_update(board, coord, S_BLACK);
1273 board_gamma_update(board, coord, S_WHITE);
1275 board->last_move2 = board->last_move;
1276 board->last_move = *m;
1277 board->moves++;
1278 board_hash_update(board, coord, color);
1279 board_symmetry_update(board, &board->symmetry, coord);
1280 struct move ko = { pass, S_NONE };
1281 board->ko = ko;
1283 check_pat3_consistency(board, coord);
1285 return group;
1288 /* We played in an eye-like shape. Either we capture at least one of the eye
1289 * sides in the process of playing, or return -1. */
1290 static int profiling_noinline
1291 board_play_in_eye(struct board *board, struct move *m, int f)
1293 coord_t coord = m->coord;
1294 enum stone color = m->color;
1295 /* Check ko: Capture at a position of ko capture one move ago */
1296 if (unlikely(color == board->ko.color && coord == board->ko.coord)) {
1297 if (DEBUGL(5))
1298 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1299 return -1;
1300 } else if (DEBUGL(6)) {
1301 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1302 color, coord_x(coord, board), coord_y(coord, board),
1303 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1306 struct move ko = { pass, S_NONE };
1308 int captured_groups = 0;
1310 foreach_neighbor(board, coord, {
1311 group_t g = group_at(board, c);
1312 if (DEBUGL(7))
1313 fprintf(stderr, "board_check: group %d has %d libs\n",
1314 g, board_group_info(board, g).libs);
1315 captured_groups += (board_group_info(board, g).libs == 1);
1318 if (likely(captured_groups == 0)) {
1319 if (DEBUGL(5)) {
1320 if (DEBUGL(6))
1321 board_print(board, stderr);
1322 fprintf(stderr, "board_check: one-stone suicide\n");
1325 return -1;
1327 #ifdef BOARD_TRAITS
1328 /* We _will_ for sure capture something. */
1329 assert(trait_at(board, coord, color).cap > 0);
1330 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1331 #endif
1333 board->f[f] = board->f[--board->flen];
1334 if (DEBUGL(6))
1335 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1337 foreach_neighbor(board, coord, {
1338 inc_neighbor_count_at(board, c, color);
1339 /* Originally, this could not have changed any trait
1340 * since no neighbors were S_NONE, however by now some
1341 * of them might be removed from the board. */
1342 board_trait_queue(board, c);
1344 group_t group = group_at(board, c);
1345 if (!group)
1346 continue;
1348 board_group_rmlib(board, group, coord);
1349 if (DEBUGL(7))
1350 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1351 group_base(group));
1353 if (board_group_captured(board, group)) {
1354 if (board_group_capture(board, group) == 1) {
1355 /* If we captured multiple groups at once,
1356 * we can't be fighting ko so we don't need
1357 * to check for that. */
1358 ko.color = stone_other(color);
1359 ko.coord = c;
1360 board->last_ko = ko;
1361 board->last_ko_age = board->moves;
1362 if (DEBUGL(5))
1363 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1368 board_at(board, coord) = color;
1369 group_t group = new_group(board, coord);
1370 board_gamma_update(board, coord, S_BLACK);
1371 board_gamma_update(board, coord, S_WHITE);
1373 board->last_move2 = board->last_move;
1374 board->last_move = *m;
1375 board->moves++;
1376 board_hash_update(board, coord, color);
1377 board_hash_commit(board);
1378 board_traits_recompute(board);
1379 board_symmetry_update(board, &board->symmetry, coord);
1380 board->ko = ko;
1382 check_pat3_consistency(board, coord);
1384 return !!group;
1387 static int __attribute__((flatten))
1388 board_play_f(struct board *board, struct move *m, int f)
1390 if (DEBUGL(7)) {
1391 fprintf(stderr, "board_play(%s): ---- Playing %d,%d\n", coord2sstr(m->coord, board), coord_x(m->coord, board), coord_y(m->coord, board));
1393 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1394 /* NOT playing in an eye. Thus this move has to succeed. (This
1395 * is thanks to New Zealand rules. Otherwise, multi-stone
1396 * suicide might fail.) */
1397 group_t group = board_play_outside(board, m, f);
1398 if (unlikely(board_group_captured(board, group))) {
1399 board_group_capture(board, group);
1401 board_hash_commit(board);
1402 board_traits_recompute(board);
1403 return 0;
1404 } else {
1405 return board_play_in_eye(board, m, f);
1410 board_play(struct board *board, struct move *m)
1412 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1413 struct move nomove = { pass, S_NONE };
1414 board->ko = nomove;
1415 board->last_move2 = board->last_move;
1416 board->last_move = *m;
1417 return 0;
1420 int f;
1421 for (f = 0; f < board->flen; f++)
1422 if (board->f[f] == m->coord)
1423 return board_play_f(board, m, f);
1425 if (DEBUGL(7))
1426 fprintf(stderr, "board_check: stone exists\n");
1427 return -1;
1431 static inline bool
1432 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1434 *coord = b->f[f];
1435 struct move m = { *coord, color };
1436 if (DEBUGL(6))
1437 fprintf(stderr, "trying random move %d: %d,%d %s %d\n", f, coord_x(*coord, b), coord_y(*coord, b), coord2sstr(*coord, b), board_is_valid_move(b, &m));
1438 if (unlikely(board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1439 || !board_is_valid_move(b, &m)
1440 || (permit && !permit(permit_data, b, &m)))
1441 return false;
1442 if (m.coord == *coord) {
1443 return likely(board_play_f(b, &m, f) >= 0);
1444 } else {
1445 *coord = m.coord; // permit modified the coordinate
1446 return likely(board_play(b, &m) >= 0);
1450 void
1451 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1453 if (unlikely(b->flen == 0))
1454 goto pass;
1456 int base = fast_random(b->flen), f;
1457 for (f = base; f < b->flen; f++)
1458 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1459 return;
1460 for (f = 0; f < base; f++)
1461 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1462 return;
1464 pass:
1465 *coord = pass;
1466 struct move m = { pass, color };
1467 board_play(b, &m);
1471 bool
1472 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1474 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1476 /* XXX: We attempt false eye detection but we will yield false
1477 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1479 foreach_diag_neighbor(board, coord) {
1480 color_diag_libs[(enum stone) board_at(board, c)]++;
1481 } foreach_diag_neighbor_end;
1482 /* For false eye, we need two enemy stones diagonally in the
1483 * middle of the board, or just one enemy stone at the edge
1484 * or in the corner. */
1485 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1486 return color_diag_libs[stone_other(eye_color)] >= 2;
1489 bool
1490 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1492 return board_is_eyelike(board, coord, eye_color)
1493 && !board_is_false_eyelike(board, coord, eye_color);
1496 enum stone
1497 board_get_one_point_eye(struct board *board, coord_t coord)
1499 if (board_is_one_point_eye(board, coord, S_WHITE))
1500 return S_WHITE;
1501 else if (board_is_one_point_eye(board, coord, S_BLACK))
1502 return S_BLACK;
1503 else
1504 return S_NONE;
1508 float
1509 board_fast_score(struct board *board)
1511 int scores[S_MAX];
1512 memset(scores, 0, sizeof(scores));
1514 foreach_point(board) {
1515 enum stone color = board_at(board, c);
1516 if (color == S_NONE)
1517 color = board_get_one_point_eye(board, c);
1518 scores[color]++;
1519 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1520 } foreach_point_end;
1522 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1525 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1527 /* One flood-fill iteration; returns true if next iteration
1528 * is required. */
1529 static bool
1530 board_tromp_taylor_iter(struct board *board, int *ownermap)
1532 bool needs_update = false;
1533 foreach_free_point(board) {
1534 /* Ignore occupied and already-dame positions. */
1535 assert(board_at(board, c) == S_NONE);
1536 if (ownermap[c] == 3)
1537 continue;
1538 /* Count neighbors. */
1539 int nei[4] = {0};
1540 foreach_neighbor(board, c, {
1541 nei[ownermap[c]]++;
1543 /* If we have neighbors of both colors, or dame,
1544 * we are dame too. */
1545 if ((nei[1] && nei[2]) || nei[3]) {
1546 ownermap[c] = 3;
1547 /* Speed up the propagation. */
1548 foreach_neighbor(board, c, {
1549 if (board_at(board, c) == S_NONE)
1550 ownermap[c] = 3;
1552 needs_update = true;
1553 continue;
1555 /* If we have neighbors of one color, we are owned
1556 * by that color, too. */
1557 if (!ownermap[c] && (nei[1] || nei[2])) {
1558 int newowner = nei[1] ? 1 : 2;
1559 ownermap[c] = newowner;
1560 /* Speed up the propagation. */
1561 foreach_neighbor(board, c, {
1562 if (board_at(board, c) == S_NONE && !ownermap[c])
1563 ownermap[c] = newowner;
1565 needs_update = true;
1566 continue;
1568 } foreach_free_point_end;
1569 return needs_update;
1572 /* Tromp-Taylor Counting */
1573 float
1574 board_official_score(struct board *board, struct move_queue *q)
1577 /* A point P, not colored C, is said to reach C, if there is a path of
1578 * (vertically or horizontally) adjacent points of P's color from P to
1579 * a point of color C.
1581 * A player's score is the number of points of her color, plus the
1582 * number of empty points that reach only her color. */
1584 int ownermap[board_size2(board)];
1585 int s[4] = {0};
1586 const int o[4] = {0, 1, 2, 0};
1587 foreach_point(board) {
1588 ownermap[c] = o[board_at(board, c)];
1589 s[board_at(board, c)]++;
1590 } foreach_point_end;
1592 if (q) {
1593 /* Process dead groups. */
1594 for (unsigned int i = 0; i < q->moves; i++) {
1595 foreach_in_group(board, q->move[i]) {
1596 enum stone color = board_at(board, c);
1597 ownermap[c] = o[stone_other(color)];
1598 s[color]--; s[stone_other(color)]++;
1599 } foreach_in_group_end;
1603 /* We need to special-case empty board. */
1604 if (!s[S_BLACK] && !s[S_WHITE])
1605 return board->komi + board->handicap;
1607 while (board_tromp_taylor_iter(board, ownermap))
1608 /* Flood-fill... */;
1610 int scores[S_MAX];
1611 memset(scores, 0, sizeof(scores));
1613 foreach_point(board) {
1614 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1615 if (ownermap[c] == 3)
1616 continue;
1617 scores[ownermap[c]]++;
1618 } foreach_point_end;
1620 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];