Moggy: Fillboard support
[pachi.git] / board.c
blob0b9c2657626ccf687865f34ae471b5f8f213228a
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);
41 // Default setup
42 b->size = 9 + 2;
43 board_clear(b);
45 return b;
48 struct board *
49 board_copy(struct board *b2, struct board *b1)
51 memcpy(b2, b1, sizeof(struct board));
53 int bsize = board_size2(b2) * sizeof(*b2->b);
54 int gsize = board_size2(b2) * sizeof(*b2->g);
55 int fsize = board_size2(b2) * sizeof(*b2->f);
56 int nsize = board_size2(b2) * sizeof(*b2->n);
57 int psize = board_size2(b2) * sizeof(*b2->p);
58 int hsize = board_size2(b2) * 2 * sizeof(*b2->h);
59 int gisize = board_size2(b2) * sizeof(*b2->gi);
60 #ifdef WANT_BOARD_C
61 int csize = board_size2(b2) * sizeof(*b2->c);
62 #else
63 int csize = 0;
64 #endif
65 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
66 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
67 b2->b = x; x += bsize;
68 b2->g = x; x += gsize;
69 b2->f = x; x += fsize;
70 b2->p = x; x += psize;
71 b2->n = x; x += nsize;
72 b2->h = x; x += hsize;
73 b2->gi = x; x += gisize;
74 #ifdef WANT_BOARD_C
75 b2->c = x; x += csize;
76 #endif
78 return b2;
81 void
82 board_done_noalloc(struct board *board)
84 if (board->b) free(board->b);
87 void
88 board_done(struct board *board)
90 board_done_noalloc(board);
91 free(board);
94 void
95 board_resize(struct board *board, int size)
97 #ifdef BOARD_SIZE
98 assert(board_size(board) == size + 2);
99 #else
100 board_size(board) = size + 2 /* S_OFFBOARD margin */;
101 board_size2(board) = board_size(board) * board_size(board);
102 #endif
103 if (board->b)
104 free(board->b);
106 int bsize = board_size2(board) * sizeof(*board->b);
107 int gsize = board_size2(board) * sizeof(*board->g);
108 int fsize = board_size2(board) * sizeof(*board->f);
109 int nsize = board_size2(board) * sizeof(*board->n);
110 int psize = board_size2(board) * sizeof(*board->p);
111 int hsize = board_size2(board) * 2 * sizeof(*board->h);
112 int gisize = board_size2(board) * sizeof(*board->gi);
113 #ifdef WANT_BOARD_C
114 int csize = board_size2(board) * sizeof(*board->c);
115 #else
116 int csize = 0;
117 #endif
118 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
119 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize);
120 board->b = x; x += bsize;
121 board->g = x; x += gsize;
122 board->f = x; x += fsize;
123 board->p = x; x += psize;
124 board->n = x; x += nsize;
125 board->h = x; x += hsize;
126 board->gi = x; x += gisize;
127 #ifdef WANT_BOARD_C
128 board->c = x; x += csize;
129 #endif
132 void
133 board_clear(struct board *board)
135 int size = board_size(board);
136 float komi = board->komi;
138 board_done_noalloc(board);
139 board_setup(board);
140 board_resize(board, size - 2 /* S_OFFBOARD margin */);
142 board->komi = komi;
144 /* Setup initial symmetry */
145 board->symmetry.d = 1;
146 board->symmetry.x1 = board->symmetry.y1 = board->size / 2;
147 board->symmetry.x2 = board->symmetry.y2 = board->size - 1;
148 board->symmetry.type = SYM_FULL;
150 /* Draw the offboard margin */
151 int top_row = board_size2(board) - board_size(board);
152 int i;
153 for (i = 0; i < board_size(board); i++)
154 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
155 for (i = 0; i <= top_row; i += board_size(board))
156 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
158 foreach_point(board) {
159 coord_t coord = c;
160 if (board_at(board, coord) == S_OFFBOARD)
161 continue;
162 foreach_neighbor(board, c, {
163 inc_neighbor_count_at(board, coord, board_at(board, c));
164 } );
165 } foreach_point_end;
167 /* First, pass is always a free position. */
168 board->f[board->flen++] = coord_raw(pass);
169 /* All positions are free! Except the margin. */
170 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
171 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
172 board->f[board->flen++] = i;
174 /* Initialize zobrist hashtable. */
175 foreach_point(board) {
176 int max = (sizeof(hash_t) << history_hash_bits);
177 /* fast_random() is 16-bit only */
178 board->h[coord_raw(c) * 2] = ((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])
183 /* Would be kinda "oops". */
184 board->h[coord_raw(c) * 2] = 1;
185 /* And once again for white */
186 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
187 | ((hash_t) fast_random(max) << 16)
188 | ((hash_t) fast_random(max) << 32)
189 | ((hash_t) fast_random(max) << 48);
190 if (!board->h[coord_raw(c) * 2 + 1])
191 board->h[coord_raw(c) * 2 + 1] = 1;
192 } foreach_point_end;
196 void
197 board_print(struct board *board, FILE *f)
199 fprintf(f, "Move: % 3d Komi: %2.1f Captures B: %d W: %d\n ",
200 board->moves, board->komi,
201 board->captures[S_BLACK], board->captures[S_WHITE]);
202 int x, y;
203 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
204 for (x = 1; x < board_size(board) - 1; x++)
205 fprintf(f, "%c ", asdf[x - 1]);
206 fprintf(f, "\n +-");
207 for (x = 1; x < board_size(board) - 1; x++)
208 fprintf(f, "--");
209 fprintf(f, "+\n");
210 for (y = board_size(board) - 2; y >= 1; y--) {
211 fprintf(f, "%2d | ", y);
212 for (x = 1; x < board_size(board) - 1; x++) {
213 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
214 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
215 else
216 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
218 if (DEBUGL(6)) {
219 fprintf(f, "| ");
220 for (x = 1; x < board_size(board) - 1; x++) {
221 fprintf(f, "%d ", group_base(group_atxy(board, x, y)));
224 fprintf(f, "|\n");
226 fprintf(f, " +-");
227 for (x = 1; x < board_size(board) - 1; x++)
228 fprintf(f, "--");
229 fprintf(f, "+\n\n");
233 /* Update board hash with given coordinate. */
234 static void profiling_noinline
235 board_hash_update(struct board *board, coord_t coord, enum stone color)
237 board->hash ^= hash_at(board, coord, color);
238 if (DEBUGL(8))
239 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);
242 /* Commit current board hash to history. */
243 static void profiling_noinline
244 board_hash_commit(struct board *board)
246 if (DEBUGL(8))
247 fprintf(stderr, "board_hash_commit %llx\n", board->hash);
248 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
249 board->history_hash[board->hash & history_hash_mask] = board->hash;
250 } else {
251 hash_t i = board->hash;
252 while (board->history_hash[i & history_hash_mask]) {
253 if (board->history_hash[i & history_hash_mask] == board->hash) {
254 if (DEBUGL(5))
255 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
256 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
257 board->superko_violation = true;
258 return;
260 i = history_hash_next(i);
262 board->history_hash[i & history_hash_mask] = board->hash;
267 void
268 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
270 if (likely(symmetry->type == SYM_NONE)) {
271 /* Fully degenerated already. We do not support detection
272 * of restoring of symmetry, assuming that this is too rare
273 * a case to handle. */
274 return;
277 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
278 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
279 if (DEBUGL(6)) {
280 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
281 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
282 symmetry->d, symmetry->type, x, y);
285 switch (symmetry->type) {
286 case SYM_FULL:
287 if (x == t && y == t) {
288 /* Tengen keeps full symmetry. */
289 return;
291 /* New symmetry now? */
292 if (x == y) {
293 symmetry->type = SYM_DIAG_UP;
294 symmetry->x1 = symmetry->y1 = 1;
295 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
296 symmetry->d = 1;
297 } else if (dx == y) {
298 symmetry->type = SYM_DIAG_DOWN;
299 symmetry->x1 = symmetry->y1 = 1;
300 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
301 symmetry->d = 1;
302 } else if (x == t) {
303 symmetry->type = SYM_HORIZ;
304 symmetry->y1 = 1;
305 symmetry->y2 = board_size(b) - 1;
306 symmetry->d = 0;
307 } else if (y == t) {
308 symmetry->type = SYM_VERT;
309 symmetry->x1 = 1;
310 symmetry->x2 = board_size(b) - 1;
311 symmetry->d = 0;
312 } else {
313 break_symmetry:
314 symmetry->type = SYM_NONE;
315 symmetry->x1 = symmetry->y1 = 1;
316 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
317 symmetry->d = 0;
319 break;
320 case SYM_DIAG_UP:
321 if (x == y)
322 return;
323 goto break_symmetry;
324 case SYM_DIAG_DOWN:
325 if (dx == y)
326 return;
327 goto break_symmetry;
328 case SYM_HORIZ:
329 if (x == t)
330 return;
331 goto break_symmetry;
332 case SYM_VERT:
333 if (y == t)
334 return;
335 goto break_symmetry;
336 case SYM_NONE:
337 assert(0);
338 break;
341 if (DEBUGL(6)) {
342 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
343 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
344 symmetry->d, symmetry->type);
346 /* Whew. */
350 void
351 board_handicap_stone(struct board *board, int x, int y, FILE *f)
353 struct move m;
354 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
356 board_play(board, &m);
357 /* Simulate white passing; otherwise, UCT search can get confused since
358 * tree depth parity won't match the color to move. */
359 board->moves++;
361 char *str = coord2str(m.coord, board);
362 if (DEBUGL(1))
363 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
364 fprintf(f, "%s ", str);
365 free(str);
368 void
369 board_handicap(struct board *board, int stones, FILE *f)
371 int margin = 3 + (board_size(board) >= 13);
372 int min = margin;
373 int mid = board_size(board) / 2;
374 int max = board_size(board) - 1 - margin;
375 const int places[][2] = {
376 { min, min }, { max, max }, { max, min }, { min, max },
377 { min, mid }, { max, mid },
378 { mid, min }, { mid, max },
379 { mid, mid },
382 board->handicap = stones;
384 if (stones == 5 || stones == 7) {
385 board_handicap_stone(board, mid, mid, f);
386 stones--;
389 int i;
390 for (i = 0; i < stones; i++)
391 board_handicap_stone(board, places[i][0], places[i][1], f);
395 static void __attribute__((noinline))
396 check_libs_consistency(struct board *board, group_t g)
398 #ifdef DEBUG
399 if (!g) return;
400 struct group *gi = &board_group_info(board, g);
401 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
402 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
403 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
404 assert(0);
406 #endif
409 static void
410 board_capturable_add(struct board *board, group_t group)
412 #ifdef WANT_BOARD_C
413 //fprintf(stderr, "add of group %d (%d)\n", group_base(group), board->clen);
414 assert(group);
415 assert(board->clen < board_size2(board));
416 board->c[board->clen++] = group;
417 #endif
419 static void
420 board_capturable_rm(struct board *board, group_t group)
422 #ifdef WANT_BOARD_C
423 //fprintf(stderr, "rm of group %d\n", group_base(group));
424 for (int i = 0; i < board->clen; i++) {
425 if (unlikely(board->c[i] == group)) {
426 board->c[i] = board->c[--board->clen];
427 return;
430 fprintf(stderr, "rm of bad group %d\n", group_base(group));
431 assert(0);
432 #endif
435 static void
436 board_group_addlib(struct board *board, group_t group, coord_t coord)
438 if (DEBUGL(7)) {
439 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
440 group_base(group), coord2sstr(group_base(group), board),
441 board_group_info(board, group).libs, coord2sstr(coord, board));
444 check_libs_consistency(board, group);
446 struct group *gi = &board_group_info(board, group);
447 if (gi->libs < GROUP_KEEP_LIBS) {
448 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
449 #if 0
450 /* Seems extra branch just slows it down */
451 if (!gi->lib[i])
452 break;
453 #endif
454 if (unlikely(gi->lib[i] == coord))
455 return;
457 if (gi->libs == 0)
458 board_capturable_add(board, group);
459 else if (gi->libs == 1)
460 board_capturable_rm(board, group);
461 gi->lib[gi->libs++] = coord;
464 check_libs_consistency(board, group);
467 static void
468 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
470 /* Add extra liberty from the board to our liberty list. */
471 enum stone watermark[board_size2(board)];
472 memcpy(watermark, board->b, sizeof(watermark));
474 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
475 watermark[coord_raw(gi->lib[i])] = S_OFFBOARD;
476 watermark[coord_raw(avoid)] = S_OFFBOARD;
478 foreach_in_group(board, group) {
479 coord_t coord2 = c;
480 foreach_neighbor(board, coord2, {
481 if (likely(watermark[coord_raw(c)] != S_NONE))
482 continue;
483 watermark[coord_raw(c)] = S_OFFBOARD;
484 gi->lib[gi->libs++] = c;
485 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
486 return;
487 } );
488 } foreach_in_group_end;
491 static void
492 board_group_rmlib(struct board *board, group_t group, coord_t coord)
494 if (DEBUGL(7)) {
495 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
496 group_base(group), coord2sstr(group_base(group), board),
497 board_group_info(board, group).libs, coord2sstr(coord, board));
500 struct group *gi = &board_group_info(board, group);
501 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
502 #if 0
503 /* Seems extra branch just slows it down */
504 if (!gi->lib[i])
505 break;
506 #endif
507 if (likely(gi->lib[i] != coord))
508 continue;
510 gi->lib[i] = gi->lib[--gi->libs];
511 gi->lib[gi->libs] = 0;
513 check_libs_consistency(board, group);
515 /* Postpone refilling lib[] until we need to. */
516 assert(GROUP_REFILL_LIBS > 1);
517 if (gi->libs > GROUP_REFILL_LIBS)
518 return;
519 if (gi->libs == GROUP_REFILL_LIBS)
520 board_group_find_extra_libs(board, group, gi, coord);
522 if (gi->libs == 1)
523 board_capturable_add(board, group);
524 else if (gi->libs == 0)
525 board_capturable_rm(board, group);
526 return;
529 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
530 * can call this multiple times per coord. */
531 check_libs_consistency(board, group);
532 return;
536 /* This is a low-level routine that doesn't maintain consistency
537 * of all the board data structures. Use board_group_capture() from
538 * your code. */
539 static void
540 board_remove_stone(struct board *board, coord_t c)
542 enum stone color = board_at(board, c);
543 board_at(board, c) = S_NONE;
544 group_at(board, c) = 0;
545 board_hash_update(board, c, color);
547 /* Increase liberties of surrounding groups */
548 coord_t coord = c;
549 foreach_neighbor(board, coord, {
550 dec_neighbor_count_at(board, c, color);
551 group_t g = group_at(board, c);
552 if (g)
553 board_group_addlib(board, g, coord);
556 if (DEBUGL(6))
557 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
558 board->f[board->flen++] = coord_raw(c);
562 static void profiling_noinline
563 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
565 foreach_neighbor(board, coord, {
566 if (board_at(board, c) == S_NONE)
567 board_group_addlib(board, group, c);
570 group_at(board, coord) = group;
571 groupnext_at(board, coord) = groupnext_at(board, prevstone);
572 groupnext_at(board, prevstone) = coord_raw(coord);
574 if (DEBUGL(8))
575 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
576 coord_x(prevstone, board), coord_y(prevstone, board),
577 coord_x(coord, board), coord_y(coord, board),
578 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
579 group_base(group));
582 static void profiling_noinline
583 merge_groups(struct board *board, group_t group_to, group_t group_from)
585 if (DEBUGL(7))
586 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
587 group_base(group_from), group_base(group_to));
589 coord_t last_in_group;
590 foreach_in_group(board, group_from) {
591 last_in_group = c;
592 group_at(board, c) = group_to;
593 } foreach_in_group_end;
594 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
595 groupnext_at(board, group_base(group_to)) = group_base(group_from);
597 struct group *gi_from = &board_group_info(board, group_from);
598 struct group *gi_to = &board_group_info(board, group_to);
599 if (gi_to->libs < GROUP_KEEP_LIBS) {
600 for (int i = 0; i < gi_from->libs; i++) {
601 for (int j = 0; j < gi_to->libs; j++)
602 if (gi_to->lib[j] == gi_from->lib[i])
603 goto next_from_lib;
604 if (gi_to->libs == 0)
605 board_capturable_add(board, group_to);
606 else if (gi_to->libs == 1)
607 board_capturable_rm(board, group_to);
608 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
609 if (gi_to->libs >= GROUP_KEEP_LIBS)
610 break;
611 next_from_lib:;
615 if (gi_from->libs == 1)
616 board_capturable_rm(board, group_from);
617 memset(gi_from, 0, sizeof(struct group));
619 if (DEBUGL(7))
620 fprintf(stderr, "board_play_raw: merged group: %d\n",
621 group_base(group_to));
624 static group_t profiling_noinline
625 new_group(struct board *board, coord_t coord)
627 group_t group = coord_raw(coord);
628 struct group *gi = &board_group_info(board, group);
629 foreach_neighbor(board, coord, {
630 if (board_at(board, c) == S_NONE)
631 /* board_group_addlib is ridiculously expensive for us */
632 #if GROUP_KEEP_LIBS < 4
633 if (gi->libs < GROUP_KEEP_LIBS)
634 #endif
635 gi->lib[gi->libs++] = c;
637 if (gi->libs == 1)
638 board_capturable_add(board, group);
639 check_libs_consistency(board, group);
641 group_at(board, coord) = group;
642 groupnext_at(board, coord) = 0;
644 if (DEBUGL(8))
645 fprintf(stderr, "new_group: added %d,%d to group %d\n",
646 coord_x(coord, board), coord_y(coord, board),
647 group_base(group));
649 return group;
652 static inline group_t
653 play_one_neighbor(struct board *board,
654 coord_t coord, enum stone color, enum stone other_color,
655 coord_t c, group_t group)
657 enum stone ncolor = board_at(board, c);
658 group_t ngroup = group_at(board, c);
660 inc_neighbor_count_at(board, c, color);
662 if (!ngroup)
663 return group;
665 board_group_rmlib(board, ngroup, coord);
666 if (DEBUGL(7))
667 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
668 group_base(ngroup), ncolor, color, other_color);
670 if (ncolor == color && ngroup != group) {
671 if (!group) {
672 group = ngroup;
673 add_to_group(board, group, c, coord);
674 } else {
675 merge_groups(board, group, ngroup);
677 } else if (ncolor == other_color) {
678 if (DEBUGL(8)) {
679 struct group *gi = &board_group_info(board, ngroup);
680 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
681 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
682 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
683 fprintf(stderr, "\n");
685 if (unlikely(board_group_captured(board, ngroup)))
686 board_group_capture(board, ngroup);
688 return group;
691 /* We played on a place with at least one liberty. We will become a member of
692 * some group for sure. */
693 static group_t profiling_noinline
694 board_play_outside(struct board *board, struct move *m, int f)
696 coord_t coord = m->coord;
697 enum stone color = m->color;
698 enum stone other_color = stone_other(color);
699 group_t group = 0;
701 board->f[f] = board->f[--board->flen];
702 if (DEBUGL(6))
703 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
705 foreach_neighbor(board, coord, {
706 group = play_one_neighbor(board, coord, color, other_color, c, group);
709 if (unlikely(!group))
710 group = new_group(board, coord);
712 board_at(board, coord) = color;
713 board->last_move = *m;
714 board->moves++;
715 board_hash_update(board, coord, color);
716 board_symmetry_update(board, &board->symmetry, coord);
717 struct move ko = { pass, S_NONE };
718 board->ko = ko;
720 return group;
723 /* We played in an eye-like shape. Either we capture at least one of the eye
724 * sides in the process of playing, or return -1. */
725 static int profiling_noinline
726 board_play_in_eye(struct board *board, struct move *m, int f)
728 coord_t coord = m->coord;
729 enum stone color = m->color;
730 /* Check ko: Capture at a position of ko capture one move ago */
731 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
732 if (DEBUGL(5))
733 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
734 return -1;
735 } else if (DEBUGL(6)) {
736 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
737 color, coord_x(coord, board), coord_y(coord, board),
738 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
741 struct move ko = { pass, S_NONE };
743 int captured_groups = 0;
745 foreach_neighbor(board, coord, {
746 group_t g = group_at(board, c);
747 if (DEBUGL(7))
748 fprintf(stderr, "board_check: group %d has %d libs\n",
749 g, board_group_info(board, g).libs);
750 captured_groups += (board_group_info(board, g).libs == 1);
753 if (likely(captured_groups == 0)) {
754 if (DEBUGL(5)) {
755 if (DEBUGL(6))
756 board_print(board, stderr);
757 fprintf(stderr, "board_check: one-stone suicide\n");
760 return -1;
763 board->f[f] = board->f[--board->flen];
764 if (DEBUGL(6))
765 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
767 foreach_neighbor(board, coord, {
768 inc_neighbor_count_at(board, c, color);
770 group_t group = group_at(board, c);
771 if (!group)
772 continue;
774 board_group_rmlib(board, group, coord);
775 if (DEBUGL(7))
776 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
777 group_base(group));
779 if (board_group_captured(board, group)) {
780 if (board_group_capture(board, group) == 1) {
781 /* If we captured multiple groups at once,
782 * we can't be fighting ko so we don't need
783 * to check for that. */
784 ko.color = stone_other(color);
785 ko.coord = c;
786 if (DEBUGL(5))
787 fprintf(stderr, "guarding ko at %d,%d,%d\n", ko.color, coord_x(ko.coord, board), coord_y(ko.coord, board));
792 board_at(board, coord) = color;
794 board->last_move = *m;
795 board->moves++;
796 board_hash_update(board, coord, color);
797 board_hash_commit(board);
798 board_symmetry_update(board, &board->symmetry, coord);
799 board->ko = ko;
801 return !!new_group(board, coord);
804 static int __attribute__((flatten))
805 board_play_f(struct board *board, struct move *m, int f)
807 if (DEBUGL(7)) {
808 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
810 if (likely(!board_is_eyelike(board, &m->coord, stone_other(m->color)))) {
811 /* NOT playing in an eye. Thus this move has to succeed. (This
812 * is thanks to New Zealand rules. Otherwise, multi-stone
813 * suicide might fail.) */
814 group_t group = board_play_outside(board, m, f);
815 if (unlikely(board_group_captured(board, group))) {
816 board_group_capture(board, group);
818 board_hash_commit(board);
819 return 0;
820 } else {
821 return board_play_in_eye(board, m, f);
826 board_play(struct board *board, struct move *m)
828 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
829 board->last_move = *m;
830 return 0;
833 int f;
834 for (f = 0; f < board->flen; f++)
835 if (board->f[f] == coord_raw(m->coord))
836 return board_play_f(board, m, f);
838 if (DEBUGL(7))
839 fprintf(stderr, "board_check: stone exists\n");
840 return -1;
844 static inline bool
845 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
847 coord_raw(*coord) = b->f[f];
848 if (unlikely(is_pass(*coord)))
849 return random_pass;
850 struct move m = { *coord, color };
851 if (DEBUGL(6))
852 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
853 return (likely(!board_is_one_point_eye(b, coord, color)) /* bad idea to play into one, usually */
854 && (!permit || permit(permit_data, b, &m))
855 && likely(board_play_f(b, &m, f) >= 0));
858 void
859 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
861 int base = fast_random(b->flen);
862 coord_pos(*coord, base, b);
863 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
864 return;
866 int f;
867 for (f = base + 1; f < b->flen; f++)
868 if (board_try_random_move(b, color, coord, f, permit, permit_data))
869 return;
870 for (f = 0; f < base; f++)
871 if (board_try_random_move(b, color, coord, f, permit, permit_data))
872 return;
874 *coord = pass;
878 bool
879 board_is_valid_move(struct board *board, struct move *m)
881 if (board_at(board, m->coord) != S_NONE)
882 return false;
883 if (!board_is_eyelike(board, &m->coord, stone_other(m->color)))
884 return true;
885 /* Play within {true,false} eye-ish formation */
886 if (board->ko.coord == m->coord && board->ko.color == m->color)
887 return false;
888 int groups_in_atari = 0;
889 foreach_neighbor(board, m->coord, {
890 group_t g = group_at(board, c);
891 groups_in_atari += (board_group_info(board, g).libs == 1);
893 return !!groups_in_atari;
897 bool
898 board_is_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
900 return (neighbor_count_at(board, *coord, eye_color)
901 + neighbor_count_at(board, *coord, S_OFFBOARD)) == 4;
904 bool
905 board_is_false_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
907 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
909 /* XXX: We attempt false eye detection but we will yield false
910 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
912 foreach_diag_neighbor(board, *coord) {
913 color_diag_libs[(enum stone) board_at(board, c)]++;
914 } foreach_diag_neighbor_end;
915 /* For false eye, we need two enemy stones diagonally in the
916 * middle of the board, or just one enemy stone at the edge
917 * or in the corner. */
918 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
919 return color_diag_libs[stone_other(eye_color)] >= 2;
922 bool
923 board_is_one_point_eye(struct board *board, coord_t *coord, enum stone eye_color)
925 return board_is_eyelike(board, coord, eye_color)
926 && !board_is_false_eyelike(board, coord, eye_color);
929 enum stone
930 board_get_one_point_eye(struct board *board, coord_t *coord)
932 if (board_is_one_point_eye(board, coord, S_WHITE))
933 return S_WHITE;
934 else if (board_is_one_point_eye(board, coord, S_BLACK))
935 return S_BLACK;
936 else
937 return S_NONE;
941 int profiling_noinline
942 board_group_capture(struct board *board, group_t group)
944 int stones = 0;
946 foreach_in_group(board, group) {
947 board->captures[stone_other(board_at(board, c))]++;
948 board_remove_stone(board, c);
949 stones++;
950 } foreach_in_group_end;
952 if (board_group_info(board, group).libs == 1)
953 board_capturable_rm(board, group);
954 memset(&board_group_info(board, group), 0, sizeof(struct group));
956 return stones;
959 bool
960 board_group_in_atari(struct board *board, group_t group, coord_t *lastlib)
962 if (board_group_info(board, group).libs != 1)
963 return false;
964 *lastlib = board_group_info(board, group).lib[0];
965 return true;
968 bool
969 board_group_can_atari(struct board *board, group_t group, coord_t lastlib[2])
971 if (board_group_info(board, group).libs != 2)
972 return false;
973 lastlib[0] = board_group_info(board, group).lib[0];
974 lastlib[1] = board_group_info(board, group).lib[1];
975 return true;
979 static enum stone
980 board_tromp_taylor_owner(struct board *board, coord_t c)
982 int x = coord_x(c, board), y = coord_y(c, board);
983 enum stone color = S_NONE;
984 #define TEST_REACH(xx, yy) \
986 enum stone c2 = board_atxy(board, xx, yy); \
987 if (c2 != S_NONE) { \
988 if (color != S_NONE && color != c2) \
989 return S_NONE; \
990 color = c2; \
991 break; \
994 for (int i = x; i > 0; i--)
995 TEST_REACH(i, y);
996 for (int i = x; i < board_size(board) - 1; i++)
997 TEST_REACH(i, y);
998 for (int i = y; i > 0; i--)
999 TEST_REACH(x, i);
1000 for (int i = y; i < board_size(board) - 1; i++)
1001 TEST_REACH(x, i);
1002 return color;
1005 /* Tromp-Taylor Counting */
1006 float
1007 board_official_score(struct board *board)
1010 /* A point P, not colored C, is said to reach C, if there is a path of
1011 * (vertically or horizontally) adjacent points of P's color from P to
1012 * a point of color C.
1014 * A player's score is the number of points of her color, plus the
1015 * number of empty points that reach only her color. */
1017 int scores[S_MAX];
1018 memset(scores, 0, sizeof(scores));
1020 foreach_point(board) {
1021 enum stone color = board_at(board, c);
1022 if (color == S_NONE)
1023 color = board_tromp_taylor_owner(board, c);
1024 scores[color]++;
1025 } foreach_point_end;
1027 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
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];
1048 bool
1049 is_bad_selfatari(struct board *b, enum stone color, coord_t to)
1051 //fprintf(stderr, "sar check %s %s\n", stone2str(color), coord2sstr(to, b));
1052 /* Assess if we actually gain any liberties by this escape route.
1053 * Note that this is not 100% as we cannot check whether we are
1054 * connecting out or just to ourselves. */
1055 int groupcts[S_MAX] = {};
1056 group_t groupids[S_MAX][4] = {};
1057 foreach_neighbor(b, to, {
1058 enum stone s = board_at(b, c);
1059 groupids[s][groupcts[s]++] = group_at(b, c);
1062 /* More than one immediate liberty, thumbs up! */
1063 if (groupcts[S_NONE] > 1)
1064 return false;
1066 /* Quickly weed out suicides. */
1067 if (board_is_one_point_eye(b, &to, stone_other(color))
1068 && board_group_info(b, groupids[stone_other(color)][0]).libs > 1)
1069 return true;
1071 /* This is set if this move puts a group out of _all_
1072 * liberties; we need to watch out for snapback then. */
1073 bool friend_has_no_libs = false;
1074 /* We may have one liberty, but be looking for one more.
1075 * In that case, @needs_more_lib is id of group
1076 * already providing one, don't consider it again. */
1077 group_t needs_more_lib = 0;
1078 /* ID of the first liberty, providing it again is not
1079 * interesting. */
1080 coord_t needs_more_lib_except = 0;
1082 /* Examine friendly groups: */
1083 for (int i = 0; i < 4; i++) {
1084 /* We can escape by connecting to this group if it's
1085 * not in atari. */
1086 group_t g = groupids[color][i];
1087 if (!g) continue;
1089 if (board_group_info(b, g).libs == 1) {
1090 if (!needs_more_lib)
1091 friend_has_no_libs = true;
1092 // or we already have a friend with 1 lib
1093 continue;
1096 /* Could we self-atari the group here? */
1097 if (board_group_info(b, g).libs > 2)
1098 return false;
1100 /* We need to have another liberty, and
1101 * it must not be the other liberty of
1102 * the group. */
1103 int lib2 = board_group_info(b, g).lib[0];
1104 if (lib2 == to) lib2 = board_group_info(b, g).lib[1];
1105 /* Maybe we already looked at another
1106 * group providing one liberty? */
1107 if (needs_more_lib && needs_more_lib != g
1108 && needs_more_lib_except != lib2)
1109 return false;
1111 /* Can we get the liberty locally? */
1112 /* Yes if we are route to more liberties... */
1113 if (groupcts[S_NONE] > 1)
1114 return false;
1115 /* ...or one liberty, but not lib2. */
1116 if (groupcts[S_NONE] > 0
1117 && abs(lib2 - to) != 1
1118 && abs(lib2 - to) != board_size(b))
1119 return false;
1121 /* ...ok, then we can still contribute a liberty
1122 * later by capturing something. */
1123 needs_more_lib = g;
1124 needs_more_lib_except = lib2;
1125 friend_has_no_libs = false;
1128 //fprintf(stderr, "no friendly group\n");
1130 /* We may be able to gain a liberty by capturing this group. */
1131 group_t can_capture = 0;
1133 /* Examine enemy groups: */
1134 for (int i = 0; i < 4; i++) {
1135 /* We can escape by capturing this group if it's in atari. */
1136 group_t g = groupids[stone_other(color)][i];
1137 if (!g || board_group_info(b, g).libs > 1)
1138 continue;
1140 /* But we need to get to at least two liberties by this;
1141 * we already have one outside liberty, or the group is
1142 * more than 1 stone (in that case, capturing is always
1143 * nice!). */
1144 if (groupcts[S_NONE] > 0 || !group_is_onestone(b, g))
1145 return false;
1146 /* ...or, it's a ko stone, */
1147 if (neighbor_count_at(b, g, color) + neighbor_count_at(b, g, S_OFFBOARD) == 3) {
1148 /* and we don't have a group to save: then, just taking
1149 * single stone means snapback! */
1150 if (!friend_has_no_libs)
1151 return false;
1153 /* ...or, we already have one indirect liberty provided
1154 * by another group. */
1155 if (needs_more_lib || (can_capture && can_capture != g))
1156 return false;
1157 can_capture = g;
1161 //fprintf(stderr, "no cap group\n");
1163 if (!needs_more_lib && !can_capture) {
1164 /* We have no hope for more fancy tactics - this move is simply
1165 * a suicide, not even a self-atari. */
1166 return true;
1168 /* XXX: I wonder if it makes sense to continue if we actually
1169 * just !needs_more_lib. */
1171 /* There is another possibility - we can self-atari if it is
1172 * a nakade: we put an enemy group in atari from the inside. */
1173 /* This branch also allows eyes falsification:
1174 * O O O . . (This is different from throw-in to false eye
1175 * X X O O . checked below in that there is no X stone at the
1176 * X . X O . right of the star point in this diagram.)
1177 * X X X O O
1178 * X O * . . */
1179 /* TODO: Allow to only nakade if the created shape is dead
1180 * (http://senseis.xmp.net/?Nakade). */
1182 /* The nakade is valid only if it's valid for all surrounding
1183 * enemy groups, thus we do the check only once - for the
1184 * first one. */
1185 group_t g = groupids[stone_other(color)][0];
1186 if (g && board_group_info(b, g).libs == 2) {
1187 /* We must make sure the other liberty of that group:
1188 * (i) is an internal liberty
1189 * (ii) filling it to capture our group will not gain
1190 * safety */
1192 /* Let's look at the other liberty neighbors: */
1193 int lib2 = board_group_info(b, g).lib[0];
1194 if (lib2 == to) lib2 = board_group_info(b, g).lib[1];
1195 foreach_neighbor(b, lib2, {
1196 /* This neighbor of course does not contribute
1197 * anything to the enemy. */
1198 if (board_at(b, c) == S_OFFBOARD)
1199 continue;
1201 /* If the other liberty has empty neighbor,
1202 * it must be the original liberty; otherwise,
1203 * since the whole group has only 2 liberties,
1204 * the other liberty may not be internal and
1205 * we are nakade'ing eyeless group from outside,
1206 * which is stupid. */
1207 if (board_at(b, c) == S_NONE) {
1208 if (c == to)
1209 continue;
1210 else
1211 goto invalid_nakade;
1214 int g2 = group_at(b, c);
1215 /* If the neighbor is of our color, it must
1216 * be our group; if it is a different group,
1217 * we won't allow the self-atari. */
1218 /* X X X X We will not allow play on 'a',
1219 * X X a X because 'b' would capture two
1220 * X O b X different groups, forming two
1221 * X X X X eyes. */
1222 if (board_at(b, c) == color) {
1223 /* Our group == one of the groups
1224 * we (@to) are connected to. */
1225 int j;
1226 for (j = 0; j < 4; j++)
1227 if (groupids[color][j] == g2)
1228 break;
1229 if (j == 4)
1230 goto invalid_nakade;
1231 continue;
1234 /* The neighbor is enemy color. It's ok if
1235 * it's still the same group or this is its
1236 * only liberty. */
1237 if (g == g2 || board_group_info(b, g2).libs == 1)
1238 continue;
1239 /* Otherwise, it must have the exact same
1240 * liberties as the original enemy group. */
1241 if (board_group_info(b, g2).libs > 2
1242 || board_group_info(b, g2).lib[0] == to
1243 || board_group_info(b, g2).lib[1] == to)
1244 goto invalid_nakade;
1247 /* Now, we must distinguish between nakade and eye
1248 * falsification; we must not falsify an eye by more
1249 * than two stones. */
1250 if (groupcts[color] < 1 ||
1251 (groupcts[color] == 1 && group_is_onestone(b, groupids[color][0])))
1252 return false;
1254 /* We would create more than 2-stone group; in that
1255 * case, the liberty of our result must be lib2,
1256 * indicating this really is a nakade. */
1257 for (int j = 0; j < 4; j++) {
1258 group_t g2 = groupids[color][j];
1259 if (!g2) continue;
1260 assert(board_group_info(b, g2).libs <= 2);
1261 if (board_group_info(b, g2).libs == 2) {
1262 if (board_group_info(b, g2).lib[0] != lib2
1263 && board_group_info(b, g2).lib[1] != lib2)
1264 goto invalid_nakade;
1265 } else {
1266 assert(board_group_info(b, g2).lib[0] == to);
1270 return false;
1272 invalid_nakade:;
1275 //fprintf(stderr, "no nakade group\n");
1277 /* We can be throwing-in to false eye:
1278 * X X X O X X X O X X X X X
1279 * X . * X * O . X * O O . X
1280 * # # # # # # # # # # # # # */
1281 /* We cannot sensibly throw-in into a corner. */
1282 if (neighbor_count_at(b, to, S_OFFBOARD) < 2
1283 && neighbor_count_at(b, to, stone_other(color))
1284 + neighbor_count_at(b, to, S_OFFBOARD) == 3
1285 && board_is_false_eyelike(b, &to, stone_other(color))) {
1286 assert(groupcts[color] <= 1);
1287 /* Single-stone throw-in may be ok... */
1288 if (groupcts[color] == 0) {
1289 /* O X . There is one problem - when it's
1290 * . * X actually not a throw-in!
1291 * # # # */
1292 foreach_neighbor(b, to, {
1293 if (board_at(b, c) == S_NONE) {
1294 /* Is the empty neighbor an escape path? */
1295 /* (Note that one S_NONE neighbor is already @to.) */
1296 if (neighbor_count_at(b, c, stone_other(color))
1297 + neighbor_count_at(b, c, S_OFFBOARD) < 2)
1298 goto invalid_throwin;
1301 return false;
1304 /* Multi-stone throwin...? */
1305 assert(groupcts[color] == 1);
1306 group_t g = groupids[color][0];
1308 assert(board_group_info(b, g).libs <= 2);
1309 /* Suicide is definitely NOT ok, no matter what else
1310 * we could test. */
1311 if (board_group_info(b, g).libs == 1)
1312 return true;
1314 /* In that case, we must be connected to at most one stone,
1315 * or throwin will not destroy any eyes. */
1316 if (group_is_onestone(b, g))
1317 return false;
1318 invalid_throwin:;
1321 //fprintf(stderr, "no throw-in group\n");
1323 /* No way to pull out, no way to connect out. This really
1324 * is a bad self-atari! */
1325 return true;
1329 bool
1330 board_stone_radar(struct board *b, coord_t coord, int distance)
1332 int bounds[4] = {
1333 coord_x(coord, b) - distance,
1334 coord_y(coord, b) - distance,
1335 coord_x(coord, b) + distance,
1336 coord_y(coord, b) + distance
1338 for (int i = 0; i < 4; i++)
1339 if (bounds[i] < 1)
1340 bounds[i] = 1;
1341 else if (bounds[i] > board_size(b) - 2)
1342 bounds[i] = board_size(b) - 2;
1343 for (int x = bounds[0]; x <= bounds[2]; x++)
1344 for (int y = bounds[1]; y <= bounds[3]; y++)
1345 if (board_atxy(b, x, y) != S_NONE) {
1346 //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));
1347 return true;
1349 return false;