Moggy: Support for choosing from full list of candidates
[pachi.git] / playout / moggy.c
blob385d06bd32c9018b315c08cb4c649e533993050e
1 /* Playout policy by stochastically applying a fixed set of decision
2 * rules in given order - modelled after the intelligent playouts
3 * in the Mogo engine. */
5 #include <assert.h>
6 #include <math.h>
7 #include <stdio.h>
8 #include <stdlib.h>
10 #define DEBUG
11 #include "board.h"
12 #include "debug.h"
13 #include "joseki/base.h"
14 #include "mq.h"
15 #include "pattern3.h"
16 #include "playout.h"
17 #include "playout/moggy.h"
18 #include "random.h"
19 #include "tactics.h"
20 #include "uct/prior.h"
22 #define PLDEBUGL(n) DEBUGL_(p->debug_level, n)
24 /* Whether to avoid capturing/atariing doomed groups (this is big
25 * performance hit and may reduce playouts balance; it does increase
26 * the strength, but not quite proportionally to the performance). */
27 //#define NO_DOOMED_GROUPS
30 /* Note that the context can be shared by multiple threads! */
32 struct moggy_policy {
33 bool ladders, ladderassess, borderladders, assess_local;
34 unsigned int lcapturerate, atarirate, capturerate, patternrate, korate, josekirate;
35 unsigned int selfatarirate, alwaysccaprate;
36 unsigned int fillboardtries;
37 int koage;
38 /* Whether to look for patterns around second-to-last move. */
39 bool pattern2;
40 /* Whether, when self-atari attempt is detected, to play the other
41 * group's liberty if that is non-self-atari. */
42 bool selfatari_other;
44 struct joseki_dict *jdict;
45 struct pattern3s patterns;
49 struct group_state {
50 enum {
51 G_ATARI,
52 G_2LIB, /* Unused. */
53 G_SAFE /* Unused. */
54 } status:2;
56 /* Below, we keep track of each trait for each |color_to_play */
57 int capturable_ready:2; // is @capturable meaningful?
58 int capturable:2;
60 int can_countercapture_ready:2;
61 int can_countercapture:2;
64 /* Cache of evaluation of various board features. */
65 struct board_state {
66 int bsize2;
67 hash_t hash;
68 struct group_state *groups; /* [board_size2()], indexed by group_t */
69 unsigned char *groups_known; /* Bitmap of known groups. */
72 /* Using board cache: this turns out to be actually a 10% slowdown,
73 * since we reuse data in the cache only very little within single
74 * move. */
75 // #define CACHE_STATE
76 /* Reusing board cache across moves if they are successive on the
77 * board; only cache entries within cfg distance 2 of the last move
78 * are cleared. */
79 // #define PERSISTENT_STATE
81 #ifdef CACHE_STATE
82 static __thread struct board_state *ss;
84 static bool
85 board_state_reuse(struct board_state *s, struct board *b)
87 /* Decide how much of the board state we can reuse. */
88 /* We do not cache ladder decisions, so we don't have
89 * to worry about this. */
90 coord_t c = b->last_move.coord;
92 if (unlikely(is_pass(c))) {
93 /* Passes don't change anything. */
94 return true;
97 if (unlikely(board_at(b, c) == S_NONE)) {
98 /* Suicide is hopeless. */
99 return false;
102 /* XXX: we can make some moves self-atari. */
104 if (neighbor_count_at(b, c, S_BLACK) + neighbor_count_at(b, c, S_WHITE) == 0) {
105 /* We are not taking off liberties of any other stones. */
106 return true;
109 return false;
112 static inline struct board_state *
113 board_state_init(struct board *b)
115 if (ss) {
116 if (ss->bsize2 != board_size2(b)) {
117 free(ss->groups);
118 free(ss->groups_known);
119 free(ss); ss = NULL;
121 #ifdef PERSISTENT_STATE
122 /* Only one stone added to the board, nothing removed. */
123 else if (ss->hash == (b->hash ^ hash_at(b, b->last_move.coord, b->last_move.color))) {
124 ss->hash = b->hash;
125 if (likely(board_state_reuse(ss, b)))
126 return ss;
128 #endif
130 if (!ss) {
131 ss = malloc2(sizeof(*ss));
132 ss->bsize2 = board_size2(b);
133 ss->groups = malloc2(board_size2(b) * sizeof(*ss->groups));
134 ss->groups_known = malloc2(board_size2(b) / 8 + 1);
136 ss->hash = b->hash;
137 memset(ss->groups_known, 0, board_size2(b) / 8 + 1);
138 return ss;
141 #define group_is_known(s, g) (s->groups_known[g >> 3] & (1 << (g & 7)))
142 #define group_set_known(s, g) (s->groups_known[g >> 3] |= (1 << (g & 7)))
143 #define group_trait_ready(s, g, color, gstat, trait) do { \
144 if (!group_is_known(s, g)) { \
145 memset(&s->groups[g], 0, sizeof(s->groups[g])); \
146 group_set_known(s, g); \
148 s->groups[g].status = gstat; \
149 s->groups[g].trait ## _ready |= color; \
150 } while (0)
151 #define group_trait_is_ready(s, g, color, trait) (s->groups[g].trait ## _ready & color)
152 #define group_trait_set(s, g, color, trait, val) s->groups[g].trait = (s->groups[g].trait & ~color) | (!!val * color)
153 #define group_trait_get(s, g, color, trait) (s->groups[g].trait & color)
155 #else
157 #define board_state_init(b) NULL
158 #define group_is_known(s, g) false
159 #define group_set_known(s, g)
160 #define group_trait_ready(s, g, color, gstat, trait)
161 #define group_trait_is_ready(s, g, color, trait) false
162 #define group_trait_set(s, g, color, trait, val)
163 #define group_trait_get(s, g, color, trait) false
164 #endif
167 static char moggy_patterns_src[][11] = {
168 /* hane pattern - enclosing hane */
169 "XOX"
170 "..."
171 "???",
172 /* hane pattern - non-cutting hane */
173 "XO."
174 "..."
175 "?.?",
176 /* hane pattern - magari */
177 "XO?"
178 "X.."
179 "x.?",
180 /* hane pattern - thin hane */
181 "XOO"
182 "..."
183 "?.?" "X",
184 /* generic pattern - katatsuke or diagonal attachment; similar to magari */
185 ".O."
186 "X.."
187 "...",
188 /* cut1 pattern (kiri) - unprotected cut */
189 "XO?"
190 "O.o"
191 "?o?",
192 /* cut1 pattern (kiri) - peeped cut */
193 "XO?"
194 "O.X"
195 "???",
196 /* cut2 pattern (de) */
197 "?X?"
198 "O.O"
199 "ooo",
200 /* cut keima (not in Mogo) */
201 "OX?"
202 "o.O"
203 "???", /* o?? has some pathological tsumego cases */
204 /* side pattern - chase */
205 "X.?"
206 "O.?"
207 "##?",
208 /* side pattern - block side cut */
209 "OX?"
210 "X.O"
211 "###",
212 /* side pattern - block side connection */
213 "?X?"
214 "x.O"
215 "###",
216 /* side pattern - sagari (SUSPICIOUS) */
217 "?XO"
218 "x.x" /* Mogo has "x.?" */
219 "###" /* Mogo has "X" */,
220 /* side pattern - throw-in (SUSPICIOUS) */
221 #if 0
222 "?OX"
223 "o.O"
224 "?##" "X",
225 #endif
226 /* side pattern - cut (SUSPICIOUS) */
227 "?OX"
228 "X.O"
229 "###" /* Mogo has "X" */,
231 #define moggy_patterns_src_n sizeof(moggy_patterns_src) / sizeof(moggy_patterns_src[0])
233 static inline bool
234 test_pattern3_here(struct playout_policy *p, struct board *b, struct move *m)
236 struct moggy_policy *pp = p->data;
237 /* Check if 3x3 pattern is matched by given move... */
238 if (!pattern3_move_here(&pp->patterns, b, m))
239 return false;
240 /* ...and the move is not obviously stupid. */
241 if (is_bad_selfatari(b, m->color, m->coord))
242 return false;
243 /* Ladder moves are stupid. */
244 group_t atari_neighbor = board_get_atari_neighbor(b, m->coord, m->color);
245 if (atari_neighbor && is_ladder(b, m->coord, atari_neighbor, pp->borderladders, pp->ladders))
246 return false;
247 return true;
250 static void
251 apply_pattern_here(struct playout_policy *p, struct board *b, coord_t c, enum stone color, struct move_queue *q)
253 struct move m2 = { .coord = c, .color = color };
254 if (board_is_valid_move(b, &m2) && test_pattern3_here(p, b, &m2))
255 mq_add(q, c);
258 /* Check if we match any pattern around given move (with the other color to play). */
259 static void
260 apply_pattern(struct playout_policy *p, struct board *b, struct move *m, struct move *mm, struct move_queue *q)
262 /* Suicides do not make any patterns and confuse us. */
263 if (board_at(b, m->coord) == S_NONE || board_at(b, m->coord) == S_OFFBOARD)
264 return;
266 foreach_8neighbor(b, m->coord) {
267 apply_pattern_here(p, b, c, stone_other(m->color), q);
268 } foreach_8neighbor_end;
270 if (mm) { /* Second move for pattern searching */
271 foreach_8neighbor(b, mm->coord) {
272 if (coord_is_8adjecent(m->coord, c, b))
273 continue;
274 apply_pattern_here(p, b, c, stone_other(m->color), q);
275 } foreach_8neighbor_end;
278 if (PLDEBUGL(5))
279 mq_print(q, b, "Pattern");
283 static bool
284 can_play_on_lib(struct playout_policy *p, struct board_state *s,
285 struct board *b, group_t g, enum stone to_play)
287 if (group_is_known(s, g) && group_trait_is_ready(s, g, to_play, capturable)) {
288 /* We have already seen this group. */
289 assert(s->groups[g].status == G_ATARI);
290 if (group_trait_get(s, g, to_play, capturable))
291 return true;
292 else
293 return false;
296 /* Cache miss. Set up cache entry, default at capturable = false. */
297 group_trait_ready(s, g, to_play, G_ATARI, capturable);
299 coord_t capture = board_group_info(b, g).lib[0];
300 if (PLDEBUGL(6))
301 fprintf(stderr, "can capture group %d (%s)?\n",
302 g, coord2sstr(capture, b));
303 /* Does playing on the liberty usefully capture the group? */
304 if (board_is_valid_play(b, to_play, capture)
305 && !is_bad_selfatari(b, to_play, capture)) {
306 group_trait_set(s, g, to_play, capturable, true);
307 return true;
310 return false;
313 /* For given position @c, decide if this is a group that is in danger from
314 * @capturer and @to_play can do anything about it (play at the last
315 * liberty to either capture or escape). */
316 /* Note that @to_play is important; e.g. consider snapback, it's good
317 * to play at the last liberty by attacker, but not defender. */
318 static __attribute__((always_inline)) bool
319 capturable_group(struct playout_policy *p, struct board_state *s,
320 struct board *b, enum stone capturer, coord_t c,
321 enum stone to_play)
323 group_t g = group_at(b, c);
324 if (likely(board_at(b, c) != stone_other(capturer)
325 || board_group_info(b, g).libs > 1))
326 return false;
328 return can_play_on_lib(p, s, b, g, to_play);
331 /* For given atari group @group owned by @owner, decide if @to_play
332 * can save it / keep it in danger by dealing with one of the
333 * neighboring groups. */
334 static bool
335 can_countercapture(struct playout_policy *p, struct board_state *s,
336 struct board *b, enum stone owner, group_t g,
337 enum stone to_play, struct move_queue *q)
339 if (b->clen < 2)
340 return false;
341 if (group_is_known(s, g) && group_trait_is_ready(s, g, to_play, can_countercapture)) {
342 /* We have already seen this group. */
343 assert(s->groups[g].status == G_ATARI);
344 if (group_trait_get(s, g, to_play, can_countercapture)) {
345 if (q) { /* Scan for countercapture liberties. */
346 goto scan;
348 return true;
349 } else {
350 return false;
354 /* Cache miss. Set up cache entry, default at can_countercapture = true. */
355 group_trait_ready(s, g, to_play, G_ATARI, can_countercapture);
356 group_trait_set(s, g, to_play, can_countercapture, true);
358 scan:;
359 unsigned int qmoves_prev = q ? q->moves : 0;
361 foreach_in_group(b, g) {
362 foreach_neighbor(b, c, {
363 if (!capturable_group(p, s, b, owner, c, to_play))
364 continue;
366 if (!q) {
367 return true;
369 mq_add(q, board_group_info(b, group_at(b, c)).lib[0]);
370 mq_nodup(q);
372 } foreach_in_group_end;
374 bool can = q ? q->moves > qmoves_prev : false;
375 group_trait_set(s, g, to_play, can_countercapture, can);
376 return can;
379 #ifdef NO_DOOMED_GROUPS
380 static bool
381 can_be_rescued(struct playout_policy *p, struct board_state *s,
382 struct board *b, group_t group, enum stone color)
384 /* Does playing on the liberty rescue the group? */
385 if (can_play_on_lib(p, s, b, group, color))
386 return true;
388 /* Then, maybe we can capture one of our neighbors? */
389 return can_countercapture(p, s, b, color, group, color, NULL);
391 #endif
393 /* ladder != NULL implies to always enqueue all relevant moves. */
394 static void
395 group_atari_check(struct playout_policy *p, struct board *b, group_t group, enum stone to_play,
396 struct move_queue *q, coord_t *ladder, struct board_state *s)
398 struct moggy_policy *pp = p->data;
399 int qmoves_prev = q->moves;
401 /* We don't use @to_play almost anywhere since any moves here are good
402 * for both defender and attacker. */
404 enum stone color = board_at(b, group_base(group));
405 coord_t lib = board_group_info(b, group).lib[0];
407 assert(color != S_OFFBOARD && color != S_NONE);
408 if (PLDEBUGL(5))
409 fprintf(stderr, "[%s] atariiiiiiiii %s of color %d\n",
410 coord2sstr(group, b), coord2sstr(lib, b), color);
411 assert(board_at(b, lib) == S_NONE);
413 /* Can we capture some neighbor? */
414 bool ccap = can_countercapture(p, s, b, color, group, to_play, q);
415 if (ccap && !ladder && pp->alwaysccaprate > fast_random(100))
416 return;
418 /* Otherwise, do not save kos. */
419 if (group_is_onestone(b, group)
420 && neighbor_count_at(b, lib, color) + neighbor_count_at(b, lib, S_OFFBOARD) == 4)
421 return;
423 /* Do not suicide... */
424 if (!can_play_on_lib(p, s, b, group, to_play))
425 return;
426 #ifdef NO_DOOMED_GROUPS
427 /* Do not remove group that cannot be saved by the opponent. */
428 if (to_play != color && !can_be_rescued(p, s, b, group, color))
429 return;
430 #endif
431 if (PLDEBUGL(6))
432 fprintf(stderr, "...escape route valid\n");
434 /* ...or play out ladders. */
435 if (is_ladder(b, lib, group, pp->borderladders, pp->ladders)) {
436 /* Sometimes we want to keep the ladder move in the
437 * queue in order to discourage it. */
438 if (!ladder)
439 return;
440 else
441 *ladder = lib;
443 if (PLDEBUGL(6))
444 fprintf(stderr, "...no ladder\n");
446 if (to_play != color) {
447 /* We are the attacker! In that case, throw away the moves
448 * that defend our groups, since we can capture the culprit. */
449 q->moves = qmoves_prev;
452 mq_add(q, lib);
453 mq_nodup(q);
456 static void
457 joseki_check(struct playout_policy *p, struct board *b, enum stone to_play, struct board_state *s, struct move_queue *q)
459 struct moggy_policy *pp = p->data;
460 if (!pp->jdict)
461 return;
463 for (int i = 0; i < 4; i++) {
464 hash_t h = b->qhash[i] & joseki_hash_mask;
465 coord_t *cc = pp->jdict->patterns[h].moves[to_play];
466 if (!cc) continue;
467 for (; !is_pass(*cc); cc++) {
468 if (coord_quadrant(*cc, b) != i)
469 continue;
470 mq_add(q, *cc);
474 if (q->moves > 0 && PLDEBUGL(5))
475 mq_print(q, b, "Joseki");
478 static void
479 global_atari_check(struct playout_policy *p, struct board *b, enum stone to_play, struct board_state *s, struct move_queue *q)
481 if (b->clen == 0)
482 return;
484 int g_base = fast_random(b->clen);
485 for (int g = g_base; g < b->clen; g++) {
486 group_atari_check(p, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, s);
487 if (q->moves > 0) {
488 /* XXX: Try carrying on. */
489 if (PLDEBUGL(5))
490 mq_print(q, b, "Global atari");
491 return;
494 for (int g = 0; g < g_base; g++) {
495 group_atari_check(p, b, group_at(b, group_base(b->c[g])), to_play, q, NULL, s);
496 if (q->moves > 0) {
497 /* XXX: Try carrying on. */
498 if (PLDEBUGL(5))
499 mq_print(q, b, "Global atari");
500 return;
503 return;
506 static void
507 local_atari_check(struct playout_policy *p, struct board *b, struct move *m, struct board_state *s, struct move_queue *q)
509 /* Did the opponent play a self-atari? */
510 if (board_group_info(b, group_at(b, m->coord)).libs == 1) {
511 group_atari_check(p, b, group_at(b, m->coord), stone_other(m->color), q, NULL, s);
514 foreach_neighbor(b, m->coord, {
515 group_t g = group_at(b, c);
516 if (!g || board_group_info(b, g).libs != 1)
517 continue;
518 group_atari_check(p, b, g, stone_other(m->color), q, NULL, s);
521 if (PLDEBUGL(5))
522 mq_print(q, b, "Local atari");
525 static bool
526 miai_2lib(struct board *b, group_t group, enum stone color)
528 bool can_connect = false, can_pull_out = false;
529 /* We have miai if we can either connect on both libs,
530 * or connect on one lib and escape on another. (Just
531 * having two escape routes can be risky.) We must make
532 * sure that we don't consider following as miai:
533 * X X X O
534 * X . . O
535 * O O X O - left dot would be pull-out, right dot connect */
536 foreach_neighbor(b, board_group_info(b, group).lib[0], {
537 enum stone cc = board_at(b, c);
538 if (cc == S_NONE && cc != board_at(b, board_group_info(b, group).lib[1])) {
539 can_pull_out = true;
540 } else if (cc != color) {
541 continue;
544 group_t cg = group_at(b, c);
545 if (cg && cg != group && board_group_info(b, cg).libs > 1)
546 can_connect = true;
548 foreach_neighbor(b, board_group_info(b, group).lib[1], {
549 enum stone cc = board_at(b, c);
550 if (c == board_group_info(b, group).lib[0])
551 continue;
552 if (cc == S_NONE && can_connect) {
553 return true;
554 } else if (cc != color) {
555 continue;
558 group_t cg = group_at(b, c);
559 if (cg && cg != group && board_group_info(b, cg).libs > 1)
560 return (can_connect || can_pull_out);
562 return false;
565 static void
566 check_group_atari(struct board *b, group_t group, enum stone owner,
567 enum stone to_play, struct move_queue *q)
569 for (int i = 0; i < 2; i++) {
570 coord_t lib = board_group_info(b, group).lib[i];
571 assert(board_at(b, lib) == S_NONE);
572 if (!board_is_valid_play(b, to_play, lib))
573 continue;
575 /* Don't play at the spot if it is extremely short
576 * of liberties... */
577 /* XXX: This looks harmful, could significantly
578 * prefer atari to throwin:
580 * XXXOOOOOXX
581 * .OO.....OX
582 * XXXOOOOOOX */
583 #if 0
584 if (neighbor_count_at(b, lib, stone_other(owner)) + immediate_liberty_count(b, lib) < 2)
585 continue;
586 #endif
588 /* If the move is too "lumpy", do not play it:
590 * #######
591 * ..O.X.X <- always play the left one!
592 * OXXXXXX */
593 if (neighbor_count_at(b, lib, stone_other(owner)) + neighbor_count_at(b, lib, S_OFFBOARD) == 3)
594 continue;
596 #ifdef NO_DOOMED_GROUPS
597 /* If the owner can't play at the spot, we don't want
598 * to bother either. */
599 if (is_bad_selfatari(b, owner, lib))
600 continue;
601 #endif
603 /* Of course we don't want to play bad selfatari
604 * ourselves, if we are the attacker... */
605 if (
606 #ifdef NO_DOOMED_GROUPS
607 to_play != owner &&
608 #endif
609 is_bad_selfatari(b, to_play, lib))
610 continue;
612 /* Tasty! Crispy! Good! */
613 mq_add(q, lib);
614 mq_nodup(q);
618 static void
619 group_2lib_check(struct playout_policy *p, struct board *b, group_t group, enum stone to_play,
620 struct move_queue *q, struct board_state *s)
622 enum stone color = board_at(b, group_base(group));
623 assert(color != S_OFFBOARD && color != S_NONE);
625 if (PLDEBUGL(5))
626 fprintf(stderr, "[%s] 2lib check of color %d\n",
627 coord2sstr(group, b), color);
629 /* Do not try to atari groups that cannot be harmed. */
630 if (miai_2lib(b, group, color))
631 return;
633 check_group_atari(b, group, color, to_play, q);
635 /* Can we counter-atari another group, if we are the defender? */
636 if (to_play != color)
637 return;
638 foreach_in_group(b, group) {
639 foreach_neighbor(b, c, {
640 if (board_at(b, c) != stone_other(color))
641 continue;
642 group_t g2 = group_at(b, c);
643 if (board_group_info(b, g2).libs == 1) {
644 /* We can capture a neighbor. */
645 mq_add(q, board_group_info(b, g2).lib[0]);
646 continue;
648 if (board_group_info(b, g2).libs != 2)
649 continue;
650 check_group_atari(b, g2, color, to_play, q);
652 } foreach_in_group_end;
655 static void
656 local_2lib_check(struct playout_policy *p, struct board *b, struct move *m, struct board_state *s, struct move_queue *q)
658 /* Does the opponent have just two liberties? */
659 if (board_group_info(b, group_at(b, m->coord)).libs == 2) {
660 group_2lib_check(p, b, group_at(b, m->coord), stone_other(m->color), q, s);
661 #if 0
662 /* We always prefer to take off an enemy chain liberty
663 * before pulling out ourselves. */
664 /* XXX: We aren't guaranteed to return to that group
665 * later. */
666 if (q->moves)
667 return q->move[fast_random(q->moves)];
668 #endif
671 /* Then he took a third liberty from neighboring chain? */
672 foreach_neighbor(b, m->coord, {
673 group_t g = group_at(b, c);
674 if (!g || board_group_info(b, g).libs != 2)
675 continue;
676 group_2lib_check(p, b, g, stone_other(m->color), q, s);
679 if (PLDEBUGL(5))
680 mq_print(q, b, "Local 2lib");
683 coord_t
684 fillboard_check(struct playout_policy *p, struct board *b)
686 struct moggy_policy *pp = p->data;
687 unsigned int fbtries = b->flen / 8;
688 if (pp->fillboardtries < fbtries)
689 fbtries = pp->fillboardtries;
691 for (unsigned int i = 0; i < fbtries; i++) {
692 coord_t coord = b->f[fast_random(b->flen)];
693 if (immediate_liberty_count(b, coord) != 4)
694 continue;
695 foreach_diag_neighbor(b, coord) {
696 if (board_at(b, c) != S_NONE)
697 goto next_try;
698 } foreach_diag_neighbor_end;
699 return coord;
700 next_try:;
702 return pass;
705 coord_t
706 playout_moggy_partchoose(struct playout_policy *p, struct board *b, enum stone to_play)
708 struct moggy_policy *pp = p->data;
709 struct board_state *s = board_state_init(b);
711 if (PLDEBUGL(5))
712 board_print(b, stderr);
714 /* Ko fight check */
715 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
716 && b->moves - b->last_ko_age < pp->koage
717 && pp->korate > fast_random(100)) {
718 if (board_is_valid_play(b, to_play, b->last_ko.coord)
719 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
720 return b->last_ko.coord;
723 /* Local checks */
724 if (!is_pass(b->last_move.coord)) {
725 /* Local group in atari? */
726 if (pp->lcapturerate > fast_random(100)) {
727 struct move_queue q = { .moves = 0 };
728 local_atari_check(p, b, &b->last_move, s, &q);
729 if (!q.moves > 0)
730 return mq_pick(&q);
733 /* Local group can be PUT in atari? */
734 if (pp->atarirate > fast_random(100)) {
735 struct move_queue q = { .moves = 0 };
736 local_2lib_check(p, b, &b->last_move, s, &q);
737 if (!q.moves > 0)
738 return mq_pick(&q);
741 /* Check for patterns we know */
742 if (pp->patternrate > fast_random(100)) {
743 struct move_queue q = { .moves = 0 };
744 apply_pattern(p, b, &b->last_move,
745 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
746 &q);
747 if (!q.moves > 0)
748 return mq_pick(&q);
752 /* Global checks */
754 /* Any groups in atari? */
755 if (pp->capturerate > fast_random(100)) {
756 struct move_queue q = { .moves = 0 };
757 global_atari_check(p, b, to_play, s, &q);
758 if (!q.moves > 0)
759 return mq_pick(&q);
762 /* Joseki moves? */
763 if (pp->josekirate > fast_random(100)) {
764 struct move_queue q = { .moves = 0 };
765 joseki_check(p, b, to_play, s, &q);
766 if (!q.moves > 0)
767 return mq_pick(&q);
770 /* Fill board */
771 if (pp->fillboardtries > 0) {
772 coord_t c = fillboard_check(p, b);
773 if (!is_pass(c))
774 return c;
777 return pass;
780 coord_t
781 playout_moggy_fullchoose(struct playout_policy *p, struct board *b, enum stone to_play)
783 struct moggy_policy *pp = p->data;
784 struct board_state *s = board_state_init(b);
785 struct move_queue q = { .moves = 0 };
787 if (PLDEBUGL(5))
788 board_print(b, stderr);
790 /* Ko fight check */
791 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
792 && b->moves - b->last_ko_age < pp->koage
793 && pp->korate > fast_random(100)) {
794 if (board_is_valid_play(b, to_play, b->last_ko.coord)
795 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
796 mq_add(&q, b->last_ko.coord);
799 /* Local checks */
800 if (!is_pass(b->last_move.coord)) {
801 /* Local group in atari? */
802 if (pp->lcapturerate > fast_random(100)) {
803 local_atari_check(p, b, &b->last_move, s, &q);
806 /* Local group can be PUT in atari? */
807 if (pp->atarirate > fast_random(100)) {
808 local_2lib_check(p, b, &b->last_move, s, &q);
811 /* Check for patterns we know */
812 if (pp->patternrate > fast_random(100)) {
813 apply_pattern(p, b, &b->last_move,
814 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL,
815 &q);
819 /* Global checks */
821 /* Any groups in atari? */
822 if (pp->capturerate > fast_random(100)) {
823 global_atari_check(p, b, to_play, s, &q);
826 /* Joseki moves? */
827 if (pp->josekirate > fast_random(100)) {
828 joseki_check(p, b, to_play, s, &q);
831 if (q.moves > 0)
832 return mq_pick(&q);
834 /* Fill board */
835 if (pp->fillboardtries > 0) {
836 coord_t c = fillboard_check(p, b);
837 if (!is_pass(c))
838 return c;
841 return pass;
845 static coord_t
846 selfatari_cousin(struct board *b, enum stone color, coord_t coord)
848 group_t groups[4]; int groups_n = 0;
849 foreach_neighbor(b, coord, {
850 enum stone s = board_at(b, c);
851 if (s != color) continue;
852 group_t g = group_at(b, c);
853 if (board_group_info(b, g).libs == 2)
854 groups[groups_n++] = g;
857 if (!groups_n)
858 return pass;
859 group_t group = groups[fast_random(groups_n)];
861 coord_t lib2 = board_group_other_lib(b, group, coord);
862 if (is_bad_selfatari(b, color, lib2))
863 return pass;
864 return lib2;
867 static int
868 assess_local_bonus(struct playout_policy *p, struct board *board, coord_t a, coord_t b, int games)
870 struct moggy_policy *pp = p->data;
871 if (!pp->assess_local)
872 return games;
874 int dx = abs(coord_x(a, board) - coord_x(b, board));
875 int dy = abs(coord_y(a, board) - coord_y(b, board));
876 /* adjecent move, directly or diagonally? */
877 if (dx + dy <= 1 + (dx && dy))
878 return games;
879 else
880 return games / 2;
883 void
884 playout_moggy_assess_group(struct playout_policy *p, struct prior_map *map, group_t g, int games,
885 struct board_state *s)
887 struct moggy_policy *pp = p->data;
888 struct board *b = map->b;
889 struct move_queue q; q.moves = 0;
891 if (board_group_info(b, g).libs > 2)
892 return;
894 if (PLDEBUGL(5)) {
895 fprintf(stderr, "ASSESS of group %s:\n", coord2sstr(g, b));
896 board_print(b, stderr);
899 if (board_group_info(b, g).libs == 2) {
900 if (!pp->atarirate)
901 return;
902 group_2lib_check(p, b, g, map->to_play, &q, s);
903 while (q.moves--) {
904 coord_t coord = q.move[q.moves];
905 if (PLDEBUGL(5))
906 fprintf(stderr, "1.0: 2lib %s\n", coord2sstr(coord, b));
907 int assess = assess_local_bonus(p, b, b->last_move.coord, coord, games) / 2;
908 add_prior_value(map, coord, 1, assess);
910 return;
913 /* This group, sir, is in atari! */
915 if (!pp->capturerate && !pp->lcapturerate && !pp->ladderassess)
916 return;
918 coord_t ladder = pass;
919 group_atari_check(p, b, g, map->to_play, &q, &ladder, s);
920 while (q.moves--) {
921 coord_t coord = q.move[q.moves];
923 /* _Never_ play here if this move plays out
924 * a caught ladder. */
925 if (coord == ladder && !board_playing_ko_threat(b)) {
926 /* Note that the opposite is not guarded against;
927 * we do not advise against capturing a laddered
928 * group (but we don't encourage it either). Such
929 * a move can simplify tactical situations if we
930 * can afford it. */
931 if (!pp->ladderassess || map->to_play != board_at(b, g))
932 continue;
933 /* FIXME: We give the malus even if this move
934 * captures another group. */
935 if (PLDEBUGL(5))
936 fprintf(stderr, "0.0: ladder %s\n", coord2sstr(coord, b));
937 add_prior_value(map, coord, 0, games);
938 continue;
941 if (!pp->capturerate && !pp->lcapturerate)
942 continue;
944 if (PLDEBUGL(5))
945 fprintf(stderr, "1.0: atari %s\n", coord2sstr(coord, b));
946 int assess = assess_local_bonus(p, b, b->last_move.coord, coord, games) * 2;
947 add_prior_value(map, coord, 1, assess);
951 void
952 playout_moggy_assess_one(struct playout_policy *p, struct prior_map *map, coord_t coord, int games)
954 struct moggy_policy *pp = p->data;
955 struct board *b = map->b;
957 if (PLDEBUGL(5)) {
958 fprintf(stderr, "ASSESS of move %s:\n", coord2sstr(coord, b));
959 board_print(b, stderr);
962 /* Is this move a self-atari? */
963 if (pp->selfatarirate) {
964 if (!board_playing_ko_threat(b) && is_bad_selfatari(b, map->to_play, coord)) {
965 if (PLDEBUGL(5))
966 fprintf(stderr, "0.0: self-atari\n");
967 add_prior_value(map, coord, 0, games);
968 if (!pp->selfatari_other)
969 return;
970 /* If we can play on the other liberty of the
971 * endangered group, do! */
972 coord = selfatari_cousin(b, map->to_play, coord);
973 if (is_pass(coord))
974 return;
975 if (PLDEBUGL(5))
976 fprintf(stderr, "1.0: self-atari redirect %s\n", coord2sstr(coord, b));
977 add_prior_value(map, coord, 1.0, games);
978 return;
982 /* Pattern check */
983 if (pp->patternrate) {
984 struct move m = { .color = map->to_play, .coord = coord };
985 if (test_pattern3_here(p, b, &m)) {
986 if (PLDEBUGL(5))
987 fprintf(stderr, "1.0: pattern\n");
988 int assess = assess_local_bonus(p, b, b->last_move.coord, coord, games);
989 add_prior_value(map, coord, 1, assess);
993 return;
996 void
997 playout_moggy_assess(struct playout_policy *p, struct prior_map *map, int games)
999 struct moggy_policy *pp = p->data;
1001 struct board_state *s = board_state_init(map->b);
1003 /* First, go through all endangered groups. */
1004 if (pp->lcapturerate || pp->capturerate || pp->atarirate || pp->ladderassess)
1005 for (group_t g = 1; g < board_size2(map->b); g++)
1006 if (group_at(map->b, g) == g)
1007 playout_moggy_assess_group(p, map, g, games, s);
1009 /* Then, assess individual moves. */
1010 if (!pp->patternrate && !pp->selfatarirate)
1011 return;
1012 foreach_free_point(map->b) {
1013 if (map->consider[c])
1014 playout_moggy_assess_one(p, map, c, games);
1015 } foreach_free_point_end;
1018 bool
1019 playout_moggy_permit(struct playout_policy *p, struct board *b, struct move *m)
1021 struct moggy_policy *pp = p->data;
1023 /* The idea is simple for now - never allow self-atari moves.
1024 * They suck in general, but this also permits us to actually
1025 * handle seki in the playout stage. */
1027 if (fast_random(100) >= pp->selfatarirate) {
1028 if (PLDEBUGL(5))
1029 fprintf(stderr, "skipping sar test\n");
1030 return true;
1032 bool selfatari = is_bad_selfatari(b, m->color, m->coord);
1033 if (selfatari) {
1034 if (PLDEBUGL(5))
1035 fprintf(stderr, "__ Prohibiting self-atari %s %s\n",
1036 stone2str(m->color), coord2sstr(m->coord, b));
1037 if (pp->selfatari_other) {
1038 /* Ok, try the other liberty of the atari'd group. */
1039 coord_t c = selfatari_cousin(b, m->color, m->coord);
1040 if (is_pass(c)) return false;
1041 if (PLDEBUGL(5))
1042 fprintf(stderr, "___ Redirecting to other lib %s\n",
1043 coord2sstr(c, b));
1044 m->coord = c;
1045 return true;
1047 return false;
1049 return true;
1053 struct playout_policy *
1054 playout_moggy_init(char *arg, struct board *b, struct joseki_dict *jdict)
1056 struct playout_policy *p = calloc2(1, sizeof(*p));
1057 struct moggy_policy *pp = calloc2(1, sizeof(*pp));
1058 p->data = pp;
1059 p->choose = playout_moggy_partchoose;
1060 p->assess = playout_moggy_assess;
1061 p->permit = playout_moggy_permit;
1063 pp->jdict = jdict;
1065 int rate = 90;
1067 pp->lcapturerate = pp->atarirate = pp->capturerate = pp->patternrate
1068 = pp->selfatarirate = pp->josekirate = -1U;
1069 pp->korate = 0; pp->koage = 4;
1070 pp->alwaysccaprate = 0;
1071 pp->ladders = pp->borderladders = true;
1072 pp->ladderassess = true;
1073 pp->selfatari_other = true;
1075 if (arg) {
1076 char *optspec, *next = arg;
1077 while (*next) {
1078 optspec = next;
1079 next += strcspn(next, ":");
1080 if (*next) { *next++ = 0; } else { *next = 0; }
1082 char *optname = optspec;
1083 char *optval = strchr(optspec, '=');
1084 if (optval) *optval++ = 0;
1086 if (!strcasecmp(optname, "debug") && optval) {
1087 p->debug_level = atoi(optval);
1088 } else if (!strcasecmp(optname, "lcapturerate") && optval) {
1089 pp->lcapturerate = atoi(optval);
1090 } else if (!strcasecmp(optname, "atarirate") && optval) {
1091 pp->atarirate = atoi(optval);
1092 } else if (!strcasecmp(optname, "capturerate") && optval) {
1093 pp->capturerate = atoi(optval);
1094 } else if (!strcasecmp(optname, "patternrate") && optval) {
1095 pp->patternrate = atoi(optval);
1096 } else if (!strcasecmp(optname, "selfatarirate") && optval) {
1097 pp->selfatarirate = atoi(optval);
1098 } else if (!strcasecmp(optname, "korate") && optval) {
1099 pp->korate = atoi(optval);
1100 } else if (!strcasecmp(optname, "josekirate") && optval) {
1101 pp->josekirate = atoi(optval);
1102 } else if (!strcasecmp(optname, "alwaysccaprate") && optval) {
1103 pp->alwaysccaprate = atoi(optval);
1104 } else if (!strcasecmp(optname, "rate") && optval) {
1105 rate = atoi(optval);
1106 } else if (!strcasecmp(optname, "fillboardtries")) {
1107 pp->fillboardtries = atoi(optval);
1108 } else if (!strcasecmp(optname, "koage") && optval) {
1109 pp->koage = atoi(optval);
1110 } else if (!strcasecmp(optname, "ladders")) {
1111 pp->ladders = optval && *optval == '0' ? false : true;
1112 } else if (!strcasecmp(optname, "borderladders")) {
1113 pp->borderladders = optval && *optval == '0' ? false : true;
1114 } else if (!strcasecmp(optname, "ladderassess")) {
1115 pp->ladderassess = optval && *optval == '0' ? false : true;
1116 } else if (!strcasecmp(optname, "assess_local")) {
1117 pp->assess_local = optval && *optval == '0' ? false : true;
1118 } else if (!strcasecmp(optname, "pattern2")) {
1119 pp->pattern2 = optval && *optval == '0' ? false : true;
1120 } else if (!strcasecmp(optname, "selfatari_other")) {
1121 pp->selfatari_other = optval && *optval == '0' ? false : true;
1122 } else if (!strcasecmp(optname, "fullchoose")) {
1123 p->choose = optval && *optval == '0' ? playout_moggy_partchoose : playout_moggy_fullchoose;
1124 } else {
1125 fprintf(stderr, "playout-moggy: Invalid policy argument %s or missing value\n", optname);
1126 exit(1);
1130 if (pp->lcapturerate == -1U) pp->lcapturerate = rate;
1131 if (pp->atarirate == -1U) pp->atarirate = rate;
1132 if (pp->capturerate == -1U) pp->capturerate = rate;
1133 if (pp->patternrate == -1U) pp->patternrate = rate;
1134 if (pp->selfatarirate == -1U) pp->selfatarirate = rate;
1135 if (pp->korate == -1U) pp->korate = rate;
1136 if (pp->josekirate == -1U) pp->josekirate = rate;
1137 if (pp->alwaysccaprate == -1U) pp->alwaysccaprate = rate;
1139 pattern3s_init(&pp->patterns, moggy_patterns_src, moggy_patterns_src_n);
1141 return p;