UCT: Pass right away if it brings us to counting stage that we win
[pachi.git] / board.c
blobe1aa742da8aa6475d2f6791e7ffb1ec93b37fb39
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 "random.h"
11 int board_group_capture(struct board *board, group_t group);
13 bool random_pass = false;
16 #if 0
17 #define profiling_noinline __attribute__((noinline))
18 #else
19 #define profiling_noinline
20 #endif
22 #define gi_granularity 4
23 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
26 static void
27 board_setup(struct board *b)
29 memset(b, 0, sizeof(*b));
31 struct move m = { pass, S_NONE };
32 b->last_move = b->ko = m;
35 struct board *
36 board_init(void)
38 struct board *b = malloc(sizeof(struct board));
39 board_setup(b);
40 return b;
43 struct board *
44 board_copy(struct board *b2, struct board *b1)
46 memcpy(b2, b1, sizeof(struct board));
48 int bsize = board_size2(b2) * sizeof(*b2->b);
49 int gsize = board_size2(b2) * sizeof(*b2->g);
50 int fsize = board_size2(b2) * sizeof(*b2->f);
51 int nsize = board_size2(b2) * sizeof(*b2->n);
52 int psize = board_size2(b2) * sizeof(*b2->p);
53 int hsize = board_size2(b2) * 2 * sizeof(*b2->h);
54 int gisize = board_size2(b2) * sizeof(*b2->gi);
55 #ifdef WANT_BOARD_C
56 int csize = board_size2(b2) * sizeof(*b2->c);
57 #else
58 int csize = 0;
59 #endif
60 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
61 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
62 b2->b = x; x += bsize;
63 b2->g = x; x += gsize;
64 b2->f = x; x += fsize;
65 b2->p = x; x += psize;
66 b2->n = x; x += nsize;
67 b2->h = x; x += hsize;
68 b2->gi = x; x += gisize;
69 #ifdef WANT_BOARD_C
70 b2->c = x; x += csize;
71 #endif
73 return b2;
76 void
77 board_done_noalloc(struct board *board)
79 if (board->b) free(board->b);
82 void
83 board_done(struct board *board)
85 board_done_noalloc(board);
86 free(board);
89 void
90 board_resize(struct board *board, int size)
92 #ifdef BOARD_SIZE
93 assert(board_size(board) == size + 2);
94 #else
95 board_size(board) = size + 2 /* S_OFFBOARD margin */;
96 board_size2(board) = board_size(board) * board_size(board);
97 #endif
98 if (board->b)
99 free(board->b);
101 int bsize = board_size2(board) * sizeof(*board->b);
102 int gsize = board_size2(board) * sizeof(*board->g);
103 int fsize = board_size2(board) * sizeof(*board->f);
104 int nsize = board_size2(board) * sizeof(*board->n);
105 int psize = board_size2(board) * sizeof(*board->p);
106 int hsize = board_size2(board) * 2 * sizeof(*board->h);
107 int gisize = board_size2(board) * sizeof(*board->gi);
108 #ifdef WANT_BOARD_C
109 int csize = board_size2(board) * sizeof(*board->c);
110 #else
111 int csize = 0;
112 #endif
113 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
114 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
115 board->b = x; x += bsize;
116 board->g = x; x += gsize;
117 board->f = x; x += fsize;
118 board->p = x; x += psize;
119 board->n = x; x += nsize;
120 board->h = x; x += hsize;
121 board->gi = x; x += gisize;
122 #ifdef WANT_BOARD_C
123 board->c = x; x += csize;
124 #endif
127 void
128 board_clear(struct board *board)
130 int size = board_size(board);
132 board_done_noalloc(board);
133 board_setup(board);
134 board_resize(board, size - 2 /* S_OFFBOARD margin */);
136 /* Setup initial symmetry */
137 board->symmetry.d = 1;
138 board->symmetry.x1 = board->symmetry.y1 = board->size / 2;
139 board->symmetry.x2 = board->symmetry.y2 = board->size - 1;
140 board->symmetry.type = SYM_FULL;
142 /* Draw the offboard margin */
143 int top_row = board_size2(board) - board_size(board);
144 int i;
145 for (i = 0; i < board_size(board); i++)
146 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
147 for (i = 0; i <= top_row; i += board_size(board))
148 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
150 foreach_point(board) {
151 coord_t coord = c;
152 if (board_at(board, coord) == S_OFFBOARD)
153 continue;
154 foreach_neighbor(board, c, {
155 inc_neighbor_count_at(board, coord, board_at(board, c));
156 } );
157 } foreach_point_end;
159 /* First, pass is always a free position. */
160 board->f[board->flen++] = coord_raw(pass);
161 /* All positions are free! Except the margin. */
162 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
163 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
164 board->f[board->flen++] = i;
166 /* Initialize zobrist hashtable. */
167 foreach_point(board) {
168 int max = (sizeof(hash_t) << history_hash_bits);
169 /* fast_random() is 16-bit only */
170 board->h[coord_raw(c) * 2] = ((hash_t) fast_random(max))
171 | ((hash_t) fast_random(max) << 16)
172 | ((hash_t) fast_random(max) << 32)
173 | ((hash_t) fast_random(max) << 48);
174 if (!board->h[coord_raw(c) * 2])
175 /* Would be kinda "oops". */
176 board->h[coord_raw(c) * 2] = 1;
177 /* And once again for white */
178 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
179 | ((hash_t) fast_random(max) << 16)
180 | ((hash_t) fast_random(max) << 32)
181 | ((hash_t) fast_random(max) << 48);
182 if (!board->h[coord_raw(c) * 2 + 1])
183 board->h[coord_raw(c) * 2 + 1] = 1;
184 } foreach_point_end;
188 void
189 board_print(struct board *board, FILE *f)
191 fprintf(f, "Move: % 3d Komi: %2.1f Captures B: %d W: %d\n ",
192 board->moves, board->komi,
193 board->captures[S_BLACK], board->captures[S_WHITE]);
194 int x, y;
195 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
196 for (x = 1; x < board_size(board) - 1; x++)
197 fprintf(f, "%c ", asdf[x - 1]);
198 fprintf(f, "\n +-");
199 for (x = 1; x < board_size(board) - 1; x++)
200 fprintf(f, "--");
201 fprintf(f, "+\n");
202 for (y = board_size(board) - 2; y >= 1; y--) {
203 fprintf(f, "%2d | ", y);
204 for (x = 1; x < board_size(board) - 1; x++) {
205 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
206 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
207 else
208 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
210 if (DEBUGL(6)) {
211 fprintf(f, "| ");
212 for (x = 1; x < board_size(board) - 1; x++) {
213 fprintf(f, "%d ", group_base(group_atxy(board, x, y)));
216 fprintf(f, "|\n");
218 fprintf(f, " +-");
219 for (x = 1; x < board_size(board) - 1; x++)
220 fprintf(f, "--");
221 fprintf(f, "+\n\n");
225 /* Update board hash with given coordinate. */
226 static void profiling_noinline
227 board_hash_update(struct board *board, coord_t coord, enum stone color)
229 board->hash ^= hash_at(board, coord, color);
230 if (DEBUGL(8))
231 fprintf(stderr, "board_hash_update(%d,%d,%d) ^ %llx -> %llx\n", color, coord_x(coord, board), coord_y(coord, board), hash_at(board, coord, color), board->hash);
234 /* Commit current board hash to history. */
235 static void profiling_noinline
236 board_hash_commit(struct board *board)
238 if (DEBUGL(8))
239 fprintf(stderr, "board_hash_commit %llx\n", board->hash);
240 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
241 board->history_hash[board->hash & history_hash_mask] = board->hash;
242 } else {
243 hash_t i = board->hash;
244 while (board->history_hash[i & history_hash_mask]) {
245 if (board->history_hash[i & history_hash_mask] == board->hash) {
246 if (DEBUGL(5))
247 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
248 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
249 board->superko_violation = true;
250 return;
252 i = history_hash_next(i);
254 board->history_hash[i & history_hash_mask] = board->hash;
259 void
260 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
262 if (likely(symmetry->type == SYM_NONE)) {
263 /* Fully degenerated already. We do not support detection
264 * of restoring of symmetry, assuming that this is too rare
265 * a case to handle. */
266 return;
269 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
270 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
271 if (DEBUGL(6)) {
272 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
273 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
274 symmetry->d, symmetry->type, x, y);
277 switch (symmetry->type) {
278 case SYM_FULL:
279 if (x == t && y == t) {
280 /* Tengen keeps full symmetry. */
281 return;
283 /* New symmetry now? */
284 if (x == y) {
285 symmetry->type = SYM_DIAG_UP;
286 symmetry->x1 = symmetry->y1 = 1;
287 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
288 symmetry->d = 1;
289 } else if (dx == y) {
290 symmetry->type = SYM_DIAG_DOWN;
291 symmetry->x1 = symmetry->y1 = 1;
292 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
293 symmetry->d = 1;
294 } else if (x == t) {
295 symmetry->type = SYM_HORIZ;
296 symmetry->y1 = 1;
297 symmetry->y2 = board_size(b) - 1;
298 symmetry->d = 0;
299 } else if (y == t) {
300 symmetry->type = SYM_VERT;
301 symmetry->x1 = 1;
302 symmetry->x2 = board_size(b) - 1;
303 symmetry->d = 0;
304 } else {
305 break_symmetry:
306 symmetry->type = SYM_NONE;
307 symmetry->x1 = symmetry->y1 = 1;
308 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
309 symmetry->d = 0;
311 break;
312 case SYM_DIAG_UP:
313 if (x == y)
314 return;
315 goto break_symmetry;
316 case SYM_DIAG_DOWN:
317 if (dx == y)
318 return;
319 goto break_symmetry;
320 case SYM_HORIZ:
321 if (x == t)
322 return;
323 goto break_symmetry;
324 case SYM_VERT:
325 if (y == t)
326 return;
327 goto break_symmetry;
328 case SYM_NONE:
329 assert(0);
330 break;
333 if (DEBUGL(6)) {
334 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
335 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
336 symmetry->d, symmetry->type);
338 /* Whew. */
342 void
343 board_handicap_stone(struct board *board, int x, int y, FILE *f)
345 struct move m;
346 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
348 board_play(board, &m);
349 /* Simulate white passing; otherwise, UCT search can get confused since
350 * tree depth parity won't match the color to move. */
351 board->moves++;
353 char *str = coord2str(m.coord, board);
354 if (DEBUGL(1))
355 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
356 fprintf(f, "%s ", str);
357 free(str);
360 void
361 board_handicap(struct board *board, int stones, FILE *f)
363 int margin = 3 + (board_size(board) >= 13);
364 int min = margin;
365 int mid = board_size(board) / 2;
366 int max = board_size(board) - 1 - margin;
367 const int places[][2] = {
368 { min, min }, { max, max }, { max, min }, { min, max },
369 { min, mid }, { max, mid },
370 { mid, min }, { mid, max },
371 { mid, mid },
374 board->handicap = stones;
376 if (stones == 5 || stones == 7) {
377 board_handicap_stone(board, mid, mid, f);
378 stones--;
381 int i;
382 for (i = 0; i < stones; i++)
383 board_handicap_stone(board, places[i][0], places[i][1], f);
387 static void __attribute__((noinline))
388 check_libs_consistency(struct board *board, group_t g)
390 #ifdef DEBUG
391 if (!g) return;
392 struct group *gi = &board_group_info(board, g);
393 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
394 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
395 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
396 assert(0);
398 #endif
401 static void
402 board_capturable_add(struct board *board, group_t group)
404 #ifdef WANT_BOARD_C
405 //fprintf(stderr, "add of group %d (%d)\n", group_base(group), board->clen);
406 assert(group);
407 assert(board->clen < board_size2(board));
408 board->c[board->clen++] = group;
409 #endif
411 static void
412 board_capturable_rm(struct board *board, group_t group)
414 #ifdef WANT_BOARD_C
415 //fprintf(stderr, "rm of group %d\n", group_base(group));
416 for (int i = 0; i < board->clen; i++) {
417 if (unlikely(board->c[i] == group)) {
418 board->c[i] = board->c[--board->clen];
419 return;
422 fprintf(stderr, "rm of bad group %d\n", group_base(group));
423 assert(0);
424 #endif
427 static void
428 board_group_addlib(struct board *board, group_t group, coord_t coord)
430 if (DEBUGL(7)) {
431 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
432 group_base(group), coord2sstr(group_base(group), board),
433 board_group_info(board, group).libs, coord2sstr(coord, board));
436 check_libs_consistency(board, group);
438 struct group *gi = &board_group_info(board, group);
439 if (gi->libs < GROUP_KEEP_LIBS) {
440 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
441 #if 0
442 /* Seems extra branch just slows it down */
443 if (!gi->lib[i])
444 break;
445 #endif
446 if (unlikely(gi->lib[i] == coord))
447 return;
449 if (gi->libs == 0)
450 board_capturable_add(board, group);
451 else if (gi->libs == 1)
452 board_capturable_rm(board, group);
453 gi->lib[gi->libs++] = coord;
456 check_libs_consistency(board, group);
459 static void
460 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
462 /* Add extra liberty from the board to our liberty list. */
463 enum stone watermark[board_size2(board)];
464 memcpy(watermark, board->b, sizeof(watermark));
466 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
467 watermark[coord_raw(gi->lib[i])] = S_OFFBOARD;
468 watermark[coord_raw(avoid)] = S_OFFBOARD;
470 foreach_in_group(board, group) {
471 coord_t coord2 = c;
472 foreach_neighbor(board, coord2, {
473 if (likely(watermark[coord_raw(c)] != S_NONE))
474 continue;
475 watermark[coord_raw(c)] = S_OFFBOARD;
476 gi->lib[gi->libs++] = c;
477 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
478 return;
479 } );
480 } foreach_in_group_end;
483 static void
484 board_group_rmlib(struct board *board, group_t group, coord_t coord)
486 if (DEBUGL(7)) {
487 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
488 group_base(group), coord2sstr(group_base(group), board),
489 board_group_info(board, group).libs, coord2sstr(coord, board));
492 struct group *gi = &board_group_info(board, group);
493 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
494 #if 0
495 /* Seems extra branch just slows it down */
496 if (!gi->lib[i])
497 break;
498 #endif
499 if (likely(gi->lib[i] != coord))
500 continue;
502 gi->lib[i] = gi->lib[--gi->libs];
503 gi->lib[gi->libs] = 0;
505 check_libs_consistency(board, group);
507 /* Postpone refilling lib[] until we need to. */
508 assert(GROUP_REFILL_LIBS > 1);
509 if (gi->libs > GROUP_REFILL_LIBS)
510 return;
511 if (gi->libs == GROUP_REFILL_LIBS)
512 board_group_find_extra_libs(board, group, gi, coord);
514 if (gi->libs == 1)
515 board_capturable_add(board, group);
516 else if (gi->libs == 0)
517 board_capturable_rm(board, group);
518 return;
521 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
522 * can call this multiple times per coord. */
523 check_libs_consistency(board, group);
524 return;
528 /* This is a low-level routine that doesn't maintain consistency
529 * of all the board data structures. Use board_group_capture() from
530 * your code. */
531 static void
532 board_remove_stone(struct board *board, coord_t c)
534 enum stone color = board_at(board, c);
535 board_at(board, c) = S_NONE;
536 group_at(board, c) = 0;
537 board_hash_update(board, c, color);
539 /* Increase liberties of surrounding groups */
540 coord_t coord = c;
541 foreach_neighbor(board, coord, {
542 dec_neighbor_count_at(board, c, color);
543 group_t g = group_at(board, c);
544 if (g)
545 board_group_addlib(board, g, coord);
548 if (DEBUGL(6))
549 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
550 board->f[board->flen++] = coord_raw(c);
554 static void profiling_noinline
555 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
557 foreach_neighbor(board, coord, {
558 if (board_at(board, c) == S_NONE)
559 board_group_addlib(board, group, c);
562 group_at(board, coord) = group;
563 groupnext_at(board, coord) = groupnext_at(board, prevstone);
564 groupnext_at(board, prevstone) = coord_raw(coord);
566 if (DEBUGL(8))
567 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
568 coord_x(prevstone, board), coord_y(prevstone, board),
569 coord_x(coord, board), coord_y(coord, board),
570 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
571 group_base(group));
574 static void profiling_noinline
575 merge_groups(struct board *board, group_t group_to, group_t group_from)
577 if (DEBUGL(7))
578 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
579 group_base(group_from), group_base(group_to));
581 coord_t last_in_group;
582 foreach_in_group(board, group_from) {
583 last_in_group = c;
584 group_at(board, c) = group_to;
585 } foreach_in_group_end;
586 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
587 groupnext_at(board, group_base(group_to)) = group_base(group_from);
589 struct group *gi_from = &board_group_info(board, group_from);
590 struct group *gi_to = &board_group_info(board, group_to);
591 if (gi_to->libs < GROUP_KEEP_LIBS) {
592 for (int i = 0; i < gi_from->libs; i++) {
593 for (int j = 0; j < gi_to->libs; j++)
594 if (gi_to->lib[j] == gi_from->lib[i])
595 goto next_from_lib;
596 if (gi_to->libs == 0)
597 board_capturable_add(board, group_to);
598 else if (gi_to->libs == 1)
599 board_capturable_rm(board, group_to);
600 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
601 if (gi_to->libs >= GROUP_KEEP_LIBS)
602 break;
603 next_from_lib:;
607 if (gi_from->libs == 1)
608 board_capturable_rm(board, group_from);
609 memset(gi_from, 0, sizeof(struct group));
611 if (DEBUGL(7))
612 fprintf(stderr, "board_play_raw: merged group: %d\n",
613 group_base(group_to));
616 static group_t profiling_noinline
617 new_group(struct board *board, coord_t coord)
619 group_t group = coord_raw(coord);
620 struct group *gi = &board_group_info(board, group);
621 foreach_neighbor(board, coord, {
622 if (board_at(board, c) == S_NONE)
623 /* board_group_addlib is ridiculously expensive for us */
624 #if GROUP_KEEP_LIBS < 4
625 if (gi->libs < GROUP_KEEP_LIBS)
626 #endif
627 gi->lib[gi->libs++] = c;
629 if (gi->libs == 1)
630 board_capturable_add(board, group);
631 check_libs_consistency(board, group);
633 group_at(board, coord) = group;
634 groupnext_at(board, coord) = 0;
636 if (DEBUGL(8))
637 fprintf(stderr, "new_group: added %d,%d to group %d\n",
638 coord_x(coord, board), coord_y(coord, board),
639 group_base(group));
641 return group;
644 static inline group_t
645 play_one_neighbor(struct board *board,
646 coord_t coord, enum stone color, enum stone other_color,
647 coord_t c, group_t group)
649 enum stone ncolor = board_at(board, c);
650 group_t ngroup = group_at(board, c);
652 inc_neighbor_count_at(board, c, color);
654 if (!ngroup)
655 return group;
657 board_group_rmlib(board, ngroup, coord);
658 if (DEBUGL(7))
659 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
660 group_base(ngroup), ncolor, color, other_color);
662 if (ncolor == color && ngroup != group) {
663 if (!group) {
664 group = ngroup;
665 add_to_group(board, group, c, coord);
666 } else {
667 merge_groups(board, group, ngroup);
669 } else if (ncolor == other_color) {
670 if (DEBUGL(8)) {
671 struct group *gi = &board_group_info(board, ngroup);
672 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
673 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
674 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
675 fprintf(stderr, "\n");
677 if (unlikely(board_group_captured(board, ngroup)))
678 board_group_capture(board, ngroup);
680 return group;
683 /* We played on a place with at least one liberty. We will become a member of
684 * some group for sure. */
685 static group_t profiling_noinline
686 board_play_outside(struct board *board, struct move *m, int f)
688 coord_t coord = m->coord;
689 enum stone color = m->color;
690 enum stone other_color = stone_other(color);
691 group_t group = 0;
693 board->f[f] = board->f[--board->flen];
694 if (DEBUGL(6))
695 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
697 foreach_neighbor(board, coord, {
698 group = play_one_neighbor(board, coord, color, other_color, c, group);
701 if (unlikely(!group))
702 group = new_group(board, coord);
704 board_at(board, coord) = color;
705 board->last_move = *m;
706 board->moves++;
707 board_hash_update(board, coord, color);
708 board_symmetry_update(board, &board->symmetry, coord);
709 struct move ko = { pass, S_NONE };
710 board->ko = ko;
712 return group;
715 /* We played in an eye-like shape. Either we capture at least one of the eye
716 * sides in the process of playing, or return -1. */
717 static int profiling_noinline
718 board_play_in_eye(struct board *board, struct move *m, int f)
720 coord_t coord = m->coord;
721 enum stone color = m->color;
722 /* Check ko: Capture at a position of ko capture one move ago */
723 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
724 if (DEBUGL(5))
725 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
726 return -1;
727 } else if (DEBUGL(6)) {
728 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
729 color, coord_x(coord, board), coord_y(coord, board),
730 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
733 struct move ko = { pass, S_NONE };
735 int captured_groups = 0;
737 foreach_neighbor(board, coord, {
738 group_t g = group_at(board, c);
739 if (DEBUGL(7))
740 fprintf(stderr, "board_check: group %d has %d libs\n",
741 g, board_group_info(board, g).libs);
742 captured_groups += (board_group_info(board, g).libs == 1);
745 if (likely(captured_groups == 0)) {
746 if (DEBUGL(5)) {
747 if (DEBUGL(6))
748 board_print(board, stderr);
749 fprintf(stderr, "board_check: one-stone suicide\n");
752 return -1;
755 board->f[f] = board->f[--board->flen];
756 if (DEBUGL(6))
757 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
759 foreach_neighbor(board, coord, {
760 inc_neighbor_count_at(board, c, color);
762 group_t group = group_at(board, c);
763 if (!group)
764 continue;
766 board_group_rmlib(board, group, coord);
767 if (DEBUGL(7))
768 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
769 group_base(group));
771 if (board_group_captured(board, group)) {
772 if (board_group_capture(board, group) == 1) {
773 /* If we captured multiple groups at once,
774 * we can't be fighting ko so we don't need
775 * to check for that. */
776 ko.color = stone_other(color);
777 ko.coord = c;
778 if (DEBUGL(5))
779 fprintf(stderr, "guarding ko at %d,%d,%d\n", ko.color, coord_x(ko.coord, board), coord_y(ko.coord, board));
784 board_at(board, coord) = color;
786 board->last_move = *m;
787 board->moves++;
788 board_hash_update(board, coord, color);
789 board_hash_commit(board);
790 board_symmetry_update(board, &board->symmetry, coord);
791 board->ko = ko;
793 return !!new_group(board, coord);
796 static int __attribute__((flatten))
797 board_play_f(struct board *board, struct move *m, int f)
799 if (DEBUGL(7)) {
800 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
802 if (likely(!board_is_eyelike(board, &m->coord, stone_other(m->color)))) {
803 /* NOT playing in an eye. Thus this move has to succeed. (This
804 * is thanks to New Zealand rules. Otherwise, multi-stone
805 * suicide might fail.) */
806 group_t group = board_play_outside(board, m, f);
807 if (unlikely(board_group_captured(board, group))) {
808 board_group_capture(board, group);
810 board_hash_commit(board);
811 return 0;
812 } else {
813 return board_play_in_eye(board, m, f);
818 board_play(struct board *board, struct move *m)
820 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
821 board->last_move = *m;
822 return 0;
825 int f;
826 for (f = 0; f < board->flen; f++)
827 if (board->f[f] == coord_raw(m->coord))
828 return board_play_f(board, m, f);
830 if (DEBUGL(7))
831 fprintf(stderr, "board_check: stone exists\n");
832 return -1;
836 static inline bool
837 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
839 coord_raw(*coord) = b->f[f];
840 if (unlikely(is_pass(*coord)))
841 return random_pass;
842 struct move m = { *coord, color };
843 if (DEBUGL(6))
844 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
845 return (likely(!board_is_one_point_eye(b, coord, color)) /* bad idea to play into one, usually */
846 && (!permit || permit(permit_data, b, &m))
847 && likely(board_play_f(b, &m, f) >= 0));
850 void
851 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
853 int base = fast_random(b->flen);
854 coord_pos(*coord, base, b);
855 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
856 return;
858 int f;
859 for (f = base + 1; f < b->flen; f++)
860 if (board_try_random_move(b, color, coord, f, permit, permit_data))
861 return;
862 for (f = 0; f < base; f++)
863 if (board_try_random_move(b, color, coord, f, permit, permit_data))
864 return;
866 *coord = pass;
870 bool
871 board_is_valid_move(struct board *board, struct move *m)
873 if (board_at(board, m->coord) != S_NONE)
874 return false;
875 if (!board_is_eyelike(board, &m->coord, stone_other(m->color)))
876 return true;
877 /* Play within {true,false} eye-ish formation */
878 if (board->ko.coord == m->coord && board->ko.color == m->coord)
879 return false;
880 int groups_in_atari = 0;
881 foreach_neighbor(board, m->coord, {
882 group_t g = group_at(board, c);
883 groups_in_atari += (board_group_info(board, g).libs == 1);
885 return !!groups_in_atari;
889 bool
890 board_is_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
892 return (neighbor_count_at(board, *coord, eye_color)
893 + neighbor_count_at(board, *coord, S_OFFBOARD)) == 4;
896 bool
897 board_is_false_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
899 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
901 /* XXX: We attempt false eye detection but we will yield false
902 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
904 foreach_diag_neighbor(board, *coord) {
905 color_diag_libs[(enum stone) board_at(board, c)]++;
906 } foreach_diag_neighbor_end;
907 /* For false eye, we need two enemy stones diagonally in the
908 * middle of the board, or just one enemy stone at the edge
909 * or in the corner. */
910 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
911 return color_diag_libs[stone_other(eye_color)] >= 2;
914 bool
915 board_is_one_point_eye(struct board *board, coord_t *coord, enum stone eye_color)
917 return board_is_eyelike(board, coord, eye_color)
918 && !board_is_false_eyelike(board, coord, eye_color);
921 enum stone
922 board_get_one_point_eye(struct board *board, coord_t *coord)
924 if (board_is_one_point_eye(board, coord, S_WHITE))
925 return S_WHITE;
926 else if (board_is_one_point_eye(board, coord, S_BLACK))
927 return S_BLACK;
928 else
929 return S_NONE;
933 int profiling_noinline
934 board_group_capture(struct board *board, group_t group)
936 int stones = 0;
938 foreach_in_group(board, group) {
939 board->captures[stone_other(board_at(board, c))]++;
940 board_remove_stone(board, c);
941 stones++;
942 } foreach_in_group_end;
944 if (board_group_info(board, group).libs == 1)
945 board_capturable_rm(board, group);
946 memset(&board_group_info(board, group), 0, sizeof(struct group));
948 return stones;
951 bool
952 board_group_in_atari(struct board *board, group_t group, coord_t *lastlib)
954 if (board_group_info(board, group).libs != 1)
955 return false;
956 *lastlib = board_group_info(board, group).lib[0];
957 return true;
960 bool
961 board_group_can_atari(struct board *board, group_t group, coord_t lastlib[2])
963 if (board_group_info(board, group).libs != 2)
964 return false;
965 lastlib[0] = board_group_info(board, group).lib[0];
966 lastlib[1] = board_group_info(board, group).lib[1];
967 return true;
971 static enum stone
972 board_tromp_taylor_owner(struct board *board, coord_t c)
974 int x = coord_x(c, board), y = coord_y(c, board);
975 enum stone color = S_NONE;
976 #define TEST_REACH(xx, yy) \
978 enum stone c2 = board_atxy(board, xx, yy); \
979 if (c2 != S_NONE) { \
980 if (color != S_NONE && color != c2) \
981 return S_NONE; \
982 color = c2; \
983 break; \
986 for (int i = x; i > 0; i--)
987 TEST_REACH(i, y);
988 for (int i = x; i < board_size(board) - 1; i++)
989 TEST_REACH(i, y);
990 for (int i = y; i > 0; i--)
991 TEST_REACH(x, i);
992 for (int i = y; i < board_size(board) - 1; i++)
993 TEST_REACH(x, i);
994 return color;
997 /* Tromp-Taylor Counting */
998 float
999 board_official_score(struct board *board)
1002 /* A point P, not colored C, is said to reach C, if there is a path of
1003 * (vertically or horizontally) adjacent points of P's color from P to
1004 * a point of color C.
1006 * A player's score is the number of points of her color, plus the
1007 * number of empty points that reach only her color. */
1009 int scores[S_MAX];
1010 memset(scores, 0, sizeof(scores));
1012 foreach_point(board) {
1013 enum stone color = board_at(board, c);
1014 if (color == S_NONE)
1015 color = board_tromp_taylor_owner(board, c);
1016 scores[color]++;
1017 } foreach_point_end;
1019 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1022 float
1023 board_fast_score(struct board *board)
1025 int scores[S_MAX];
1026 memset(scores, 0, sizeof(scores));
1028 foreach_point(board) {
1029 enum stone color = board_at(board, c);
1030 if (color == S_NONE)
1031 color = board_get_one_point_eye(board, &c);
1032 scores[color]++;
1033 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1034 } foreach_point_end;
1036 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1040 bool
1041 is_bad_selfatari(struct board *b, enum stone color, coord_t to)
1043 //fprintf(stderr, "sar check %s %s\n", stone2str(color), coord2sstr(to, b));
1044 /* Assess if we actually gain any liberties by this escape route.
1045 * Note that this is not 100% as we cannot check whether we are
1046 * connecting out or just to ourselves. */
1047 int groupcts[S_MAX] = {};
1048 group_t groupids[S_MAX][4] = {};
1049 foreach_neighbor(b, to, {
1050 enum stone s = board_at(b, c);
1051 groupids[s][groupcts[s]++] = group_at(b, c);
1054 /* More than one immediate liberty, thumbs up! */
1055 if (groupcts[S_NONE] > 1)
1056 return false;
1058 /* Quickly weed out suicides. */
1059 if (board_is_one_point_eye(b, &to, stone_other(color))
1060 && board_group_info(b, groupids[stone_other(color)][0]).libs > 1)
1061 return true;
1063 /* This is set if this move puts a group out of _all_
1064 * liberties; we need to watch out for snapback then. */
1065 bool friend_has_no_libs = false;
1066 /* We may have one liberty, but be looking for one more.
1067 * In that case, @needs_more_lib is id of group
1068 * already providing one, don't consider it again. */
1069 group_t needs_more_lib = 0;
1070 /* ID of the first liberty, providing it again is not
1071 * interesting. */
1072 coord_t needs_more_lib_except = 0;
1074 /* Examine friendly groups: */
1075 for (int i = 0; i < 4; i++) {
1076 /* We can escape by connecting to this group if it's
1077 * not in atari. */
1078 group_t g = groupids[color][i];
1079 if (!g) continue;
1081 if (board_group_info(b, g).libs == 1) {
1082 if (!needs_more_lib)
1083 friend_has_no_libs = true;
1084 // or we already have a friend with 1 lib
1085 continue;
1088 /* Could we self-atari the group here? */
1089 if (board_group_info(b, g).libs > 2)
1090 return false;
1092 /* We need to have another liberty, and
1093 * it must not be the other liberty of
1094 * the group. */
1095 int lib2 = board_group_info(b, g).lib[0];
1096 if (lib2 == to) lib2 = board_group_info(b, g).lib[1];
1097 /* Maybe we already looked at another
1098 * group providing one liberty? */
1099 if (needs_more_lib && needs_more_lib != g
1100 && needs_more_lib_except != lib2)
1101 return false;
1103 /* Can we get the liberty locally? */
1104 /* Yes if we are route to more liberties... */
1105 if (groupcts[S_NONE] > 1)
1106 return false;
1107 /* ...or one liberty, but not lib2. */
1108 if (groupcts[S_NONE] > 0
1109 && abs(lib2 - to) != 1
1110 && abs(lib2 - to) != board_size(b))
1111 return false;
1113 /* ...ok, then we can still contribute a liberty
1114 * later by capturing something. */
1115 needs_more_lib = g;
1116 needs_more_lib_except = lib2;
1117 friend_has_no_libs = false;
1120 //fprintf(stderr, "no friendly group\n");
1122 /* We may be able to gain a liberty by capturing this group. */
1123 group_t can_capture = 0;
1125 /* Examine enemy groups: */
1126 for (int i = 0; i < 4; i++) {
1127 /* We can escape by capturing this group if it's in atari. */
1128 group_t g = groupids[stone_other(color)][i];
1129 if (!g || board_group_info(b, g).libs > 1)
1130 continue;
1132 /* But we need to get to at least two liberties by this;
1133 * we already have one outside liberty, or the group is
1134 * more than 1 stone (in that case, capturing is always
1135 * nice!). */
1136 if (groupcts[S_NONE] > 0 || !group_is_onestone(b, g))
1137 return false;
1138 /* ...or, it's a ko stone, */
1139 if (neighbor_count_at(b, g, color) + neighbor_count_at(b, g, S_OFFBOARD) == 3) {
1140 /* and we don't have a group to save: then, just taking
1141 * single stone means snapback! */
1142 if (!friend_has_no_libs)
1143 return false;
1145 /* ...or, we already have one indirect liberty provided
1146 * by another group. */
1147 if (needs_more_lib || (can_capture && can_capture != g))
1148 return false;
1149 can_capture = g;
1153 //fprintf(stderr, "no cap group\n");
1155 if (!needs_more_lib && !can_capture) {
1156 /* We have no hope for more fancy tactics - this move is simply
1157 * a suicide, not even a self-atari. */
1158 return true;
1160 /* XXX: I wonder if it makes sense to continue if we actually
1161 * just !needs_more_lib. */
1163 /* There is another possibility - we can self-atari if it is
1164 * a nakade: we put an enemy group in atari from the inside. */
1165 /* This branch also allows eyes falsification:
1166 * O O O . . (This is different from throw-in to false eye
1167 * X X O O . checked below in that there is no X stone at the
1168 * X . X O . right of the star point in this diagram.)
1169 * X X X O O
1170 * X O * . . */
1171 /* TODO: Allow to only nakade if the created shape is dead
1172 * (http://senseis.xmp.net/?Nakade). */
1174 /* The nakade is valid only if it's valid for all surrounding
1175 * enemy groups, thus we do the check only once - for the
1176 * first one. */
1177 group_t g = groupids[stone_other(color)][0];
1178 if (g && board_group_info(b, g).libs == 2) {
1179 /* We must make sure the other liberty of that group:
1180 * (i) is an internal liberty
1181 * (ii) filling it to capture our group will not gain
1182 * safety */
1184 /* Let's look at the other liberty neighbors: */
1185 int lib2 = board_group_info(b, g).lib[0];
1186 if (lib2 == to) lib2 = board_group_info(b, g).lib[1];
1187 foreach_neighbor(b, lib2, {
1188 /* This neighbor of course does not contribute
1189 * anything to the enemy. */
1190 if (board_at(b, c) == S_OFFBOARD)
1191 continue;
1193 /* If the other liberty has empty neighbor,
1194 * it must be the original liberty; otherwise,
1195 * since the whole group has only 2 liberties,
1196 * the other liberty may not be internal and
1197 * we are nakade'ing eyeless group from outside,
1198 * which is stupid. */
1199 if (board_at(b, c) == S_NONE) {
1200 if (c == to)
1201 continue;
1202 else
1203 goto invalid_nakade;
1206 int g2 = group_at(b, c);
1207 /* If the neighbor is of our color, it must
1208 * be our group; if it is a different group,
1209 * we won't allow the self-atari. */
1210 /* X X X X We will not allow play on 'a',
1211 * X X a X because 'b' would capture two
1212 * X O b X different groups, forming two
1213 * X X X X eyes. */
1214 if (board_at(b, c) == color) {
1215 /* Our group == one of the groups
1216 * we (@to) are connected to. */
1217 int j;
1218 for (j = 0; j < 4; j++)
1219 if (groupids[color][j] == g2)
1220 break;
1221 if (j == 4)
1222 goto invalid_nakade;
1223 continue;
1226 /* The neighbor is enemy color. It's ok if
1227 * it's still the same group or this is its
1228 * only liberty. */
1229 if (g == g2 || board_group_info(b, g2).libs == 1)
1230 continue;
1231 /* Otherwise, it must have the exact same
1232 * liberties as the original enemy group. */
1233 if (board_group_info(b, g2).libs > 2
1234 || board_group_info(b, g2).lib[0] == to
1235 || board_group_info(b, g2).lib[1] == to)
1236 goto invalid_nakade;
1239 /* Now, we must distinguish between nakade and eye
1240 * falsification; we must not falsify an eye by more
1241 * than two stones. */
1242 if (groupcts[color] < 1 ||
1243 (groupcts[color] == 1 && group_is_onestone(b, groupids[color][0])))
1244 return false;
1246 /* We would create more than 2-stone group; in that
1247 * case, the liberty of our result must be lib2,
1248 * indicating this really is a nakade. */
1249 for (int j = 0; j < 4; j++) {
1250 group_t g2 = groupids[color][j];
1251 if (!g2) continue;
1252 assert(board_group_info(b, g2).libs <= 2);
1253 if (board_group_info(b, g2).libs == 2) {
1254 if (board_group_info(b, g2).lib[0] != lib2
1255 && board_group_info(b, g2).lib[1] != lib2)
1256 goto invalid_nakade;
1257 } else {
1258 assert(board_group_info(b, g2).lib[0] == to);
1262 return false;
1264 invalid_nakade:;
1267 //fprintf(stderr, "no nakade group\n");
1269 /* We can be throwing-in to false eye:
1270 * X X X O X X X O X X X X X
1271 * X . * X * O . X * O O . X
1272 * # # # # # # # # # # # # # */
1273 /* We cannot sensibly throw-in into a corner. */
1274 if (neighbor_count_at(b, to, S_OFFBOARD) < 2
1275 && neighbor_count_at(b, to, stone_other(color))
1276 + neighbor_count_at(b, to, S_OFFBOARD) == 3
1277 && board_is_false_eyelike(b, &to, stone_other(color))) {
1278 assert(groupcts[color] <= 1);
1279 /* Single-stone throw-in may be ok... */
1280 if (groupcts[color] == 0) {
1281 /* O X . There is one problem - when it's
1282 * . * X actually not a throw-in!
1283 * # # # */
1284 foreach_neighbor(b, to, {
1285 if (board_at(b, c) == S_NONE) {
1286 /* Is the empty neighbor an escape path? */
1287 /* (Note that one S_NONE neighbor is already @to.) */
1288 if (neighbor_count_at(b, c, stone_other(color))
1289 + neighbor_count_at(b, c, S_OFFBOARD) < 2)
1290 goto invalid_throwin;
1293 return false;
1296 /* Multi-stone throwin...? */
1297 assert(groupcts[color] == 1);
1298 group_t g = groupids[color][0];
1300 assert(board_group_info(b, g).libs <= 2);
1301 /* Suicide is definitely NOT ok, no matter what else
1302 * we could test. */
1303 if (board_group_info(b, g).libs == 1)
1304 return true;
1306 /* In that case, we must be connected to at most one stone,
1307 * or throwin will not destroy any eyes. */
1308 if (group_is_onestone(b, g))
1309 return false;
1310 invalid_throwin:;
1313 //fprintf(stderr, "no throw-in group\n");
1315 /* No way to pull out, no way to connect out. This really
1316 * is a bad self-atari! */
1317 return true;
1321 bool
1322 board_stone_radar(struct board *b, coord_t coord, int distance)
1324 int bounds[4] = {
1325 coord_x(coord, b) - distance,
1326 coord_y(coord, b) - distance,
1327 coord_x(coord, b) + distance,
1328 coord_y(coord, b) + distance
1330 for (int i = 0; i < 4; i++)
1331 if (bounds[i] < 1)
1332 bounds[i] = 1;
1333 else if (bounds[i] > board_size(b) - 2)
1334 bounds[i] = board_size(b) - 2;
1335 for (int x = bounds[0]; x <= bounds[2]; x++)
1336 for (int y = bounds[1]; y <= bounds[3]; y++)
1337 if (board_atxy(b, x, y) != S_NONE) {
1338 //fprintf(stderr, "radar %d,%d,%d: %d,%d (%d)\n", coord_x(coord, b), coord_y(coord, b), distance, x, y, board_atxy(b, x, y));
1339 return true;
1341 return false;