middle_ladder_walk(): Allow alternative near-edge termination of ladders
[pachi/nmclean.git] / board.c
blob1a06d1c6b31f2465b5ad03426b0e79cb61f0be1d
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
27 #if 0
28 #define profiling_noinline __attribute__((noinline))
29 #else
30 #define profiling_noinline
31 #endif
33 #define gi_granularity 4
34 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
37 static void
38 board_setup(struct board *b)
40 memset(b, 0, sizeof(*b));
42 struct move m = { pass, S_NONE };
43 b->last_move = b->last_move2 = b->last_move3 = b->last_move4 = b->last_ko = b->ko = m;
46 struct board *
47 board_init(char *fbookfile)
49 struct board *b = malloc2(sizeof(struct board));
50 board_setup(b);
52 b->fbookfile = fbookfile;
54 // Default setup
55 b->size = 9 + 2;
56 board_clear(b);
58 return b;
61 static size_t
62 board_alloc(struct board *board)
64 /* We do not allocate the board structure itself but we allocate
65 * all the arrays with board contents. */
67 int bsize = board_size2(board) * sizeof(*board->b);
68 int gsize = board_size2(board) * sizeof(*board->g);
69 int fsize = board_size2(board) * sizeof(*board->f);
70 int nsize = board_size2(board) * sizeof(*board->n);
71 int psize = board_size2(board) * sizeof(*board->p);
72 int hsize = board_size2(board) * 2 * sizeof(*board->h);
73 int gisize = board_size2(board) * sizeof(*board->gi);
74 #ifdef WANT_BOARD_C
75 int csize = board_size2(board) * sizeof(*board->c);
76 #else
77 int csize = 0;
78 #endif
79 #ifdef BOARD_SPATHASH
80 int ssize = board_size2(board) * sizeof(*board->spathash);
81 #else
82 int ssize = 0;
83 #endif
84 #ifdef BOARD_PAT3
85 int p3size = board_size2(board) * sizeof(*board->pat3);
86 #else
87 int p3size = 0;
88 #endif
89 #ifdef BOARD_TRAITS
90 int tsize = board_size2(board) * sizeof(*board->t);
91 int tqsize = board_size2(board) * sizeof(*board->t);
92 #else
93 int tsize = 0;
94 int tqsize = 0;
95 #endif
96 int cdsize = board_size2(board) * sizeof(*board->coord);
98 size_t size = bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + cdsize;
99 void *x = malloc2(size);
101 /* board->b must come first */
102 board->b = x; x += bsize;
103 board->g = x; x += gsize;
104 board->f = x; x += fsize;
105 board->p = x; x += psize;
106 board->n = x; x += nsize;
107 board->h = x; x += hsize;
108 board->gi = x; x += gisize;
109 #ifdef WANT_BOARD_C
110 board->c = x; x += csize;
111 #endif
112 #ifdef BOARD_SPATHASH
113 board->spathash = x; x += ssize;
114 #endif
115 #ifdef BOARD_PAT3
116 board->pat3 = x; x += p3size;
117 #endif
118 #ifdef BOARD_TRAITS
119 board->t = x; x += tsize;
120 board->tq = x; x += tqsize;
121 #endif
122 board->coord = x; x += cdsize;
124 return size;
127 struct board *
128 board_copy(struct board *b2, struct board *b1)
130 memcpy(b2, b1, sizeof(struct board));
132 size_t size = board_alloc(b2);
133 memcpy(b2->b, b1->b, size);
135 // XXX: Special semantics.
136 b2->fbook = NULL;
138 return b2;
141 void
142 board_done_noalloc(struct board *board)
144 if (board->b) free(board->b);
145 if (board->fbook) fbook_done(board->fbook);
148 void
149 board_done(struct board *board)
151 board_done_noalloc(board);
152 free(board);
155 void
156 board_resize(struct board *board, int size)
158 #ifdef BOARD_SIZE
159 assert(board_size(board) == size + 2);
160 #endif
161 assert(size <= BOARD_MAX_SIZE);
162 board->size = size + 2 /* S_OFFBOARD margin */;
163 board->size2 = board_size(board) * board_size(board);
165 board->bits2 = 1;
166 while ((1 << board->bits2) < board->size2) board->bits2++;
168 if (board->b)
169 free(board->b);
171 size_t asize = board_alloc(board);
172 memset(board->b, 0, asize);
175 static void
176 board_init_data(struct board *board)
178 int size = board_size(board);
180 board_setup(board);
181 board_resize(board, size - 2 /* S_OFFBOARD margin */);
183 /* Setup neighborhood iterators */
184 board->nei8[0] = -size - 1; // (-1,-1)
185 board->nei8[1] = 1;
186 board->nei8[2] = 1;
187 board->nei8[3] = size - 2; // (-1,0)
188 board->nei8[4] = 2;
189 board->nei8[5] = size - 2; // (-1,1)
190 board->nei8[6] = 1;
191 board->nei8[7] = 1;
192 board->dnei[0] = -size - 1;
193 board->dnei[1] = 2;
194 board->dnei[2] = size*2 - 2;
195 board->dnei[3] = 2;
197 /* Setup initial symmetry */
198 if (size % 2) {
199 board->symmetry.d = 1;
200 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
201 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
202 board->symmetry.type = SYM_FULL;
203 } else {
204 /* TODO: We do not handle board symmetry on boards
205 * with no tengen yet. */
206 board->symmetry.d = 0;
207 board->symmetry.x1 = board->symmetry.y1 = 1;
208 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
209 board->symmetry.type = SYM_NONE;
212 /* Set up coordinate cache */
213 foreach_point(board) {
214 board->coord[c][0] = c % board_size(board);
215 board->coord[c][1] = c / board_size(board);
216 } foreach_point_end;
218 /* Draw the offboard margin */
219 int top_row = board_size2(board) - board_size(board);
220 int i;
221 for (i = 0; i < board_size(board); i++)
222 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
223 for (i = 0; i <= top_row; i += board_size(board))
224 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
226 foreach_point(board) {
227 coord_t coord = c;
228 if (board_at(board, coord) == S_OFFBOARD)
229 continue;
230 foreach_neighbor(board, c, {
231 inc_neighbor_count_at(board, coord, board_at(board, c));
232 } );
233 } foreach_point_end;
235 /* All positions are free! Except the margin. */
236 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
237 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
238 board->f[board->flen++] = i;
240 /* Initialize zobrist hashtable. */
241 /* We will need these to be stable across Pachi runs for
242 * certain kinds of pattern matching, thus we do not use
243 * fast_random() for this. */
244 hash_t hseed = 0x3121110101112131;
245 foreach_point(board) {
246 board->h[c * 2] = (hseed *= 16807);
247 if (!board->h[c * 2])
248 board->h[c * 2] = 1;
249 /* And once again for white */
250 board->h[c * 2 + 1] = (hseed *= 16807);
251 if (!board->h[c * 2 + 1])
252 board->h[c * 2 + 1] = 1;
253 } foreach_point_end;
255 #ifdef BOARD_SPATHASH
256 /* Initialize spatial hashes. */
257 foreach_point(board) {
258 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
259 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
260 ptcoords_at(x, y, c, board, j);
261 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
262 pthashes[0][j][board_at(board, c)];
263 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
264 pthashes[0][j][stone_other(board_at(board, c))];
267 } foreach_point_end;
268 #endif
269 #ifdef BOARD_PAT3
270 /* Initialize 3x3 pattern codes. */
271 foreach_point(board) {
272 if (board_at(board, c) == S_NONE)
273 board->pat3[c] = pattern3_hash(board, c);
274 } foreach_point_end;
275 #endif
276 #ifdef BOARD_TRAITS
277 /* Initialize traits. */
278 foreach_point(board) {
279 trait_at(board, c, S_BLACK).cap = 0;
280 trait_at(board, c, S_WHITE).cap = 0;
281 trait_at(board, c, S_BLACK).cap1 = 0;
282 trait_at(board, c, S_WHITE).cap1 = 0;
283 #ifdef BOARD_TRAIT_SAFE
284 trait_at(board, c, S_BLACK).safe = true;
285 trait_at(board, c, S_WHITE).safe = true;
286 #endif
287 } foreach_point_end;
288 #endif
291 void
292 board_clear(struct board *board)
294 int size = board_size(board);
295 floating_t komi = board->komi;
296 char *fbookfile = board->fbookfile;
298 board_done_noalloc(board);
300 static struct board bcache[BOARD_MAX_SIZE + 2];
301 assert(size > 0 && size <= BOARD_MAX_SIZE + 2);
302 if (bcache[size - 1].size == size) {
303 board_copy(board, &bcache[size - 1]);
304 } else {
305 board_init_data(board);
306 board_copy(&bcache[size - 1], board);
309 board->komi = komi;
310 board->fbookfile = fbookfile;
312 if (board->fbookfile) {
313 board->fbook = fbook_init(board->fbookfile, board);
317 static char *
318 board_print_top(struct board *board, char *s, char *end, int c)
320 for (int i = 0; i < c; i++) {
321 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
322 s += snprintf(s, end - s, " ");
323 for (int x = 1; x < board_size(board) - 1; x++)
324 s += snprintf(s, end - s, "%c ", asdf[x - 1]);
325 s += snprintf(s, end -s, " ");
327 s += snprintf(s, end - s, "\n");
328 for (int i = 0; i < c; i++) {
329 s += snprintf(s, end - s, " +-");
330 for (int x = 1; x < board_size(board) - 1; x++)
331 s += snprintf(s, end - s, "--");
332 s += snprintf(s, end - s, "+");
334 s += snprintf(s, end - s, "\n");
335 return s;
338 static char *
339 board_print_bottom(struct board *board, char *s, char *end, int c)
341 for (int i = 0; i < c; i++) {
342 s += snprintf(s, end - s, " +-");
343 for (int x = 1; x < board_size(board) - 1; x++)
344 s += snprintf(s, end - s, "--");
345 s += snprintf(s, end - s, "+");
347 s += snprintf(s, end - s, "\n");
348 return s;
351 static char *
352 board_print_row(struct board *board, int y, char *s, char *end, board_cprint cprint)
354 s += snprintf(s, end - s, " %2d | ", y);
355 for (int x = 1; x < board_size(board) - 1; x++) {
356 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
357 s += snprintf(s, end - s, "%c)", stone2char(board_atxy(board, x, y)));
358 else
359 s += snprintf(s, end - s, "%c ", stone2char(board_atxy(board, x, y)));
361 s += snprintf(s, end - s, "|");
362 if (cprint) {
363 s += snprintf(s, end - s, " %2d | ", y);
364 for (int x = 1; x < board_size(board) - 1; x++) {
365 s = cprint(board, coord_xy(board, x, y), s, end);
367 s += snprintf(s, end - s, "|");
369 s += snprintf(s, end - s, "\n");
370 return s;
373 void
374 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
376 char buf[10240];
377 char *s = buf;
378 char *end = buf + sizeof(buf);
379 s += snprintf(s, end - s, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
380 board->moves, board->komi, board->handicap,
381 board->captures[S_BLACK], board->captures[S_WHITE]);
382 s = board_print_top(board, s, end, 1 + !!cprint);
383 for (int y = board_size(board) - 2; y >= 1; y--)
384 s = board_print_row(board, y, s, end, cprint);
385 board_print_bottom(board, s, end, 1 + !!cprint);
386 fprintf(f, "%s\n", buf);
389 static char *
390 cprint_group(struct board *board, coord_t c, char *s, char *end)
392 s += snprintf(s, end - s, "%d ", group_base(group_at(board, c)));
393 return s;
396 void
397 board_print(struct board *board, FILE *f)
399 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
403 #ifdef BOARD_TRAITS
405 #if BOARD_TRAIT_SAFE == 1
406 static bool
407 board_trait_safe(struct board *board, coord_t coord, enum stone color)
409 return board_safe_to_play(board, coord, color);
411 #elif BOARD_TRAIT_SAFE == 2
412 static bool
413 board_trait_safe(struct board *board, coord_t coord, enum stone color)
415 return !is_bad_selfatari(board, color, coord);
417 #endif
419 static void
420 board_trait_recompute(struct board *board, coord_t coord)
422 int sfb = -1, sfw = -1;
423 #ifdef BOARD_TRAIT_SAFE
424 sfb = trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);
425 sfw = trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
426 #endif
427 if (DEBUGL(8)) {
428 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d cap1=%d safe=%d) (white cap=%d cap1=%d safe=%d)\n",
429 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
430 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).cap1, sfb,
431 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).cap1, sfw);
434 #endif
436 /* Recompute traits for dirty points that we have previously touched
437 * somehow (libs of their neighbors changed or so). */
438 static void
439 board_traits_recompute(struct board *board)
441 #ifdef BOARD_TRAITS
442 for (int i = 0; i < board->tqlen; i++) {
443 coord_t coord = board->tq[i];
444 trait_at(board, coord, S_BLACK).dirty = false;
445 if (board_at(board, coord) != S_NONE)
446 continue;
447 board_trait_recompute(board, coord);
449 board->tqlen = 0;
450 #endif
453 /* Queue traits of given point for recomputing. */
454 static void
455 board_trait_queue(struct board *board, coord_t coord)
457 #ifdef BOARD_TRAITS
458 if (trait_at(board, coord, S_BLACK).dirty)
459 return;
460 board->tq[board->tqlen++] = coord;
461 trait_at(board, coord, S_BLACK).dirty = true;
462 #endif
466 /* Update board hash with given coordinate. */
467 static void profiling_noinline
468 board_hash_update(struct board *board, coord_t coord, enum stone color)
470 board->hash ^= hash_at(board, coord, color);
471 board->qhash[coord_quadrant(coord, board)] ^= hash_at(board, coord, color);
472 if (DEBUGL(8))
473 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);
475 #ifdef BOARD_SPATHASH
476 /* Gridcular metric is reflective, so we update all hashes
477 * of appropriate ditance in OUR circle. */
478 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
479 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
480 ptcoords_at(x, y, coord, board, j);
481 /* We either changed from S_NONE to color
482 * or vice versa; doesn't matter. */
483 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
484 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
485 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
486 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
489 #endif
491 #if defined(BOARD_PAT3)
492 /* @color is not what we need in case of capture. */
493 static const int ataribits[8] = { -1, 0, -1, 1, 2, -1, 3, -1 };
494 enum stone new_color = board_at(board, coord);
495 bool in_atari = false;
496 if (new_color == S_NONE) {
497 board->pat3[coord] = pattern3_hash(board, coord);
498 } else {
499 in_atari = (board_group_info(board, group_at(board, coord)).libs == 1);
501 foreach_8neighbor(board, coord) {
502 /* Internally, the loop uses fn__i=[0..7]. We can use
503 * it directly to address bits within the bitmap of the
504 * neighbors since the bitmap order is reverse to the
505 * loop order. */
506 if (board_at(board, c) != S_NONE)
507 continue;
508 board->pat3[c] &= ~(3 << (fn__i*2));
509 board->pat3[c] |= new_color << (fn__i*2);
510 if (ataribits[fn__i] >= 0) {
511 board->pat3[c] &= ~(1 << (16 + ataribits[fn__i]));
512 board->pat3[c] |= in_atari << (16 + ataribits[fn__i]);
514 #if defined(BOARD_TRAITS)
515 board_trait_queue(board, c);
516 #endif
517 } foreach_8neighbor_end;
518 #endif
521 /* Commit current board hash to history. */
522 static void profiling_noinline
523 board_hash_commit(struct board *board)
525 if (DEBUGL(8))
526 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
527 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
528 board->history_hash[board->hash & history_hash_mask] = board->hash;
529 } else {
530 hash_t i = board->hash;
531 while (board->history_hash[i & history_hash_mask]) {
532 if (board->history_hash[i & history_hash_mask] == board->hash) {
533 if (DEBUGL(5))
534 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
535 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
536 board->superko_violation = true;
537 return;
539 i = history_hash_next(i);
541 board->history_hash[i & history_hash_mask] = board->hash;
546 void
547 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
549 if (likely(symmetry->type == SYM_NONE)) {
550 /* Fully degenerated already. We do not support detection
551 * of restoring of symmetry, assuming that this is too rare
552 * a case to handle. */
553 return;
556 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
557 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
558 if (DEBUGL(6)) {
559 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
560 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
561 symmetry->d, symmetry->type, x, y);
564 switch (symmetry->type) {
565 case SYM_FULL:
566 if (x == t && y == t) {
567 /* Tengen keeps full symmetry. */
568 return;
570 /* New symmetry now? */
571 if (x == y) {
572 symmetry->type = SYM_DIAG_UP;
573 symmetry->x1 = symmetry->y1 = 1;
574 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
575 symmetry->d = 1;
576 } else if (dx == y) {
577 symmetry->type = SYM_DIAG_DOWN;
578 symmetry->x1 = symmetry->y1 = 1;
579 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
580 symmetry->d = 1;
581 } else if (x == t) {
582 symmetry->type = SYM_HORIZ;
583 symmetry->y1 = 1;
584 symmetry->y2 = board_size(b) - 1;
585 symmetry->d = 0;
586 } else if (y == t) {
587 symmetry->type = SYM_VERT;
588 symmetry->x1 = 1;
589 symmetry->x2 = board_size(b) - 1;
590 symmetry->d = 0;
591 } else {
592 break_symmetry:
593 symmetry->type = SYM_NONE;
594 symmetry->x1 = symmetry->y1 = 1;
595 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
596 symmetry->d = 0;
598 break;
599 case SYM_DIAG_UP:
600 if (x == y)
601 return;
602 goto break_symmetry;
603 case SYM_DIAG_DOWN:
604 if (dx == y)
605 return;
606 goto break_symmetry;
607 case SYM_HORIZ:
608 if (x == t)
609 return;
610 goto break_symmetry;
611 case SYM_VERT:
612 if (y == t)
613 return;
614 goto break_symmetry;
615 case SYM_NONE:
616 assert(0);
617 break;
620 if (DEBUGL(6)) {
621 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
622 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
623 symmetry->d, symmetry->type);
625 /* Whew. */
629 void
630 board_handicap_stone(struct board *board, int x, int y, FILE *f)
632 struct move m;
633 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
635 board_play(board, &m);
636 /* Simulate white passing; otherwise, UCT search can get confused since
637 * tree depth parity won't match the color to move. */
638 board->moves++;
640 char *str = coord2str(m.coord, board);
641 if (DEBUGL(1))
642 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
643 if (f) fprintf(f, "%s ", str);
644 free(str);
647 void
648 board_handicap(struct board *board, int stones, FILE *f)
650 int margin = 3 + (board_size(board) >= 13);
651 int min = margin;
652 int mid = board_size(board) / 2;
653 int max = board_size(board) - 1 - margin;
654 const int places[][2] = {
655 { min, min }, { max, max }, { min, max }, { max, min },
656 { min, mid }, { max, mid },
657 { mid, min }, { mid, max },
658 { mid, mid },
661 board->handicap = stones;
663 if (stones == 5 || stones == 7) {
664 board_handicap_stone(board, mid, mid, f);
665 stones--;
668 int i;
669 for (i = 0; i < stones; i++)
670 board_handicap_stone(board, places[i][0], places[i][1], f);
674 static void __attribute__((noinline))
675 check_libs_consistency(struct board *board, group_t g)
677 #ifdef DEBUG
678 if (!g) return;
679 struct group *gi = &board_group_info(board, g);
680 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
681 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
682 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
683 assert(0);
685 #endif
688 static void
689 check_pat3_consistency(struct board *board, coord_t coord)
691 #ifdef DEBUG
692 foreach_8neighbor(board, coord) {
693 if (board_at(board, c) == S_NONE && pattern3_hash(board, c) != board->pat3[c]) {
694 board_print(board, stderr);
695 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);
696 assert(0);
698 } foreach_8neighbor_end;
699 #endif
702 static void
703 board_capturable_add(struct board *board, group_t group, coord_t lib, bool onestone)
705 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
706 #ifdef BOARD_TRAITS
707 /* Increase capturable count trait of my last lib. */
708 enum stone capturing_color = stone_other(board_at(board, group));
709 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
710 foreach_neighbor(board, lib, {
711 if (DEBUGL(8) && group_at(board, c) == group)
712 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);
713 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
714 trait_at(board, lib, capturing_color).cap1 += (group_at(board, c) == group && onestone);
716 board_trait_queue(board, lib);
717 #endif
719 #ifdef BOARD_PAT3
720 int fn__i = 0;
721 foreach_neighbor(board, lib, {
722 board->pat3[lib] |= (group_at(board, c) == group) << (16 + 3 - fn__i);
723 fn__i++;
725 #endif
727 #ifdef WANT_BOARD_C
728 /* Update the list of capturable groups. */
729 assert(group);
730 assert(board->clen < board_size2(board));
731 board->c[board->clen++] = group;
732 #endif
734 static void
735 board_capturable_rm(struct board *board, group_t group, coord_t lib, bool onestone)
737 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
738 #ifdef BOARD_TRAITS
739 /* Decrease capturable count trait of my previously-last lib. */
740 enum stone capturing_color = stone_other(board_at(board, group));
741 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
742 foreach_neighbor(board, lib, {
743 if (DEBUGL(8) && group_at(board, c) == group)
744 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);
745 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
746 trait_at(board, lib, capturing_color).cap1 -= (group_at(board, c) == group && onestone);
748 board_trait_queue(board, lib);
749 #endif
751 #ifdef BOARD_PAT3
752 int fn__i = 0;
753 foreach_neighbor(board, lib, {
754 board->pat3[lib] &= ~((group_at(board, c) == group) << (16 + 3 - fn__i));
755 fn__i++;
757 #endif
759 #ifdef WANT_BOARD_C
760 /* Update the list of capturable groups. */
761 for (int i = 0; i < board->clen; i++) {
762 if (unlikely(board->c[i] == group)) {
763 board->c[i] = board->c[--board->clen];
764 return;
767 fprintf(stderr, "rm of bad group %d\n", group_base(group));
768 assert(0);
769 #endif
772 static void
773 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
775 #ifdef BOARD_TRAITS
776 board_trait_queue(board, lib1);
777 board_trait_queue(board, lib2);
778 #endif
780 static void
781 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
783 #ifdef BOARD_TRAITS
784 board_trait_queue(board, lib1);
785 board_trait_queue(board, lib2);
786 #endif
789 static void
790 board_group_addlib(struct board *board, group_t group, coord_t coord)
792 if (DEBUGL(7)) {
793 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
794 group_base(group), coord2sstr(group_base(group), board),
795 board_group_info(board, group).libs, coord2sstr(coord, board));
798 check_libs_consistency(board, group);
800 struct group *gi = &board_group_info(board, group);
801 bool onestone = group_is_onestone(board, group);
802 if (gi->libs < GROUP_KEEP_LIBS) {
803 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
804 #if 0
805 /* Seems extra branch just slows it down */
806 if (!gi->lib[i])
807 break;
808 #endif
809 if (unlikely(gi->lib[i] == coord))
810 return;
812 if (gi->libs == 0) {
813 board_capturable_add(board, group, coord, onestone);
814 } else if (gi->libs == 1) {
815 board_capturable_rm(board, group, gi->lib[0], onestone);
816 board_atariable_add(board, group, gi->lib[0], coord);
817 } else if (gi->libs == 2) {
818 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
820 gi->lib[gi->libs++] = coord;
823 check_libs_consistency(board, group);
826 static void
827 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
829 /* Add extra liberty from the board to our liberty list. */
830 unsigned char watermark[board_size2(board) / 8];
831 memset(watermark, 0, sizeof(watermark));
832 #define watermark_get(c) (watermark[c >> 3] & (1 << (c & 7)))
833 #define watermark_set(c) watermark[c >> 3] |= (1 << (c & 7))
835 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
836 watermark_set(gi->lib[i]);
837 watermark_set(avoid);
839 foreach_in_group(board, group) {
840 coord_t coord2 = c;
841 foreach_neighbor(board, coord2, {
842 if (board_at(board, c) + watermark_get(c) != S_NONE)
843 continue;
844 watermark_set(c);
845 gi->lib[gi->libs++] = c;
846 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
847 return;
848 } );
849 } foreach_in_group_end;
850 #undef watermark_get
851 #undef watermark_set
854 static void
855 board_group_rmlib(struct board *board, group_t group, coord_t coord)
857 if (DEBUGL(7)) {
858 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
859 group_base(group), coord2sstr(group_base(group), board),
860 board_group_info(board, group).libs, coord2sstr(coord, board));
863 struct group *gi = &board_group_info(board, group);
864 bool onestone = group_is_onestone(board, group);
865 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
866 #if 0
867 /* Seems extra branch just slows it down */
868 if (!gi->lib[i])
869 break;
870 #endif
871 if (likely(gi->lib[i] != coord))
872 continue;
874 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
875 gi->lib[gi->libs] = 0;
877 check_libs_consistency(board, group);
879 /* Postpone refilling lib[] until we need to. */
880 assert(GROUP_REFILL_LIBS > 1);
881 if (gi->libs > GROUP_REFILL_LIBS)
882 return;
883 if (gi->libs == GROUP_REFILL_LIBS)
884 board_group_find_extra_libs(board, group, gi, coord);
886 if (gi->libs == 2) {
887 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
888 } else if (gi->libs == 1) {
889 board_capturable_add(board, group, gi->lib[0], onestone);
890 board_atariable_rm(board, group, gi->lib[0], lib);
891 } else if (gi->libs == 0)
892 board_capturable_rm(board, group, lib, onestone);
893 return;
896 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
897 * can call this multiple times per coord. */
898 check_libs_consistency(board, group);
899 return;
903 /* This is a low-level routine that doesn't maintain consistency
904 * of all the board data structures. */
905 static void
906 board_remove_stone(struct board *board, group_t group, coord_t c)
908 enum stone color = board_at(board, c);
909 board_at(board, c) = S_NONE;
910 group_at(board, c) = 0;
911 board_hash_update(board, c, color);
912 #ifdef BOARD_TRAITS
913 /* We mark as cannot-capture now. If this is a ko/snapback,
914 * we will get incremented later in board_group_addlib(). */
915 trait_at(board, c, S_BLACK).cap = trait_at(board, c, S_BLACK).cap1 = 0;
916 trait_at(board, c, S_WHITE).cap = trait_at(board, c, S_WHITE).cap1 = 0;
917 board_trait_queue(board, c);
918 #endif
920 /* Increase liberties of surrounding groups */
921 coord_t coord = c;
922 foreach_neighbor(board, coord, {
923 dec_neighbor_count_at(board, c, color);
924 board_trait_queue(board, c);
925 group_t g = group_at(board, c);
926 if (g && g != group)
927 board_group_addlib(board, g, coord);
930 #ifdef BOARD_PAT3
931 /* board_hash_update() might have seen the freed up point as able
932 * to capture another group in atari that only after the loop
933 * above gained enough liberties. Reset pat3 again. */
934 board->pat3[c] = pattern3_hash(board, c);
935 #endif
937 if (DEBUGL(6))
938 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
939 board->f[board->flen++] = c;
942 static int profiling_noinline
943 board_group_capture(struct board *board, group_t group)
945 int stones = 0;
947 foreach_in_group(board, group) {
948 board->captures[stone_other(board_at(board, c))]++;
949 board_remove_stone(board, group, c);
950 stones++;
951 } foreach_in_group_end;
953 struct group *gi = &board_group_info(board, group);
954 assert(gi->libs == 0);
955 memset(gi, 0, sizeof(*gi));
957 return stones;
961 static void profiling_noinline
962 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
964 #ifdef BOARD_TRAITS
965 struct group *gi = &board_group_info(board, group);
966 bool onestone = group_is_onestone(board, group);
968 if (gi->libs == 1) {
969 /* Our group is temporarily in atari; make sure the capturable
970 * counts also correspond to the newly added stone before we
971 * start adding liberties again so bump-dump ops match. */
972 enum stone capturing_color = stone_other(board_at(board, group));
973 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
975 coord_t lib = board_group_info(board, group).lib[0];
976 if (coord_is_adjecent(lib, coord, board)) {
977 if (DEBUGL(8))
978 fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
979 trait_at(board, lib, capturing_color).cap++;
980 /* This is never a 1-stone group, obviously. */
981 board_trait_queue(board, lib);
984 if (onestone) {
985 /* We are not 1-stone group anymore, update the cap1
986 * counter specifically. */
987 foreach_neighbor(board, group, {
988 if (board_at(board, c) != S_NONE) continue;
989 trait_at(board, c, capturing_color).cap1--;
990 board_trait_queue(board, c);
994 #endif
996 group_at(board, coord) = group;
997 groupnext_at(board, coord) = groupnext_at(board, prevstone);
998 groupnext_at(board, prevstone) = coord;
1000 foreach_neighbor(board, coord, {
1001 if (board_at(board, c) == S_NONE)
1002 board_group_addlib(board, group, c);
1005 if (DEBUGL(8))
1006 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
1007 coord_x(prevstone, board), coord_y(prevstone, board),
1008 coord_x(coord, board), coord_y(coord, board),
1009 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
1010 group_base(group));
1013 static void profiling_noinline
1014 merge_groups(struct board *board, group_t group_to, group_t group_from)
1016 if (DEBUGL(7))
1017 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
1018 group_base(group_from), group_base(group_to));
1019 struct group *gi_from = &board_group_info(board, group_from);
1020 struct group *gi_to = &board_group_info(board, group_to);
1021 bool onestone_from = group_is_onestone(board, group_from);
1022 bool onestone_to = group_is_onestone(board, group_to);
1024 /* We do this early before the group info is rewritten. */
1025 if (gi_from->libs == 2)
1026 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1027 else if (gi_from->libs == 1)
1028 board_capturable_rm(board, group_from, gi_from->lib[0], onestone_from);
1030 if (DEBUGL(7))
1031 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1033 if (gi_to->libs < GROUP_KEEP_LIBS) {
1034 for (int i = 0; i < gi_from->libs; i++) {
1035 for (int j = 0; j < gi_to->libs; j++)
1036 if (gi_to->lib[j] == gi_from->lib[i])
1037 goto next_from_lib;
1038 if (gi_to->libs == 0) {
1039 board_capturable_add(board, group_to, gi_from->lib[i], onestone_to);
1040 } else if (gi_to->libs == 1) {
1041 board_capturable_rm(board, group_to, gi_to->lib[0], onestone_to);
1042 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1043 } else if (gi_to->libs == 2) {
1044 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1046 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1047 if (gi_to->libs >= GROUP_KEEP_LIBS)
1048 break;
1049 next_from_lib:;
1053 if (gi_to->libs == 1) {
1054 coord_t lib = board_group_info(board, group_to).lib[0];
1055 #ifdef BOARD_TRAITS
1056 enum stone capturing_color = stone_other(board_at(board, group_to));
1057 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1059 /* Our group is currently in atari; make sure we properly
1060 * count in even the neighbors from the other group in the
1061 * capturable counter. */
1062 foreach_neighbor(board, lib, {
1063 if (DEBUGL(8) && group_at(board, c) == group_from)
1064 fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1065 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1066 /* This is never a 1-stone group, obviously. */
1068 board_trait_queue(board, lib);
1070 if (onestone_to) {
1071 /* We are not 1-stone group anymore, update the cap1
1072 * counter specifically. */
1073 foreach_neighbor(board, group_to, {
1074 if (board_at(board, c) != S_NONE) continue;
1075 trait_at(board, c, capturing_color).cap1--;
1076 board_trait_queue(board, c);
1079 #endif
1080 #ifdef BOARD_PAT3
1081 if (gi_from->libs == 1) {
1082 /* We removed group_from from capturable groups,
1083 * therefore switching the atari flag off.
1084 * We need to set it again since group_to is also
1085 * capturable. */
1086 int fn__i = 0;
1087 foreach_neighbor(board, lib, {
1088 board->pat3[lib] |= (group_at(board, c) == group_from) << (16 + 3 - fn__i);
1089 fn__i++;
1092 #endif
1095 coord_t last_in_group;
1096 foreach_in_group(board, group_from) {
1097 last_in_group = c;
1098 group_at(board, c) = group_to;
1099 } foreach_in_group_end;
1100 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1101 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1102 memset(gi_from, 0, sizeof(struct group));
1104 if (DEBUGL(7))
1105 fprintf(stderr, "board_play_raw: merged group: %d\n",
1106 group_base(group_to));
1109 static group_t profiling_noinline
1110 new_group(struct board *board, coord_t coord)
1112 group_t group = coord;
1113 struct group *gi = &board_group_info(board, group);
1114 foreach_neighbor(board, coord, {
1115 if (board_at(board, c) == S_NONE)
1116 /* board_group_addlib is ridiculously expensive for us */
1117 #if GROUP_KEEP_LIBS < 4
1118 if (gi->libs < GROUP_KEEP_LIBS)
1119 #endif
1120 gi->lib[gi->libs++] = c;
1123 group_at(board, coord) = group;
1124 groupnext_at(board, coord) = 0;
1126 if (gi->libs == 2)
1127 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1128 else if (gi->libs == 1)
1129 board_capturable_add(board, group, gi->lib[0], true);
1130 check_libs_consistency(board, group);
1132 if (DEBUGL(8))
1133 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1134 coord_x(coord, board), coord_y(coord, board),
1135 group_base(group));
1137 return group;
1140 static inline group_t
1141 play_one_neighbor(struct board *board,
1142 coord_t coord, enum stone color, enum stone other_color,
1143 coord_t c, group_t group)
1145 enum stone ncolor = board_at(board, c);
1146 group_t ngroup = group_at(board, c);
1148 inc_neighbor_count_at(board, c, color);
1149 /* We can be S_NONE, in that case we need to update the safety
1150 * trait since we might be left with only one liberty. */
1151 board_trait_queue(board, c);
1153 if (!ngroup)
1154 return group;
1156 board_group_rmlib(board, ngroup, coord);
1157 if (DEBUGL(7))
1158 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1159 group_base(ngroup), ncolor, color, other_color);
1161 if (ncolor == color && ngroup != group) {
1162 if (!group) {
1163 group = ngroup;
1164 add_to_group(board, group, c, coord);
1165 } else {
1166 merge_groups(board, group, ngroup);
1168 } else if (ncolor == other_color) {
1169 if (DEBUGL(8)) {
1170 struct group *gi = &board_group_info(board, ngroup);
1171 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1172 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1173 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1174 fprintf(stderr, "\n");
1176 if (unlikely(board_group_captured(board, ngroup)))
1177 board_group_capture(board, ngroup);
1179 return group;
1182 /* We played on a place with at least one liberty. We will become a member of
1183 * some group for sure. */
1184 static group_t profiling_noinline
1185 board_play_outside(struct board *board, struct move *m, int f)
1187 coord_t coord = m->coord;
1188 enum stone color = m->color;
1189 enum stone other_color = stone_other(color);
1190 group_t group = 0;
1192 board->f[f] = board->f[--board->flen];
1193 if (DEBUGL(6))
1194 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1196 #if defined(BOARD_TRAITS) && defined(DEBUG)
1197 /* Sanity check that cap matches reality. */
1199 int a = 0, b = 0;
1200 foreach_neighbor(board, coord, {
1201 group_t g = group_at(board, c);
1202 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1203 b += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1) && group_is_onestone(board, g);
1205 assert(a == trait_at(board, coord, color).cap);
1206 assert(b == trait_at(board, coord, color).cap1);
1207 #ifdef BOARD_TRAIT_SAFE
1208 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1209 #endif
1211 #endif
1212 foreach_neighbor(board, coord, {
1213 group = play_one_neighbor(board, coord, color, other_color, c, group);
1216 board_at(board, coord) = color;
1217 if (unlikely(!group))
1218 group = new_group(board, coord);
1220 board->last_move2 = board->last_move;
1221 board->last_move = *m;
1222 board->moves++;
1223 board_hash_update(board, coord, color);
1224 board_symmetry_update(board, &board->symmetry, coord);
1225 struct move ko = { pass, S_NONE };
1226 board->ko = ko;
1228 check_pat3_consistency(board, coord);
1230 return group;
1233 /* We played in an eye-like shape. Either we capture at least one of the eye
1234 * sides in the process of playing, or return -1. */
1235 static int profiling_noinline
1236 board_play_in_eye(struct board *board, struct move *m, int f)
1238 coord_t coord = m->coord;
1239 enum stone color = m->color;
1240 /* Check ko: Capture at a position of ko capture one move ago */
1241 if (unlikely(color == board->ko.color && coord == board->ko.coord)) {
1242 if (DEBUGL(5))
1243 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1244 return -1;
1245 } else if (DEBUGL(6)) {
1246 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1247 color, coord_x(coord, board), coord_y(coord, board),
1248 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1251 struct move ko = { pass, S_NONE };
1253 int captured_groups = 0;
1255 foreach_neighbor(board, coord, {
1256 group_t g = group_at(board, c);
1257 if (DEBUGL(7))
1258 fprintf(stderr, "board_check: group %d has %d libs\n",
1259 g, board_group_info(board, g).libs);
1260 captured_groups += (board_group_info(board, g).libs == 1);
1263 if (likely(captured_groups == 0)) {
1264 if (DEBUGL(5)) {
1265 if (DEBUGL(6))
1266 board_print(board, stderr);
1267 fprintf(stderr, "board_check: one-stone suicide\n");
1270 return -1;
1272 #ifdef BOARD_TRAITS
1273 /* We _will_ for sure capture something. */
1274 assert(trait_at(board, coord, color).cap > 0);
1275 #ifdef BOARD_TRAIT_SAFE
1276 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1277 #endif
1278 #endif
1280 board->f[f] = board->f[--board->flen];
1281 if (DEBUGL(6))
1282 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1284 int ko_caps = 0;
1285 coord_t cap_at = pass;
1286 foreach_neighbor(board, coord, {
1287 inc_neighbor_count_at(board, c, color);
1288 /* Originally, this could not have changed any trait
1289 * since no neighbors were S_NONE, however by now some
1290 * of them might be removed from the board. */
1291 board_trait_queue(board, c);
1293 group_t group = group_at(board, c);
1294 if (!group)
1295 continue;
1297 board_group_rmlib(board, group, coord);
1298 if (DEBUGL(7))
1299 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1300 group_base(group));
1302 if (board_group_captured(board, group)) {
1303 ko_caps += board_group_capture(board, group);
1304 cap_at = c;
1307 if (ko_caps == 1) {
1308 ko.color = stone_other(color);
1309 ko.coord = cap_at; // unique
1310 board->last_ko = ko;
1311 board->last_ko_age = board->moves;
1312 if (DEBUGL(5))
1313 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1316 board_at(board, coord) = color;
1317 group_t group = new_group(board, coord);
1319 board->last_move2 = board->last_move;
1320 board->last_move = *m;
1321 board->moves++;
1322 board_hash_update(board, coord, color);
1323 board_hash_commit(board);
1324 board_traits_recompute(board);
1325 board_symmetry_update(board, &board->symmetry, coord);
1326 board->ko = ko;
1328 check_pat3_consistency(board, coord);
1330 return !!group;
1333 static int __attribute__((flatten))
1334 board_play_f(struct board *board, struct move *m, int f)
1336 if (DEBUGL(7)) {
1337 fprintf(stderr, "board_play(%s): ---- Playing %d,%d\n", coord2sstr(m->coord, board), coord_x(m->coord, board), coord_y(m->coord, board));
1339 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1340 /* NOT playing in an eye. Thus this move has to succeed. (This
1341 * is thanks to New Zealand rules. Otherwise, multi-stone
1342 * suicide might fail.) */
1343 group_t group = board_play_outside(board, m, f);
1344 if (unlikely(board_group_captured(board, group))) {
1345 board_group_capture(board, group);
1347 board_hash_commit(board);
1348 board_traits_recompute(board);
1349 return 0;
1350 } else {
1351 return board_play_in_eye(board, m, f);
1356 board_play(struct board *board, struct move *m)
1358 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1359 struct move nomove = { pass, S_NONE };
1360 board->ko = nomove;
1361 board->last_move4 = board->last_move3;
1362 board->last_move3 = board->last_move2;
1363 board->last_move2 = board->last_move;
1364 board->last_move = *m;
1365 return 0;
1368 int f;
1369 for (f = 0; f < board->flen; f++)
1370 if (board->f[f] == m->coord)
1371 return board_play_f(board, m, f);
1373 if (DEBUGL(7))
1374 fprintf(stderr, "board_check: stone exists\n");
1375 return -1;
1378 /* Undo, supported only for pass moves. This form of undo is required by KGS
1379 * to settle disputes on dead groups. (Undo of real moves would be more complex
1380 * particularly for capturing moves.) */
1381 int board_undo(struct board *board)
1383 if (!is_pass(board->last_move.coord))
1384 return -1;
1385 board->last_move = board->last_move2;
1386 board->last_move2 = board->last_move3;
1387 board->last_move3 = board->last_move4;
1388 if (board->last_ko_age == board->moves)
1389 board->ko = board->last_ko;
1390 return 0;
1393 static inline bool
1394 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1396 *coord = b->f[f];
1397 struct move m = { *coord, color };
1398 if (DEBUGL(6))
1399 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));
1400 if (unlikely(board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1401 || !board_is_valid_move(b, &m)
1402 || (permit && !permit(permit_data, b, &m)))
1403 return false;
1404 if (m.coord == *coord) {
1405 return likely(board_play_f(b, &m, f) >= 0);
1406 } else {
1407 *coord = m.coord; // permit modified the coordinate
1408 return likely(board_play(b, &m) >= 0);
1412 void
1413 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1415 if (unlikely(b->flen == 0))
1416 goto pass;
1418 int base = fast_random(b->flen), f;
1419 for (f = base; f < b->flen; f++)
1420 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1421 return;
1422 for (f = 0; f < base; f++)
1423 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1424 return;
1426 pass:
1427 *coord = pass;
1428 struct move m = { pass, color };
1429 board_play(b, &m);
1433 bool
1434 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1436 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1438 /* XXX: We attempt false eye detection but we will yield false
1439 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1441 foreach_diag_neighbor(board, coord) {
1442 color_diag_libs[(enum stone) board_at(board, c)]++;
1443 } foreach_diag_neighbor_end;
1444 /* For false eye, we need two enemy stones diagonally in the
1445 * middle of the board, or just one enemy stone at the edge
1446 * or in the corner. */
1447 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1448 return color_diag_libs[stone_other(eye_color)] >= 2;
1451 bool
1452 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1454 return board_is_eyelike(board, coord, eye_color)
1455 && !board_is_false_eyelike(board, coord, eye_color);
1458 enum stone
1459 board_get_one_point_eye(struct board *board, coord_t coord)
1461 if (board_is_one_point_eye(board, coord, S_WHITE))
1462 return S_WHITE;
1463 else if (board_is_one_point_eye(board, coord, S_BLACK))
1464 return S_BLACK;
1465 else
1466 return S_NONE;
1470 floating_t
1471 board_fast_score(struct board *board)
1473 int scores[S_MAX];
1474 memset(scores, 0, sizeof(scores));
1476 foreach_point(board) {
1477 enum stone color = board_at(board, c);
1478 if (color == S_NONE && board->rules != RULES_STONES_ONLY)
1479 color = board_get_one_point_eye(board, c);
1480 scores[color]++;
1481 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1482 } foreach_point_end;
1484 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1487 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1489 /* One flood-fill iteration; returns true if next iteration
1490 * is required. */
1491 static bool
1492 board_tromp_taylor_iter(struct board *board, int *ownermap)
1494 bool needs_update = false;
1495 foreach_free_point(board) {
1496 /* Ignore occupied and already-dame positions. */
1497 assert(board_at(board, c) == S_NONE);
1498 if (board->rules == RULES_STONES_ONLY)
1499 ownermap[c] = 3;
1500 if (ownermap[c] == 3)
1501 continue;
1502 /* Count neighbors. */
1503 int nei[4] = {0};
1504 foreach_neighbor(board, c, {
1505 nei[ownermap[c]]++;
1507 /* If we have neighbors of both colors, or dame,
1508 * we are dame too. */
1509 if ((nei[1] && nei[2]) || nei[3]) {
1510 ownermap[c] = 3;
1511 /* Speed up the propagation. */
1512 foreach_neighbor(board, c, {
1513 if (board_at(board, c) == S_NONE)
1514 ownermap[c] = 3;
1516 needs_update = true;
1517 continue;
1519 /* If we have neighbors of one color, we are owned
1520 * by that color, too. */
1521 if (!ownermap[c] && (nei[1] || nei[2])) {
1522 int newowner = nei[1] ? 1 : 2;
1523 ownermap[c] = newowner;
1524 /* Speed up the propagation. */
1525 foreach_neighbor(board, c, {
1526 if (board_at(board, c) == S_NONE && !ownermap[c])
1527 ownermap[c] = newowner;
1529 needs_update = true;
1530 continue;
1532 } foreach_free_point_end;
1533 return needs_update;
1536 /* Tromp-Taylor Counting */
1537 floating_t
1538 board_official_score(struct board *board, struct move_queue *q)
1541 /* A point P, not colored C, is said to reach C, if there is a path of
1542 * (vertically or horizontally) adjacent points of P's color from P to
1543 * a point of color C.
1545 * A player's score is the number of points of her color, plus the
1546 * number of empty points that reach only her color. */
1548 int ownermap[board_size2(board)];
1549 int s[4] = {0};
1550 const int o[4] = {0, 1, 2, 0};
1551 foreach_point(board) {
1552 ownermap[c] = o[board_at(board, c)];
1553 s[board_at(board, c)]++;
1554 } foreach_point_end;
1556 if (q) {
1557 /* Process dead groups. */
1558 for (unsigned int i = 0; i < q->moves; i++) {
1559 foreach_in_group(board, q->move[i]) {
1560 enum stone color = board_at(board, c);
1561 ownermap[c] = o[stone_other(color)];
1562 s[color]--; s[stone_other(color)]++;
1563 } foreach_in_group_end;
1567 /* We need to special-case empty board. */
1568 if (!s[S_BLACK] && !s[S_WHITE])
1569 return board->komi + board->handicap;
1571 while (board_tromp_taylor_iter(board, ownermap))
1572 /* Flood-fill... */;
1574 int scores[S_MAX];
1575 memset(scores, 0, sizeof(scores));
1577 foreach_point(board) {
1578 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1579 if (ownermap[c] == 3)
1580 continue;
1581 scores[ownermap[c]]++;
1582 } foreach_point_end;
1584 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];