is_selfatari(): Fix the capture possibility test
[pachi.git] / playout / moggy.c
blob6a38e3a48d5d9fbbdbf373b73a395f876de8018e
1 #include <assert.h>
2 #include <math.h>
3 #include <stdio.h>
4 #include <stdlib.h>
6 #define DEBUG
7 #include "board.h"
8 #include "debug.h"
9 #include "playout.h"
10 #include "playout/moggy.h"
11 #include "random.h"
13 #define PLDEBUGL(n) DEBUGL_(p->debug_level, n)
16 struct moggy_policy {
17 bool ladders, ladderassess, borderladders;
18 int lcapturerate, capturerate, patternrate;
21 #define MQL 64
22 struct move_queue {
23 int moves;
24 coord_t move[MQL];
27 static void
28 mq_nodup(struct move_queue *q)
30 if ((q->moves > 1 && q->move[q->moves - 2] == q->move[q->moves - 1])
31 || (q->moves > 2 && q->move[q->moves - 3] == q->move[q->moves - 1])
32 || (q->moves > 3 && q->move[q->moves - 4] == q->move[q->moves - 1]))
33 q->moves--;
37 /* Pattern encoding:
38 * X: black; O: white; .: empty; #: edge
39 * x: !black; o: !white; ?: any
41 * extra X: pattern valid only for one side;
42 * middle point ignored. */
44 static char moggy_patterns_src[][11] = {
45 /* hane pattern - enclosing hane */
46 "XOX"
47 "..."
48 "???",
49 /* hane pattern - non-cutting hane */
50 "XO."
51 "..."
52 "?.?",
53 /* hane pattern - magari */
54 "XO?"
55 "X.."
56 "?.?",
57 /* hane pattern - thin hane */
58 "XOO"
59 "..."
60 "?.?" "X",
61 /* cut1 pattern (kiri) - unprotected cut */
62 "XO?"
63 "O.o"
64 "?o?",
65 /* cut1 pattern (kiri) - peeped cut */
66 "XO?"
67 "O.X"
68 "???",
69 /* cut2 pattern (de) */
70 "?X?"
71 "O.O"
72 "ooo",
73 /* cut keima (not in Mogo) */
74 "OX?"
75 "o.O"
76 "o??",
77 /* side pattern - chase */
78 "X.?"
79 "O.?"
80 "##?",
81 /* side pattern - weirdness (SUSPICIOUS) */
82 "?X?"
83 "X.O"
84 "###",
85 /* side pattern - sagari (SUSPICIOUS) */
86 "?XO"
87 "?.?" /* "?.x" ? */
88 "###" "X",
89 /* side pattern - weirdcut (SUSPICIOUS) */
90 /* "?OX"
91 "?.O"
92 "?##" "X", */
93 /* side pattern - cut (SUSPICIOUS) */
94 "?OX"
95 "X.O"
96 "###" /* Mogo has "X" */,
98 #define moggy_patterns_src_n sizeof(moggy_patterns_src) / sizeof(moggy_patterns_src[0])
100 /* Hashtable: 2*8 bits (ignore middle point, 2 bits per intersection) */
101 /* Value: 0: no pattern, 1: black pattern, 2: white pattern, 3: both patterns */
102 static char moggy_patterns[65536];
104 static void
105 _record_pattern(char *table, char *str, int pat, int fixed_color)
107 //fprintf(stderr, "[%s] %04x\n", str, pat);
109 /* Original color assignment */
110 table[pat] = fixed_color ? fixed_color : 3;
112 /* Reverse color assignment - achieved by swapping odd and even bits */
113 pat = ((pat >> 1) & 0x5555) | ((pat & 0x5555) << 1);
114 table[pat] = fixed_color ? 2 - (fixed_color == 2) : 3;
117 static int
118 _pat_vmirror(int pat)
120 /* V mirror pattern; reverse order of 3-2-3 chunks */
121 return ((pat & 0xfc00) >> 10) | (pat & 0x03c0) | ((pat & 0x003f) << 10);
124 static int
125 _pat_hmirror(int pat)
127 /* H mirror pattern; reverse order of 2-bit values within the chunks */
128 #define rev3(p) ((p >> 4) | (p & 0xc) | ((p & 0x3) << 4))
129 #define rev2(p) ((p >> 2) | ((p & 0x3) << 2))
130 return (rev3((pat & 0xfc00) >> 10) << 10)
131 | (rev2((pat & 0x03c0) >> 6) << 6)
132 | rev3((pat & 0x003f));
133 #undef rev3
134 #undef rev2
137 static int
138 _pat_90rot(int pat)
140 /* Rotate by 90 degrees:
141 * 5 6 7 7 4 2
142 * 3 4 -> 6 1
143 * 0 1 2 5 3 0 */
144 /* I'm too lazy to optimize this :) */
145 int vals[8];
146 for (int i = 0; i < 8; i++)
147 vals[i] = (pat >> (i * 2)) & 0x3;
148 int vals2[8];
149 vals2[0] = vals[5]; vals2[1] = vals[3]; vals2[2] = vals[0];
150 vals2[3] = vals[6]; vals2[4] = vals[1];
151 vals2[5] = vals[7]; vals2[6] = vals[4]; vals2[7] = vals[2];
152 int p2 = 0;
153 for (int i = 0; i < 8; i++)
154 p2 |= vals2[i] << (i * 2);
155 return p2;
158 static void
159 _gen_pattern(char *table, int pat, char *src, int srclen, int fixed_color)
161 for (; srclen > 0; src++, srclen--) {
162 if (srclen == 5)
163 continue;
164 int patofs = (srclen > 5 ? srclen - 1 : srclen) - 1;
165 switch (*src) {
166 case '?':
167 *src = '.'; _gen_pattern(table, pat, src, srclen, fixed_color);
168 *src = 'X'; _gen_pattern(table, pat, src, srclen, fixed_color);
169 *src = 'O'; _gen_pattern(table, pat, src, srclen, fixed_color);
170 *src = '#'; _gen_pattern(table, pat, src, srclen, fixed_color);
171 *src = '?'; // for future recursions
172 return;
173 case 'x':
174 *src = '.'; _gen_pattern(table, pat, src, srclen, fixed_color);
175 *src = 'O'; _gen_pattern(table, pat, src, srclen, fixed_color);
176 *src = '#'; _gen_pattern(table, pat, src, srclen, fixed_color);
177 *src = 'x'; // for future recursions
178 return;
179 case 'o':
180 *src = '.'; _gen_pattern(table, pat, src, srclen, fixed_color);
181 *src = 'X'; _gen_pattern(table, pat, src, srclen, fixed_color);
182 *src = '#'; _gen_pattern(table, pat, src, srclen, fixed_color);
183 *src = 'o'; // for future recursions
184 return;
185 case '.': /* 0 */ break;
186 case 'X': pat |= S_BLACK << (patofs * 2); break;
187 case 'O': pat |= S_WHITE << (patofs * 2); break;
188 case '#': pat |= S_OFFBOARD << (patofs * 2); break;
192 /* Original pattern, all transpositions and rotations */
193 _record_pattern(table, src - 9, pat, fixed_color);
194 _record_pattern(table, src - 9, _pat_vmirror(pat), fixed_color);
195 _record_pattern(table, src - 9, _pat_hmirror(pat), fixed_color);
196 _record_pattern(table, src - 9, _pat_vmirror(_pat_hmirror(pat)), fixed_color);
197 _record_pattern(table, src - 9, _pat_90rot(pat), fixed_color);
198 _record_pattern(table, src - 9, _pat_90rot(_pat_vmirror(pat)), fixed_color);
199 _record_pattern(table, src - 9, _pat_90rot(_pat_hmirror(pat)), fixed_color);
200 _record_pattern(table, src - 9, _pat_90rot(_pat_vmirror(_pat_hmirror(pat))), fixed_color);
203 static void __attribute__((constructor))
204 _init_patterns(void)
206 for (int i = 0; i < moggy_patterns_src_n; i++) {
207 int fixed_color = 0;
208 switch (moggy_patterns_src[i][9]) {
209 case 'X': fixed_color = S_BLACK; break;
210 case 'O': fixed_color = S_WHITE; break;
212 _gen_pattern(moggy_patterns, 0, moggy_patterns_src[i], 9, fixed_color);
217 /* Check if we match any pattern centered on given move. */
218 static bool
219 test_pattern_here(struct playout_policy *p, char *hashtable,
220 struct board *b, struct move *m)
222 int pat = 0;
223 int x = coord_x(m->coord, b), y = coord_y(m->coord, b);
224 pat |= (board_atxy(b, x - 1, y - 1) << 14)
225 | (board_atxy(b, x, y - 1) << 12)
226 | (board_atxy(b, x + 1, y - 1) << 10);
227 pat |= (board_atxy(b, x - 1, y) << 8)
228 | (board_atxy(b, x + 1, y) << 6);
229 pat |= (board_atxy(b, x - 1, y + 1) << 4)
230 | (board_atxy(b, x, y + 1) << 2)
231 | (board_atxy(b, x + 1, y + 1));
232 //fprintf(stderr, "(%d,%d) hashtable[%04x] = %d\n", x, y, pat, hashtable[pat]);
233 return (hashtable[pat] & m->color);
236 static void
237 apply_pattern_here(struct playout_policy *p, char *hashtable,
238 struct board *b, struct move *m, struct move_queue *q)
240 if (test_pattern_here(p, hashtable, b, m)
241 && !is_selfatari(b, m->color, m->coord))
242 q->move[q->moves++] = m->coord;
245 /* Check if we match any pattern around given move (with the other color to play). */
246 static coord_t
247 apply_pattern(struct playout_policy *p, struct board *b, struct move *m)
249 //struct moggy_policy *pp = p->data;
250 struct move_queue q;
251 q.moves = 0;
253 /* Suicides do not make any patterns and confuse us. */
254 if (board_at(b, m->coord) == S_NONE || board_at(b, m->coord) == S_OFFBOARD)
255 return pass;
257 foreach_neighbor(b, m->coord, {
258 struct move m2; m2.coord = c; m2.color = stone_other(m->color);
259 if (board_at(b, c) == S_NONE)
260 apply_pattern_here(p, moggy_patterns, b, &m2, &q);
262 foreach_diag_neighbor(b, m->coord) {
263 struct move m2; m2.coord = c; m2.color = stone_other(m->color);
264 if (board_at(b, c) == S_NONE)
265 apply_pattern_here(p, moggy_patterns, b, &m2, &q);
266 } foreach_diag_neighbor_end;
268 if (PLDEBUGL(5)) {
269 fprintf(stderr, "Pattern candidate moves: ");
270 for (int i = 0; i < q.moves; i++) {
271 fprintf(stderr, "%s ", coord2sstr(q.move[i], b));
273 fprintf(stderr, "\n");
276 int i = fast_random(q.moves);
277 return q.moves ? q.move[i] : pass;
282 /* Is this ladder breaker friendly for the one who catches ladder. */
283 static bool
284 ladder_catcher(struct board *b, int x, int y, enum stone laddered)
286 enum stone breaker = board_atxy(b, x, y);
287 return breaker == stone_other(laddered) || breaker == S_OFFBOARD;
290 static bool
291 ladder_catches(struct playout_policy *p, struct board *b, coord_t coord, group_t laddered)
293 struct moggy_policy *pp = p->data;
295 /* This is very trivial and gets a lot of corner cases wrong.
296 * We need this to be just very fast. One important point is
297 * that we sometimes might not notice a ladder but if we do,
298 * it should always work; thus we can use this for strong
299 * negative hinting safely. */
300 //fprintf(stderr, "ladder check\n");
302 enum stone lcolor = board_at(b, group_base(laddered));
303 int x = coord_x(coord, b), y = coord_y(coord, b);
305 /* First, special-case first-line "ladders". This is a huge chunk
306 * of ladders we actually meet and want to play. */
307 if (pp->borderladders
308 && neighbor_count_at(b, coord, S_OFFBOARD) == 1
309 && neighbor_count_at(b, coord, lcolor) == 1) {
310 if (PLDEBUGL(5))
311 fprintf(stderr, "border ladder\n");
312 /* Direction along border; xd is horiz. border, yd vertical. */
313 int xd = 0, yd = 0;
314 if (board_atxy(b, x + 1, y) == S_OFFBOARD || board_atxy(b, x - 1, y) == S_OFFBOARD)
315 yd = 1;
316 else
317 xd = 1;
318 /* Direction from the border; -1 is above/left, 1 is below/right. */
319 int dd = (board_atxy(b, x + yd, y + xd) == S_OFFBOARD) ? 1 : -1;
320 if (PLDEBUGL(6))
321 fprintf(stderr, "xd %d yd %d dd %d\n", xd, yd, dd);
322 /* | ? ?
323 * | . O #
324 * | c X #
325 * | . O #
326 * | ? ? */
327 /* This is normally caught, unless we have friends both above
328 * and below... */
329 if (board_atxy(b, x + xd * 2, y + yd * 2) == lcolor
330 && board_atxy(b, x - xd * 2, y - yd * 2) == lcolor)
331 return false;
332 /* ...or can't block where we need because of shortage
333 * of liberties. */
334 int libs1 = board_group_info(b, group_atxy(b, x + xd - yd * dd, y + yd - xd * dd)).libs;
335 int libs2 = board_group_info(b, group_atxy(b, x - xd - yd * dd, y - yd - xd * dd)).libs;
336 if (PLDEBUGL(6))
337 fprintf(stderr, "libs1 %d libs2 %d\n", libs1, libs2);
338 if (libs1 < 2 && libs2 < 2)
339 return false;
340 if (board_atxy(b, x + xd * 2, y + yd * 2) == lcolor && libs1 < 3)
341 return false;
342 if (board_atxy(b, x - xd * 2, y - yd * 2) == lcolor && libs2 < 3)
343 return false;
344 return true;
347 /* Figure out the ladder direction */
348 int xd, yd;
349 xd = board_atxy(b, x + 1, y) == S_NONE ? 1 : board_atxy(b, x - 1, y) == S_NONE ? -1 : 0;
350 yd = board_atxy(b, x, y + 1) == S_NONE ? 1 : board_atxy(b, x, y - 1) == S_NONE ? -1 : 0;
352 /* We do only tight ladders, not loose ladders. Furthermore,
353 * the ladders need to be simple:
354 * . X . . . X
355 * c O X supported . c O unsupported
356 * X # # X O #
359 /* For given (xd,yd), we have two possibilities where to move
360 * next. Consider (-1,1):
361 * n X . n c X
362 * c O X X O #
363 * X # # . X #
365 if (!xd || !yd || !(ladder_catcher(b, x - xd, y, lcolor) ^ ladder_catcher(b, x, y - yd, lcolor))) {
366 /* Silly situation, probably non-simple ladder or suicide. */
367 /* TODO: In case of basic non-simple ladder, play out both variants. */
368 if (PLDEBUGL(5))
369 fprintf(stderr, "non-simple ladder\n");
370 return false;
373 #define ladder_check(xd1_, yd1_, xd2_, yd2_) \
374 if (board_atxy(b, x, y) != S_NONE) { \
375 /* Did we hit a stone when playing out ladder? */ \
376 if (ladder_catcher(b, x, y, lcolor)) \
377 return true; /* ladder works */ \
378 if (board_group_info(b, group_atxy(b, x, y)).lib[0] > 0) \
379 return false; /* friend that's not in atari himself */ \
380 } else { \
381 /* No. So we are at new position. \
382 * We need to check indirect ladder breakers. */ \
383 /* . 2 x . . \
384 * . x o O 1 <- only at O we can check for o at 2 \
385 * x o o x . otherwise x at O would be still deadly \
386 * o o x . . \
387 * We check for o and x at 1, these are vital. \
388 * We check only for o at 2; x at 2 would mean we \
389 * need to fork (one step earlier). */ \
390 enum stone s1 = board_atxy(b, x + (xd1_), y + (yd1_)); \
391 if (s1 == lcolor) return false; \
392 if (s1 == stone_other(lcolor)) return true; \
393 enum stone s2 = board_atxy(b, x + (xd2_), y + (yd2_)); \
394 if (s2 == lcolor) return false; \
396 #define ladder_horiz do { if (PLDEBUGL(6)) fprintf(stderr, "%d,%d horiz step %d\n", x, y, xd); x += xd; ladder_check(xd, 0, -2 * xd, yd); } while (0)
397 #define ladder_vert do { if (PLDEBUGL(6)) fprintf(stderr, "%d,%d vert step %d\n", x, y, yd); y += yd; ladder_check(0, yd, xd, -2 * yd); } while (0)
399 if (ladder_catcher(b, x - xd, y, lcolor))
400 ladder_horiz;
401 do {
402 ladder_vert;
403 ladder_horiz;
404 } while (1);
408 static void
409 group_atari_check(struct playout_policy *p, struct board *b, group_t group, struct move_queue *q)
411 struct moggy_policy *pp = p->data;
412 enum stone color = board_at(b, group_base(group));
413 coord_t lib = board_group_info(b, group).lib[0];
415 assert(color != S_OFFBOARD && color != S_NONE);
416 if (PLDEBUGL(5))
417 fprintf(stderr, "atariiiiiiiii %s of color %d\n", coord2sstr(lib, b), color);
418 assert(board_at(b, lib) == S_NONE);
420 /* Can we capture some neighbor? */
421 foreach_in_group(b, group) {
422 foreach_neighbor(b, c, {
423 if (board_at(b, c) != stone_other(color)
424 || board_group_info(b, group_at(b, c)).libs > 1)
425 continue;
426 if (PLDEBUGL(6))
427 fprintf(stderr, "can capture group %d\n", group_at(b, c));
428 /* If we are saving our group, capture! */
429 if (b->last_move.color == stone_other(color))
430 q->move[q->moves++] = board_group_info(b, group_at(b, c)).lib[0];
431 else /* If we chase the group, capture it now! */
432 q->move[q->moves++] = lib;
433 /* Make sure capturing the group will actually
434 * expand our liberties if we are filling our
435 * last liberty. */
436 if (q->move[q->moves - 1] == lib && is_selfatari(b, color, lib))
437 q->moves--;
438 else
439 mq_nodup(q);
441 } foreach_in_group_end;
443 /* Do not suicide... */
444 if (is_selfatari(b, color, lib))
445 return;
446 if (PLDEBUGL(6))
447 fprintf(stderr, "...escape route valid\n");
449 /* ...or play out ladders. */
450 if (pp->ladders && ladder_catches(p, b, lib, group)) {
451 return;
453 if (PLDEBUGL(6))
454 fprintf(stderr, "...no ladder\n");
456 q->move[q->moves++] = lib;
457 mq_nodup(q);
460 static coord_t
461 global_atari_check(struct playout_policy *p, struct board *b)
463 struct move_queue q;
464 q.moves = 0;
466 if (b->clen == 0)
467 return pass;
469 int g_base = fast_random(b->clen);
470 for (int g = g_base; g < b->clen; g++) {
471 group_atari_check(p, b, group_at(b, group_base(b->c[g])), &q);
472 if (q.moves > 0)
473 return q.move[fast_random(q.moves)];
475 for (int g = 0; g < g_base; g++) {
476 group_atari_check(p, b, group_at(b, group_base(b->c[g])), &q);
477 if (q.moves > 0)
478 return q.move[fast_random(q.moves)];
480 return pass;
483 static coord_t
484 local_atari_check(struct playout_policy *p, struct board *b, struct move *m)
486 struct move_queue q;
487 q.moves = 0;
489 /* Did the opponent play a self-atari? */
490 if (board_group_info(b, group_at(b, m->coord)).libs == 1) {
491 group_atari_check(p, b, group_at(b, m->coord), &q);
494 foreach_neighbor(b, m->coord, {
495 group_t g = group_at(b, c);
496 if (!g || board_group_info(b, g).libs != 1)
497 continue;
498 group_atari_check(p, b, g, &q);
501 if (PLDEBUGL(5)) {
502 fprintf(stderr, "Local atari candidate moves: ");
503 for (int i = 0; i < q.moves; i++) {
504 fprintf(stderr, "%s ", coord2sstr(q.move[i], b));
506 fprintf(stderr, "\n");
509 int i = fast_random(q.moves);
510 return q.moves ? q.move[i] : pass;
513 coord_t
514 playout_moggy_choose(struct playout_policy *p, struct board *b, enum stone our_real_color)
516 struct moggy_policy *pp = p->data;
517 coord_t c;
519 if (PLDEBUGL(5))
520 board_print(b, stderr);
522 /* Local checks */
523 if (!is_pass(b->last_move.coord)) {
524 /* Local group in atari? */
525 if (pp->lcapturerate > fast_random(100)) {
526 c = local_atari_check(p, b, &b->last_move);
527 if (!is_pass(c))
528 return c;
531 /* Check for patterns we know */
532 if (pp->patternrate > fast_random(100)) {
533 c = apply_pattern(p, b, &b->last_move);
534 if (!is_pass(c))
535 return c;
539 /* Global checks */
541 /* Any groups in atari? */
542 if (pp->capturerate > fast_random(100)) {
543 c = global_atari_check(p, b);
544 if (!is_pass(c))
545 return c;
548 return pass;
551 float
552 playout_moggy_assess(struct playout_policy *p, struct board *b, struct move *m)
554 struct moggy_policy *pp = p->data;
556 if (is_pass(m->coord))
557 return NAN;
559 if (PLDEBUGL(5)) {
560 fprintf(stderr, "ASSESS of %s:\n", coord2sstr(m->coord, b));
561 board_print(b, stderr);
564 /* Are we dealing with atari? */
565 if (pp->lcapturerate || pp->capturerate) {
566 bool ladder = false;
568 foreach_neighbor(b, m->coord, {
569 group_t g = group_at(b, c);
570 if (!g || board_group_info(b, g).libs != 1)
571 continue;
573 struct move_queue q; q.moves = 0;
574 group_atari_check(p, b, g, &q);
575 while (q.moves--)
576 if (q.move[q.moves] == m->coord)
577 return 1.0;
579 /* _Never_ play here if this move plays out
580 * a caught ladder. (Unless it captures another
581 * group. :-) */
582 if (pp->ladderassess && ladder_catches(p, b, m->coord, g))
583 ladder = true;
586 if (ladder)
587 return 0.0;
590 /* Pattern check */
591 if (pp->patternrate) {
592 if (test_pattern_here(p, moggy_patterns, b, m))
593 return 1.0;
596 return NAN;
600 struct playout_policy *
601 playout_moggy_init(char *arg)
603 struct playout_policy *p = calloc(1, sizeof(*p));
604 struct moggy_policy *pp = calloc(1, sizeof(*pp));
605 p->data = pp;
606 p->choose = playout_moggy_choose;
607 p->assess = playout_moggy_assess;
609 pp->lcapturerate = 90;
610 pp->capturerate = 90;
611 pp->patternrate = 90;
612 pp->ladders = pp->borderladders = true;
613 pp->ladderassess = true;
615 if (arg) {
616 char *optspec, *next = arg;
617 while (*next) {
618 optspec = next;
619 next += strcspn(next, ":");
620 if (*next) { *next++ = 0; } else { *next = 0; }
622 char *optname = optspec;
623 char *optval = strchr(optspec, '=');
624 if (optval) *optval++ = 0;
626 if (!strcasecmp(optname, "lcapturerate") && optval) {
627 pp->lcapturerate = atoi(optval);
628 } else if (!strcasecmp(optname, "capturerate") && optval) {
629 pp->capturerate = atoi(optval);
630 } else if (!strcasecmp(optname, "patternrate") && optval) {
631 pp->patternrate = atoi(optval);
632 } else if (!strcasecmp(optname, "ladders")) {
633 pp->ladders = optval && *optval == '0' ? false : true;
634 } else if (!strcasecmp(optname, "borderladders")) {
635 pp->borderladders = optval && *optval == '0' ? false : true;
636 } else if (!strcasecmp(optname, "ladderassess")) {
637 pp->ladderassess = optval && *optval == '0' ? false : true;
638 } else {
639 fprintf(stderr, "playout-moggy: Invalid policy argument %s or missing value\n", optname);
644 return p;