Moggy: More detailed initial description
[pachi.git] / board.c
blob370183cf45fdda644a6169db57e28c690f044fc9
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/selfatari.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 #ifdef BOARD_TRAITS
392 for (int i = 0; i < b->flen; i++) {
393 board_trait_recompute(b, b->f[i]);
395 #endif
396 #endif
400 /* Update the probability distribution we maintain incrementally. */
401 void
402 board_gamma_update(struct board *board, coord_t coord, enum stone color)
404 #if defined(BOARD_GAMMA) && defined(BOARD_TRAITS)
405 if (!board->gamma)
406 return;
408 /* Punch out invalid moves and moves filling our own eyes. */
409 if (board_at(board, coord) != S_NONE
410 || (board_is_eyelike(board, coord, stone_other(color))
411 && !trait_at(board, coord, color).cap)
412 || (board_is_one_point_eye(board, coord, color))) {
413 probdist_set(&board->prob[color - 1], coord, 0);
414 return;
417 hash3_t pat = board->pat3[coord];
418 if (color == S_WHITE) {
419 /* We work with the pattern3s as black-to-play. */
420 pat = pattern3_reverse(pat);
423 /* We just quickly replicate the general pattern matcher stuff
424 * here in the most bare-bone way. */
425 double value = board->gamma->gamma[FEAT_PATTERN3][pat];
426 if (trait_at(board, coord, color).cap) {
427 int i = 0;
428 i |= (trait_at(board, coord, color).cap1 == trait_at(board, coord, color).cap) << PF_CAPTURE_1STONE;
429 i |= (!trait_at(board, coord, stone_other(color)).safe) << PF_CAPTURE_TRAPPED;
430 i |= (trait_at(board, coord, color).cap < neighbor_count_at(board, coord, stone_other(color))) << PF_CAPTURE_CONNECTION;
431 value *= board->gamma->gamma[FEAT_CAPTURE][i];
433 if (trait_at(board, coord, stone_other(color)).cap) {
434 int i = 0;
435 i |= (trait_at(board, coord, stone_other(color)).cap1 == trait_at(board, coord, stone_other(color)).cap) << PF_AESCAPE_1STONE;
436 i |= (!trait_at(board, coord, color).safe) << PF_AESCAPE_TRAPPED;
437 i |= (trait_at(board, coord, stone_other(color)).cap < neighbor_count_at(board, coord, color)) << PF_AESCAPE_CONNECTION;
438 value *= board->gamma->gamma[FEAT_AESCAPE][i];
440 if (!trait_at(board, coord, color).safe)
441 value *= board->gamma->gamma[FEAT_SELFATARI][1 + board->precise_selfatari];
442 probdist_set(&board->prob[color - 1], coord, double_to_fixp(value));
443 #endif
446 #ifdef BOARD_TRAITS
447 static bool
448 board_trait_safe(struct board *board, coord_t coord, enum stone color)
450 if (board->precise_selfatari)
451 return !is_bad_selfatari(board, color, coord);
452 else
453 return board_safe_to_play(board, coord, color);
456 static void
457 board_trait_recompute(struct board *board, coord_t coord)
459 trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);;
460 trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
461 if (DEBUGL(8)) {
462 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d cap1=%d safe=%d) (white cap=%d cap1=%d safe=%d)\n",
463 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
464 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).cap1, trait_at(board, coord, S_BLACK).safe,
465 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).cap1, trait_at(board, coord, S_WHITE).safe);
467 board_gamma_update(board, coord, S_BLACK);
468 board_gamma_update(board, coord, S_WHITE);
470 #endif
472 /* Recompute traits for dirty points that we have previously touched
473 * somehow (libs of their neighbors changed or so). */
474 static void
475 board_traits_recompute(struct board *board)
477 #ifdef BOARD_TRAITS
478 for (int i = 0; i < board->tqlen; i++) {
479 coord_t coord = board->tq[i];
480 trait_at(board, coord, S_BLACK).dirty = false;
481 if (board_at(board, coord) != S_NONE)
482 continue;
483 board_trait_recompute(board, coord);
485 board->tqlen = 0;
486 #endif
489 /* Queue traits of given point for recomputing. */
490 static void
491 board_trait_queue(struct board *board, coord_t coord)
493 #ifdef BOARD_TRAITS
494 if (trait_at(board, coord, S_BLACK).dirty)
495 return;
496 board->tq[board->tqlen++] = coord;
497 trait_at(board, coord, S_BLACK).dirty = true;
498 #endif
502 /* Update board hash with given coordinate. */
503 static void profiling_noinline
504 board_hash_update(struct board *board, coord_t coord, enum stone color)
506 board->hash ^= hash_at(board, coord, color);
507 board->qhash[coord_quadrant(coord, board)] ^= hash_at(board, coord, color);
508 if (DEBUGL(8))
509 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);
511 #ifdef BOARD_SPATHASH
512 /* Gridcular metric is reflective, so we update all hashes
513 * of appropriate ditance in OUR circle. */
514 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
515 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
516 ptcoords_at(x, y, coord, board, j);
517 /* We either changed from S_NONE to color
518 * or vice versa; doesn't matter. */
519 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
520 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
521 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
522 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
525 #endif
527 #if defined(BOARD_PAT3)
528 /* @color is not what we need in case of capture. */
529 static const int ataribits[8] = { -1, 0, -1, 1, 2, -1, 3, -1 };
530 enum stone new_color = board_at(board, coord);
531 bool in_atari = false;
532 if (new_color == S_NONE) {
533 board->pat3[coord] = pattern3_hash(board, coord);
534 } else {
535 in_atari = (board_group_info(board, group_at(board, coord)).libs == 1);
537 foreach_8neighbor(board, coord) {
538 /* Internally, the loop uses fn__i=[0..7]. We can use
539 * it directly to address bits within the bitmap of the
540 * neighbors since the bitmap order is reverse to the
541 * loop order. */
542 if (board_at(board, c) != S_NONE)
543 continue;
544 board->pat3[c] &= ~(3 << (fn__i*2));
545 board->pat3[c] |= new_color << (fn__i*2);
546 if (ataribits[fn__i] >= 0) {
547 board->pat3[c] &= ~(1 << (16 + ataribits[fn__i]));
548 board->pat3[c] |= in_atari << (16 + ataribits[fn__i]);
550 #if defined(BOARD_TRAITS)
551 board_trait_queue(board, c);
552 #elif defined(BOARD_GAMMA)
553 if (board->gamma) {
554 hash3_t pat = board->pat3[c];
555 if (color == S_WHITE) pat = pattern3_reverse(pat);
556 double value = board->gamma->gamma[FEAT_PATTERN3][pat];
557 probdist_set(&board->prob[color - 1], c, double_to_fixp(value));
559 #endif
560 } foreach_8neighbor_end;
561 #endif
564 /* Commit current board hash to history. */
565 static void profiling_noinline
566 board_hash_commit(struct board *board)
568 if (DEBUGL(8))
569 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
570 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
571 board->history_hash[board->hash & history_hash_mask] = board->hash;
572 } else {
573 hash_t i = board->hash;
574 while (board->history_hash[i & history_hash_mask]) {
575 if (board->history_hash[i & history_hash_mask] == board->hash) {
576 if (DEBUGL(5))
577 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
578 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
579 board->superko_violation = true;
580 return;
582 i = history_hash_next(i);
584 board->history_hash[i & history_hash_mask] = board->hash;
589 void
590 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
592 if (likely(symmetry->type == SYM_NONE)) {
593 /* Fully degenerated already. We do not support detection
594 * of restoring of symmetry, assuming that this is too rare
595 * a case to handle. */
596 return;
599 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
600 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
601 if (DEBUGL(6)) {
602 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
603 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
604 symmetry->d, symmetry->type, x, y);
607 switch (symmetry->type) {
608 case SYM_FULL:
609 if (x == t && y == t) {
610 /* Tengen keeps full symmetry. */
611 return;
613 /* New symmetry now? */
614 if (x == y) {
615 symmetry->type = SYM_DIAG_UP;
616 symmetry->x1 = symmetry->y1 = 1;
617 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
618 symmetry->d = 1;
619 } else if (dx == y) {
620 symmetry->type = SYM_DIAG_DOWN;
621 symmetry->x1 = symmetry->y1 = 1;
622 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
623 symmetry->d = 1;
624 } else if (x == t) {
625 symmetry->type = SYM_HORIZ;
626 symmetry->y1 = 1;
627 symmetry->y2 = board_size(b) - 1;
628 symmetry->d = 0;
629 } else if (y == t) {
630 symmetry->type = SYM_VERT;
631 symmetry->x1 = 1;
632 symmetry->x2 = board_size(b) - 1;
633 symmetry->d = 0;
634 } else {
635 break_symmetry:
636 symmetry->type = SYM_NONE;
637 symmetry->x1 = symmetry->y1 = 1;
638 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
639 symmetry->d = 0;
641 break;
642 case SYM_DIAG_UP:
643 if (x == y)
644 return;
645 goto break_symmetry;
646 case SYM_DIAG_DOWN:
647 if (dx == y)
648 return;
649 goto break_symmetry;
650 case SYM_HORIZ:
651 if (x == t)
652 return;
653 goto break_symmetry;
654 case SYM_VERT:
655 if (y == t)
656 return;
657 goto break_symmetry;
658 case SYM_NONE:
659 assert(0);
660 break;
663 if (DEBUGL(6)) {
664 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
665 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
666 symmetry->d, symmetry->type);
668 /* Whew. */
672 void
673 board_handicap_stone(struct board *board, int x, int y, FILE *f)
675 struct move m;
676 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
678 board_play(board, &m);
679 /* Simulate white passing; otherwise, UCT search can get confused since
680 * tree depth parity won't match the color to move. */
681 board->moves++;
683 char *str = coord2str(m.coord, board);
684 if (DEBUGL(1))
685 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
686 if (f) fprintf(f, "%s ", str);
687 free(str);
690 void
691 board_handicap(struct board *board, int stones, FILE *f)
693 int margin = 3 + (board_size(board) >= 13);
694 int min = margin;
695 int mid = board_size(board) / 2;
696 int max = board_size(board) - 1 - margin;
697 const int places[][2] = {
698 { min, min }, { max, max }, { max, min }, { min, max },
699 { min, mid }, { max, mid },
700 { mid, min }, { mid, max },
701 { mid, mid },
704 board->handicap = stones;
706 if (stones == 5 || stones == 7) {
707 board_handicap_stone(board, mid, mid, f);
708 stones--;
711 int i;
712 for (i = 0; i < stones; i++)
713 board_handicap_stone(board, places[i][0], places[i][1], f);
717 static void __attribute__((noinline))
718 check_libs_consistency(struct board *board, group_t g)
720 #ifdef DEBUG
721 if (!g) return;
722 struct group *gi = &board_group_info(board, g);
723 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
724 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
725 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
726 assert(0);
728 #endif
731 static void
732 check_pat3_consistency(struct board *board, coord_t coord)
734 #ifdef DEBUG
735 foreach_8neighbor(board, coord) {
736 if (board_at(board, c) == S_NONE && pattern3_hash(board, c) != board->pat3[c]) {
737 board_print(board, stderr);
738 fprintf(stderr, "%s(%d)->%s(%d) computed %x != stored %x (%d)\n", coord2sstr(coord, board), coord, coord2sstr(c, board), c, pattern3_hash(board, c), board->pat3[c], fn__i);
739 assert(0);
741 } foreach_8neighbor_end;
742 #endif
745 static void
746 board_capturable_add(struct board *board, group_t group, coord_t lib, bool onestone)
748 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
749 #ifdef BOARD_TRAITS
750 /* Increase capturable count trait of my last lib. */
751 enum stone capturing_color = stone_other(board_at(board, group));
752 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
753 foreach_neighbor(board, lib, {
754 if (DEBUGL(8) && group_at(board, c) == group)
755 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);
756 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
757 trait_at(board, lib, capturing_color).cap1 += (group_at(board, c) == group && onestone);
759 board_trait_queue(board, lib);
760 #endif
762 #ifdef BOARD_PAT3
763 int fn__i = 0;
764 foreach_neighbor(board, lib, {
765 board->pat3[lib] |= (group_at(board, c) == group) << (16 + 3 - fn__i);
766 fn__i++;
768 #endif
770 #ifdef WANT_BOARD_C
771 /* Update the list of capturable groups. */
772 assert(group);
773 assert(board->clen < board_size2(board));
774 board->c[board->clen++] = group;
775 #endif
777 static void
778 board_capturable_rm(struct board *board, group_t group, coord_t lib, bool onestone)
780 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
781 #ifdef BOARD_TRAITS
782 /* Decrease capturable count trait of my previously-last lib. */
783 enum stone capturing_color = stone_other(board_at(board, group));
784 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
785 foreach_neighbor(board, lib, {
786 if (DEBUGL(8) && group_at(board, c) == group)
787 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);
788 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
789 trait_at(board, lib, capturing_color).cap1 -= (group_at(board, c) == group && onestone);
791 board_trait_queue(board, lib);
792 #endif
794 #ifdef BOARD_PAT3
795 int fn__i = 0;
796 foreach_neighbor(board, lib, {
797 board->pat3[lib] &= ~((group_at(board, c) == group) << (16 + 3 - fn__i));
798 fn__i++;
800 #endif
802 #ifdef WANT_BOARD_C
803 /* Update the list of capturable groups. */
804 for (int i = 0; i < board->clen; i++) {
805 if (unlikely(board->c[i] == group)) {
806 board->c[i] = board->c[--board->clen];
807 return;
810 fprintf(stderr, "rm of bad group %d\n", group_base(group));
811 assert(0);
812 #endif
815 static void
816 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
818 #ifdef BOARD_TRAITS
819 board_trait_queue(board, lib1);
820 board_trait_queue(board, lib2);
821 #endif
823 static void
824 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
826 #ifdef BOARD_TRAITS
827 board_trait_queue(board, lib1);
828 board_trait_queue(board, lib2);
829 #endif
832 static void
833 board_group_addlib(struct board *board, group_t group, coord_t coord)
835 if (DEBUGL(7)) {
836 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
837 group_base(group), coord2sstr(group_base(group), board),
838 board_group_info(board, group).libs, coord2sstr(coord, board));
841 check_libs_consistency(board, group);
843 struct group *gi = &board_group_info(board, group);
844 bool onestone = group_is_onestone(board, group);
845 if (gi->libs < GROUP_KEEP_LIBS) {
846 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
847 #if 0
848 /* Seems extra branch just slows it down */
849 if (!gi->lib[i])
850 break;
851 #endif
852 if (unlikely(gi->lib[i] == coord))
853 return;
855 if (gi->libs == 0) {
856 board_capturable_add(board, group, coord, onestone);
857 } else if (gi->libs == 1) {
858 board_capturable_rm(board, group, gi->lib[0], onestone);
859 board_atariable_add(board, group, gi->lib[0], coord);
860 } else if (gi->libs == 2) {
861 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
863 gi->lib[gi->libs++] = coord;
866 check_libs_consistency(board, group);
869 static void
870 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
872 /* Add extra liberty from the board to our liberty list. */
873 unsigned char watermark[board_size2(board) / 8];
874 memset(watermark, 0, sizeof(watermark));
875 #define watermark_get(c) (watermark[c >> 3] & (1 << (c & 7)))
876 #define watermark_set(c) watermark[c >> 3] |= (1 << (c & 7))
878 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
879 watermark_set(gi->lib[i]);
880 watermark_set(avoid);
882 foreach_in_group(board, group) {
883 coord_t coord2 = c;
884 foreach_neighbor(board, coord2, {
885 if (board_at(board, c) + watermark_get(c) != S_NONE)
886 continue;
887 watermark_set(c);
888 gi->lib[gi->libs++] = c;
889 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
890 return;
891 } );
892 } foreach_in_group_end;
893 #undef watermark_get
894 #undef watermark_set
897 static void
898 board_group_rmlib(struct board *board, group_t group, coord_t coord)
900 if (DEBUGL(7)) {
901 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
902 group_base(group), coord2sstr(group_base(group), board),
903 board_group_info(board, group).libs, coord2sstr(coord, board));
906 struct group *gi = &board_group_info(board, group);
907 bool onestone = group_is_onestone(board, group);
908 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
909 #if 0
910 /* Seems extra branch just slows it down */
911 if (!gi->lib[i])
912 break;
913 #endif
914 if (likely(gi->lib[i] != coord))
915 continue;
917 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
918 gi->lib[gi->libs] = 0;
920 check_libs_consistency(board, group);
922 /* Postpone refilling lib[] until we need to. */
923 assert(GROUP_REFILL_LIBS > 1);
924 if (gi->libs > GROUP_REFILL_LIBS)
925 return;
926 if (gi->libs == GROUP_REFILL_LIBS)
927 board_group_find_extra_libs(board, group, gi, coord);
929 if (gi->libs == 2) {
930 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
931 } else if (gi->libs == 1) {
932 board_capturable_add(board, group, gi->lib[0], onestone);
933 board_atariable_rm(board, group, gi->lib[0], lib);
934 } else if (gi->libs == 0)
935 board_capturable_rm(board, group, lib, onestone);
936 return;
939 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
940 * can call this multiple times per coord. */
941 check_libs_consistency(board, group);
942 return;
946 /* This is a low-level routine that doesn't maintain consistency
947 * of all the board data structures. */
948 static void
949 board_remove_stone(struct board *board, group_t group, coord_t c)
951 enum stone color = board_at(board, c);
952 board_at(board, c) = S_NONE;
953 group_at(board, c) = 0;
954 board_hash_update(board, c, color);
955 #ifdef BOARD_TRAITS
956 /* We mark as cannot-capture now. If this is a ko/snapback,
957 * we will get incremented later in board_group_addlib(). */
958 trait_at(board, c, S_BLACK).cap = trait_at(board, c, S_BLACK).cap1 = 0;
959 trait_at(board, c, S_WHITE).cap = trait_at(board, c, S_WHITE).cap1 = 0;
960 board_trait_queue(board, c);
961 #endif
963 /* Increase liberties of surrounding groups */
964 coord_t coord = c;
965 foreach_neighbor(board, coord, {
966 dec_neighbor_count_at(board, c, color);
967 board_trait_queue(board, c);
968 group_t g = group_at(board, c);
969 if (g && g != group)
970 board_group_addlib(board, g, coord);
973 #ifdef BOARD_PAT3
974 /* board_hash_update() might have seen the freed up point as able
975 * to capture another group in atari that only after the loop
976 * above gained enough liberties. Reset pat3 again. */
977 board->pat3[c] = pattern3_hash(board, c);
978 #endif
980 if (DEBUGL(6))
981 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
982 board->f[board->flen++] = c;
985 static int profiling_noinline
986 board_group_capture(struct board *board, group_t group)
988 int stones = 0;
990 foreach_in_group(board, group) {
991 board->captures[stone_other(board_at(board, c))]++;
992 board_remove_stone(board, group, c);
993 stones++;
994 } foreach_in_group_end;
996 struct group *gi = &board_group_info(board, group);
997 assert(gi->libs == 0);
998 memset(gi, 0, sizeof(*gi));
1000 return stones;
1004 static void profiling_noinline
1005 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
1007 #ifdef BOARD_TRAITS
1008 struct group *gi = &board_group_info(board, group);
1009 bool onestone = group_is_onestone(board, group);
1011 if (gi->libs == 1) {
1012 /* Our group is temporarily in atari; make sure the capturable
1013 * counts also correspond to the newly added stone before we
1014 * start adding liberties again so bump-dump ops match. */
1015 enum stone capturing_color = stone_other(board_at(board, group));
1016 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1018 coord_t lib = board_group_info(board, group).lib[0];
1019 if (coord_is_adjecent(lib, coord, board)) {
1020 if (DEBUGL(8))
1021 fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1022 trait_at(board, lib, capturing_color).cap++;
1023 /* This is never a 1-stone group, obviously. */
1024 board_trait_queue(board, lib);
1027 if (onestone) {
1028 /* We are not 1-stone group anymore, update the cap1
1029 * counter specifically. */
1030 foreach_neighbor(board, group, {
1031 if (board_at(board, c) != S_NONE) continue;
1032 trait_at(board, c, capturing_color).cap1--;
1033 board_trait_queue(board, c);
1037 #endif
1039 group_at(board, coord) = group;
1040 groupnext_at(board, coord) = groupnext_at(board, prevstone);
1041 groupnext_at(board, prevstone) = coord;
1043 foreach_neighbor(board, coord, {
1044 if (board_at(board, c) == S_NONE)
1045 board_group_addlib(board, group, c);
1048 if (DEBUGL(8))
1049 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
1050 coord_x(prevstone, board), coord_y(prevstone, board),
1051 coord_x(coord, board), coord_y(coord, board),
1052 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
1053 group_base(group));
1056 static void profiling_noinline
1057 merge_groups(struct board *board, group_t group_to, group_t group_from)
1059 if (DEBUGL(7))
1060 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
1061 group_base(group_from), group_base(group_to));
1062 struct group *gi_from = &board_group_info(board, group_from);
1063 struct group *gi_to = &board_group_info(board, group_to);
1064 bool onestone_from = group_is_onestone(board, group_from);
1065 bool onestone_to = group_is_onestone(board, group_to);
1067 /* We do this early before the group info is rewritten. */
1068 if (gi_from->libs == 2)
1069 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1070 else if (gi_from->libs == 1)
1071 board_capturable_rm(board, group_from, gi_from->lib[0], onestone_from);
1073 if (DEBUGL(7))
1074 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1076 if (gi_to->libs < GROUP_KEEP_LIBS) {
1077 for (int i = 0; i < gi_from->libs; i++) {
1078 for (int j = 0; j < gi_to->libs; j++)
1079 if (gi_to->lib[j] == gi_from->lib[i])
1080 goto next_from_lib;
1081 if (gi_to->libs == 0) {
1082 board_capturable_add(board, group_to, gi_from->lib[i], onestone_to);
1083 } else if (gi_to->libs == 1) {
1084 board_capturable_rm(board, group_to, gi_to->lib[0], onestone_to);
1085 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1086 } else if (gi_to->libs == 2) {
1087 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1089 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1090 if (gi_to->libs >= GROUP_KEEP_LIBS)
1091 break;
1092 next_from_lib:;
1096 if (gi_to->libs == 1) {
1097 coord_t lib = board_group_info(board, group_to).lib[0];
1098 #ifdef BOARD_TRAITS
1099 enum stone capturing_color = stone_other(board_at(board, group_to));
1100 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1102 /* Our group is currently in atari; make sure we properly
1103 * count in even the neighbors from the other group in the
1104 * capturable counter. */
1105 foreach_neighbor(board, lib, {
1106 if (DEBUGL(8) && group_at(board, c) == group_from)
1107 fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1108 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1109 /* This is never a 1-stone group, obviously. */
1111 board_trait_queue(board, lib);
1113 if (onestone_to) {
1114 /* We are not 1-stone group anymore, update the cap1
1115 * counter specifically. */
1116 foreach_neighbor(board, group_to, {
1117 if (board_at(board, c) != S_NONE) continue;
1118 trait_at(board, c, capturing_color).cap1--;
1119 board_trait_queue(board, c);
1122 #endif
1123 #ifdef BOARD_PAT3
1124 if (gi_from->libs == 1) {
1125 /* We removed group_from from capturable groups,
1126 * therefore switching the atari flag off.
1127 * We need to set it again since group_to is also
1128 * capturable. */
1129 int fn__i = 0;
1130 foreach_neighbor(board, lib, {
1131 board->pat3[lib] |= (group_at(board, c) == group_from) << (16 + 3 - fn__i);
1132 fn__i++;
1135 #endif
1138 coord_t last_in_group;
1139 foreach_in_group(board, group_from) {
1140 last_in_group = c;
1141 group_at(board, c) = group_to;
1142 } foreach_in_group_end;
1143 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1144 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1145 memset(gi_from, 0, sizeof(struct group));
1147 if (DEBUGL(7))
1148 fprintf(stderr, "board_play_raw: merged group: %d\n",
1149 group_base(group_to));
1152 static group_t profiling_noinline
1153 new_group(struct board *board, coord_t coord)
1155 group_t group = coord;
1156 struct group *gi = &board_group_info(board, group);
1157 foreach_neighbor(board, coord, {
1158 if (board_at(board, c) == S_NONE)
1159 /* board_group_addlib is ridiculously expensive for us */
1160 #if GROUP_KEEP_LIBS < 4
1161 if (gi->libs < GROUP_KEEP_LIBS)
1162 #endif
1163 gi->lib[gi->libs++] = c;
1166 group_at(board, coord) = group;
1167 groupnext_at(board, coord) = 0;
1169 if (gi->libs == 2)
1170 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1171 else if (gi->libs == 1)
1172 board_capturable_add(board, group, gi->lib[0], true);
1173 check_libs_consistency(board, group);
1175 if (DEBUGL(8))
1176 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1177 coord_x(coord, board), coord_y(coord, board),
1178 group_base(group));
1180 return group;
1183 static inline group_t
1184 play_one_neighbor(struct board *board,
1185 coord_t coord, enum stone color, enum stone other_color,
1186 coord_t c, group_t group)
1188 enum stone ncolor = board_at(board, c);
1189 group_t ngroup = group_at(board, c);
1191 inc_neighbor_count_at(board, c, color);
1192 /* We can be S_NONE, in that case we need to update the safety
1193 * trait since we might be left with only one liberty. */
1194 board_trait_queue(board, c);
1196 if (!ngroup)
1197 return group;
1199 board_group_rmlib(board, ngroup, coord);
1200 if (DEBUGL(7))
1201 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1202 group_base(ngroup), ncolor, color, other_color);
1204 if (ncolor == color && ngroup != group) {
1205 if (!group) {
1206 group = ngroup;
1207 add_to_group(board, group, c, coord);
1208 } else {
1209 merge_groups(board, group, ngroup);
1211 } else if (ncolor == other_color) {
1212 if (DEBUGL(8)) {
1213 struct group *gi = &board_group_info(board, ngroup);
1214 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1215 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1216 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1217 fprintf(stderr, "\n");
1219 if (unlikely(board_group_captured(board, ngroup)))
1220 board_group_capture(board, ngroup);
1222 return group;
1225 /* We played on a place with at least one liberty. We will become a member of
1226 * some group for sure. */
1227 static group_t profiling_noinline
1228 board_play_outside(struct board *board, struct move *m, int f)
1230 coord_t coord = m->coord;
1231 enum stone color = m->color;
1232 enum stone other_color = stone_other(color);
1233 group_t group = 0;
1235 board->f[f] = board->f[--board->flen];
1236 if (DEBUGL(6))
1237 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1239 #if defined(BOARD_TRAITS) && defined(DEBUG)
1240 /* Sanity check that cap matches reality. */
1242 int a = 0, b = 0;
1243 foreach_neighbor(board, coord, {
1244 group_t g = group_at(board, c);
1245 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1246 b += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1) && group_is_onestone(board, g);
1248 assert(a == trait_at(board, coord, color).cap);
1249 assert(b == trait_at(board, coord, color).cap1);
1250 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1252 #endif
1253 foreach_neighbor(board, coord, {
1254 group = play_one_neighbor(board, coord, color, other_color, c, group);
1257 board_at(board, coord) = color;
1258 if (unlikely(!group))
1259 group = new_group(board, coord);
1260 board_gamma_update(board, coord, S_BLACK);
1261 board_gamma_update(board, coord, S_WHITE);
1263 board->last_move2 = board->last_move;
1264 board->last_move = *m;
1265 board->moves++;
1266 board_hash_update(board, coord, color);
1267 board_symmetry_update(board, &board->symmetry, coord);
1268 struct move ko = { pass, S_NONE };
1269 board->ko = ko;
1271 check_pat3_consistency(board, coord);
1273 return group;
1276 /* We played in an eye-like shape. Either we capture at least one of the eye
1277 * sides in the process of playing, or return -1. */
1278 static int profiling_noinline
1279 board_play_in_eye(struct board *board, struct move *m, int f)
1281 coord_t coord = m->coord;
1282 enum stone color = m->color;
1283 /* Check ko: Capture at a position of ko capture one move ago */
1284 if (unlikely(color == board->ko.color && coord == board->ko.coord)) {
1285 if (DEBUGL(5))
1286 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1287 return -1;
1288 } else if (DEBUGL(6)) {
1289 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1290 color, coord_x(coord, board), coord_y(coord, board),
1291 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1294 struct move ko = { pass, S_NONE };
1296 int captured_groups = 0;
1298 foreach_neighbor(board, coord, {
1299 group_t g = group_at(board, c);
1300 if (DEBUGL(7))
1301 fprintf(stderr, "board_check: group %d has %d libs\n",
1302 g, board_group_info(board, g).libs);
1303 captured_groups += (board_group_info(board, g).libs == 1);
1306 if (likely(captured_groups == 0)) {
1307 if (DEBUGL(5)) {
1308 if (DEBUGL(6))
1309 board_print(board, stderr);
1310 fprintf(stderr, "board_check: one-stone suicide\n");
1313 return -1;
1315 #ifdef BOARD_TRAITS
1316 /* We _will_ for sure capture something. */
1317 assert(trait_at(board, coord, color).cap > 0);
1318 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1319 #endif
1321 board->f[f] = board->f[--board->flen];
1322 if (DEBUGL(6))
1323 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1325 foreach_neighbor(board, coord, {
1326 inc_neighbor_count_at(board, c, color);
1327 /* Originally, this could not have changed any trait
1328 * since no neighbors were S_NONE, however by now some
1329 * of them might be removed from the board. */
1330 board_trait_queue(board, c);
1332 group_t group = group_at(board, c);
1333 if (!group)
1334 continue;
1336 board_group_rmlib(board, group, coord);
1337 if (DEBUGL(7))
1338 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1339 group_base(group));
1341 if (board_group_captured(board, group)) {
1342 if (board_group_capture(board, group) == 1) {
1343 /* If we captured multiple groups at once,
1344 * we can't be fighting ko so we don't need
1345 * to check for that. */
1346 ko.color = stone_other(color);
1347 ko.coord = c;
1348 board->last_ko = ko;
1349 board->last_ko_age = board->moves;
1350 if (DEBUGL(5))
1351 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1356 board_at(board, coord) = color;
1357 group_t group = new_group(board, coord);
1358 board_gamma_update(board, coord, S_BLACK);
1359 board_gamma_update(board, coord, S_WHITE);
1361 board->last_move2 = board->last_move;
1362 board->last_move = *m;
1363 board->moves++;
1364 board_hash_update(board, coord, color);
1365 board_hash_commit(board);
1366 board_traits_recompute(board);
1367 board_symmetry_update(board, &board->symmetry, coord);
1368 board->ko = ko;
1370 check_pat3_consistency(board, coord);
1372 return !!group;
1375 static int __attribute__((flatten))
1376 board_play_f(struct board *board, struct move *m, int f)
1378 if (DEBUGL(7)) {
1379 fprintf(stderr, "board_play(%s): ---- Playing %d,%d\n", coord2sstr(m->coord, board), coord_x(m->coord, board), coord_y(m->coord, board));
1381 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1382 /* NOT playing in an eye. Thus this move has to succeed. (This
1383 * is thanks to New Zealand rules. Otherwise, multi-stone
1384 * suicide might fail.) */
1385 group_t group = board_play_outside(board, m, f);
1386 if (unlikely(board_group_captured(board, group))) {
1387 board_group_capture(board, group);
1389 board_hash_commit(board);
1390 board_traits_recompute(board);
1391 return 0;
1392 } else {
1393 return board_play_in_eye(board, m, f);
1398 board_play(struct board *board, struct move *m)
1400 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1401 struct move nomove = { pass, S_NONE };
1402 board->ko = nomove;
1403 board->last_move2 = board->last_move;
1404 board->last_move = *m;
1405 return 0;
1408 int f;
1409 for (f = 0; f < board->flen; f++)
1410 if (board->f[f] == m->coord)
1411 return board_play_f(board, m, f);
1413 if (DEBUGL(7))
1414 fprintf(stderr, "board_check: stone exists\n");
1415 return -1;
1419 static inline bool
1420 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1422 *coord = b->f[f];
1423 struct move m = { *coord, color };
1424 if (DEBUGL(6))
1425 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));
1426 if (unlikely(board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1427 || !board_is_valid_move(b, &m)
1428 || (permit && !permit(permit_data, b, &m)))
1429 return false;
1430 if (m.coord == *coord) {
1431 return likely(board_play_f(b, &m, f) >= 0);
1432 } else {
1433 *coord = m.coord; // permit modified the coordinate
1434 return likely(board_play(b, &m) >= 0);
1438 void
1439 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1441 if (unlikely(b->flen == 0))
1442 goto pass;
1444 int base = fast_random(b->flen), f;
1445 for (f = base; f < b->flen; f++)
1446 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1447 return;
1448 for (f = 0; f < base; f++)
1449 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1450 return;
1452 pass:
1453 *coord = pass;
1454 struct move m = { pass, color };
1455 board_play(b, &m);
1459 bool
1460 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1462 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1464 /* XXX: We attempt false eye detection but we will yield false
1465 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1467 foreach_diag_neighbor(board, coord) {
1468 color_diag_libs[(enum stone) board_at(board, c)]++;
1469 } foreach_diag_neighbor_end;
1470 /* For false eye, we need two enemy stones diagonally in the
1471 * middle of the board, or just one enemy stone at the edge
1472 * or in the corner. */
1473 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1474 return color_diag_libs[stone_other(eye_color)] >= 2;
1477 bool
1478 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1480 return board_is_eyelike(board, coord, eye_color)
1481 && !board_is_false_eyelike(board, coord, eye_color);
1484 enum stone
1485 board_get_one_point_eye(struct board *board, coord_t coord)
1487 if (board_is_one_point_eye(board, coord, S_WHITE))
1488 return S_WHITE;
1489 else if (board_is_one_point_eye(board, coord, S_BLACK))
1490 return S_BLACK;
1491 else
1492 return S_NONE;
1496 float
1497 board_fast_score(struct board *board)
1499 int scores[S_MAX];
1500 memset(scores, 0, sizeof(scores));
1502 foreach_point(board) {
1503 enum stone color = board_at(board, c);
1504 if (color == S_NONE)
1505 color = board_get_one_point_eye(board, c);
1506 scores[color]++;
1507 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1508 } foreach_point_end;
1510 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1513 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1515 /* One flood-fill iteration; returns true if next iteration
1516 * is required. */
1517 static bool
1518 board_tromp_taylor_iter(struct board *board, int *ownermap)
1520 bool needs_update = false;
1521 foreach_free_point(board) {
1522 /* Ignore occupied and already-dame positions. */
1523 assert(board_at(board, c) == S_NONE);
1524 if (ownermap[c] == 3)
1525 continue;
1526 /* Count neighbors. */
1527 int nei[4] = {0};
1528 foreach_neighbor(board, c, {
1529 nei[ownermap[c]]++;
1531 /* If we have neighbors of both colors, or dame,
1532 * we are dame too. */
1533 if ((nei[1] && nei[2]) || nei[3]) {
1534 ownermap[c] = 3;
1535 /* Speed up the propagation. */
1536 foreach_neighbor(board, c, {
1537 if (board_at(board, c) == S_NONE)
1538 ownermap[c] = 3;
1540 needs_update = true;
1541 continue;
1543 /* If we have neighbors of one color, we are owned
1544 * by that color, too. */
1545 if (!ownermap[c] && (nei[1] || nei[2])) {
1546 int newowner = nei[1] ? 1 : 2;
1547 ownermap[c] = newowner;
1548 /* Speed up the propagation. */
1549 foreach_neighbor(board, c, {
1550 if (board_at(board, c) == S_NONE && !ownermap[c])
1551 ownermap[c] = newowner;
1553 needs_update = true;
1554 continue;
1556 } foreach_free_point_end;
1557 return needs_update;
1560 /* Tromp-Taylor Counting */
1561 float
1562 board_official_score(struct board *board, struct move_queue *q)
1565 /* A point P, not colored C, is said to reach C, if there is a path of
1566 * (vertically or horizontally) adjacent points of P's color from P to
1567 * a point of color C.
1569 * A player's score is the number of points of her color, plus the
1570 * number of empty points that reach only her color. */
1572 int ownermap[board_size2(board)];
1573 int s[4] = {0};
1574 const int o[4] = {0, 1, 2, 0};
1575 foreach_point(board) {
1576 ownermap[c] = o[board_at(board, c)];
1577 s[board_at(board, c)]++;
1578 } foreach_point_end;
1580 if (q) {
1581 /* Process dead groups. */
1582 for (unsigned int i = 0; i < q->moves; i++) {
1583 foreach_in_group(board, q->move[i]) {
1584 enum stone color = board_at(board, c);
1585 ownermap[c] = o[stone_other(color)];
1586 s[color]--; s[stone_other(color)]++;
1587 } foreach_in_group_end;
1591 /* We need to special-case empty board. */
1592 if (!s[S_BLACK] && !s[S_WHITE])
1593 return board->komi + board->handicap;
1595 while (board_tromp_taylor_iter(board, ownermap))
1596 /* Flood-fill... */;
1598 int scores[S_MAX];
1599 memset(scores, 0, sizeof(scores));
1601 foreach_point(board) {
1602 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1603 if (ownermap[c] == 3)
1604 continue;
1605 scores[ownermap[c]]++;
1606 } foreach_point_end;
1608 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];