Support redirecting stdin, stdout & stderr to sockets.
[pachi/peepo.git] / board.c
blob472ac6ff096af4e0a884ddb9e12d033cef2fbe0b
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 #include "tactics.h"
20 #endif
21 #ifdef BOARD_GAMMA
22 #include "pattern.h"
23 #endif
25 bool random_pass = false;
28 #if 0
29 #define profiling_noinline __attribute__((noinline))
30 #else
31 #define profiling_noinline
32 #endif
34 #define gi_granularity 4
35 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
38 static void
39 board_setup(struct board *b)
41 memset(b, 0, sizeof(*b));
43 struct move m = { pass, S_NONE };
44 b->last_move = b->last_move2 = b->last_ko = b->ko = m;
47 struct board *
48 board_init(void)
50 struct board *b = malloc(sizeof(struct board));
51 board_setup(b);
53 // Default setup
54 b->size = 9 + 2;
55 board_clear(b);
57 return b;
60 struct board *
61 board_copy(struct board *b2, struct board *b1)
63 memcpy(b2, b1, sizeof(struct board));
65 int bsize = board_size2(b2) * sizeof(*b2->b);
66 int gsize = board_size2(b2) * sizeof(*b2->g);
67 int fsize = board_size2(b2) * sizeof(*b2->f);
68 int nsize = board_size2(b2) * sizeof(*b2->n);
69 int psize = board_size2(b2) * sizeof(*b2->p);
70 int hsize = board_size2(b2) * 2 * sizeof(*b2->h);
71 int gisize = board_size2(b2) * sizeof(*b2->gi);
72 #ifdef WANT_BOARD_C
73 int csize = board_size2(b2) * sizeof(*b2->c);
74 #else
75 int csize = 0;
76 #endif
77 #ifdef BOARD_SPATHASH
78 int ssize = board_size2(b2) * sizeof(*b2->spathash);
79 #else
80 int ssize = 0;
81 #endif
82 #ifdef BOARD_PAT3
83 int p3size = board_size2(b2) * sizeof(*b2->pat3);
84 #else
85 int p3size = 0;
86 #endif
87 #ifdef BOARD_TRAITS
88 int tsize = board_size2(b2) * sizeof(*b2->t);
89 int tqsize = board_size2(b2) * sizeof(*b2->t);
90 #else
91 int tsize = 0;
92 int tqsize = 0;
93 #endif
94 #ifdef BOARD_GAMMA
95 int pbsize = board_size2(b2) * sizeof(*b2->prob[0].items);
96 #else
97 int pbsize = 0;
98 #endif
99 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
100 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
101 b2->b = x; x += bsize;
102 b2->g = x; x += gsize;
103 b2->f = x; x += fsize;
104 b2->p = x; x += psize;
105 b2->n = x; x += nsize;
106 b2->h = x; x += hsize;
107 b2->gi = x; x += gisize;
108 #ifdef WANT_BOARD_C
109 b2->c = x; x += csize;
110 #endif
111 #ifdef BOARD_SPATHASH
112 b2->spathash = x; x += ssize;
113 #endif
114 #ifdef BOARD_PAT3
115 b2->pat3 = x; x += p3size;
116 #endif
117 #ifdef BOARD_TRAITS
118 b2->t = x; x += tsize;
119 b2->tq = x; x += tqsize;
120 #endif
121 #ifdef BOARD_GAMMA
122 b2->prob[0].items = x; x += pbsize;
123 b2->prob[1].items = x; x += pbsize;
124 #endif
126 return b2;
129 void
130 board_done_noalloc(struct board *board)
132 if (board->b) free(board->b);
135 void
136 board_done(struct board *board)
138 board_done_noalloc(board);
139 free(board);
142 void
143 board_resize(struct board *board, int size)
145 #ifdef BOARD_SIZE
146 assert(board_size(board) == size + 2);
147 #else
148 board_size(board) = size + 2 /* S_OFFBOARD margin */;
149 board_size2(board) = board_size(board) * board_size(board);
150 #endif
151 if (board->b)
152 free(board->b);
154 int bsize = board_size2(board) * sizeof(*board->b);
155 int gsize = board_size2(board) * sizeof(*board->g);
156 int fsize = board_size2(board) * sizeof(*board->f);
157 int nsize = board_size2(board) * sizeof(*board->n);
158 int psize = board_size2(board) * sizeof(*board->p);
159 int hsize = board_size2(board) * 2 * sizeof(*board->h);
160 int gisize = board_size2(board) * sizeof(*board->gi);
161 #ifdef WANT_BOARD_C
162 int csize = board_size2(board) * sizeof(*board->c);
163 #else
164 int csize = 0;
165 #endif
166 #ifdef BOARD_SPATHASH
167 int ssize = board_size2(board) * sizeof(*board->spathash);
168 #else
169 int ssize = 0;
170 #endif
171 #ifdef BOARD_PAT3
172 int p3size = board_size2(board) * sizeof(*board->pat3);
173 #else
174 int p3size = 0;
175 #endif
176 #ifdef BOARD_TRAITS
177 int tsize = board_size2(board) * sizeof(*board->t);
178 int tqsize = board_size2(board) * sizeof(*board->t);
179 #else
180 int tsize = 0;
181 int tqsize = 0;
182 #endif
183 #ifdef BOARD_GAMMA
184 int pbsize = board_size2(board) * sizeof(*board->prob[0].items);
185 #else
186 int pbsize = 0;
187 #endif
188 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
189 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize + tqsize + pbsize * 2);
190 board->b = x; x += bsize;
191 board->g = x; x += gsize;
192 board->f = x; x += fsize;
193 board->p = x; x += psize;
194 board->n = x; x += nsize;
195 board->h = x; x += hsize;
196 board->gi = x; x += gisize;
197 #ifdef WANT_BOARD_C
198 board->c = x; x += csize;
199 #endif
200 #ifdef BOARD_SPATHASH
201 board->spathash = x; x += ssize;
202 #endif
203 #ifdef BOARD_PAT3
204 board->pat3 = x; x += p3size;
205 #endif
206 #ifdef BOARD_TRAITS
207 board->t = x; x += tsize;
208 board->tq = x; x += tqsize;
209 #endif
210 #ifdef BOARD_GAMMA
211 board->prob[0].items = x; x += pbsize;
212 board->prob[1].items = x; x += pbsize;
213 #endif
216 void
217 board_clear(struct board *board)
219 int size = board_size(board);
220 float komi = board->komi;
222 board_done_noalloc(board);
223 board_setup(board);
224 board_resize(board, size - 2 /* S_OFFBOARD margin */);
226 board->komi = komi;
228 /* Setup neighborhood iterators */
229 board->nei8[0] = -size - 1; // (-1,-1)
230 board->nei8[1] = 1;
231 board->nei8[2] = 1;
232 board->nei8[3] = size - 2; // (-1,0)
233 board->nei8[4] = 2;
234 board->nei8[5] = size - 2; // (-1,1)
235 board->nei8[6] = 1;
236 board->nei8[7] = 1;
237 board->dnei[0] = -size - 1;
238 board->dnei[1] = 2;
239 board->dnei[2] = size*2 - 2;
240 board->dnei[3] = 2;
242 /* Setup initial symmetry */
243 board->symmetry.d = 1;
244 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
245 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
246 board->symmetry.type = SYM_FULL;
248 /* Draw the offboard margin */
249 int top_row = board_size2(board) - board_size(board);
250 int i;
251 for (i = 0; i < board_size(board); i++)
252 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
253 for (i = 0; i <= top_row; i += board_size(board))
254 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
256 foreach_point(board) {
257 coord_t coord = c;
258 if (board_at(board, coord) == S_OFFBOARD)
259 continue;
260 foreach_neighbor(board, c, {
261 inc_neighbor_count_at(board, coord, board_at(board, c));
262 } );
263 } foreach_point_end;
265 /* First, pass is always a free position. */
266 board->f[board->flen++] = coord_raw(pass);
267 /* All positions are free! Except the margin. */
268 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
269 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
270 board->f[board->flen++] = i;
272 /* Initialize zobrist hashtable. */
273 foreach_point(board) {
274 int max = (sizeof(hash_t) << history_hash_bits);
275 /* fast_random() is 16-bit only */
276 board->h[coord_raw(c) * 2] = ((hash_t) fast_random(max))
277 | ((hash_t) fast_random(max) << 16)
278 | ((hash_t) fast_random(max) << 32)
279 | ((hash_t) fast_random(max) << 48);
280 if (!board->h[coord_raw(c) * 2])
281 /* Would be kinda "oops". */
282 board->h[coord_raw(c) * 2] = 1;
283 /* And once again for white */
284 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
285 | ((hash_t) fast_random(max) << 16)
286 | ((hash_t) fast_random(max) << 32)
287 | ((hash_t) fast_random(max) << 48);
288 if (!board->h[coord_raw(c) * 2 + 1])
289 board->h[coord_raw(c) * 2 + 1] = 1;
290 } foreach_point_end;
292 #ifdef BOARD_SPATHASH
293 /* Initialize spatial hashes. */
294 foreach_point(board) {
295 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
296 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
297 ptcoords_at(x, y, c, board, j);
298 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
299 pthashes[0][j][board_at(board, c)];
300 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
301 pthashes[0][j][stone_other(board_at(board, c))];
304 } foreach_point_end;
305 #endif
306 #ifdef BOARD_PAT3
307 /* Initialize 3x3 pattern codes. */
308 foreach_point(board) {
309 if (board_at(board, c) == S_NONE)
310 board->pat3[c] = pattern3_hash(board, c);
311 } foreach_point_end;
312 #endif
313 #ifdef BOARD_TRAITS
314 /* Initialize traits. */
315 foreach_point(board) {
316 trait_at(board, c, S_BLACK).cap = 0;
317 trait_at(board, c, S_BLACK).safe = true;
318 trait_at(board, c, S_WHITE).cap = 0;
319 trait_at(board, c, S_WHITE).safe = true;
320 } foreach_point_end;
321 #endif
322 #ifdef BOARD_GAMMA
323 board->prob[0].n = board->prob[1].n = board_size2(board);
324 foreach_point(board) {
325 probdist_set(&board->prob[0], c, (board_at(board, c) == S_NONE) * 1.0f);
326 probdist_set(&board->prob[1], c, (board_at(board, c) == S_NONE) * 1.0f);
327 } foreach_point_end;
328 #endif
332 static void
333 board_print_top(struct board *board, FILE *f, int c)
335 for (int i = 0; i < c; i++) {
336 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
337 fprintf(f, " ");
338 for (int x = 1; x < board_size(board) - 1; x++)
339 fprintf(f, "%c ", asdf[x - 1]);
340 fprintf(f, " ");
342 fprintf(f, "\n");
343 for (int i = 0; i < c; i++) {
344 fprintf(f, " +-");
345 for (int x = 1; x < board_size(board) - 1; x++)
346 fprintf(f, "--");
347 fprintf(f, "+");
349 fprintf(f, "\n");
352 static void
353 board_print_bottom(struct board *board, FILE *f, int c)
355 for (int i = 0; i < c; i++) {
356 fprintf(f, " +-");
357 for (int x = 1; x < board_size(board) - 1; x++)
358 fprintf(f, "--");
359 fprintf(f, "+");
361 fprintf(f, "\n");
364 static void
365 board_print_row(struct board *board, int y, FILE *f, board_cprint cprint)
367 fprintf(f, " %2d | ", y);
368 for (int x = 1; x < board_size(board) - 1; x++) {
369 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
370 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
371 else
372 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
374 fprintf(f, "|");
375 if (cprint) {
376 fprintf(f, " %2d | ", y);
377 for (int x = 1; x < board_size(board) - 1; x++) {
378 cprint(board, coord_xy(board, x, y), f);
380 fprintf(f, "|");
382 fprintf(f, "\n");
385 void
386 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
388 fprintf(f, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
389 board->moves, board->komi, board->handicap,
390 board->captures[S_BLACK], board->captures[S_WHITE]);
391 board_print_top(board, f, 1 + !!cprint);
392 for (int y = board_size(board) - 2; y >= 1; y--)
393 board_print_row(board, y, f, cprint);
394 board_print_bottom(board, f, 1 + !!cprint);
395 fprintf(f, "\n");
398 static void
399 cprint_group(struct board *board, coord_t c, FILE *f)
401 fprintf(f, "%d ", group_base(group_at(board, c)));
404 void
405 board_print(struct board *board, FILE *f)
407 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
410 static void board_trait_recompute(struct board *board, coord_t coord);
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);
472 #endif
474 static void
475 board_trait_recompute(struct board *board, coord_t coord)
477 #ifdef BOARD_TRAITS
478 trait_at(board, coord, S_BLACK).safe = board_trait_safe(board, coord, S_BLACK);;
479 trait_at(board, coord, S_WHITE).safe = board_trait_safe(board, coord, S_WHITE);
480 if (DEBUGL(8)) {
481 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d safe=%d) (white cap=%d safe=%d)\n",
482 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
483 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).safe,
484 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).safe);
486 board_gamma_update(board, coord, S_BLACK);
487 board_gamma_update(board, coord, S_WHITE);
488 #endif
491 /* Recompute traits for dirty points that we have previously touched
492 * somehow (libs of their neighbors changed or so). */
493 static void
494 board_traits_recompute(struct board *board)
496 #ifdef BOARD_TRAITS
497 for (int i = 0; i < board->tqlen; i++) {
498 coord_t coord = board->tq[i];
499 if (!trait_at(board, coord, S_BLACK).dirty) continue;
500 if (board_at(board, coord) != S_NONE) continue;
501 board_trait_recompute(board, coord);
502 trait_at(board, coord, S_BLACK).dirty = false;
504 board->tqlen = 0;
505 #endif
508 /* Queue traits of given point for recomputing. */
509 static void
510 board_trait_queue(struct board *board, coord_t coord)
512 #ifdef BOARD_TRAITS
513 board->tq[board->tqlen++] = coord;
514 trait_at(board, coord, S_BLACK).dirty = true;
515 #endif
519 /* Update board hash with given coordinate. */
520 static void profiling_noinline
521 board_hash_update(struct board *board, coord_t coord, enum stone color)
523 board->hash ^= hash_at(board, coord, color);
524 if (DEBUGL(8))
525 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);
527 #ifdef BOARD_SPATHASH
528 /* Gridcular metric is reflective, so we update all hashes
529 * of appropriate ditance in OUR circle. */
530 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
531 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
532 ptcoords_at(x, y, coord, board, j);
533 /* We either changed from S_NONE to color
534 * or vice versa; doesn't matter. */
535 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
536 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
537 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
538 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
541 #endif
543 #if defined(BOARD_PAT3)
544 /* @color is not what we need in case of capture. */
545 enum stone new_color = board_at(board, coord);
546 if (new_color == S_NONE)
547 board->pat3[coord] = pattern3_hash(board, coord);
548 foreach_8neighbor(board, coord) { // internally, the loop uses fn__i=[0..7]
549 if (board_at(board, c) != S_NONE)
550 continue;
551 board->pat3[c] &= ~(3 << (fn__i*2));
552 board->pat3[c] |= new_color << (fn__i*2);
553 #if 0
554 if (board_at(board, c) != S_OFFBOARD && pattern3_hash(board, c) != board->pat3[c]) {
555 board_print(board, stderr);
556 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);
557 assert(0);
559 #endif
560 board_gamma_update(board, c, S_BLACK);
561 board_gamma_update(board, c, S_WHITE);
562 } foreach_8neighbor_end;
563 #endif
566 /* Commit current board hash to history. */
567 static void profiling_noinline
568 board_hash_commit(struct board *board)
570 if (DEBUGL(8))
571 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
572 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
573 board->history_hash[board->hash & history_hash_mask] = board->hash;
574 } else {
575 hash_t i = board->hash;
576 while (board->history_hash[i & history_hash_mask]) {
577 if (board->history_hash[i & history_hash_mask] == board->hash) {
578 if (DEBUGL(5))
579 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
580 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
581 board->superko_violation = true;
582 return;
584 i = history_hash_next(i);
586 board->history_hash[i & history_hash_mask] = board->hash;
591 void
592 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
594 if (likely(symmetry->type == SYM_NONE)) {
595 /* Fully degenerated already. We do not support detection
596 * of restoring of symmetry, assuming that this is too rare
597 * a case to handle. */
598 return;
601 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
602 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
603 if (DEBUGL(6)) {
604 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
605 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
606 symmetry->d, symmetry->type, x, y);
609 switch (symmetry->type) {
610 case SYM_FULL:
611 if (x == t && y == t) {
612 /* Tengen keeps full symmetry. */
613 return;
615 /* New symmetry now? */
616 if (x == y) {
617 symmetry->type = SYM_DIAG_UP;
618 symmetry->x1 = symmetry->y1 = 1;
619 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
620 symmetry->d = 1;
621 } else if (dx == y) {
622 symmetry->type = SYM_DIAG_DOWN;
623 symmetry->x1 = symmetry->y1 = 1;
624 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
625 symmetry->d = 1;
626 } else if (x == t) {
627 symmetry->type = SYM_HORIZ;
628 symmetry->y1 = 1;
629 symmetry->y2 = board_size(b) - 1;
630 symmetry->d = 0;
631 } else if (y == t) {
632 symmetry->type = SYM_VERT;
633 symmetry->x1 = 1;
634 symmetry->x2 = board_size(b) - 1;
635 symmetry->d = 0;
636 } else {
637 break_symmetry:
638 symmetry->type = SYM_NONE;
639 symmetry->x1 = symmetry->y1 = 1;
640 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
641 symmetry->d = 0;
643 break;
644 case SYM_DIAG_UP:
645 if (x == y)
646 return;
647 goto break_symmetry;
648 case SYM_DIAG_DOWN:
649 if (dx == y)
650 return;
651 goto break_symmetry;
652 case SYM_HORIZ:
653 if (x == t)
654 return;
655 goto break_symmetry;
656 case SYM_VERT:
657 if (y == t)
658 return;
659 goto break_symmetry;
660 case SYM_NONE:
661 assert(0);
662 break;
665 if (DEBUGL(6)) {
666 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
667 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
668 symmetry->d, symmetry->type);
670 /* Whew. */
674 void
675 board_handicap_stone(struct board *board, int x, int y, FILE *f)
677 struct move m;
678 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
680 board_play(board, &m);
681 /* Simulate white passing; otherwise, UCT search can get confused since
682 * tree depth parity won't match the color to move. */
683 board->moves++;
685 char *str = coord2str(m.coord, board);
686 if (DEBUGL(1))
687 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
688 fprintf(f, "%s ", str);
689 free(str);
692 void
693 board_handicap(struct board *board, int stones, FILE *f)
695 int margin = 3 + (board_size(board) >= 13);
696 int min = margin;
697 int mid = board_size(board) / 2;
698 int max = board_size(board) - 1 - margin;
699 const int places[][2] = {
700 { min, min }, { max, max }, { max, min }, { min, max },
701 { min, mid }, { max, mid },
702 { mid, min }, { mid, max },
703 { mid, mid },
706 board->handicap = stones;
708 if (stones == 5 || stones == 7) {
709 board_handicap_stone(board, mid, mid, f);
710 stones--;
713 int i;
714 for (i = 0; i < stones; i++)
715 board_handicap_stone(board, places[i][0], places[i][1], f);
719 static void __attribute__((noinline))
720 check_libs_consistency(struct board *board, group_t g)
722 #ifdef DEBUG
723 if (!g) return;
724 struct group *gi = &board_group_info(board, g);
725 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
726 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
727 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
728 assert(0);
730 #endif
733 static void
734 board_capturable_add(struct board *board, group_t group, coord_t lib)
736 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
737 #ifdef BOARD_TRAITS
738 /* Increase capturable count trait of my last lib. */
739 enum stone capturing_color = stone_other(board_at(board, group));
740 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
741 foreach_neighbor(board, lib, {
742 if (DEBUGL(8) && group_at(board, c) == group)
743 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));
744 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
746 board_trait_queue(board, lib);
747 #endif
749 #ifdef WANT_BOARD_C
750 /* Update the list of capturable groups. */
751 assert(group);
752 assert(board->clen < board_size2(board));
753 board->c[board->clen++] = group;
754 #endif
756 static void
757 board_capturable_rm(struct board *board, group_t group, coord_t lib)
759 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
760 #ifdef BOARD_TRAITS
761 /* Decrease capturable count trait of my previously-last lib. */
762 enum stone capturing_color = stone_other(board_at(board, group));
763 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
764 foreach_neighbor(board, lib, {
765 if (DEBUGL(8) && group_at(board, c) == group)
766 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));
767 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
769 board_trait_queue(board, lib);
770 #endif
772 #ifdef WANT_BOARD_C
773 /* Update the list of capturable groups. */
774 for (int i = 0; i < board->clen; i++) {
775 if (unlikely(board->c[i] == group)) {
776 board->c[i] = board->c[--board->clen];
777 return;
780 fprintf(stderr, "rm of bad group %d\n", group_base(group));
781 assert(0);
782 #endif
785 static void
786 board_atariable_add(struct board *board, group_t group, coord_t lib1, coord_t lib2)
788 #ifdef BOARD_TRAITS
789 board_trait_queue(board, lib1);
790 board_trait_queue(board, lib2);
791 #endif
793 static void
794 board_atariable_rm(struct board *board, group_t group, coord_t lib1, coord_t lib2)
796 #ifdef BOARD_TRAITS
797 board_trait_queue(board, lib1);
798 board_trait_queue(board, lib2);
799 #endif
802 static void
803 board_group_addlib(struct board *board, group_t group, coord_t coord)
805 if (DEBUGL(7)) {
806 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
807 group_base(group), coord2sstr(group_base(group), board),
808 board_group_info(board, group).libs, coord2sstr(coord, board));
811 check_libs_consistency(board, group);
813 struct group *gi = &board_group_info(board, group);
814 if (gi->libs < GROUP_KEEP_LIBS) {
815 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
816 #if 0
817 /* Seems extra branch just slows it down */
818 if (!gi->lib[i])
819 break;
820 #endif
821 if (unlikely(gi->lib[i] == coord))
822 return;
824 if (gi->libs == 0) {
825 board_capturable_add(board, group, coord);
826 } else if (gi->libs == 1) {
827 board_capturable_rm(board, group, gi->lib[0]);
828 board_atariable_add(board, group, gi->lib[0], coord);
829 } else if (gi->libs == 2) {
830 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
832 gi->lib[gi->libs++] = coord;
835 check_libs_consistency(board, group);
838 static void
839 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
841 /* Add extra liberty from the board to our liberty list. */
842 unsigned char watermark[board_size2(board) / 8];
843 memset(watermark, 0, sizeof(watermark));
844 #define watermark_get(c) (watermark[coord_raw(c) >> 3] & (1 << (coord_raw(c) & 7)))
845 #define watermark_set(c) watermark[coord_raw(c) >> 3] |= (1 << (coord_raw(c) & 7))
847 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
848 watermark_set(gi->lib[i]);
849 watermark_set(avoid);
851 foreach_in_group(board, group) {
852 coord_t coord2 = c;
853 foreach_neighbor(board, coord2, {
854 if (board_at(board, c) + watermark_get(c) != S_NONE)
855 continue;
856 watermark_set(c);
857 gi->lib[gi->libs++] = c;
858 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
859 return;
860 } );
861 } foreach_in_group_end;
862 #undef watermark_get
863 #undef watermark_set
866 static void
867 board_group_rmlib(struct board *board, group_t group, coord_t coord)
869 if (DEBUGL(7)) {
870 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
871 group_base(group), coord2sstr(group_base(group), board),
872 board_group_info(board, group).libs, coord2sstr(coord, board));
875 struct group *gi = &board_group_info(board, group);
876 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
877 #if 0
878 /* Seems extra branch just slows it down */
879 if (!gi->lib[i])
880 break;
881 #endif
882 if (likely(gi->lib[i] != coord))
883 continue;
885 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
886 gi->lib[gi->libs] = 0;
888 check_libs_consistency(board, group);
890 /* Postpone refilling lib[] until we need to. */
891 assert(GROUP_REFILL_LIBS > 1);
892 if (gi->libs > GROUP_REFILL_LIBS)
893 return;
894 if (gi->libs == GROUP_REFILL_LIBS)
895 board_group_find_extra_libs(board, group, gi, coord);
897 if (gi->libs == 2) {
898 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
899 } else if (gi->libs == 1) {
900 board_capturable_add(board, group, gi->lib[0]);
901 board_atariable_rm(board, group, gi->lib[0], lib);
902 } else if (gi->libs == 0)
903 board_capturable_rm(board, group, lib);
904 return;
907 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
908 * can call this multiple times per coord. */
909 check_libs_consistency(board, group);
910 return;
914 /* This is a low-level routine that doesn't maintain consistency
915 * of all the board data structures. */
916 static void
917 board_remove_stone(struct board *board, group_t group, coord_t c)
919 enum stone color = board_at(board, c);
920 board_at(board, c) = S_NONE;
921 group_at(board, c) = 0;
922 board_hash_update(board, c, color);
923 #ifdef BOARD_TRAITS
924 /* We mark as cannot-capture now. If this is a ko/snapback,
925 * we will get incremented later in board_group_addlib(). */
926 trait_at(board, c, S_BLACK).cap = 0;
927 trait_at(board, c, S_WHITE).cap = 0;
928 board_trait_queue(board, c);
929 #endif
931 /* Increase liberties of surrounding groups */
932 coord_t coord = c;
933 foreach_neighbor(board, coord, {
934 dec_neighbor_count_at(board, c, color);
935 board_trait_queue(board, c);
936 group_t g = group_at(board, c);
937 if (g && g != group)
938 board_group_addlib(board, g, coord);
941 if (DEBUGL(6))
942 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
943 board->f[board->flen++] = coord_raw(c);
946 static int profiling_noinline
947 board_group_capture(struct board *board, group_t group)
949 int stones = 0;
951 foreach_in_group(board, group) {
952 board->captures[stone_other(board_at(board, c))]++;
953 board_remove_stone(board, group, c);
954 stones++;
955 } foreach_in_group_end;
957 struct group *gi = &board_group_info(board, group);
958 if (gi->libs == 2)
959 board_atariable_rm(board, group, gi->lib[0], gi->lib[1]);
960 else if (gi->libs == 1)
961 board_capturable_rm(board, group, gi->lib[0]);
962 memset(gi, 0, sizeof(*gi));
964 return stones;
968 static void profiling_noinline
969 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
971 group_at(board, coord) = group;
972 groupnext_at(board, coord) = groupnext_at(board, prevstone);
973 groupnext_at(board, prevstone) = coord_raw(coord);
975 #ifdef BOARD_TRAITS
976 if (board_group_info(board, group).libs == 1) {
977 /* Our group is temporarily in atari; make sure the capturable
978 * counts also correspond to the newly added stone before we
979 * start adding liberties again so bump-dump ops match. */
980 enum stone capturing_color = stone_other(board_at(board, group));
981 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
982 coord_t lib = board_group_info(board, group).lib[0];
983 if (coord_is_adjecent(lib, coord, board)) {
984 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);
985 trait_at(board, lib, capturing_color).cap++;
986 board_trait_queue(board, lib);
989 #endif
991 foreach_neighbor(board, coord, {
992 if (board_at(board, c) == S_NONE)
993 board_group_addlib(board, group, c);
996 if (DEBUGL(8))
997 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
998 coord_x(prevstone, board), coord_y(prevstone, board),
999 coord_x(coord, board), coord_y(coord, board),
1000 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
1001 group_base(group));
1004 static void profiling_noinline
1005 merge_groups(struct board *board, group_t group_to, group_t group_from)
1007 if (DEBUGL(7))
1008 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
1009 group_base(group_from), group_base(group_to));
1010 struct group *gi_from = &board_group_info(board, group_from);
1011 struct group *gi_to = &board_group_info(board, group_to);
1013 /* We do this early before the group info is rewritten. */
1014 if (gi_from->libs == 2)
1015 board_atariable_rm(board, group_from, gi_from->lib[0], gi_from->lib[1]);
1016 else if (gi_from->libs == 1)
1017 board_capturable_rm(board, group_from, gi_from->lib[0]);
1019 if (DEBUGL(7))
1020 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
1022 if (gi_to->libs < GROUP_KEEP_LIBS) {
1023 for (int i = 0; i < gi_from->libs; i++) {
1024 for (int j = 0; j < gi_to->libs; j++)
1025 if (gi_to->lib[j] == gi_from->lib[i])
1026 goto next_from_lib;
1027 if (gi_to->libs == 0) {
1028 board_capturable_add(board, group_to, gi_from->lib[i]);
1029 } else if (gi_to->libs == 1) {
1030 board_capturable_rm(board, group_to, gi_to->lib[0]);
1031 board_atariable_add(board, group_to, gi_to->lib[0], gi_from->lib[i]);
1032 } else if (gi_to->libs == 2) {
1033 board_atariable_rm(board, group_to, gi_to->lib[0], gi_to->lib[1]);
1035 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
1036 if (gi_to->libs >= GROUP_KEEP_LIBS)
1037 break;
1038 next_from_lib:;
1042 #ifdef BOARD_TRAITS
1043 if (board_group_info(board, group_to).libs == 1) {
1044 /* Our group is currently in atari; make sure we properly
1045 * count in even the neighbors from the other group in the
1046 * capturable counter. */
1047 enum stone capturing_color = stone_other(board_at(board, group_to));
1048 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
1049 coord_t lib = board_group_info(board, group_to).lib[0];
1050 foreach_neighbor(board, lib, {
1051 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);
1052 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
1054 board_trait_queue(board, lib);
1056 #endif
1058 coord_t last_in_group;
1059 foreach_in_group(board, group_from) {
1060 last_in_group = c;
1061 group_at(board, c) = group_to;
1062 } foreach_in_group_end;
1063 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
1064 groupnext_at(board, group_base(group_to)) = group_base(group_from);
1065 memset(gi_from, 0, sizeof(struct group));
1067 if (DEBUGL(7))
1068 fprintf(stderr, "board_play_raw: merged group: %d\n",
1069 group_base(group_to));
1072 static group_t profiling_noinline
1073 new_group(struct board *board, coord_t coord)
1075 group_t group = coord_raw(coord);
1076 struct group *gi = &board_group_info(board, group);
1077 foreach_neighbor(board, coord, {
1078 if (board_at(board, c) == S_NONE)
1079 /* board_group_addlib is ridiculously expensive for us */
1080 #if GROUP_KEEP_LIBS < 4
1081 if (gi->libs < GROUP_KEEP_LIBS)
1082 #endif
1083 gi->lib[gi->libs++] = c;
1086 group_at(board, coord) = group;
1087 groupnext_at(board, coord) = 0;
1089 if (gi->libs == 2)
1090 board_atariable_add(board, group, gi->lib[0], gi->lib[1]);
1091 else if (gi->libs == 1)
1092 board_capturable_add(board, group, gi->lib[0]);
1093 check_libs_consistency(board, group);
1095 if (DEBUGL(8))
1096 fprintf(stderr, "new_group: added %d,%d to group %d\n",
1097 coord_x(coord, board), coord_y(coord, board),
1098 group_base(group));
1100 return group;
1103 static inline group_t
1104 play_one_neighbor(struct board *board,
1105 coord_t coord, enum stone color, enum stone other_color,
1106 coord_t c, group_t group)
1108 enum stone ncolor = board_at(board, c);
1109 group_t ngroup = group_at(board, c);
1111 inc_neighbor_count_at(board, c, color);
1112 /* We can be S_NONE, in that case we need to update the safety
1113 * trait since we might be left with only one liberty. */
1114 board_trait_queue(board, c);
1116 if (!ngroup)
1117 return group;
1119 board_group_rmlib(board, ngroup, coord);
1120 if (DEBUGL(7))
1121 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
1122 group_base(ngroup), ncolor, color, other_color);
1124 if (ncolor == color && ngroup != group) {
1125 if (!group) {
1126 group = ngroup;
1127 add_to_group(board, group, c, coord);
1128 } else {
1129 merge_groups(board, group, ngroup);
1131 } else if (ncolor == other_color) {
1132 if (DEBUGL(8)) {
1133 struct group *gi = &board_group_info(board, ngroup);
1134 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
1135 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
1136 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
1137 fprintf(stderr, "\n");
1139 if (unlikely(board_group_captured(board, ngroup)))
1140 board_group_capture(board, ngroup);
1142 return group;
1145 /* We played on a place with at least one liberty. We will become a member of
1146 * some group for sure. */
1147 static group_t profiling_noinline
1148 board_play_outside(struct board *board, struct move *m, int f)
1150 coord_t coord = m->coord;
1151 enum stone color = m->color;
1152 enum stone other_color = stone_other(color);
1153 group_t group = 0;
1155 board->f[f] = board->f[--board->flen];
1156 if (DEBUGL(6))
1157 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1159 #if defined(BOARD_TRAITS) && defined(DEBUG)
1160 /* Sanity check that cap matches reality. */
1162 int a = 0;
1163 foreach_neighbor(board, coord, {
1164 group_t g = group_at(board, c);
1165 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1167 assert(a == trait_at(board, coord, color).cap);
1168 assert(board_trait_safe(board, coord, color) == trait_at(board, coord, color).safe);
1170 #endif
1171 foreach_neighbor(board, coord, {
1172 group = play_one_neighbor(board, coord, color, other_color, c, group);
1175 board_at(board, coord) = color;
1176 if (unlikely(!group))
1177 group = new_group(board, coord);
1178 board_gamma_update(board, coord, S_BLACK);
1179 board_gamma_update(board, coord, S_WHITE);
1181 board->last_move2 = board->last_move;
1182 board->last_move = *m;
1183 board->moves++;
1184 board_hash_update(board, coord, color);
1185 board_symmetry_update(board, &board->symmetry, coord);
1186 struct move ko = { pass, S_NONE };
1187 board->ko = ko;
1189 return group;
1192 /* We played in an eye-like shape. Either we capture at least one of the eye
1193 * sides in the process of playing, or return -1. */
1194 static int profiling_noinline
1195 board_play_in_eye(struct board *board, struct move *m, int f)
1197 coord_t coord = m->coord;
1198 enum stone color = m->color;
1199 /* Check ko: Capture at a position of ko capture one move ago */
1200 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
1201 if (DEBUGL(5))
1202 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1203 return -1;
1204 } else if (DEBUGL(6)) {
1205 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1206 color, coord_x(coord, board), coord_y(coord, board),
1207 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1210 struct move ko = { pass, S_NONE };
1212 int captured_groups = 0;
1214 foreach_neighbor(board, coord, {
1215 group_t g = group_at(board, c);
1216 if (DEBUGL(7))
1217 fprintf(stderr, "board_check: group %d has %d libs\n",
1218 g, board_group_info(board, g).libs);
1219 captured_groups += (board_group_info(board, g).libs == 1);
1222 if (likely(captured_groups == 0)) {
1223 if (DEBUGL(5)) {
1224 if (DEBUGL(6))
1225 board_print(board, stderr);
1226 fprintf(stderr, "board_check: one-stone suicide\n");
1229 return -1;
1231 #ifdef BOARD_TRAITS
1232 /* We _will_ for sure capture something. */
1233 assert(trait_at(board, coord, color).cap > 0);
1234 assert(trait_at(board, coord, color).safe == board_trait_safe(board, coord, color));
1235 #endif
1237 board->f[f] = board->f[--board->flen];
1238 if (DEBUGL(6))
1239 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1241 foreach_neighbor(board, coord, {
1242 inc_neighbor_count_at(board, c, color);
1243 /* Originally, this could not have changed any trait
1244 * since no neighbors were S_NONE, however by now some
1245 * of them might be removed from the board. */
1246 board_trait_queue(board, c);
1248 group_t group = group_at(board, c);
1249 if (!group)
1250 continue;
1252 board_group_rmlib(board, group, coord);
1253 if (DEBUGL(7))
1254 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1255 group_base(group));
1257 if (board_group_captured(board, group)) {
1258 if (board_group_capture(board, group) == 1) {
1259 /* If we captured multiple groups at once,
1260 * we can't be fighting ko so we don't need
1261 * to check for that. */
1262 ko.color = stone_other(color);
1263 ko.coord = c;
1264 board->last_ko = ko;
1265 board->last_ko_age = board->moves;
1266 if (DEBUGL(5))
1267 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1272 board_at(board, coord) = color;
1273 group_t group = new_group(board, coord);
1274 board_gamma_update(board, coord, S_BLACK);
1275 board_gamma_update(board, coord, S_WHITE);
1277 board->last_move2 = board->last_move;
1278 board->last_move = *m;
1279 board->moves++;
1280 board_hash_update(board, coord, color);
1281 board_hash_commit(board);
1282 board_traits_recompute(board);
1283 board_symmetry_update(board, &board->symmetry, coord);
1284 board->ko = ko;
1286 return !!group;
1289 static int __attribute__((flatten))
1290 board_play_f(struct board *board, struct move *m, int f)
1292 if (DEBUGL(7)) {
1293 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
1295 if (likely(!board_is_eyelike(board, m->coord, stone_other(m->color)))) {
1296 /* NOT playing in an eye. Thus this move has to succeed. (This
1297 * is thanks to New Zealand rules. Otherwise, multi-stone
1298 * suicide might fail.) */
1299 group_t group = board_play_outside(board, m, f);
1300 if (unlikely(board_group_captured(board, group))) {
1301 board_group_capture(board, group);
1303 board_hash_commit(board);
1304 board_traits_recompute(board);
1305 return 0;
1306 } else {
1307 return board_play_in_eye(board, m, f);
1312 board_play(struct board *board, struct move *m)
1314 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1315 struct move nomove = { pass, S_NONE };
1316 board->ko = nomove;
1317 board->last_move2 = board->last_move;
1318 board->last_move = *m;
1319 return 0;
1322 int f;
1323 for (f = 0; f < board->flen; f++)
1324 if (board->f[f] == coord_raw(m->coord))
1325 return board_play_f(board, m, f);
1327 if (DEBUGL(7))
1328 fprintf(stderr, "board_check: stone exists\n");
1329 return -1;
1333 static inline bool
1334 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1336 coord_raw(*coord) = b->f[f];
1337 if (unlikely(is_pass(*coord)))
1338 return random_pass;
1339 struct move m = { *coord, color };
1340 if (DEBUGL(6))
1341 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
1342 return (likely(!board_is_one_point_eye(b, *coord, color)) /* bad idea to play into one, usually */
1343 && board_is_valid_move(b, &m)
1344 && (!permit || permit(permit_data, b, &m))
1345 && likely(board_play_f(b, &m, f) >= 0));
1348 void
1349 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1351 int base = fast_random(b->flen);
1352 coord_pos(*coord, base, b);
1353 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
1354 return;
1356 int f;
1357 for (f = base + 1; f < b->flen; f++)
1358 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1359 return;
1360 for (f = 0; f < base; f++)
1361 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1362 return;
1364 *coord = pass;
1365 struct move m = { pass, color };
1366 board_play(b, &m);
1370 bool
1371 board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color)
1373 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1375 /* XXX: We attempt false eye detection but we will yield false
1376 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1378 foreach_diag_neighbor(board, coord) {
1379 color_diag_libs[(enum stone) board_at(board, c)]++;
1380 } foreach_diag_neighbor_end;
1381 /* For false eye, we need two enemy stones diagonally in the
1382 * middle of the board, or just one enemy stone at the edge
1383 * or in the corner. */
1384 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1385 return color_diag_libs[stone_other(eye_color)] >= 2;
1388 bool
1389 board_is_one_point_eye(struct board *board, coord_t coord, enum stone eye_color)
1391 return board_is_eyelike(board, coord, eye_color)
1392 && !board_is_false_eyelike(board, coord, eye_color);
1395 enum stone
1396 board_get_one_point_eye(struct board *board, coord_t coord)
1398 if (board_is_one_point_eye(board, coord, S_WHITE))
1399 return S_WHITE;
1400 else if (board_is_one_point_eye(board, coord, S_BLACK))
1401 return S_BLACK;
1402 else
1403 return S_NONE;
1407 float
1408 board_fast_score(struct board *board)
1410 int scores[S_MAX];
1411 memset(scores, 0, sizeof(scores));
1413 foreach_point(board) {
1414 enum stone color = board_at(board, c);
1415 if (color == S_NONE)
1416 color = board_get_one_point_eye(board, c);
1417 scores[color]++;
1418 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1419 } foreach_point_end;
1421 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1424 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1426 /* One flood-fill iteration; returns true if next iteration
1427 * is required. */
1428 static bool
1429 board_tromp_taylor_iter(struct board *board, int *ownermap)
1431 bool needs_update = false;
1432 foreach_point(board) {
1433 /* Ignore occupied and already-dame positions. */
1434 if (board_at(board, c) != S_NONE || ownermap[c] == 3)
1435 continue;
1436 /* Count neighbors. */
1437 int nei[4] = {0};
1438 foreach_neighbor(board, c, {
1439 nei[ownermap[c]]++;
1441 /* If we have neighbors of both colors, or dame,
1442 * we are dame too. */
1443 if ((nei[1] && nei[2]) || nei[3]) {
1444 ownermap[c] = 3;
1445 /* Speed up the propagation. */
1446 foreach_neighbor(board, c, {
1447 if (board_at(board, c) == S_NONE)
1448 ownermap[c] = 3;
1450 needs_update = true;
1451 continue;
1453 /* If we have neighbors of one color, we are owned
1454 * by that color, too. */
1455 if (!ownermap[c] && (nei[1] || nei[2])) {
1456 int newowner = nei[1] ? 1 : 2;
1457 ownermap[c] = newowner;
1458 /* Speed up the propagation. */
1459 foreach_neighbor(board, c, {
1460 if (board_at(board, c) == S_NONE && !ownermap[c])
1461 ownermap[c] = newowner;
1463 needs_update = true;
1464 continue;
1466 } foreach_point_end;
1467 return needs_update;
1470 /* Tromp-Taylor Counting */
1471 float
1472 board_official_score(struct board *board, struct move_queue *q)
1475 /* A point P, not colored C, is said to reach C, if there is a path of
1476 * (vertically or horizontally) adjacent points of P's color from P to
1477 * a point of color C.
1479 * A player's score is the number of points of her color, plus the
1480 * number of empty points that reach only her color. */
1482 int ownermap[board_size2(board)];
1483 int s[4] = {0};
1484 const int o[4] = {0, 1, 2, 0};
1485 foreach_point(board) {
1486 ownermap[c] = o[board_at(board, c)];
1487 s[board_at(board, c)]++;
1488 } foreach_point_end;
1490 if (q) {
1491 /* Process dead groups. */
1492 for (int i = 0; i < q->moves; i++) {
1493 foreach_in_group(board, q->move[i]) {
1494 enum stone color = board_at(board, c);
1495 ownermap[c] = o[stone_other(color)];
1496 s[color]--; s[stone_other(color)]++;
1497 } foreach_in_group_end;
1501 /* We need to special-case empty board. */
1502 if (!s[S_BLACK] && !s[S_WHITE])
1503 return board->komi + board->handicap;
1505 while (board_tromp_taylor_iter(board, ownermap))
1506 /* Flood-fill... */;
1508 int scores[S_MAX];
1509 memset(scores, 0, sizeof(scores));
1511 foreach_point(board) {
1512 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1513 if (ownermap[c] == 3)
1514 continue;
1515 scores[ownermap[c]]++;
1516 } foreach_point_end;
1518 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];