UCT node expansion: Try to expand only leaf nodes, handle virtual loss
[pachi.git] / board.c
blob7ba27909e9bef403e6616fa5849d1536b112304b
1 #include <alloca.h>
2 #include <assert.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 //#define DEBUG
9 #include "board.h"
10 #include "debug.h"
11 #include "fbook.h"
12 #include "mq.h"
13 #include "random.h"
15 #ifdef BOARD_PAT3
16 #include "pattern3.h"
17 #endif
18 #ifdef BOARD_TRAITS
19 static void board_trait_recompute(struct board *board, coord_t coord);
20 #include "tactics/selfatari.h"
21 #endif
24 #if 0
25 #define profiling_noinline __attribute__((noinline))
26 #else
27 #define profiling_noinline
28 #endif
30 #define gi_granularity 4
31 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
34 static void
35 board_setup(struct board *b)
37 memset(b, 0, sizeof(*b));
39 struct move m = { pass, S_NONE };
40 b->last_move = b->last_move2 = b->last_move3 = b->last_move4 = b->last_ko = b->ko = m;
43 struct board *
44 board_init(char *fbookfile)
46 struct board *b = malloc2(sizeof(struct board));
47 board_setup(b);
49 b->fbookfile = fbookfile;
51 // Default setup
52 b->size = 9 + 2;
53 board_clear(b);
55 return b;
58 static size_t
59 board_alloc(struct board *board)
61 /* We do not allocate the board structure itself but we allocate
62 * all the arrays with board contents. */
64 int bsize = board_size2(board) * sizeof(*board->b);
65 int gsize = board_size2(board) * sizeof(*board->g);
66 int fsize = board_size2(board) * sizeof(*board->f);
67 int nsize = board_size2(board) * sizeof(*board->n);
68 int psize = board_size2(board) * sizeof(*board->p);
69 int hsize = board_size2(board) * 2 * sizeof(*board->h);
70 int gisize = board_size2(board) * sizeof(*board->gi);
71 #ifdef WANT_BOARD_C
72 int csize = board_size2(board) * sizeof(*board->c);
73 #else
74 int csize = 0;
75 #endif
76 #ifdef BOARD_PAT3
77 int p3size = board_size2(board) * sizeof(*board->pat3);
78 #else
79 int p3size = 0;
80 #endif
81 #ifdef BOARD_TRAITS
82 int tsize = board_size2(board) * sizeof(*board->t);
83 int tqsize = board_size2(board) * sizeof(*board->t);
84 #else
85 int tsize = 0;
86 int tqsize = 0;
87 #endif
88 int cdsize = board_size2(board) * sizeof(*board->coord);
90 size_t size = bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + p3size + tsize + tqsize + cdsize;
91 void *x = malloc2(size);
93 /* board->b must come first */
94 board->b = x; x += bsize;
95 board->g = x; x += gsize;
96 board->f = x; x += fsize;
97 board->p = x; x += psize;
98 board->n = x; x += nsize;
99 board->h = x; x += hsize;
100 board->gi = x; x += gisize;
101 #ifdef WANT_BOARD_C
102 board->c = x; x += csize;
103 #endif
104 #ifdef BOARD_PAT3
105 board->pat3 = x; x += p3size;
106 #endif
107 #ifdef BOARD_TRAITS
108 board->t = x; x += tsize;
109 board->tq = x; x += tqsize;
110 #endif
111 board->coord = x; x += cdsize;
113 return size;
116 struct board *
117 board_copy(struct board *b2, struct board *b1)
119 memcpy(b2, b1, sizeof(struct board));
121 size_t size = board_alloc(b2);
122 memcpy(b2->b, b1->b, size);
124 // XXX: Special semantics.
125 b2->fbook = NULL;
127 return b2;
130 void
131 board_done_noalloc(struct board *board)
133 if (board->b) free(board->b);
134 if (board->fbook) fbook_done(board->fbook);
137 void
138 board_done(struct board *board)
140 board_done_noalloc(board);
141 free(board);
144 void
145 board_resize(struct board *board, int size)
147 #ifdef BOARD_SIZE
148 assert(board_size(board) == size + 2);
149 #endif
150 assert(size <= BOARD_MAX_SIZE);
151 board->size = size + 2 /* S_OFFBOARD margin */;
152 board->size2 = board_size(board) * board_size(board);
154 board->bits2 = 1;
155 while ((1 << board->bits2) < board->size2) board->bits2++;
157 if (board->b)
158 free(board->b);
160 size_t asize = board_alloc(board);
161 memset(board->b, 0, asize);
164 static void
165 board_init_data(struct board *board)
167 int size = board_size(board);
169 board_setup(board);
170 board_resize(board, size - 2 /* S_OFFBOARD margin */);
172 /* Setup neighborhood iterators */
173 board->nei8[0] = -size - 1; // (-1,-1)
174 board->nei8[1] = 1;
175 board->nei8[2] = 1;
176 board->nei8[3] = size - 2; // (-1,0)
177 board->nei8[4] = 2;
178 board->nei8[5] = size - 2; // (-1,1)
179 board->nei8[6] = 1;
180 board->nei8[7] = 1;
181 board->dnei[0] = -size - 1;
182 board->dnei[1] = 2;
183 board->dnei[2] = size*2 - 2;
184 board->dnei[3] = 2;
186 /* Setup initial symmetry */
187 if (size % 2) {
188 board->symmetry.d = 1;
189 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
190 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
191 board->symmetry.type = SYM_FULL;
192 } else {
193 /* TODO: We do not handle board symmetry on boards
194 * with no tengen yet. */
195 board->symmetry.d = 0;
196 board->symmetry.x1 = board->symmetry.y1 = 1;
197 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
198 board->symmetry.type = SYM_NONE;
201 /* Set up coordinate cache */
202 foreach_point(board) {
203 board->coord[c][0] = c % board_size(board);
204 board->coord[c][1] = c / board_size(board);
205 } foreach_point_end;
207 /* Draw the offboard margin */
208 int top_row = board_size2(board) - board_size(board);
209 int i;
210 for (i = 0; i < board_size(board); i++)
211 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
212 for (i = 0; i <= top_row; i += board_size(board))
213 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
215 foreach_point(board) {
216 coord_t coord = c;
217 if (board_at(board, coord) == S_OFFBOARD)
218 continue;
219 foreach_neighbor(board, c, {
220 inc_neighbor_count_at(board, coord, board_at(board, c));
221 } );
222 } foreach_point_end;
224 /* All positions are free! Except the margin. */
225 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
226 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
227 board->f[board->flen++] = i;
229 /* Initialize zobrist hashtable. */
230 /* We will need these to be stable across Pachi runs for
231 * certain kinds of pattern matching, thus we do not use
232 * fast_random() for this. */
233 hash_t hseed = 0x3121110101112131;
234 foreach_point(board) {
235 board->h[c * 2] = (hseed *= 16807);
236 if (!board->h[c * 2])
237 board->h[c * 2] = 1;
238 /* And once again for white */
239 board->h[c * 2 + 1] = (hseed *= 16807);
240 if (!board->h[c * 2 + 1])
241 board->h[c * 2 + 1] = 1;
242 } foreach_point_end;
244 #ifdef BOARD_PAT3
245 /* Initialize 3x3 pattern codes. */
246 foreach_point(board) {
247 if (board_at(board, c) == S_NONE)
248 board->pat3[c] = pattern3_hash(board, c);
249 } foreach_point_end;
250 #endif
251 #ifdef BOARD_TRAITS
252 /* Initialize traits. */
253 foreach_point(board) {
254 trait_at(board, c, S_BLACK).cap = 0;
255 trait_at(board, c, S_BLACK).cap1 = 0;
256 trait_at(board, c, S_BLACK).safe = true;
257 trait_at(board, c, S_WHITE).cap = 0;
258 trait_at(board, c, S_WHITE).cap1 = 0;
259 trait_at(board, c, S_WHITE).safe = true;
260 } foreach_point_end;
261 #endif
264 void
265 board_clear(struct board *board)
267 int size = board_size(board);
268 floating_t komi = board->komi;
269 char *fbookfile = board->fbookfile;
271 board_done_noalloc(board);
273 static struct board bcache[BOARD_MAX_SIZE + 2];
274 assert(size > 0 && size <= BOARD_MAX_SIZE + 2);
275 if (bcache[size - 1].size == size) {
276 board_copy(board, &bcache[size - 1]);
277 } else {
278 board_init_data(board);
279 board_copy(&bcache[size - 1], board);
282 board->komi = komi;
283 board->fbookfile = fbookfile;
285 if (board->fbookfile) {
286 board->fbook = fbook_init(board->fbookfile, board);
290 static char *
291 board_print_top(struct board *board, char *s, char *end, int c)
293 for (int i = 0; i < c; i++) {
294 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
295 s += snprintf(s, end - s, " ");
296 for (int x = 1; x < board_size(board) - 1; x++)
297 s += snprintf(s, end - s, "%c ", asdf[x - 1]);
298 s += snprintf(s, end -s, " ");
300 s += snprintf(s, end - s, "\n");
301 for (int i = 0; i < c; i++) {
302 s += snprintf(s, end - s, " +-");
303 for (int x = 1; x < board_size(board) - 1; x++)
304 s += snprintf(s, end - s, "--");
305 s += snprintf(s, end - s, "+");
307 s += snprintf(s, end - s, "\n");
308 return s;
311 static char *
312 board_print_bottom(struct board *board, char *s, char *end, int c)
314 for (int i = 0; i < c; i++) {
315 s += snprintf(s, end - s, " +-");
316 for (int x = 1; x < board_size(board) - 1; x++)
317 s += snprintf(s, end - s, "--");
318 s += snprintf(s, end - s, "+");
320 s += snprintf(s, end - s, "\n");
321 return s;
324 static char *
325 board_print_row(struct board *board, int y, char *s, char *end, board_cprint cprint)
327 s += snprintf(s, end - s, " %2d | ", y);
328 for (int x = 1; x < board_size(board) - 1; x++) {
329 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
330 s += snprintf(s, end - s, "%c)", stone2char(board_atxy(board, x, y)));
331 else
332 s += snprintf(s, end - s, "%c ", stone2char(board_atxy(board, x, y)));
334 s += snprintf(s, end - s, "|");
335 if (cprint) {
336 s += snprintf(s, end - s, " %2d | ", y);
337 for (int x = 1; x < board_size(board) - 1; x++) {
338 s = cprint(board, coord_xy(board, x, y), s, end);
340 s += snprintf(s, end - s, "|");
342 s += snprintf(s, end - s, "\n");
343 return s;
346 void
347 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
349 char buf[10240];
350 char *s = buf;
351 char *end = buf + sizeof(buf);
352 s += snprintf(s, end - s, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
353 board->moves, board->komi, board->handicap,
354 board->captures[S_BLACK], board->captures[S_WHITE]);
355 s = board_print_top(board, s, end, 1 + !!cprint);
356 for (int y = board_size(board) - 2; y >= 1; y--)
357 s = board_print_row(board, y, s, end, cprint);
358 board_print_bottom(board, s, end, 1 + !!cprint);
359 fprintf(f, "%s\n", buf);
362 static char *
363 cprint_group(struct board *board, coord_t c, char *s, char *end)
365 s += snprintf(s, end - s, "%d ", group_base(group_at(board, c)));
366 return s;
369 void
370 board_print(struct board *board, FILE *f)
372 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
376 #ifdef BOARD_TRAITS
377 static bool
378 board_trait_safe(struct board *board, coord_t coord, enum stone color)
380 if (board->precise_selfatari)
381 return !is_bad_selfatari(board, color, coord);
382 else
383 return board_safe_to_play(board, coord, color);
386 static void
387 board_trait_recompute(struct board *board, coord_t coord)
389 trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);;
390 trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
391 if (DEBUGL(8)) {
392 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d cap1=%d safe=%d) (white cap=%d cap1=%d safe=%d)\n",
393 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
394 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).cap1, trait_at(board, coord, S_BLACK).safe,
395 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).cap1, trait_at(board, coord, S_WHITE).safe);
398 #endif
400 /* Recompute traits for dirty points that we have previously touched
401 * somehow (libs of their neighbors changed or so). */
402 static void
403 board_traits_recompute(struct board *board)
405 #ifdef BOARD_TRAITS
406 for (int i = 0; i < board->tqlen; i++) {
407 coord_t coord = board->tq[i];
408 trait_at(board, coord, S_BLACK).dirty = false;
409 if (board_at(board, coord) != S_NONE)
410 continue;
411 board_trait_recompute(board, coord);
413 board->tqlen = 0;
414 #endif
417 /* Queue traits of given point for recomputing. */
418 static void
419 board_trait_queue(struct board *board, coord_t coord)
421 #ifdef BOARD_TRAITS
422 if (trait_at(board, coord, S_BLACK).dirty)
423 return;
424 board->tq[board->tqlen++] = coord;
425 trait_at(board, coord, S_BLACK).dirty = true;
426 #endif
430 /* Update board hash with given coordinate. */
431 static void profiling_noinline
432 board_hash_update(struct board *board, coord_t coord, enum stone color)
434 board->hash ^= hash_at(board, coord, color);
435 board->qhash[coord_quadrant(coord, board)] ^= hash_at(board, coord, color);
436 if (DEBUGL(8))
437 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);
439 #if defined(BOARD_PAT3)
440 /* @color is not what we need in case of capture. */
441 static const int ataribits[8] = { -1, 0, -1, 1, 2, -1, 3, -1 };
442 enum stone new_color = board_at(board, coord);
443 bool in_atari = false;
444 if (new_color == S_NONE) {
445 board->pat3[coord] = pattern3_hash(board, coord);
446 } else {
447 in_atari = (board_group_info(board, group_at(board, coord)).libs == 1);
449 foreach_8neighbor(board, coord) {
450 /* Internally, the loop uses fn__i=[0..7]. We can use
451 * it directly to address bits within the bitmap of the
452 * neighbors since the bitmap order is reverse to the
453 * loop order. */
454 if (board_at(board, c) != S_NONE)
455 continue;
456 board->pat3[c] &= ~(3 << (fn__i*2));
457 board->pat3[c] |= new_color << (fn__i*2);
458 if (ataribits[fn__i] >= 0) {
459 board->pat3[c] &= ~(1 << (16 + ataribits[fn__i]));
460 board->pat3[c] |= in_atari << (16 + ataribits[fn__i]);
462 #if defined(BOARD_TRAITS)
463 board_trait_queue(board, c);
464 #endif
465 } foreach_8neighbor_end;
466 #endif
469 /* Commit current board hash to history. */
470 static void profiling_noinline
471 board_hash_commit(struct board *board)
473 if (DEBUGL(8))
474 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
475 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
476 board->history_hash[board->hash & history_hash_mask] = board->hash;
477 } else {
478 hash_t i = board->hash;
479 while (board->history_hash[i & history_hash_mask]) {
480 if (board->history_hash[i & history_hash_mask] == board->hash) {
481 if (DEBUGL(5))
482 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
483 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
484 board->superko_violation = true;
485 return;
487 i = history_hash_next(i);
489 board->history_hash[i & history_hash_mask] = board->hash;
494 void
495 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
497 if (likely(symmetry->type == SYM_NONE)) {
498 /* Fully degenerated already. We do not support detection
499 * of restoring of symmetry, assuming that this is too rare
500 * a case to handle. */
501 return;
504 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
505 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
506 if (DEBUGL(6)) {
507 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
508 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
509 symmetry->d, symmetry->type, x, y);
512 switch (symmetry->type) {
513 case SYM_FULL:
514 if (x == t && y == t) {
515 /* Tengen keeps full symmetry. */
516 return;
518 /* New symmetry now? */
519 if (x == y) {
520 symmetry->type = SYM_DIAG_UP;
521 symmetry->x1 = symmetry->y1 = 1;
522 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
523 symmetry->d = 1;
524 } else if (dx == y) {
525 symmetry->type = SYM_DIAG_DOWN;
526 symmetry->x1 = symmetry->y1 = 1;
527 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
528 symmetry->d = 1;
529 } else if (x == t) {
530 symmetry->type = SYM_HORIZ;
531 symmetry->y1 = 1;
532 symmetry->y2 = board_size(b) - 1;
533 symmetry->d = 0;
534 } else if (y == t) {
535 symmetry->type = SYM_VERT;
536 symmetry->x1 = 1;
537 symmetry->x2 = board_size(b) - 1;
538 symmetry->d = 0;
539 } else {
540 break_symmetry:
541 symmetry->type = SYM_NONE;
542 symmetry->x1 = symmetry->y1 = 1;
543 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
544 symmetry->d = 0;
546 break;
547 case SYM_DIAG_UP:
548 if (x == y)
549 return;
550 goto break_symmetry;
551 case SYM_DIAG_DOWN:
552 if (dx == y)
553 return;
554 goto break_symmetry;
555 case SYM_HORIZ:
556 if (x == t)
557 return;
558 goto break_symmetry;
559 case SYM_VERT:
560 if (y == t)
561 return;
562 goto break_symmetry;
563 case SYM_NONE:
564 assert(0);
565 break;
568 if (DEBUGL(6)) {
569 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
570 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
571 symmetry->d, symmetry->type);
573 /* Whew. */
577 void
578 board_handicap_stone(struct board *board, int x, int y, FILE *f)
580 struct move m;
581 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
583 board_play(board, &m);
584 /* Simulate white passing; otherwise, UCT search can get confused since
585 * tree depth parity won't match the color to move. */
586 board->moves++;
588 char *str = coord2str(m.coord, board);
589 if (DEBUGL(1))
590 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
591 if (f) fprintf(f, "%s ", str);
592 free(str);
595 void
596 board_handicap(struct board *board, int stones, FILE *f)
598 int margin = 3 + (board_size(board) >= 13);
599 int min = margin;
600 int mid = board_size(board) / 2;
601 int max = board_size(board) - 1 - margin;
602 const int places[][2] = {
603 { min, min }, { max, max }, { min, max }, { max, min },
604 { min, mid }, { max, mid },
605 { mid, min }, { mid, max },
606 { mid, mid },
609 board->handicap = stones;
611 if (stones == 5 || stones == 7) {
612 board_handicap_stone(board, mid, mid, f);
613 stones--;
616 int i;
617 for (i = 0; i < stones; i++)
618 board_handicap_stone(board, places[i][0], places[i][1], f);
622 static void __attribute__((noinline))
623 check_libs_consistency(struct board *board, group_t g)
625 #ifdef DEBUG
626 if (!g) return;
627 struct group *gi = &board_group_info(board, g);
628 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
629 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
630 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
631 assert(0);
633 #endif
636 static void
637 check_pat3_consistency(struct board *board, coord_t coord)
639 #ifdef DEBUG
640 foreach_8neighbor(board, coord) {
641 if (board_at(board, c) == S_NONE && pattern3_hash(board, c) != board->pat3[c]) {
642 board_print(board, stderr);
643 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);
644 assert(0);
646 } foreach_8neighbor_end;
647 #endif
650 static void
651 board_capturable_add(struct board *board, group_t group, coord_t lib, bool onestone)
653 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
654 #ifdef BOARD_TRAITS
655 /* Increase capturable count trait of my last lib. */
656 enum stone capturing_color = stone_other(board_at(board, group));
657 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
658 foreach_neighbor(board, lib, {
659 if (DEBUGL(8) && group_at(board, c) == group)
660 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);
661 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
662 trait_at(board, lib, capturing_color).cap1 += (group_at(board, c) == group && onestone);
664 board_trait_queue(board, lib);
665 #endif
667 #ifdef BOARD_PAT3
668 int fn__i = 0;
669 foreach_neighbor(board, lib, {
670 board->pat3[lib] |= (group_at(board, c) == group) << (16 + 3 - fn__i);
671 fn__i++;
673 #endif
675 #ifdef WANT_BOARD_C
676 /* Update the list of capturable groups. */
677 assert(group);
678 assert(board->clen < board_size2(board));
679 board->c[board->clen++] = group;
680 #endif
682 static void
683 board_capturable_rm(struct board *board, group_t group, coord_t lib, bool onestone)
685 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
686 #ifdef BOARD_TRAITS
687 /* Decrease capturable count trait of my previously-last lib. */
688 enum stone capturing_color = stone_other(board_at(board, group));
689 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
690 foreach_neighbor(board, lib, {
691 if (DEBUGL(8) && group_at(board, c) == group)
692 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);
693 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
694 trait_at(board, lib, capturing_color).cap1 -= (group_at(board, c) == group && onestone);
696 board_trait_queue(board, lib);
697 #endif
699 #ifdef BOARD_PAT3
700 int fn__i = 0;
701 foreach_neighbor(board, lib, {
702 board->pat3[lib] &= ~((group_at(board, c) == group) << (16 + 3 - fn__i));
703 fn__i++;
705 #endif
707 #ifdef WANT_BOARD_C
708 /* Update the list of capturable groups. */
709 for (int i = 0; i < board->clen; i++) {
710 if (unlikely(board->c[i] == group)) {
711 board->c[i] = board->c[--board->clen];
712 return;
715 fprintf(stderr, "rm of bad group %d\n", group_base(group));
716 assert(0);
717 #endif
720 static void
721 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
723 #ifdef BOARD_TRAITS
724 board_trait_queue(board, lib1);
725 board_trait_queue(board, lib2);
726 #endif
728 static void
729 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
731 #ifdef BOARD_TRAITS
732 board_trait_queue(board, lib1);
733 board_trait_queue(board, lib2);
734 #endif
737 static void
738 board_group_addlib(struct board *board, group_t group, coord_t coord)
740 if (DEBUGL(7)) {
741 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
742 group_base(group), coord2sstr(group_base(group), board),
743 board_group_info(board, group).libs, coord2sstr(coord, board));
746 check_libs_consistency(board, group);
748 struct group *gi = &board_group_info(board, group);
749 bool onestone = group_is_onestone(board, group);
750 if (gi->libs < GROUP_KEEP_LIBS) {
751 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
752 #if 0
753 /* Seems extra branch just slows it down */
754 if (!gi->lib[i])
755 break;
756 #endif
757 if (unlikely(gi->lib[i] == coord))
758 return;
760 if (gi->libs == 0) {
761 board_capturable_add(board, group, coord, onestone);
762 } else if (gi->libs == 1) {
763 board_capturable_rm(board, group, gi->lib[0], onestone);
764 board_atariable_add(board, group, gi->lib[0], coord);
765 } else if (gi->libs == 2) {
766 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
768 gi->lib[gi->libs++] = coord;
771 check_libs_consistency(board, group);
774 static void
775 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
777 /* Add extra liberty from the board to our liberty list. */
778 unsigned char watermark[board_size2(board) / 8];
779 memset(watermark, 0, sizeof(watermark));
780 #define watermark_get(c) (watermark[c >> 3] & (1 << (c & 7)))
781 #define watermark_set(c) watermark[c >> 3] |= (1 << (c & 7))
783 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
784 watermark_set(gi->lib[i]);
785 watermark_set(avoid);
787 foreach_in_group(board, group) {
788 coord_t coord2 = c;
789 foreach_neighbor(board, coord2, {
790 if (board_at(board, c) + watermark_get(c) != S_NONE)
791 continue;
792 watermark_set(c);
793 gi->lib[gi->libs++] = c;
794 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
795 return;
796 } );
797 } foreach_in_group_end;
798 #undef watermark_get
799 #undef watermark_set
802 static void
803 board_group_rmlib(struct board *board, group_t group, coord_t coord)
805 if (DEBUGL(7)) {
806 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
807 group_base(group), coord2sstr(group_base(group), board),
808 board_group_info(board, group).libs, coord2sstr(coord, board));
811 struct group *gi = &board_group_info(board, group);
812 bool onestone = group_is_onestone(board, group);
813 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
814 #if 0
815 /* Seems extra branch just slows it down */
816 if (!gi->lib[i])
817 break;
818 #endif
819 if (likely(gi->lib[i] != coord))
820 continue;
822 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
823 gi->lib[gi->libs] = 0;
825 check_libs_consistency(board, group);
827 /* Postpone refilling lib[] until we need to. */
828 assert(GROUP_REFILL_LIBS > 1);
829 if (gi->libs > GROUP_REFILL_LIBS)
830 return;
831 if (gi->libs == GROUP_REFILL_LIBS)
832 board_group_find_extra_libs(board, group, gi, coord);
834 if (gi->libs == 2) {
835 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
836 } else if (gi->libs == 1) {
837 board_capturable_add(board, group, gi->lib[0], onestone);
838 board_atariable_rm(board, group, gi->lib[0], lib);
839 } else if (gi->libs == 0)
840 board_capturable_rm(board, group, lib, onestone);
841 return;
844 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
845 * can call this multiple times per coord. */
846 check_libs_consistency(board, group);
847 return;
851 /* This is a low-level routine that doesn't maintain consistency
852 * of all the board data structures. */
853 static void
854 board_remove_stone(struct board *board, group_t group, coord_t c)
856 enum stone color = board_at(board, c);
857 board_at(board, c) = S_NONE;
858 group_at(board, c) = 0;
859 board_hash_update(board, c, color);
860 #ifdef BOARD_TRAITS
861 /* We mark as cannot-capture now. If this is a ko/snapback,
862 * we will get incremented later in board_group_addlib(). */
863 trait_at(board, c, S_BLACK).cap = trait_at(board, c, S_BLACK).cap1 = 0;
864 trait_at(board, c, S_WHITE).cap = trait_at(board, c, S_WHITE).cap1 = 0;
865 board_trait_queue(board, c);
866 #endif
868 /* Increase liberties of surrounding groups */
869 coord_t coord = c;
870 foreach_neighbor(board, coord, {
871 dec_neighbor_count_at(board, c, color);
872 board_trait_queue(board, c);
873 group_t g = group_at(board, c);
874 if (g && g != group)
875 board_group_addlib(board, g, coord);
878 #ifdef BOARD_PAT3
879 /* board_hash_update() might have seen the freed up point as able
880 * to capture another group in atari that only after the loop
881 * above gained enough liberties. Reset pat3 again. */
882 board->pat3[c] = pattern3_hash(board, c);
883 #endif
885 if (DEBUGL(6))
886 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
887 board->f[board->flen++] = c;
890 static int profiling_noinline
891 board_group_capture(struct board *board, group_t group)
893 int stones = 0;
895 foreach_in_group(board, group) {
896 board->captures[stone_other(board_at(board, c))]++;
897 board_remove_stone(board, group, c);
898 stones++;
899 } foreach_in_group_end;
901 struct group *gi = &board_group_info(board, group);
902 assert(gi->libs == 0);
903 memset(gi, 0, sizeof(*gi));
905 return stones;
909 static void profiling_noinline
910 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
912 #ifdef BOARD_TRAITS
913 struct group *gi = &board_group_info(board, group);
914 bool onestone = group_is_onestone(board, group);
916 if (gi->libs == 1) {
917 /* Our group is temporarily in atari; make sure the capturable
918 * counts also correspond to the newly added stone before we
919 * start adding liberties again so bump-dump ops match. */
920 enum stone capturing_color = stone_other(board_at(board, group));
921 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
923 coord_t lib = board_group_info(board, group).lib[0];
924 if (coord_is_adjecent(lib, coord, board)) {
925 if (DEBUGL(8))
926 fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
927 trait_at(board, lib, capturing_color).cap++;
928 /* This is never a 1-stone group, obviously. */
929 board_trait_queue(board, lib);
932 if (onestone) {
933 /* We are not 1-stone group anymore, update the cap1
934 * counter specifically. */
935 foreach_neighbor(board, group, {
936 if (board_at(board, c) != S_NONE) continue;
937 trait_at(board, c, capturing_color).cap1--;
938 board_trait_queue(board, c);
942 #endif
944 group_at(board, coord) = group;
945 groupnext_at(board, coord) = groupnext_at(board, prevstone);
946 groupnext_at(board, prevstone) = coord;
948 foreach_neighbor(board, coord, {
949 if (board_at(board, c) == S_NONE)
950 board_group_addlib(board, group, c);
953 if (DEBUGL(8))
954 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
955 coord_x(prevstone, board), coord_y(prevstone, board),
956 coord_x(coord, board), coord_y(coord, board),
957 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
958 group_base(group));
961 static void profiling_noinline
962 merge_groups(struct board *board, group_t group_to, group_t group_from)
964 if (DEBUGL(7))
965 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
966 group_base(group_from), group_base(group_to));
967 struct group *gi_from = &board_group_info(board, group_from);
968 struct group *gi_to = &board_group_info(board, group_to);
969 bool onestone_from = group_is_onestone(board, group_from);
970 bool onestone_to = group_is_onestone(board, group_to);
972 /* We do this early before the group info is rewritten. */
973 if (gi_from->libs == 2)
974 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
975 else if (gi_from->libs == 1)
976 board_capturable_rm(board, group_from, gi_from->lib[0], onestone_from);
978 if (DEBUGL(7))
979 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
981 if (gi_to->libs < GROUP_KEEP_LIBS) {
982 for (int i = 0; i < gi_from->libs; i++) {
983 for (int j = 0; j < gi_to->libs; j++)
984 if (gi_to->lib[j] == gi_from->lib[i])
985 goto next_from_lib;
986 if (gi_to->libs == 0) {
987 board_capturable_add(board, group_to, gi_from->lib[i], onestone_to);
988 } else if (gi_to->libs == 1) {
989 board_capturable_rm(board, group_to, gi_to->lib[0], onestone_to);
990 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
991 } else if (gi_to->libs == 2) {
992 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
994 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
995 if (gi_to->libs >= GROUP_KEEP_LIBS)
996 break;
997 next_from_lib:;
1001 if (gi_to->libs == 1) {
1002 coord_t lib = board_group_info(board, group_to).lib[0];
1003 #ifdef BOARD_TRAITS
1004 enum stone capturing_color = stone_other(board_at(board, group_to));
1005 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1007 /* Our group is currently in atari; make sure we properly
1008 * count in even the neighbors from the other group in the
1009 * capturable counter. */
1010 foreach_neighbor(board, lib, {
1011 if (DEBUGL(8) && group_at(board, c) == group_from)
1012 fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1013 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1014 /* This is never a 1-stone group, obviously. */
1016 board_trait_queue(board, lib);
1018 if (onestone_to) {
1019 /* We are not 1-stone group anymore, update the cap1
1020 * counter specifically. */
1021 foreach_neighbor(board, group_to, {
1022 if (board_at(board, c) != S_NONE) continue;
1023 trait_at(board, c, capturing_color).cap1--;
1024 board_trait_queue(board, c);
1027 #endif
1028 #ifdef BOARD_PAT3
1029 if (gi_from->libs == 1) {
1030 /* We removed group_from from capturable groups,
1031 * therefore switching the atari flag off.
1032 * We need to set it again since group_to is also
1033 * capturable. */
1034 int fn__i = 0;
1035 foreach_neighbor(board, lib, {
1036 board->pat3[lib] |= (group_at(board, c) == group_from) << (16 + 3 - fn__i);
1037 fn__i++;
1040 #endif
1043 coord_t last_in_group;
1044 foreach_in_group(board, group_from) {
1045 last_in_group = c;
1046 group_at(board, c) = group_to;
1047 } foreach_in_group_end;
1048 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1049 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1050 memset(gi_from, 0, sizeof(struct group));
1052 if (DEBUGL(7))
1053 fprintf(stderr, "board_play_raw: merged group: %d\n",
1054 group_base(group_to));
1057 static group_t profiling_noinline
1058 new_group(struct board *board, coord_t coord)
1060 group_t group = coord;
1061 struct group *gi = &board_group_info(board, group);
1062 foreach_neighbor(board, coord, {
1063 if (board_at(board, c) == S_NONE)
1064 /* board_group_addlib is ridiculously expensive for us */
1065 #if GROUP_KEEP_LIBS < 4
1066 if (gi->libs < GROUP_KEEP_LIBS)
1067 #endif
1068 gi->lib[gi->libs++] = c;
1071 group_at(board, coord) = group;
1072 groupnext_at(board, coord) = 0;
1074 if (gi->libs == 2)
1075 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1076 else if (gi->libs == 1)
1077 board_capturable_add(board, group, gi->lib[0], true);
1078 check_libs_consistency(board, group);
1080 if (DEBUGL(8))
1081 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1082 coord_x(coord, board), coord_y(coord, board),
1083 group_base(group));
1085 return group;
1088 static inline group_t
1089 play_one_neighbor(struct board *board,
1090 coord_t coord, enum stone color, enum stone other_color,
1091 coord_t c, group_t group)
1093 enum stone ncolor = board_at(board, c);
1094 group_t ngroup = group_at(board, c);
1096 inc_neighbor_count_at(board, c, color);
1097 /* We can be S_NONE, in that case we need to update the safety
1098 * trait since we might be left with only one liberty. */
1099 board_trait_queue(board, c);
1101 if (!ngroup)
1102 return group;
1104 board_group_rmlib(board, ngroup, coord);
1105 if (DEBUGL(7))
1106 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1107 group_base(ngroup), ncolor, color, other_color);
1109 if (ncolor == color && ngroup != group) {
1110 if (!group) {
1111 group = ngroup;
1112 add_to_group(board, group, c, coord);
1113 } else {
1114 merge_groups(board, group, ngroup);
1116 } else if (ncolor == other_color) {
1117 if (DEBUGL(8)) {
1118 struct group *gi = &board_group_info(board, ngroup);
1119 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1120 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1121 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1122 fprintf(stderr, "\n");
1124 if (unlikely(board_group_captured(board, ngroup)))
1125 board_group_capture(board, ngroup);
1127 return group;
1130 /* We played on a place with at least one liberty. We will become a member of
1131 * some group for sure. */
1132 static group_t profiling_noinline
1133 board_play_outside(struct board *board, struct move *m, int f)
1135 coord_t coord = m->coord;
1136 enum stone color = m->color;
1137 enum stone other_color = stone_other(color);
1138 group_t group = 0;
1140 board->f[f] = board->f[--board->flen];
1141 if (DEBUGL(6))
1142 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1144 #if defined(BOARD_TRAITS) && defined(DEBUG)
1145 /* Sanity check that cap matches reality. */
1147 int a = 0, b = 0;
1148 foreach_neighbor(board, coord, {
1149 group_t g = group_at(board, c);
1150 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1151 b += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1) && group_is_onestone(board, g);
1153 assert(a == trait_at(board, coord, color).cap);
1154 assert(b == trait_at(board, coord, color).cap1);
1155 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1157 #endif
1158 foreach_neighbor(board, coord, {
1159 group = play_one_neighbor(board, coord, color, other_color, c, group);
1162 board_at(board, coord) = color;
1163 if (unlikely(!group))
1164 group = new_group(board, coord);
1166 board->last_move2 = board->last_move;
1167 board->last_move = *m;
1168 board->moves++;
1169 board_hash_update(board, coord, color);
1170 board_symmetry_update(board, &board->symmetry, coord);
1171 struct move ko = { pass, S_NONE };
1172 board->ko = ko;
1174 check_pat3_consistency(board, coord);
1176 return group;
1179 /* We played in an eye-like shape. Either we capture at least one of the eye
1180 * sides in the process of playing, or return -1. */
1181 static int profiling_noinline
1182 board_play_in_eye(struct board *board, struct move *m, int f)
1184 coord_t coord = m->coord;
1185 enum stone color = m->color;
1186 /* Check ko: Capture at a position of ko capture one move ago */
1187 if (unlikely(color == board->ko.color && coord == board->ko.coord)) {
1188 if (DEBUGL(5))
1189 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1190 return -1;
1191 } else if (DEBUGL(6)) {
1192 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1193 color, coord_x(coord, board), coord_y(coord, board),
1194 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1197 struct move ko = { pass, S_NONE };
1199 int captured_groups = 0;
1201 foreach_neighbor(board, coord, {
1202 group_t g = group_at(board, c);
1203 if (DEBUGL(7))
1204 fprintf(stderr, "board_check: group %d has %d libs\n",
1205 g, board_group_info(board, g).libs);
1206 captured_groups += (board_group_info(board, g).libs == 1);
1209 if (likely(captured_groups == 0)) {
1210 if (DEBUGL(5)) {
1211 if (DEBUGL(6))
1212 board_print(board, stderr);
1213 fprintf(stderr, "board_check: one-stone suicide\n");
1216 return -1;
1218 #ifdef BOARD_TRAITS
1219 /* We _will_ for sure capture something. */
1220 assert(trait_at(board, coord, color).cap > 0);
1221 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1222 #endif
1224 board->f[f] = board->f[--board->flen];
1225 if (DEBUGL(6))
1226 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1228 foreach_neighbor(board, coord, {
1229 inc_neighbor_count_at(board, c, color);
1230 /* Originally, this could not have changed any trait
1231 * since no neighbors were S_NONE, however by now some
1232 * of them might be removed from the board. */
1233 board_trait_queue(board, c);
1235 group_t group = group_at(board, c);
1236 if (!group)
1237 continue;
1239 board_group_rmlib(board, group, coord);
1240 if (DEBUGL(7))
1241 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1242 group_base(group));
1244 if (board_group_captured(board, group)) {
1245 if (board_group_capture(board, group) == 1) {
1246 /* If we captured multiple groups at once,
1247 * we can't be fighting ko so we don't need
1248 * to check for that. */
1249 ko.color = stone_other(color);
1250 ko.coord = c;
1251 board->last_ko = ko;
1252 board->last_ko_age = board->moves;
1253 if (DEBUGL(5))
1254 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1259 board_at(board, coord) = color;
1260 group_t group = new_group(board, coord);
1262 board->last_move2 = board->last_move;
1263 board->last_move = *m;
1264 board->moves++;
1265 board_hash_update(board, coord, color);
1266 board_hash_commit(board);
1267 board_traits_recompute(board);
1268 board_symmetry_update(board, &board->symmetry, coord);
1269 board->ko = ko;
1271 check_pat3_consistency(board, coord);
1273 return !!group;
1276 static int __attribute__((flatten))
1277 board_play_f(struct board *board, struct move *m, int f)
1279 if (DEBUGL(7)) {
1280 fprintf(stderr, "board_play(%s): ---- Playing %d,%d\n", coord2sstr(m->coord, board), coord_x(m->coord, board), coord_y(m->coord, board));
1282 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1283 /* NOT playing in an eye. Thus this move has to succeed. (This
1284 * is thanks to New Zealand rules. Otherwise, multi-stone
1285 * suicide might fail.) */
1286 group_t group = board_play_outside(board, m, f);
1287 if (unlikely(board_group_captured(board, group))) {
1288 board_group_capture(board, group);
1290 board_hash_commit(board);
1291 board_traits_recompute(board);
1292 return 0;
1293 } else {
1294 return board_play_in_eye(board, m, f);
1299 board_play(struct board *board, struct move *m)
1301 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1302 struct move nomove = { pass, S_NONE };
1303 board->ko = nomove;
1304 board->last_move4 = board->last_move3;
1305 board->last_move3 = board->last_move2;
1306 board->last_move2 = board->last_move;
1307 board->last_move = *m;
1308 return 0;
1311 int f;
1312 for (f = 0; f < board->flen; f++)
1313 if (board->f[f] == m->coord)
1314 return board_play_f(board, m, f);
1316 if (DEBUGL(7))
1317 fprintf(stderr, "board_check: stone exists\n");
1318 return -1;
1321 /* Undo, supported only for pass moves. This form of undo is required by KGS
1322 * to settle disputes on dead groups. (Undo of real moves would be more complex
1323 * particularly for capturing moves.) */
1324 int board_undo(struct board *board)
1326 if (!is_pass(board->last_move.coord))
1327 return -1;
1328 board->last_move = board->last_move2;
1329 board->last_move2 = board->last_move3;
1330 board->last_move3 = board->last_move4;
1331 if (board->last_ko_age == board->moves)
1332 board->ko = board->last_ko;
1333 return 0;
1336 static inline bool
1337 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1339 *coord = b->f[f];
1340 struct move m = { *coord, color };
1341 if (DEBUGL(6))
1342 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));
1343 if (unlikely(board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1344 || !board_is_valid_move(b, &m)
1345 || (permit && !permit(permit_data, b, &m)))
1346 return false;
1347 if (m.coord == *coord) {
1348 return likely(board_play_f(b, &m, f) >= 0);
1349 } else {
1350 *coord = m.coord; // permit modified the coordinate
1351 return likely(board_play(b, &m) >= 0);
1355 void
1356 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1358 if (unlikely(b->flen == 0))
1359 goto pass;
1361 int base = fast_random(b->flen), f;
1362 for (f = base; f < b->flen; f++)
1363 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1364 return;
1365 for (f = 0; f < base; f++)
1366 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1367 return;
1369 pass:
1370 *coord = pass;
1371 struct move m = { pass, color };
1372 board_play(b, &m);
1376 bool
1377 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1379 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1381 /* XXX: We attempt false eye detection but we will yield false
1382 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1384 foreach_diag_neighbor(board, coord) {
1385 color_diag_libs[(enum stone) board_at(board, c)]++;
1386 } foreach_diag_neighbor_end;
1387 /* For false eye, we need two enemy stones diagonally in the
1388 * middle of the board, or just one enemy stone at the edge
1389 * or in the corner. */
1390 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1391 return color_diag_libs[stone_other(eye_color)] >= 2;
1394 bool
1395 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1397 return board_is_eyelike(board, coord, eye_color)
1398 && !board_is_false_eyelike(board, coord, eye_color);
1401 enum stone
1402 board_get_one_point_eye(struct board *board, coord_t coord)
1404 if (board_is_one_point_eye(board, coord, S_WHITE))
1405 return S_WHITE;
1406 else if (board_is_one_point_eye(board, coord, S_BLACK))
1407 return S_BLACK;
1408 else
1409 return S_NONE;
1413 floating_t
1414 board_fast_score(struct board *board)
1416 int scores[S_MAX];
1417 memset(scores, 0, sizeof(scores));
1419 foreach_point(board) {
1420 enum stone color = board_at(board, c);
1421 if (color == S_NONE)
1422 color = board_get_one_point_eye(board, c);
1423 scores[color]++;
1424 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1425 } foreach_point_end;
1427 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1430 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1432 /* One flood-fill iteration; returns true if next iteration
1433 * is required. */
1434 static bool
1435 board_tromp_taylor_iter(struct board *board, int *ownermap)
1437 bool needs_update = false;
1438 foreach_free_point(board) {
1439 /* Ignore occupied and already-dame positions. */
1440 assert(board_at(board, c) == S_NONE);
1441 if (ownermap[c] == 3)
1442 continue;
1443 /* Count neighbors. */
1444 int nei[4] = {0};
1445 foreach_neighbor(board, c, {
1446 nei[ownermap[c]]++;
1448 /* If we have neighbors of both colors, or dame,
1449 * we are dame too. */
1450 if ((nei[1] && nei[2]) || nei[3]) {
1451 ownermap[c] = 3;
1452 /* Speed up the propagation. */
1453 foreach_neighbor(board, c, {
1454 if (board_at(board, c) == S_NONE)
1455 ownermap[c] = 3;
1457 needs_update = true;
1458 continue;
1460 /* If we have neighbors of one color, we are owned
1461 * by that color, too. */
1462 if (!ownermap[c] && (nei[1] || nei[2])) {
1463 int newowner = nei[1] ? 1 : 2;
1464 ownermap[c] = newowner;
1465 /* Speed up the propagation. */
1466 foreach_neighbor(board, c, {
1467 if (board_at(board, c) == S_NONE && !ownermap[c])
1468 ownermap[c] = newowner;
1470 needs_update = true;
1471 continue;
1473 } foreach_free_point_end;
1474 return needs_update;
1477 /* Tromp-Taylor Counting */
1478 floating_t
1479 board_official_score(struct board *board, struct move_queue *q)
1482 /* A point P, not colored C, is said to reach C, if there is a path of
1483 * (vertically or horizontally) adjacent points of P's color from P to
1484 * a point of color C.
1486 * A player's score is the number of points of her color, plus the
1487 * number of empty points that reach only her color. */
1489 int ownermap[board_size2(board)];
1490 int s[4] = {0};
1491 const int o[4] = {0, 1, 2, 0};
1492 foreach_point(board) {
1493 ownermap[c] = o[board_at(board, c)];
1494 s[board_at(board, c)]++;
1495 } foreach_point_end;
1497 if (q) {
1498 /* Process dead groups. */
1499 for (unsigned int i = 0; i < q->moves; i++) {
1500 foreach_in_group(board, q->move[i]) {
1501 enum stone color = board_at(board, c);
1502 ownermap[c] = o[stone_other(color)];
1503 s[color]--; s[stone_other(color)]++;
1504 } foreach_in_group_end;
1508 /* We need to special-case empty board. */
1509 if (!s[S_BLACK] && !s[S_WHITE])
1510 return board->komi + board->handicap;
1512 while (board_tromp_taylor_iter(board, ownermap))
1513 /* Flood-fill... */;
1515 int scores[S_MAX];
1516 memset(scores, 0, sizeof(scores));
1518 foreach_point(board) {
1519 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1520 if (ownermap[c] == 3)
1521 continue;
1522 scores[ownermap[c]]++;
1523 } foreach_point_end;
1525 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];