Moggy: Do not play 'lumpy' 2-lib moves
[pachi/derm.git] / playout / moggy.c
blobd2a337d5012c51e2486c2dd3a6cd270596bd437b
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 pattern3s patterns;
48 struct group_state {
49 enum {
50 G_ATARI,
51 G_2LIB, /* Unused. */
52 G_SAFE /* Unused. */
53 } status:2;
55 /* Below, we keep track of each trait for each |color_to_play */
56 int capturable_ready:2; // is @capturable meaningful?
57 int capturable:2;
59 int can_countercapture_ready:2;
60 int can_countercapture:2;
63 /* Cache of evaluation of various board features. */
64 struct board_state {
65 int bsize2;
66 hash_t hash;
67 struct group_state *groups; /* [board_size2()], indexed by group_t */
68 unsigned char *groups_known; /* Bitmap of known groups. */
71 /* Using board cache: this turns out to be actually a 10% slowdown,
72 * since we reuse data in the cache only very little within single
73 * move. */
74 // #define CACHE_STATE
75 /* Reusing board cache across moves if they are successive on the
76 * board; only cache entries within cfg distance 2 of the last move
77 * are cleared. */
78 // #define PERSISTENT_STATE
80 #ifdef CACHE_STATE
81 static __thread struct board_state *ss;
83 static bool
84 board_state_reuse(struct board_state *s, struct board *b)
86 /* Decide how much of the board state we can reuse. */
87 /* We do not cache ladder decisions, so we don't have
88 * to worry about this. */
89 coord_t c = b->last_move.coord;
91 if (unlikely(is_pass(c))) {
92 /* Passes don't change anything. */
93 return true;
96 if (unlikely(board_at(b, c) == S_NONE)) {
97 /* Suicide is hopeless. */
98 return false;
101 /* XXX: we can make some moves self-atari. */
103 if (neighbor_count_at(b, c, S_BLACK) + neighbor_count_at(b, c, S_WHITE) == 0) {
104 /* We are not taking off liberties of any other stones. */
105 return true;
108 return false;
111 static inline struct board_state *
112 board_state_init(struct board *b)
114 if (ss) {
115 if (ss->bsize2 != board_size2(b)) {
116 free(ss->groups);
117 free(ss->groups_known);
118 free(ss); ss = NULL;
120 #ifdef PERSISTENT_STATE
121 /* Only one stone added to the board, nothing removed. */
122 else if (ss->hash == (b->hash ^ hash_at(b, b->last_move.coord, b->last_move.color))) {
123 ss->hash = b->hash;
124 if (likely(board_state_reuse(ss, b)))
125 return ss;
127 #endif
129 if (!ss) {
130 ss = malloc2(sizeof(*ss));
131 ss->bsize2 = board_size2(b);
132 ss->groups = malloc2(board_size2(b) * sizeof(*ss->groups));
133 ss->groups_known = malloc2(board_size2(b) / 8 + 1);
135 ss->hash = b->hash;
136 memset(ss->groups_known, 0, board_size2(b) / 8 + 1);
137 return ss;
140 #define group_is_known(s, g) (s->groups_known[g >> 3] & (1 << (g & 7)))
141 #define group_set_known(s, g) (s->groups_known[g >> 3] |= (1 << (g & 7)))
142 #define group_trait_ready(s, g, color, gstat, trait) do { \
143 if (!group_is_known(s, g)) { \
144 memset(&s->groups[g], 0, sizeof(s->groups[g])); \
145 group_set_known(s, g); \
147 s->groups[g].status = gstat; \
148 s->groups[g].trait ## _ready |= color; \
149 } while (0)
150 #define group_trait_is_ready(s, g, color, trait) (s->groups[g].trait ## _ready & color)
151 #define group_trait_set(s, g, color, trait, val) s->groups[g].trait = (s->groups[g].trait & ~color) | (!!val * color)
152 #define group_trait_get(s, g, color, trait) (s->groups[g].trait & color)
154 #else
156 #define board_state_init(b) NULL
157 #define group_is_known(s, g) false
158 #define group_set_known(s, g)
159 #define group_trait_ready(s, g, color, gstat, trait)
160 #define group_trait_is_ready(s, g, color, trait) false
161 #define group_trait_set(s, g, color, trait, val)
162 #define group_trait_get(s, g, color, trait) false
163 #endif
166 static char moggy_patterns_src[][11] = {
167 /* hane pattern - enclosing hane */
168 "XOX"
169 "..."
170 "???",
171 /* hane pattern - non-cutting hane */
172 "XO."
173 "..."
174 "?.?",
175 /* hane pattern - magari */
176 "XO?"
177 "X.."
178 "x.?",
179 /* hane pattern - thin hane */
180 "XOO"
181 "..."
182 "?.?" "X",
183 /* generic pattern - katatsuke or diagonal attachment; similar to magari */
184 ".O."
185 "X.."
186 "...",
187 /* cut1 pattern (kiri) - unprotected cut */
188 "XO?"
189 "O.o"
190 "?o?",
191 /* cut1 pattern (kiri) - peeped cut */
192 "XO?"
193 "O.X"
194 "???",
195 /* cut2 pattern (de) */
196 "?X?"
197 "O.O"
198 "ooo",
199 /* cut keima (not in Mogo) */
200 "OX?"
201 "o.O"
202 "???", /* o?? has some pathological tsumego cases */
203 /* side pattern - chase */
204 "X.?"
205 "O.?"
206 "##?",
207 /* side pattern - weirdness (SUSPICIOUS) */
208 "?X?"
209 "X.O"
210 "###",
211 /* side pattern - sagari (SUSPICIOUS) */
212 "?XO"
213 "x.x" /* Mogo has "x.?" */
214 "###" /* Mogo has "X" */,
215 /* side pattern - throw-in (SUSPICIOUS) */
216 #if 0
217 "?OX"
218 "o.O"
219 "?##" "X",
220 #endif
221 /* side pattern - cut (SUSPICIOUS) */
222 "?OX"
223 "X.O"
224 "###" /* Mogo has "X" */,
226 #define moggy_patterns_src_n sizeof(moggy_patterns_src) / sizeof(moggy_patterns_src[0])
228 static inline bool
229 test_pattern3_here(struct playout_policy *p, struct board *b, struct move *m)
231 struct moggy_policy *pp = p->data;
232 /* Check if 3x3 pattern is matched by given move... */
233 if (!pattern3_move_here(&pp->patterns, b, m))
234 return false;
235 /* ...and the move is not obviously stupid. */
236 if (is_bad_selfatari(b, m->color, m->coord))
237 return false;
238 /* Ladder moves are stupid. */
239 group_t atari_neighbor = board_get_atari_neighbor(b, m->coord, m->color);
240 if (atari_neighbor && is_ladder(b, m->coord, atari_neighbor, pp->borderladders, pp->ladders))
241 return false;
242 return true;
245 static void
246 apply_pattern_here(struct playout_policy *p, struct board *b, coord_t c, enum stone color, struct move_queue *q)
248 struct move m2 = { .coord = c, .color = color };
249 if (board_is_valid_move(b, &m2) && test_pattern3_here(p, b, &m2))
250 mq_add(q, c);
253 /* Check if we match any pattern around given move (with the other color to play). */
254 static coord_t
255 apply_pattern(struct playout_policy *p, struct board *b, struct move *m, struct move *mm)
257 struct move_queue q;
258 q.moves = 0;
260 /* Suicides do not make any patterns and confuse us. */
261 if (board_at(b, m->coord) == S_NONE || board_at(b, m->coord) == S_OFFBOARD)
262 return pass;
264 foreach_8neighbor(b, m->coord) {
265 apply_pattern_here(p, b, c, stone_other(m->color), &q);
266 } foreach_8neighbor_end;
268 if (mm) { /* Second move for pattern searching */
269 foreach_8neighbor(b, mm->coord) {
270 if (coord_is_8adjecent(m->coord, c, b))
271 continue;
272 apply_pattern_here(p, b, c, stone_other(m->color), &q);
273 } foreach_8neighbor_end;
276 if (PLDEBUGL(5))
277 mq_print(&q, b, "Pattern");
279 return mq_pick(&q);
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 /* Do not bother with kos. */
414 if (group_is_onestone(b, group)
415 && neighbor_count_at(b, lib, color) + neighbor_count_at(b, lib, S_OFFBOARD) == 4)
416 return;
418 /* Can we capture some neighbor? */
419 bool ccap = can_countercapture(p, s, b, color, group, to_play, q);
420 if (ccap && !ladder && pp->alwaysccaprate > fast_random(100))
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 coord_t
457 joseki_check(struct playout_policy *p, struct board *b, enum stone to_play, struct board_state *s)
459 struct move_queue q;
460 q.moves = 0;
462 for (int i = 0; i < 4; i++) {
463 hash_t h = b->qhash[i] & joseki_hash_mask;
464 coord_t *cc = joseki_pats[h].moves[to_play];
465 if (!cc) continue;
466 fprintf(stderr, "%"PRIhash" %d\n", h, i);
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) {
475 if (PLDEBUGL(5))
476 mq_print(&q, b, "Joseki");
477 return mq_pick(&q);
479 return pass;
482 static coord_t
483 global_atari_check(struct playout_policy *p, struct board *b, enum stone to_play, struct board_state *s)
485 struct move_queue q;
486 q.moves = 0;
488 if (b->clen == 0)
489 return pass;
491 int g_base = fast_random(b->clen);
492 for (int g = g_base; g < b->clen; g++) {
493 group_atari_check(p, b, group_at(b, group_base(b->c[g])), to_play, &q, NULL, s);
494 if (q.moves > 0) {
495 if (PLDEBUGL(5))
496 mq_print(&q, b, "Global atari");
497 return mq_pick(&q);
500 for (int g = 0; g < g_base; g++) {
501 group_atari_check(p, b, group_at(b, group_base(b->c[g])), to_play, &q, NULL, s);
502 if (q.moves > 0) {
503 if (PLDEBUGL(5))
504 mq_print(&q, b, "Global atari");
505 return mq_pick(&q);
508 return pass;
511 static coord_t
512 local_atari_check(struct playout_policy *p, struct board *b, struct move *m, struct board_state *s)
514 struct move_queue q;
515 q.moves = 0;
517 /* Did the opponent play a self-atari? */
518 if (board_group_info(b, group_at(b, m->coord)).libs == 1) {
519 group_atari_check(p, b, group_at(b, m->coord), stone_other(m->color), &q, NULL, s);
522 foreach_neighbor(b, m->coord, {
523 group_t g = group_at(b, c);
524 if (!g || board_group_info(b, g).libs != 1)
525 continue;
526 group_atari_check(p, b, g, stone_other(m->color), &q, NULL, s);
529 if (PLDEBUGL(5))
530 mq_print(&q, b, "Local atari");
532 return mq_pick(&q);
535 static bool
536 miai_2lib(struct board *b, group_t group, enum stone color)
538 bool can_connect = false, can_pull_out = false;
539 /* We have miai if we can either connect on both libs,
540 * or connect on one lib and escape on another. (Just
541 * having two escape routes can be risky.) We must make
542 * sure that we don't consider following as miai:
543 * X X X O
544 * X . . O
545 * O O X O - left dot would be pull-out, right dot connect */
546 foreach_neighbor(b, board_group_info(b, group).lib[0], {
547 enum stone cc = board_at(b, c);
548 if (cc == S_NONE && cc != board_at(b, board_group_info(b, group).lib[1])) {
549 can_pull_out = true;
550 } else if (cc != color) {
551 continue;
554 group_t cg = group_at(b, c);
555 if (cg && cg != group && board_group_info(b, cg).libs > 1)
556 can_connect = true;
558 foreach_neighbor(b, board_group_info(b, group).lib[1], {
559 enum stone cc = board_at(b, c);
560 if (c == board_group_info(b, group).lib[0])
561 continue;
562 if (cc == S_NONE && can_connect) {
563 return true;
564 } else if (cc != color) {
565 continue;
568 group_t cg = group_at(b, c);
569 if (cg && cg != group && board_group_info(b, cg).libs > 1)
570 return (can_connect || can_pull_out);
572 return false;
575 static void
576 check_group_atari(struct board *b, group_t group, enum stone owner,
577 enum stone to_play, struct move_queue *q)
579 for (int i = 0; i < 2; i++) {
580 coord_t lib = board_group_info(b, group).lib[i];
581 assert(board_at(b, lib) == S_NONE);
582 if (!board_is_valid_play(b, to_play, lib))
583 continue;
585 /* Don't play at the spot if it is extremely short
586 * of liberties... */
587 /* XXX: This looks harmful, could significantly
588 * prefer atari to throwin:
590 * XXXOOOOOXX
591 * .OO.....OX
592 * XXXOOOOOOX */
593 #if 0
594 if (neighbor_count_at(b, lib, stone_other(owner)) + immediate_liberty_count(b, lib) < 2)
595 continue;
596 #endif
598 /* If the move is too "lumpy", do not play it:
600 * #######
601 * ..O.X.X <- always play the left one!
602 * OXXXXXX */
603 if (neighbor_count_at(b, lib, stone_other(owner)) + neighbor_count_at(b, lib, S_OFFBOARD) == 3)
604 continue;
606 #ifdef NO_DOOMED_GROUPS
607 /* If the owner can't play at the spot, we don't want
608 * to bother either. */
609 if (is_bad_selfatari(b, owner, lib))
610 continue;
611 #endif
613 /* Of course we don't want to play bad selfatari
614 * ourselves, if we are the attacker... */
615 if (
616 #ifdef NO_DOOMED_GROUPS
617 to_play != owner &&
618 #endif
619 is_bad_selfatari(b, to_play, lib))
620 continue;
622 /* Tasty! Crispy! Good! */
623 mq_add(q, lib);
624 mq_nodup(q);
628 static void
629 group_2lib_check(struct playout_policy *p, struct board *b, group_t group, enum stone to_play,
630 struct move_queue *q, struct board_state *s)
632 enum stone color = board_at(b, group_base(group));
633 assert(color != S_OFFBOARD && color != S_NONE);
635 if (PLDEBUGL(5))
636 fprintf(stderr, "[%s] 2lib check of color %d\n",
637 coord2sstr(group, b), color);
639 /* Do not try to atari groups that cannot be harmed. */
640 if (miai_2lib(b, group, color))
641 return;
643 check_group_atari(b, group, color, to_play, q);
645 /* Can we counter-atari another group, if we are the defender? */
646 if (to_play != color)
647 return;
648 foreach_in_group(b, group) {
649 foreach_neighbor(b, c, {
650 if (board_at(b, c) != stone_other(color))
651 continue;
652 group_t g2 = group_at(b, c);
653 if (board_group_info(b, g2).libs != 2)
654 continue;
655 check_group_atari(b, g2, color, to_play, q);
657 } foreach_in_group_end;
660 static coord_t
661 local_2lib_check(struct playout_policy *p, struct board *b, struct move *m, struct board_state *s)
663 struct move_queue q;
664 q.moves = 0;
666 /* Does the opponent have just two liberties? */
667 if (board_group_info(b, group_at(b, m->coord)).libs == 2) {
668 group_2lib_check(p, b, group_at(b, m->coord), stone_other(m->color), &q, s);
669 #if 0
670 /* We always prefer to take off an enemy chain liberty
671 * before pulling out ourselves. */
672 /* XXX: We aren't guaranteed to return to that group
673 * later. */
674 if (q.moves)
675 return q.move[fast_random(q.moves)];
676 #endif
679 /* Then he took a third liberty from neighboring chain? */
680 foreach_neighbor(b, m->coord, {
681 group_t g = group_at(b, c);
682 if (!g || board_group_info(b, g).libs != 2)
683 continue;
684 group_2lib_check(p, b, g, stone_other(m->color), &q, s);
687 if (PLDEBUGL(5))
688 mq_print(&q, b, "Local 2lib");
690 return mq_pick(&q);
693 coord_t
694 playout_moggy_choose(struct playout_policy *p, struct board *b, enum stone to_play)
696 struct moggy_policy *pp = p->data;
697 coord_t c;
699 struct board_state *s = board_state_init(b);
701 if (PLDEBUGL(5))
702 board_print(b, stderr);
704 /* Ko fight check */
705 if (!is_pass(b->last_ko.coord) && is_pass(b->ko.coord)
706 && b->moves - b->last_ko_age < pp->koage
707 && pp->korate > fast_random(100)) {
708 if (board_is_valid_play(b, to_play, b->last_ko.coord)
709 && !is_bad_selfatari(b, to_play, b->last_ko.coord))
710 return b->last_ko.coord;
713 /* Local checks */
714 if (!is_pass(b->last_move.coord)) {
715 /* Local group in atari? */
716 if (pp->lcapturerate > fast_random(100)) {
717 c = local_atari_check(p, b, &b->last_move, s);
718 if (!is_pass(c))
719 return c;
722 /* Local group can be PUT in atari? */
723 if (pp->atarirate > fast_random(100)) {
724 c = local_2lib_check(p, b, &b->last_move, s);
725 if (!is_pass(c))
726 return c;
729 /* Check for patterns we know */
730 if (pp->patternrate > fast_random(100)) {
731 c = apply_pattern(p, b, &b->last_move,
732 pp->pattern2 && b->last_move2.coord >= 0 ? &b->last_move2 : NULL);
733 if (!is_pass(c))
734 return c;
738 /* Global checks */
740 /* Any groups in atari? */
741 if (pp->capturerate > fast_random(100)) {
742 c = global_atari_check(p, b, to_play, s);
743 if (!is_pass(c))
744 return c;
747 /* Joseki moves? */
748 if (pp->josekirate > fast_random(100)) {
749 c = joseki_check(p, b, to_play, s);
750 if (!is_pass(c))
751 return c;
754 /* Fill board */
755 unsigned int fbtries = b->flen / 8;
756 for (unsigned int i = 0; i < (fbtries < pp->fillboardtries ? fbtries : pp->fillboardtries); i++) {
757 coord_t coord = b->f[fast_random(b->flen)];
758 if (immediate_liberty_count(b, coord) != 4)
759 continue;
760 foreach_diag_neighbor(b, coord) {
761 if (board_at(b, c) != S_NONE)
762 goto next_try;
763 } foreach_diag_neighbor_end;
764 return coord;
765 next_try:;
768 return pass;
772 static coord_t
773 selfatari_cousin(struct board *b, enum stone color, coord_t coord)
775 group_t groups[4]; int groups_n = 0;
776 foreach_neighbor(b, coord, {
777 enum stone s = board_at(b, c);
778 if (s != color) continue;
779 group_t g = group_at(b, c);
780 if (board_group_info(b, g).libs == 2)
781 groups[groups_n++] = g;
784 if (!groups_n)
785 return pass;
786 group_t group = groups[fast_random(groups_n)];
788 coord_t lib2 = board_group_other_lib(b, group, coord);
789 if (is_bad_selfatari(b, color, lib2))
790 return pass;
791 return lib2;
794 static int
795 assess_local_bonus(struct playout_policy *p, struct board *board, coord_t a, coord_t b, int games)
797 struct moggy_policy *pp = p->data;
798 if (!pp->assess_local)
799 return games;
801 int dx = abs(coord_x(a, board) - coord_x(b, board));
802 int dy = abs(coord_y(a, board) - coord_y(b, board));
803 /* adjecent move, directly or diagonally? */
804 if (dx + dy <= 1 + (dx && dy))
805 return games;
806 else
807 return games / 2;
810 void
811 playout_moggy_assess_group(struct playout_policy *p, struct prior_map *map, group_t g, int games,
812 struct board_state *s)
814 struct moggy_policy *pp = p->data;
815 struct board *b = map->b;
816 struct move_queue q; q.moves = 0;
818 if (board_group_info(b, g).libs > 2)
819 return;
821 if (PLDEBUGL(5)) {
822 fprintf(stderr, "ASSESS of group %s:\n", coord2sstr(g, b));
823 board_print(b, stderr);
826 if (board_group_info(b, g).libs == 2) {
827 if (!pp->atarirate)
828 return;
829 group_2lib_check(p, b, g, map->to_play, &q, s);
830 while (q.moves--) {
831 coord_t coord = q.move[q.moves];
832 if (PLDEBUGL(5))
833 fprintf(stderr, "1.0: 2lib %s\n", coord2sstr(coord, b));
834 int assess = assess_local_bonus(p, b, b->last_move.coord, coord, games) / 2;
835 add_prior_value(map, coord, 1, assess);
837 return;
840 /* This group, sir, is in atari! */
842 if (!pp->capturerate && !pp->lcapturerate && !pp->ladderassess)
843 return;
845 coord_t ladder = pass;
846 group_atari_check(p, b, g, map->to_play, &q, &ladder, s);
847 while (q.moves--) {
848 coord_t coord = q.move[q.moves];
850 /* _Never_ play here if this move plays out
851 * a caught ladder. */
852 if (coord == ladder && !board_playing_ko_threat(b)) {
853 /* Note that the opposite is not guarded against;
854 * we do not advise against capturing a laddered
855 * group (but we don't encourage it either). Such
856 * a move can simplify tactical situations if we
857 * can afford it. */
858 if (!pp->ladderassess || map->to_play != board_at(b, g))
859 continue;
860 /* FIXME: We give the malus even if this move
861 * captures another group. */
862 if (PLDEBUGL(5))
863 fprintf(stderr, "0.0: ladder %s\n", coord2sstr(coord, b));
864 add_prior_value(map, coord, 0, games);
865 continue;
868 if (!pp->capturerate && !pp->lcapturerate)
869 continue;
871 if (PLDEBUGL(5))
872 fprintf(stderr, "1.0: atari %s\n", coord2sstr(coord, b));
873 int assess = assess_local_bonus(p, b, b->last_move.coord, coord, games) * 2;
874 add_prior_value(map, coord, 1, assess);
878 void
879 playout_moggy_assess_one(struct playout_policy *p, struct prior_map *map, coord_t coord, int games)
881 struct moggy_policy *pp = p->data;
882 struct board *b = map->b;
884 if (PLDEBUGL(5)) {
885 fprintf(stderr, "ASSESS of move %s:\n", coord2sstr(coord, b));
886 board_print(b, stderr);
889 /* Is this move a self-atari? */
890 if (pp->selfatarirate) {
891 if (!board_playing_ko_threat(b) && is_bad_selfatari(b, map->to_play, coord)) {
892 if (PLDEBUGL(5))
893 fprintf(stderr, "0.0: self-atari\n");
894 add_prior_value(map, coord, 0, games);
895 if (!pp->selfatari_other)
896 return;
897 /* If we can play on the other liberty of the
898 * endangered group, do! */
899 coord = selfatari_cousin(b, map->to_play, coord);
900 if (is_pass(coord))
901 return;
902 if (PLDEBUGL(5))
903 fprintf(stderr, "1.0: self-atari redirect %s\n", coord2sstr(coord, b));
904 add_prior_value(map, coord, 1.0, games);
905 return;
909 /* Pattern check */
910 if (pp->patternrate) {
911 struct move m = { .color = map->to_play, .coord = coord };
912 if (test_pattern3_here(p, b, &m)) {
913 if (PLDEBUGL(5))
914 fprintf(stderr, "1.0: pattern\n");
915 int assess = assess_local_bonus(p, b, b->last_move.coord, coord, games);
916 add_prior_value(map, coord, 1, assess);
920 return;
923 void
924 playout_moggy_assess(struct playout_policy *p, struct prior_map *map, int games)
926 struct moggy_policy *pp = p->data;
928 struct board_state *s = board_state_init(map->b);
930 /* First, go through all endangered groups. */
931 if (pp->lcapturerate || pp->capturerate || pp->atarirate || pp->ladderassess)
932 for (group_t g = 1; g < board_size2(map->b); g++)
933 if (group_at(map->b, g) == g)
934 playout_moggy_assess_group(p, map, g, games, s);
936 /* Then, assess individual moves. */
937 if (!pp->patternrate && !pp->selfatarirate)
938 return;
939 foreach_free_point(map->b) {
940 if (map->consider[c])
941 playout_moggy_assess_one(p, map, c, games);
942 } foreach_free_point_end;
945 bool
946 playout_moggy_permit(struct playout_policy *p, struct board *b, struct move *m)
948 struct moggy_policy *pp = p->data;
950 /* The idea is simple for now - never allow self-atari moves.
951 * They suck in general, but this also permits us to actually
952 * handle seki in the playout stage. */
954 if (fast_random(100) >= pp->selfatarirate) {
955 if (PLDEBUGL(5))
956 fprintf(stderr, "skipping sar test\n");
957 return true;
959 bool selfatari = is_bad_selfatari(b, m->color, m->coord);
960 if (selfatari) {
961 if (PLDEBUGL(5))
962 fprintf(stderr, "__ Prohibiting self-atari %s %s\n",
963 stone2str(m->color), coord2sstr(m->coord, b));
964 if (pp->selfatari_other) {
965 /* Ok, try the other liberty of the atari'd group. */
966 coord_t c = selfatari_cousin(b, m->color, m->coord);
967 if (is_pass(c)) return false;
968 if (PLDEBUGL(5))
969 fprintf(stderr, "___ Redirecting to other lib %s\n",
970 coord2sstr(c, b));
971 m->coord = c;
972 return true;
974 return false;
976 return true;
980 struct playout_policy *
981 playout_moggy_init(char *arg, struct board *b)
983 struct playout_policy *p = calloc2(1, sizeof(*p));
984 struct moggy_policy *pp = calloc2(1, sizeof(*pp));
985 p->data = pp;
986 p->choose = playout_moggy_choose;
987 p->assess = playout_moggy_assess;
988 p->permit = playout_moggy_permit;
990 int rate = 90;
992 pp->lcapturerate = pp->atarirate = pp->capturerate = pp->patternrate = pp->selfatarirate
993 = -1U;
994 pp->korate = 0; pp->koage = 4;
995 pp->alwaysccaprate = 0;
996 pp->josekirate = 0;
997 pp->ladders = pp->borderladders = true;
998 pp->ladderassess = true;
1000 if (arg) {
1001 char *optspec, *next = arg;
1002 while (*next) {
1003 optspec = next;
1004 next += strcspn(next, ":");
1005 if (*next) { *next++ = 0; } else { *next = 0; }
1007 char *optname = optspec;
1008 char *optval = strchr(optspec, '=');
1009 if (optval) *optval++ = 0;
1011 if (!strcasecmp(optname, "lcapturerate") && optval) {
1012 pp->lcapturerate = atoi(optval);
1013 } else if (!strcasecmp(optname, "atarirate") && optval) {
1014 pp->atarirate = atoi(optval);
1015 } else if (!strcasecmp(optname, "capturerate") && optval) {
1016 pp->capturerate = atoi(optval);
1017 } else if (!strcasecmp(optname, "patternrate") && optval) {
1018 pp->patternrate = atoi(optval);
1019 } else if (!strcasecmp(optname, "selfatarirate") && optval) {
1020 pp->selfatarirate = atoi(optval);
1021 } else if (!strcasecmp(optname, "korate") && optval) {
1022 pp->korate = atoi(optval);
1023 } else if (!strcasecmp(optname, "josekirate") && optval) {
1024 pp->josekirate = atoi(optval);
1025 } else if (!strcasecmp(optname, "alwaysccaprate") && optval) {
1026 pp->alwaysccaprate = atoi(optval);
1027 } else if (!strcasecmp(optname, "rate") && optval) {
1028 rate = atoi(optval);
1029 } else if (!strcasecmp(optname, "fillboardtries")) {
1030 pp->fillboardtries = atoi(optval);
1031 } else if (!strcasecmp(optname, "koage") && optval) {
1032 pp->koage = atoi(optval);
1033 } else if (!strcasecmp(optname, "ladders")) {
1034 pp->ladders = optval && *optval == '0' ? false : true;
1035 } else if (!strcasecmp(optname, "borderladders")) {
1036 pp->borderladders = optval && *optval == '0' ? false : true;
1037 } else if (!strcasecmp(optname, "ladderassess")) {
1038 pp->ladderassess = optval && *optval == '0' ? false : true;
1039 } else if (!strcasecmp(optname, "assess_local")) {
1040 pp->assess_local = optval && *optval == '0' ? false : true;
1041 } else if (!strcasecmp(optname, "pattern2")) {
1042 pp->pattern2 = optval && *optval == '0' ? false : true;
1043 } else if (!strcasecmp(optname, "selfatari_other")) {
1044 pp->selfatari_other = optval && *optval == '0' ? false : true;
1045 } else {
1046 fprintf(stderr, "playout-moggy: Invalid policy argument %s or missing value\n", optname);
1047 exit(1);
1051 if (pp->lcapturerate == -1U) pp->lcapturerate = rate;
1052 if (pp->atarirate == -1U) pp->atarirate = rate;
1053 if (pp->capturerate == -1U) pp->capturerate = rate;
1054 if (pp->patternrate == -1U) pp->patternrate = rate;
1055 if (pp->selfatarirate == -1U) pp->selfatarirate = rate;
1056 if (pp->korate == -1U) pp->korate = rate;
1057 if (pp->josekirate == -1U) pp->josekirate = rate;
1058 if (pp->alwaysccaprate == -1U) pp->alwaysccaprate = rate;
1060 pattern3s_init(&pp->patterns, moggy_patterns_src, moggy_patterns_src_n);
1062 return p;