Merge branch 'master' into derm
[pachi.git] / board.c
blob31b5d1f3a87d66e1189feb17cc17ca2194eba76f
1 #include <alloca.h>
2 #include <assert.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
7 #include "board.h"
8 #include "debug.h"
9 #include "mq.h"
10 #include "random.h"
12 #ifdef BOARD_SPATHASH
13 #include "patternsp.h"
14 #endif
15 #ifdef BOARD_PAT3
16 #include "pattern3.h"
17 #endif
18 #ifdef BOARD_TRAITS
19 static void board_trait_recompute(struct board *board, coord_t coord);
20 #include "tactics.h"
21 #endif
22 #ifdef BOARD_GAMMA
23 #include "pattern.h"
24 #endif
26 bool random_pass = false;
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 = malloc(sizeof(struct board));
52 board_setup(b);
54 // Default setup
55 b->size = 9 + 2;
56 board_clear(b);
58 return b;
61 struct board *
62 board_copy(struct board *b2, struct board *b1)
64 memcpy(b2, b1, sizeof(struct board));
66 int bsize = board_size2(b2) * sizeof(*b2->b);
67 int gsize = board_size2(b2) * sizeof(*b2->g);
68 int fsize = board_size2(b2) * sizeof(*b2->f);
69 int nsize = board_size2(b2) * sizeof(*b2->n);
70 int psize = board_size2(b2) * sizeof(*b2->p);
71 int hsize = board_size2(b2) * 2 * sizeof(*b2->h);
72 int gisize = board_size2(b2) * sizeof(*b2->gi);
73 #ifdef WANT_BOARD_C
74 int csize = board_size2(b2) * sizeof(*b2->c);
75 #else
76 int csize = 0;
77 #endif
78 #ifdef BOARD_SPATHASH
79 int ssize = board_size2(b2) * sizeof(*b2->spathash);
80 #else
81 int ssize = 0;
82 #endif
83 #ifdef BOARD_PAT3
84 int p3size = board_size2(b2) * sizeof(*b2->pat3);
85 #else
86 int p3size = 0;
87 #endif
88 #ifdef BOARD_TRAITS
89 int tsize = board_size2(b2) * sizeof(*b2->t);
90 int tqsize = board_size2(b2) * sizeof(*b2->t);
91 #else
92 int tsize = 0;
93 int tqsize = 0;
94 #endif
95 #ifdef BOARD_GAMMA
96 int pbsize = board_size2(b2) * sizeof(*b2->prob[0].items);
97 #else
98 int pbsize = 0;
99 #endif
100 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
101 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
102 b2->b = x; x += bsize;
103 b2->g = x; x += gsize;
104 b2->f = x; x += fsize;
105 b2->p = x; x += psize;
106 b2->n = x; x += nsize;
107 b2->h = x; x += hsize;
108 b2->gi = x; x += gisize;
109 #ifdef WANT_BOARD_C
110 b2->c = x; x += csize;
111 #endif
112 #ifdef BOARD_SPATHASH
113 b2->spathash = x; x += ssize;
114 #endif
115 #ifdef BOARD_PAT3
116 b2->pat3 = x; x += p3size;
117 #endif
118 #ifdef BOARD_TRAITS
119 b2->t = x; x += tsize;
120 b2->tq = x; x += tqsize;
121 #endif
122 #ifdef BOARD_GAMMA
123 b2->prob[0].items = x; x += pbsize;
124 b2->prob[1].items = x; x += pbsize;
125 #endif
127 return b2;
130 void
131 board_done_noalloc(struct board *board)
133 if (board->b) free(board->b);
136 void
137 board_done(struct board *board)
139 board_done_noalloc(board);
140 free(board);
143 void
144 board_resize(struct board *board, int size)
146 #ifdef BOARD_SIZE
147 assert(board_size(board) == size + 2);
148 #else
149 board_size(board) = size + 2 /* S_OFFBOARD margin */;
150 board_size2(board) = board_size(board) * board_size(board);
151 #endif
152 if (board->b)
153 free(board->b);
155 int bsize = board_size2(board) * sizeof(*board->b);
156 int gsize = board_size2(board) * sizeof(*board->g);
157 int fsize = board_size2(board) * sizeof(*board->f);
158 int nsize = board_size2(board) * sizeof(*board->n);
159 int psize = board_size2(board) * sizeof(*board->p);
160 int hsize = board_size2(board) * 2 * sizeof(*board->h);
161 int gisize = board_size2(board) * sizeof(*board->gi);
162 #ifdef WANT_BOARD_C
163 int csize = board_size2(board) * sizeof(*board->c);
164 #else
165 int csize = 0;
166 #endif
167 #ifdef BOARD_SPATHASH
168 int ssize = board_size2(board) * sizeof(*board->spathash);
169 #else
170 int ssize = 0;
171 #endif
172 #ifdef BOARD_PAT3
173 int p3size = board_size2(board) * sizeof(*board->pat3);
174 #else
175 int p3size = 0;
176 #endif
177 #ifdef BOARD_TRAITS
178 int tsize = board_size2(board) * sizeof(*board->t);
179 int tqsize = board_size2(board) * sizeof(*board->t);
180 #else
181 int tsize = 0;
182 int tqsize = 0;
183 #endif
184 #ifdef BOARD_GAMMA
185 int pbsize = board_size2(board) * sizeof(*board->prob[0].items);
186 #else
187 int pbsize = 0;
188 #endif
189 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
190 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
191 board->b = x; x += bsize;
192 board->g = x; x += gsize;
193 board->f = x; x += fsize;
194 board->p = x; x += psize;
195 board->n = x; x += nsize;
196 board->h = x; x += hsize;
197 board->gi = x; x += gisize;
198 #ifdef WANT_BOARD_C
199 board->c = x; x += csize;
200 #endif
201 #ifdef BOARD_SPATHASH
202 board->spathash = x; x += ssize;
203 #endif
204 #ifdef BOARD_PAT3
205 board->pat3 = x; x += p3size;
206 #endif
207 #ifdef BOARD_TRAITS
208 board->t = x; x += tsize;
209 board->tq = x; x += tqsize;
210 #endif
211 #ifdef BOARD_GAMMA
212 board->prob[0].items = x; x += pbsize;
213 board->prob[1].items = x; x += pbsize;
214 #endif
217 void
218 board_clear(struct board *board)
220 int size = board_size(board);
221 float komi = board->komi;
223 board_done_noalloc(board);
224 board_setup(board);
225 board_resize(board, size - 2 /* S_OFFBOARD margin */);
227 board->komi = komi;
229 /* Setup neighborhood iterators */
230 board->nei8[0] = -size - 1; // (-1,-1)
231 board->nei8[1] = 1;
232 board->nei8[2] = 1;
233 board->nei8[3] = size - 2; // (-1,0)
234 board->nei8[4] = 2;
235 board->nei8[5] = size - 2; // (-1,1)
236 board->nei8[6] = 1;
237 board->nei8[7] = 1;
238 board->dnei[0] = -size - 1;
239 board->dnei[1] = 2;
240 board->dnei[2] = size*2 - 2;
241 board->dnei[3] = 2;
243 /* Setup initial symmetry */
244 board->symmetry.d = 1;
245 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
246 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
247 board->symmetry.type = SYM_FULL;
249 /* Draw the offboard margin */
250 int top_row = board_size2(board) - board_size(board);
251 int i;
252 for (i = 0; i < board_size(board); i++)
253 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
254 for (i = 0; i <= top_row; i += board_size(board))
255 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
257 foreach_point(board) {
258 coord_t coord = c;
259 if (board_at(board, coord) == S_OFFBOARD)
260 continue;
261 foreach_neighbor(board, c, {
262 inc_neighbor_count_at(board, coord, board_at(board, c));
263 } );
264 } foreach_point_end;
266 /* First, pass is always a free position. */
267 board->f[board->flen++] = coord_raw(pass);
268 /* All positions are free! Except the margin. */
269 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
270 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
271 board->f[board->flen++] = i;
273 /* Initialize zobrist hashtable. */
274 foreach_point(board) {
275 int max = (sizeof(hash_t) << history_hash_bits);
276 /* fast_random() is 16-bit only */
277 board->h[coord_raw(c) * 2] = ((hash_t) fast_random(max))
278 | ((hash_t) fast_random(max) << 16)
279 | ((hash_t) fast_random(max) << 32)
280 | ((hash_t) fast_random(max) << 48);
281 if (!board->h[coord_raw(c) * 2])
282 /* Would be kinda "oops". */
283 board->h[coord_raw(c) * 2] = 1;
284 /* And once again for white */
285 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
286 | ((hash_t) fast_random(max) << 16)
287 | ((hash_t) fast_random(max) << 32)
288 | ((hash_t) fast_random(max) << 48);
289 if (!board->h[coord_raw(c) * 2 + 1])
290 board->h[coord_raw(c) * 2 + 1] = 1;
291 } foreach_point_end;
293 #ifdef BOARD_SPATHASH
294 /* Initialize spatial hashes. */
295 foreach_point(board) {
296 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
297 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
298 ptcoords_at(x, y, c, board, j);
299 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
300 pthashes[0][j][board_at(board, c)];
301 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
302 pthashes[0][j][stone_other(board_at(board, c))];
305 } foreach_point_end;
306 #endif
307 #ifdef BOARD_PAT3
308 /* Initialize 3x3 pattern codes. */
309 foreach_point(board) {
310 if (board_at(board, c) == S_NONE)
311 board->pat3[c] = pattern3_hash(board, c);
312 } foreach_point_end;
313 #endif
314 #ifdef BOARD_TRAITS
315 /* Initialize traits. */
316 foreach_point(board) {
317 trait_at(board, c, S_BLACK).cap = 0;
318 trait_at(board, c, S_BLACK).safe = true;
319 trait_at(board, c, S_WHITE).cap = 0;
320 trait_at(board, c, S_WHITE).safe = true;
321 } foreach_point_end;
322 #endif
323 #ifdef BOARD_GAMMA
324 board->prob[0].n = board->prob[1].n = board_size2(board);
325 foreach_point(board) {
326 probdist_set(&board->prob[0], c, (board_at(board, c) == S_NONE) * 1.0f);
327 probdist_set(&board->prob[1], c, (board_at(board, c) == S_NONE) * 1.0f);
328 } foreach_point_end;
329 #endif
333 static void
334 board_print_top(struct board *board, FILE *f, int c)
336 for (int i = 0; i < c; i++) {
337 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
338 fprintf(f, " ");
339 for (int x = 1; x < board_size(board) - 1; x++)
340 fprintf(f, "%c ", asdf[x - 1]);
341 fprintf(f, " ");
343 fprintf(f, "\n");
344 for (int i = 0; i < c; i++) {
345 fprintf(f, " +-");
346 for (int x = 1; x < board_size(board) - 1; x++)
347 fprintf(f, "--");
348 fprintf(f, "+");
350 fprintf(f, "\n");
353 static void
354 board_print_bottom(struct board *board, FILE *f, int c)
356 for (int i = 0; i < c; i++) {
357 fprintf(f, " +-");
358 for (int x = 1; x < board_size(board) - 1; x++)
359 fprintf(f, "--");
360 fprintf(f, "+");
362 fprintf(f, "\n");
365 static void
366 board_print_row(struct board *board, int y, FILE *f, board_cprint cprint)
368 fprintf(f, " %2d | ", y);
369 for (int x = 1; x < board_size(board) - 1; x++) {
370 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
371 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
372 else
373 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
375 fprintf(f, "|");
376 if (cprint) {
377 fprintf(f, " %2d | ", y);
378 for (int x = 1; x < board_size(board) - 1; x++) {
379 cprint(board, coord_xy(board, x, y), f);
381 fprintf(f, "|");
383 fprintf(f, "\n");
386 void
387 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
389 fprintf(f, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
390 board->moves, board->komi, board->handicap,
391 board->captures[S_BLACK], board->captures[S_WHITE]);
392 board_print_top(board, f, 1 + !!cprint);
393 for (int y = board_size(board) - 2; y >= 1; y--)
394 board_print_row(board, y, f, cprint);
395 board_print_bottom(board, f, 1 + !!cprint);
396 fprintf(f, "\n");
399 static void
400 cprint_group(struct board *board, coord_t c, FILE *f)
402 fprintf(f, "%d ", group_base(group_at(board, c)));
405 void
406 board_print(struct board *board, FILE *f)
408 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
411 void
412 board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari)
414 #ifdef BOARD_GAMMA
415 b->gamma = gamma;
416 b->precise_selfatari = precise_selfatari;
417 for (int i = 0; i < b->flen; i++) {
418 if (is_pass(b->f[i])) continue;
419 board_trait_recompute(b, b->f[i]);
421 #endif
425 /* Update the probability distribution we maintain incrementally. */
426 void
427 board_gamma_update(struct board *board, coord_t coord, enum stone color)
429 #ifdef BOARD_GAMMA
430 if (!board->gamma)
431 return;
433 /* Punch out invalid moves and moves filling our own eyes. */
434 if (board_at(board, coord) != S_NONE
435 || (board_is_eyelike(board, coord, stone_other(color))
436 && !trait_at(board, coord, color).cap)
437 || (board_is_one_point_eye(board, coord, color))) {
438 probdist_set(&board->prob[color - 1], coord, 0);
439 return;
442 int pat = board->pat3[coord];
443 if (color == S_WHITE) {
444 /* We work with the pattern3s as black-to-play. */
445 pat = pattern3_reverse(pat);
448 /* We just quickly replicate the general pattern matcher stuff
449 * here in the most bare-bone way. */
450 double value = board->gamma->gamma[FEAT_PATTERN3][pat];
451 if (trait_at(board, coord, color).cap)
452 value *= board->gamma->gamma[FEAT_CAPTURE][0];
453 if (trait_at(board, coord, stone_other(color)).cap
454 && trait_at(board, coord, color).safe)
455 value *= board->gamma->gamma[FEAT_AESCAPE][0];
456 if (!trait_at(board, coord, color).safe)
457 value *= board->gamma->gamma[FEAT_SELFATARI][1 + board->precise_selfatari];
458 probdist_set(&board->prob[color - 1], coord, value);
459 #endif
462 #ifdef BOARD_TRAITS
463 static bool
464 board_trait_safe(struct board *board, coord_t coord, enum stone color)
466 /* sic! */
467 if (board->precise_selfatari)
468 return is_bad_selfatari(board, color, coord);
469 else
470 return board_safe_to_play(board, coord, color);
473 static void
474 board_trait_recompute(struct board *board, coord_t coord)
476 trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);;
477 trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
478 if (DEBUGL(8)) {
479 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d safe=%d) (white cap=%d safe=%d)\n",
480 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
481 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).safe,
482 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).safe);
484 board_gamma_update(board, coord, S_BLACK);
485 board_gamma_update(board, coord, S_WHITE);
487 #endif
489 /* Recompute traits for dirty points that we have previously touched
490 * somehow (libs of their neighbors changed or so). */
491 static void
492 board_traits_recompute(struct board *board)
494 #ifdef BOARD_TRAITS
495 for (int i = 0; i < board->tqlen; i++) {
496 coord_t coord = board->tq[i];
497 if (!trait_at(board, coord, S_BLACK).dirty) continue;
498 if (board_at(board, coord) != S_NONE) continue;
499 board_trait_recompute(board, coord);
500 trait_at(board, coord, S_BLACK).dirty = false;
502 board->tqlen = 0;
503 #endif
506 /* Queue traits of given point for recomputing. */
507 static void
508 board_trait_queue(struct board *board, coord_t coord)
510 #ifdef BOARD_TRAITS
511 board->tq[board->tqlen++] = coord;
512 trait_at(board, coord, S_BLACK).dirty = true;
513 #endif
517 /* Update board hash with given coordinate. */
518 static void profiling_noinline
519 board_hash_update(struct board *board, coord_t coord, enum stone color)
521 board->hash ^= hash_at(board, coord, color);
522 if (DEBUGL(8))
523 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);
525 #ifdef BOARD_SPATHASH
526 /* Gridcular metric is reflective, so we update all hashes
527 * of appropriate ditance in OUR circle. */
528 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
529 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
530 ptcoords_at(x, y, coord, board, j);
531 /* We either changed from S_NONE to color
532 * or vice versa; doesn't matter. */
533 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
534 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
535 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
536 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
539 #endif
541 #if defined(BOARD_PAT3)
542 /* @color is not what we need in case of capture. */
543 enum stone new_color = board_at(board, coord);
544 if (new_color == S_NONE)
545 board->pat3[coord] = pattern3_hash(board, coord);
546 foreach_8neighbor(board, coord) { // internally, the loop uses fn__i=[0..7]
547 if (board_at(board, c) != S_NONE)
548 continue;
549 board->pat3[c] &= ~(3 << (fn__i*2));
550 board->pat3[c] |= new_color << (fn__i*2);
551 #if 0
552 if (board_at(board, c) != S_OFFBOARD && pattern3_hash(board, c) != board->pat3[c]) {
553 board_print(board, stderr);
554 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);
555 assert(0);
557 #endif
558 board_gamma_update(board, c, S_BLACK);
559 board_gamma_update(board, c, S_WHITE);
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 board_capturable_add(struct board *board, group_t group, coord_t lib)
734 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
735 #ifdef BOARD_TRAITS
736 /* Increase capturable count trait of my last lib. */
737 enum stone capturing_color = stone_other(board_at(board, group));
738 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
739 foreach_neighbor(board, lib, {
740 if (DEBUGL(8) && group_at(board, c) == group)
741 fprintf(stderr, "%s[%d] %s cap bump bc of %s(%d) member %s\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));
742 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
744 board_trait_queue(board, lib);
745 #endif
747 #ifdef WANT_BOARD_C
748 /* Update the list of capturable groups. */
749 assert(group);
750 assert(board->clen < board_size2(board));
751 board->c[board->clen++] = group;
752 #endif
754 static void
755 board_capturable_rm(struct board *board, group_t group, coord_t lib)
757 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
758 #ifdef BOARD_TRAITS
759 /* Decrease capturable count trait of my previously-last lib. */
760 enum stone capturing_color = stone_other(board_at(board, group));
761 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
762 foreach_neighbor(board, lib, {
763 if (DEBUGL(8) && group_at(board, c) == group)
764 fprintf(stderr, "%s[%d] cap dump bc of %s(%d) member %s\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap, coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board));
765 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
767 board_trait_queue(board, lib);
768 #endif
770 #ifdef WANT_BOARD_C
771 /* Update the list of capturable groups. */
772 for (int i = 0; i < board->clen; i++) {
773 if (unlikely(board->c[i] == group)) {
774 board->c[i] = board->c[--board->clen];
775 return;
778 fprintf(stderr, "rm of bad group %d\n", group_base(group));
779 assert(0);
780 #endif
783 static void
784 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
786 #ifdef BOARD_TRAITS
787 board_trait_queue(board, lib1);
788 board_trait_queue(board, lib2);
789 #endif
791 static void
792 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
794 #ifdef BOARD_TRAITS
795 board_trait_queue(board, lib1);
796 board_trait_queue(board, lib2);
797 #endif
800 static void
801 board_group_addlib(struct board *board, group_t group, coord_t coord)
803 if (DEBUGL(7)) {
804 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
805 group_base(group), coord2sstr(group_base(group), board),
806 board_group_info(board, group).libs, coord2sstr(coord, board));
809 check_libs_consistency(board, group);
811 struct group *gi = &board_group_info(board, group);
812 if (gi->libs < GROUP_KEEP_LIBS) {
813 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
814 #if 0
815 /* Seems extra branch just slows it down */
816 if (!gi->lib[i])
817 break;
818 #endif
819 if (unlikely(gi->lib[i] == coord))
820 return;
822 if (gi->libs == 0) {
823 board_capturable_add(board, group, coord);
824 } else if (gi->libs == 1) {
825 board_capturable_rm(board, group, gi->lib[0]);
826 board_atariable_add(board, group, gi->lib[0], coord);
827 } else if (gi->libs == 2) {
828 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
830 gi->lib[gi->libs++] = coord;
833 check_libs_consistency(board, group);
836 static void
837 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
839 /* Add extra liberty from the board to our liberty list. */
840 unsigned char watermark[board_size2(board) / 8];
841 memset(watermark, 0, sizeof(watermark));
842 #define watermark_get(c) (watermark[coord_raw(c) >> 3] & (1 << (coord_raw(c) & 7)))
843 #define watermark_set(c) watermark[coord_raw(c) >> 3] |= (1 << (coord_raw(c) & 7))
845 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
846 watermark_set(gi->lib[i]);
847 watermark_set(avoid);
849 foreach_in_group(board, group) {
850 coord_t coord2 = c;
851 foreach_neighbor(board, coord2, {
852 if (board_at(board, c) + watermark_get(c) != S_NONE)
853 continue;
854 watermark_set(c);
855 gi->lib[gi->libs++] = c;
856 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
857 return;
858 } );
859 } foreach_in_group_end;
860 #undef watermark_get
861 #undef watermark_set
864 static void
865 board_group_rmlib(struct board *board, group_t group, coord_t coord)
867 if (DEBUGL(7)) {
868 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
869 group_base(group), coord2sstr(group_base(group), board),
870 board_group_info(board, group).libs, coord2sstr(coord, board));
873 struct group *gi = &board_group_info(board, group);
874 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
875 #if 0
876 /* Seems extra branch just slows it down */
877 if (!gi->lib[i])
878 break;
879 #endif
880 if (likely(gi->lib[i] != coord))
881 continue;
883 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
884 gi->lib[gi->libs] = 0;
886 check_libs_consistency(board, group);
888 /* Postpone refilling lib[] until we need to. */
889 assert(GROUP_REFILL_LIBS > 1);
890 if (gi->libs > GROUP_REFILL_LIBS)
891 return;
892 if (gi->libs == GROUP_REFILL_LIBS)
893 board_group_find_extra_libs(board, group, gi, coord);
895 if (gi->libs == 2) {
896 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
897 } else if (gi->libs == 1) {
898 board_capturable_add(board, group, gi->lib[0]);
899 board_atariable_rm(board, group, gi->lib[0], lib);
900 } else if (gi->libs == 0)
901 board_capturable_rm(board, group, lib);
902 return;
905 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
906 * can call this multiple times per coord. */
907 check_libs_consistency(board, group);
908 return;
912 /* This is a low-level routine that doesn't maintain consistency
913 * of all the board data structures. */
914 static void
915 board_remove_stone(struct board *board, group_t group, coord_t c)
917 enum stone color = board_at(board, c);
918 board_at(board, c) = S_NONE;
919 group_at(board, c) = 0;
920 board_hash_update(board, c, color);
921 #ifdef BOARD_TRAITS
922 /* We mark as cannot-capture now. If this is a ko/snapback,
923 * we will get incremented later in board_group_addlib(). */
924 trait_at(board, c, S_BLACK).cap = 0;
925 trait_at(board, c, S_WHITE).cap = 0;
926 board_trait_queue(board, c);
927 #endif
929 /* Increase liberties of surrounding groups */
930 coord_t coord = c;
931 foreach_neighbor(board, coord, {
932 dec_neighbor_count_at(board, c, color);
933 board_trait_queue(board, c);
934 group_t g = group_at(board, c);
935 if (g && g != group)
936 board_group_addlib(board, g, coord);
939 if (DEBUGL(6))
940 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
941 board->f[board->flen++] = coord_raw(c);
944 static int profiling_noinline
945 board_group_capture(struct board *board, group_t group)
947 int stones = 0;
949 foreach_in_group(board, group) {
950 board->captures[stone_other(board_at(board, c))]++;
951 board_remove_stone(board, group, c);
952 stones++;
953 } foreach_in_group_end;
955 struct group *gi = &board_group_info(board, group);
956 if (gi->libs == 2)
957 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
958 else if (gi->libs == 1)
959 board_capturable_rm(board, group, gi->lib[0]);
960 memset(gi, 0, sizeof(*gi));
962 return stones;
966 static void profiling_noinline
967 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
969 group_at(board, coord) = group;
970 groupnext_at(board, coord) = groupnext_at(board, prevstone);
971 groupnext_at(board, prevstone) = coord_raw(coord);
973 #ifdef BOARD_TRAITS
974 if (board_group_info(board, group).libs == 1) {
975 /* Our group is temporarily in atari; make sure the capturable
976 * counts also correspond to the newly added stone before we
977 * start adding liberties again so bump-dump ops match. */
978 enum stone capturing_color = stone_other(board_at(board, group));
979 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
980 coord_t lib = board_group_info(board, group).lib[0];
981 if (coord_is_adjecent(lib, coord, board)) {
982 if (DEBUGL(8)) fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
983 trait_at(board, lib, capturing_color).cap++;
984 board_trait_queue(board, lib);
987 #endif
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);
1011 /* We do this early before the group info is rewritten. */
1012 if (gi_from->libs == 2)
1013 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1014 else if (gi_from->libs == 1)
1015 board_capturable_rm(board, group_from, gi_from->lib[0]);
1017 if (DEBUGL(7))
1018 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1020 if (gi_to->libs < GROUP_KEEP_LIBS) {
1021 for (int i = 0; i < gi_from->libs; i++) {
1022 for (int j = 0; j < gi_to->libs; j++)
1023 if (gi_to->lib[j] == gi_from->lib[i])
1024 goto next_from_lib;
1025 if (gi_to->libs == 0) {
1026 board_capturable_add(board, group_to, gi_from->lib[i]);
1027 } else if (gi_to->libs == 1) {
1028 board_capturable_rm(board, group_to, gi_to->lib[0]);
1029 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1030 } else if (gi_to->libs == 2) {
1031 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1033 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1034 if (gi_to->libs >= GROUP_KEEP_LIBS)
1035 break;
1036 next_from_lib:;
1040 #ifdef BOARD_TRAITS
1041 if (board_group_info(board, group_to).libs == 1) {
1042 /* Our group is currently in atari; make sure we properly
1043 * count in even the neighbors from the other group in the
1044 * capturable counter. */
1045 enum stone capturing_color = stone_other(board_at(board, group_to));
1046 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1047 coord_t lib = board_group_info(board, group_to).lib[0];
1048 foreach_neighbor(board, lib, {
1049 if (DEBUGL(8) && group_at(board, c) == group_from) fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
1050 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1052 board_trait_queue(board, lib);
1054 #endif
1056 coord_t last_in_group;
1057 foreach_in_group(board, group_from) {
1058 last_in_group = c;
1059 group_at(board, c) = group_to;
1060 } foreach_in_group_end;
1061 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1062 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1063 memset(gi_from, 0, sizeof(struct group));
1065 if (DEBUGL(7))
1066 fprintf(stderr, "board_play_raw: merged group: %d\n",
1067 group_base(group_to));
1070 static group_t profiling_noinline
1071 new_group(struct board *board, coord_t coord)
1073 group_t group = coord_raw(coord);
1074 struct group *gi = &board_group_info(board, group);
1075 foreach_neighbor(board, coord, {
1076 if (board_at(board, c) == S_NONE)
1077 /* board_group_addlib is ridiculously expensive for us */
1078 #if GROUP_KEEP_LIBS < 4
1079 if (gi->libs < GROUP_KEEP_LIBS)
1080 #endif
1081 gi->lib[gi->libs++] = c;
1084 group_at(board, coord) = group;
1085 groupnext_at(board, coord) = 0;
1087 if (gi->libs == 2)
1088 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1089 else if (gi->libs == 1)
1090 board_capturable_add(board, group, gi->lib[0]);
1091 check_libs_consistency(board, group);
1093 if (DEBUGL(8))
1094 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1095 coord_x(coord, board), coord_y(coord, board),
1096 group_base(group));
1098 return group;
1101 static inline group_t
1102 play_one_neighbor(struct board *board,
1103 coord_t coord, enum stone color, enum stone other_color,
1104 coord_t c, group_t group)
1106 enum stone ncolor = board_at(board, c);
1107 group_t ngroup = group_at(board, c);
1109 inc_neighbor_count_at(board, c, color);
1110 /* We can be S_NONE, in that case we need to update the safety
1111 * trait since we might be left with only one liberty. */
1112 board_trait_queue(board, c);
1114 if (!ngroup)
1115 return group;
1117 board_group_rmlib(board, ngroup, coord);
1118 if (DEBUGL(7))
1119 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1120 group_base(ngroup), ncolor, color, other_color);
1122 if (ncolor == color && ngroup != group) {
1123 if (!group) {
1124 group = ngroup;
1125 add_to_group(board, group, c, coord);
1126 } else {
1127 merge_groups(board, group, ngroup);
1129 } else if (ncolor == other_color) {
1130 if (DEBUGL(8)) {
1131 struct group *gi = &board_group_info(board, ngroup);
1132 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1133 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1134 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1135 fprintf(stderr, "\n");
1137 if (unlikely(board_group_captured(board, ngroup)))
1138 board_group_capture(board, ngroup);
1140 return group;
1143 /* We played on a place with at least one liberty. We will become a member of
1144 * some group for sure. */
1145 static group_t profiling_noinline
1146 board_play_outside(struct board *board, struct move *m, int f)
1148 coord_t coord = m->coord;
1149 enum stone color = m->color;
1150 enum stone other_color = stone_other(color);
1151 group_t group = 0;
1153 board->f[f] = board->f[--board->flen];
1154 if (DEBUGL(6))
1155 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1157 #if defined(BOARD_TRAITS) && defined(DEBUG)
1158 /* Sanity check that cap matches reality. */
1160 int a = 0;
1161 foreach_neighbor(board, coord, {
1162 group_t g = group_at(board, c);
1163 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1165 assert(a == trait_at(board, coord, color).cap);
1166 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1168 #endif
1169 foreach_neighbor(board, coord, {
1170 group = play_one_neighbor(board, coord, color, other_color, c, group);
1173 board_at(board, coord) = color;
1174 if (unlikely(!group))
1175 group = new_group(board, coord);
1176 board_gamma_update(board, coord, S_BLACK);
1177 board_gamma_update(board, coord, S_WHITE);
1179 board->last_move2 = board->last_move;
1180 board->last_move = *m;
1181 board->moves++;
1182 board_hash_update(board, coord, color);
1183 board_symmetry_update(board, &board->symmetry, coord);
1184 struct move ko = { pass, S_NONE };
1185 board->ko = ko;
1187 return group;
1190 /* We played in an eye-like shape. Either we capture at least one of the eye
1191 * sides in the process of playing, or return -1. */
1192 static int profiling_noinline
1193 board_play_in_eye(struct board *board, struct move *m, int f)
1195 coord_t coord = m->coord;
1196 enum stone color = m->color;
1197 /* Check ko: Capture at a position of ko capture one move ago */
1198 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
1199 if (DEBUGL(5))
1200 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1201 return -1;
1202 } else if (DEBUGL(6)) {
1203 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1204 color, coord_x(coord, board), coord_y(coord, board),
1205 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1208 struct move ko = { pass, S_NONE };
1210 int captured_groups = 0;
1212 foreach_neighbor(board, coord, {
1213 group_t g = group_at(board, c);
1214 if (DEBUGL(7))
1215 fprintf(stderr, "board_check: group %d has %d libs\n",
1216 g, board_group_info(board, g).libs);
1217 captured_groups += (board_group_info(board, g).libs == 1);
1220 if (likely(captured_groups == 0)) {
1221 if (DEBUGL(5)) {
1222 if (DEBUGL(6))
1223 board_print(board, stderr);
1224 fprintf(stderr, "board_check: one-stone suicide\n");
1227 return -1;
1229 #ifdef BOARD_TRAITS
1230 /* We _will_ for sure capture something. */
1231 assert(trait_at(board, coord, color).cap > 0);
1232 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1233 #endif
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 foreach_neighbor(board, coord, {
1240 inc_neighbor_count_at(board, c, color);
1241 /* Originally, this could not have changed any trait
1242 * since no neighbors were S_NONE, however by now some
1243 * of them might be removed from the board. */
1244 board_trait_queue(board, c);
1246 group_t group = group_at(board, c);
1247 if (!group)
1248 continue;
1250 board_group_rmlib(board, group, coord);
1251 if (DEBUGL(7))
1252 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1253 group_base(group));
1255 if (board_group_captured(board, group)) {
1256 if (board_group_capture(board, group) == 1) {
1257 /* If we captured multiple groups at once,
1258 * we can't be fighting ko so we don't need
1259 * to check for that. */
1260 ko.color = stone_other(color);
1261 ko.coord = c;
1262 board->last_ko = ko;
1263 board->last_ko_age = board->moves;
1264 if (DEBUGL(5))
1265 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1270 board_at(board, coord) = color;
1271 group_t group = new_group(board, coord);
1272 board_gamma_update(board, coord, S_BLACK);
1273 board_gamma_update(board, coord, S_WHITE);
1275 board->last_move2 = board->last_move;
1276 board->last_move = *m;
1277 board->moves++;
1278 board_hash_update(board, coord, color);
1279 board_hash_commit(board);
1280 board_traits_recompute(board);
1281 board_symmetry_update(board, &board->symmetry, coord);
1282 board->ko = ko;
1284 return !!group;
1287 static int __attribute__((flatten))
1288 board_play_f(struct board *board, struct move *m, int f)
1290 if (DEBUGL(7)) {
1291 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
1293 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1294 /* NOT playing in an eye. Thus this move has to succeed. (This
1295 * is thanks to New Zealand rules. Otherwise, multi-stone
1296 * suicide might fail.) */
1297 group_t group = board_play_outside(board, m, f);
1298 if (unlikely(board_group_captured(board, group))) {
1299 board_group_capture(board, group);
1301 board_hash_commit(board);
1302 board_traits_recompute(board);
1303 return 0;
1304 } else {
1305 return board_play_in_eye(board, m, f);
1310 board_play(struct board *board, struct move *m)
1312 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1313 struct move nomove = { pass, S_NONE };
1314 board->ko = nomove;
1315 board->last_move2 = board->last_move;
1316 board->last_move = *m;
1317 return 0;
1320 int f;
1321 for (f = 0; f < board->flen; f++)
1322 if (board->f[f] == coord_raw(m->coord))
1323 return board_play_f(board, m, f);
1325 if (DEBUGL(7))
1326 fprintf(stderr, "board_check: stone exists\n");
1327 return -1;
1331 static inline bool
1332 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1334 coord_raw(*coord) = b->f[f];
1335 if (unlikely(is_pass(*coord)))
1336 return random_pass;
1337 struct move m = { *coord, color };
1338 if (DEBUGL(6))
1339 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
1340 return (likely(!board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1341 && board_is_valid_move(b, &m)
1342 && (!permit || permit(permit_data, b, &m))
1343 && likely(board_play_f(b, &m, f) >= 0));
1346 void
1347 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1349 int base = fast_random(b->flen);
1350 coord_pos(*coord, base, b);
1351 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
1352 return;
1354 int f;
1355 for (f = base + 1; f < b->flen; f++)
1356 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1357 return;
1358 for (f = 0; f < base; f++)
1359 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1360 return;
1362 *coord = pass;
1363 struct move m = { pass, color };
1364 board_play(b, &m);
1368 bool
1369 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1371 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1373 /* XXX: We attempt false eye detection but we will yield false
1374 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1376 foreach_diag_neighbor(board, coord) {
1377 color_diag_libs[(enum stone) board_at(board, c)]++;
1378 } foreach_diag_neighbor_end;
1379 /* For false eye, we need two enemy stones diagonally in the
1380 * middle of the board, or just one enemy stone at the edge
1381 * or in the corner. */
1382 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1383 return color_diag_libs[stone_other(eye_color)] >= 2;
1386 bool
1387 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1389 return board_is_eyelike(board, coord, eye_color)
1390 && !board_is_false_eyelike(board, coord, eye_color);
1393 enum stone
1394 board_get_one_point_eye(struct board *board, coord_t coord)
1396 if (board_is_one_point_eye(board, coord, S_WHITE))
1397 return S_WHITE;
1398 else if (board_is_one_point_eye(board, coord, S_BLACK))
1399 return S_BLACK;
1400 else
1401 return S_NONE;
1405 float
1406 board_fast_score(struct board *board)
1408 int scores[S_MAX];
1409 memset(scores, 0, sizeof(scores));
1411 foreach_point(board) {
1412 enum stone color = board_at(board, c);
1413 if (color == S_NONE)
1414 color = board_get_one_point_eye(board, c);
1415 scores[color]++;
1416 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1417 } foreach_point_end;
1419 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1422 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1424 /* One flood-fill iteration; returns true if next iteration
1425 * is required. */
1426 static bool
1427 board_tromp_taylor_iter(struct board *board, int *ownermap)
1429 bool needs_update = false;
1430 foreach_point(board) {
1431 /* Ignore occupied and already-dame positions. */
1432 if (board_at(board, c) != S_NONE || ownermap[c] == 3)
1433 continue;
1434 /* Count neighbors. */
1435 int nei[4] = {0};
1436 foreach_neighbor(board, c, {
1437 nei[ownermap[c]]++;
1439 /* If we have neighbors of both colors, or dame,
1440 * we are dame too. */
1441 if ((nei[1] && nei[2]) || nei[3]) {
1442 ownermap[c] = 3;
1443 /* Speed up the propagation. */
1444 foreach_neighbor(board, c, {
1445 if (board_at(board, c) == S_NONE)
1446 ownermap[c] = 3;
1448 needs_update = true;
1449 continue;
1451 /* If we have neighbors of one color, we are owned
1452 * by that color, too. */
1453 if (!ownermap[c] && (nei[1] || nei[2])) {
1454 int newowner = nei[1] ? 1 : 2;
1455 ownermap[c] = newowner;
1456 /* Speed up the propagation. */
1457 foreach_neighbor(board, c, {
1458 if (board_at(board, c) == S_NONE && !ownermap[c])
1459 ownermap[c] = newowner;
1461 needs_update = true;
1462 continue;
1464 } foreach_point_end;
1465 return needs_update;
1468 /* Tromp-Taylor Counting */
1469 float
1470 board_official_score(struct board *board, struct move_queue *q)
1473 /* A point P, not colored C, is said to reach C, if there is a path of
1474 * (vertically or horizontally) adjacent points of P's color from P to
1475 * a point of color C.
1477 * A player's score is the number of points of her color, plus the
1478 * number of empty points that reach only her color. */
1480 int ownermap[board_size2(board)];
1481 int s[4] = {0};
1482 const int o[4] = {0, 1, 2, 0};
1483 foreach_point(board) {
1484 ownermap[c] = o[board_at(board, c)];
1485 s[board_at(board, c)]++;
1486 } foreach_point_end;
1488 if (q) {
1489 /* Process dead groups. */
1490 for (int i = 0; i < q->moves; i++) {
1491 foreach_in_group(board, q->move[i]) {
1492 enum stone color = board_at(board, c);
1493 ownermap[c] = o[stone_other(color)];
1494 s[color]--; s[stone_other(color)]++;
1495 } foreach_in_group_end;
1499 /* We need to special-case empty board. */
1500 if (!s[S_BLACK] && !s[S_WHITE])
1501 return board->komi + board->handicap;
1503 while (board_tromp_taylor_iter(board, ownermap))
1504 /* Flood-fill... */;
1506 int scores[S_MAX];
1507 memset(scores, 0, sizeof(scores));
1509 foreach_point(board) {
1510 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1511 if (ownermap[c] == 3)
1512 continue;
1513 scores[ownermap[c]]++;
1514 } foreach_point_end;
1516 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];