board_undo: define QUICK_BOARD_CODE to get compiler error with forbidden fields.
[pachi.git] / board.c
blobebb07eaa3e2b0f3223682054e871869c9904f3b8
1 #include <assert.h>
2 #include <math.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
7 //#define DEBUG
8 #include "board.h"
9 #include "debug.h"
10 #include "fbook.h"
11 #include "mq.h"
12 #include "random.h"
14 #ifdef BOARD_SPATHASH
15 #include "patternsp.h"
16 #endif
17 #ifdef BOARD_PAT3
18 #include "pattern3.h"
19 #endif
20 #ifdef BOARD_TRAITS
21 static void board_trait_recompute(struct board *board, coord_t coord);
22 #include "tactics/selfatari.h"
23 #endif
26 #if 0
27 #define profiling_noinline __attribute__((noinline))
28 #else
29 #define profiling_noinline
30 #endif
32 #define gi_granularity 4
33 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
36 static void
37 board_setup(struct board *b)
39 memset(b, 0, sizeof(*b));
41 struct move m = { pass, S_NONE };
42 b->last_move = b->last_move2 = b->last_move3 = b->last_move4 = b->last_ko = b->ko = m;
45 struct board *
46 board_init(char *fbookfile)
48 struct board *b = malloc2(sizeof(struct board));
49 board_setup(b);
51 b->fbookfile = fbookfile;
53 // Default setup
54 b->size = 9 + 2;
55 board_clear(b);
57 return b;
60 static size_t
61 board_alloc(struct board *board)
63 /* We do not allocate the board structure itself but we allocate
64 * all the arrays with board contents. */
66 int bsize = board_size2(board) * sizeof(*board->b);
67 int gsize = board_size2(board) * sizeof(*board->g);
68 int fsize = board_size2(board) * sizeof(*board->f);
69 int nsize = board_size2(board) * sizeof(*board->n);
70 int psize = board_size2(board) * sizeof(*board->p);
71 int hsize = board_size2(board) * 2 * sizeof(*board->h);
72 int gisize = board_size2(board) * sizeof(*board->gi);
73 #ifdef WANT_BOARD_C
74 int csize = board_size2(board) * sizeof(*board->c);
75 #else
76 int csize = 0;
77 #endif
78 #ifdef BOARD_SPATHASH
79 int ssize = board_size2(board) * sizeof(*board->spathash);
80 #else
81 int ssize = 0;
82 #endif
83 #ifdef BOARD_PAT3
84 int p3size = board_size2(board) * sizeof(*board->pat3);
85 #else
86 int p3size = 0;
87 #endif
88 #ifdef BOARD_TRAITS
89 int tsize = board_size2(board) * sizeof(*board->t);
90 int tqsize = board_size2(board) * sizeof(*board->t);
91 #else
92 int tsize = 0;
93 int tqsize = 0;
94 #endif
95 int cdsize = board_size2(board) * sizeof(*board->coord);
97 size_t size = bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + cdsize;
98 void *x = malloc2(size);
100 /* board->b must come first */
101 board->b = x; x += bsize;
102 board->g = x; x += gsize;
103 board->f = x; x += fsize;
104 board->p = x; x += psize;
105 board->n = x; x += nsize;
106 board->h = x; x += hsize;
107 board->gi = x; x += gisize;
108 #ifdef WANT_BOARD_C
109 board->c = x; x += csize;
110 #endif
111 #ifdef BOARD_SPATHASH
112 board->spathash = x; x += ssize;
113 #endif
114 #ifdef BOARD_PAT3
115 board->pat3 = x; x += p3size;
116 #endif
117 #ifdef BOARD_TRAITS
118 board->t = x; x += tsize;
119 board->tq = x; x += tqsize;
120 #endif
121 board->coord = x; x += cdsize;
123 return size;
127 board_cmp(struct board *b1, struct board *b2)
129 void **p1 = (void**)b1, **p2 = (void**)b2;
130 for (unsigned int i = 0; i < sizeof(struct board) / sizeof(void*); i++)
131 if (p1[i] != p2[i] &&
132 &p1[i] != (void**)&b1->b &&
133 &p1[i] != (void**)&b1->g &&
134 &p1[i] != (void**)&b1->f &&
135 &p1[i] != (void**)&b1->n &&
136 &p1[i] != (void**)&b1->p &&
137 &p1[i] != (void**)&b1->h &&
138 &p1[i] != (void**)&b1->gi &&
139 #ifdef WANT_BOARD_C
140 &p1[i] != (void**)&b1->c &&
141 #endif
142 #ifdef BOARD_SPATHASH
143 &p1[i] != (void**)&b1->spathash &&
144 #endif
145 #ifdef BOARD_PAT3
146 &p1[i] != (void**)&b1->pat3 &&
147 #endif
148 #ifdef BOARD_TRAITS
149 &p1[i] != (void**)&b1->t &&
150 &p1[i] != (void**)&b1->tq &&
151 #endif
152 &p1[i] != (void**)&b1->coord)
153 return 1;
155 /* Find alloc size */
156 struct board tmp;
157 board_setup(&tmp);
158 size_t size = board_alloc(&tmp);
159 board_done_noalloc(&tmp);
161 return memcmp(b1->b, b2->b, size);
167 struct board *
168 board_copy(struct board *b2, struct board *b1)
170 memcpy(b2, b1, sizeof(struct board));
172 size_t size = board_alloc(b2);
173 memcpy(b2->b, b1->b, size);
175 // XXX: Special semantics.
176 b2->fbook = NULL;
178 return b2;
181 void
182 board_done_noalloc(struct board *board)
184 if (board->b) free(board->b);
185 if (board->fbook) fbook_done(board->fbook);
188 void
189 board_done(struct board *board)
191 board_done_noalloc(board);
192 free(board);
195 void
196 board_resize(struct board *board, int size)
198 #ifdef BOARD_SIZE
199 assert(board_size(board) == size + 2);
200 #endif
201 assert(size <= BOARD_MAX_SIZE);
202 board->size = size + 2 /* S_OFFBOARD margin */;
203 board->size2 = board_size(board) * board_size(board);
205 board->bits2 = 1;
206 while ((1 << board->bits2) < board->size2) board->bits2++;
208 if (board->b)
209 free(board->b);
211 size_t asize = board_alloc(board);
212 memset(board->b, 0, asize);
215 static void
216 board_init_data(struct board *board)
218 int size = board_size(board);
220 board_setup(board);
221 board_resize(board, size - 2 /* S_OFFBOARD margin */);
223 /* Setup neighborhood iterators */
224 board->nei8[0] = -size - 1; // (-1,-1)
225 board->nei8[1] = 1;
226 board->nei8[2] = 1;
227 board->nei8[3] = size - 2; // (-1,0)
228 board->nei8[4] = 2;
229 board->nei8[5] = size - 2; // (-1,1)
230 board->nei8[6] = 1;
231 board->nei8[7] = 1;
232 board->dnei[0] = -size - 1;
233 board->dnei[1] = 2;
234 board->dnei[2] = size*2 - 2;
235 board->dnei[3] = 2;
237 /* Setup initial symmetry */
238 if (size % 2) {
239 board->symmetry.d = 1;
240 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
241 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
242 board->symmetry.type = SYM_FULL;
243 } else {
244 /* TODO: We do not handle board symmetry on boards
245 * with no tengen yet. */
246 board->symmetry.d = 0;
247 board->symmetry.x1 = board->symmetry.y1 = 1;
248 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
249 board->symmetry.type = SYM_NONE;
252 /* Set up coordinate cache */
253 foreach_point(board) {
254 board->coord[c][0] = c % board_size(board);
255 board->coord[c][1] = c / board_size(board);
256 } foreach_point_end;
258 /* Draw the offboard margin */
259 int top_row = board_size2(board) - board_size(board);
260 int i;
261 for (i = 0; i < board_size(board); i++)
262 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
263 for (i = 0; i <= top_row; i += board_size(board))
264 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
266 foreach_point(board) {
267 coord_t coord = c;
268 if (board_at(board, coord) == S_OFFBOARD)
269 continue;
270 foreach_neighbor(board, c, {
271 inc_neighbor_count_at(board, coord, board_at(board, c));
272 } );
273 } foreach_point_end;
275 /* All positions are free! Except the margin. */
276 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
277 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
278 board->f[board->flen++] = i;
280 /* Initialize zobrist hashtable. */
281 /* We will need these to be stable across Pachi runs for
282 * certain kinds of pattern matching, thus we do not use
283 * fast_random() for this. */
284 hash_t hseed = 0x3121110101112131;
285 foreach_point(board) {
286 board->h[c * 2] = (hseed *= 16807);
287 if (!board->h[c * 2])
288 board->h[c * 2] = 1;
289 /* And once again for white */
290 board->h[c * 2 + 1] = (hseed *= 16807);
291 if (!board->h[c * 2 + 1])
292 board->h[c * 2 + 1] = 1;
293 } foreach_point_end;
295 #ifdef BOARD_SPATHASH
296 /* Initialize spatial hashes. */
297 foreach_point(board) {
298 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
299 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
300 ptcoords_at(x, y, c, board, j);
301 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
302 pthashes[0][j][board_at(board, c)];
303 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
304 pthashes[0][j][stone_other(board_at(board, c))];
307 } foreach_point_end;
308 #endif
309 #ifdef BOARD_PAT3
310 /* Initialize 3x3 pattern codes. */
311 foreach_point(board) {
312 if (board_at(board, c) == S_NONE)
313 board->pat3[c] = pattern3_hash(board, c);
314 } foreach_point_end;
315 #endif
316 #ifdef BOARD_TRAITS
317 /* Initialize traits. */
318 foreach_point(board) {
319 trait_at(board, c, S_BLACK).cap = 0;
320 trait_at(board, c, S_WHITE).cap = 0;
321 trait_at(board, c, S_BLACK).cap1 = 0;
322 trait_at(board, c, S_WHITE).cap1 = 0;
323 #ifdef BOARD_TRAIT_SAFE
324 trait_at(board, c, S_BLACK).safe = true;
325 trait_at(board, c, S_WHITE).safe = true;
326 #endif
327 } foreach_point_end;
328 #endif
331 void
332 board_clear(struct board *board)
334 int size = board_size(board);
335 floating_t komi = board->komi;
336 char *fbookfile = board->fbookfile;
337 enum go_ruleset rules = board->rules;
339 board_done_noalloc(board);
341 static struct board bcache[BOARD_MAX_SIZE + 2];
342 assert(size > 0 && size <= BOARD_MAX_SIZE + 2);
343 if (bcache[size - 1].size == size) {
344 board_copy(board, &bcache[size - 1]);
345 } else {
346 board_init_data(board);
347 board_copy(&bcache[size - 1], board);
350 board->komi = komi;
351 board->fbookfile = fbookfile;
352 board->rules = rules;
354 if (board->fbookfile) {
355 board->fbook = fbook_init(board->fbookfile, board);
359 static char *
360 board_print_top(struct board *board, char *s, char *end, int c)
362 for (int i = 0; i < c; i++) {
363 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
364 s += snprintf(s, end - s, " ");
365 for (int x = 1; x < board_size(board) - 1; x++)
366 s += snprintf(s, end - s, "%c ", asdf[x - 1]);
367 s += snprintf(s, end -s, " ");
369 s += snprintf(s, end - s, "\n");
370 for (int i = 0; i < c; i++) {
371 s += snprintf(s, end - s, " +-");
372 for (int x = 1; x < board_size(board) - 1; x++)
373 s += snprintf(s, end - s, "--");
374 s += snprintf(s, end - s, "+");
376 s += snprintf(s, end - s, "\n");
377 return s;
380 static char *
381 board_print_bottom(struct board *board, char *s, char *end, int c)
383 for (int i = 0; i < c; i++) {
384 s += snprintf(s, end - s, " +-");
385 for (int x = 1; x < board_size(board) - 1; x++)
386 s += snprintf(s, end - s, "--");
387 s += snprintf(s, end - s, "+");
389 s += snprintf(s, end - s, "\n");
390 return s;
393 static char *
394 board_print_row(struct board *board, int y, char *s, char *end, board_cprint cprint, void *data)
396 s += snprintf(s, end - s, " %2d | ", y);
397 for (int x = 1; x < board_size(board) - 1; x++) {
398 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
399 s += snprintf(s, end - s, "%c)", stone2char(board_atxy(board, x, y)));
400 else
401 s += snprintf(s, end - s, "%c ", stone2char(board_atxy(board, x, y)));
403 s += snprintf(s, end - s, "|");
404 if (cprint) {
405 s += snprintf(s, end - s, " %2d | ", y);
406 for (int x = 1; x < board_size(board) - 1; x++) {
407 s = cprint(board, coord_xy(board, x, y), s, end, data);
409 s += snprintf(s, end - s, "|");
411 s += snprintf(s, end - s, "\n");
412 return s;
415 void
416 board_print_custom(struct board *board, FILE *f, board_cprint cprint, void *data)
418 char buf[10240];
419 char *s = buf;
420 char *end = buf + sizeof(buf);
421 s += snprintf(s, end - s, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
422 board->moves, board->komi, board->handicap,
423 board->captures[S_BLACK], board->captures[S_WHITE]);
424 s = board_print_top(board, s, end, 1 + !!cprint);
425 for (int y = board_size(board) - 2; y >= 1; y--)
426 s = board_print_row(board, y, s, end, cprint, data);
427 board_print_bottom(board, s, end, 1 + !!cprint);
428 fprintf(f, "%s\n", buf);
431 static char *
432 cprint_group(struct board *board, coord_t c, char *s, char *end, void *data)
434 s += snprintf(s, end - s, "%d ", group_base(group_at(board, c)));
435 return s;
438 void
439 board_print(struct board *board, FILE *f)
441 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL, NULL);
445 #ifdef BOARD_TRAITS
447 #if BOARD_TRAIT_SAFE == 1
448 static bool
449 board_trait_safe(struct board *board, coord_t coord, enum stone color)
451 return board_safe_to_play(board, coord, color);
453 #elif BOARD_TRAIT_SAFE == 2
454 static bool
455 board_trait_safe(struct board *board, coord_t coord, enum stone color)
457 return !is_bad_selfatari(board, color, coord);
459 #endif
461 static void
462 board_trait_recompute(struct board *board, coord_t coord)
464 int sfb = -1, sfw = -1;
465 #ifdef BOARD_TRAIT_SAFE
466 sfb = trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);
467 sfw = trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
468 #endif
469 if (DEBUGL(8)) {
470 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d cap1=%d safe=%d) (white cap=%d cap1=%d safe=%d)\n",
471 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
472 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).cap1, sfb,
473 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).cap1, sfw);
476 #endif
478 /* Recompute traits for dirty points that we have previously touched
479 * somehow (libs of their neighbors changed or so). */
480 static void
481 board_traits_recompute(struct board *board)
483 #ifdef BOARD_TRAITS
484 for (int i = 0; i < board->tqlen; i++) {
485 coord_t coord = board->tq[i];
486 trait_at(board, coord, S_BLACK).dirty = false;
487 if (board_at(board, coord) != S_NONE)
488 continue;
489 board_trait_recompute(board, coord);
491 board->tqlen = 0;
492 #endif
495 /* Queue traits of given point for recomputing. */
496 static void
497 board_trait_queue(struct board *board, coord_t coord)
499 #ifdef BOARD_TRAITS
500 if (trait_at(board, coord, S_BLACK).dirty)
501 return;
502 board->tq[board->tqlen++] = coord;
503 trait_at(board, coord, S_BLACK).dirty = true;
504 #endif
508 /* Update board hash with given coordinate. */
509 static void profiling_noinline
510 board_hash_update(struct board *board, coord_t coord, enum stone color)
512 board->hash ^= hash_at(board, coord, color);
513 board->qhash[coord_quadrant(coord, board)] ^= hash_at(board, coord, color);
514 if (DEBUGL(8))
515 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);
517 #ifdef BOARD_SPATHASH
518 /* Gridcular metric is reflective, so we update all hashes
519 * of appropriate ditance in OUR circle. */
520 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
521 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
522 ptcoords_at(x, y, coord, board, j);
523 /* We either changed from S_NONE to color
524 * or vice versa; doesn't matter. */
525 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
526 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
527 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
528 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
531 #endif
533 #if defined(BOARD_PAT3)
534 /* @color is not what we need in case of capture. */
535 static const int ataribits[8] = { -1, 0, -1, 1, 2, -1, 3, -1 };
536 enum stone new_color = board_at(board, coord);
537 bool in_atari = false;
538 if (new_color == S_NONE) {
539 board->pat3[coord] = pattern3_hash(board, coord);
540 } else {
541 in_atari = (board_group_info(board, group_at(board, coord)).libs == 1);
543 foreach_8neighbor(board, coord) {
544 /* Internally, the loop uses fn__i=[0..7]. We can use
545 * it directly to address bits within the bitmap of the
546 * neighbors since the bitmap order is reverse to the
547 * loop order. */
548 if (board_at(board, c) != S_NONE)
549 continue;
550 board->pat3[c] &= ~(3 << (fn__i*2));
551 board->pat3[c] |= new_color << (fn__i*2);
552 if (ataribits[fn__i] >= 0) {
553 board->pat3[c] &= ~(1 << (16 + ataribits[fn__i]));
554 board->pat3[c] |= in_atari << (16 + ataribits[fn__i]);
556 #if defined(BOARD_TRAITS)
557 board_trait_queue(board, c);
558 #endif
559 } foreach_8neighbor_end;
560 #endif
563 /* Commit current board hash to history. */
564 static void profiling_noinline
565 board_hash_commit(struct board *board)
567 if (DEBUGL(8))
568 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
569 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
570 board->history_hash[board->hash & history_hash_mask] = board->hash;
571 } else {
572 hash_t i = board->hash;
573 while (board->history_hash[i & history_hash_mask]) {
574 if (board->history_hash[i & history_hash_mask] == board->hash) {
575 if (DEBUGL(5))
576 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
577 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
578 board->superko_violation = true;
579 return;
581 i = history_hash_next(i);
583 board->history_hash[i & history_hash_mask] = board->hash;
588 void
589 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
591 if (likely(symmetry->type == SYM_NONE)) {
592 /* Fully degenerated already. We do not support detection
593 * of restoring of symmetry, assuming that this is too rare
594 * a case to handle. */
595 return;
598 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
599 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
600 if (DEBUGL(6)) {
601 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
602 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
603 symmetry->d, symmetry->type, x, y);
606 switch (symmetry->type) {
607 case SYM_FULL:
608 if (x == t && y == t) {
609 /* Tengen keeps full symmetry. */
610 return;
612 /* New symmetry now? */
613 if (x == y) {
614 symmetry->type = SYM_DIAG_UP;
615 symmetry->x1 = symmetry->y1 = 1;
616 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
617 symmetry->d = 1;
618 } else if (dx == y) {
619 symmetry->type = SYM_DIAG_DOWN;
620 symmetry->x1 = symmetry->y1 = 1;
621 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
622 symmetry->d = 1;
623 } else if (x == t) {
624 symmetry->type = SYM_HORIZ;
625 symmetry->y1 = 1;
626 symmetry->y2 = board_size(b) - 1;
627 symmetry->d = 0;
628 } else if (y == t) {
629 symmetry->type = SYM_VERT;
630 symmetry->x1 = 1;
631 symmetry->x2 = board_size(b) - 1;
632 symmetry->d = 0;
633 } else {
634 break_symmetry:
635 symmetry->type = SYM_NONE;
636 symmetry->x1 = symmetry->y1 = 1;
637 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
638 symmetry->d = 0;
640 break;
641 case SYM_DIAG_UP:
642 if (x == y)
643 return;
644 goto break_symmetry;
645 case SYM_DIAG_DOWN:
646 if (dx == y)
647 return;
648 goto break_symmetry;
649 case SYM_HORIZ:
650 if (x == t)
651 return;
652 goto break_symmetry;
653 case SYM_VERT:
654 if (y == t)
655 return;
656 goto break_symmetry;
657 case SYM_NONE:
658 assert(0);
659 break;
662 if (DEBUGL(6)) {
663 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
664 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
665 symmetry->d, symmetry->type);
667 /* Whew. */
671 void
672 board_handicap_stone(struct board *board, int x, int y, FILE *f)
674 struct move m;
675 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
677 board_play(board, &m);
678 /* Simulate white passing; otherwise, UCT search can get confused since
679 * tree depth parity won't match the color to move. */
680 board->moves++;
682 char *str = coord2str(m.coord, board);
683 if (DEBUGL(1))
684 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
685 if (f) fprintf(f, "%s ", str);
686 free(str);
689 void
690 board_handicap(struct board *board, int stones, FILE *f)
692 int margin = 3 + (board_size(board) >= 13);
693 int min = margin;
694 int mid = board_size(board) / 2;
695 int max = board_size(board) - 1 - margin;
696 const int places[][2] = {
697 { min, min }, { max, max }, { min, max }, { max, min },
698 { min, mid }, { max, mid },
699 { mid, min }, { mid, max },
700 { mid, mid },
703 board->handicap = stones;
705 if (stones == 5 || stones == 7) {
706 board_handicap_stone(board, mid, mid, f);
707 stones--;
710 int i;
711 for (i = 0; i < stones; i++)
712 board_handicap_stone(board, places[i][0], places[i][1], f);
716 static void __attribute__((noinline))
717 check_libs_consistency(struct board *board, group_t g)
719 #ifdef DEBUG
720 if (!g) return;
721 struct group *gi = &board_group_info(board, g);
722 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
723 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
724 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
725 assert(0);
727 #endif
730 static void
731 check_pat3_consistency(struct board *board, coord_t coord)
733 #ifdef DEBUG
734 foreach_8neighbor(board, coord) {
735 if (board_at(board, c) == S_NONE && pattern3_hash(board, c) != board->pat3[c]) {
736 board_print(board, stderr);
737 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);
738 assert(0);
740 } foreach_8neighbor_end;
741 #endif
744 static void
745 board_capturable_add(struct board *board, group_t group, coord_t lib, bool onestone)
747 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
748 #ifdef BOARD_TRAITS
749 /* Increase capturable count trait of my last lib. */
750 enum stone capturing_color = stone_other(board_at(board, group));
751 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
752 foreach_neighbor(board, lib, {
753 if (DEBUGL(8) && group_at(board, c) == group)
754 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);
755 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
756 trait_at(board, lib, capturing_color).cap1 += (group_at(board, c) == group && onestone);
758 board_trait_queue(board, lib);
759 #endif
761 #ifdef BOARD_PAT3
762 int fn__i = 0;
763 foreach_neighbor(board, lib, {
764 board->pat3[lib] |= (group_at(board, c) == group) << (16 + 3 - fn__i);
765 fn__i++;
767 #endif
769 #ifdef WANT_BOARD_C
770 /* Update the list of capturable groups. */
771 assert(group);
772 assert(board->clen < board_size2(board));
773 board->c[board->clen++] = group;
774 #endif
776 static void
777 board_capturable_rm(struct board *board, group_t group, coord_t lib, bool onestone)
779 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
780 #ifdef BOARD_TRAITS
781 /* Decrease capturable count trait of my previously-last lib. */
782 enum stone capturing_color = stone_other(board_at(board, group));
783 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
784 foreach_neighbor(board, lib, {
785 if (DEBUGL(8) && group_at(board, c) == group)
786 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);
787 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
788 trait_at(board, lib, capturing_color).cap1 -= (group_at(board, c) == group && onestone);
790 board_trait_queue(board, lib);
791 #endif
793 #ifdef BOARD_PAT3
794 int fn__i = 0;
795 foreach_neighbor(board, lib, {
796 board->pat3[lib] &= ~((group_at(board, c) == group) << (16 + 3 - fn__i));
797 fn__i++;
799 #endif
801 #ifdef WANT_BOARD_C
802 /* Update the list of capturable groups. */
803 for (int i = 0; i < board->clen; i++) {
804 if (unlikely(board->c[i] == group)) {
805 board->c[i] = board->c[--board->clen];
806 return;
809 fprintf(stderr, "rm of bad group %d\n", group_base(group));
810 assert(0);
811 #endif
814 static void
815 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
817 #ifdef BOARD_TRAITS
818 board_trait_queue(board, lib1);
819 board_trait_queue(board, lib2);
820 #endif
822 static void
823 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
825 #ifdef BOARD_TRAITS
826 board_trait_queue(board, lib1);
827 board_trait_queue(board, lib2);
828 #endif
831 static void
832 board_group_addlib(struct board *board, group_t group, coord_t coord)
834 if (DEBUGL(7)) {
835 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
836 group_base(group), coord2sstr(group_base(group), board),
837 board_group_info(board, group).libs, coord2sstr(coord, board));
840 check_libs_consistency(board, group);
842 struct group *gi = &board_group_info(board, group);
843 bool onestone = group_is_onestone(board, group);
844 if (gi->libs < GROUP_KEEP_LIBS) {
845 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
846 #if 0
847 /* Seems extra branch just slows it down */
848 if (!gi->lib[i])
849 break;
850 #endif
851 if (unlikely(gi->lib[i] == coord))
852 return;
854 if (gi->libs == 0) {
855 board_capturable_add(board, group, coord, onestone);
856 } else if (gi->libs == 1) {
857 board_capturable_rm(board, group, gi->lib[0], onestone);
858 board_atariable_add(board, group, gi->lib[0], coord);
859 } else if (gi->libs == 2) {
860 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
862 gi->lib[gi->libs++] = coord;
865 check_libs_consistency(board, group);
868 static void
869 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
871 /* Add extra liberty from the board to our liberty list. */
872 unsigned char watermark[board_size2(board) / 8];
873 memset(watermark, 0, sizeof(watermark));
874 #define watermark_get(c) (watermark[c >> 3] & (1 << (c & 7)))
875 #define watermark_set(c) watermark[c >> 3] |= (1 << (c & 7))
877 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
878 watermark_set(gi->lib[i]);
879 watermark_set(avoid);
881 foreach_in_group(board, group) {
882 coord_t coord2 = c;
883 foreach_neighbor(board, coord2, {
884 if (board_at(board, c) + watermark_get(c) != S_NONE)
885 continue;
886 watermark_set(c);
887 gi->lib[gi->libs++] = c;
888 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
889 return;
890 } );
891 } foreach_in_group_end;
892 #undef watermark_get
893 #undef watermark_set
896 static void
897 board_group_rmlib(struct board *board, group_t group, coord_t coord)
899 if (DEBUGL(7)) {
900 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
901 group_base(group), coord2sstr(group_base(group), board),
902 board_group_info(board, group).libs, coord2sstr(coord, board));
905 struct group *gi = &board_group_info(board, group);
906 bool onestone = group_is_onestone(board, group);
907 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
908 #if 0
909 /* Seems extra branch just slows it down */
910 if (!gi->lib[i])
911 break;
912 #endif
913 if (likely(gi->lib[i] != coord))
914 continue;
916 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
917 gi->lib[gi->libs] = 0;
919 check_libs_consistency(board, group);
921 /* Postpone refilling lib[] until we need to. */
922 assert(GROUP_REFILL_LIBS > 1);
923 if (gi->libs > GROUP_REFILL_LIBS)
924 return;
925 if (gi->libs == GROUP_REFILL_LIBS)
926 board_group_find_extra_libs(board, group, gi, coord);
928 if (gi->libs == 2) {
929 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
930 } else if (gi->libs == 1) {
931 board_capturable_add(board, group, gi->lib[0], onestone);
932 board_atariable_rm(board, group, gi->lib[0], lib);
933 } else if (gi->libs == 0)
934 board_capturable_rm(board, group, lib, onestone);
935 return;
938 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
939 * can call this multiple times per coord. */
940 check_libs_consistency(board, group);
941 return;
945 /* This is a low-level routine that doesn't maintain consistency
946 * of all the board data structures. */
947 static void
948 board_remove_stone(struct board *board, group_t group, coord_t c)
950 enum stone color = board_at(board, c);
951 board_at(board, c) = S_NONE;
952 group_at(board, c) = 0;
953 board_hash_update(board, c, color);
954 #ifdef BOARD_TRAITS
955 /* We mark as cannot-capture now. If this is a ko/snapback,
956 * we will get incremented later in board_group_addlib(). */
957 trait_at(board, c, S_BLACK).cap = trait_at(board, c, S_BLACK).cap1 = 0;
958 trait_at(board, c, S_WHITE).cap = trait_at(board, c, S_WHITE).cap1 = 0;
959 board_trait_queue(board, c);
960 #endif
962 /* Increase liberties of surrounding groups */
963 coord_t coord = c;
964 foreach_neighbor(board, coord, {
965 dec_neighbor_count_at(board, c, color);
966 board_trait_queue(board, c);
967 group_t g = group_at(board, c);
968 if (g && g != group)
969 board_group_addlib(board, g, coord);
972 #ifdef BOARD_PAT3
973 /* board_hash_update() might have seen the freed up point as able
974 * to capture another group in atari that only after the loop
975 * above gained enough liberties. Reset pat3 again. */
976 board->pat3[c] = pattern3_hash(board, c);
977 #endif
979 if (DEBUGL(6))
980 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
981 board->f[board->flen++] = c;
984 static int profiling_noinline
985 board_group_capture(struct board *board, group_t group)
987 int stones = 0;
989 foreach_in_group(board, group) {
990 board->captures[stone_other(board_at(board, c))]++;
991 board_remove_stone(board, group, c);
992 stones++;
993 } foreach_in_group_end;
995 struct group *gi = &board_group_info(board, group);
996 assert(gi->libs == 0);
997 memset(gi, 0, sizeof(*gi));
999 return stones;
1003 static void profiling_noinline
1004 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
1006 #ifdef BOARD_TRAITS
1007 struct group *gi = &board_group_info(board, group);
1008 bool onestone = group_is_onestone(board, group);
1010 if (gi->libs == 1) {
1011 /* Our group is temporarily in atari; make sure the capturable
1012 * counts also correspond to the newly added stone before we
1013 * start adding liberties again so bump-dump ops match. */
1014 enum stone capturing_color = stone_other(board_at(board, group));
1015 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1017 coord_t lib = board_group_info(board, group).lib[0];
1018 if (coord_is_adjecent(lib, coord, board)) {
1019 if (DEBUGL(8))
1020 fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1021 trait_at(board, lib, capturing_color).cap++;
1022 /* This is never a 1-stone group, obviously. */
1023 board_trait_queue(board, lib);
1026 if (onestone) {
1027 /* We are not 1-stone group anymore, update the cap1
1028 * counter specifically. */
1029 foreach_neighbor(board, group, {
1030 if (board_at(board, c) != S_NONE) continue;
1031 trait_at(board, c, capturing_color).cap1--;
1032 board_trait_queue(board, c);
1036 #endif
1038 group_at(board, coord) = group;
1039 groupnext_at(board, coord) = groupnext_at(board, prevstone);
1040 groupnext_at(board, prevstone) = coord;
1042 foreach_neighbor(board, coord, {
1043 if (board_at(board, c) == S_NONE)
1044 board_group_addlib(board, group, c);
1047 if (DEBUGL(8))
1048 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
1049 coord_x(prevstone, board), coord_y(prevstone, board),
1050 coord_x(coord, board), coord_y(coord, board),
1051 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
1052 group_base(group));
1055 static void profiling_noinline
1056 merge_groups(struct board *board, group_t group_to, group_t group_from)
1058 if (DEBUGL(7))
1059 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
1060 group_base(group_from), group_base(group_to));
1061 struct group *gi_from = &board_group_info(board, group_from);
1062 struct group *gi_to = &board_group_info(board, group_to);
1063 bool onestone_from = group_is_onestone(board, group_from);
1064 bool onestone_to = group_is_onestone(board, group_to);
1066 /* We do this early before the group info is rewritten. */
1067 if (gi_from->libs == 2)
1068 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1069 else if (gi_from->libs == 1)
1070 board_capturable_rm(board, group_from, gi_from->lib[0], onestone_from);
1072 if (DEBUGL(7))
1073 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1075 if (gi_to->libs < GROUP_KEEP_LIBS) {
1076 for (int i = 0; i < gi_from->libs; i++) {
1077 for (int j = 0; j < gi_to->libs; j++)
1078 if (gi_to->lib[j] == gi_from->lib[i])
1079 goto next_from_lib;
1080 if (gi_to->libs == 0) {
1081 board_capturable_add(board, group_to, gi_from->lib[i], onestone_to);
1082 } else if (gi_to->libs == 1) {
1083 board_capturable_rm(board, group_to, gi_to->lib[0], onestone_to);
1084 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1085 } else if (gi_to->libs == 2) {
1086 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1088 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1089 if (gi_to->libs >= GROUP_KEEP_LIBS)
1090 break;
1091 next_from_lib:;
1095 if (gi_to->libs == 1) {
1096 coord_t lib = board_group_info(board, group_to).lib[0];
1097 #ifdef BOARD_TRAITS
1098 enum stone capturing_color = stone_other(board_at(board, group_to));
1099 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1101 /* Our group is currently in atari; make sure we properly
1102 * count in even the neighbors from the other group in the
1103 * capturable counter. */
1104 foreach_neighbor(board, lib, {
1105 if (DEBUGL(8) && group_at(board, c) == group_from)
1106 fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1107 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1108 /* This is never a 1-stone group, obviously. */
1110 board_trait_queue(board, lib);
1112 if (onestone_to) {
1113 /* We are not 1-stone group anymore, update the cap1
1114 * counter specifically. */
1115 foreach_neighbor(board, group_to, {
1116 if (board_at(board, c) != S_NONE) continue;
1117 trait_at(board, c, capturing_color).cap1--;
1118 board_trait_queue(board, c);
1121 #endif
1122 #ifdef BOARD_PAT3
1123 if (gi_from->libs == 1) {
1124 /* We removed group_from from capturable groups,
1125 * therefore switching the atari flag off.
1126 * We need to set it again since group_to is also
1127 * capturable. */
1128 int fn__i = 0;
1129 foreach_neighbor(board, lib, {
1130 board->pat3[lib] |= (group_at(board, c) == group_from) << (16 + 3 - fn__i);
1131 fn__i++;
1134 #endif
1137 coord_t last_in_group;
1138 foreach_in_group(board, group_from) {
1139 last_in_group = c;
1140 group_at(board, c) = group_to;
1141 } foreach_in_group_end;
1142 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1143 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1144 memset(gi_from, 0, sizeof(struct group));
1146 if (DEBUGL(7))
1147 fprintf(stderr, "board_play_raw: merged group: %d\n",
1148 group_base(group_to));
1151 static group_t profiling_noinline
1152 new_group(struct board *board, coord_t coord)
1154 group_t group = coord;
1155 struct group *gi = &board_group_info(board, group);
1156 foreach_neighbor(board, coord, {
1157 if (board_at(board, c) == S_NONE)
1158 /* board_group_addlib is ridiculously expensive for us */
1159 #if GROUP_KEEP_LIBS < 4
1160 if (gi->libs < GROUP_KEEP_LIBS)
1161 #endif
1162 gi->lib[gi->libs++] = c;
1165 group_at(board, coord) = group;
1166 groupnext_at(board, coord) = 0;
1168 if (gi->libs == 2)
1169 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1170 else if (gi->libs == 1)
1171 board_capturable_add(board, group, gi->lib[0], true);
1172 check_libs_consistency(board, group);
1174 if (DEBUGL(8))
1175 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1176 coord_x(coord, board), coord_y(coord, board),
1177 group_base(group));
1179 return group;
1182 static inline group_t
1183 play_one_neighbor(struct board *board,
1184 coord_t coord, enum stone color, enum stone other_color,
1185 coord_t c, group_t group)
1187 enum stone ncolor = board_at(board, c);
1188 group_t ngroup = group_at(board, c);
1190 inc_neighbor_count_at(board, c, color);
1191 /* We can be S_NONE, in that case we need to update the safety
1192 * trait since we might be left with only one liberty. */
1193 board_trait_queue(board, c);
1195 if (!ngroup)
1196 return group;
1198 board_group_rmlib(board, ngroup, coord);
1199 if (DEBUGL(7))
1200 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1201 group_base(ngroup), ncolor, color, other_color);
1203 if (ncolor == color && ngroup != group) {
1204 if (!group) {
1205 group = ngroup;
1206 add_to_group(board, group, c, coord);
1207 } else {
1208 merge_groups(board, group, ngroup);
1210 } else if (ncolor == other_color) {
1211 if (DEBUGL(8)) {
1212 struct group *gi = &board_group_info(board, ngroup);
1213 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1214 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1215 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1216 fprintf(stderr, "\n");
1218 if (unlikely(board_group_captured(board, ngroup)))
1219 board_group_capture(board, ngroup);
1221 return group;
1224 /* We played on a place with at least one liberty. We will become a member of
1225 * some group for sure. */
1226 static group_t profiling_noinline
1227 board_play_outside(struct board *board, struct move *m, int f)
1229 coord_t coord = m->coord;
1230 enum stone color = m->color;
1231 enum stone other_color = stone_other(color);
1232 group_t group = 0;
1234 board->f[f] = board->f[--board->flen];
1235 if (DEBUGL(6))
1236 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1238 #if defined(BOARD_TRAITS) && defined(DEBUG)
1239 /* Sanity check that cap matches reality. */
1241 int a = 0, b = 0;
1242 foreach_neighbor(board, coord, {
1243 group_t g = group_at(board, c);
1244 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1245 b += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1) && group_is_onestone(board, g);
1247 assert(a == trait_at(board, coord, color).cap);
1248 assert(b == trait_at(board, coord, color).cap1);
1249 #ifdef BOARD_TRAIT_SAFE
1250 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1251 #endif
1253 #endif
1254 foreach_neighbor(board, coord, {
1255 group = play_one_neighbor(board, coord, color, other_color, c, group);
1258 board_at(board, coord) = color;
1259 if (unlikely(!group))
1260 group = new_group(board, coord);
1262 board->last_move4 = board->last_move3;
1263 board->last_move3 = board->last_move2;
1264 board->last_move2 = board->last_move;
1265 board->last_move = *m;
1266 board->moves++;
1267 board_hash_update(board, coord, color);
1268 board_symmetry_update(board, &board->symmetry, coord);
1269 struct move ko = { pass, S_NONE };
1270 board->ko = ko;
1272 check_pat3_consistency(board, coord);
1274 return group;
1277 /* We played in an eye-like shape. Either we capture at least one of the eye
1278 * sides in the process of playing, or return -1. */
1279 static int profiling_noinline
1280 board_play_in_eye(struct board *board, struct move *m, int f)
1282 coord_t coord = m->coord;
1283 enum stone color = m->color;
1284 /* Check ko: Capture at a position of ko capture one move ago */
1285 if (unlikely(color == board->ko.color && coord == board->ko.coord)) {
1286 if (DEBUGL(5))
1287 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1288 return -1;
1289 } else if (DEBUGL(6)) {
1290 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1291 color, coord_x(coord, board), coord_y(coord, board),
1292 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1295 struct move ko = { pass, S_NONE };
1297 int captured_groups = 0;
1299 foreach_neighbor(board, coord, {
1300 group_t g = group_at(board, c);
1301 if (DEBUGL(7))
1302 fprintf(stderr, "board_check: group %d has %d libs\n",
1303 g, board_group_info(board, g).libs);
1304 captured_groups += (board_group_info(board, g).libs == 1);
1307 if (likely(captured_groups == 0)) {
1308 if (DEBUGL(5)) {
1309 if (DEBUGL(6))
1310 board_print(board, stderr);
1311 fprintf(stderr, "board_check: one-stone suicide\n");
1314 return -1;
1316 #ifdef BOARD_TRAITS
1317 /* We _will_ for sure capture something. */
1318 assert(trait_at(board, coord, color).cap > 0);
1319 #ifdef BOARD_TRAIT_SAFE
1320 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1321 #endif
1322 #endif
1324 board->f[f] = board->f[--board->flen];
1325 if (DEBUGL(6))
1326 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1328 int ko_caps = 0;
1329 coord_t cap_at = pass;
1330 foreach_neighbor(board, coord, {
1331 inc_neighbor_count_at(board, c, color);
1332 /* Originally, this could not have changed any trait
1333 * since no neighbors were S_NONE, however by now some
1334 * of them might be removed from the board. */
1335 board_trait_queue(board, c);
1337 group_t group = group_at(board, c);
1338 if (!group)
1339 continue;
1341 board_group_rmlib(board, group, coord);
1342 if (DEBUGL(7))
1343 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1344 group_base(group));
1346 if (board_group_captured(board, group)) {
1347 ko_caps += board_group_capture(board, group);
1348 cap_at = c;
1351 if (ko_caps == 1) {
1352 ko.color = stone_other(color);
1353 ko.coord = cap_at; // unique
1354 board->last_ko = ko;
1355 board->last_ko_age = board->moves;
1356 if (DEBUGL(5))
1357 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1360 board_at(board, coord) = color;
1361 group_t group = new_group(board, coord);
1363 board->last_move4 = board->last_move3;
1364 board->last_move3 = board->last_move2;
1365 board->last_move2 = board->last_move;
1366 board->last_move = *m;
1367 board->moves++;
1368 board_hash_update(board, coord, color);
1369 board_hash_commit(board);
1370 board_traits_recompute(board);
1371 board_symmetry_update(board, &board->symmetry, coord);
1372 board->ko = ko;
1374 check_pat3_consistency(board, coord);
1376 return !!group;
1379 static int __attribute__((flatten))
1380 board_play_f(struct board *board, struct move *m, int f)
1382 if (DEBUGL(7)) {
1383 fprintf(stderr, "board_play(%s): ---- Playing %d,%d\n", coord2sstr(m->coord, board), coord_x(m->coord, board), coord_y(m->coord, board));
1385 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1386 /* NOT playing in an eye. Thus this move has to succeed. (This
1387 * is thanks to New Zealand rules. Otherwise, multi-stone
1388 * suicide might fail.) */
1389 group_t group = board_play_outside(board, m, f);
1390 if (unlikely(board_group_captured(board, group))) {
1391 board_group_capture(board, group);
1393 board_hash_commit(board);
1394 board_traits_recompute(board);
1395 return 0;
1396 } else {
1397 return board_play_in_eye(board, m, f);
1402 board_play(struct board *board, struct move *m)
1404 #ifdef BOARD_UNDO_CHECKS
1405 assert(!board->quicked);
1406 #endif
1408 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1409 if (is_pass(m->coord) && board->rules == RULES_SIMING) {
1410 /* On pass, the player gives a pass stone
1411 * to the opponent. */
1412 board->captures[stone_other(m->color)]++;
1414 struct move nomove = { pass, S_NONE };
1415 board->ko = nomove;
1416 board->last_move4 = board->last_move3;
1417 board->last_move3 = board->last_move2;
1418 board->last_move2 = board->last_move;
1419 board->last_move = *m;
1420 return 0;
1423 int f;
1424 for (f = 0; f < board->flen; f++)
1425 if (board->f[f] == m->coord)
1426 return board_play_f(board, m, f);
1428 if (DEBUGL(7))
1429 fprintf(stderr, "board_check: stone exists\n");
1430 return -1;
1433 /* Undo, supported only for pass moves. This form of undo is required by KGS
1434 * to settle disputes on dead groups. See also fast_board_undo() */
1435 int board_undo(struct board *board)
1437 if (!is_pass(board->last_move.coord))
1438 return -1;
1439 if (board->rules == RULES_SIMING) {
1440 /* Return pass stone to the passing player. */
1441 board->captures[stone_other(board->last_move.color)]--;
1443 board->last_move = board->last_move2;
1444 board->last_move2 = board->last_move3;
1445 board->last_move3 = board->last_move4;
1446 if (board->last_ko_age == board->moves)
1447 board->ko = board->last_ko;
1448 return 0;
1451 static inline bool
1452 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1454 *coord = b->f[f];
1455 struct move m = { *coord, color };
1456 if (DEBUGL(6))
1457 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));
1458 if (unlikely(board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1459 || !board_is_valid_move(b, &m)
1460 || (permit && !permit(permit_data, b, &m)))
1461 return false;
1462 if (m.coord == *coord) {
1463 return likely(board_play_f(b, &m, f) >= 0);
1464 } else {
1465 *coord = m.coord; // permit modified the coordinate
1466 return likely(board_play(b, &m) >= 0);
1470 void
1471 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1473 if (unlikely(b->flen == 0))
1474 goto pass;
1476 int base = fast_random(b->flen), f;
1477 for (f = base; f < b->flen; f++)
1478 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1479 return;
1480 for (f = 0; f < base; f++)
1481 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1482 return;
1484 pass:
1485 *coord = pass;
1486 struct move m = { pass, color };
1487 board_play(b, &m);
1491 bool
1492 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1494 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1496 /* XXX: We attempt false eye detection but we will yield false
1497 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1499 foreach_diag_neighbor(board, coord) {
1500 color_diag_libs[(enum stone) board_at(board, c)]++;
1501 } foreach_diag_neighbor_end;
1502 /* For false eye, we need two enemy stones diagonally in the
1503 * middle of the board, or just one enemy stone at the edge
1504 * or in the corner. */
1505 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1506 return color_diag_libs[stone_other(eye_color)] >= 2;
1509 bool
1510 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1512 return board_is_eyelike(board, coord, eye_color)
1513 && !board_is_false_eyelike(board, coord, eye_color);
1516 enum stone
1517 board_get_one_point_eye(struct board *board, coord_t coord)
1519 if (board_is_one_point_eye(board, coord, S_WHITE))
1520 return S_WHITE;
1521 else if (board_is_one_point_eye(board, coord, S_BLACK))
1522 return S_BLACK;
1523 else
1524 return S_NONE;
1528 floating_t
1529 board_fast_score(struct board *board)
1531 int scores[S_MAX];
1532 memset(scores, 0, sizeof(scores));
1534 foreach_point(board) {
1535 enum stone color = board_at(board, c);
1536 if (color == S_NONE && board->rules != RULES_STONES_ONLY)
1537 color = board_get_one_point_eye(board, c);
1538 scores[color]++;
1539 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1540 } foreach_point_end;
1542 return board->komi + (board->rules != RULES_SIMING ? board->handicap : 0) + scores[S_WHITE] - scores[S_BLACK];
1545 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1547 /* One flood-fill iteration; returns true if next iteration
1548 * is required. */
1549 static bool
1550 board_tromp_taylor_iter(struct board *board, int *ownermap)
1552 bool needs_update = false;
1553 foreach_free_point(board) {
1554 /* Ignore occupied and already-dame positions. */
1555 assert(board_at(board, c) == S_NONE);
1556 if (board->rules == RULES_STONES_ONLY)
1557 ownermap[c] = 3;
1558 if (ownermap[c] == 3)
1559 continue;
1560 /* Count neighbors. */
1561 int nei[4] = {0};
1562 foreach_neighbor(board, c, {
1563 nei[ownermap[c]]++;
1565 /* If we have neighbors of both colors, or dame,
1566 * we are dame too. */
1567 if ((nei[1] && nei[2]) || nei[3]) {
1568 ownermap[c] = 3;
1569 /* Speed up the propagation. */
1570 foreach_neighbor(board, c, {
1571 if (board_at(board, c) == S_NONE)
1572 ownermap[c] = 3;
1574 needs_update = true;
1575 continue;
1577 /* If we have neighbors of one color, we are owned
1578 * by that color, too. */
1579 if (!ownermap[c] && (nei[1] || nei[2])) {
1580 int newowner = nei[1] ? 1 : 2;
1581 ownermap[c] = newowner;
1582 /* Speed up the propagation. */
1583 foreach_neighbor(board, c, {
1584 if (board_at(board, c) == S_NONE && !ownermap[c])
1585 ownermap[c] = newowner;
1587 needs_update = true;
1588 continue;
1590 } foreach_free_point_end;
1591 return needs_update;
1594 /* Tromp-Taylor Counting */
1595 floating_t
1596 board_official_score(struct board *board, struct move_queue *q)
1599 /* A point P, not colored C, is said to reach C, if there is a path of
1600 * (vertically or horizontally) adjacent points of P's color from P to
1601 * a point of color C.
1603 * A player's score is the number of points of her color, plus the
1604 * number of empty points that reach only her color. */
1606 int ownermap[board_size2(board)];
1607 int s[4] = {0};
1608 const int o[4] = {0, 1, 2, 0};
1609 foreach_point(board) {
1610 ownermap[c] = o[board_at(board, c)];
1611 s[board_at(board, c)]++;
1612 } foreach_point_end;
1614 if (q) {
1615 /* Process dead groups. */
1616 for (unsigned int i = 0; i < q->moves; i++) {
1617 foreach_in_group(board, q->move[i]) {
1618 enum stone color = board_at(board, c);
1619 ownermap[c] = o[stone_other(color)];
1620 s[color]--; s[stone_other(color)]++;
1621 } foreach_in_group_end;
1625 /* We need to special-case empty board. */
1626 if (!s[S_BLACK] && !s[S_WHITE])
1627 return board->komi;
1629 while (board_tromp_taylor_iter(board, ownermap))
1630 /* Flood-fill... */;
1632 int scores[S_MAX];
1633 memset(scores, 0, sizeof(scores));
1635 foreach_point(board) {
1636 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1637 if (ownermap[c] == 3)
1638 continue;
1639 scores[ownermap[c]]++;
1640 } foreach_point_end;
1642 return board->komi + (board->rules != RULES_SIMING ? board->handicap : 0) + scores[S_WHITE] - scores[S_BLACK];
1645 bool
1646 board_set_rules(struct board *board, char *name)
1648 if (!strcasecmp(name, "japanese")) {
1649 board->rules = RULES_JAPANESE;
1650 } else if (!strcasecmp(name, "chinese")) {
1651 board->rules = RULES_CHINESE;
1652 } else if (!strcasecmp(name, "aga")) {
1653 board->rules = RULES_AGA;
1654 } else if (!strcasecmp(name, "new_zealand")) {
1655 board->rules = RULES_NEW_ZEALAND;
1656 } else if (!strcasecmp(name, "siming") || !strcasecmp(name, "simplified_ing")) {
1657 board->rules = RULES_SIMING;
1658 } else {
1659 return false;
1661 return true;