ELO: Use probability distribution over available moves, not whole board
[pachi/json.git] / board.c
blobfb15a1ae2afd77879bec7051d5b6ceb9dbc07515
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] ^=
220 pthashes[0][j][board_at(board, c)];
223 } foreach_point_end;
224 #endif
228 static void
229 board_print_top(struct board *board, FILE *f, int c)
231 for (int i = 0; i < c; i++) {
232 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
233 fprintf(f, " ");
234 for (int x = 1; x < board_size(board) - 1; x++)
235 fprintf(f, "%c ", asdf[x - 1]);
236 fprintf(f, " ");
238 fprintf(f, "\n");
239 for (int i = 0; i < c; i++) {
240 fprintf(f, " +-");
241 for (int x = 1; x < board_size(board) - 1; x++)
242 fprintf(f, "--");
243 fprintf(f, "+");
245 fprintf(f, "\n");
248 static void
249 board_print_bottom(struct board *board, FILE *f, int c)
251 for (int i = 0; i < c; i++) {
252 fprintf(f, " +-");
253 for (int x = 1; x < board_size(board) - 1; x++)
254 fprintf(f, "--");
255 fprintf(f, "+");
257 fprintf(f, "\n");
260 static void
261 board_print_row(struct board *board, int y, FILE *f, board_cprint cprint)
263 fprintf(f, " %2d | ", y);
264 for (int x = 1; x < board_size(board) - 1; x++) {
265 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
266 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
267 else
268 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
270 fprintf(f, "|");
271 if (cprint) {
272 fprintf(f, " %2d | ", y);
273 for (int x = 1; x < board_size(board) - 1; x++) {
274 cprint(board, coord_xy(board, x, y), f);
276 fprintf(f, "|");
278 fprintf(f, "\n");
281 void
282 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
284 fprintf(f, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
285 board->moves, board->komi, board->handicap,
286 board->captures[S_BLACK], board->captures[S_WHITE]);
287 board_print_top(board, f, 1 + !!cprint);
288 for (int y = board_size(board) - 2; y >= 1; y--)
289 board_print_row(board, y, f, cprint);
290 board_print_bottom(board, f, 1 + !!cprint);
291 fprintf(f, "\n");
294 static void
295 cprint_group(struct board *board, coord_t c, FILE *f)
297 fprintf(f, "%d ", group_base(group_at(board, c)));
300 void
301 board_print(struct board *board, FILE *f)
303 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
307 /* Update board hash with given coordinate. */
308 static void profiling_noinline
309 board_hash_update(struct board *board, coord_t coord, enum stone color)
311 board->hash ^= hash_at(board, coord, color);
312 if (DEBUGL(8))
313 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);
315 #ifdef BOARD_SPATHASH
316 /* Gridcular metric is reflective, so we update all hashes
317 * of appropriate ditance in OUR circle. */
318 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
319 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
320 ptcoords_at(x, y, coord, board, j);
321 /* We either changed from S_NONE to color
322 * or vice versa; doesn't matter. */
323 board->spathash[coord_xy(board, x, y)][d - 1] ^=
324 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
327 #endif
330 /* Commit current board hash to history. */
331 static void profiling_noinline
332 board_hash_commit(struct board *board)
334 if (DEBUGL(8))
335 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
336 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
337 board->history_hash[board->hash & history_hash_mask] = board->hash;
338 } else {
339 hash_t i = board->hash;
340 while (board->history_hash[i & history_hash_mask]) {
341 if (board->history_hash[i & history_hash_mask] == board->hash) {
342 if (DEBUGL(5))
343 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
344 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
345 board->superko_violation = true;
346 return;
348 i = history_hash_next(i);
350 board->history_hash[i & history_hash_mask] = board->hash;
355 void
356 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
358 if (likely(symmetry->type == SYM_NONE)) {
359 /* Fully degenerated already. We do not support detection
360 * of restoring of symmetry, assuming that this is too rare
361 * a case to handle. */
362 return;
365 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
366 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
367 if (DEBUGL(6)) {
368 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
369 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
370 symmetry->d, symmetry->type, x, y);
373 switch (symmetry->type) {
374 case SYM_FULL:
375 if (x == t && y == t) {
376 /* Tengen keeps full symmetry. */
377 return;
379 /* New symmetry now? */
380 if (x == y) {
381 symmetry->type = SYM_DIAG_UP;
382 symmetry->x1 = symmetry->y1 = 1;
383 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
384 symmetry->d = 1;
385 } else if (dx == y) {
386 symmetry->type = SYM_DIAG_DOWN;
387 symmetry->x1 = symmetry->y1 = 1;
388 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
389 symmetry->d = 1;
390 } else if (x == t) {
391 symmetry->type = SYM_HORIZ;
392 symmetry->y1 = 1;
393 symmetry->y2 = board_size(b) - 1;
394 symmetry->d = 0;
395 } else if (y == t) {
396 symmetry->type = SYM_VERT;
397 symmetry->x1 = 1;
398 symmetry->x2 = board_size(b) - 1;
399 symmetry->d = 0;
400 } else {
401 break_symmetry:
402 symmetry->type = SYM_NONE;
403 symmetry->x1 = symmetry->y1 = 1;
404 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
405 symmetry->d = 0;
407 break;
408 case SYM_DIAG_UP:
409 if (x == y)
410 return;
411 goto break_symmetry;
412 case SYM_DIAG_DOWN:
413 if (dx == y)
414 return;
415 goto break_symmetry;
416 case SYM_HORIZ:
417 if (x == t)
418 return;
419 goto break_symmetry;
420 case SYM_VERT:
421 if (y == t)
422 return;
423 goto break_symmetry;
424 case SYM_NONE:
425 assert(0);
426 break;
429 if (DEBUGL(6)) {
430 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
431 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
432 symmetry->d, symmetry->type);
434 /* Whew. */
438 void
439 board_handicap_stone(struct board *board, int x, int y, FILE *f)
441 struct move m;
442 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
444 board_play(board, &m);
445 /* Simulate white passing; otherwise, UCT search can get confused since
446 * tree depth parity won't match the color to move. */
447 board->moves++;
449 char *str = coord2str(m.coord, board);
450 if (DEBUGL(1))
451 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
452 fprintf(f, "%s ", str);
453 free(str);
456 void
457 board_handicap(struct board *board, int stones, FILE *f)
459 int margin = 3 + (board_size(board) >= 13);
460 int min = margin;
461 int mid = board_size(board) / 2;
462 int max = board_size(board) - 1 - margin;
463 const int places[][2] = {
464 { min, min }, { max, max }, { max, min }, { min, max },
465 { min, mid }, { max, mid },
466 { mid, min }, { mid, max },
467 { mid, mid },
470 board->handicap = stones;
472 if (stones == 5 || stones == 7) {
473 board_handicap_stone(board, mid, mid, f);
474 stones--;
477 int i;
478 for (i = 0; i < stones; i++)
479 board_handicap_stone(board, places[i][0], places[i][1], f);
483 static void __attribute__((noinline))
484 check_libs_consistency(struct board *board, group_t g)
486 #ifdef DEBUG
487 if (!g) return;
488 struct group *gi = &board_group_info(board, g);
489 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
490 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
491 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
492 assert(0);
494 #endif
497 static void
498 board_capturable_add(struct board *board, group_t group)
500 #ifdef WANT_BOARD_C
501 //fprintf(stderr, "add of group %d (%d)\n", group_base(group), board->clen);
502 assert(group);
503 assert(board->clen < board_size2(board));
504 board->c[board->clen++] = group;
505 #endif
507 static void
508 board_capturable_rm(struct board *board, group_t group)
510 #ifdef WANT_BOARD_C
511 //fprintf(stderr, "rm of group %d\n", group_base(group));
512 for (int i = 0; i < board->clen; i++) {
513 if (unlikely(board->c[i] == group)) {
514 board->c[i] = board->c[--board->clen];
515 return;
518 fprintf(stderr, "rm of bad group %d\n", group_base(group));
519 assert(0);
520 #endif
523 static void
524 board_group_addlib(struct board *board, group_t group, coord_t coord)
526 if (DEBUGL(7)) {
527 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
528 group_base(group), coord2sstr(group_base(group), board),
529 board_group_info(board, group).libs, coord2sstr(coord, board));
532 check_libs_consistency(board, group);
534 struct group *gi = &board_group_info(board, group);
535 if (gi->libs < GROUP_KEEP_LIBS) {
536 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
537 #if 0
538 /* Seems extra branch just slows it down */
539 if (!gi->lib[i])
540 break;
541 #endif
542 if (unlikely(gi->lib[i] == coord))
543 return;
545 if (gi->libs == 0)
546 board_capturable_add(board, group);
547 else if (gi->libs == 1)
548 board_capturable_rm(board, group);
549 gi->lib[gi->libs++] = coord;
552 check_libs_consistency(board, group);
555 static void
556 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
558 /* Add extra liberty from the board to our liberty list. */
559 unsigned char watermark[board_size2(board) / 8];
560 memset(watermark, 0, sizeof(watermark));
561 #define watermark_get(c) (watermark[coord_raw(c) >> 3] & (1 << (coord_raw(c) & 7)))
562 #define watermark_set(c) watermark[coord_raw(c) >> 3] |= (1 << (coord_raw(c) & 7))
564 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
565 watermark_set(gi->lib[i]);
566 watermark_set(avoid);
568 foreach_in_group(board, group) {
569 coord_t coord2 = c;
570 foreach_neighbor(board, coord2, {
571 if (board_at(board, c) + watermark_get(c) != S_NONE)
572 continue;
573 watermark_set(c);
574 gi->lib[gi->libs++] = c;
575 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
576 return;
577 } );
578 } foreach_in_group_end;
579 #undef watermark_get
580 #undef watermark_set
583 static void
584 board_group_rmlib(struct board *board, group_t group, coord_t coord)
586 if (DEBUGL(7)) {
587 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
588 group_base(group), coord2sstr(group_base(group), board),
589 board_group_info(board, group).libs, coord2sstr(coord, board));
592 struct group *gi = &board_group_info(board, group);
593 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
594 #if 0
595 /* Seems extra branch just slows it down */
596 if (!gi->lib[i])
597 break;
598 #endif
599 if (likely(gi->lib[i] != coord))
600 continue;
602 gi->lib[i] = gi->lib[--gi->libs];
603 gi->lib[gi->libs] = 0;
605 check_libs_consistency(board, group);
607 /* Postpone refilling lib[] until we need to. */
608 assert(GROUP_REFILL_LIBS > 1);
609 if (gi->libs > GROUP_REFILL_LIBS)
610 return;
611 if (gi->libs == GROUP_REFILL_LIBS)
612 board_group_find_extra_libs(board, group, gi, coord);
614 if (gi->libs == 1)
615 board_capturable_add(board, group);
616 else if (gi->libs == 0)
617 board_capturable_rm(board, group);
618 return;
621 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
622 * can call this multiple times per coord. */
623 check_libs_consistency(board, group);
624 return;
628 /* This is a low-level routine that doesn't maintain consistency
629 * of all the board data structures. */
630 static void
631 board_remove_stone(struct board *board, coord_t c)
633 enum stone color = board_at(board, c);
634 board_at(board, c) = S_NONE;
635 group_at(board, c) = 0;
636 board_hash_update(board, c, color);
638 /* Increase liberties of surrounding groups */
639 coord_t coord = c;
640 foreach_neighbor(board, coord, {
641 dec_neighbor_count_at(board, c, color);
642 group_t g = group_at(board, c);
643 if (g)
644 board_group_addlib(board, g, coord);
647 if (DEBUGL(6))
648 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
649 board->f[board->flen++] = coord_raw(c);
652 static int profiling_noinline
653 board_group_capture(struct board *board, group_t group)
655 int stones = 0;
657 foreach_in_group(board, group) {
658 board->captures[stone_other(board_at(board, c))]++;
659 board_remove_stone(board, c);
660 stones++;
661 } foreach_in_group_end;
663 if (board_group_info(board, group).libs == 1)
664 board_capturable_rm(board, group);
665 memset(&board_group_info(board, group), 0, sizeof(struct group));
667 return stones;
671 static void profiling_noinline
672 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
674 foreach_neighbor(board, coord, {
675 if (board_at(board, c) == S_NONE)
676 board_group_addlib(board, group, c);
679 group_at(board, coord) = group;
680 groupnext_at(board, coord) = groupnext_at(board, prevstone);
681 groupnext_at(board, prevstone) = coord_raw(coord);
683 if (DEBUGL(8))
684 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
685 coord_x(prevstone, board), coord_y(prevstone, board),
686 coord_x(coord, board), coord_y(coord, board),
687 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
688 group_base(group));
691 static void profiling_noinline
692 merge_groups(struct board *board, group_t group_to, group_t group_from)
694 if (DEBUGL(7))
695 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
696 group_base(group_from), group_base(group_to));
698 coord_t last_in_group;
699 foreach_in_group(board, group_from) {
700 last_in_group = c;
701 group_at(board, c) = group_to;
702 } foreach_in_group_end;
703 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
704 groupnext_at(board, group_base(group_to)) = group_base(group_from);
706 struct group *gi_from = &board_group_info(board, group_from);
707 struct group *gi_to = &board_group_info(board, group_to);
708 if (gi_to->libs < GROUP_KEEP_LIBS) {
709 for (int i = 0; i < gi_from->libs; i++) {
710 for (int j = 0; j < gi_to->libs; j++)
711 if (gi_to->lib[j] == gi_from->lib[i])
712 goto next_from_lib;
713 if (gi_to->libs == 0)
714 board_capturable_add(board, group_to);
715 else if (gi_to->libs == 1)
716 board_capturable_rm(board, group_to);
717 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
718 if (gi_to->libs >= GROUP_KEEP_LIBS)
719 break;
720 next_from_lib:;
724 if (gi_from->libs == 1)
725 board_capturable_rm(board, group_from);
726 memset(gi_from, 0, sizeof(struct group));
728 if (DEBUGL(7))
729 fprintf(stderr, "board_play_raw: merged group: %d\n",
730 group_base(group_to));
733 static group_t profiling_noinline
734 new_group(struct board *board, coord_t coord)
736 group_t group = coord_raw(coord);
737 struct group *gi = &board_group_info(board, group);
738 foreach_neighbor(board, coord, {
739 if (board_at(board, c) == S_NONE)
740 /* board_group_addlib is ridiculously expensive for us */
741 #if GROUP_KEEP_LIBS < 4
742 if (gi->libs < GROUP_KEEP_LIBS)
743 #endif
744 gi->lib[gi->libs++] = c;
746 if (gi->libs == 1)
747 board_capturable_add(board, group);
748 check_libs_consistency(board, group);
750 group_at(board, coord) = group;
751 groupnext_at(board, coord) = 0;
753 if (DEBUGL(8))
754 fprintf(stderr, "new_group: added %d,%d to group %d\n",
755 coord_x(coord, board), coord_y(coord, board),
756 group_base(group));
758 return group;
761 static inline group_t
762 play_one_neighbor(struct board *board,
763 coord_t coord, enum stone color, enum stone other_color,
764 coord_t c, group_t group)
766 enum stone ncolor = board_at(board, c);
767 group_t ngroup = group_at(board, c);
769 inc_neighbor_count_at(board, c, color);
771 if (!ngroup)
772 return group;
774 board_group_rmlib(board, ngroup, coord);
775 if (DEBUGL(7))
776 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
777 group_base(ngroup), ncolor, color, other_color);
779 if (ncolor == color && ngroup != group) {
780 if (!group) {
781 group = ngroup;
782 add_to_group(board, group, c, coord);
783 } else {
784 merge_groups(board, group, ngroup);
786 } else if (ncolor == other_color) {
787 if (DEBUGL(8)) {
788 struct group *gi = &board_group_info(board, ngroup);
789 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
790 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
791 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
792 fprintf(stderr, "\n");
794 if (unlikely(board_group_captured(board, ngroup)))
795 board_group_capture(board, ngroup);
797 return group;
800 /* We played on a place with at least one liberty. We will become a member of
801 * some group for sure. */
802 static group_t profiling_noinline
803 board_play_outside(struct board *board, struct move *m, int f)
805 coord_t coord = m->coord;
806 enum stone color = m->color;
807 enum stone other_color = stone_other(color);
808 group_t group = 0;
810 board->f[f] = board->f[--board->flen];
811 if (DEBUGL(6))
812 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
814 foreach_neighbor(board, coord, {
815 group = play_one_neighbor(board, coord, color, other_color, c, group);
818 if (unlikely(!group))
819 group = new_group(board, coord);
821 board_at(board, coord) = color;
822 board->last_move2 = board->last_move;
823 board->last_move = *m;
824 board->moves++;
825 board_hash_update(board, coord, color);
826 board_symmetry_update(board, &board->symmetry, coord);
827 struct move ko = { pass, S_NONE };
828 board->ko = ko;
830 return group;
833 /* We played in an eye-like shape. Either we capture at least one of the eye
834 * sides in the process of playing, or return -1. */
835 static int profiling_noinline
836 board_play_in_eye(struct board *board, struct move *m, int f)
838 coord_t coord = m->coord;
839 enum stone color = m->color;
840 /* Check ko: Capture at a position of ko capture one move ago */
841 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
842 if (DEBUGL(5))
843 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
844 return -1;
845 } else if (DEBUGL(6)) {
846 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
847 color, coord_x(coord, board), coord_y(coord, board),
848 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
851 struct move ko = { pass, S_NONE };
853 int captured_groups = 0;
855 foreach_neighbor(board, coord, {
856 group_t g = group_at(board, c);
857 if (DEBUGL(7))
858 fprintf(stderr, "board_check: group %d has %d libs\n",
859 g, board_group_info(board, g).libs);
860 captured_groups += (board_group_info(board, g).libs == 1);
863 if (likely(captured_groups == 0)) {
864 if (DEBUGL(5)) {
865 if (DEBUGL(6))
866 board_print(board, stderr);
867 fprintf(stderr, "board_check: one-stone suicide\n");
870 return -1;
873 board->f[f] = board->f[--board->flen];
874 if (DEBUGL(6))
875 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
877 foreach_neighbor(board, coord, {
878 inc_neighbor_count_at(board, c, color);
880 group_t group = group_at(board, c);
881 if (!group)
882 continue;
884 board_group_rmlib(board, group, coord);
885 if (DEBUGL(7))
886 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
887 group_base(group));
889 if (board_group_captured(board, group)) {
890 if (board_group_capture(board, group) == 1) {
891 /* If we captured multiple groups at once,
892 * we can't be fighting ko so we don't need
893 * to check for that. */
894 ko.color = stone_other(color);
895 ko.coord = c;
896 board->last_ko = ko;
897 board->last_ko_age = board->moves;
898 if (DEBUGL(5))
899 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
904 board_at(board, coord) = color;
906 board->last_move2 = board->last_move;
907 board->last_move = *m;
908 board->moves++;
909 board_hash_update(board, coord, color);
910 board_hash_commit(board);
911 board_symmetry_update(board, &board->symmetry, coord);
912 board->ko = ko;
914 return !!new_group(board, coord);
917 static int __attribute__((flatten))
918 board_play_f(struct board *board, struct move *m, int f)
920 if (DEBUGL(7)) {
921 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
923 if (likely(!board_is_eyelike(board, &m->coord, stone_other(m->color)))) {
924 /* NOT playing in an eye. Thus this move has to succeed. (This
925 * is thanks to New Zealand rules. Otherwise, multi-stone
926 * suicide might fail.) */
927 group_t group = board_play_outside(board, m, f);
928 if (unlikely(board_group_captured(board, group))) {
929 board_group_capture(board, group);
931 board_hash_commit(board);
932 return 0;
933 } else {
934 return board_play_in_eye(board, m, f);
939 board_play(struct board *board, struct move *m)
941 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
942 board->last_move2 = board->last_move;
943 board->last_move = *m;
944 return 0;
947 int f;
948 for (f = 0; f < board->flen; f++)
949 if (board->f[f] == coord_raw(m->coord))
950 return board_play_f(board, m, f);
952 if (DEBUGL(7))
953 fprintf(stderr, "board_check: stone exists\n");
954 return -1;
958 static inline bool
959 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
961 coord_raw(*coord) = b->f[f];
962 if (unlikely(is_pass(*coord)))
963 return random_pass;
964 struct move m = { *coord, color };
965 if (DEBUGL(6))
966 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
967 return (likely(!board_is_one_point_eye(b, coord, color)) /* bad idea to play into one, usually */
968 && board_is_valid_move(b, &m)
969 && (!permit || permit(permit_data, b, &m))
970 && likely(board_play_f(b, &m, f) >= 0));
973 void
974 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
976 int base = fast_random(b->flen);
977 coord_pos(*coord, base, b);
978 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
979 return;
981 int f;
982 for (f = base + 1; f < b->flen; f++)
983 if (board_try_random_move(b, color, coord, f, permit, permit_data))
984 return;
985 for (f = 0; f < base; f++)
986 if (board_try_random_move(b, color, coord, f, permit, permit_data))
987 return;
989 *coord = pass;
993 bool
994 board_is_false_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
996 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
998 /* XXX: We attempt false eye detection but we will yield false
999 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1001 foreach_diag_neighbor(board, *coord) {
1002 color_diag_libs[(enum stone) board_at(board, c)]++;
1003 } foreach_diag_neighbor_end;
1004 /* For false eye, we need two enemy stones diagonally in the
1005 * middle of the board, or just one enemy stone at the edge
1006 * or in the corner. */
1007 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1008 return color_diag_libs[stone_other(eye_color)] >= 2;
1011 bool
1012 board_is_one_point_eye(struct board *board, coord_t *coord, enum stone eye_color)
1014 return board_is_eyelike(board, coord, eye_color)
1015 && !board_is_false_eyelike(board, coord, eye_color);
1018 enum stone
1019 board_get_one_point_eye(struct board *board, coord_t *coord)
1021 if (board_is_one_point_eye(board, coord, S_WHITE))
1022 return S_WHITE;
1023 else if (board_is_one_point_eye(board, coord, S_BLACK))
1024 return S_BLACK;
1025 else
1026 return S_NONE;
1030 float
1031 board_fast_score(struct board *board)
1033 int scores[S_MAX];
1034 memset(scores, 0, sizeof(scores));
1036 foreach_point(board) {
1037 enum stone color = board_at(board, c);
1038 if (color == S_NONE)
1039 color = board_get_one_point_eye(board, &c);
1040 scores[color]++;
1041 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1042 } foreach_point_end;
1044 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1047 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1049 /* One flood-fill iteration; returns true if next iteration
1050 * is required. */
1051 static bool
1052 board_tromp_taylor_iter(struct board *board, int *ownermap)
1054 bool needs_update = false;
1055 foreach_point(board) {
1056 /* Ignore occupied and already-dame positions. */
1057 if (board_at(board, c) != S_NONE || ownermap[c] == 3)
1058 continue;
1059 /* Count neighbors. */
1060 int nei[4] = {0};
1061 foreach_neighbor(board, c, {
1062 nei[ownermap[c]]++;
1064 /* If we have neighbors of both colors, or dame,
1065 * we are dame too. */
1066 if ((nei[1] && nei[2]) || nei[3]) {
1067 ownermap[c] = 3;
1068 /* Speed up the propagation. */
1069 foreach_neighbor(board, c, {
1070 if (board_at(board, c) == S_NONE)
1071 ownermap[c] = 3;
1073 needs_update = true;
1074 continue;
1076 /* If we have neighbors of one color, we are owned
1077 * by that color, too. */
1078 if (!ownermap[c] && (nei[1] || nei[2])) {
1079 int newowner = nei[1] ? 1 : 2;
1080 ownermap[c] = newowner;
1081 /* Speed up the propagation. */
1082 foreach_neighbor(board, c, {
1083 if (board_at(board, c) == S_NONE && !ownermap[c])
1084 ownermap[c] = newowner;
1086 needs_update = true;
1087 continue;
1089 } foreach_point_end;
1090 return needs_update;
1093 /* Tromp-Taylor Counting */
1094 float
1095 board_official_score(struct board *board, struct move_queue *q)
1098 /* A point P, not colored C, is said to reach C, if there is a path of
1099 * (vertically or horizontally) adjacent points of P's color from P to
1100 * a point of color C.
1102 * A player's score is the number of points of her color, plus the
1103 * number of empty points that reach only her color. */
1105 int ownermap[board_size2(board)];
1106 int s[4] = {0};
1107 const int o[4] = {0, 1, 2, 0};
1108 foreach_point(board) {
1109 ownermap[c] = o[board_at(board, c)];
1110 s[board_at(board, c)]++;
1111 } foreach_point_end;
1113 if (q) {
1114 /* Process dead groups. */
1115 for (int i = 0; i < q->moves; i++) {
1116 foreach_in_group(board, q->move[i]) {
1117 enum stone color = board_at(board, c);
1118 ownermap[c] = o[stone_other(color)];
1119 s[color]--; s[stone_other(color)]++;
1120 } foreach_in_group_end;
1124 /* We need to special-case empty board. */
1125 if (!s[S_BLACK] && !s[S_WHITE])
1126 return board->komi + board->handicap;
1128 while (board_tromp_taylor_iter(board, ownermap))
1129 /* Flood-fill... */;
1131 int scores[S_MAX];
1132 memset(scores, 0, sizeof(scores));
1134 foreach_point(board) {
1135 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1136 if (ownermap[c] == 3)
1137 continue;
1138 scores[ownermap[c]]++;
1139 } foreach_point_end;
1141 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];