fast_frandom(): Introduce, use in the probdist picker
[pachi/json.git] / board.c
blobc05201d3d92e209ad656822d4857c7325be45752
1 #include <alloca.h>
2 #include <assert.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
7 #include "board.h"
8 #include "debug.h"
9 #include "mq.h"
10 #include "random.h"
12 #ifdef BOARD_SPATHASH
13 #include "patternsp.h"
14 #endif
16 bool random_pass = false;
19 #if 0
20 #define profiling_noinline __attribute__((noinline))
21 #else
22 #define profiling_noinline
23 #endif
25 #define gi_granularity 4
26 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
29 static void
30 board_setup(struct board *b)
32 memset(b, 0, sizeof(*b));
34 struct move m = { pass, S_NONE };
35 b->last_move = b->last_move2 = b->last_ko = b->ko = m;
38 struct board *
39 board_init(void)
41 struct board *b = malloc(sizeof(struct board));
42 board_setup(b);
44 // Default setup
45 b->size = 9 + 2;
46 board_clear(b);
48 return b;
51 struct board *
52 board_copy(struct board *b2, struct board *b1)
54 memcpy(b2, b1, sizeof(struct board));
56 int bsize = board_size2(b2) * sizeof(*b2->b);
57 int gsize = board_size2(b2) * sizeof(*b2->g);
58 int fsize = board_size2(b2) * sizeof(*b2->f);
59 int nsize = board_size2(b2) * sizeof(*b2->n);
60 int psize = board_size2(b2) * sizeof(*b2->p);
61 int hsize = board_size2(b2) * 2 * sizeof(*b2->h);
62 int gisize = board_size2(b2) * sizeof(*b2->gi);
63 #ifdef WANT_BOARD_C
64 int csize = board_size2(b2) * sizeof(*b2->c);
65 #else
66 int csize = 0;
67 #endif
68 #ifdef BOARD_SPATHASH
69 int ssize = board_size2(b2) * sizeof(*b2->spathash);
70 #else
71 int ssize = 0;
72 #endif
73 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize);
74 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize);
75 b2->b = x; x += bsize;
76 b2->g = x; x += gsize;
77 b2->f = x; x += fsize;
78 b2->p = x; x += psize;
79 b2->n = x; x += nsize;
80 b2->h = x; x += hsize;
81 b2->gi = x; x += gisize;
82 #ifdef WANT_BOARD_C
83 b2->c = x; x += csize;
84 #endif
85 #ifdef BOARD_SPATHASH
86 b2->spathash = x; x += ssize;
87 #endif
89 return b2;
92 void
93 board_done_noalloc(struct board *board)
95 if (board->b) free(board->b);
98 void
99 board_done(struct board *board)
101 board_done_noalloc(board);
102 free(board);
105 void
106 board_resize(struct board *board, int size)
108 #ifdef BOARD_SIZE
109 assert(board_size(board) == size + 2);
110 #else
111 board_size(board) = size + 2 /* S_OFFBOARD margin */;
112 board_size2(board) = board_size(board) * board_size(board);
113 #endif
114 if (board->b)
115 free(board->b);
117 int bsize = board_size2(board) * sizeof(*board->b);
118 int gsize = board_size2(board) * sizeof(*board->g);
119 int fsize = board_size2(board) * sizeof(*board->f);
120 int nsize = board_size2(board) * sizeof(*board->n);
121 int psize = board_size2(board) * sizeof(*board->p);
122 int hsize = board_size2(board) * 2 * sizeof(*board->h);
123 int gisize = board_size2(board) * sizeof(*board->gi);
124 #ifdef WANT_BOARD_C
125 int csize = board_size2(board) * sizeof(*board->c);
126 #else
127 int csize = 0;
128 #endif
129 #ifdef BOARD_SPATHASH
130 int ssize = board_size2(board) * sizeof(*board->spathash);
131 #else
132 int ssize = 0;
133 #endif
134 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize);
135 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize);
136 board->b = x; x += bsize;
137 board->g = x; x += gsize;
138 board->f = x; x += fsize;
139 board->p = x; x += psize;
140 board->n = x; x += nsize;
141 board->h = x; x += hsize;
142 board->gi = x; x += gisize;
143 #ifdef WANT_BOARD_C
144 board->c = x; x += csize;
145 #endif
146 #ifdef BOARD_SPATHASH
147 board->spathash = x; x += ssize;
148 #endif
151 void
152 board_clear(struct board *board)
154 int size = board_size(board);
155 float komi = board->komi;
157 board_done_noalloc(board);
158 board_setup(board);
159 board_resize(board, size - 2 /* S_OFFBOARD margin */);
161 board->komi = komi;
163 /* Setup initial symmetry */
164 board->symmetry.d = 1;
165 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
166 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
167 board->symmetry.type = SYM_FULL;
169 /* Draw the offboard margin */
170 int top_row = board_size2(board) - board_size(board);
171 int i;
172 for (i = 0; i < board_size(board); i++)
173 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
174 for (i = 0; i <= top_row; i += board_size(board))
175 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
177 foreach_point(board) {
178 coord_t coord = c;
179 if (board_at(board, coord) == S_OFFBOARD)
180 continue;
181 foreach_neighbor(board, c, {
182 inc_neighbor_count_at(board, coord, board_at(board, c));
183 } );
184 } foreach_point_end;
186 /* First, pass is always a free position. */
187 board->f[board->flen++] = coord_raw(pass);
188 /* All positions are free! Except the margin. */
189 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
190 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
191 board->f[board->flen++] = i;
193 /* Initialize zobrist hashtable. */
194 foreach_point(board) {
195 int max = (sizeof(hash_t) << history_hash_bits);
196 /* fast_random() is 16-bit only */
197 board->h[coord_raw(c) * 2] = ((hash_t) fast_random(max))
198 | ((hash_t) fast_random(max) << 16)
199 | ((hash_t) fast_random(max) << 32)
200 | ((hash_t) fast_random(max) << 48);
201 if (!board->h[coord_raw(c) * 2])
202 /* Would be kinda "oops". */
203 board->h[coord_raw(c) * 2] = 1;
204 /* And once again for white */
205 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
206 | ((hash_t) fast_random(max) << 16)
207 | ((hash_t) fast_random(max) << 32)
208 | ((hash_t) fast_random(max) << 48);
209 if (!board->h[coord_raw(c) * 2 + 1])
210 board->h[coord_raw(c) * 2 + 1] = 1;
211 } foreach_point_end;
213 #ifdef BOARD_SPATHASH
214 /* Initialize spatial hashes. */
215 foreach_point(board) {
216 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
217 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
218 ptcoords_at(x, y, c, board, j);
219 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
220 pthashes[0][j][board_at(board, c)];
221 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
222 pthashes[0][j][stone_other(board_at(board, c))];
225 } foreach_point_end;
226 #endif
230 static void
231 board_print_top(struct board *board, FILE *f, int c)
233 for (int i = 0; i < c; i++) {
234 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
235 fprintf(f, " ");
236 for (int x = 1; x < board_size(board) - 1; x++)
237 fprintf(f, "%c ", asdf[x - 1]);
238 fprintf(f, " ");
240 fprintf(f, "\n");
241 for (int i = 0; i < c; i++) {
242 fprintf(f, " +-");
243 for (int x = 1; x < board_size(board) - 1; x++)
244 fprintf(f, "--");
245 fprintf(f, "+");
247 fprintf(f, "\n");
250 static void
251 board_print_bottom(struct board *board, FILE *f, int c)
253 for (int i = 0; i < c; i++) {
254 fprintf(f, " +-");
255 for (int x = 1; x < board_size(board) - 1; x++)
256 fprintf(f, "--");
257 fprintf(f, "+");
259 fprintf(f, "\n");
262 static void
263 board_print_row(struct board *board, int y, FILE *f, board_cprint cprint)
265 fprintf(f, " %2d | ", y);
266 for (int x = 1; x < board_size(board) - 1; x++) {
267 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
268 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
269 else
270 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
272 fprintf(f, "|");
273 if (cprint) {
274 fprintf(f, " %2d | ", y);
275 for (int x = 1; x < board_size(board) - 1; x++) {
276 cprint(board, coord_xy(board, x, y), f);
278 fprintf(f, "|");
280 fprintf(f, "\n");
283 void
284 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
286 fprintf(f, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
287 board->moves, board->komi, board->handicap,
288 board->captures[S_BLACK], board->captures[S_WHITE]);
289 board_print_top(board, f, 1 + !!cprint);
290 for (int y = board_size(board) - 2; y >= 1; y--)
291 board_print_row(board, y, f, cprint);
292 board_print_bottom(board, f, 1 + !!cprint);
293 fprintf(f, "\n");
296 static void
297 cprint_group(struct board *board, coord_t c, FILE *f)
299 fprintf(f, "%d ", group_base(group_at(board, c)));
302 void
303 board_print(struct board *board, FILE *f)
305 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
309 /* Update board hash with given coordinate. */
310 static void profiling_noinline
311 board_hash_update(struct board *board, coord_t coord, enum stone color)
313 board->hash ^= hash_at(board, coord, color);
314 if (DEBUGL(8))
315 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);
317 #ifdef BOARD_SPATHASH
318 /* Gridcular metric is reflective, so we update all hashes
319 * of appropriate ditance in OUR circle. */
320 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
321 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
322 ptcoords_at(x, y, coord, board, j);
323 /* We either changed from S_NONE to color
324 * or vice versa; doesn't matter. */
325 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
326 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
327 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
328 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
331 #endif
334 /* Commit current board hash to history. */
335 static void profiling_noinline
336 board_hash_commit(struct board *board)
338 if (DEBUGL(8))
339 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
340 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
341 board->history_hash[board->hash & history_hash_mask] = board->hash;
342 } else {
343 hash_t i = board->hash;
344 while (board->history_hash[i & history_hash_mask]) {
345 if (board->history_hash[i & history_hash_mask] == board->hash) {
346 if (DEBUGL(5))
347 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
348 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
349 board->superko_violation = true;
350 return;
352 i = history_hash_next(i);
354 board->history_hash[i & history_hash_mask] = board->hash;
359 void
360 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
362 if (likely(symmetry->type == SYM_NONE)) {
363 /* Fully degenerated already. We do not support detection
364 * of restoring of symmetry, assuming that this is too rare
365 * a case to handle. */
366 return;
369 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
370 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
371 if (DEBUGL(6)) {
372 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
373 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
374 symmetry->d, symmetry->type, x, y);
377 switch (symmetry->type) {
378 case SYM_FULL:
379 if (x == t && y == t) {
380 /* Tengen keeps full symmetry. */
381 return;
383 /* New symmetry now? */
384 if (x == y) {
385 symmetry->type = SYM_DIAG_UP;
386 symmetry->x1 = symmetry->y1 = 1;
387 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
388 symmetry->d = 1;
389 } else if (dx == y) {
390 symmetry->type = SYM_DIAG_DOWN;
391 symmetry->x1 = symmetry->y1 = 1;
392 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
393 symmetry->d = 1;
394 } else if (x == t) {
395 symmetry->type = SYM_HORIZ;
396 symmetry->y1 = 1;
397 symmetry->y2 = board_size(b) - 1;
398 symmetry->d = 0;
399 } else if (y == t) {
400 symmetry->type = SYM_VERT;
401 symmetry->x1 = 1;
402 symmetry->x2 = board_size(b) - 1;
403 symmetry->d = 0;
404 } else {
405 break_symmetry:
406 symmetry->type = SYM_NONE;
407 symmetry->x1 = symmetry->y1 = 1;
408 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
409 symmetry->d = 0;
411 break;
412 case SYM_DIAG_UP:
413 if (x == y)
414 return;
415 goto break_symmetry;
416 case SYM_DIAG_DOWN:
417 if (dx == y)
418 return;
419 goto break_symmetry;
420 case SYM_HORIZ:
421 if (x == t)
422 return;
423 goto break_symmetry;
424 case SYM_VERT:
425 if (y == t)
426 return;
427 goto break_symmetry;
428 case SYM_NONE:
429 assert(0);
430 break;
433 if (DEBUGL(6)) {
434 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
435 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
436 symmetry->d, symmetry->type);
438 /* Whew. */
442 void
443 board_handicap_stone(struct board *board, int x, int y, FILE *f)
445 struct move m;
446 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
448 board_play(board, &m);
449 /* Simulate white passing; otherwise, UCT search can get confused since
450 * tree depth parity won't match the color to move. */
451 board->moves++;
453 char *str = coord2str(m.coord, board);
454 if (DEBUGL(1))
455 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
456 fprintf(f, "%s ", str);
457 free(str);
460 void
461 board_handicap(struct board *board, int stones, FILE *f)
463 int margin = 3 + (board_size(board) >= 13);
464 int min = margin;
465 int mid = board_size(board) / 2;
466 int max = board_size(board) - 1 - margin;
467 const int places[][2] = {
468 { min, min }, { max, max }, { max, min }, { min, max },
469 { min, mid }, { max, mid },
470 { mid, min }, { mid, max },
471 { mid, mid },
474 board->handicap = stones;
476 if (stones == 5 || stones == 7) {
477 board_handicap_stone(board, mid, mid, f);
478 stones--;
481 int i;
482 for (i = 0; i < stones; i++)
483 board_handicap_stone(board, places[i][0], places[i][1], f);
487 static void __attribute__((noinline))
488 check_libs_consistency(struct board *board, group_t g)
490 #ifdef DEBUG
491 if (!g) return;
492 struct group *gi = &board_group_info(board, g);
493 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
494 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
495 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
496 assert(0);
498 #endif
501 static void
502 board_capturable_add(struct board *board, group_t group)
504 #ifdef WANT_BOARD_C
505 //fprintf(stderr, "add of group %d (%d)\n", group_base(group), board->clen);
506 assert(group);
507 assert(board->clen < board_size2(board));
508 board->c[board->clen++] = group;
509 #endif
511 static void
512 board_capturable_rm(struct board *board, group_t group)
514 #ifdef WANT_BOARD_C
515 //fprintf(stderr, "rm of group %d\n", group_base(group));
516 for (int i = 0; i < board->clen; i++) {
517 if (unlikely(board->c[i] == group)) {
518 board->c[i] = board->c[--board->clen];
519 return;
522 fprintf(stderr, "rm of bad group %d\n", group_base(group));
523 assert(0);
524 #endif
527 static void
528 board_group_addlib(struct board *board, group_t group, coord_t coord)
530 if (DEBUGL(7)) {
531 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
532 group_base(group), coord2sstr(group_base(group), board),
533 board_group_info(board, group).libs, coord2sstr(coord, board));
536 check_libs_consistency(board, group);
538 struct group *gi = &board_group_info(board, group);
539 if (gi->libs < GROUP_KEEP_LIBS) {
540 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
541 #if 0
542 /* Seems extra branch just slows it down */
543 if (!gi->lib[i])
544 break;
545 #endif
546 if (unlikely(gi->lib[i] == coord))
547 return;
549 if (gi->libs == 0)
550 board_capturable_add(board, group);
551 else if (gi->libs == 1)
552 board_capturable_rm(board, group);
553 gi->lib[gi->libs++] = coord;
556 check_libs_consistency(board, group);
559 static void
560 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
562 /* Add extra liberty from the board to our liberty list. */
563 unsigned char watermark[board_size2(board) / 8];
564 memset(watermark, 0, sizeof(watermark));
565 #define watermark_get(c) (watermark[coord_raw(c) >> 3] & (1 << (coord_raw(c) & 7)))
566 #define watermark_set(c) watermark[coord_raw(c) >> 3] |= (1 << (coord_raw(c) & 7))
568 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
569 watermark_set(gi->lib[i]);
570 watermark_set(avoid);
572 foreach_in_group(board, group) {
573 coord_t coord2 = c;
574 foreach_neighbor(board, coord2, {
575 if (board_at(board, c) + watermark_get(c) != S_NONE)
576 continue;
577 watermark_set(c);
578 gi->lib[gi->libs++] = c;
579 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
580 return;
581 } );
582 } foreach_in_group_end;
583 #undef watermark_get
584 #undef watermark_set
587 static void
588 board_group_rmlib(struct board *board, group_t group, coord_t coord)
590 if (DEBUGL(7)) {
591 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
592 group_base(group), coord2sstr(group_base(group), board),
593 board_group_info(board, group).libs, coord2sstr(coord, board));
596 struct group *gi = &board_group_info(board, group);
597 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
598 #if 0
599 /* Seems extra branch just slows it down */
600 if (!gi->lib[i])
601 break;
602 #endif
603 if (likely(gi->lib[i] != coord))
604 continue;
606 gi->lib[i] = gi->lib[--gi->libs];
607 gi->lib[gi->libs] = 0;
609 check_libs_consistency(board, group);
611 /* Postpone refilling lib[] until we need to. */
612 assert(GROUP_REFILL_LIBS > 1);
613 if (gi->libs > GROUP_REFILL_LIBS)
614 return;
615 if (gi->libs == GROUP_REFILL_LIBS)
616 board_group_find_extra_libs(board, group, gi, coord);
618 if (gi->libs == 1)
619 board_capturable_add(board, group);
620 else if (gi->libs == 0)
621 board_capturable_rm(board, group);
622 return;
625 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
626 * can call this multiple times per coord. */
627 check_libs_consistency(board, group);
628 return;
632 /* This is a low-level routine that doesn't maintain consistency
633 * of all the board data structures. */
634 static void
635 board_remove_stone(struct board *board, coord_t c)
637 enum stone color = board_at(board, c);
638 board_at(board, c) = S_NONE;
639 group_at(board, c) = 0;
640 board_hash_update(board, c, color);
642 /* Increase liberties of surrounding groups */
643 coord_t coord = c;
644 foreach_neighbor(board, coord, {
645 dec_neighbor_count_at(board, c, color);
646 group_t g = group_at(board, c);
647 if (g)
648 board_group_addlib(board, g, coord);
651 if (DEBUGL(6))
652 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
653 board->f[board->flen++] = coord_raw(c);
656 static int profiling_noinline
657 board_group_capture(struct board *board, group_t group)
659 int stones = 0;
661 foreach_in_group(board, group) {
662 board->captures[stone_other(board_at(board, c))]++;
663 board_remove_stone(board, c);
664 stones++;
665 } foreach_in_group_end;
667 if (board_group_info(board, group).libs == 1)
668 board_capturable_rm(board, group);
669 memset(&board_group_info(board, group), 0, sizeof(struct group));
671 return stones;
675 static void profiling_noinline
676 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
678 foreach_neighbor(board, coord, {
679 if (board_at(board, c) == S_NONE)
680 board_group_addlib(board, group, c);
683 group_at(board, coord) = group;
684 groupnext_at(board, coord) = groupnext_at(board, prevstone);
685 groupnext_at(board, prevstone) = coord_raw(coord);
687 if (DEBUGL(8))
688 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
689 coord_x(prevstone, board), coord_y(prevstone, board),
690 coord_x(coord, board), coord_y(coord, board),
691 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
692 group_base(group));
695 static void profiling_noinline
696 merge_groups(struct board *board, group_t group_to, group_t group_from)
698 if (DEBUGL(7))
699 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
700 group_base(group_from), group_base(group_to));
702 coord_t last_in_group;
703 foreach_in_group(board, group_from) {
704 last_in_group = c;
705 group_at(board, c) = group_to;
706 } foreach_in_group_end;
707 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
708 groupnext_at(board, group_base(group_to)) = group_base(group_from);
710 struct group *gi_from = &board_group_info(board, group_from);
711 struct group *gi_to = &board_group_info(board, group_to);
712 if (gi_to->libs < GROUP_KEEP_LIBS) {
713 for (int i = 0; i < gi_from->libs; i++) {
714 for (int j = 0; j < gi_to->libs; j++)
715 if (gi_to->lib[j] == gi_from->lib[i])
716 goto next_from_lib;
717 if (gi_to->libs == 0)
718 board_capturable_add(board, group_to);
719 else if (gi_to->libs == 1)
720 board_capturable_rm(board, group_to);
721 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
722 if (gi_to->libs >= GROUP_KEEP_LIBS)
723 break;
724 next_from_lib:;
728 if (gi_from->libs == 1)
729 board_capturable_rm(board, group_from);
730 memset(gi_from, 0, sizeof(struct group));
732 if (DEBUGL(7))
733 fprintf(stderr, "board_play_raw: merged group: %d\n",
734 group_base(group_to));
737 static group_t profiling_noinline
738 new_group(struct board *board, coord_t coord)
740 group_t group = coord_raw(coord);
741 struct group *gi = &board_group_info(board, group);
742 foreach_neighbor(board, coord, {
743 if (board_at(board, c) == S_NONE)
744 /* board_group_addlib is ridiculously expensive for us */
745 #if GROUP_KEEP_LIBS < 4
746 if (gi->libs < GROUP_KEEP_LIBS)
747 #endif
748 gi->lib[gi->libs++] = c;
750 if (gi->libs == 1)
751 board_capturable_add(board, group);
752 check_libs_consistency(board, group);
754 group_at(board, coord) = group;
755 groupnext_at(board, coord) = 0;
757 if (DEBUGL(8))
758 fprintf(stderr, "new_group: added %d,%d to group %d\n",
759 coord_x(coord, board), coord_y(coord, board),
760 group_base(group));
762 return group;
765 static inline group_t
766 play_one_neighbor(struct board *board,
767 coord_t coord, enum stone color, enum stone other_color,
768 coord_t c, group_t group)
770 enum stone ncolor = board_at(board, c);
771 group_t ngroup = group_at(board, c);
773 inc_neighbor_count_at(board, c, color);
775 if (!ngroup)
776 return group;
778 board_group_rmlib(board, ngroup, coord);
779 if (DEBUGL(7))
780 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
781 group_base(ngroup), ncolor, color, other_color);
783 if (ncolor == color && ngroup != group) {
784 if (!group) {
785 group = ngroup;
786 add_to_group(board, group, c, coord);
787 } else {
788 merge_groups(board, group, ngroup);
790 } else if (ncolor == other_color) {
791 if (DEBUGL(8)) {
792 struct group *gi = &board_group_info(board, ngroup);
793 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
794 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
795 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
796 fprintf(stderr, "\n");
798 if (unlikely(board_group_captured(board, ngroup)))
799 board_group_capture(board, ngroup);
801 return group;
804 /* We played on a place with at least one liberty. We will become a member of
805 * some group for sure. */
806 static group_t profiling_noinline
807 board_play_outside(struct board *board, struct move *m, int f)
809 coord_t coord = m->coord;
810 enum stone color = m->color;
811 enum stone other_color = stone_other(color);
812 group_t group = 0;
814 board->f[f] = board->f[--board->flen];
815 if (DEBUGL(6))
816 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
818 foreach_neighbor(board, coord, {
819 group = play_one_neighbor(board, coord, color, other_color, c, group);
822 if (unlikely(!group))
823 group = new_group(board, coord);
825 board_at(board, coord) = color;
826 board->last_move2 = board->last_move;
827 board->last_move = *m;
828 board->moves++;
829 board_hash_update(board, coord, color);
830 board_symmetry_update(board, &board->symmetry, coord);
831 struct move ko = { pass, S_NONE };
832 board->ko = ko;
834 return group;
837 /* We played in an eye-like shape. Either we capture at least one of the eye
838 * sides in the process of playing, or return -1. */
839 static int profiling_noinline
840 board_play_in_eye(struct board *board, struct move *m, int f)
842 coord_t coord = m->coord;
843 enum stone color = m->color;
844 /* Check ko: Capture at a position of ko capture one move ago */
845 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
846 if (DEBUGL(5))
847 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
848 return -1;
849 } else if (DEBUGL(6)) {
850 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
851 color, coord_x(coord, board), coord_y(coord, board),
852 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
855 struct move ko = { pass, S_NONE };
857 int captured_groups = 0;
859 foreach_neighbor(board, coord, {
860 group_t g = group_at(board, c);
861 if (DEBUGL(7))
862 fprintf(stderr, "board_check: group %d has %d libs\n",
863 g, board_group_info(board, g).libs);
864 captured_groups += (board_group_info(board, g).libs == 1);
867 if (likely(captured_groups == 0)) {
868 if (DEBUGL(5)) {
869 if (DEBUGL(6))
870 board_print(board, stderr);
871 fprintf(stderr, "board_check: one-stone suicide\n");
874 return -1;
877 board->f[f] = board->f[--board->flen];
878 if (DEBUGL(6))
879 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
881 foreach_neighbor(board, coord, {
882 inc_neighbor_count_at(board, c, color);
884 group_t group = group_at(board, c);
885 if (!group)
886 continue;
888 board_group_rmlib(board, group, coord);
889 if (DEBUGL(7))
890 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
891 group_base(group));
893 if (board_group_captured(board, group)) {
894 if (board_group_capture(board, group) == 1) {
895 /* If we captured multiple groups at once,
896 * we can't be fighting ko so we don't need
897 * to check for that. */
898 ko.color = stone_other(color);
899 ko.coord = c;
900 board->last_ko = ko;
901 board->last_ko_age = board->moves;
902 if (DEBUGL(5))
903 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
908 board_at(board, coord) = color;
910 board->last_move2 = board->last_move;
911 board->last_move = *m;
912 board->moves++;
913 board_hash_update(board, coord, color);
914 board_hash_commit(board);
915 board_symmetry_update(board, &board->symmetry, coord);
916 board->ko = ko;
918 return !!new_group(board, coord);
921 static int __attribute__((flatten))
922 board_play_f(struct board *board, struct move *m, int f)
924 if (DEBUGL(7)) {
925 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
927 if (likely(!board_is_eyelike(board, &m->coord, stone_other(m->color)))) {
928 /* NOT playing in an eye. Thus this move has to succeed. (This
929 * is thanks to New Zealand rules. Otherwise, multi-stone
930 * suicide might fail.) */
931 group_t group = board_play_outside(board, m, f);
932 if (unlikely(board_group_captured(board, group))) {
933 board_group_capture(board, group);
935 board_hash_commit(board);
936 return 0;
937 } else {
938 return board_play_in_eye(board, m, f);
943 board_play(struct board *board, struct move *m)
945 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
946 board->last_move2 = board->last_move;
947 board->last_move = *m;
948 return 0;
951 int f;
952 for (f = 0; f < board->flen; f++)
953 if (board->f[f] == coord_raw(m->coord))
954 return board_play_f(board, m, f);
956 if (DEBUGL(7))
957 fprintf(stderr, "board_check: stone exists\n");
958 return -1;
962 static inline bool
963 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
965 coord_raw(*coord) = b->f[f];
966 if (unlikely(is_pass(*coord)))
967 return random_pass;
968 struct move m = { *coord, color };
969 if (DEBUGL(6))
970 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
971 return (likely(!board_is_one_point_eye(b, coord, color)) /* bad idea to play into one, usually */
972 && board_is_valid_move(b, &m)
973 && (!permit || permit(permit_data, b, &m))
974 && likely(board_play_f(b, &m, f) >= 0));
977 void
978 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
980 int base = fast_random(b->flen);
981 coord_pos(*coord, base, b);
982 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
983 return;
985 int f;
986 for (f = base + 1; f < b->flen; f++)
987 if (board_try_random_move(b, color, coord, f, permit, permit_data))
988 return;
989 for (f = 0; f < base; f++)
990 if (board_try_random_move(b, color, coord, f, permit, permit_data))
991 return;
993 *coord = pass;
997 bool
998 board_is_false_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
1000 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1002 /* XXX: We attempt false eye detection but we will yield false
1003 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1005 foreach_diag_neighbor(board, *coord) {
1006 color_diag_libs[(enum stone) board_at(board, c)]++;
1007 } foreach_diag_neighbor_end;
1008 /* For false eye, we need two enemy stones diagonally in the
1009 * middle of the board, or just one enemy stone at the edge
1010 * or in the corner. */
1011 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1012 return color_diag_libs[stone_other(eye_color)] >= 2;
1015 bool
1016 board_is_one_point_eye(struct board *board, coord_t *coord, enum stone eye_color)
1018 return board_is_eyelike(board, coord, eye_color)
1019 && !board_is_false_eyelike(board, coord, eye_color);
1022 enum stone
1023 board_get_one_point_eye(struct board *board, coord_t *coord)
1025 if (board_is_one_point_eye(board, coord, S_WHITE))
1026 return S_WHITE;
1027 else if (board_is_one_point_eye(board, coord, S_BLACK))
1028 return S_BLACK;
1029 else
1030 return S_NONE;
1034 float
1035 board_fast_score(struct board *board)
1037 int scores[S_MAX];
1038 memset(scores, 0, sizeof(scores));
1040 foreach_point(board) {
1041 enum stone color = board_at(board, c);
1042 if (color == S_NONE)
1043 color = board_get_one_point_eye(board, &c);
1044 scores[color]++;
1045 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1046 } foreach_point_end;
1048 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1051 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1053 /* One flood-fill iteration; returns true if next iteration
1054 * is required. */
1055 static bool
1056 board_tromp_taylor_iter(struct board *board, int *ownermap)
1058 bool needs_update = false;
1059 foreach_point(board) {
1060 /* Ignore occupied and already-dame positions. */
1061 if (board_at(board, c) != S_NONE || ownermap[c] == 3)
1062 continue;
1063 /* Count neighbors. */
1064 int nei[4] = {0};
1065 foreach_neighbor(board, c, {
1066 nei[ownermap[c]]++;
1068 /* If we have neighbors of both colors, or dame,
1069 * we are dame too. */
1070 if ((nei[1] && nei[2]) || nei[3]) {
1071 ownermap[c] = 3;
1072 /* Speed up the propagation. */
1073 foreach_neighbor(board, c, {
1074 if (board_at(board, c) == S_NONE)
1075 ownermap[c] = 3;
1077 needs_update = true;
1078 continue;
1080 /* If we have neighbors of one color, we are owned
1081 * by that color, too. */
1082 if (!ownermap[c] && (nei[1] || nei[2])) {
1083 int newowner = nei[1] ? 1 : 2;
1084 ownermap[c] = newowner;
1085 /* Speed up the propagation. */
1086 foreach_neighbor(board, c, {
1087 if (board_at(board, c) == S_NONE && !ownermap[c])
1088 ownermap[c] = newowner;
1090 needs_update = true;
1091 continue;
1093 } foreach_point_end;
1094 return needs_update;
1097 /* Tromp-Taylor Counting */
1098 float
1099 board_official_score(struct board *board, struct move_queue *q)
1102 /* A point P, not colored C, is said to reach C, if there is a path of
1103 * (vertically or horizontally) adjacent points of P's color from P to
1104 * a point of color C.
1106 * A player's score is the number of points of her color, plus the
1107 * number of empty points that reach only her color. */
1109 int ownermap[board_size2(board)];
1110 int s[4] = {0};
1111 const int o[4] = {0, 1, 2, 0};
1112 foreach_point(board) {
1113 ownermap[c] = o[board_at(board, c)];
1114 s[board_at(board, c)]++;
1115 } foreach_point_end;
1117 if (q) {
1118 /* Process dead groups. */
1119 for (int i = 0; i < q->moves; i++) {
1120 foreach_in_group(board, q->move[i]) {
1121 enum stone color = board_at(board, c);
1122 ownermap[c] = o[stone_other(color)];
1123 s[color]--; s[stone_other(color)]++;
1124 } foreach_in_group_end;
1128 /* We need to special-case empty board. */
1129 if (!s[S_BLACK] && !s[S_WHITE])
1130 return board->komi + board->handicap;
1132 while (board_tromp_taylor_iter(board, ownermap))
1133 /* Flood-fill... */;
1135 int scores[S_MAX];
1136 memset(scores, 0, sizeof(scores));
1138 foreach_point(board) {
1139 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1140 if (ownermap[c] == 3)
1141 continue;
1142 scores[ownermap[c]]++;
1143 } foreach_point_end;
1145 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];