Moggy Patterns: Add block side cut
[pachi.git] / board.c
blobc712e7288c19ea62f77f02deddb85b5b209c207e
1 #include <alloca.h>
2 #include <assert.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 //#define DEBUG
9 #include "board.h"
10 #include "debug.h"
11 #include "mq.h"
12 #include "random.h"
14 #ifdef BOARD_SPATHASH
15 #include "patternsp.h"
16 #endif
17 #ifdef BOARD_PAT3
18 #include "pattern3.h"
19 #endif
20 #ifdef BOARD_TRAITS
21 static void board_trait_recompute(struct board *board, coord_t coord);
22 #include "tactics.h"
23 #endif
24 #ifdef BOARD_GAMMA
25 #include "pattern.h"
26 #endif
29 #if 0
30 #define profiling_noinline __attribute__((noinline))
31 #else
32 #define profiling_noinline
33 #endif
35 #define gi_granularity 4
36 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
39 static void
40 board_setup(struct board *b)
42 memset(b, 0, sizeof(*b));
44 struct move m = { pass, S_NONE };
45 b->last_move = b->last_move2 = b->last_ko = b->ko = m;
48 struct board *
49 board_init(void)
51 struct board *b = malloc2(sizeof(struct board));
52 board_setup(b);
54 // Default setup
55 b->size = 9 + 2;
56 board_clear(b);
58 return b;
61 static size_t
62 board_alloc(struct board *board)
64 /* We do not allocate the board structure itself but we allocate
65 * all the arrays with board contents. */
67 int bsize = board_size2(board) * sizeof(*board->b);
68 int gsize = board_size2(board) * sizeof(*board->g);
69 int fsize = board_size2(board) * sizeof(*board->f);
70 int nsize = board_size2(board) * sizeof(*board->n);
71 int psize = board_size2(board) * sizeof(*board->p);
72 int hsize = board_size2(board) * 2 * sizeof(*board->h);
73 int gisize = board_size2(board) * sizeof(*board->gi);
74 #ifdef WANT_BOARD_C
75 int csize = board_size2(board) * sizeof(*board->c);
76 #else
77 int csize = 0;
78 #endif
79 #ifdef BOARD_SPATHASH
80 int ssize = board_size2(board) * sizeof(*board->spathash);
81 #else
82 int ssize = 0;
83 #endif
84 #ifdef BOARD_PAT3
85 int p3size = board_size2(board) * sizeof(*board->pat3);
86 #else
87 int p3size = 0;
88 #endif
89 #ifdef BOARD_TRAITS
90 int tsize = board_size2(board) * sizeof(*board->t);
91 int tqsize = board_size2(board) * sizeof(*board->t);
92 #else
93 int tsize = 0;
94 int tqsize = 0;
95 #endif
96 #ifdef BOARD_GAMMA
97 int pbsize = board_size2(board) * sizeof(*board->prob[0].items);
98 int rowpbsize = board_size(board) * sizeof(*board->prob[0].rowtotals);
99 #else
100 int pbsize = 0;
101 int rowpbsize = 0;
102 #endif
103 int cdsize = board_size2(board) * sizeof(*board->coord);
105 size_t size = bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + (pbsize + rowpbsize) * 2 + cdsize;
106 void *x = malloc2(size);
108 /* board->b must come first */
109 board->b = x; x += bsize;
110 board->g = x; x += gsize;
111 board->f = x; x += fsize;
112 board->p = x; x += psize;
113 board->n = x; x += nsize;
114 board->h = x; x += hsize;
115 board->gi = x; x += gisize;
116 #ifdef WANT_BOARD_C
117 board->c = x; x += csize;
118 #endif
119 #ifdef BOARD_SPATHASH
120 board->spathash = x; x += ssize;
121 #endif
122 #ifdef BOARD_PAT3
123 board->pat3 = x; x += p3size;
124 #endif
125 #ifdef BOARD_TRAITS
126 board->t = x; x += tsize;
127 board->tq = x; x += tqsize;
128 #endif
129 #ifdef BOARD_GAMMA
130 board->prob[0].items = x; x += pbsize;
131 board->prob[1].items = x; x += pbsize;
132 board->prob[0].rowtotals = x; x += rowpbsize;
133 board->prob[1].rowtotals = x; x += rowpbsize;
134 #endif
135 board->coord = x; x += cdsize;
137 return size;
140 struct board *
141 board_copy(struct board *b2, struct board *b1)
143 memcpy(b2, b1, sizeof(struct board));
145 size_t size = board_alloc(b2);
146 memcpy(b2->b, b1->b, size);
148 return b2;
151 void
152 board_done_noalloc(struct board *board)
154 if (board->b) free(board->b);
157 void
158 board_done(struct board *board)
160 board_done_noalloc(board);
161 free(board);
164 void
165 board_resize(struct board *board, int size)
167 #ifdef BOARD_SIZE
168 assert(board_size(board) == size + 2);
169 #endif
170 assert(size <= BOARD_MAX_SIZE);
171 board->size = size + 2 /* S_OFFBOARD margin */;
172 board->size2 = board_size(board) * board_size(board);
174 board->bits2 = 1;
175 while ((1 << board->bits2) < board->size2) board->bits2++;
177 if (board->b)
178 free(board->b);
180 size_t asize = board_alloc(board);
181 memset(board->b, 0, asize);
184 void
185 board_clear(struct board *board)
187 int size = board_size(board);
188 float komi = board->komi;
190 board_done_noalloc(board);
191 board_setup(board);
192 board_resize(board, size - 2 /* S_OFFBOARD margin */);
194 board->komi = komi;
196 /* Setup neighborhood iterators */
197 board->nei8[0] = -size - 1; // (-1,-1)
198 board->nei8[1] = 1;
199 board->nei8[2] = 1;
200 board->nei8[3] = size - 2; // (-1,0)
201 board->nei8[4] = 2;
202 board->nei8[5] = size - 2; // (-1,1)
203 board->nei8[6] = 1;
204 board->nei8[7] = 1;
205 board->dnei[0] = -size - 1;
206 board->dnei[1] = 2;
207 board->dnei[2] = size*2 - 2;
208 board->dnei[3] = 2;
210 /* Setup initial symmetry */
211 board->symmetry.d = 1;
212 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
213 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
214 board->symmetry.type = SYM_FULL;
216 /* Set up coordinate cache */
217 foreach_point(board) {
218 board->coord[c][0] = c % board_size(board);
219 board->coord[c][1] = c / board_size(board);
220 } foreach_point_end;
222 /* Draw the offboard margin */
223 int top_row = board_size2(board) - board_size(board);
224 int i;
225 for (i = 0; i < board_size(board); i++)
226 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
227 for (i = 0; i <= top_row; i += board_size(board))
228 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
230 foreach_point(board) {
231 coord_t coord = c;
232 if (board_at(board, coord) == S_OFFBOARD)
233 continue;
234 foreach_neighbor(board, c, {
235 inc_neighbor_count_at(board, coord, board_at(board, c));
236 } );
237 } foreach_point_end;
239 /* All positions are free! Except the margin. */
240 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
241 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
242 board->f[board->flen++] = i;
244 /* Initialize zobrist hashtable. */
245 /* We will need these to be stable across Pachi runs for
246 * certain kinds of pattern matching, thus we do not use
247 * fast_random() for this. */
248 hash_t hseed = 0x3121110101112131;
249 foreach_point(board) {
250 board->h[c * 2] = (hseed *= 16807);
251 if (!board->h[c * 2])
252 board->h[c * 2] = 1;
253 /* And once again for white */
254 board->h[c * 2 + 1] = (hseed *= 16807);
255 if (!board->h[c * 2 + 1])
256 board->h[c * 2 + 1] = 1;
257 } foreach_point_end;
259 #ifdef BOARD_SPATHASH
260 /* Initialize spatial hashes. */
261 foreach_point(board) {
262 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
263 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
264 ptcoords_at(x, y, c, board, j);
265 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
266 pthashes[0][j][board_at(board, c)];
267 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
268 pthashes[0][j][stone_other(board_at(board, c))];
271 } foreach_point_end;
272 #endif
273 #ifdef BOARD_PAT3
274 /* Initialize 3x3 pattern codes. */
275 foreach_point(board) {
276 if (board_at(board, c) == S_NONE)
277 board->pat3[c] = pattern3_hash(board, c);
278 } foreach_point_end;
279 #endif
280 #ifdef BOARD_TRAITS
281 /* Initialize traits. */
282 foreach_point(board) {
283 trait_at(board, c, S_BLACK).cap = 0;
284 trait_at(board, c, S_BLACK).cap1 = 0;
285 trait_at(board, c, S_BLACK).safe = true;
286 trait_at(board, c, S_WHITE).cap = 0;
287 trait_at(board, c, S_WHITE).cap1 = 0;
288 trait_at(board, c, S_WHITE).safe = true;
289 } foreach_point_end;
290 #endif
291 #ifdef BOARD_GAMMA
292 board->prob[0].b = board->prob[1].b = board;
293 foreach_point(board) {
294 probdist_set(&board->prob[0], c, double_to_fixp((board_at(board, c) == S_NONE) * 1.0f));
295 probdist_set(&board->prob[1], c, double_to_fixp((board_at(board, c) == S_NONE) * 1.0f));
296 } foreach_point_end;
297 #endif
300 static char *
301 board_print_top(struct board *board, char *s, char *end, int c)
303 for (int i = 0; i < c; i++) {
304 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
305 s += snprintf(s, end - s, " ");
306 for (int x = 1; x < board_size(board) - 1; x++)
307 s += snprintf(s, end - s, "%c ", asdf[x - 1]);
308 s += snprintf(s, end -s, " ");
310 s += snprintf(s, end - s, "\n");
311 for (int i = 0; i < c; i++) {
312 s += snprintf(s, end - s, " +-");
313 for (int x = 1; x < board_size(board) - 1; x++)
314 s += snprintf(s, end - s, "--");
315 s += snprintf(s, end - s, "+");
317 s += snprintf(s, end - s, "\n");
318 return s;
321 static char *
322 board_print_bottom(struct board *board, char *s, char *end, int c)
324 for (int i = 0; i < c; i++) {
325 s += snprintf(s, end - s, " +-");
326 for (int x = 1; x < board_size(board) - 1; x++)
327 s += snprintf(s, end - s, "--");
328 s += snprintf(s, end - s, "+");
330 s += snprintf(s, end - s, "\n");
331 return s;
334 static char *
335 board_print_row(struct board *board, int y, char *s, char *end, board_cprint cprint)
337 s += snprintf(s, end - s, " %2d | ", y);
338 for (int x = 1; x < board_size(board) - 1; x++) {
339 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
340 s += snprintf(s, end - s, "%c)", stone2char(board_atxy(board, x, y)));
341 else
342 s += snprintf(s, end - s, "%c ", stone2char(board_atxy(board, x, y)));
344 s += snprintf(s, end - s, "|");
345 if (cprint) {
346 s += snprintf(s, end - s, " %2d | ", y);
347 for (int x = 1; x < board_size(board) - 1; x++) {
348 s = cprint(board, coord_xy(board, x, y), s, end);
350 s += snprintf(s, end - s, "|");
352 s += snprintf(s, end - s, "\n");
353 return s;
356 void
357 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
359 char buf[10240];
360 char *s = buf;
361 char *end = buf + sizeof(buf);
362 s += snprintf(s, end - s, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
363 board->moves, board->komi, board->handicap,
364 board->captures[S_BLACK], board->captures[S_WHITE]);
365 s = board_print_top(board, s, end, 1 + !!cprint);
366 for (int y = board_size(board) - 2; y >= 1; y--)
367 s = board_print_row(board, y, s, end, cprint);
368 board_print_bottom(board, s, end, 1 + !!cprint);
369 fprintf(f, "%s\n", buf);
372 static char *
373 cprint_group(struct board *board, coord_t c, char *s, char *end)
375 s += snprintf(s, end - s, "%d ", group_base(group_at(board, c)));
376 return s;
379 void
380 board_print(struct board *board, FILE *f)
382 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
385 void
386 board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari)
388 #ifdef BOARD_GAMMA
389 b->gamma = gamma;
390 b->precise_selfatari = precise_selfatari;
391 for (int i = 0; i < b->flen; i++) {
392 board_trait_recompute(b, b->f[i]);
394 #endif
398 /* Update the probability distribution we maintain incrementally. */
399 void
400 board_gamma_update(struct board *board, coord_t coord, enum stone color)
402 #ifdef BOARD_GAMMA
403 if (!board->gamma)
404 return;
406 /* Punch out invalid moves and moves filling our own eyes. */
407 if (board_at(board, coord) != S_NONE
408 || (board_is_eyelike(board, coord, stone_other(color))
409 && !trait_at(board, coord, color).cap)
410 || (board_is_one_point_eye(board, coord, color))) {
411 probdist_set(&board->prob[color - 1], coord, 0);
412 return;
415 hash3_t pat = board->pat3[coord];
416 if (color == S_WHITE) {
417 /* We work with the pattern3s as black-to-play. */
418 pat = pattern3_reverse(pat);
421 /* We just quickly replicate the general pattern matcher stuff
422 * here in the most bare-bone way. */
423 double value = board->gamma->gamma[FEAT_PATTERN3][pat];
424 if (trait_at(board, coord, color).cap) {
425 int i = 0;
426 i |= (trait_at(board, coord, color).cap1 == trait_at(board, coord, color).cap) << PF_CAPTURE_1STONE;
427 i |= (!trait_at(board, coord, stone_other(color)).safe) << PF_CAPTURE_TRAPPED;
428 i |= (trait_at(board, coord, color).cap < neighbor_count_at(board, coord, stone_other(color))) << PF_CAPTURE_CONNECTION;
429 value *= board->gamma->gamma[FEAT_CAPTURE][i];
431 if (trait_at(board, coord, stone_other(color)).cap) {
432 int i = 0;
433 i |= (trait_at(board, coord, stone_other(color)).cap1 == trait_at(board, coord, stone_other(color)).cap) << PF_AESCAPE_1STONE;
434 i |= (!trait_at(board, coord, color).safe) << PF_AESCAPE_TRAPPED;
435 i |= (trait_at(board, coord, stone_other(color)).cap < neighbor_count_at(board, coord, color)) << PF_AESCAPE_CONNECTION;
436 value *= board->gamma->gamma[FEAT_AESCAPE][i];
438 if (!trait_at(board, coord, color).safe)
439 value *= board->gamma->gamma[FEAT_SELFATARI][1 + board->precise_selfatari];
440 probdist_set(&board->prob[color - 1], coord, double_to_fixp(value));
441 #endif
444 #ifdef BOARD_TRAITS
445 static bool
446 board_trait_safe(struct board *board, coord_t coord, enum stone color)
448 if (board->precise_selfatari)
449 return !is_bad_selfatari(board, color, coord);
450 else
451 return board_safe_to_play(board, coord, color);
454 static void
455 board_trait_recompute(struct board *board, coord_t coord)
457 trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);;
458 trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
459 if (DEBUGL(8)) {
460 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d cap1=%d safe=%d) (white cap=%d cap1=%d safe=%d)\n",
461 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
462 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).cap1, trait_at(board, coord, S_BLACK).safe,
463 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).cap1, trait_at(board, coord, S_WHITE).safe);
465 board_gamma_update(board, coord, S_BLACK);
466 board_gamma_update(board, coord, S_WHITE);
468 #endif
470 /* Recompute traits for dirty points that we have previously touched
471 * somehow (libs of their neighbors changed or so). */
472 static void
473 board_traits_recompute(struct board *board)
475 #ifdef BOARD_TRAITS
476 for (int i = 0; i < board->tqlen; i++) {
477 coord_t coord = board->tq[i];
478 trait_at(board, coord, S_BLACK).dirty = false;
479 if (board_at(board, coord) != S_NONE)
480 continue;
481 board_trait_recompute(board, coord);
483 board->tqlen = 0;
484 #endif
487 /* Queue traits of given point for recomputing. */
488 static void
489 board_trait_queue(struct board *board, coord_t coord)
491 #ifdef BOARD_TRAITS
492 if (trait_at(board, coord, S_BLACK).dirty)
493 return;
494 board->tq[board->tqlen++] = coord;
495 trait_at(board, coord, S_BLACK).dirty = true;
496 #endif
500 /* Update board hash with given coordinate. */
501 static void profiling_noinline
502 board_hash_update(struct board *board, coord_t coord, enum stone color)
504 board->hash ^= hash_at(board, coord, color);
505 board->qhash[coord_quadrant(coord, board)] ^= hash_at(board, coord, color);
506 if (DEBUGL(8))
507 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);
509 #ifdef BOARD_SPATHASH
510 /* Gridcular metric is reflective, so we update all hashes
511 * of appropriate ditance in OUR circle. */
512 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
513 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
514 ptcoords_at(x, y, coord, board, j);
515 /* We either changed from S_NONE to color
516 * or vice versa; doesn't matter. */
517 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
518 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
519 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
520 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
523 #endif
525 #if defined(BOARD_PAT3)
526 /* @color is not what we need in case of capture. */
527 enum stone new_color = board_at(board, coord);
528 if (new_color == S_NONE)
529 board->pat3[coord] = pattern3_hash(board, coord);
530 foreach_8neighbor(board, coord) { // internally, the loop uses fn__i=[0..7]
531 if (board_at(board, c) != S_NONE)
532 continue;
533 board->pat3[c] &= ~(3 << (fn__i*2));
534 board->pat3[c] |= new_color << (fn__i*2);
535 #if 0
536 if (board_at(board, c) != S_OFFBOARD && pattern3_hash(board, c) != board->pat3[c]) {
537 board_print(board, stderr);
538 fprintf(stderr, "%s->%s %x != %x (%d-%d:%d)\n", coord2sstr(coord, board), coord2sstr(c, board), pattern3_hash(board, c), board->pat3[c], coord, c, fn__i);
539 assert(0);
541 #endif
542 board_trait_queue(board, c);
543 } foreach_8neighbor_end;
544 #endif
547 /* Commit current board hash to history. */
548 static void profiling_noinline
549 board_hash_commit(struct board *board)
551 if (DEBUGL(8))
552 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
553 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
554 board->history_hash[board->hash & history_hash_mask] = board->hash;
555 } else {
556 hash_t i = board->hash;
557 while (board->history_hash[i & history_hash_mask]) {
558 if (board->history_hash[i & history_hash_mask] == board->hash) {
559 if (DEBUGL(5))
560 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
561 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
562 board->superko_violation = true;
563 return;
565 i = history_hash_next(i);
567 board->history_hash[i & history_hash_mask] = board->hash;
572 void
573 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
575 if (likely(symmetry->type == SYM_NONE)) {
576 /* Fully degenerated already. We do not support detection
577 * of restoring of symmetry, assuming that this is too rare
578 * a case to handle. */
579 return;
582 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
583 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
584 if (DEBUGL(6)) {
585 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
586 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
587 symmetry->d, symmetry->type, x, y);
590 switch (symmetry->type) {
591 case SYM_FULL:
592 if (x == t && y == t) {
593 /* Tengen keeps full symmetry. */
594 return;
596 /* New symmetry now? */
597 if (x == y) {
598 symmetry->type = SYM_DIAG_UP;
599 symmetry->x1 = symmetry->y1 = 1;
600 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
601 symmetry->d = 1;
602 } else if (dx == y) {
603 symmetry->type = SYM_DIAG_DOWN;
604 symmetry->x1 = symmetry->y1 = 1;
605 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
606 symmetry->d = 1;
607 } else if (x == t) {
608 symmetry->type = SYM_HORIZ;
609 symmetry->y1 = 1;
610 symmetry->y2 = board_size(b) - 1;
611 symmetry->d = 0;
612 } else if (y == t) {
613 symmetry->type = SYM_VERT;
614 symmetry->x1 = 1;
615 symmetry->x2 = board_size(b) - 1;
616 symmetry->d = 0;
617 } else {
618 break_symmetry:
619 symmetry->type = SYM_NONE;
620 symmetry->x1 = symmetry->y1 = 1;
621 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
622 symmetry->d = 0;
624 break;
625 case SYM_DIAG_UP:
626 if (x == y)
627 return;
628 goto break_symmetry;
629 case SYM_DIAG_DOWN:
630 if (dx == y)
631 return;
632 goto break_symmetry;
633 case SYM_HORIZ:
634 if (x == t)
635 return;
636 goto break_symmetry;
637 case SYM_VERT:
638 if (y == t)
639 return;
640 goto break_symmetry;
641 case SYM_NONE:
642 assert(0);
643 break;
646 if (DEBUGL(6)) {
647 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
648 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
649 symmetry->d, symmetry->type);
651 /* Whew. */
655 void
656 board_handicap_stone(struct board *board, int x, int y, FILE *f)
658 struct move m;
659 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
661 board_play(board, &m);
662 /* Simulate white passing; otherwise, UCT search can get confused since
663 * tree depth parity won't match the color to move. */
664 board->moves++;
666 char *str = coord2str(m.coord, board);
667 if (DEBUGL(1))
668 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
669 if (f) fprintf(f, "%s ", str);
670 free(str);
673 void
674 board_handicap(struct board *board, int stones, FILE *f)
676 int margin = 3 + (board_size(board) >= 13);
677 int min = margin;
678 int mid = board_size(board) / 2;
679 int max = board_size(board) - 1 - margin;
680 const int places[][2] = {
681 { min, min }, { max, max }, { max, min }, { min, max },
682 { min, mid }, { max, mid },
683 { mid, min }, { mid, max },
684 { mid, mid },
687 board->handicap = stones;
689 if (stones == 5 || stones == 7) {
690 board_handicap_stone(board, mid, mid, f);
691 stones--;
694 int i;
695 for (i = 0; i < stones; i++)
696 board_handicap_stone(board, places[i][0], places[i][1], f);
700 static void __attribute__((noinline))
701 check_libs_consistency(struct board *board, group_t g)
703 #ifdef DEBUG
704 if (!g) return;
705 struct group *gi = &board_group_info(board, g);
706 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
707 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
708 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
709 assert(0);
711 #endif
714 static void
715 board_capturable_add(struct board *board, group_t group, coord_t lib, bool onestone)
717 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
718 #ifdef BOARD_TRAITS
719 /* Increase capturable count trait of my last lib. */
720 enum stone capturing_color = stone_other(board_at(board, group));
721 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
722 foreach_neighbor(board, lib, {
723 if (DEBUGL(8) && group_at(board, c) == group)
724 fprintf(stderr, "%s[%d] %s cap bump bc of %s(%d) member %s onestone %d\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap, stone2str(capturing_color), coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board), onestone);
725 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
726 trait_at(board, lib, capturing_color).cap1 += (group_at(board, c) == group && onestone);
728 board_trait_queue(board, lib);
729 #endif
731 #ifdef WANT_BOARD_C
732 /* Update the list of capturable groups. */
733 assert(group);
734 assert(board->clen < board_size2(board));
735 board->c[board->clen++] = group;
736 #endif
738 static void
739 board_capturable_rm(struct board *board, group_t group, coord_t lib, bool onestone)
741 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
742 #ifdef BOARD_TRAITS
743 /* Decrease capturable count trait of my previously-last lib. */
744 enum stone capturing_color = stone_other(board_at(board, group));
745 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
746 foreach_neighbor(board, lib, {
747 if (DEBUGL(8) && group_at(board, c) == group)
748 fprintf(stderr, "%s[%d] cap dump bc of %s(%d) member %s onestone %d\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap, coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board), onestone);
749 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
750 trait_at(board, lib, capturing_color).cap1 -= (group_at(board, c) == group && onestone);
752 board_trait_queue(board, lib);
753 #endif
755 #ifdef WANT_BOARD_C
756 /* Update the list of capturable groups. */
757 for (int i = 0; i < board->clen; i++) {
758 if (unlikely(board->c[i] == group)) {
759 board->c[i] = board->c[--board->clen];
760 return;
763 fprintf(stderr, "rm of bad group %d\n", group_base(group));
764 assert(0);
765 #endif
768 static void
769 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
771 #ifdef BOARD_TRAITS
772 board_trait_queue(board, lib1);
773 board_trait_queue(board, lib2);
774 #endif
776 static void
777 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
779 #ifdef BOARD_TRAITS
780 board_trait_queue(board, lib1);
781 board_trait_queue(board, lib2);
782 #endif
785 static void
786 board_group_addlib(struct board *board, group_t group, coord_t coord)
788 if (DEBUGL(7)) {
789 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
790 group_base(group), coord2sstr(group_base(group), board),
791 board_group_info(board, group).libs, coord2sstr(coord, board));
794 check_libs_consistency(board, group);
796 struct group *gi = &board_group_info(board, group);
797 bool onestone = group_is_onestone(board, group);
798 if (gi->libs < GROUP_KEEP_LIBS) {
799 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
800 #if 0
801 /* Seems extra branch just slows it down */
802 if (!gi->lib[i])
803 break;
804 #endif
805 if (unlikely(gi->lib[i] == coord))
806 return;
808 if (gi->libs == 0) {
809 board_capturable_add(board, group, coord, onestone);
810 } else if (gi->libs == 1) {
811 board_capturable_rm(board, group, gi->lib[0], onestone);
812 board_atariable_add(board, group, gi->lib[0], coord);
813 } else if (gi->libs == 2) {
814 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
816 gi->lib[gi->libs++] = coord;
819 check_libs_consistency(board, group);
822 static void
823 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
825 /* Add extra liberty from the board to our liberty list. */
826 unsigned char watermark[board_size2(board) / 8];
827 memset(watermark, 0, sizeof(watermark));
828 #define watermark_get(c) (watermark[c >> 3] & (1 << (c & 7)))
829 #define watermark_set(c) watermark[c >> 3] |= (1 << (c & 7))
831 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
832 watermark_set(gi->lib[i]);
833 watermark_set(avoid);
835 foreach_in_group(board, group) {
836 coord_t coord2 = c;
837 foreach_neighbor(board, coord2, {
838 if (board_at(board, c) + watermark_get(c) != S_NONE)
839 continue;
840 watermark_set(c);
841 gi->lib[gi->libs++] = c;
842 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
843 return;
844 } );
845 } foreach_in_group_end;
846 #undef watermark_get
847 #undef watermark_set
850 static void
851 board_group_rmlib(struct board *board, group_t group, coord_t coord)
853 if (DEBUGL(7)) {
854 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
855 group_base(group), coord2sstr(group_base(group), board),
856 board_group_info(board, group).libs, coord2sstr(coord, board));
859 struct group *gi = &board_group_info(board, group);
860 bool onestone = group_is_onestone(board, group);
861 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
862 #if 0
863 /* Seems extra branch just slows it down */
864 if (!gi->lib[i])
865 break;
866 #endif
867 if (likely(gi->lib[i] != coord))
868 continue;
870 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
871 gi->lib[gi->libs] = 0;
873 check_libs_consistency(board, group);
875 /* Postpone refilling lib[] until we need to. */
876 assert(GROUP_REFILL_LIBS > 1);
877 if (gi->libs > GROUP_REFILL_LIBS)
878 return;
879 if (gi->libs == GROUP_REFILL_LIBS)
880 board_group_find_extra_libs(board, group, gi, coord);
882 if (gi->libs == 2) {
883 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
884 } else if (gi->libs == 1) {
885 board_capturable_add(board, group, gi->lib[0], onestone);
886 board_atariable_rm(board, group, gi->lib[0], lib);
887 } else if (gi->libs == 0)
888 board_capturable_rm(board, group, lib, onestone);
889 return;
892 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
893 * can call this multiple times per coord. */
894 check_libs_consistency(board, group);
895 return;
899 /* This is a low-level routine that doesn't maintain consistency
900 * of all the board data structures. */
901 static void
902 board_remove_stone(struct board *board, group_t group, coord_t c)
904 enum stone color = board_at(board, c);
905 board_at(board, c) = S_NONE;
906 group_at(board, c) = 0;
907 board_hash_update(board, c, color);
908 #ifdef BOARD_TRAITS
909 /* We mark as cannot-capture now. If this is a ko/snapback,
910 * we will get incremented later in board_group_addlib(). */
911 trait_at(board, c, S_BLACK).cap = trait_at(board, c, S_BLACK).cap1 = 0;
912 trait_at(board, c, S_WHITE).cap = trait_at(board, c, S_WHITE).cap1 = 0;
913 board_trait_queue(board, c);
914 #endif
916 /* Increase liberties of surrounding groups */
917 coord_t coord = c;
918 foreach_neighbor(board, coord, {
919 dec_neighbor_count_at(board, c, color);
920 board_trait_queue(board, c);
921 group_t g = group_at(board, c);
922 if (g && g != group)
923 board_group_addlib(board, g, coord);
926 if (DEBUGL(6))
927 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
928 board->f[board->flen++] = c;
931 static int profiling_noinline
932 board_group_capture(struct board *board, group_t group)
934 int stones = 0;
936 foreach_in_group(board, group) {
937 board->captures[stone_other(board_at(board, c))]++;
938 board_remove_stone(board, group, c);
939 stones++;
940 } foreach_in_group_end;
942 struct group *gi = &board_group_info(board, group);
943 assert(gi->libs == 0);
944 memset(gi, 0, sizeof(*gi));
946 return stones;
950 static void profiling_noinline
951 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
953 #ifdef BOARD_TRAITS
954 struct group *gi = &board_group_info(board, group);
955 bool onestone = group_is_onestone(board, group);
957 if (gi->libs == 1) {
958 /* Our group is temporarily in atari; make sure the capturable
959 * counts also correspond to the newly added stone before we
960 * start adding liberties again so bump-dump ops match. */
961 enum stone capturing_color = stone_other(board_at(board, group));
962 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
964 coord_t lib = board_group_info(board, group).lib[0];
965 if (coord_is_adjecent(lib, coord, board)) {
966 if (DEBUGL(8))
967 fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
968 trait_at(board, lib, capturing_color).cap++;
969 /* This is never a 1-stone group, obviously. */
970 board_trait_queue(board, lib);
973 if (onestone) {
974 /* We are not 1-stone group anymore, update the cap1
975 * counter specifically. */
976 foreach_neighbor(board, group, {
977 if (board_at(board, c) != S_NONE) continue;
978 trait_at(board, c, capturing_color).cap1--;
979 board_trait_queue(board, c);
983 #endif
985 group_at(board, coord) = group;
986 groupnext_at(board, coord) = groupnext_at(board, prevstone);
987 groupnext_at(board, prevstone) = coord;
989 foreach_neighbor(board, coord, {
990 if (board_at(board, c) == S_NONE)
991 board_group_addlib(board, group, c);
994 if (DEBUGL(8))
995 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
996 coord_x(prevstone, board), coord_y(prevstone, board),
997 coord_x(coord, board), coord_y(coord, board),
998 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
999 group_base(group));
1002 static void profiling_noinline
1003 merge_groups(struct board *board, group_t group_to, group_t group_from)
1005 if (DEBUGL(7))
1006 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
1007 group_base(group_from), group_base(group_to));
1008 struct group *gi_from = &board_group_info(board, group_from);
1009 struct group *gi_to = &board_group_info(board, group_to);
1010 bool onestone_from = group_is_onestone(board, group_from);
1011 bool onestone_to = group_is_onestone(board, group_to);
1013 /* We do this early before the group info is rewritten. */
1014 if (gi_from->libs == 2)
1015 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1016 else if (gi_from->libs == 1)
1017 board_capturable_rm(board, group_from, gi_from->lib[0], onestone_from);
1019 if (DEBUGL(7))
1020 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1022 if (gi_to->libs < GROUP_KEEP_LIBS) {
1023 for (int i = 0; i < gi_from->libs; i++) {
1024 for (int j = 0; j < gi_to->libs; j++)
1025 if (gi_to->lib[j] == gi_from->lib[i])
1026 goto next_from_lib;
1027 if (gi_to->libs == 0) {
1028 board_capturable_add(board, group_to, gi_from->lib[i], onestone_to);
1029 } else if (gi_to->libs == 1) {
1030 board_capturable_rm(board, group_to, gi_to->lib[0], onestone_to);
1031 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1032 } else if (gi_to->libs == 2) {
1033 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1035 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1036 if (gi_to->libs >= GROUP_KEEP_LIBS)
1037 break;
1038 next_from_lib:;
1042 #ifdef BOARD_TRAITS
1043 if (gi_to->libs == 1) {
1044 enum stone capturing_color = stone_other(board_at(board, group_to));
1045 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1047 /* Our group is currently in atari; make sure we properly
1048 * count in even the neighbors from the other group in the
1049 * capturable counter. */
1050 coord_t lib = board_group_info(board, group_to).lib[0];
1051 foreach_neighbor(board, lib, {
1052 if (DEBUGL(8) && group_at(board, c) == group_from)
1053 fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1054 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1055 /* This is never a 1-stone group, obviously. */
1057 board_trait_queue(board, lib);
1059 if (onestone_to) {
1060 /* We are not 1-stone group anymore, update the cap1
1061 * counter specifically. */
1062 foreach_neighbor(board, group_to, {
1063 if (board_at(board, c) != S_NONE) continue;
1064 trait_at(board, c, capturing_color).cap1--;
1065 board_trait_queue(board, c);
1069 #endif
1071 coord_t last_in_group;
1072 foreach_in_group(board, group_from) {
1073 last_in_group = c;
1074 group_at(board, c) = group_to;
1075 } foreach_in_group_end;
1076 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1077 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1078 memset(gi_from, 0, sizeof(struct group));
1080 if (DEBUGL(7))
1081 fprintf(stderr, "board_play_raw: merged group: %d\n",
1082 group_base(group_to));
1085 static group_t profiling_noinline
1086 new_group(struct board *board, coord_t coord)
1088 group_t group = coord;
1089 struct group *gi = &board_group_info(board, group);
1090 foreach_neighbor(board, coord, {
1091 if (board_at(board, c) == S_NONE)
1092 /* board_group_addlib is ridiculously expensive for us */
1093 #if GROUP_KEEP_LIBS < 4
1094 if (gi->libs < GROUP_KEEP_LIBS)
1095 #endif
1096 gi->lib[gi->libs++] = c;
1099 group_at(board, coord) = group;
1100 groupnext_at(board, coord) = 0;
1102 if (gi->libs == 2)
1103 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1104 else if (gi->libs == 1)
1105 board_capturable_add(board, group, gi->lib[0], true);
1106 check_libs_consistency(board, group);
1108 if (DEBUGL(8))
1109 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1110 coord_x(coord, board), coord_y(coord, board),
1111 group_base(group));
1113 return group;
1116 static inline group_t
1117 play_one_neighbor(struct board *board,
1118 coord_t coord, enum stone color, enum stone other_color,
1119 coord_t c, group_t group)
1121 enum stone ncolor = board_at(board, c);
1122 group_t ngroup = group_at(board, c);
1124 inc_neighbor_count_at(board, c, color);
1125 /* We can be S_NONE, in that case we need to update the safety
1126 * trait since we might be left with only one liberty. */
1127 board_trait_queue(board, c);
1129 if (!ngroup)
1130 return group;
1132 board_group_rmlib(board, ngroup, coord);
1133 if (DEBUGL(7))
1134 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1135 group_base(ngroup), ncolor, color, other_color);
1137 if (ncolor == color && ngroup != group) {
1138 if (!group) {
1139 group = ngroup;
1140 add_to_group(board, group, c, coord);
1141 } else {
1142 merge_groups(board, group, ngroup);
1144 } else if (ncolor == other_color) {
1145 if (DEBUGL(8)) {
1146 struct group *gi = &board_group_info(board, ngroup);
1147 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1148 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1149 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1150 fprintf(stderr, "\n");
1152 if (unlikely(board_group_captured(board, ngroup)))
1153 board_group_capture(board, ngroup);
1155 return group;
1158 /* We played on a place with at least one liberty. We will become a member of
1159 * some group for sure. */
1160 static group_t profiling_noinline
1161 board_play_outside(struct board *board, struct move *m, int f)
1163 coord_t coord = m->coord;
1164 enum stone color = m->color;
1165 enum stone other_color = stone_other(color);
1166 group_t group = 0;
1168 board->f[f] = board->f[--board->flen];
1169 if (DEBUGL(6))
1170 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1172 #if defined(BOARD_TRAITS) && defined(DEBUG)
1173 /* Sanity check that cap matches reality. */
1175 int a = 0, b = 0;
1176 foreach_neighbor(board, coord, {
1177 group_t g = group_at(board, c);
1178 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1179 b += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1) && group_is_onestone(board, g);
1181 assert(a == trait_at(board, coord, color).cap);
1182 assert(b == trait_at(board, coord, color).cap1);
1183 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1185 #endif
1186 foreach_neighbor(board, coord, {
1187 group = play_one_neighbor(board, coord, color, other_color, c, group);
1190 board_at(board, coord) = color;
1191 if (unlikely(!group))
1192 group = new_group(board, coord);
1193 board_gamma_update(board, coord, S_BLACK);
1194 board_gamma_update(board, coord, S_WHITE);
1196 board->last_move2 = board->last_move;
1197 board->last_move = *m;
1198 board->moves++;
1199 board_hash_update(board, coord, color);
1200 board_symmetry_update(board, &board->symmetry, coord);
1201 struct move ko = { pass, S_NONE };
1202 board->ko = ko;
1204 return group;
1207 /* We played in an eye-like shape. Either we capture at least one of the eye
1208 * sides in the process of playing, or return -1. */
1209 static int profiling_noinline
1210 board_play_in_eye(struct board *board, struct move *m, int f)
1212 coord_t coord = m->coord;
1213 enum stone color = m->color;
1214 /* Check ko: Capture at a position of ko capture one move ago */
1215 if (unlikely(color == board->ko.color && coord == board->ko.coord)) {
1216 if (DEBUGL(5))
1217 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1218 return -1;
1219 } else if (DEBUGL(6)) {
1220 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1221 color, coord_x(coord, board), coord_y(coord, board),
1222 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1225 struct move ko = { pass, S_NONE };
1227 int captured_groups = 0;
1229 foreach_neighbor(board, coord, {
1230 group_t g = group_at(board, c);
1231 if (DEBUGL(7))
1232 fprintf(stderr, "board_check: group %d has %d libs\n",
1233 g, board_group_info(board, g).libs);
1234 captured_groups += (board_group_info(board, g).libs == 1);
1237 if (likely(captured_groups == 0)) {
1238 if (DEBUGL(5)) {
1239 if (DEBUGL(6))
1240 board_print(board, stderr);
1241 fprintf(stderr, "board_check: one-stone suicide\n");
1244 return -1;
1246 #ifdef BOARD_TRAITS
1247 /* We _will_ for sure capture something. */
1248 assert(trait_at(board, coord, color).cap > 0);
1249 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1250 #endif
1252 board->f[f] = board->f[--board->flen];
1253 if (DEBUGL(6))
1254 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1256 foreach_neighbor(board, coord, {
1257 inc_neighbor_count_at(board, c, color);
1258 /* Originally, this could not have changed any trait
1259 * since no neighbors were S_NONE, however by now some
1260 * of them might be removed from the board. */
1261 board_trait_queue(board, c);
1263 group_t group = group_at(board, c);
1264 if (!group)
1265 continue;
1267 board_group_rmlib(board, group, coord);
1268 if (DEBUGL(7))
1269 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1270 group_base(group));
1272 if (board_group_captured(board, group)) {
1273 if (board_group_capture(board, group) == 1) {
1274 /* If we captured multiple groups at once,
1275 * we can't be fighting ko so we don't need
1276 * to check for that. */
1277 ko.color = stone_other(color);
1278 ko.coord = c;
1279 board->last_ko = ko;
1280 board->last_ko_age = board->moves;
1281 if (DEBUGL(5))
1282 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1287 board_at(board, coord) = color;
1288 group_t group = new_group(board, coord);
1289 board_gamma_update(board, coord, S_BLACK);
1290 board_gamma_update(board, coord, S_WHITE);
1292 board->last_move2 = board->last_move;
1293 board->last_move = *m;
1294 board->moves++;
1295 board_hash_update(board, coord, color);
1296 board_hash_commit(board);
1297 board_traits_recompute(board);
1298 board_symmetry_update(board, &board->symmetry, coord);
1299 board->ko = ko;
1301 return !!group;
1304 static int __attribute__((flatten))
1305 board_play_f(struct board *board, struct move *m, int f)
1307 if (DEBUGL(7)) {
1308 fprintf(stderr, "board_play(%s): ---- Playing %d,%d\n", coord2sstr(m->coord, board), coord_x(m->coord, board), coord_y(m->coord, board));
1310 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1311 /* NOT playing in an eye. Thus this move has to succeed. (This
1312 * is thanks to New Zealand rules. Otherwise, multi-stone
1313 * suicide might fail.) */
1314 group_t group = board_play_outside(board, m, f);
1315 if (unlikely(board_group_captured(board, group))) {
1316 board_group_capture(board, group);
1318 board_hash_commit(board);
1319 board_traits_recompute(board);
1320 return 0;
1321 } else {
1322 return board_play_in_eye(board, m, f);
1327 board_play(struct board *board, struct move *m)
1329 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1330 struct move nomove = { pass, S_NONE };
1331 board->ko = nomove;
1332 board->last_move2 = board->last_move;
1333 board->last_move = *m;
1334 return 0;
1337 int f;
1338 for (f = 0; f < board->flen; f++)
1339 if (board->f[f] == m->coord)
1340 return board_play_f(board, m, f);
1342 if (DEBUGL(7))
1343 fprintf(stderr, "board_check: stone exists\n");
1344 return -1;
1348 static inline bool
1349 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1351 *coord = b->f[f];
1352 struct move m = { *coord, color };
1353 if (DEBUGL(6))
1354 fprintf(stderr, "trying random move %d: %d,%d %s %d\n", f, coord_x(*coord, b), coord_y(*coord, b), coord2sstr(*coord, b), board_is_valid_move(b, &m));
1355 if (unlikely(board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1356 || !board_is_valid_move(b, &m)
1357 || (permit && !permit(permit_data, b, &m)))
1358 return false;
1359 if (m.coord == *coord) {
1360 return likely(board_play_f(b, &m, f) >= 0);
1361 } else {
1362 *coord = m.coord; // permit modified the coordinate
1363 return likely(board_play(b, &m) >= 0);
1367 void
1368 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1370 if (unlikely(b->flen == 0))
1371 goto pass;
1373 int base = fast_random(b->flen), f;
1374 for (f = base; f < b->flen; f++)
1375 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1376 return;
1377 for (f = 0; f < base; f++)
1378 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1379 return;
1381 pass:
1382 *coord = pass;
1383 struct move m = { pass, color };
1384 board_play(b, &m);
1388 bool
1389 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1391 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1393 /* XXX: We attempt false eye detection but we will yield false
1394 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1396 foreach_diag_neighbor(board, coord) {
1397 color_diag_libs[(enum stone) board_at(board, c)]++;
1398 } foreach_diag_neighbor_end;
1399 /* For false eye, we need two enemy stones diagonally in the
1400 * middle of the board, or just one enemy stone at the edge
1401 * or in the corner. */
1402 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1403 return color_diag_libs[stone_other(eye_color)] >= 2;
1406 bool
1407 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1409 return board_is_eyelike(board, coord, eye_color)
1410 && !board_is_false_eyelike(board, coord, eye_color);
1413 enum stone
1414 board_get_one_point_eye(struct board *board, coord_t coord)
1416 if (board_is_one_point_eye(board, coord, S_WHITE))
1417 return S_WHITE;
1418 else if (board_is_one_point_eye(board, coord, S_BLACK))
1419 return S_BLACK;
1420 else
1421 return S_NONE;
1425 float
1426 board_fast_score(struct board *board)
1428 int scores[S_MAX];
1429 memset(scores, 0, sizeof(scores));
1431 foreach_point(board) {
1432 enum stone color = board_at(board, c);
1433 if (color == S_NONE)
1434 color = board_get_one_point_eye(board, c);
1435 scores[color]++;
1436 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1437 } foreach_point_end;
1439 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1442 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1444 /* One flood-fill iteration; returns true if next iteration
1445 * is required. */
1446 static bool
1447 board_tromp_taylor_iter(struct board *board, int *ownermap)
1449 bool needs_update = false;
1450 foreach_free_point(board) {
1451 /* Ignore occupied and already-dame positions. */
1452 assert(board_at(board, c) == S_NONE);
1453 if (ownermap[c] == 3)
1454 continue;
1455 /* Count neighbors. */
1456 int nei[4] = {0};
1457 foreach_neighbor(board, c, {
1458 nei[ownermap[c]]++;
1460 /* If we have neighbors of both colors, or dame,
1461 * we are dame too. */
1462 if ((nei[1] && nei[2]) || nei[3]) {
1463 ownermap[c] = 3;
1464 /* Speed up the propagation. */
1465 foreach_neighbor(board, c, {
1466 if (board_at(board, c) == S_NONE)
1467 ownermap[c] = 3;
1469 needs_update = true;
1470 continue;
1472 /* If we have neighbors of one color, we are owned
1473 * by that color, too. */
1474 if (!ownermap[c] && (nei[1] || nei[2])) {
1475 int newowner = nei[1] ? 1 : 2;
1476 ownermap[c] = newowner;
1477 /* Speed up the propagation. */
1478 foreach_neighbor(board, c, {
1479 if (board_at(board, c) == S_NONE && !ownermap[c])
1480 ownermap[c] = newowner;
1482 needs_update = true;
1483 continue;
1485 } foreach_free_point_end;
1486 return needs_update;
1489 /* Tromp-Taylor Counting */
1490 float
1491 board_official_score(struct board *board, struct move_queue *q)
1494 /* A point P, not colored C, is said to reach C, if there is a path of
1495 * (vertically or horizontally) adjacent points of P's color from P to
1496 * a point of color C.
1498 * A player's score is the number of points of her color, plus the
1499 * number of empty points that reach only her color. */
1501 int ownermap[board_size2(board)];
1502 int s[4] = {0};
1503 const int o[4] = {0, 1, 2, 0};
1504 foreach_point(board) {
1505 ownermap[c] = o[board_at(board, c)];
1506 s[board_at(board, c)]++;
1507 } foreach_point_end;
1509 if (q) {
1510 /* Process dead groups. */
1511 for (unsigned int i = 0; i < q->moves; i++) {
1512 foreach_in_group(board, q->move[i]) {
1513 enum stone color = board_at(board, c);
1514 ownermap[c] = o[stone_other(color)];
1515 s[color]--; s[stone_other(color)]++;
1516 } foreach_in_group_end;
1520 /* We need to special-case empty board. */
1521 if (!s[S_BLACK] && !s[S_WHITE])
1522 return board->komi + board->handicap;
1524 while (board_tromp_taylor_iter(board, ownermap))
1525 /* Flood-fill... */;
1527 int scores[S_MAX];
1528 memset(scores, 0, sizeof(scores));
1530 foreach_point(board) {
1531 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1532 if (ownermap[c] == 3)
1533 continue;
1534 scores[ownermap[c]]++;
1535 } foreach_point_end;
1537 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];