Merge branch 'master' of git+ssh://repo.or.cz/srv/git/pachi
[pachi.git] / tactics.c
blob57c27b5e9400d21ce30635da35599050525de598
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
5 #define DEBUG
6 #include "board.h"
7 #include "debug.h"
8 #include "tactics.h"
11 struct selfatari_state {
12 int groupcts[S_MAX];
13 group_t groupids[S_MAX][4];
15 /* This is set if this move puts a group out of _all_
16 * liberties; we need to watch out for snapback then. */
17 bool friend_has_no_libs;
18 /* We may have one liberty, but be looking for one more.
19 * In that case, @needs_more_lib is id of group
20 * already providing one, don't consider it again. */
21 group_t needs_more_lib;
22 /* ID of the first liberty, providing it again is not
23 * interesting. */
24 coord_t needs_more_lib_except;
27 static int
28 examine_friendly_groups(struct board *b, enum stone color, coord_t to, struct selfatari_state *s)
30 for (int i = 0; i < s->groupcts[color]; i++) {
31 /* We can escape by connecting to this group if it's
32 * not in atari. */
33 group_t g = s->groupids[color][i];
35 if (board_group_info(b, g).libs == 1) {
36 if (!s->needs_more_lib)
37 s->friend_has_no_libs = true;
38 // or we already have a friend with 1 lib
39 continue;
42 /* Could we self-atari the group here? */
43 if (board_group_info(b, g).libs > 2)
44 return false;
46 /* We need to have another liberty, and
47 * it must not be the other liberty of
48 * the group. */
49 int lib2 = board_group_other_lib(b, g, to);
50 /* Maybe we already looked at another
51 * group providing one liberty? */
52 if (s->needs_more_lib && s->needs_more_lib != g
53 && s->needs_more_lib_except != lib2)
54 return false;
56 /* Can we get the liberty locally? */
57 /* Yes if we are route to more liberties... */
58 if (s->groupcts[S_NONE] > 1)
59 return false;
60 /* ...or one liberty, but not lib2. */
61 if (s->groupcts[S_NONE] > 0
62 && !coord_is_adjecent(lib2, to, b))
63 return false;
65 /* ...ok, then we can still contribute a liberty
66 * later by capturing something. */
67 s->needs_more_lib = g;
68 s->needs_more_lib_except = lib2;
69 s->friend_has_no_libs = false;
72 return -1;
75 static int
76 examine_enemy_groups(struct board *b, enum stone color, coord_t to, struct selfatari_state *s)
78 /* We may be able to gain a liberty by capturing this group. */
79 group_t can_capture = 0;
81 /* Examine enemy groups: */
82 for (int i = 0; i < s->groupcts[stone_other(color)]; i++) {
83 /* We can escape by capturing this group if it's in atari. */
84 group_t g = s->groupids[stone_other(color)][i];
85 if (board_group_info(b, g).libs > 1)
86 continue;
88 /* But we need to get to at least two liberties by this;
89 * we already have one outside liberty, or the group is
90 * more than 1 stone (in that case, capturing is always
91 * nice!). */
92 if (s->groupcts[S_NONE] > 0 || !group_is_onestone(b, g))
93 return false;
94 /* ...or, it's a ko stone, */
95 if (neighbor_count_at(b, g, color) + neighbor_count_at(b, g, S_OFFBOARD) == 3) {
96 /* and we don't have a group to save: then, just taking
97 * single stone means snapback! */
98 if (!s->friend_has_no_libs)
99 return false;
101 /* ...or, we already have one indirect liberty provided
102 * by another group. */
103 if (s->needs_more_lib || (can_capture && can_capture != g))
104 return false;
105 can_capture = g;
109 if (DEBUGL(6))
110 fprintf(stderr, "no cap group\n");
112 if (!s->needs_more_lib && !can_capture && !s->groupcts[S_NONE]) {
113 /* We have no hope for more fancy tactics - this move is simply
114 * a suicide, not even a self-atari. */
115 if (DEBUGL(6))
116 fprintf(stderr, "suicide\n");
117 return true;
119 /* XXX: I wonder if it makes sense to continue if we actually
120 * just !s->needs_more_lib. */
122 return -1;
125 static int
126 setup_nakade_or_snapback(struct board *b, enum stone color, coord_t to, struct selfatari_state *s)
128 /* There is another possibility - we can self-atari if it is
129 * a nakade: we put an enemy group in atari from the inside. */
130 /* This branch also allows eyes falsification:
131 * O O O . . (This is different from throw-in to false eye
132 * X X O O . checked below in that there is no X stone at the
133 * X . X O . right of the star point in this diagram.)
134 * X X X O O
135 * X O * . . */
136 /* TODO: Allow to only nakade if the created shape is dead
137 * (http://senseis.xmp.net/?Nakade). */
139 /* This branch also covers snapback, which is kind of special
140 * nakade case. ;-) */
141 for (int i = 0; i < s->groupcts[stone_other(color)]; i++) {
142 group_t g = s->groupids[stone_other(color)][i];
143 if (board_group_info(b, g).libs != 2)
144 goto next_group;
145 /* Simple check not to re-examine the same group. */
146 if (i > 0 && s->groupids[stone_other(color)][i] == s->groupids[stone_other(color)][i - 1])
147 continue;
149 /* We must make sure the other liberty of that group:
150 * (i) is an internal liberty
151 * (ii) filling it to capture our group will not gain
152 * safety */
154 /* Let's look at the other liberty neighbors: */
155 int lib2 = board_group_other_lib(b, g, to);
156 foreach_neighbor(b, lib2, {
157 /* This neighbor of course does not contribute
158 * anything to the enemy. */
159 if (board_at(b, c) == S_OFFBOARD)
160 continue;
162 /* If the other liberty has empty neighbor,
163 * it must be the original liberty; otherwise,
164 * since the whole group has only 2 liberties,
165 * the other liberty may not be internal and
166 * we are nakade'ing eyeless group from outside,
167 * which is stupid. */
168 if (board_at(b, c) == S_NONE) {
169 if (c == to)
170 continue;
171 else
172 goto next_group;
175 int g2 = group_at(b, c);
176 /* If the neighbor is of our color, it must
177 * be our group; if it is a different group,
178 * it must not be in atari. */
179 /* X X X X We will not allow play on 'a',
180 * X X a X because 'b' would capture two
181 * X O b X different groups, forming two
182 * X X X X eyes. */
183 if (board_at(b, c) == color) {
184 if (board_group_info(b, group_at(b, c)).libs > 1)
185 continue;
186 /* Our group == one of the groups
187 * we (@to) are connected to. */
188 int j;
189 for (j = 0; j < 4; j++)
190 if (s->groupids[color][j] == g2)
191 break;
192 if (j == 4)
193 goto next_group;
194 continue;
197 /* The neighbor is enemy color. It's ok if
198 * it's still the same group or this is its
199 * only liberty. */
200 if (g == g2 || board_group_info(b, g2).libs == 1)
201 continue;
202 /* Otherwise, it must have the exact same
203 * liberties as the original enemy group. */
204 if (board_group_info(b, g2).libs == 2
205 && (board_group_info(b, g2).lib[0] == to
206 || board_group_info(b, g2).lib[1] == to))
207 continue;
209 goto next_group;
212 /* Now, we must distinguish between nakade and eye
213 * falsification; we must not falsify an eye by more
214 * than two stones. */
215 if (s->groupcts[color] < 1 ||
216 (s->groupcts[color] == 1 && group_is_onestone(b, s->groupids[color][0])))
217 return false;
219 /* We would create more than 2-stone group; in that
220 * case, the liberty of our result must be lib2,
221 * indicating this really is a nakade. */
222 for (int j = 0; j < s->groupcts[color]; j++) {
223 group_t g2 = s->groupids[color][j];
224 assert(board_group_info(b, g2).libs <= 2);
225 if (board_group_info(b, g2).libs == 2) {
226 if (board_group_info(b, g2).lib[0] != lib2
227 && board_group_info(b, g2).lib[1] != lib2)
228 goto next_group;
229 } else {
230 assert(board_group_info(b, g2).lib[0] == to);
234 return false;
235 next_group:
236 /* Unless we are dealing with snapback setup, we don't need to look
237 * further. */
238 if (s->groupcts[color])
239 return -1;
242 return -1;
245 static int
246 check_throwin(struct board *b, enum stone color, coord_t to, struct selfatari_state *s)
248 /* We can be throwing-in to false eye:
249 * X X X O X X X O X X X X X
250 * X . * X * O . X * O O . X
251 * # # # # # # # # # # # # # */
252 /* We cannot sensibly throw-in into a corner. */
253 if (neighbor_count_at(b, to, S_OFFBOARD) < 2
254 && neighbor_count_at(b, to, stone_other(color))
255 + neighbor_count_at(b, to, S_OFFBOARD) == 3
256 && board_is_false_eyelike(b, to, stone_other(color))) {
257 assert(s->groupcts[color] <= 1);
258 /* Single-stone throw-in may be ok... */
259 if (s->groupcts[color] == 0) {
260 /* O X . There is one problem - when it's
261 * . * X actually not a throw-in!
262 * # # # */
263 foreach_neighbor(b, to, {
264 if (board_at(b, c) == S_NONE) {
265 /* Is the empty neighbor an escape path? */
266 /* (Note that one S_NONE neighbor is already @to.) */
267 if (neighbor_count_at(b, c, stone_other(color))
268 + neighbor_count_at(b, c, S_OFFBOARD) < 2)
269 return -1;
272 return false;
275 /* Multi-stone throwin...? */
276 assert(s->groupcts[color] == 1);
277 group_t g = s->groupids[color][0];
279 assert(board_group_info(b, g).libs <= 2);
280 /* Suicide is definitely NOT ok, no matter what else
281 * we could test. */
282 if (board_group_info(b, g).libs == 1)
283 return true;
285 /* In that case, we must be connected to at most one stone,
286 * or throwin will not destroy any eyes. */
287 if (group_is_onestone(b, g))
288 return false;
290 return -1;
293 bool
294 is_bad_selfatari_slow(struct board *b, enum stone color, coord_t to)
296 if (DEBUGL(5))
297 fprintf(stderr, "sar check %s %s\n", stone2str(color), coord2sstr(to, b));
298 /* Assess if we actually gain any liberties by this escape route.
299 * Note that this is not 100% as we cannot check whether we are
300 * connecting out or just to ourselves. */
302 struct selfatari_state s;
303 memset(&s, 0, sizeof(s));
304 int d;
306 foreach_neighbor(b, to, {
307 enum stone color = board_at(b, c);
308 s.groupids[color][s.groupcts[color]++] = group_at(b, c);
311 /* We have shortage of liberties; that's the point. */
312 assert(s.groupcts[S_NONE] <= 1);
314 d = examine_friendly_groups(b, color, to, &s);
315 if (d >= 0)
316 return d;
318 if (DEBUGL(6))
319 fprintf(stderr, "no friendly group\n");
321 d = examine_enemy_groups(b, color, to, &s);
322 if (d >= 0)
323 return d;
325 if (DEBUGL(6))
326 fprintf(stderr, "no escape\n");
328 d = setup_nakade_or_snapback(b, color, to, &s);
329 if (d >= 0)
330 return d;
332 if (DEBUGL(6))
333 fprintf(stderr, "no nakade group\n");
335 d = check_throwin(b, color, to, &s);
336 if (d >= 0)
337 return d;
339 if (DEBUGL(6))
340 fprintf(stderr, "no throw-in group\n");
342 /* No way to pull out, no way to connect out. This really
343 * is a bad self-atari! */
344 return true;
348 /* Is this ladder breaker friendly for the one who catches ladder. */
349 static bool
350 ladder_catcher(struct board *b, int x, int y, enum stone laddered)
352 enum stone breaker = board_atxy(b, x, y);
353 return breaker == stone_other(laddered) || breaker == S_OFFBOARD;
356 bool
357 is_border_ladder(struct board *b, coord_t coord, enum stone lcolor)
359 int x = coord_x(coord, b), y = coord_y(coord, b);
361 if (DEBUGL(5))
362 fprintf(stderr, "border ladder\n");
363 /* Direction along border; xd is horiz. border, yd vertical. */
364 int xd = 0, yd = 0;
365 if (board_atxy(b, x + 1, y) == S_OFFBOARD || board_atxy(b, x - 1, y) == S_OFFBOARD)
366 yd = 1;
367 else
368 xd = 1;
369 /* Direction from the border; -1 is above/left, 1 is below/right. */
370 int dd = (board_atxy(b, x + yd, y + xd) == S_OFFBOARD) ? 1 : -1;
371 if (DEBUGL(6))
372 fprintf(stderr, "xd %d yd %d dd %d\n", xd, yd, dd);
373 /* | ? ?
374 * | . O #
375 * | c X #
376 * | . O #
377 * | ? ? */
378 /* This is normally caught, unless we have friends both above
379 * and below... */
380 if (board_atxy(b, x + xd * 2, y + yd * 2) == lcolor
381 && board_atxy(b, x - xd * 2, y - yd * 2) == lcolor)
382 return false;
383 /* ...or can't block where we need because of shortage
384 * of liberties. */
385 int libs1 = board_group_info(b, group_atxy(b, x + xd - yd * dd, y + yd - xd * dd)).libs;
386 int libs2 = board_group_info(b, group_atxy(b, x - xd - yd * dd, y - yd - xd * dd)).libs;
387 if (DEBUGL(6))
388 fprintf(stderr, "libs1 %d libs2 %d\n", libs1, libs2);
389 if (libs1 < 2 && libs2 < 2)
390 return false;
391 if (board_atxy(b, x + xd * 2, y + yd * 2) == lcolor && libs1 < 3)
392 return false;
393 if (board_atxy(b, x - xd * 2, y - yd * 2) == lcolor && libs2 < 3)
394 return false;
395 return true;
398 /* This is very trivial and gets a lot of corner cases wrong.
399 * We need this to be just very fast. One important point is
400 * that we sometimes might not notice a ladder but if we do,
401 * it should always work; thus we can use this for strong
402 * negative hinting safely. */
403 bool
404 is_middle_ladder(struct board *b, coord_t coord, enum stone lcolor)
406 int x = coord_x(coord, b), y = coord_y(coord, b);
408 /* Figure out the ladder direction */
409 int xd, yd;
410 xd = board_atxy(b, x + 1, y) == S_NONE ? 1 : board_atxy(b, x - 1, y) == S_NONE ? -1 : 0;
411 yd = board_atxy(b, x, y + 1) == S_NONE ? 1 : board_atxy(b, x, y - 1) == S_NONE ? -1 : 0;
413 if (!xd || !yd) {
414 if (DEBUGL(5))
415 fprintf(stderr, "no ladder, too little space; self-atari?\n");
416 return false;
419 /* For given (xd,yd), we have two possibilities where to move
420 * next. Consider (-1,-1):
421 * n X . n c X
422 * c O X X O #
423 * X # # . X #
425 bool horiz_first = ladder_catcher(b, x, y - yd, lcolor); // left case
426 bool vert_first = ladder_catcher(b, x - xd, y, lcolor); // right case
428 /* We don't have to look at the other 'X' in the position - if it
429 * wouldn't be there, the group wouldn't be in atari. */
431 /* We do only tight ladders, not loose ladders. Furthermore,
432 * the ladders need to be simple:
433 * . X . . . X
434 * c O X supported . c O unsupported
435 * X # # X O #
437 assert(!(horiz_first && vert_first));
438 if (!horiz_first && !vert_first) {
439 /* TODO: In case of basic non-simple ladder, play out both variants. */
440 if (DEBUGL(5))
441 fprintf(stderr, "non-simple ladder\n");
442 return false;
445 /* We do that below for further moves, but now initially - check
446 * that at 'c', we aren't putting any of the catching stones
447 * in atari. */
448 #if 1 // this might be broken?
449 #define check_catcher_danger(b, x_, y_) do { \
450 if (board_atxy(b, (x_), (y_)) != S_OFFBOARD \
451 && board_group_info(b, group_atxy(b, (x_), (y_))).libs <= 2) { \
452 if (DEBUGL(5)) \
453 fprintf(stderr, "ladder failed - atari at the beginning\n"); \
454 return false; \
455 } } while (0)
457 if (horiz_first) {
458 check_catcher_danger(b, x, y - yd);
459 check_catcher_danger(b, x - xd, y + yd);
460 } else {
461 check_catcher_danger(b, x - xd, y);
462 check_catcher_danger(b, x + xd, y - yd);
464 #undef check_catcher_danger
465 #endif
467 #define ladder_check(xd1_, yd1_, xd2_, yd2_, xd3_, yd3_) \
468 if (board_atxy(b, x, y) != S_NONE) { \
469 /* Did we hit a stone when playing out ladder? */ \
470 if (ladder_catcher(b, x, y, lcolor)) \
471 return true; /* ladder works */ \
472 if (board_group_info(b, group_atxy(b, x, y)).lib[0] > 0) \
473 return false; /* friend that's not in atari himself */ \
474 } else { \
475 /* No. So we are at new position. \
476 * We need to check indirect ladder breakers. */ \
477 /* . 2 x 3 . \
478 * . x o O 1 <- only at O we can check for o at 2 \
479 * x o o x . otherwise x at O would be still deadly \
480 * o o x . . \
481 * We check for o and x at 1, these are vital. \
482 * We check only for o at 2; x at 2 would mean we \
483 * need to fork (one step earlier). */ \
484 coord_t c1 = coord_xy(b, x + (xd1_), y + (yd1_)); \
485 enum stone s1 = board_at(b, c1); \
486 if (s1 == lcolor) return false; \
487 if (s1 == stone_other(lcolor)) { \
488 /* One more thing - if the position at 3 is \
489 * friendly and safe, we escaped anyway! */ \
490 coord_t c3 = coord_xy(b, x + (xd3_), y + (yd3_)); \
491 return board_at(b, c3) != lcolor \
492 || board_group_info(b, group_at(b, c3)).libs < 2; \
494 enum stone s2 = board_atxy(b, x + (xd2_), y + (yd2_)); \
495 if (s2 == lcolor) return false; \
496 /* Then, can X actually "play" 1 in the ladder? */ \
497 if (neighbor_count_at(b, c1, lcolor) + neighbor_count_at(b, c1, S_OFFBOARD) >= 2) \
498 return false; /* It would be self-atari! */ \
500 #define ladder_horiz do { if (DEBUGL(6)) fprintf(stderr, "%d,%d horiz step (%d,%d)\n", x, y, xd, yd); x += xd; ladder_check(xd, 0, -2 * xd, yd, 0, yd); } while (0)
501 #define ladder_vert do { if (DEBUGL(6)) fprintf(stderr, "%d,%d vert step of (%d,%d)\n", x, y, xd, yd); y += yd; ladder_check(0, yd, xd, -2 * yd, xd, 0); } while (0)
503 if (ladder_catcher(b, x - xd, y, lcolor))
504 ladder_horiz;
505 do {
506 ladder_vert;
507 ladder_horiz;
508 } while (1);
512 bool
513 board_stone_radar(struct board *b, coord_t coord, int distance)
515 int bounds[4] = {
516 coord_x(coord, b) - distance,
517 coord_y(coord, b) - distance,
518 coord_x(coord, b) + distance,
519 coord_y(coord, b) + distance
521 for (int i = 0; i < 4; i++)
522 if (bounds[i] < 1)
523 bounds[i] = 1;
524 else if (bounds[i] > board_size(b) - 2)
525 bounds[i] = board_size(b) - 2;
526 for (int x = bounds[0]; x <= bounds[2]; x++)
527 for (int y = bounds[1]; y <= bounds[3]; y++)
528 if (board_atxy(b, x, y) != S_NONE) {
529 /* fprintf(stderr, "radar %d,%d,%d: %d,%d (%d)\n",
530 coord_x(coord, b), coord_y(coord, b),
531 distance, x, y, board_atxy(b, x, y)); */
532 return true;
534 return false;
538 void
539 cfg_distances(struct board *b, coord_t start, int *distances, int maxdist)
541 /* Queue for d+1 spots; no two spots of the same group
542 * should appear in the queue. */
543 #define qinc(x) (x = ((x + 1) >= board_size2(b) ? ((x) + 1 - board_size2(b)) : (x) + 1))
544 coord_t queue[board_size2(b)]; int qstart = 0, qstop = 0;
546 foreach_point(b) {
547 distances[c] = board_at(b, c) == S_OFFBOARD ? maxdist + 1 : -1;
548 } foreach_point_end;
550 queue[qstop++] = start;
551 for (int d = 0; d <= maxdist; d++) {
552 /* Process queued moves, while setting the queue
553 * for new wave. */
554 int qa = qstart, qb = qstop;
555 qstart = qstop;
556 for (int q = qa; q < qb; qinc(q)) {
557 #define cfg_one(coord, grp) do {\
558 distances[coord] = d; \
559 foreach_neighbor (b, coord, { \
560 if (distances[c] < 0 && (!grp || group_at(b, coord) != grp)) { \
561 queue[qstop] = c; \
562 qinc(qstop); \
564 }); \
565 } while (0)
566 coord_t cq = queue[q];
567 if (distances[cq] >= 0)
568 continue; /* We already looked here. */
569 if (board_at(b, cq) == S_NONE) {
570 cfg_one(cq, 0);
571 } else {
572 group_t g = group_at(b, cq);
573 foreach_in_group(b, g) {
574 cfg_one(c, g);
575 } foreach_in_group_end;
577 #undef cfg_one
581 foreach_point(b) {
582 if (distances[c] < 0)
583 distances[c] = maxdist + 1;
584 } foreach_point_end;
588 float
589 board_effective_handicap(struct board *b, int first_move_value)
591 /* This can happen if the opponent passes during handicap
592 * placing phase. */
593 // assert(b->handicap != 1);
594 return (b->handicap ? b->handicap : 1) * first_move_value + 0.5 - b->komi;
598 bool
599 pass_is_safe(struct board *b, enum stone color, struct move_queue *mq)
601 float score = board_official_score(b, mq);
602 if (color == S_BLACK)
603 score = -score;
604 //fprintf(stderr, "%d score %f\n", color, score);
605 return (score > 0);
609 /* On average 25% of points remain empty at the end of a game */
610 #define EXPECTED_FINAL_EMPTY_PERCENT 25
612 /* Returns estimated number of remaining moves for one player until end of game. */
614 board_estimated_moves_left(struct board *b)
616 int total_points = (board_size(b)-2)*(board_size(b)-2);
617 int moves_left = (b->flen - total_points*EXPECTED_FINAL_EMPTY_PERCENT/100)/2;
618 return moves_left > MIN_MOVES_LEFT ? moves_left : MIN_MOVES_LEFT;