Localize libmap_hash.queue to b.lmqueue, play_random_game():lmqueue
[pachi.git] / board.c
blob2788ae8ba52eea10479a1b7bceb3dcee122207c5
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 "libmap.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 b2->fbook = NULL; // XXX: Special semantics.
136 if (b2->libmap) {
137 /* This is not 100% correct, but we can do away without
138 * locking as libmap cannot go away in the course of
139 * copy - b1 will still keep holding refcount at 1
140 * at least. */
141 __sync_fetch_and_add(&b2->libmap->refcount, 1);
143 b2->lmqueue = NULL;
145 return b2;
148 void
149 board_done_noalloc(struct board *board)
151 if (board->b) free(board->b);
152 if (board->fbook) fbook_done(board->fbook);
153 if (board->libmap) libmap_put(board->libmap);
156 void
157 board_done(struct board *board)
159 board_done_noalloc(board);
160 free(board);
163 void
164 board_resize(struct board *board, int size)
166 #ifdef BOARD_SIZE
167 assert(board_size(board) == size + 2);
168 #endif
169 assert(size <= BOARD_MAX_SIZE);
170 board->size = size + 2 /* S_OFFBOARD margin */;
171 board->size2 = board_size(board) * board_size(board);
173 board->bits2 = 1;
174 while ((1 << board->bits2) < board->size2) board->bits2++;
176 if (board->b)
177 free(board->b);
179 size_t asize = board_alloc(board);
180 memset(board->b, 0, asize);
183 static void
184 board_init_data(struct board *board)
186 int size = board_size(board);
188 board_setup(board);
189 board_resize(board, size - 2 /* S_OFFBOARD margin */);
191 /* Setup neighborhood iterators */
192 board->nei8[0] = -size - 1; // (-1,-1)
193 board->nei8[1] = 1;
194 board->nei8[2] = 1;
195 board->nei8[3] = size - 2; // (-1,0)
196 board->nei8[4] = 2;
197 board->nei8[5] = size - 2; // (-1,1)
198 board->nei8[6] = 1;
199 board->nei8[7] = 1;
200 board->dnei[0] = -size - 1;
201 board->dnei[1] = 2;
202 board->dnei[2] = size*2 - 2;
203 board->dnei[3] = 2;
205 /* Setup initial symmetry */
206 if (size % 2) {
207 board->symmetry.d = 1;
208 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
209 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
210 board->symmetry.type = SYM_FULL;
211 } else {
212 /* TODO: We do not handle board symmetry on boards
213 * with no tengen yet. */
214 board->symmetry.d = 0;
215 board->symmetry.x1 = board->symmetry.y1 = 1;
216 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
217 board->symmetry.type = SYM_NONE;
220 /* Set up coordinate cache */
221 foreach_point(board) {
222 board->coord[c][0] = c % board_size(board);
223 board->coord[c][1] = c / board_size(board);
224 } foreach_point_end;
226 /* Draw the offboard margin */
227 int top_row = board_size2(board) - board_size(board);
228 int i;
229 for (i = 0; i < board_size(board); i++)
230 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
231 for (i = 0; i <= top_row; i += board_size(board))
232 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
234 foreach_point(board) {
235 coord_t coord = c;
236 if (board_at(board, coord) == S_OFFBOARD)
237 continue;
238 foreach_neighbor(board, c, {
239 inc_neighbor_count_at(board, coord, board_at(board, c));
240 } );
241 } foreach_point_end;
243 /* All positions are free! Except the margin. */
244 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
245 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
246 board->f[board->flen++] = i;
248 /* Initialize zobrist hashtable. */
249 /* We will need these to be stable across Pachi runs for
250 * certain kinds of pattern matching, thus we do not use
251 * fast_random() for this. */
252 hash_t hseed = 0x3121110101112131;
253 foreach_point(board) {
254 board->h[c * 2] = (hseed *= 16807);
255 if (!board->h[c * 2])
256 board->h[c * 2] = 1;
257 /* And once again for white */
258 board->h[c * 2 + 1] = (hseed *= 16807);
259 if (!board->h[c * 2 + 1])
260 board->h[c * 2 + 1] = 1;
261 } foreach_point_end;
263 #ifdef BOARD_SPATHASH
264 /* Initialize spatial hashes. */
265 foreach_point(board) {
266 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
267 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
268 ptcoords_at(x, y, c, board, j);
269 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
270 pthashes[0][j][board_at(board, c)];
271 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
272 pthashes[0][j][stone_other(board_at(board, c))];
275 } foreach_point_end;
276 #endif
277 #ifdef BOARD_PAT3
278 /* Initialize 3x3 pattern codes. */
279 foreach_point(board) {
280 if (board_at(board, c) == S_NONE)
281 board->pat3[c] = pattern3_hash(board, c);
282 } foreach_point_end;
283 #endif
284 #ifdef BOARD_TRAITS
285 /* Initialize traits. */
286 foreach_point(board) {
287 trait_at(board, c, S_BLACK).cap = 0;
288 trait_at(board, c, S_WHITE).cap = 0;
289 trait_at(board, c, S_BLACK).cap1 = 0;
290 trait_at(board, c, S_WHITE).cap1 = 0;
291 #ifdef BOARD_TRAIT_SAFE
292 trait_at(board, c, S_BLACK).safe = true;
293 trait_at(board, c, S_WHITE).safe = true;
294 #endif
295 } foreach_point_end;
296 #endif
299 void
300 board_clear(struct board *board)
302 int size = board_size(board);
303 floating_t komi = board->komi;
304 char *fbookfile = board->fbookfile;
305 enum go_ruleset rules = board->rules;
307 board_done_noalloc(board);
309 static struct board bcache[BOARD_MAX_SIZE + 2];
310 assert(size > 0 && size <= BOARD_MAX_SIZE + 2);
311 if (bcache[size - 1].size == size) {
312 board_copy(board, &bcache[size - 1]);
313 } else {
314 board_init_data(board);
315 board_copy(&bcache[size - 1], board);
318 board->komi = komi;
319 board->fbookfile = fbookfile;
320 board->rules = rules;
322 if (board->fbookfile) {
323 board->fbook = fbook_init(board->fbookfile, board);
325 if (board->libmap) {
326 libmap_put(board->libmap);
327 board->libmap = NULL;
329 board->lmqueue = NULL;
332 static char *
333 board_print_top(struct board *board, char *s, char *end, int c)
335 for (int i = 0; i < c; i++) {
336 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
337 s += snprintf(s, end - s, " ");
338 for (int x = 1; x < board_size(board) - 1; x++)
339 s += snprintf(s, end - s, "%c ", asdf[x - 1]);
340 s += snprintf(s, end -s, " ");
342 s += snprintf(s, end - s, "\n");
343 for (int i = 0; i < c; i++) {
344 s += snprintf(s, end - s, " +-");
345 for (int x = 1; x < board_size(board) - 1; x++)
346 s += snprintf(s, end - s, "--");
347 s += snprintf(s, end - s, "+");
349 s += snprintf(s, end - s, "\n");
350 return s;
353 static char *
354 board_print_bottom(struct board *board, char *s, char *end, int c)
356 for (int i = 0; i < c; i++) {
357 s += snprintf(s, end - s, " +-");
358 for (int x = 1; x < board_size(board) - 1; x++)
359 s += snprintf(s, end - s, "--");
360 s += snprintf(s, end - s, "+");
362 s += snprintf(s, end - s, "\n");
363 return s;
366 static char *
367 board_print_row(struct board *board, int y, char *s, char *end, board_cprint cprint)
369 s += snprintf(s, end - s, " %2d | ", y);
370 for (int x = 1; x < board_size(board) - 1; x++) {
371 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
372 s += snprintf(s, end - s, "%c)", stone2char(board_atxy(board, x, y)));
373 else
374 s += snprintf(s, end - s, "%c ", stone2char(board_atxy(board, x, y)));
376 s += snprintf(s, end - s, "|");
377 if (cprint) {
378 s += snprintf(s, end - s, " %2d | ", y);
379 for (int x = 1; x < board_size(board) - 1; x++) {
380 s = cprint(board, coord_xy(board, x, y), s, end);
382 s += snprintf(s, end - s, "|");
384 s += snprintf(s, end - s, "\n");
385 return s;
388 void
389 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
391 char buf[10240];
392 char *s = buf;
393 char *end = buf + sizeof(buf);
394 s += snprintf(s, end - s, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
395 board->moves, board->komi, board->handicap,
396 board->captures[S_BLACK], board->captures[S_WHITE]);
397 s = board_print_top(board, s, end, 1 + !!cprint);
398 for (int y = board_size(board) - 2; y >= 1; y--)
399 s = board_print_row(board, y, s, end, cprint);
400 board_print_bottom(board, s, end, 1 + !!cprint);
401 fprintf(f, "%s\n", buf);
404 static char *
405 cprint_group(struct board *board, coord_t c, char *s, char *end)
407 s += snprintf(s, end - s, "%d ", group_base(group_at(board, c)));
408 return s;
411 void
412 board_print(struct board *board, FILE *f)
414 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
418 #ifdef BOARD_TRAITS
420 #if BOARD_TRAIT_SAFE == 1
421 static bool
422 board_trait_safe(struct board *board, coord_t coord, enum stone color)
424 return board_safe_to_play(board, coord, color);
426 #elif BOARD_TRAIT_SAFE == 2
427 static bool
428 board_trait_safe(struct board *board, coord_t coord, enum stone color)
430 return !is_bad_selfatari(board, color, coord);
432 #endif
434 static void
435 board_trait_recompute(struct board *board, coord_t coord)
437 int sfb = -1, sfw = -1;
438 #ifdef BOARD_TRAIT_SAFE
439 sfb = trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);
440 sfw = trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
441 #endif
442 if (DEBUGL(8)) {
443 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d cap1=%d safe=%d) (white cap=%d cap1=%d safe=%d)\n",
444 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
445 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).cap1, sfb,
446 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).cap1, sfw);
449 #endif
451 /* Recompute traits for dirty points that we have previously touched
452 * somehow (libs of their neighbors changed or so). */
453 static void
454 board_traits_recompute(struct board *board)
456 #ifdef BOARD_TRAITS
457 for (int i = 0; i < board->tqlen; i++) {
458 coord_t coord = board->tq[i];
459 trait_at(board, coord, S_BLACK).dirty = false;
460 if (board_at(board, coord) != S_NONE)
461 continue;
462 board_trait_recompute(board, coord);
464 board->tqlen = 0;
465 #endif
468 /* Queue traits of given point for recomputing. */
469 static void
470 board_trait_queue(struct board *board, coord_t coord)
472 #ifdef BOARD_TRAITS
473 if (trait_at(board, coord, S_BLACK).dirty)
474 return;
475 board->tq[board->tqlen++] = coord;
476 trait_at(board, coord, S_BLACK).dirty = true;
477 #endif
481 /* Update board hash with given coordinate. */
482 static void profiling_noinline
483 board_hash_update(struct board *board, coord_t coord, enum stone color)
485 board->hash ^= hash_at(board, coord, color);
486 board->qhash[coord_quadrant(coord, board)] ^= hash_at(board, coord, color);
487 if (DEBUGL(8))
488 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);
490 #ifdef BOARD_SPATHASH
491 /* Gridcular metric is reflective, so we update all hashes
492 * of appropriate ditance in OUR circle. */
493 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
494 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
495 ptcoords_at(x, y, coord, board, j);
496 /* We either changed from S_NONE to color
497 * or vice versa; doesn't matter. */
498 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
499 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
500 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
501 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
504 #endif
506 #if defined(BOARD_PAT3)
507 /* @color is not what we need in case of capture. */
508 static const int ataribits[8] = { -1, 0, -1, 1, 2, -1, 3, -1 };
509 enum stone new_color = board_at(board, coord);
510 bool in_atari = false;
511 if (new_color == S_NONE) {
512 board->pat3[coord] = pattern3_hash(board, coord);
513 } else {
514 in_atari = (board_group_info(board, group_at(board, coord)).libs == 1);
516 foreach_8neighbor(board, coord) {
517 /* Internally, the loop uses fn__i=[0..7]. We can use
518 * it directly to address bits within the bitmap of the
519 * neighbors since the bitmap order is reverse to the
520 * loop order. */
521 if (board_at(board, c) != S_NONE)
522 continue;
523 board->pat3[c] &= ~(3 << (fn__i*2));
524 board->pat3[c] |= new_color << (fn__i*2);
525 if (ataribits[fn__i] >= 0) {
526 board->pat3[c] &= ~(1 << (16 + ataribits[fn__i]));
527 board->pat3[c] |= in_atari << (16 + ataribits[fn__i]);
529 #if defined(BOARD_TRAITS)
530 board_trait_queue(board, c);
531 #endif
532 } foreach_8neighbor_end;
533 #endif
536 /* Commit current board hash to history. */
537 static void profiling_noinline
538 board_hash_commit(struct board *board)
540 if (DEBUGL(8))
541 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
542 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
543 board->history_hash[board->hash & history_hash_mask] = board->hash;
544 } else {
545 hash_t i = board->hash;
546 while (board->history_hash[i & history_hash_mask]) {
547 if (board->history_hash[i & history_hash_mask] == board->hash) {
548 if (DEBUGL(5))
549 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
550 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
551 board->superko_violation = true;
552 return;
554 i = history_hash_next(i);
556 board->history_hash[i & history_hash_mask] = board->hash;
561 void
562 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
564 if (likely(symmetry->type == SYM_NONE)) {
565 /* Fully degenerated already. We do not support detection
566 * of restoring of symmetry, assuming that this is too rare
567 * a case to handle. */
568 return;
571 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
572 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
573 if (DEBUGL(6)) {
574 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
575 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
576 symmetry->d, symmetry->type, x, y);
579 switch (symmetry->type) {
580 case SYM_FULL:
581 if (x == t && y == t) {
582 /* Tengen keeps full symmetry. */
583 return;
585 /* New symmetry now? */
586 if (x == y) {
587 symmetry->type = SYM_DIAG_UP;
588 symmetry->x1 = symmetry->y1 = 1;
589 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
590 symmetry->d = 1;
591 } else if (dx == y) {
592 symmetry->type = SYM_DIAG_DOWN;
593 symmetry->x1 = symmetry->y1 = 1;
594 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
595 symmetry->d = 1;
596 } else if (x == t) {
597 symmetry->type = SYM_HORIZ;
598 symmetry->y1 = 1;
599 symmetry->y2 = board_size(b) - 1;
600 symmetry->d = 0;
601 } else if (y == t) {
602 symmetry->type = SYM_VERT;
603 symmetry->x1 = 1;
604 symmetry->x2 = board_size(b) - 1;
605 symmetry->d = 0;
606 } else {
607 break_symmetry:
608 symmetry->type = SYM_NONE;
609 symmetry->x1 = symmetry->y1 = 1;
610 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
611 symmetry->d = 0;
613 break;
614 case SYM_DIAG_UP:
615 if (x == y)
616 return;
617 goto break_symmetry;
618 case SYM_DIAG_DOWN:
619 if (dx == y)
620 return;
621 goto break_symmetry;
622 case SYM_HORIZ:
623 if (x == t)
624 return;
625 goto break_symmetry;
626 case SYM_VERT:
627 if (y == t)
628 return;
629 goto break_symmetry;
630 case SYM_NONE:
631 assert(0);
632 break;
635 if (DEBUGL(6)) {
636 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
637 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
638 symmetry->d, symmetry->type);
640 /* Whew. */
644 void
645 board_handicap_stone(struct board *board, int x, int y, FILE *f)
647 struct move m;
648 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
650 board_play(board, &m);
651 /* Simulate white passing; otherwise, UCT search can get confused since
652 * tree depth parity won't match the color to move. */
653 board->moves++;
655 char *str = coord2str(m.coord, board);
656 if (DEBUGL(1))
657 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
658 if (f) fprintf(f, "%s ", str);
659 free(str);
662 void
663 board_handicap(struct board *board, int stones, FILE *f)
665 int margin = 3 + (board_size(board) >= 13);
666 int min = margin;
667 int mid = board_size(board) / 2;
668 int max = board_size(board) - 1 - margin;
669 const int places[][2] = {
670 { min, min }, { max, max }, { min, max }, { max, min },
671 { min, mid }, { max, mid },
672 { mid, min }, { mid, max },
673 { mid, mid },
676 board->handicap = stones;
678 if (stones == 5 || stones == 7) {
679 board_handicap_stone(board, mid, mid, f);
680 stones--;
683 int i;
684 for (i = 0; i < stones; i++)
685 board_handicap_stone(board, places[i][0], places[i][1], f);
689 static void __attribute__((noinline))
690 check_libs_consistency(struct board *board, group_t g)
692 #ifdef DEBUG
693 if (!g) return;
694 struct group *gi = &board_group_info(board, g);
695 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
696 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
697 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
698 assert(0);
700 #endif
703 static void
704 check_pat3_consistency(struct board *board, coord_t coord)
706 #ifdef DEBUG
707 foreach_8neighbor(board, coord) {
708 if (board_at(board, c) == S_NONE && pattern3_hash(board, c) != board->pat3[c]) {
709 board_print(board, stderr);
710 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);
711 assert(0);
713 } foreach_8neighbor_end;
714 #endif
717 static void
718 board_capturable_add(struct board *board, group_t group, coord_t lib, bool onestone)
720 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
721 #ifdef BOARD_TRAITS
722 /* Increase capturable count trait of my last lib. */
723 enum stone capturing_color = stone_other(board_at(board, group));
724 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
725 foreach_neighbor(board, lib, {
726 if (DEBUGL(8) && group_at(board, c) == group)
727 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);
728 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
729 trait_at(board, lib, capturing_color).cap1 += (group_at(board, c) == group && onestone);
731 board_trait_queue(board, lib);
732 #endif
734 #ifdef BOARD_PAT3
735 int fn__i = 0;
736 foreach_neighbor(board, lib, {
737 board->pat3[lib] |= (group_at(board, c) == group) << (16 + 3 - fn__i);
738 fn__i++;
740 #endif
742 #ifdef WANT_BOARD_C
743 /* Update the list of capturable groups. */
744 assert(group);
745 assert(board->clen < board_size2(board));
746 board->c[board->clen++] = group;
747 #endif
749 static void
750 board_capturable_rm(struct board *board, group_t group, coord_t lib, bool onestone)
752 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
753 #ifdef BOARD_TRAITS
754 /* Decrease capturable count trait of my previously-last lib. */
755 enum stone capturing_color = stone_other(board_at(board, group));
756 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
757 foreach_neighbor(board, lib, {
758 if (DEBUGL(8) && group_at(board, c) == group)
759 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);
760 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
761 trait_at(board, lib, capturing_color).cap1 -= (group_at(board, c) == group && onestone);
763 board_trait_queue(board, lib);
764 #endif
766 #ifdef BOARD_PAT3
767 int fn__i = 0;
768 foreach_neighbor(board, lib, {
769 board->pat3[lib] &= ~((group_at(board, c) == group) << (16 + 3 - fn__i));
770 fn__i++;
772 #endif
774 #ifdef WANT_BOARD_C
775 /* Update the list of capturable groups. */
776 for (int i = 0; i < board->clen; i++) {
777 if (unlikely(board->c[i] == group)) {
778 board->c[i] = board->c[--board->clen];
779 return;
782 fprintf(stderr, "rm of bad group %d\n", group_base(group));
783 assert(0);
784 #endif
787 static void
788 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
790 #ifdef BOARD_TRAITS
791 board_trait_queue(board, lib1);
792 board_trait_queue(board, lib2);
793 #endif
795 static void
796 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
798 #ifdef BOARD_TRAITS
799 board_trait_queue(board, lib1);
800 board_trait_queue(board, lib2);
801 #endif
804 static void
805 board_group_addlib(struct board *board, group_t group, coord_t coord)
807 if (DEBUGL(7)) {
808 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
809 group_base(group), coord2sstr(group_base(group), board),
810 board_group_info(board, group).libs, coord2sstr(coord, board));
813 check_libs_consistency(board, group);
815 struct group *gi = &board_group_info(board, group);
816 bool onestone = group_is_onestone(board, group);
817 if (gi->libs < GROUP_KEEP_LIBS) {
818 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
819 #if 0
820 /* Seems extra branch just slows it down */
821 if (!gi->lib[i])
822 break;
823 #endif
824 if (unlikely(gi->lib[i] == coord))
825 return;
827 if (gi->libs == 0) {
828 board_capturable_add(board, group, coord, onestone);
829 } else if (gi->libs == 1) {
830 board_capturable_rm(board, group, gi->lib[0], onestone);
831 board_atariable_add(board, group, gi->lib[0], coord);
832 } else if (gi->libs == 2) {
833 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
835 gi->lib[gi->libs++] = coord;
838 check_libs_consistency(board, group);
841 static void
842 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
844 /* Add extra liberty from the board to our liberty list. */
845 unsigned char watermark[board_size2(board) / 8];
846 memset(watermark, 0, sizeof(watermark));
847 #define watermark_get(c) (watermark[c >> 3] & (1 << (c & 7)))
848 #define watermark_set(c) watermark[c >> 3] |= (1 << (c & 7))
850 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
851 watermark_set(gi->lib[i]);
852 watermark_set(avoid);
854 foreach_in_group(board, group) {
855 coord_t coord2 = c;
856 foreach_neighbor(board, coord2, {
857 if (board_at(board, c) + watermark_get(c) != S_NONE)
858 continue;
859 watermark_set(c);
860 gi->lib[gi->libs++] = c;
861 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
862 return;
863 } );
864 } foreach_in_group_end;
865 #undef watermark_get
866 #undef watermark_set
869 static void
870 board_group_rmlib(struct board *board, group_t group, coord_t coord)
872 if (DEBUGL(7)) {
873 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
874 group_base(group), coord2sstr(group_base(group), board),
875 board_group_info(board, group).libs, coord2sstr(coord, board));
878 struct group *gi = &board_group_info(board, group);
879 bool onestone = group_is_onestone(board, group);
880 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
881 #if 0
882 /* Seems extra branch just slows it down */
883 if (!gi->lib[i])
884 break;
885 #endif
886 if (likely(gi->lib[i] != coord))
887 continue;
889 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
890 gi->lib[gi->libs] = 0;
892 check_libs_consistency(board, group);
894 /* Postpone refilling lib[] until we need to. */
895 assert(GROUP_REFILL_LIBS > 1);
896 if (gi->libs > GROUP_REFILL_LIBS)
897 return;
898 if (gi->libs == GROUP_REFILL_LIBS)
899 board_group_find_extra_libs(board, group, gi, coord);
901 if (gi->libs == 2) {
902 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
903 } else if (gi->libs == 1) {
904 board_capturable_add(board, group, gi->lib[0], onestone);
905 board_atariable_rm(board, group, gi->lib[0], lib);
906 } else if (gi->libs == 0)
907 board_capturable_rm(board, group, lib, onestone);
908 return;
911 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
912 * can call this multiple times per coord. */
913 check_libs_consistency(board, group);
914 return;
918 /* This is a low-level routine that doesn't maintain consistency
919 * of all the board data structures. */
920 static void
921 board_remove_stone(struct board *board, group_t group, coord_t c)
923 enum stone color = board_at(board, c);
924 board_at(board, c) = S_NONE;
925 group_at(board, c) = 0;
926 board_hash_update(board, c, color);
927 #ifdef BOARD_TRAITS
928 /* We mark as cannot-capture now. If this is a ko/snapback,
929 * we will get incremented later in board_group_addlib(). */
930 trait_at(board, c, S_BLACK).cap = trait_at(board, c, S_BLACK).cap1 = 0;
931 trait_at(board, c, S_WHITE).cap = trait_at(board, c, S_WHITE).cap1 = 0;
932 board_trait_queue(board, c);
933 #endif
935 /* Increase liberties of surrounding groups */
936 coord_t coord = c;
937 foreach_neighbor(board, coord, {
938 dec_neighbor_count_at(board, c, color);
939 board_trait_queue(board, c);
940 group_t g = group_at(board, c);
941 if (g && g != group)
942 board_group_addlib(board, g, coord);
945 #ifdef BOARD_PAT3
946 /* board_hash_update() might have seen the freed up point as able
947 * to capture another group in atari that only after the loop
948 * above gained enough liberties. Reset pat3 again. */
949 board->pat3[c] = pattern3_hash(board, c);
950 #endif
952 if (DEBUGL(6))
953 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
954 board->f[board->flen++] = c;
957 static int profiling_noinline
958 board_group_capture(struct board *board, group_t group)
960 int stones = 0;
962 foreach_in_group(board, group) {
963 board->captures[stone_other(board_at(board, c))]++;
964 board_remove_stone(board, group, c);
965 stones++;
966 } foreach_in_group_end;
968 struct group *gi = &board_group_info(board, group);
969 assert(gi->libs == 0);
970 memset(gi, 0, sizeof(*gi));
972 return stones;
976 static void profiling_noinline
977 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
979 #ifdef BOARD_TRAITS
980 struct group *gi = &board_group_info(board, group);
981 bool onestone = group_is_onestone(board, group);
983 if (gi->libs == 1) {
984 /* Our group is temporarily in atari; make sure the capturable
985 * counts also correspond to the newly added stone before we
986 * start adding liberties again so bump-dump ops match. */
987 enum stone capturing_color = stone_other(board_at(board, group));
988 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
990 coord_t lib = board_group_info(board, group).lib[0];
991 if (coord_is_adjecent(lib, coord, board)) {
992 if (DEBUGL(8))
993 fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
994 trait_at(board, lib, capturing_color).cap++;
995 /* This is never a 1-stone group, obviously. */
996 board_trait_queue(board, lib);
999 if (onestone) {
1000 /* We are not 1-stone group anymore, update the cap1
1001 * counter specifically. */
1002 foreach_neighbor(board, group, {
1003 if (board_at(board, c) != S_NONE) continue;
1004 trait_at(board, c, capturing_color).cap1--;
1005 board_trait_queue(board, c);
1009 #endif
1011 group_at(board, coord) = group;
1012 groupnext_at(board, coord) = groupnext_at(board, prevstone);
1013 groupnext_at(board, prevstone) = coord;
1015 foreach_neighbor(board, coord, {
1016 if (board_at(board, c) == S_NONE)
1017 board_group_addlib(board, group, c);
1020 if (DEBUGL(8))
1021 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
1022 coord_x(prevstone, board), coord_y(prevstone, board),
1023 coord_x(coord, board), coord_y(coord, board),
1024 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
1025 group_base(group));
1028 static void profiling_noinline
1029 merge_groups(struct board *board, group_t group_to, group_t group_from)
1031 if (DEBUGL(7))
1032 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
1033 group_base(group_from), group_base(group_to));
1034 struct group *gi_from = &board_group_info(board, group_from);
1035 struct group *gi_to = &board_group_info(board, group_to);
1036 bool onestone_from = group_is_onestone(board, group_from);
1037 bool onestone_to = group_is_onestone(board, group_to);
1039 /* We do this early before the group info is rewritten. */
1040 if (gi_from->libs == 2)
1041 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1042 else if (gi_from->libs == 1)
1043 board_capturable_rm(board, group_from, gi_from->lib[0], onestone_from);
1045 if (DEBUGL(7))
1046 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1048 if (gi_to->libs < GROUP_KEEP_LIBS) {
1049 for (int i = 0; i < gi_from->libs; i++) {
1050 for (int j = 0; j < gi_to->libs; j++)
1051 if (gi_to->lib[j] == gi_from->lib[i])
1052 goto next_from_lib;
1053 if (gi_to->libs == 0) {
1054 board_capturable_add(board, group_to, gi_from->lib[i], onestone_to);
1055 } else if (gi_to->libs == 1) {
1056 board_capturable_rm(board, group_to, gi_to->lib[0], onestone_to);
1057 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1058 } else if (gi_to->libs == 2) {
1059 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1061 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1062 if (gi_to->libs >= GROUP_KEEP_LIBS)
1063 break;
1064 next_from_lib:;
1068 if (gi_to->libs == 1) {
1069 coord_t lib = board_group_info(board, group_to).lib[0];
1070 #ifdef BOARD_TRAITS
1071 enum stone capturing_color = stone_other(board_at(board, group_to));
1072 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1074 /* Our group is currently in atari; make sure we properly
1075 * count in even the neighbors from the other group in the
1076 * capturable counter. */
1077 foreach_neighbor(board, lib, {
1078 if (DEBUGL(8) && group_at(board, c) == group_from)
1079 fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1080 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1081 /* This is never a 1-stone group, obviously. */
1083 board_trait_queue(board, lib);
1085 if (onestone_to) {
1086 /* We are not 1-stone group anymore, update the cap1
1087 * counter specifically. */
1088 foreach_neighbor(board, group_to, {
1089 if (board_at(board, c) != S_NONE) continue;
1090 trait_at(board, c, capturing_color).cap1--;
1091 board_trait_queue(board, c);
1094 #endif
1095 #ifdef BOARD_PAT3
1096 if (gi_from->libs == 1) {
1097 /* We removed group_from from capturable groups,
1098 * therefore switching the atari flag off.
1099 * We need to set it again since group_to is also
1100 * capturable. */
1101 int fn__i = 0;
1102 foreach_neighbor(board, lib, {
1103 board->pat3[lib] |= (group_at(board, c) == group_from) << (16 + 3 - fn__i);
1104 fn__i++;
1107 #endif
1110 coord_t last_in_group;
1111 foreach_in_group(board, group_from) {
1112 last_in_group = c;
1113 group_at(board, c) = group_to;
1114 } foreach_in_group_end;
1115 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1116 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1117 memset(gi_from, 0, sizeof(struct group));
1119 if (DEBUGL(7))
1120 fprintf(stderr, "board_play_raw: merged group: %d\n",
1121 group_base(group_to));
1124 static group_t profiling_noinline
1125 new_group(struct board *board, coord_t coord)
1127 group_t group = coord;
1128 struct group *gi = &board_group_info(board, group);
1129 foreach_neighbor(board, coord, {
1130 if (board_at(board, c) == S_NONE)
1131 /* board_group_addlib is ridiculously expensive for us */
1132 #if GROUP_KEEP_LIBS < 4
1133 if (gi->libs < GROUP_KEEP_LIBS)
1134 #endif
1135 gi->lib[gi->libs++] = c;
1138 group_at(board, coord) = group;
1139 groupnext_at(board, coord) = 0;
1141 if (gi->libs == 2)
1142 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1143 else if (gi->libs == 1)
1144 board_capturable_add(board, group, gi->lib[0], true);
1145 check_libs_consistency(board, group);
1147 if (DEBUGL(8))
1148 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1149 coord_x(coord, board), coord_y(coord, board),
1150 group_base(group));
1152 return group;
1155 static inline group_t
1156 play_one_neighbor(struct board *board,
1157 coord_t coord, enum stone color, enum stone other_color,
1158 coord_t c, group_t group)
1160 enum stone ncolor = board_at(board, c);
1161 group_t ngroup = group_at(board, c);
1163 inc_neighbor_count_at(board, c, color);
1164 /* We can be S_NONE, in that case we need to update the safety
1165 * trait since we might be left with only one liberty. */
1166 board_trait_queue(board, c);
1168 if (!ngroup)
1169 return group;
1171 board_group_rmlib(board, ngroup, coord);
1172 if (DEBUGL(7))
1173 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1174 group_base(ngroup), ncolor, color, other_color);
1176 if (ncolor == color && ngroup != group) {
1177 if (!group) {
1178 group = ngroup;
1179 add_to_group(board, group, c, coord);
1180 } else {
1181 merge_groups(board, group, ngroup);
1183 } else if (ncolor == other_color) {
1184 if (DEBUGL(8)) {
1185 struct group *gi = &board_group_info(board, ngroup);
1186 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1187 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1188 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1189 fprintf(stderr, "\n");
1191 if (unlikely(board_group_captured(board, ngroup)))
1192 board_group_capture(board, ngroup);
1194 return group;
1197 /* We played on a place with at least one liberty. We will become a member of
1198 * some group for sure. */
1199 static group_t profiling_noinline
1200 board_play_outside(struct board *board, struct move *m, int f)
1202 coord_t coord = m->coord;
1203 enum stone color = m->color;
1204 enum stone other_color = stone_other(color);
1205 group_t group = 0;
1207 board->f[f] = board->f[--board->flen];
1208 if (DEBUGL(6))
1209 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1211 #if defined(BOARD_TRAITS) && defined(DEBUG)
1212 /* Sanity check that cap matches reality. */
1214 int a = 0, b = 0;
1215 foreach_neighbor(board, coord, {
1216 group_t g = group_at(board, c);
1217 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1218 b += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1) && group_is_onestone(board, g);
1220 assert(a == trait_at(board, coord, color).cap);
1221 assert(b == trait_at(board, coord, color).cap1);
1222 #ifdef BOARD_TRAIT_SAFE
1223 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1224 #endif
1226 #endif
1227 foreach_neighbor(board, coord, {
1228 group = play_one_neighbor(board, coord, color, other_color, c, group);
1231 board_at(board, coord) = color;
1232 if (unlikely(!group))
1233 group = new_group(board, coord);
1235 board->last_move2 = board->last_move;
1236 board->last_move = *m;
1237 board->moves++;
1238 board_hash_update(board, coord, color);
1239 board_symmetry_update(board, &board->symmetry, coord);
1240 struct move ko = { pass, S_NONE };
1241 board->ko = ko;
1243 check_pat3_consistency(board, coord);
1245 return group;
1248 /* We played in an eye-like shape. Either we capture at least one of the eye
1249 * sides in the process of playing, or return -1. */
1250 static int profiling_noinline
1251 board_play_in_eye(struct board *board, struct move *m, int f)
1253 coord_t coord = m->coord;
1254 enum stone color = m->color;
1255 /* Check ko: Capture at a position of ko capture one move ago */
1256 if (unlikely(color == board->ko.color && coord == board->ko.coord)) {
1257 if (DEBUGL(5))
1258 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1259 return -1;
1260 } else if (DEBUGL(6)) {
1261 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1262 color, coord_x(coord, board), coord_y(coord, board),
1263 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1266 struct move ko = { pass, S_NONE };
1268 int captured_groups = 0;
1270 foreach_neighbor(board, coord, {
1271 group_t g = group_at(board, c);
1272 if (DEBUGL(7))
1273 fprintf(stderr, "board_check: group %d has %d libs\n",
1274 g, board_group_info(board, g).libs);
1275 captured_groups += (board_group_info(board, g).libs == 1);
1278 if (likely(captured_groups == 0)) {
1279 if (DEBUGL(5)) {
1280 if (DEBUGL(6))
1281 board_print(board, stderr);
1282 fprintf(stderr, "board_check: one-stone suicide\n");
1285 return -1;
1287 #ifdef BOARD_TRAITS
1288 /* We _will_ for sure capture something. */
1289 assert(trait_at(board, coord, color).cap > 0);
1290 #ifdef BOARD_TRAIT_SAFE
1291 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1292 #endif
1293 #endif
1295 board->f[f] = board->f[--board->flen];
1296 if (DEBUGL(6))
1297 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1299 int ko_caps = 0;
1300 coord_t cap_at = pass;
1301 foreach_neighbor(board, coord, {
1302 inc_neighbor_count_at(board, c, color);
1303 /* Originally, this could not have changed any trait
1304 * since no neighbors were S_NONE, however by now some
1305 * of them might be removed from the board. */
1306 board_trait_queue(board, c);
1308 group_t group = group_at(board, c);
1309 if (!group)
1310 continue;
1312 board_group_rmlib(board, group, coord);
1313 if (DEBUGL(7))
1314 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1315 group_base(group));
1317 if (board_group_captured(board, group)) {
1318 ko_caps += board_group_capture(board, group);
1319 cap_at = c;
1322 if (ko_caps == 1) {
1323 ko.color = stone_other(color);
1324 ko.coord = cap_at; // unique
1325 board->last_ko = ko;
1326 board->last_ko_age = board->moves;
1327 if (DEBUGL(5))
1328 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1331 board_at(board, coord) = color;
1332 group_t group = new_group(board, coord);
1334 board->last_move2 = board->last_move;
1335 board->last_move = *m;
1336 board->moves++;
1337 board_hash_update(board, coord, color);
1338 board_hash_commit(board);
1339 board_traits_recompute(board);
1340 board_symmetry_update(board, &board->symmetry, coord);
1341 board->ko = ko;
1343 check_pat3_consistency(board, coord);
1345 return !!group;
1348 static int __attribute__((flatten))
1349 board_play_f(struct board *board, struct move *m, int f)
1351 if (DEBUGL(7)) {
1352 fprintf(stderr, "board_play(%s): ---- Playing %d,%d\n", coord2sstr(m->coord, board), coord_x(m->coord, board), coord_y(m->coord, board));
1354 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1355 /* NOT playing in an eye. Thus this move has to succeed. (This
1356 * is thanks to New Zealand rules. Otherwise, multi-stone
1357 * suicide might fail.) */
1358 group_t group = board_play_outside(board, m, f);
1359 if (unlikely(board_group_captured(board, group))) {
1360 board_group_capture(board, group);
1362 board_hash_commit(board);
1363 board_traits_recompute(board);
1364 return 0;
1365 } else {
1366 return board_play_in_eye(board, m, f);
1371 board_play(struct board *board, struct move *m)
1373 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1374 if (is_pass(m->coord) && board->rules == RULES_SIMING) {
1375 /* On pass, the player gives a pass stone
1376 * to the opponent. */
1377 board->captures[stone_other(m->color)]++;
1379 struct move nomove = { pass, S_NONE };
1380 board->ko = nomove;
1381 board->last_move4 = board->last_move3;
1382 board->last_move3 = board->last_move2;
1383 board->last_move2 = board->last_move;
1384 board->last_move = *m;
1385 return 0;
1388 int f;
1389 for (f = 0; f < board->flen; f++)
1390 if (board->f[f] == m->coord)
1391 return board_play_f(board, m, f);
1393 if (DEBUGL(7))
1394 fprintf(stderr, "board_check: stone exists\n");
1395 return -1;
1398 /* Undo, supported only for pass moves. This form of undo is required by KGS
1399 * to settle disputes on dead groups. (Undo of real moves would be more complex
1400 * particularly for capturing moves.) */
1401 int board_undo(struct board *board)
1403 if (!is_pass(board->last_move.coord))
1404 return -1;
1405 if (board->rules == RULES_SIMING) {
1406 /* Return pass stone to the passing player. */
1407 board->captures[stone_other(board->last_move.color)]--;
1409 board->last_move = board->last_move2;
1410 board->last_move2 = board->last_move3;
1411 board->last_move3 = board->last_move4;
1412 if (board->last_ko_age == board->moves)
1413 board->ko = board->last_ko;
1414 return 0;
1417 static inline bool
1418 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1420 *coord = b->f[f];
1421 struct move m = { *coord, color };
1422 if (DEBUGL(6))
1423 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));
1424 if (unlikely(board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1425 || !board_is_valid_move(b, &m)
1426 || (permit && !permit(permit_data, b, &m)))
1427 return false;
1428 if (m.coord == *coord) {
1429 return likely(board_play_f(b, &m, f) >= 0);
1430 } else {
1431 *coord = m.coord; // permit modified the coordinate
1432 return likely(board_play(b, &m) >= 0);
1436 void
1437 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1439 if (unlikely(b->flen == 0))
1440 goto pass;
1442 int base = fast_random(b->flen), f;
1443 for (f = base; f < b->flen; f++)
1444 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1445 return;
1446 for (f = 0; f < base; f++)
1447 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1448 return;
1450 pass:
1451 *coord = pass;
1452 struct move m = { pass, color };
1453 board_play(b, &m);
1457 bool
1458 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1460 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1462 /* XXX: We attempt false eye detection but we will yield false
1463 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1465 foreach_diag_neighbor(board, coord) {
1466 color_diag_libs[(enum stone) board_at(board, c)]++;
1467 } foreach_diag_neighbor_end;
1468 /* For false eye, we need two enemy stones diagonally in the
1469 * middle of the board, or just one enemy stone at the edge
1470 * or in the corner. */
1471 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1472 return color_diag_libs[stone_other(eye_color)] >= 2;
1475 bool
1476 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1478 return board_is_eyelike(board, coord, eye_color)
1479 && !board_is_false_eyelike(board, coord, eye_color);
1482 enum stone
1483 board_get_one_point_eye(struct board *board, coord_t coord)
1485 if (board_is_one_point_eye(board, coord, S_WHITE))
1486 return S_WHITE;
1487 else if (board_is_one_point_eye(board, coord, S_BLACK))
1488 return S_BLACK;
1489 else
1490 return S_NONE;
1494 floating_t
1495 board_fast_score(struct board *board)
1497 int scores[S_MAX];
1498 memset(scores, 0, sizeof(scores));
1500 foreach_point(board) {
1501 enum stone color = board_at(board, c);
1502 if (color == S_NONE && board->rules != RULES_STONES_ONLY)
1503 color = board_get_one_point_eye(board, c);
1504 scores[color]++;
1505 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1506 } foreach_point_end;
1508 return board->komi + (board->rules != RULES_SIMING ? board->handicap : 0) + scores[S_WHITE] - scores[S_BLACK];
1511 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1513 /* One flood-fill iteration; returns true if next iteration
1514 * is required. */
1515 static bool
1516 board_tromp_taylor_iter(struct board *board, int *ownermap)
1518 bool needs_update = false;
1519 foreach_free_point(board) {
1520 /* Ignore occupied and already-dame positions. */
1521 assert(board_at(board, c) == S_NONE);
1522 if (board->rules == RULES_STONES_ONLY)
1523 ownermap[c] = 3;
1524 if (ownermap[c] == 3)
1525 continue;
1526 /* Count neighbors. */
1527 int nei[4] = {0};
1528 foreach_neighbor(board, c, {
1529 nei[ownermap[c]]++;
1531 /* If we have neighbors of both colors, or dame,
1532 * we are dame too. */
1533 if ((nei[1] && nei[2]) || nei[3]) {
1534 ownermap[c] = 3;
1535 /* Speed up the propagation. */
1536 foreach_neighbor(board, c, {
1537 if (board_at(board, c) == S_NONE)
1538 ownermap[c] = 3;
1540 needs_update = true;
1541 continue;
1543 /* If we have neighbors of one color, we are owned
1544 * by that color, too. */
1545 if (!ownermap[c] && (nei[1] || nei[2])) {
1546 int newowner = nei[1] ? 1 : 2;
1547 ownermap[c] = newowner;
1548 /* Speed up the propagation. */
1549 foreach_neighbor(board, c, {
1550 if (board_at(board, c) == S_NONE && !ownermap[c])
1551 ownermap[c] = newowner;
1553 needs_update = true;
1554 continue;
1556 } foreach_free_point_end;
1557 return needs_update;
1560 /* Tromp-Taylor Counting */
1561 floating_t
1562 board_official_score(struct board *board, struct move_queue *q)
1565 /* A point P, not colored C, is said to reach C, if there is a path of
1566 * (vertically or horizontally) adjacent points of P's color from P to
1567 * a point of color C.
1569 * A player's score is the number of points of her color, plus the
1570 * number of empty points that reach only her color. */
1572 int ownermap[board_size2(board)];
1573 int s[4] = {0};
1574 const int o[4] = {0, 1, 2, 0};
1575 foreach_point(board) {
1576 ownermap[c] = o[board_at(board, c)];
1577 s[board_at(board, c)]++;
1578 } foreach_point_end;
1580 if (q) {
1581 /* Process dead groups. */
1582 for (unsigned int i = 0; i < q->moves; i++) {
1583 foreach_in_group(board, q->move[i]) {
1584 enum stone color = board_at(board, c);
1585 ownermap[c] = o[stone_other(color)];
1586 s[color]--; s[stone_other(color)]++;
1587 } foreach_in_group_end;
1591 /* We need to special-case empty board. */
1592 if (!s[S_BLACK] && !s[S_WHITE])
1593 return board->komi;
1595 while (board_tromp_taylor_iter(board, ownermap))
1596 /* Flood-fill... */;
1598 int scores[S_MAX];
1599 memset(scores, 0, sizeof(scores));
1601 foreach_point(board) {
1602 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1603 if (ownermap[c] == 3)
1604 continue;
1605 scores[ownermap[c]]++;
1606 } foreach_point_end;
1608 return board->komi + (board->rules != RULES_SIMING ? board->handicap : 0) + scores[S_WHITE] - scores[S_BLACK];
1611 bool
1612 board_set_rules(struct board *board, char *name)
1614 if (!strcasecmp(name, "japanese")) {
1615 board->rules = RULES_JAPANESE;
1616 } else if (!strcasecmp(name, "chinese")) {
1617 board->rules = RULES_CHINESE;
1618 } else if (!strcasecmp(name, "aga")) {
1619 board->rules = RULES_AGA;
1620 } else if (!strcasecmp(name, "new_zealand")) {
1621 board->rules = RULES_NEW_ZEALAND;
1622 } else if (!strcasecmp(name, "siming") || !strcasecmp(name, "simplified_ing")) {
1623 board->rules = RULES_SIMING;
1624 } else {
1625 return false;
1627 return true;