Updated README: Equal sign not required with `--mode` flag.
[sgk-go] / engine / reading.c
CommitLineData
7eeb782e
AT
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
2 * This is GNU Go, a Go program. Contact gnugo@gnu.org, or see *
3 * http://www.gnu.org/software/gnugo/ for more information. *
4 * *
5 * Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, *
6 * 2008 and 2009 by the Free Software Foundation. *
7 * *
8 * This program is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU General Public License as *
10 * published by the Free Software Foundation - version 3 or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License in file COPYING for more details. *
17 * *
18 * You should have received a copy of the GNU General Public *
19 * License along with this program; if not, write to the Free *
20 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
21 * Boston, MA 02111, USA. *
22\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
23
24#include "gnugo.h"
25
26#include <stdio.h>
27#include <stdlib.h>
28#include <stdarg.h>
29#include <string.h>
30
31#include "liberty.h"
32#include "cache.h"
33#include "gg_utils.h"
34
35/* If nonzero, attack() and find_defense() write all results to
36 * stderr. Use this to if you have deviations in results, but cannot
37 * find where they come from.
38 *
39 * Redirect results to a file. Take dumps of two versions and
40 * (assuming GNU tools) do `sort -t= -s' on both. Then join the
41 * sorted dumps:
42 *
43 * join -t= sorted-first-dump sorted-second-dump \
44 * | sed -e "s/^[^=]\+=\([^=]\+\)=\1$//" | tr -s "\n" | tr = "\t" \
45 * | uniq
46 *
47 * to get a nice list of deviations. This is only meaningful if you
48 * dump results of a single test (or at least tests originating at a
49 * same position).
50 */
51#define DUMP_ALL_RESULTS 0
52
53
54/* Size of array where candidate moves are stored. */
55#define MAX_MOVES 50
56
57/* Please notice that message had better be a fixed string. Only the
58 * pointer to it is saved and there is no attempt to free up any
59 * storage.
60 */
61#define ADD_CANDIDATE_MOVE(move, this_score, moves, this_message) \
62 do { \
63 int u; \
64 for (u = 0; u < (moves).num; u++) \
65 if ((moves).pos[u] == (move)) { \
66 (moves).score[u] += this_score; \
67 break; \
68 } \
69 if ((u == (moves).num) && ((moves).num < MAX_MOVES)) { \
70 (moves).pos[(moves).num] = move; \
71 (moves).score[(moves).num] = this_score; \
72 (moves).message[(moves).num] = this_message; \
73 (moves).num++; \
74 } \
75 } while (0)
76
77#define REMOVE_CANDIDATE_MOVE(move, moves) \
78 do { \
79 int u; \
80 for (u = (moves).num_tried; u < (moves).num; u++) { \
81 if ((moves).pos[u] == (move)) { \
82 (moves).pos[u] = (moves).pos[(moves).num - 1]; \
83 (moves).score[u] = (moves).score[(moves).num - 1]; \
84 (moves).message[u] = (moves).message[(moves).num - 1]; \
85 (moves).num--; \
86 break; \
87 } \
88 } \
89 } while (0)
90
91
92/* This macro checks whether the reported result is a loss, so we have won
93 * and can exit, or else if it is the best result so far.
94 * Note that SGFTRACE must have been setup.
95 */
96#define CHECK_RESULT(savecode, savemove, code, move_pos, move_ptr, \
97 trace_message) \
98 do { \
99 if (code == 0) { \
100 if (move_ptr) \
101 *(move_ptr) = (move_pos); \
102 SGFTRACE(move_pos, WIN, trace_message); \
103 return WIN; \
104 } \
105 else if (REVERSE_RESULT(code) > savecode) { \
106 savemove = move_pos; \
107 savecode = REVERSE_RESULT(code); \
108 } \
109 } while (0)
110
111/* Reverse of CHECK_RESULT, for results passed from a helper function. */
112#define CHECK_RESULT_UNREVERSED(savecode, savemove, code, move_pos, \
113 move_ptr, trace_message) \
114 CHECK_RESULT(savecode, savemove, REVERSE_RESULT(code), move_pos, \
115 move_ptr, trace_message)
116
117
118#define RETURN_RESULT(savecode, savemove, move_ptr, trace_message) \
119 do { \
120 if (savecode) { \
121 if (move_ptr) \
122 *(move_ptr) = (savemove); \
123 SGFTRACE(savemove, savecode, trace_message); \
124 } \
125 else \
126 SGFTRACE(0, 0, NULL); \
127 return savecode; \
128 } while (0)
129
130
131/* Play a collected batch of moves and see if any of them works. This
132 * is a defense version.
133 */
134#define DEFEND_TRY_MOVES(no_deep_branching, attack_hint) \
135 do { \
136 int k; \
137 \
138 for (k = moves.num_tried; k < moves.num; k++) { \
139 int ko_move; \
140 int dpos = moves.pos[k]; \
141 \
142 if (komaster_trymove(dpos, color, moves.message[k], str, &ko_move,\
143 stackp <= ko_depth && savecode == 0)) { \
144 int acode = do_attack(str, (attack_hint)); \
145 popgo(); \
146 \
147 if (!ko_move) { \
148 CHECK_RESULT(savecode, savemove, acode, dpos, move, \
149 "defense effective"); \
150 } \
151 else { \
152 if (acode != WIN) { \
153 savemove = dpos; \
154 savecode = KO_B; \
155 } \
156 } \
157 } \
158 \
159 if ((no_deep_branching) && stackp >= branch_depth) \
160 RETURN_RESULT(savecode, savemove, move, "branching limit"); \
161 } \
162 \
163 moves.num_tried = moves.num; \
164 } while (0)
165
166
167/* Attack version of the macro above. This one is a bit more
168 * complicated, because when defender fails to defend, attacker has to
169 * prove that he can capture the string before claiming victory.
170 */
171#define ATTACK_TRY_MOVES(no_deep_branching, defense_hint) \
172 do { \
173 int k; \
174 \
175 for (k = moves.num_tried; k < moves.num; k++) { \
176 int ko_move; \
177 int apos = moves.pos[k]; \
178 \
179 if ((board_ko_pos != NO_MOVE || !send_two_return_one(apos, other))\
180 && komaster_trymove(apos, other, moves.message[k], \
181 str, &ko_move, \
182 stackp <= ko_depth && savecode == 0)) { \
183 int dcode = do_find_defense(str, (defense_hint)); \
184 \
185 if (REVERSE_RESULT(dcode) > savecode \
186 && do_attack(str, NULL)) { \
187 if (!ko_move) { \
188 if (dcode == 0) { \
189 popgo(); \
190 RETURN_RESULT(WIN, apos, move, "attack effective"); \
191 } \
192 \
193 savemove = apos; \
194 savecode = REVERSE_RESULT(dcode); \
195 } \
196 else { \
197 savemove = apos; \
198 savecode = KO_B; \
199 } \
200 } \
201 \
202 popgo(); \
203 } \
204 \
205 if ((no_deep_branching) && stackp >= branch_depth) \
206 RETURN_RESULT(savecode, savemove, move, "branching limit"); \
207 } \
208 \
209 moves.num_tried = moves.num; \
210 } while (0)
211
212
213
214struct reading_moves
215{
216 int pos[MAX_MOVES];
217 int score[MAX_MOVES];
218 const char *message[MAX_MOVES];
219 int num;
220 int num_tried;
221};
222
223/*
224 * The functions in reading.c are used to read whether groups
225 * can be captured or not. See the Texinfo documentation
226 * (Reading) for more information.
227 *
228 * NULL POINTERS: Many functions in this file can use pointers
229 * to return the locations of recommended plays. These can be
230 * set NULL in which case these values are not returned.
231 */
232
233static int do_find_defense(int str, int *move);
234static int defend1(int str, int *move);
235static int defend2(int str, int *move);
236static int defend3(int str, int *move);
237static int defend4(int str, int *move);
238static void special_rescue_moves(int str, int lib,
239 struct reading_moves *moves);
240static void bamboo_rescue_moves(int str, int num_libs, int libs[],
241 struct reading_moves *moves);
242static void special_rescue2_moves(int str, int libs[2],
243 struct reading_moves *moves);
244static void special_rescue3_moves(int str, int libs[3],
245 struct reading_moves *moves);
246static void special_rescue4_moves(int str, int libs[2],
247 struct reading_moves *moves);
248static void hane_rescue_moves(int str, int libs[4],
249 struct reading_moves *moves);
250static void special_rescue5_moves(int str, int libs[3],
251 struct reading_moves *moves);
252static void special_rescue6_moves(int str, int libs[3],
253 struct reading_moves *moves);
254static void set_up_snapback_moves(int str, int lib,
255 struct reading_moves *moves);
256static void edge_clamp_moves(int str, struct reading_moves *moves);
257static int do_attack(int str, int *move);
258static int attack1(int str, int *move);
259static int attack2(int str, int *move);
260static int attack3(int str, int *move);
261static int attack4(int str, int *move);
262static void find_cap_moves(int str, struct reading_moves *moves);
263static void special_attack2_moves(int str, int libs[2],
264 struct reading_moves *moves);
265static void special_attack3_moves(int str, int libs[2],
266 struct reading_moves *moves);
267static void special_attack4_moves(int str, int libs[2],
268 struct reading_moves *moves);
269static void draw_back_moves(int str, struct reading_moves *moves);
270static void edge_closing_backfill_moves(int str, int apos,
271 struct reading_moves *moves);
272static void edge_block_moves(int str, int apos,
273 struct reading_moves *moves);
274static void propose_edge_moves(int str, int *libs, int liberties,
275 struct reading_moves *moves, int color);
276static void break_chain_moves(int str, struct reading_moves *moves);
277static int defend_secondary_chain1_moves(int str, struct reading_moves *moves,
278 int min_liberties);
279static void defend_secondary_chain2_moves(int str, struct reading_moves *moves,
280 int min_liberties);
281static void break_chain2_efficient_moves(int str,
282 struct reading_moves *moves);
283static void do_find_break_chain2_efficient_moves(int str, int adj,
284 struct reading_moves *moves);
285static void break_chain2_moves(int str, struct reading_moves *moves,
286 int require_safe, int be_aggressive);
287static void break_chain2_defense_moves(int str, struct reading_moves *moves,
288 int be_aggressive);
289static void break_chain3_moves(int str, struct reading_moves *moves,
290 int be_aggressive);
291static void break_chain4_moves(int str, struct reading_moves *moves,
292 int be_aggressive);
293static void superstring_moves(int str, struct reading_moves *moves,
294 int liberty_cap, int does_attack);
295static void squeeze_moves(int str, struct reading_moves *moves);
296static void superstring_break_chain_moves(int str, int liberty_cap,
297 struct reading_moves *moves);
298static void double_atari_chain2_moves(int str,
299 struct reading_moves *moves,
300 int generate_more_moves);
301static void order_moves(int str, struct reading_moves *moves,
302 int color, const char *funcname, int killer);
303static int simple_ladder_defend(int str, int *move);
304static int in_list(int move, int num_moves, int *moves);
305
306
307/* Statistics. */
308static int reading_node_counter = 0;
309static int nodes_when_called = 0;
310
311
312
313/* ================================================================ */
314/* Goal functions */
315/* ================================================================ */
316
317
318/*
319 * These functions define goals for the reading process. They use
320 * the rest of the reading machinery to evaluate whether the goal
321 * is fulfillable.
322 *
323 * The simplest goals are defined by attack() and find_defense(),
324 * namely to see if it is possible to capture or defend a single
325 * string. More complex goals are defined by e.g. attack_either()
326 * or defend_both().
327 *
328 * The functions in this section and the next are the only ones which are
329 * callable from outside this file.
330 */
331
332
333/* attack(str, *move) determines if the string at (str) can be
334 * captured, and if so, (*move) returns the attacking move, unless
335 * (move) is a null pointer. Use a null pointer if you are interested
336 * in the result of the attack but not the attacking move itself.
337 *
338 * Return WIN if the attack succeeds unconditionally, 0 if it doesn't.
339 * Returns KO_A or KO_B if the result depends on ko:
340 * - Returns KO_A if the attack succeeds provided attacker is willing to
341 * ignore any ko threat (the attacker makes the first ko capture).
342 * - Returns KO_B if attack succeeds provided attacker has a ko threat
343 * which must be answered (the defender makes the first ko capture).
344 */
345
346int
347attack(int str, int *move)
348{
349 int result;
350 int nodes;
351 int origin;
352 int the_move = NO_MOVE;
353 int liberties = countlib(str);
354
355 nodes_when_called = reading_node_counter;
356 /* Don't even spend time looking in the cache if there are more than
357 * enough liberties. We need this before the persistent cache lookup
358 * to avoid results inconsistent with find_defense().
359 */
360 if (liberties > 4
361 || (liberties == 4 && stackp > fourlib_depth)
362 || (liberties == 3 && stackp > depth))
363 return 0;
364
365 origin = find_origin(str);
366 if (search_persistent_reading_cache(ATTACK, origin, &result, &the_move)) {
367 if (move)
368 *move = the_move;
369 return result;
370 }
371
372 memset(shadow, 0, sizeof(shadow));
373 result = do_attack(str, &the_move);
374 nodes = reading_node_counter - nodes_when_called;
375
376 if (debug & DEBUG_READING_PERFORMANCE) {
377 if (reading_node_counter - nodes_when_called
378 >= MIN_READING_NODES_TO_REPORT) {
379 if (result != 0)
380 gprintf("%oattack %1m(%1m) = %d %1M, %d nodes ", str, origin, result,
381 the_move, nodes);
382 else
383 gprintf("%oattack %1m(%1m) = %d, %d nodes ", str, origin, result,
384 nodes);
385 dump_stack();
386 }
387 }
388
389 store_persistent_reading_cache(ATTACK, origin, result, the_move, nodes);
390
391 if (move)
392 *move = the_move;
393
394#if DUMP_ALL_RESULTS
395 do_dump_stack();
396 gprintf("%oattack %1m (%d)=%d %1m\n", str, depth, result, the_move);
397#endif
398
399 return result;
400}
401
402
403/* find_defense(str, *move) attempts to find a move that will save
404 * the string at (str). It returns WIN if such a move is found, with
405 * (*move) the location of the saving move, unless (move) is a
406 * null pointer. It is not checked that tenuki defends, so this may
407 * give an erroneous answer if !attack(str).
408 *
409 * Returns KO_A or KO_B if the result depends on ko. Returns KO_A if the
410 * string can be defended provided the defender is willing to ignore
411 * any ko threat. Returns KO_B if the defender wins by having a ko threat
412 * which must be answered.
413 */
414
415int
416find_defense(int str, int *move)
417{
418 int result;
419 int nodes;
420 int origin;
421 int the_move = NO_MOVE;
422 int liberties = countlib(str);
423
424 nodes_when_called = reading_node_counter;
425 /* Don't even spend time looking in the cache if there are more than
426 * enough liberties.
427 */
428 if (liberties > 4
429 || (liberties == 4 && stackp > fourlib_depth)) {
430 if (move)
431 *move = NO_MOVE;
432 return WIN;
433 }
434
435 origin = find_origin(str);
436 if (search_persistent_reading_cache(FIND_DEFENSE, origin,
437 &result, &the_move)) {
438 if (move)
439 *move = the_move;
440 return result;
441 }
442
443 memset(shadow, 0, sizeof(shadow));
444 result = do_find_defense(str, &the_move);
445 nodes = reading_node_counter - nodes_when_called;
446
447 if (debug & DEBUG_READING_PERFORMANCE) {
448 if (reading_node_counter - nodes_when_called
449 >= MIN_READING_NODES_TO_REPORT) {
450 if (result != 0)
451 gprintf("%odefend %1m(%1m) = %d %1M, %d nodes ", str, origin, result,
452 the_move, nodes);
453 else
454 gprintf("%odefend %1m(%1m) = %d, %d nodes ", str, origin, result,
455 nodes);
456 dump_stack();
457 }
458 }
459
460 store_persistent_reading_cache(FIND_DEFENSE, origin, result,
461 the_move, nodes);
462
463 if (move)
464 *move = the_move;
465
466#if DUMP_ALL_RESULTS
467 do_dump_stack();
468 gprintf("%odefend %1m (%d)=%d %1m\n", str, depth, result, the_move);
469#endif
470
471 return result;
472}
473
474
475/* attack_and_defend(str, &acode, &attack_point,
476 * &dcode, &defense_point)
477 * is a frontend to the attack() and find_defense() functions, which
478 * guarantees a consistent result. If a string cannot be attacked, 0
479 * is returned and acode is 0. If a string can be attacked and
480 * defended, WIN is returned, acode and dcode are both non-zero, and
481 * (attack_point), (defense_point) both point to vertices on the board.
482 * If a string can be attacked but not defended, 0 is again returned,
483 * acode is non-zero, dcode is 0, and (attack_point) points to a vertex
484 * on the board.
485 *
486 * This function in particular guarantees that if there is an attack,
487 * it will never return (defense_point) = NO_MOVE, which means the string is
488 * safe without defense. Separate calls to attack() and find_defense()
489 * may occasionally give this result, due to irregularities introduced
490 * by the persistent reading cache.
491 */
492int
493attack_and_defend(int str,
494 int *attack_code, int *attack_point,
495 int *defend_code, int *defense_point)
496{
497 int acode = 0;
498 int apos = NO_MOVE;
499 int dcode = 0;
500 int dpos = NO_MOVE;
501
502 acode = attack(str, &apos);
503 if (acode != 0)
504 dcode = find_defense(str, &dpos);
505
506 ASSERT1(!(acode != 0 && dcode == WIN && dpos == NO_MOVE), str);
507
508 if (attack_code)
509 *attack_code = acode;
510 if (attack_point)
511 *attack_point = apos;
512 if (defend_code)
513 *defend_code = dcode;
514 if (defense_point)
515 *defense_point = dpos;
516
517 return acode != 0 && dcode != 0;
518}
519
520
521/*
522 * attack_either(astr, bstr) returns true if there is a move which
523 * guarantees that at least one of the strings (astr) and (bstr)
524 * can be captured. A typical application for this is in connection
525 * patterns, where after a cut it suffices to capture one of the cutting
526 * stones.
527 *
528 * FIXME: The current implementation only looks for uncoordinated
529 * attacks. This is insufficient to find double ataris or
530 * moves such as 'a' in positions like
531 *
532 * XOOOOOOOX
533 * XOXXOXXOX
534 * XX..a..XX
535 * ---------
536 *
537 * where neither of the threatened X stones can be captured right
538 * out. Still either can be captured by a move down to a.
539 */
540
541int
542attack_either(int astr, int bstr)
543{
544 int asuccess = 0;
545 int bsuccess = 0;
546 int color = board[astr];
547 ASSERT1(IS_STONE(color) , astr);
548 ASSERT1(color == board[bstr], bstr);
549
550 /* Start by attacking the string with the fewest liberties. On
551 * average this seems to be slightly more efficient.
552 */
553 if (countlib(astr) > countlib(bstr)) {
554 int t = astr;
555 astr = bstr;
556 bstr = t;
557 }
558
559 asuccess = attack(astr, NULL);
560 if (asuccess == WIN)
561 return asuccess;
562
563 bsuccess = attack(bstr, NULL);
564 if (asuccess || bsuccess) {
565 return (asuccess > bsuccess) ? asuccess : bsuccess;
566 }
567
568 /* Try (a little) harder */
569 {
570 int alibs[2];
571 int blibs[2];
572 int alib = findlib(astr, 2, alibs);
573 int defended0 = WIN;
574 int defended1 = WIN;
575 int other = OTHER_COLOR(color);
576 /* Let's just try the case where the group with the fewest liberties
577 * has only 2, and try each atari in turn.
578 */
579 if (alib == 2) {
580 if (trymove(alibs[0], other, "attack_either-A", astr)) {
581 defended0 = defend_both(astr, bstr);
582 popgo();
583 }
584 if (defended0
585 && trymove(alibs[1], other, "attack_either-B", astr)) {
586 defended1 = defend_both(astr, bstr);
587 popgo();
588 }
589 }
590 /* The second string is possibly also short in liberties.
591 * Let's try to improve the result.
592 */
593 if (defended0 > 0 && defended1 > 0
594 && findlib(bstr, 2, blibs) == 2) {
595 defended0 = gg_min(defended0, defended1);
596 defended1 = defended0;
597
598 /* We may get here even if alib==1, in case there is a snapback.
599 * To avoid referencing uninitialized memory in this case we
600 * explicitly set alibs[1] to NO_MOVE.
601 */
602 if (alib == 1)
603 alibs[1] = NO_MOVE;
604
605 if (blibs[0] != alibs[0] && blibs[0] != alibs[1]
606 && trymove(blibs[0], other, "attack_either-C", bstr)) {
607 int defended = defend_both(astr, bstr);
608 defended0 = gg_min(defended0, defended);
609 popgo();
610 }
611 if (defended0
612 && blibs[1] != alibs[0] && blibs[1] != alibs[1]
613 && trymove(blibs[1], other, "attack_either-D", bstr)) {
614 int defended = defend_both(astr, bstr);
615 defended1 = gg_min(defended1, defended);
616 popgo();
617 }
618 }
619 return REVERSE_RESULT(gg_min(defended0, defended1));
620 }
621
622}
623
624
625/*
626 * defend_both(astr, bstr) returns true if both the strings (astr)
627 * and (bstr) can be defended simultaneously or if there is no attack.
628 * A typical application for this is in connection patterns, where
629 * after a cut it's necessary to defend both cutting stones.
630 *
631 * FIXME: The current implementation only makes halfhearted
632 * attempts to find coordinated defense moves. A proper implementation
633 * would require some serious reading.
634 */
635
636int
637defend_both(int astr, int bstr)
638{
639 int a_threatened = 0;
640 int b_threatened = 0;
641 int a_savepos;
642 int b_savepos;
643 int acode = 0;
644 int dcode = 0;
645
646 int color = board[astr];
647 ASSERT1(IS_STONE(color) , astr);
648 ASSERT1(color == board[bstr], bstr);
649
650 /* This probably helps here too...
651 * (see attack_either)
652 */
653 if (countlib(astr) > countlib(bstr)) {
654 int t = astr;
655 astr = bstr;
656 bstr = t;
657 }
658
659 attack_and_defend(astr, &acode, NULL, &dcode, &a_savepos);
660 if (acode != 0) {
661 a_threatened = 1;
662 if (dcode != WIN)
663 return 0; /* (astr) already lost */
664 }
665
666 attack_and_defend(bstr, &acode, NULL, &dcode, &b_savepos);
667 if (acode != 0) {
668 b_threatened = 1;
669 if (dcode != WIN)
670 return 0; /* (bstr) already lost */
671 }
672
673 /* Neither string can be attacked or only one of them, in which case
674 * we have time to save it.
675 */
676 if (!a_threatened || !b_threatened)
677 return WIN;
678
679 /* If both strings are threatened we assume that one will become lost,
680 * unless find_defense() happened to return the same defense point for
681 * both (which e.g. may happen if they are in fact the same string).
682 * This is still a bit too pessimistic, as there may be one move which
683 * saves both strings. To do this right we should try each move which
684 * defends either string and see if it also defends the other string.
685 */
686
687 if (a_savepos == b_savepos)
688 return WIN; /* Both strings can be attacked but also defended
689 * by one move. */
690
691 /* We also try each of the returned defense points and see whether
692 * the other string can still be attacked. This still gives a
693 * somewhat pessimistic estimation.
694 */
695
696 if (trymove(a_savepos, color, "defend_both-A", astr)) {
697 if (board[bstr] && !attack(bstr, NULL)) {
698 popgo();
699 return WIN;
700 }
701 popgo();
702 }
703
704 if (trymove(b_savepos, color, "defend_both-B", bstr)) {
705 if (board[astr] && !attack(astr, NULL)) {
706 popgo();
707 return WIN;
708 }
709 popgo();
710 }
711
712 /* The next improvement is to try to attack a common adjacent string. */
713 {
714 int adjs1[MAXCHAIN];
715 int neighbors1;
716 int adjs2[MAXCHAIN];
717 int neighbors2;
718 int r;
719 int s;
720 int epos;
721 int fpos;
722
723 neighbors1 = chainlinks(astr, adjs1);
724 neighbors2 = chainlinks(bstr, adjs2);
725
726 for (r = 0; r < neighbors1; r++) {
727 epos = adjs1[r];
728 if (countlib(epos) <= 4
729 && (epos != a_savepos)
730 && (epos != b_savepos)) {
731 /* Is (epos) also adjacent to (bstr)? */
732 for (s = 0; s < neighbors2; s++) {
733 if (adjs2[s] == adjs1[r])
734 break;
735 }
736 if (s == neighbors2)
737 continue; /* No, it wasn't. */
738
739 if (attack(epos, &fpos)) {
740 if (trymove(fpos, color, "defend_both-C", astr)) {
741 if (board[astr] && board[bstr]
742 && !attack(astr, NULL)
743 && !attack(bstr, NULL)) {
744 popgo();
745 return WIN;
746 }
747 popgo();
748 }
749 }
750 }
751 }
752 }
753
754 /* Both strings can be attacked but we have only time to defend one. */
755 return 0;
756}
757
758
759/*
760 * break_through(apos, bpos, cpos) returns WIN if a position can
761 * succesfully be broken through and CUT if it can be cut. The position
762 * is assumed to have the shape (the colors may be reversed)
763 *
764 * .O. dbe
765 * OXO aFc
766 *
767 * It is X to move and try to capture at least one of a, b, and c. If
768 * this succeeds, X is said to have broken through the position.
769 * Otherwise X may try to cut through the position, which means
770 * keeping F safe and getting a tactically safe string at either d or
771 * e.
772 *
773 * Important notice: a, b, and c must be given in the correct order.
774 *
775 * FIXME: The reading involved here can most likely be improved.
776 *
777 * FIXME: We need to take ko results properly into account.
778 */
779
780static int
781break_through_helper(int apos, int bpos, int cpos,
782 int dpos, int epos, int Fpos,
783 int color, int other);
784
785int
786break_through(int apos, int bpos, int cpos)
787{
788 int color = board[apos];
789 int other = OTHER_COLOR(color);
790
791 int dpos;
792 int epos;
793 int Fpos;
794 int gpos;
795
796 int success = 0;
797 int success2 = 0;
798
799 /* Basic sanity checking. */
800 ASSERT1(IS_STONE(color) , apos);
801 ASSERT1(color == board[bpos], bpos);
802 ASSERT1(color == board[cpos], cpos);
803
804 /* Construct the rest of the points in the pattern. */
805 Fpos = (apos + cpos) / 2; /* F midpoint between a and c. */
806 dpos = apos + bpos - Fpos; /* Use diagonal relation a+b = d+F. */
807 epos = bpos + cpos - Fpos; /* Use diagonal relation b+c = e+F. */
808
809 /* More sanity checking. */
810 ASSERT1(board[dpos] == EMPTY , dpos);
811 ASSERT1(board[epos] == EMPTY , epos);
812
813 /* F might already have been captured. (play_break_through_n() can't
814 * detect this.
815 */
816 if (board[Fpos] == EMPTY)
817 return 0;
818
819 ASSERT1(board[Fpos] == other, Fpos);
820
821 /* First X tries to play at d. */
822 success = break_through_helper(apos, bpos, cpos, dpos, epos, Fpos,
823 color, other);
824 if (success == WIN)
825 return WIN;
826
827 success2 = break_through_helper(cpos, bpos, apos, epos, dpos, Fpos,
828 color, other);
829
830 if (success2 == WIN)
831 return WIN;
832
833 if (success2 == CUT)
834 success = CUT;
835
836 /* If we haven't been lucky yet, we might need to start by
837 * defending F.
838 *
839 * FIXME: The function would probably be considerably faster if we
840 * start by checking whether F needs defense. Beware of ko potential
841 * though.
842 */
843 success2 = 0;
844 if (attack_and_defend(Fpos, NULL, NULL, NULL, &gpos)) {
845 if (trymove(gpos, other, "break_through-A", Fpos)) {
846 /* Now we let O defend his position by playing either d or e.
847 * FIXME: There may be other plausible moves too.
848 */
849 if (trymove(dpos, color, "break_through-B", Fpos)) {
850 /* O connects at d, so X cuts at e. */
851 if (safe_move(epos, other)) {
852 success2 = CUT;
853 if (!board[cpos] || attack(cpos, NULL))
854 success2 = WIN;
855 }
856 popgo();
857 }
858
859 if (success2 > 0 && trymove(epos, color, "break_through-C", Fpos)) {
860 /* O connects at e, so X cuts at d. */
861 if (safe_move(dpos, other)) {
862 /* success2 is already WIN or CUT. */
863 if (board[apos] && !attack(apos, NULL))
864 success2 = CUT;
865 }
866 else
867 success2 = 0;
868 popgo();
869 }
870 popgo();
871 }
872 }
873
874 if (success2 > 0)
875 return success2;
876
877 return success;
878}
879
880/* Helper function for break_through(). Since we can symmetrically
881 * start by cutting at d or e, we use the same code for both attacks,
882 * simply switching positions between the two calls.
883 */
884static int
885break_through_helper(int apos, int bpos, int cpos,
886 int dpos, int epos, int Fpos,
887 int color, int other)
888{
889 int success = 0;
890 int gpos;
891
892 if (trymove(dpos, other, "break_through_helper-A", Fpos)) {
893 /* If F can be attacked we can't start in this way. */
894 if (!attack(Fpos, NULL)) {
895 /* If d is safe too, we have at least managed to break through. */
896 if (!attack(dpos, &gpos))
897 success = CUT;
898
899 /* Too bad, d could be attacked. We let O play the attack and
900 * then try to make a second cut at e. But first we must test if
901 * O at e is sufficient to capture d.
902 */
903 else {
904 if (trymove(epos, color, "break_through_helper-E", Fpos)) {
905 if (!board[dpos] || !find_defense(dpos, NULL)) {
906 popgo();
907 popgo();
908 return 0;
909 }
910 popgo();
911 }
912
913 if (gpos == epos) {
914 popgo();
915 return 0;
916 }
917
918 if (trymove(gpos, color, "break_through_helper-F", Fpos)) {
919 if (trymove(epos, other, "break_through_helper-G", Fpos)) {
920 if (!attack(epos, NULL)) {
921 success = CUT;
922 /* Make sure b and c are safe. If not, back up & let O try
923 * to defend in a different way. */
924 if (board[bpos]
925 && board[cpos]
926 && defend_both(bpos, cpos)) {
927 /* Can't do better than CUT. */
928 popgo();
929 popgo();
930 popgo();
931 return CUT;
932 }
933 }
934 else {
935 /* Lost everything. (Note we ignore ko at the moment.) */
936 popgo();
937 popgo();
938 popgo();
939 return 0;
940 }
941 popgo();
942 }
943 else {
944 /* Failed to cut at all. */
945 popgo();
946 popgo();
947 return 0;
948 }
949 popgo();
950 }
951 }
952
953 /* By now, we're sure a cut works, so now we can try
954 * to capture something.
955 */
956 if (!board[apos] || !board[bpos] || !defend_both(apos, bpos))
957 success = WIN;
958 else {
959 /* Both a and b could be defended, or didn't need to be.
960 * Let's see if a move at e is sufficient for O.
961 */
962 int attack_on_b = 0;
963 int attack_on_a = 0;
964
965 if (trymove(epos, color, "break_through_helper-B", Fpos)) {
966 if (attack(bpos, NULL))
967 attack_on_b = 1;
968 else if (attack(apos, NULL))
969 attack_on_a = 1;
970 popgo();
971 }
972
973 /* Let O find a defense and play it. */
974 if (attack_on_a || attack_on_b) {
975 int hpos = NO_MOVE;
976
977 if (((attack_on_a && find_defense(apos, &hpos))
978 || (attack_on_b && find_defense(bpos, &hpos)))
979 && hpos != NO_MOVE
980 && trymove(hpos, color, "break_through_helper-C", Fpos)) {
981 /* Now we make a second cut at e, trying to capture
982 * either b or c.
983 */
984 if (trymove(epos, other, "break_through_helper-D", Fpos)) {
985 if (!board[bpos]
986 || !board[cpos]
987 || !defend_both(bpos, cpos))
988 success = WIN;
989 popgo();
990 }
991 popgo();
992 }
993 else
994 success = WIN; /* This should have been covered by
995 * defend_both(), so probably unnecessary. */
996 }
997 }
998 }
999 popgo();
1000 }
1001
1002 return success;
1003}
1004
1005
1006/* ---------------------------------------------------------------- */
1007/* Threats */
1008/* ---------------------------------------------------------------- */
1009
1010
1011/* Return up to max_threats threats to capture the string at str.
1012 * If the string is directly attackable the number of threats
1013 * is reported to be 0.
1014 *
1015 * NOTE: You can call attack_threats with moves[] and codes[]
1016 * already partly filled in. So if you want to get the
1017 * threats from scratch, you have to set them to 0
1018 * yourself.
1019 *
1020 * FIXME: Shall we report upgrades, like we can capture in ko but
1021 * have a threat to capture unconditionally?
1022 */
1023
1024int
1025attack_threats(int str, int max_points, int moves[], int codes[])
1026{
1027 int other;
1028 int num_threats;
1029 int liberties;
1030 int libs[MAXLIBS];
1031 int num_adj;
1032 int adjs[MAXCHAIN];
1033 int k;
1034 int l;
1035 int r;
1036
1037 ASSERT1(IS_STONE(board[str]), str);
1038 other = OTHER_COLOR(board[str]);
1039
1040 /* Only handle strings with no way to capture immediately.
1041 * For now, we treat ko the same as unconditionally. */
1042 if (attack(str, NULL) != 0)
1043 return 0;
1044
1045 /* This test would seem to be unnecessary since we only threaten
1046 * strings with attack_code == 0, but it turns out that single
1047 * stones with one liberty that can be captured, but come to
1048 * live again in a snap-back get attack_code == 0.
1049 *
1050 * The test against 6 liberties is just an optimization.
1051 */
1052 liberties = findlib(str, MAXLIBS, libs);
1053 if (liberties > 1 && liberties < 6) {
1054 for (k = 0; k < liberties; k++) {
1055 int aa = libs[k];
1056
1057 /* Try to threaten on the liberty. */
1058 if (trymove(aa, other, "attack_threats-A", str)) {
1059 int acode = attack(str, NULL);
1060 if (acode != 0)
1061 movelist_change_point(aa, acode, max_points, moves, codes);
1062 popgo();
1063 }
1064
1065 /* Try to threaten on second order liberties. */
1066 for (l = 0; l < 4; l++) {
1067 int bb = libs[k] + delta[l];
1068
1069 if (!ON_BOARD(bb)
1070 || IS_STONE(board[bb])
1071 || liberty_of_string(bb, str))
1072 continue;
1073
1074 if (trymove(bb, other, "attack_threats-B", str)) {
1075 int acode = attack(str, NULL);
1076 if (acode != 0)
1077 movelist_change_point(bb, acode, max_points, moves, codes);
1078 popgo();
1079 }
1080 }
1081 }
1082 }
1083
1084 /* Threaten to attack by saving weak neighbors. */
1085 num_adj = chainlinks(str, adjs);
1086 for (k = 0; k < num_adj; k++) {
1087 int bb;
1088 int dd; /* Defense point of weak neighbor. */
1089 int acode;
1090 int dcode;
1091
1092 attack_and_defend(adjs[k], &acode, NULL, &dcode, &dd);
1093 if (acode == 0 || dcode == 0)
1094 continue;
1095
1096 /* The strange code using r == -1 below is only avoid duplication
1097 * of the code starting with "if (trymove..)" below.
1098 * If r == -1 and stackp == 0 then use the defense point what we got from
1099 * attack_and_defend above. Otherwise step through all defense points.
1100 */
1101 for (r = -1; r < max_points; r++) {
1102 if (stackp == 0) {
1103 if (r == -1)
1104 continue;
1105 if (worm[adjs[k]].defense_codes[r] == 0)
1106 break;
1107 bb = worm[adjs[k]].defense_points[r];
1108 }
1109 else {
1110 if (r == -1)
1111 bb = dd;
1112 else
1113 break;
1114 }
1115
1116 /* Test the move and see if it is a threat. */
1117 if (trymove(bb, other, "attack_threats-C", str)) {
1118 if (board[str] == EMPTY)
1119 acode = WIN;
1120 else
1121 acode = attack(str, NULL);
1122 if (acode != 0)
1123 movelist_change_point(bb, acode, max_points, moves, codes);
1124 popgo();
1125 }
1126 }
1127 }
1128
1129 /* Return actual number of threats found regardless of attack code. */
1130 if (codes[max_points - 1] > 0)
1131 return max_points;
1132 for (num_threats = 0; num_threats < max_points; num_threats++)
1133 if (codes[num_threats] == 0)
1134 break;
1135 return num_threats;
1136}
1137
1138
1139/* ================================================================ */
1140/* Defensive functions */
1141/* ================================================================ */
1142
1143
1144/* Like find_defense, but takes the komaster argument. If the
1145 * opponent is reading functions will not try
1146 * to take ko.
1147 */
1148
1149static int
1150do_find_defense(int str, int *move)
1151{
1152 int xpos = NO_MOVE;
1153 int dcode = 0;
1154 int liberties;
1155 int retval;
1156
1157 SETUP_TRACE_INFO("find_defense", str);
1158
1159 /* We first check if the number of liberties is larger than four. In
1160 * that case we don't cache the result and to avoid needlessly
1161 * storing the position in the hash table, we must do this test
1162 * before we look for cached results.
1163 */
1164 str = find_origin(str);
1165 liberties = countlib(str);
1166
1167 if (liberties > 4
1168 || (liberties == 4 && stackp > fourlib_depth)
1169 || (liberties == 3 && stackp > depth)) {
1170 /* No need to cache the result in these cases. */
1171 SGFTRACE(0, WIN, "too many liberties or stackp > depth");
1172 if (move)
1173 *move = 0;
1174 return WIN;
1175 }
1176
1177 /* Set "killer move" up. This move (if set) was successful in
1178 * another variation, so it is reasonable to try it now. However,
1179 * we only do this if the string has at least 3 liberties -
1180 * otherwise the situation changes too much from variation to
1181 * variation.
1182 */
1183 if (liberties > 2 && move)
1184 xpos = *move;
1185
1186 if (stackp <= depth
1187 && tt_get(&ttable, FIND_DEFENSE, str, NO_MOVE, depth - stackp, NULL,
1188 &retval, NULL, &xpos) == 2) {
1189 /* Note that if return value is 1 (too small depth), the move will
1190 * still be used for move ordering.
1191 */
1192 TRACE_CACHED_RESULT(retval, xpos);
1193 SGFTRACE(xpos, retval, "cached");
1194 if (move)
1195 *move = xpos;
1196 return retval;
1197 }
1198
1199 if (liberties == 1)
1200 dcode = defend1(str, &xpos);
1201 else if (liberties == 2)
1202 dcode = defend2(str, &xpos);
1203 else if (liberties == 3)
1204 dcode = defend3(str, &xpos);
1205 else if (liberties == 4)
1206 dcode = defend4(str, &xpos);
1207
1208 if (dcode) {
1209 READ_RETURN(FIND_DEFENSE, str, depth - stackp, move, xpos, dcode);
1210 }
1211
1212 READ_RETURN0(FIND_DEFENSE, str, depth - stackp);
1213}
1214
1215
1216/* Determine if a `move' by `color' allows under-the-stones tesuji
1217 * a.k.a. "big snapback". Here is an example:
1218 *
1219 * |XXXX...
1220 * |XXOOXXX
1221 * |OOOXOOX
1222 * |..O*OOX
1223 * +-------
1224 *
1225 * Even though the move at '*' allows black to capture four white
1226 * stones, white can later recapture black stones and create a second
1227 * eye. This is very similar to a snapback.
1228 *
1229 * This function returns true if a move creates a string of with two
1230 * liberties, which can, however, be instantly recaptured by opponent.
1231 * It is actually not required that the move captures something. If
1232 * the caller needs captures, it should check for them itself.
1233 */
1234static int
1235allows_under_the_stones_tesuji(int move, int color)
1236{
1237 int result = 0;
1238 SGFTree *save_sgf_dumptree;
1239 int save_count_variations;
1240
1241 if (accuratelib(move, color, 3, NULL) != 2)
1242 return 0;
1243
1244 save_sgf_dumptree = sgf_dumptree;
1245 save_count_variations = count_variations;
1246
1247 sgf_dumptree = NULL;
1248 count_variations = 0;
1249
1250 if (trymove(move, color, "allows_under_the_stones_tesuji", NO_MOVE)) {
1251 int libs[2];
1252
1253 findlib(move, 2, libs);
1254 if ((!is_self_atari(libs[0], color)
1255 && accuratelib(libs[1], OTHER_COLOR(color), 3, NULL) <= 2)
1256 || (!is_self_atari(libs[1], color)
1257 && accuratelib(libs[0], OTHER_COLOR(color), 3, NULL) <= 2))
1258 result = 1;
1259
1260 popgo();
1261 }
1262
1263 sgf_dumptree = save_sgf_dumptree;
1264 count_variations = save_count_variations;
1265
1266 return result;
1267}
1268
1269
1270/* Called by the defendN functions. Don't think too much if there's
1271 * an easy way to get enough liberties.
1272 */
1273static int
1274fast_defense(int str, int liberties, int *libs, int *move)
1275{
1276 int color = board[str];
1277 int j, k, l;
1278 int goal_liberties = (stackp < fourlib_depth ? 5 : 4);
1279 int adj, adjs[MAXCHAIN];
1280
1281 /* We would like to initialize liberty_mark to -1, but some
1282 * compilers warn, quite correctly, that -1 is not an unsigned
1283 * number.
1284 */
1285 static unsigned liberty_mark = ~0U;
1286 static unsigned lm[BOARDMAX];
1287
1288 ASSERT1(libs != NULL, str);
1289 ASSERT1(move != NULL, str);
1290
1291 for (k = 0; k < liberties; k++) {
1292 /* accuratelib() seems to be more efficient than fastlib() here,
1293 * probably because it catches more cases.
1294 */
1295 if (accuratelib(libs[k], color, goal_liberties, NULL) >= goal_liberties) {
1296 *move = libs[k];
1297 return 1;
1298 }
1299 }
1300
1301 /* Check the cases where an opponent neighbor string is in
1302 * atari.
1303 */
1304 adj = chainlinks2(str, adjs, 1);
1305 for (j = 0; j < adj; j++) {
1306 int lib;
1307 int missing = goal_liberties - liberties;
1308 int total = 0;
1309 int adj2, adjs2[MAXCHAIN];
1310 int alib, alibs[MAXLIBS];
1311 int num_adjacent_stones;
1312
1313 findlib(adjs[j], 1, &lib);
1314 /* We aren't interested in ko (at this stage). And playing
1315 * our own last liberty to capture is prone to snapbacks,
1316 * so better let the 'normal' reading routines do the job.
1317 */
1318 if ((liberties == 1 && lib == libs[0]
1319 && countstones(adjs[j]) <= 2)
1320 || is_ko(lib, color, NULL))
1321 continue;
1322
1323 /* Would the capture already gain enough liberties ?
1324 * No need to test the case if the move is one of our liberties,
1325 * it has already been done in the first loop of this function.
1326 */
1327 num_adjacent_stones = count_adjacent_stones(adjs[j], str, missing);
1328 if (!liberty_of_string(lib, str)
1329 && num_adjacent_stones >= missing) {
1330 *move = lib;
1331 return 1;
1332 }
1333 ASSERT1(num_adjacent_stones >= 1, str);
1334
1335 /* What is the total number of liberties of the friendly strings around
1336 * the lunch?
1337 */
1338 if (++liberty_mark == 0) {
1339 memset(lm, 0, sizeof(lm));
1340 liberty_mark++;
1341 }
1342 /* Loop over all neighbors of the lunch. */
1343 adj2 = chainlinks(adjs[j], adjs2);
1344 for (k = 0; k < adj2; k++) {
1345 /* Loop over all liberties of the neighbor. */
1346 alib = findlib(adjs2[k], MAXLIBS, alibs);
1347 for (l = 0; l < alib; l++) {
1348 if (lm[alibs[l]] != liberty_mark) {
1349 lm[alibs[l]] = liberty_mark;
1350 total++;
1351 }
1352 }
1353 }
1354
1355 /* The captured string is treated as common liberties, and
1356 * some adjustements are made :
1357 * - we're adding a stone for capturing the lunch (-1)
1358 * - opponent might be able to remove a liberty (-1)
1359 * - and possibly force us to connect (-1)
1360 * - reduce us by one more liberty with a throw-in; this
1361 * is only possible if there is only one adjacent stone in the
1362 * lunch to the string (-1)
1363 * Probably there are more damezumari-type cases, but as a heuristic,
1364 * it seems good enough.
1365 */
1366 total += countstones(adjs[j]) - 2;
1367 if (lm[lib] == liberty_mark)
1368 total--;
1369 if (num_adjacent_stones == 1)
1370 total--;
1371
1372 if (total >= goal_liberties) {
1373 /* One case when this code can give a false defense is an
1374 * under-the-stones tesuji or "big snapback." See reading:199
1375 * for an example. While this position is probably very rare,
1376 * it is nice to make GNU Go understand "neat" tesujis.
1377 */
1378 if (liberties == 1 && lib == libs[0]
1379 && allows_under_the_stones_tesuji(lib, color)) {
1380 /* This is a bad "fast defense". */
1381 continue;
1382 }
1383
1384 *move = lib;
1385 return 1;
1386 }
1387 }
1388
1389 return 0;
1390}
1391
1392/* If str points to a string with exactly one liberty, defend1
1393 * determines whether it can be saved by extending or capturing
1394 * a boundary chain having one liberty. The function returns WIN if the string
1395 * can be saved, otherwise 0. It returns KO_A or KO_B if it can be saved,
1396 * conditioned on ko. Returns KO_A if it can be saved provided (color) is
1397 * willing to ignore any ko threat. Returns KO_B if it can be saved if (color)
1398 * has a ko threat which must be answered.
1399 *
1400 * The pair defend1-attack2 call each other recursively to
1401 * read situations such as ladders. They read all ladders to the end.
1402 * If the reading ply (stackp) is deeper than the deep-reading cutoff
1403 * parameter depth, whose default value DEPTH is defined in gnugo.h, then a
1404 * string is assumed alive if it can get 3 liberties. When
1405 * fourlib_depth < stackp < depth, a string is considered alive if it can get
1406 * four liberties. When stackp < fourlib_depth, it is considered alive
1407 * if it can get 5 liberties.
1408 * */
1409
1410static int
1411defend1(int str, int *move)
1412{
1413 int color = board[str];
1414 int other = OTHER_COLOR(color);
1415 int xpos;
1416 int lib;
1417 struct reading_moves moves;
1418 int savemove = 0;
1419 int savecode = 0;
1420 int liberties;
1421 int k;
1422
1423 SETUP_TRACE_INFO("defend1", str);
1424 reading_node_counter++;
1425
1426 ASSERT1(IS_STONE(board[str]), str);
1427 ASSERT1(countlib(str) == 1, str);
1428
1429 /* lib will be the liberty of the string. */
1430 liberties = findlib(str, 1, &lib);
1431 ASSERT1(liberties == 1, str);
1432
1433 if (fast_defense(str, liberties, &lib, &xpos))
1434 RETURN_RESULT(WIN, xpos, move, "fast defense");
1435
1436 /* Collect moves to try in the first batch.
1437 * 1. First order liberty.
1438 * 2. Chain breaking moves.
1439 * 3. Moves to set up a snapback.
1440 */
1441 moves.pos[0] = lib;
1442 moves.score[0] = 0;
1443 moves.message[0] = "liberty";
1444 moves.num = 1;
1445 moves.num_tried = 0;
1446
1447 break_chain_moves(str, &moves);
1448 set_up_snapback_moves(str, lib, &moves);
1449
1450 order_moves(str, &moves, color, read_function_name, *move);
1451 DEFEND_TRY_MOVES(0, NULL);
1452
1453 /* If the string is a single stone and a capture would give a ko,
1454 * try to defend it with ko by backfilling.
1455 *
1456 * FIXME: What is an example of this? Is it correct that the
1457 * return value is WIN and not KO_A or KO_B?
1458 */
1459 if (stackp <= backfill_depth
1460 && countstones(str) == 1
1461 && is_ko(lib, other, NULL)) {
1462 int libs2[6];
1463 liberties = approxlib(lib, color, 6, libs2);
1464 if (liberties <= 5) {
1465 for (k = 0; k < liberties; k++) {
1466 int apos = libs2[k];
1467 if ((liberties == 1 || !is_self_atari(apos, other))
1468 && trymove(apos, color, "defend1-C", str)) {
1469 int acode = do_attack(str, NULL);
1470 popgo();
1471 CHECK_RESULT(savecode, savemove, acode, apos, move, "backfilling");
1472 }
1473 }
1474 }
1475 }
1476
1477 RETURN_RESULT(savecode, savemove, move, "saved move");
1478}
1479
1480
1481
1482/* If str points to a group with two liberties, defend2 determines
1483 * whether the group can be saved by extending, or by capturing part of
1484 * its surrounding chain. A group is considered safe if either part of
1485 * the surrounding chain may be captured, or if it can get 3
1486 * liberties. It is presumed that the opponent could kill if tenuki.
1487 * If both extensions work, it prefers the one which maximizes
1488 * liberties.
1489 *
1490 * *move returns the move to save the stones.
1491 */
1492
1493static int
1494defend2(int str, int *move)
1495{
1496 int color, other;
1497 int xpos = NO_MOVE;
1498 int liberties;
1499 int libs[2];
1500 int liberties2;
1501 int libs2[6];
1502 struct reading_moves moves;
1503 int savemove = 0;
1504 int savecode = 0;
1505 int k;
1506 int r;
1507 int suggest_move = NO_MOVE;
1508 int string_size;
1509 int be_aggressive;
1510
1511 SETUP_TRACE_INFO("defend2", str);
1512 reading_node_counter++;
1513
1514 color = board[str];
1515 other = OTHER_COLOR(color);
1516
1517 ASSERT1(IS_STONE(board[str]), str);
1518 ASSERT1(countlib(str) == 2, str);
1519
1520 liberties = findlib(str, 2, libs);
1521
1522 if (fast_defense(str, liberties, libs, &xpos))
1523 RETURN_RESULT(WIN, xpos, move, "fast defense");
1524
1525 /* Collect moves to try in the first batch.
1526 * 1. First order liberties.
1527 * 2. Chain breaking moves.
1528 * 3. Second order liberties moving up from first line to second.
1529 * 4. Edge clamps.
1530 */
1531 moves.num = 0;
1532 moves.num_tried = 0;
1533
1534 /* We don't want to play self-atari liberties, unless the string is a
1535 * single stone (in which case it might be a snapback move). Sacrifices
1536 * might be good moves, but not in tactical reading.
1537 */
1538 string_size = countstones(str);
1539 if (string_size == 1 || !is_self_atari(libs[0], color))
1540 ADD_CANDIDATE_MOVE(libs[0], 0, moves, "liberty");
1541 if (string_size == 1 || !is_self_atari(libs[1], color))
1542 ADD_CANDIDATE_MOVE(libs[1], 0, moves, "liberty");
1543
1544 break_chain_moves(str, &moves);
1545 break_chain2_efficient_moves(str, &moves);
1546 propose_edge_moves(str, libs, liberties, &moves, color);
1547 edge_clamp_moves(str, &moves);
1548
1549 if (stackp <= depth) {
1550 for (k = 0; k < liberties; k++)
1551 special_rescue_moves(str, libs[k], &moves);
1552 bamboo_rescue_moves(str, liberties, libs, &moves);
1553 }
1554
1555 if (stackp <= backfill_depth)
1556 special_rescue2_moves(str, libs, &moves);
1557
1558 order_moves(str, &moves, color, read_function_name, *move);
1559 DEFEND_TRY_MOVES(0, &suggest_move);
1560
1561 /* Look for backfilling moves. */
1562 for (k = 0; k < liberties; k++) {
1563 if (is_self_atari(libs[k], other)) {
1564 liberties2 = approxlib(libs[k], color, 6, libs2);
1565 /* Note: liberties2 must be smaller than 5, otherwise libs[k] had been
1566 * a direct defense.
1567 */
1568 for (r = 0; r < liberties2; r++) {
1569 xpos = libs2[r];
1570 /* If the newly placed stone would be in atari, but not a single
1571 * stone, we don't even try.
1572 */
1573 if (!is_self_atari(xpos, color)
1574 && has_neighbor(xpos, color))
1575 ADD_CANDIDATE_MOVE(xpos, 0, moves, "backfill-A");
1576 }
1577 }
1578
1579 liberties2 = approxlib(libs[k], other, 3, libs2);
1580 if (liberties2 <= 2) {
1581 for (r = 0; r < liberties2; r++) {
1582 xpos = libs2[r];
1583 if (!is_self_atari(xpos, color))
1584 ADD_CANDIDATE_MOVE(xpos, 0, moves, "backfill-B");
1585 }
1586 }
1587 }
1588
1589 special_rescue4_moves(str, libs, &moves);
1590
1591 /* Only order and test the new set of moves. */
1592 order_moves(str, &moves, color, read_function_name, *move);
1593 DEFEND_TRY_MOVES(0, &suggest_move);
1594
1595 /* If we haven't found any useful moves in first batches, be more
1596 * aggressive in break_chain[23]_moves().
1597 */
1598 be_aggressive = (moves.num == 0);
1599
1600 if (stackp <= superstring_depth)
1601 superstring_break_chain_moves(str, 4, &moves);
1602
1603 /* If nothing else works, we try playing a liberty of the
1604 * super_string.
1605 */
1606 if (stackp <= superstring_depth) {
1607 superstring_moves(str, &moves, 3, 0);
1608 squeeze_moves(str, &moves);
1609 }
1610
1611 break_chain2_defense_moves(str, &moves, be_aggressive);
1612
1613 if (stackp <= backfill_depth)
1614 special_rescue5_moves(str, libs, &moves);
1615
1616 if (stackp <= break_chain_depth
1617 || (be_aggressive && stackp <= backfill_depth))
1618 break_chain3_moves(str, &moves, be_aggressive);
1619
1620 if (be_aggressive && stackp <= backfill_depth)
1621 break_chain4_moves(str, &moves, be_aggressive);
1622
1623 /* Only order and test the new set of moves. */
1624 order_moves(str, &moves, color, read_function_name, *move);
1625 DEFEND_TRY_MOVES(0, &suggest_move);
1626
1627 RETURN_RESULT(savecode, savemove, move, "saved move");
1628}
1629
1630
1631/* defend3(str, *move) attempts to find a move rescuing the
1632 * string at (str) with 3 liberties. If such a move can be found,
1633 * it returns true and the saving move in *move.
1634 */
1635
1636static int
1637defend3(int str, int *move)
1638{
1639 int color;
1640 int xpos = NO_MOVE;
1641 int liberties;
1642 int libs[3];
1643 struct reading_moves moves;
1644 int savemove = 0;
1645 int savecode = 0;
1646 int k;
1647 int suggest_move = NO_MOVE;
1648
1649 SETUP_TRACE_INFO("defend3", str);
1650 reading_node_counter++;
1651
1652 color = board[str];
1653
1654 ASSERT1(IS_STONE(board[str]), str);
1655 ASSERT1(countlib(str) == 3, str);
1656
1657 liberties = findlib(str, 3, libs);
1658
1659 if (fast_defense(str, liberties, libs, &xpos))
1660 RETURN_RESULT(WIN, xpos, move, "fast defense");
1661
1662 /* Collect moves to try in the first batch.
1663 * 1. First order liberties.
1664 * 2. Chain breaking moves.
1665 * 3. Second order liberties moving up from first line to second.
1666 * 4. Edge clamps.
1667 */
1668 for (k = 0; k < liberties; k++) {
1669 moves.pos[k] = libs[k];
1670 moves.score[k] = 0;
1671 moves.message[k] = "liberty";
1672 }
1673
1674 moves.num = liberties;
1675 moves.num_tried = 0;
1676
1677 break_chain_moves(str, &moves);
1678 break_chain2_efficient_moves(str, &moves);
1679 propose_edge_moves(str, libs, liberties, &moves, color);
1680 edge_clamp_moves(str, &moves);
1681
1682 if (stackp <= backfill2_depth)
1683 hane_rescue_moves(str, libs, &moves);
1684
1685 order_moves(str, &moves, color, read_function_name, *move);
1686 DEFEND_TRY_MOVES(1, &suggest_move);
1687
1688 /* This looks a little too expensive. */
1689#if 0
1690 /* Look for backfilling moves. */
1691 if (stackp <= backfill_depth) {
1692 int other = OTHER_COLOR(color);
1693 int liberties2;
1694 int libs2[6];
1695 int r;
1696 int s;
1697 for (k = 0; k < liberties; k++) {
1698 if (is_self_atari(libs[k], other)) {
1699 liberties2 = approxlib(libs[k], color, 6, libs2);
1700 for (r = 0; r < liberties2; r++) {
1701 xpos = libs2[r];
1702 /* Don't reconsider previously tested moves. */
1703 for (s = 0; s < moves.num; s++)
1704 if (xpos == moves.pos[s])
1705 break;
1706 if (s < moves.num)
1707 continue;
1708
1709 if (trymove(xpos, color, "defend3-D", str)) {
1710 int acode;
1711 /* If the newly placed stone is in atari, we give up
1712 * without fight.
1713 */
1714 if (countlib(xpos) == 1)
1715 acode = WIN;
1716 else
1717 acode = do_attack(str, NULL);
1718
1719 popgo();
1720 CHECK_RESULT(savecode, savemove, acode, xpos, move,
1721 "backfill effective");
1722 }
1723 }
1724 }
1725 else {
1726 liberties2 = approxlib(libs[k], other, 3, libs2);
1727 if (liberties2 <= 3) {
1728 for (r = 0; r < liberties2; r++) {
1729 xpos = libs2[r];
1730 /* Don't reconsider previously tested moves. */
1731 for (s = 0; s < moves.num; s++)
1732 if (xpos == moves.pos[s])
1733 break;
1734 if (s < moves.num)
1735 continue;
1736
1737 if (!is_self_atari(xpos, color)
1738 && trymove(xpos, color, "defend2-G", str)) {
1739 int acode = do_attack(str, NULL);
1740 popgo();
1741 CHECK_RESULT(savecode, savemove, acode, xpos, move
1742 "backfill effective");
1743 }
1744 }
1745 }
1746 }
1747 }
1748 }
1749#endif
1750
1751 /* If nothing else works, try to defend with second order liberties. */
1752
1753 if (stackp <= backfill_depth)
1754 special_rescue3_moves(str, libs, &moves);
1755
1756 if (stackp <= depth) {
1757 for (k = 0; k < liberties; k++)
1758 special_rescue_moves(str, libs[k], &moves);
1759 bamboo_rescue_moves(str, liberties, libs, &moves);
1760 }
1761
1762 if (get_level() >= 8 && stackp <= backfill2_depth)
1763 superstring_break_chain_moves(str, 4, &moves);
1764
1765 if (stackp <= break_chain_depth)
1766 break_chain2_defense_moves(str, &moves, 0);
1767
1768 if (stackp <= backfill_depth) {
1769 special_rescue5_moves(str, libs, &moves);
1770 special_rescue6_moves(str, libs, &moves);
1771 }
1772
1773 /* Only order and test the new set of moves. */
1774 order_moves(str, &moves, color, read_function_name, *move);
1775 DEFEND_TRY_MOVES(1, &suggest_move);
1776
1777 /* If nothing else works, we try playing a liberty of the
1778 * super_string.
1779 */
1780 if (get_level() >= 8 && stackp <= backfill2_depth) {
1781 superstring_moves(str, &moves, 3, 0);
1782 squeeze_moves(str, &moves);
1783 }
1784
1785 if (stackp <= break_chain_depth)
1786 break_chain3_moves(str, &moves, 0);
1787
1788 /* Only order and test the new set of moves. */
1789 order_moves(str, &moves, color, read_function_name, *move);
1790 DEFEND_TRY_MOVES(1, &suggest_move);
1791
1792 RETURN_RESULT(savecode, savemove, move, "saved move");
1793}
1794
1795
1796/* defend4(str, *move) attempts to find a move rescuing the
1797 * string at (str) with 4 liberties. If such a move can be found,
1798 * it returns true, and if the pointer move is not NULL,
1799 * then it returns the saving move in *move.
1800 */
1801
1802static int
1803defend4(int str, int *move)
1804{
1805 int color;
1806 int xpos = NO_MOVE;
1807 int liberties;
1808 int libs[4];
1809 struct reading_moves moves;
1810 int savemove = 0;
1811 int savecode = 0;
1812 int k;
1813 int suggest_move = NO_MOVE;
1814
1815 SETUP_TRACE_INFO("defend4", str);
1816 reading_node_counter++;
1817
1818 color = board[str];
1819
1820 ASSERT1(IS_STONE(board[str]), str);
1821 ASSERT1(countlib(str) == 4, str);
1822
1823 liberties = findlib(str, 4, libs);
1824
1825 if (fast_defense(str, liberties, libs, &xpos))
1826 RETURN_RESULT(WIN, xpos, move, "fast defense");
1827
1828 /* Collect moves to try in the first batch.
1829 * 1. First order liberties.
1830 * 2. Chain breaking moves.
1831 */
1832 for (k = 0; k < liberties; k++) {
1833 moves.pos[k] = libs[k];
1834 moves.score[k] = 0;
1835 moves.message[k] = "liberty";
1836 }
1837
1838 moves.num = liberties;
1839 moves.num_tried = 0;
1840
1841 break_chain_moves(str, &moves);
1842 break_chain2_efficient_moves(str, &moves);
1843
1844 if (stackp <= backfill_depth) {
1845 break_chain2_defense_moves(str, &moves, 0);
1846 break_chain3_moves(str, &moves, 0);
1847 break_chain4_moves(str, &moves, 0);
1848#if 0
1849 hane_rescue_moves(str, libs, &moves);
1850#endif
1851 if (stackp <= superstring_depth)
1852 superstring_moves(str, &moves, 4, 0);
1853 squeeze_moves(str, &moves);
1854 }
1855
1856 order_moves(str, &moves, color, read_function_name, *move);
1857 DEFEND_TRY_MOVES(1, &suggest_move);
1858
1859 if (stackp <= depth) {
1860 for (k = 0; k < liberties; k++)
1861 special_rescue_moves(str, libs[k], &moves);
1862 bamboo_rescue_moves(str, liberties, libs, &moves);
1863 }
1864
1865 order_moves(str, &moves, color, read_function_name, *move);
1866 DEFEND_TRY_MOVES(1, &suggest_move);
1867
1868 RETURN_RESULT(savecode, savemove, move, "saved move");
1869}
1870
1871
1872/*
1873 * special_rescue_moves(str, lib, *move) is called with (str) a
1874 * string having a liberty at (lib).
1875 *
1876 * This adds moves on a second order liberty to the list of candidate
1877 * moves in the struct *moves; e.g. in shapes like:
1878 *
1879 * . O O X.XXO
1880 * O.* or ..* or O.* or XOOXO
1881 * O O O ...*.
1882 * -----
1883 *
1884 * This will occasionally save a string where no other move will. To
1885 * reduce the branching caused by these moves, we require that the
1886 * opponent can be trivially captured when trying to intercept on the
1887 * corresponding first order liberty.
1888 */
1889
1890static void
1891special_rescue_moves(int str, int lib, struct reading_moves *moves)
1892{
1893 int color = board[str];
1894 int other = OTHER_COLOR(color);
1895 int otherlib;
1896 int k;
1897
1898 /* Use approxlib() to test for trivial capture. */
1899 otherlib = approxlib(lib, other, 3, NULL);
1900 if (otherlib > 2)
1901 return;
1902
1903 /* Loop over the four neighbours of the liberty, (lib + d). */
1904 for (k = 0; k < 4; k++) {
1905 int d = delta[k];
1906 if (board[lib + d] == EMPTY) {
1907
1908 /* Don't play into a self atari unless we have a potential snapback. */
1909 if (is_self_atari(lib + d, color) && otherlib > 1)
1910 continue;
1911
1912 /* Be more demanding when the string has four liberties. (Mostly
1913 * because attack4() otherwise would need more move generators.)
1914 * More precisely we require not only the first order liberty to
1915 * become a self atari for the opponent but also one more of the
1916 * neighbors of the proposed move. See reading:144 for a
1917 * position where we otherwise would try to defend at D9 and
1918 * attack4() then lacks move generators to stop black from
1919 * continuing towards the top left corner.
1920 */
1921 if (countlib(str) > 3) {
1922 int r;
1923 int number_protected = 0;
1924
1925 for (r = 0; r < 4; r++) {
1926 if (board[lib + d + delta[r]] == EMPTY
1927 && approxlib(lib + d + delta[r], other, 3, NULL) < 3)
1928 number_protected++;
1929 if (number_protected == 2)
1930 break;
1931 }
1932
1933 if (number_protected < 2)
1934 continue;
1935 }
1936
1937 ADD_CANDIDATE_MOVE(lib + d, 0, *moves, "special_rescue");
1938 }
1939 }
1940}
1941
1942
1943/*
1944 * In situations like
1945 *
1946 * XXXXXO
1947 * XO.*.O
1948 * XO.O.O
1949 * XXXXXO
1950 *
1951 * playing at * is the correct rescue move, although the opponent cannot
1952 * be captured at the respective first-order liberty.
1953 */
1954static void
1955bamboo_rescue_moves(int str, int num_libs, int libs[],
1956 struct reading_moves *moves)
1957{
1958 int color = board[str];
1959 int l1, l2;
1960
1961 for (l1 = 0; l1 < num_libs; l1++)
1962 for (l2 = 0; l2 < num_libs; l2++) {
1963 if (l1 == l2)
1964 continue;
1965
1966 if (libs[l1] == WEST(libs[l2]) || libs[l1] == EAST(libs[l2])) {
1967 if (board[SOUTH(libs[l1])] == EMPTY
1968 && board[SOUTH(libs[l2])] == color
1969 && !is_self_atari(SOUTH(libs[l1]), color))
1970 ADD_CANDIDATE_MOVE(SOUTH(libs[l1]), 0, *moves, "bamboo_rescue");
1971 if (board[NORTH(libs[l1])] == EMPTY
1972 && board[NORTH(libs[l2])] == color
1973 && !is_self_atari(NORTH(libs[l1]), color))
1974 ADD_CANDIDATE_MOVE(NORTH(libs[l1]), 0, *moves, "bamboo_rescue");
1975 }
1976 else if (libs[l1] == NORTH(libs[l2]) || libs[l1] == SOUTH(libs[l2])) {
1977 if (board[WEST(libs[l1])] == EMPTY
1978 && board[WEST(libs[l2])] == color
1979 && !is_self_atari(WEST(libs[l1]), color))
1980 ADD_CANDIDATE_MOVE(WEST(libs[l1]), 0, *moves, "bamboo_rescue");
1981 if (board[EAST(libs[l1])] == EMPTY
1982 && board[EAST(libs[l2])] == color
1983 && !is_self_atari(EAST(libs[l1]), color))
1984 ADD_CANDIDATE_MOVE(EAST(libs[l1]), 0, *moves, "bamboo_rescue");
1985 }
1986 }
1987}
1988
1989
1990/* In a situation like this:
1991 *
1992 * OOXXXX the following code can find the
1993 * .OXOOX defensive move at 'c'.
1994 * .cO.OX
1995 * .X.OOX
1996 * ------
1997 *
1998 * OOXXXX It also can find more general moves like 'c' here.
1999 * .OXOOX
2000 * cXO.OX
2001 * ...OOX
2002 * ------
2003 */
2004static void
2005special_rescue2_moves(int str, int libs[2], struct reading_moves *moves)
2006{
2007 int color = board[str];
2008 int other = OTHER_COLOR(color);
2009 int newlibs[4];
2010 int liberties;
2011 int newstr;
2012 int k, r, s;
2013
2014 for (r = 0; r < 2; r++) {
2015 /* Let alib be one of the liberties and require it to be suicide
2016 * for the opponent.
2017 */
2018 int alib = libs[r];
2019 if (!is_suicide(alib, other))
2020 continue;
2021
2022 for (k = 0; k < 4; k++) {
2023 if (board[alib + delta[k]] == color
2024 && !same_string(alib + delta[k], str)) {
2025 newstr = alib + delta[k];
2026 liberties = findlib(newstr, 4, newlibs);
2027
2028 for (s = 0; s < liberties && s < 4; s++) {
2029 if (!is_self_atari(newlibs[s], color))
2030 ADD_CANDIDATE_MOVE(newlibs[s], 0, *moves, "special_rescue2");
2031 }
2032 break_chain_moves(newstr, moves);
2033 break_chain2_efficient_moves(newstr, moves);
2034 edge_clamp_moves(newstr, moves);
2035 }
2036 }
2037 }
2038}
2039
2040
2041/* In a situation like this:
2042 *
2043 * ...X.XXO
2044 * .XXXOOXO
2045 * XXOO.OXO the following code can find the
2046 * .O..X.*. defensive move at '*'.
2047 * --------
2048 *
2049 * OXO cde
2050 * .*. afg
2051 * --- b--
2052 */
2053static void
2054special_rescue3_moves(int str, int libs[3], struct reading_moves *moves)
2055{
2056 int color = board[str];
2057 int other = OTHER_COLOR(color);
2058 int apos, bpos, cpos, dpos, epos, fpos, gpos;
2059 int k, l, r;
2060
2061 ASSERT1(countlib(str) == 3, str);
2062
2063 for (r = 0; r < 3; r++) {
2064 /* Let (apos) be one of the three liberties. */
2065 apos = libs[r];
2066 /* Try to find the configuration above. */
2067 for (k = 0; k < 4; k++) {
2068 bpos = apos + delta[k];
2069 if (ON_BOARD(bpos))
2070 continue;
2071
2072 cpos = apos - delta[k];
2073 if (board[cpos] != color)
2074 continue;
2075
2076 if (!same_string(cpos, str))
2077 continue;
2078
2079 for (l = 0; l < 2; l++) {
2080 int normal = delta[(k+1)%4];
2081 if (l == 1)
2082 normal = -normal;
2083
2084 dpos = cpos + normal;
2085 if (board[dpos] != other)
2086 continue;
2087
2088 epos = dpos + normal;
2089 if (board[epos] != color)
2090 continue;
2091
2092 fpos = apos + normal;
2093 if (board[fpos] != EMPTY)
2094 continue;
2095
2096 gpos = fpos + normal;
2097 if (board[gpos] != EMPTY)
2098 continue;
2099
2100 /* Configuration found. Now require an X move at 'a' not
2101 * getting too many liberties.
2102 */
2103
2104 if (approxlib(apos, other, 4, NULL) > 3)
2105 continue;
2106
2107 /* Try to play at (fpos). */
2108 ADD_CANDIDATE_MOVE(fpos, 0, *moves, "special_rescue3");
2109 }
2110 }
2111 }
2112}
2113
2114
2115/* This code can find moves to counter attack moves generated by
2116 * special_attack3_moves(). In case such an attack move has only two
2117 * liberties, this function finds the liberty which is not common with
2118 * the attacked string.
2119 *
2120 * For a typical example, see reading:198 where black L7 is generated
2121 * by special_attack3_moves() and the response at L8 is generated by
2122 * this function.
2123 */
2124
2125static void
2126special_rescue4_moves(int str, int libs[2], struct reading_moves *moves)
2127{
2128 int color = board[str];
2129 int other = OTHER_COLOR(color);
2130 int xpos;
2131 int apos;
2132 int bpos;
2133 int libs2[2];
2134 int k;
2135 int r;
2136
2137 ASSERT1(countlib(str) == 2, str);
2138
2139 for (k = 0; k < 2; k++) {
2140 apos = libs[k];
2141 bpos = libs[1-k];
2142
2143 if (apos == SOUTH(bpos) || apos == NORTH(bpos)) {
2144 if (board[WEST(apos)] == other)
2145 xpos = WEST(apos);
2146 else if (board[EAST(apos)] == other)
2147 xpos = EAST(apos);
2148 else
2149 continue;
2150 }
2151 else if (apos == WEST(bpos) || apos == EAST(bpos)) {
2152 if (board[SOUTH(apos)] == other)
2153 xpos = SOUTH(apos);
2154 else if (board[NORTH(apos)] == other)
2155 xpos = NORTH(apos);
2156 else
2157 continue;
2158 }
2159 else
2160 return; /* Incorrect configuration, give up. */
2161
2162 if (findlib(xpos, 2, libs2) == 2) {
2163 for (r = 0; r < 2; r++)
2164 if (libs2[r] != apos && libs2[r] != bpos
2165 && !is_self_atari(libs2[r], color))
2166 ADD_CANDIDATE_MOVE(libs2[r], 0, *moves, "special_rescue4");
2167 }
2168 }
2169}
2170
2171/* In a situation like this:
2172 *
2173 * .XXXXX
2174 * XX.*OO
2175 * X.OX.. the following code can find the
2176 * ...... defensive move at '*'.
2177 * ------
2178 *
2179 * .* ac
2180 * OX bd
2181 *
2182 * The only requirement is that d has at most as many liberties as b,
2183 * and as the newly placed stone at c.
2184 */
2185static void
2186hane_rescue_moves(int str, int libs[4], struct reading_moves *moves)
2187{
2188 int color = board[str];
2189 int other = OTHER_COLOR(color);
2190 int apos, bpos, cpos, dpos;
2191 int num_libs = countlib(str);
2192 int k, l, r;
2193
2194 ASSERT1(num_libs <= 4, str);
2195
2196 for (r = 0; r < num_libs; r++) {
2197 /* Let (apos) be one of the three liberties. */
2198 apos = libs[r];
2199 /* Try to find the configuration above. */
2200 for (k = 0; k < 4; k++) {
2201 bpos = apos + delta[k];
2202 if (board[bpos] != color)
2203 continue;
2204
2205 if (!same_string(bpos, str))
2206 continue;
2207
2208 for (l = 0; l < 2; l++) {
2209 int normal = delta[(k+1)%4];
2210 if (l == 1)
2211 normal = -normal;
2212
2213 cpos = apos + normal;
2214 if (board[cpos] != EMPTY)
2215 continue;
2216
2217 dpos = bpos + normal;
2218 if (board[dpos] != other)
2219 continue;
2220
2221 /* Configuration found. Now check liberty constraint. */
2222 {
2223 int dlibs = countlib(dpos);
2224 if (dlibs > num_libs
2225 || dlibs > accuratelib(cpos, color, dlibs, NULL))
2226 continue;
2227 }
2228
2229 if (0 && !in_list(cpos, moves->num, moves->pos)) {
2230 gprintf("hane_rescue_move added for %1m at %1m\n", str, cpos);
2231 dump_stack();
2232 showboard(0);
2233 }
2234 ADD_CANDIDATE_MOVE(cpos, 0, *moves, "hane_rescue");
2235 }
2236 }
2237 }
2238}
2239
2240
2241/* In situations like these
2242 *
2243 * |XXXX |.X... |.X...
2244 * |OOOX |.XOO. |XXOO.
2245 * |..OX |OOXO. |OOXO.
2246 * |O.OX |O.X*O |O.XOO
2247 * |.X*. |O.X.O |O.X*O
2248 * +---- +----- +-----
2249 *
2250 * the smaller of the O strings can be defended by *. The property
2251 * they have in common is that the defended string has (at least) two
2252 * liberties in common with an X string and it's effective to play on
2253 * an exterior liberty of this string. Similarly it may be worth
2254 * defending a weak neighbor of the X string.
2255 *
2256 * This function may be called for strings with 2 or 3 liberties and
2257 * returns moves which are potentially useful in these positions.
2258 */
2259static void
2260special_rescue5_moves(int str, int libs[3],
2261 struct reading_moves *moves)
2262{
2263 int color = board[str];
2264 int other = OTHER_COLOR(color);
2265 int apos, bpos;
2266 int k, r, s;
2267 int liberties = countlib(str);
2268 int libs2[4];
2269 int liberties2;
2270
2271 ASSERT1(liberties == 2 || liberties == 3, str);
2272
2273 for (r = 0; r < liberties; r++) {
2274 apos = libs[r];
2275
2276 for (k = 0; k < 4; k++) {
2277 bpos = apos + delta[k];
2278 if (board[bpos] != other)
2279 continue;
2280
2281 /* Don't bother if it has too many liberties. */
2282 if (countlib(bpos) > liberties + 1)
2283 continue;
2284
2285 if (count_common_libs(str, bpos) < 2)
2286 continue;
2287
2288 liberties2 = findlib(bpos, 4, libs2);
2289 for (s = 0; s < liberties2; s++)
2290 if (!liberty_of_string(libs2[s], str)
2291 && !is_self_atari(libs2[s], color))
2292 ADD_CANDIDATE_MOVE(libs2[s], 0, *moves, "special_rescue5-A");
2293
2294 /* Reinforce the second order chain. */
2295 if (liberties2 <= liberties) {
2296 int adj;
2297 int adjs[MAXCHAIN];
2298 int t;
2299 adj = chainlinks2(bpos, adjs, 1);
2300 for (t = 0; t < adj; t++) {
2301 int cpos;
2302 break_chain_moves(adjs[t], moves);
2303
2304 findlib(adjs[t], 1, &cpos);
2305 if (!is_self_atari(cpos, color))
2306 ADD_CANDIDATE_MOVE(cpos, 0, *moves, "special_rescue5-B");
2307 }
2308
2309 /* Defend against double atari in the surrounding chain early. */
2310 double_atari_chain2_moves(bpos, moves, 0);
2311 }
2312 }
2313 }
2314}
2315
2316
2317/* In situations like this
2318 *
2319 * |.bOX
2320 * |.Xa.
2321 * |.OXX
2322 * |.O..
2323 * |.XX.
2324 *
2325 * the lower O string can often be defended at a or b.
2326 *
2327 * This function may be called for strings with 3 or 4 liberties and
2328 * returns the * moves in the configuration below:
2329 *
2330 * |..O |.*O
2331 * |.X. |.c*
2332 * |.O? |ab?
2333 *
2334 * It also adds the * move in these configurations:
2335 *
2336 * |.X. |.c*
2337 * |.OX |abX
2338 *
2339 * |.X. |.c*
2340 * |.O. |ab.
2341 *
2342 * Provided that * is not a self atari and that the X strings have
2343 * sufficiently few liberties.
2344 */
2345static void
2346special_rescue6_moves(int str, int libs[3], struct reading_moves *moves)
2347{
2348 int color = board[str];
2349 int other = OTHER_COLOR(color);
2350 int apos, bpos, cpos;
2351 int right, up;
2352 int k, l, r;
2353 int liberties = countlib(str);
2354
2355 ASSERT1(liberties == 3 || liberties == 4, str);
2356
2357 for (r = 0; r < liberties; r++) {
2358 apos = libs[r];
2359
2360 for (k = 0; k < 4; k++) {
2361 right = delta[k];
2362
2363 if (ON_BOARD(apos - right))
2364 continue;
2365
2366 bpos = apos + right;
2367 if (board[bpos] != color || !same_string(str, bpos))
2368 continue;
2369
2370 for (l = 0; l < 2; l++) {
2371 up = delta[(k+1) % 4];
2372 if (l == 1)
2373 up = -up;
2374
2375 cpos = bpos + up;
2376 if (board[cpos] != other)
2377 continue;
2378
2379 if (board[apos + up] != EMPTY)
2380 continue;
2381
2382 if (board[cpos + right] != EMPTY)
2383 continue;
2384
2385 if (board[apos + up + up] == EMPTY
2386 && board[cpos + up] == EMPTY
2387 && board[cpos + up + right] == color) {
2388 ADD_CANDIDATE_MOVE(cpos + right, 0, *moves, "special_rescue6-A");
2389 ADD_CANDIDATE_MOVE(cpos + up, 0, *moves, "special_rescue6-B");
2390 }
2391 else if (countlib(cpos) <= 3
2392 && (board[bpos + right] == EMPTY
2393 || (board[bpos + right] == other
2394 && countlib(bpos + right) <= 4))
2395 && !is_self_atari(cpos + right, color)) {
2396 ADD_CANDIDATE_MOVE(cpos + right, 0, *moves, "special_rescue6-C");
2397 }
2398 }
2399 }
2400 }
2401}
2402
2403/*
2404 * set_up_snapback_moves() is called with (str) a string having a
2405 * single liberty at (lib).
2406 *
2407 * This adds moves which may defend a string in atari by capturing a
2408 * neighbor in a snapback. One example is this position:
2409 *
2410 * OOOOO
2411 * OXXXO
2412 * OX.OX
2413 * OXOXX
2414 * OX*..
2415 * -----
2416 *
2417 * This code also finds the move * to defend the lone O stone with ko
2418 * in this position:
2419 *
2420 * |XXXXX
2421 * |XOOOX
2422 * |OX.OO
2423 * |.*...
2424 * +-----
2425 *
2426 */
2427
2428static void
2429set_up_snapback_moves(int str, int lib, struct reading_moves *moves)
2430{
2431 int color = board[str];
2432 int other = OTHER_COLOR(color);
2433 int libs2[2];
2434
2435 ASSERT1(countlib(str) == 1, str);
2436
2437 /* This can only work if our string is a single stone and the
2438 * opponent is short of liberties.
2439 */
2440 if (stackp <= backfill_depth
2441 && countstones(str) == 1
2442 && approxlib(lib, other, 2, libs2) == 1
2443 && (!is_self_atari(libs2[0], color)
2444 || is_ko(libs2[0], color, NULL)))
2445 ADD_CANDIDATE_MOVE(libs2[0], 0, *moves, "set_up_snapback");
2446}
2447
2448
2449
2450/* This function adds liberties of the superstring as candidate moves.
2451 * For performance, this is restricted to strings with liberty_cap
2452 * liberties, and to cases where at most 5 liberties would get considered.
2453 *
2454 * When attacking, we also try backfilling in case the direct approach
2455 * would be self-atari.
2456 * When defending, we also try second order liberties.
2457 */
2458static void
2459superstring_moves(int str, struct reading_moves *moves,
2460 int liberty_cap, int does_attack)
2461{
2462 int ss_liberties;
2463 int ss_libs[MAX_LIBERTIES + 4];
2464 int color = board[str];
2465 int other = OTHER_COLOR(color);
2466 int k;
2467
2468 find_superstring_liberties(str, &ss_liberties, ss_libs, liberty_cap);
2469 if (ss_liberties <= 5) {
2470 for (k = 0; k < ss_liberties; k++) {
2471 int apos = ss_libs[k];
2472 int alibs[2];
2473 int alib = accuratelib(apos, other, 2, alibs);
2474
2475 if (liberty_of_string(apos, str))
2476 continue;
2477
2478 if (alib >= 2)
2479 ADD_CANDIDATE_MOVE(apos, 0, *moves, "superstring liberty");
2480 else if (alib == 1
2481 && does_attack
2482 && board[alibs[0]] == EMPTY
2483 && approxlib(alibs[0], other, 3, NULL) >= 3)
2484 ADD_CANDIDATE_MOVE(alibs[0], 0, *moves, "superstring backfill");
2485
2486 if (!does_attack)
2487 special_rescue_moves(str, apos, moves);
2488 }
2489 }
2490}
2491
2492
2493/* This function is somewhat related to superstring_moves() but tries
2494 * to find moves to squeeze out liberties from the superstring, aiming
2495 * to capture the main string in a shortage of liberties.
2496 *
2497 * For a typical example, see the move E9 in reading:203,204. It is
2498 * assumed that the same move is effective both for attack and
2499 * defense.
2500 */
2501static void
2502squeeze_moves(int str, struct reading_moves *moves)
2503{
2504 int color = board[str];
2505 int other = OTHER_COLOR(color);
2506 int libs[4];
2507 int num_libs;
2508 int libs2[4];
2509 int num_libs2;
2510 int k;
2511 int r;
2512 int potential_move = NO_MOVE;
2513 int previous_liberty;
2514
2515 num_libs = findlib(str, 4, libs);
2516 gg_assert(num_libs <= 4);
2517
2518 for (k = 0; k < num_libs; k++) {
2519 if (!is_suicide(libs[k], other))
2520 continue;
2521
2522 num_libs2 = approxlib(libs[k], color, 4, libs2);
2523 if (num_libs2 != num_libs)
2524 continue;
2525
2526 for (r = 0; r < num_libs2; r++)
2527 if (!liberty_of_string(libs2[r], str)) {
2528 potential_move = libs2[r];
2529 break;
2530 }
2531
2532 previous_liberty = libs[k];
2533
2534 while (is_suicide(potential_move, other)) {
2535 num_libs2 = approxlib(potential_move, color, 3, libs2);
2536 if (num_libs2 != 2) {
2537 potential_move = NO_MOVE;
2538 break;
2539 }
2540 if (libs2[0] == previous_liberty) {
2541 previous_liberty = potential_move;
2542 potential_move = libs2[1];
2543 }
2544 else {
2545 previous_liberty = potential_move;
2546 potential_move = libs2[0];
2547 }
2548 if (liberty_of_string(potential_move, str)) {
2549 potential_move = NO_MOVE;
2550 break;
2551 }
2552 }
2553
2554 if (potential_move == NO_MOVE
2555 || !is_self_atari(potential_move, other))
2556 continue;
2557
2558 approxlib(potential_move, other, 1, libs2);
2559
2560 num_libs2 = approxlib(libs2[0], color, MAXLIBS, NULL);
2561
2562 if (num_libs2 < 3
2563 && num_libs2 < approxlib(potential_move, color, MAXLIBS, NULL))
2564 ADD_CANDIDATE_MOVE(potential_move, 0, *moves, "squeeze move");
2565 }
2566}
2567
2568
2569/* In positions like
2570 *
2571 * |.XXOO.
2572 * |XXOX..
2573 * |OOOX*.
2574 * |......
2575 * +------
2576 *
2577 * the O stones to the left are best defended by the move at *.
2578 *
2579 * This function tries to find an adjacent string (apos) with exactly
2580 * three liberties. One of the liberties (bpos) must be on the edge
2581 * (but not in the corner). Diagonal to this liberty must be one stone
2582 * of the attacked string (cpos) and another liberty (dpos) of the
2583 * adjacent string. The third liberty (epos) must be adjacent to
2584 * (dpos). Furthermore must an O stone at (dpos) get at least three
2585 * liberties and and X stone at (epos) must get at most three
2586 * liberties.
2587 *
2588 * |.XXOO.
2589 * |XXOXe.
2590 * |OOcad.
2591 * |...b..
2592 * +------
2593 *
2594 * The defense move at (dpos) is proposed if the above conditions
2595 * are satisfied.
2596 */
2597
2598static void
2599edge_clamp_moves(int str, struct reading_moves *moves)
2600{
2601 int color = board[str];
2602 int other = OTHER_COLOR(color);
2603 int apos;
2604 int bpos;
2605 int cpos;
2606 int dpos;
2607 int epos;
2608 int adj, adjs[MAXCHAIN];
2609 int libs[3];
2610 int k, l, r;
2611
2612 /* Pick up neighbors with three liberties. */
2613 adj = chainlinks2(str, adjs, 3);
2614
2615 for (r = 0; r < adj; r++) {
2616 apos = adjs[r];
2617 /* Find a liberty at the edge. */
2618 bpos = NO_MOVE;
2619 findlib(apos, 3, libs);
2620 for (k = 0; k < 3; k++) {
2621 if (is_edge_vertex(libs[k])) {
2622 bpos = libs[k];
2623 break;
2624 }
2625 }
2626 if (bpos == NO_MOVE)
2627 continue;
2628
2629 /* Edge liberty found. Establish up and right directions. */
2630 for (k = 0; k < 4; k++) {
2631 int up = delta[k];
2632 if (ON_BOARD(bpos - up))
2633 continue;
2634 if (board[bpos + up] != other)
2635 continue;
2636
2637 for (l = 0; l < 2; l++) {
2638 int right = delta[(k+1)%4];
2639 if (l == 1)
2640 right = -right;
2641
2642 cpos = bpos + up - right;
2643 dpos = bpos + up + right;
2644
2645 if (board[cpos] != color || !same_string(cpos, str))
2646 continue;
2647
2648 if (board[dpos] != EMPTY || !liberty_of_string(dpos, apos))
2649 continue;
2650
2651 epos = dpos + up;
2652
2653 if (board[epos] != EMPTY || !liberty_of_string(epos, apos))
2654 continue;
2655
2656 if (approxlib(dpos, color, 3, NULL) < 3)
2657 continue;
2658
2659 if (approxlib(epos, other, 4, NULL) > 3)
2660 continue;
2661
2662 /* (dpos) looks like a good move. Add it to the list with a
2663 * substantial initial score.
2664 */
2665 ADD_CANDIDATE_MOVE(dpos, 10, *moves, "edge_clamp");
2666 }
2667 }
2668 }
2669}
2670
2671
2672/*
2673 * This function handles some special cases on the edge.
2674 *
2675 * 1. If (str) points to a string and 'a' an edge liberty of it,
2676 * there is no point of trying to defend the string by crawling
2677 * along the edge if there is no hope of ever getting more liberties.
2678 * This is of course if the blocking enemy group has enough liberties
2679 * of its own.
2680 *
2681 * XX XX
2682 * O. Oa
2683 * -- --
2684 *
2685 * This function searches the edge towards the corner and sees if there
2686 * is a friendly stone on one of the two first lines. If not, the move
2687 * is removed from the list of moves.
2688 *
2689 * 2. If (str) points to a string and 'a' an edge liberty of it,
2690 * the drawing back/climbing up move 'b' is often correct attack or
2691 * defense. Another good move to try is 'c' (but usually not for
2692 * defense of a 2 liberty string).
2693 *
2694 * X.? Xbc
2695 * O.. Oa.
2696 * --- ---
2697 *
2698 * This function adds the points configured like 'b' and 'c' relative to
2699 * (str) to the list of moves.
2700 *
2701 * color is the color to move.
2702 */
2703
2704static void
2705propose_edge_moves(int str, int *libs, int liberties,
2706 struct reading_moves *moves, int to_move)
2707{
2708 int color = board[str];
2709 int other = OTHER_COLOR(color);
2710 int right;
2711 int up;
2712 int apos;
2713 int k, l;
2714 int r;
2715
2716 for (r = 0; r < liberties; r++) {
2717 apos = libs[r];
2718 for (k = 0; k < 4; k++) {
2719 up = delta[k];
2720 if (ON_BOARD(apos - up))
2721 continue;
2722
2723 for (l = 0; l < 2; l++) {
2724 right = delta[(k+1)%4];
2725 if (l == 1)
2726 right = -right;
2727
2728 if (board[apos + up] == other /* other on top of liberty */
2729 && countlib(apos + up) > 4 /* blocking group must be secure */
2730 && color == to_move) { /* only applicable as defense */
2731
2732 /* Case 1: other above the liberty (crawl along the edge). */
2733 int xpos = apos;
2734
2735 while (ON_BOARD(xpos)) {
2736 if (board[xpos] == color
2737 || board[xpos + up] == color)
2738 break;
2739
2740 xpos += right;
2741 }
2742
2743 /* If no friendly stone found, then it is pointless and we
2744 * can just as well remove the move.
2745 */
2746 if (!ON_BOARD(xpos)) {
2747 REMOVE_CANDIDATE_MOVE(apos, *moves);
2748 }
2749 }
2750 else if (board[apos + up] == EMPTY /* empty above the liberty */
2751 && board[apos - right + up] == other
2752 && board[apos + right] == EMPTY) { /* empty to the right */
2753
2754 /* Case 2: Try to escape or contain. */
2755
2756 /* Add b
2757 * If adjacent X stone in atari, boost the initial score of this
2758 * move.
2759 */
2760 if (countlib(apos + up - right) == 1)
2761 ADD_CANDIDATE_MOVE(apos + up, 10, *moves, "propose_edge-A");
2762 else {
2763 ADD_CANDIDATE_MOVE(apos + up, 0, *moves, "propose_edge-B");
2764
2765 /* Add c if empty */
2766 if (board[apos + right + up] == EMPTY
2767 && (liberties != 2 || color != to_move))
2768 ADD_CANDIDATE_MOVE(apos + right + up, 0, *moves,
2769 "propose_edge-C");
2770 }
2771 }
2772 }
2773 }
2774 }
2775}
2776
2777
2778/* ================================================================ */
2779/* Attacking functions */
2780/* ================================================================ */
2781
2782
2783/* Like attack. If the opponent is komaster reading functions will not try
2784 * to take ko.
2785 */
2786static int
2787do_attack(int str, int *move)
2788{
2789 int color = board[str];
2790 int xpos = NO_MOVE;
2791 int liberties;
2792 int result = 0;
2793 int retval;
2794
2795 SETUP_TRACE_INFO("attack", str);
2796
2797 ASSERT1(color != 0, str);
2798
2799 if (color == 0) /* if assertions are turned off, silently fails */
2800 return 0;
2801
2802 str = find_origin(str);
2803 liberties = countlib(str);
2804
2805 if (liberties > 4
2806 || (liberties == 4 && stackp > fourlib_depth)
2807 || (liberties == 3 && stackp > depth)) {
2808 /* No need to cache the result in these cases. */
2809 if (sgf_dumptree) {
2810 char buf[100];
2811 sprintf(buf, "got 4 liberties (stackp:%d>%d)",
2812 stackp, fourlib_depth);
2813 SGFTRACE(0, 0, buf);
2814 }
2815 return 0;
2816 }
2817
2818 /* Set "killer move" up. This move (if set) was successful in
2819 * another variation, so it is reasonable to try it now. However,
2820 * we only do this if the string has 4 liberties - otherwise the
2821 * situation changes too much from variation to variation.
2822 */
2823 if (liberties > 3 && move)
2824 xpos = *move;
2825
2826 /* Note that if return value is 1 (too small depth), the move will
2827 * still be used for move ordering.
2828 */
2829 if (stackp <= depth
2830 && tt_get(&ttable, ATTACK, str, NO_MOVE, depth - stackp, NULL,
2831 &retval, NULL, &xpos) == 2) {
2832 TRACE_CACHED_RESULT(retval, xpos);
2833 SGFTRACE(xpos, retval, "cached");
2834 if (move)
2835 *move = xpos;
2836 return retval;
2837 }
2838
2839 /* Treat the attack differently depending on how many liberties the
2840 string at (str) has. */
2841 if (liberties == 1)
2842 result = attack1(str, &xpos);
2843 else if (liberties == 2) {
2844 if (stackp > depth + 10)
2845 result = simple_ladder(str, &xpos);
2846 else
2847 result = attack2(str, &xpos);
2848 }
2849 else if (liberties == 3)
2850 result = attack3(str, &xpos);
2851 else if (liberties == 4)
2852 result = attack4(str, &xpos);
2853
2854
2855 ASSERT1(result >= 0 && result <= WIN, str);
2856
2857 if (result) {
2858 READ_RETURN(ATTACK, str, depth - stackp, move, xpos, result);
2859 }
2860
2861 READ_RETURN0(ATTACK, str, depth - stackp);
2862}
2863
2864
2865/* If (str) points to a group with exactly one liberty, attack1
2866 * determines whether it can be captured by playing at this liberty.
2867 * If successful, (*move) is the killing move. move may be NULL if
2868 * caller is only interested in whether it can be captured.
2869 *
2870 * The attack may fail for two different reasons. The first one is
2871 * that the attack may be an illegal ko capture, in this case KO_B is
2872 * returned (need to play a ko threat before the attack can be
2873 * fulfilled).
2874 *
2875 * The second cause for failure is that the attack is caught in a
2876 * snapback. We must require that it is a proper snapback, though. By
2877 * proper snapback we mean a position like
2878 *
2879 * XXXXO
2880 * XO.XO
2881 * XOXOO
2882 * -----
2883 *
2884 * where capture by O and recapture by X leaves the X stone intact
2885 * with at least two liberties:
2886 *
2887 * XXXXO
2888 * X..XO
2889 * X.XOO
2890 * -----
2891 *
2892 * There are a number of different kinds of improper snapbacks, which
2893 * have in common that the attacked string ends up captured. We don't
2894 * consider these as failures to attack. Three examples are given below.
2895 *
2896 * XXOOOOO (X can recapture but loses most of the string.)
2897 * X.XXXXO
2898 * -------
2899 *
2900 * XXXOOOOOOOO (Like the previous example, except O loses one more stone)
2901 * XO*XXXXXXXO
2902 * -----------
2903 *
2904 * XXXOO (After three captures, the lone X stone is gone.)
2905 * XO.XO
2906 * -----
2907 *
2908 * This function is fast and never branches. There's little point in
2909 * caching the result.
2910 */
2911
2912static int
2913attack1(int str, int *move)
2914{
2915 int color = board[str];
2916 int other = OTHER_COLOR(color);
2917 int xpos;
2918 int savemove = 0;
2919 int savecode = 0;
2920 int liberties;
2921 int libs[6];
2922 int k;
2923 int r;
2924 int adjs[MAXCHAIN];
2925 int adj;
2926 int apos;
2927
2928
2929 SETUP_TRACE_INFO("attack1", str);
2930 reading_node_counter++;
2931
2932 /* Pick up the position of the liberty. */
2933 findlib(str, 1, &xpos);
2934
2935 /* If the attacked string consists of more than one stone, the
2936 * attack never fails. (This assumes simple ko rule. With superko
2937 * rule it could still be a ko violation.)
2938 */
2939 if (countstones(str) > 1) {
2940 RETURN_RESULT(WIN, xpos, move, "last liberty");
2941 }
2942
2943 /* Try to play on the liberty. This fails if and only if it is an
2944 * illegal ko capture.
2945 */
2946 if (trymove(xpos, other, "attack1-A", str)) {
2947 /* Is the attacker in atari? If not the attack was successful. */
2948 if (countlib(xpos) > 1) {
2949 popgo();
2950 RETURN_RESULT(WIN, xpos, move, "last liberty");
2951 }
2952
2953 /* If the attacking string is also a single stone, a possible
2954 * recapture would be a ko violation, so the defender has to make
2955 * a ko threat first.
2956 */
2957 else if (countstones(xpos) == 1) {
2958 if (get_komaster() != other) {
2959 /* If the defender is allowed to take the ko the result is KO_A. */
2960 CHECK_RESULT_UNREVERSED(savecode, savemove, KO_A, xpos, move,
2961 "last liberty - ko");
2962 }
2963 else {
2964 /* But if the attacker is the attack was successful. */
2965 popgo();
2966 RETURN_RESULT(WIN, xpos, move, "last liberty");
2967 }
2968 }
2969
2970 /* Otherwise, do recapture. Notice that the liberty must be
2971 * at (str) since we have already established that this string
2972 * was a single stone.
2973 */
2974 else if (trymove(str, color, "attack1-B", str)) {
2975 /* If this was a proper snapback, (str) will now have more
2976 * than one liberty.
2977 */
2978 if (countlib(str) > 1) {
2979 /* Proper snapback, attack fails. */
2980 popgo();
2981 }
2982 else {
2983 popgo();
2984 popgo();
2985 RETURN_RESULT(WIN, xpos, move, "last liberty");
2986 }
2987 }
2988 popgo();
2989 }
2990 else {/* Illegal ko capture. */
2991 if (get_komaster() != color) {
2992 CHECK_RESULT_UNREVERSED(savecode, savemove, KO_B, xpos, move,
2993 "last liberty - ko");
2994 }
2995 }
2996
2997 /* If not yet successful, try backfilling and back-capturing.
2998 * An example of back-capturing can be found in reading:234.
2999 * Backfilling is maybe only meaningful in positions involving ko.
3000 */
3001 liberties = approxlib(xpos, color, 6, libs);
3002 if (liberties <= 5)
3003 for (k = 0; k < liberties; k++) {
3004 apos = libs[k];
3005 if (!is_self_atari(apos, other)
3006 && trymove(apos, other, "attack1-C", str)) {
3007 int dcode = do_find_defense(str, NULL);
3008 if (dcode != WIN && do_attack(str, NULL)) {
3009 if (dcode == 0) {
3010 popgo();
3011 RETURN_RESULT(WIN, apos, move, "backfilling");
3012 }
3013 UPDATE_SAVED_KO_RESULT(savecode, savemove, dcode, apos);
3014 }
3015 popgo();
3016 }
3017 }
3018
3019 adj = chainlinks2(str, adjs, 1);
3020 for (r = 0; r < adj; r++) {
3021 if (liberty_of_string(xpos, adjs[r])) {
3022 int adjs2[MAXCHAIN];
3023 int adj2;
3024 adj2 = chainlinks2(adjs[r], adjs2, 1);
3025 for (k = 0; k < adj2; k++) {
3026 int ko_move;
3027 if (adjs2[k] == str)
3028 continue;
3029 findlib(adjs2[k], 1, &apos);
3030 if (komaster_trymove(apos, other, "attack1-D", str,
3031 &ko_move, stackp <= ko_depth && savecode == 0)) {
3032 if (!ko_move) {
3033 int dcode = do_find_defense(str, NULL);
3034 if (dcode != WIN
3035 && do_attack(str, NULL)) {
3036 popgo();
3037 CHECK_RESULT(savecode, savemove, dcode, apos, move,
3038 "attack effective");
3039 }
3040 else
3041 popgo();
3042 }
3043 else {
3044 if (do_find_defense(str, NULL) != WIN
3045 && do_attack(str, NULL) != 0) {
3046 savemove = apos;
3047 savecode = KO_B;
3048 }
3049 popgo();
3050 }
3051 }
3052 }
3053 }
3054 }
3055
3056 if (savecode == 0) {
3057 RETURN_RESULT(0, 0, move, NULL);
3058 }
3059
3060 RETURN_RESULT(savecode, savemove, move, "saved move");
3061}
3062
3063
3064/* If str points to a group with exactly two liberties
3065 * attack2 determines whether it can be captured in ladder or net.
3066 * If yes, *move is the killing move. move may be null if caller
3067 * is only interested in whether it can be captured.
3068 *
3069 * Returns KO_A or KO_B if it can be killed conditioned on ko. Returns
3070 * KO_A if it can be killed provided (other) is willing to ignore any
3071 * ko threat. Returns KO_B if (other) wins provided he has a ko threat
3072 * which must be answered. Can give a return code KO_B yet *move=0 if
3073 * the winning move is an illegal ko capture. In this case, making a
3074 * ko threat and having it answered should transform the position to
3075 * one where the return code is KO_A.
3076 *
3077 * See the comment before defend1 about ladders and reading depth.
3078 */
3079
3080static int
3081attack2(int str, int *move)
3082{
3083 int color = board[str];
3084 int other = OTHER_COLOR(color);
3085 int hpos;
3086 int xpos = NO_MOVE;
3087 int liberties, r;
3088 int libs[2];
3089 int libs2[2];
3090 int adj, adjs[MAXCHAIN];
3091 int savemove = 0;
3092 int savecode = 0;
3093 int k;
3094 int atari_possible = 0;
3095 struct reading_moves moves;
3096 int adjacent_liberties = 0;
3097 int pass;
3098 int suggest_move = NO_MOVE;
3099
3100 SETUP_TRACE_INFO("attack2", str);
3101 reading_node_counter++;
3102 moves.num = 0;
3103 moves.num_tried = 0;
3104
3105 str = find_origin(str);
3106 ASSERT1(IS_STONE(board[str]), str);
3107 ASSERT1(countlib(str) == 2, str);
3108
3109 for (pass = 0; pass < 4; pass++) {
3110
3111 switch (pass) {
3112 case 0:
3113 /* The attack may fail if a boundary string is in atari and cannot
3114 * be defended. First we must try defending such a string.
3115 *
3116 * We start by trying to defend the boundary string by looking for an
3117 * adjacent string which is in atari.
3118 */
3119 adj = chainlinks2(str, adjs, 1);
3120 for (r = 0; r < adj; r++) {
3121 /* If stackp > depth and any boundary chain is in atari, assume safe.
3122 * However, if the captured chain is only of size 1, there can still
3123 * be a working ladder, so continue if that is the case.
3124 * Also if the string in atari shares its liberty with the
3125 * attacked string, drawing it out may enable the ladder to
3126 * continue.
3127 */
3128 if (stackp > depth
3129 && countstones(adjs[r]) > 1
3130 && !have_common_lib(str, adjs[r], NULL)) {
3131 RETURN_RESULT(0, 0, move, "boundary in atari");
3132 }
3133
3134 /* Pick up moves breaking the second order chain. */
3135 if (stackp <= depth)
3136 break_chain_moves(adjs[r], &moves);
3137
3138 findlib(adjs[r], 1, &hpos);
3139 ADD_CANDIDATE_MOVE(hpos, 0, moves, "save_boundary");
3140 }
3141
3142 /* Get the two liberties of (str). */
3143 liberties = findlib(str, 2, libs);
3144 ASSERT1(liberties == 2, str);
3145
3146 if (DIRECT_NEIGHBORS(libs[0], libs[1]))
3147 adjacent_liberties = 1;
3148
3149 for (k = 0; k < 2; k++) {
3150 int apos = libs[k];
3151 if (!is_self_atari(apos, other))
3152 atari_possible = 1;
3153 /* We only want to consider the move at (apos) if:
3154 * stackp <= backfill_depth
3155 * -or- stackp <= depth and it is an isolated stone
3156 * -or- it is not in immediate atari
3157 */
3158 if (stackp <= backfill_depth
3159 || ((stackp <= depth || adjacent_liberties)
3160 && !has_neighbor(apos, other))
3161 || !is_self_atari(apos, other))
3162 ADD_CANDIDATE_MOVE(apos, 0, moves, "liberty");
3163
3164 /* Try backfilling if atari is impossible. */
3165 if (stackp <= backfill_depth
3166 && approxlib(apos, other, 2, libs2) == 1) {
3167 ADD_CANDIDATE_MOVE(libs2[0], 0, moves, "backfill");
3168 /* If there is a neighbor in atari, we also try back-capturing. */
3169 for (r = 0; r < 4; r++) {
3170 int bpos = libs2[0] + delta[r];
3171 if (board[bpos] == other && chainlinks2(bpos, adjs, 1) > 0) {
3172 /* FIXME: If there is more than one neighbor in atari, we
3173 * currently just take one randomly. This is maybe not good
3174 * enough. We might also want to check against snapback.
3175 *
3176 * FIXME: What is the purpose of this? It produces some
3177 * completely irrelevant moves (e.g. if bpos is a huge string
3178 * with many liberties and adjs[0] is somewhere else on the
3179 * board).
3180 */
3181 findlib(adjs[0], 1, &xpos);
3182 ADD_CANDIDATE_MOVE(xpos, 0, moves, "back-capture");
3183 }
3184 }
3185 }
3186 }
3187
3188 /* If we can't make a direct atari, look for edge blocking moves. */
3189 if (!atari_possible)
3190 for (k = 0; k < 2; k++)
3191 edge_block_moves(str, libs[k], &moves);
3192
3193
3194 /* If one of the surrounding chains have only two liberties, which
3195 * coincide with the liberties of the attacked string, we try to
3196 * backcapture.
3197 */
3198
3199 adj = chainlinks2(str, adjs, 2);
3200 for (r = 0; r < adj; r++) {
3201 int apos = adjs[r];
3202 if (liberty_of_string(libs[0], apos)
3203 && liberty_of_string(libs[1], apos))
3204 break_chain_moves(apos, &moves);
3205 }
3206
3207 propose_edge_moves(str, libs, liberties, &moves, other);
3208
3209 break;
3210
3211 case 1:
3212 if (stackp <= backfill_depth) {
3213 special_attack2_moves(str, libs, &moves);
3214 special_attack3_moves(str, libs, &moves);
3215 special_attack4_moves(str, libs, &moves);
3216 }
3217 break;
3218
3219 case 2:
3220 find_cap_moves(str, &moves);
3221 break;
3222
3223 case 3:
3224 /* If it is not possible to make a direct atari, we try filling
3225 * a liberty of the superstring.
3226 */
3227 if (get_level() >= 8
3228 && stackp <= backfill_depth
3229 && (stackp <= superstring_depth || !atari_possible)) {
3230 int liberty_cap = 2;
3231 if (stackp <= backfill2_depth)
3232 liberty_cap = 3;
3233 superstring_moves(str, &moves, liberty_cap, 1);
3234 squeeze_moves(str, &moves);
3235 }
3236 break;
3237
3238 default:
3239 abort();
3240 } /* switch (pass) */
3241
3242 order_moves(str, &moves, other, read_function_name, *move);
3243 ATTACK_TRY_MOVES(0, &suggest_move);
3244 }
3245
3246 RETURN_RESULT(savecode, savemove, move, "saved move");
3247}
3248
3249
3250
3251/* attack3(str, *move) is used when (str) points to a group with
3252 * three liberties. It returns true if it finds a way to kill the group.
3253 *
3254 * Return code is KO_A if the group can be killed if the attacker is
3255 * willing to ignore any ko threat.
3256 *
3257 * Return code is KO_B if the group can be killed if the attacker is
3258 * able to find a ko threat which must be answered.
3259 *
3260 * If non-NULL (*move) will be set to the move which makes the
3261 * attack succeed.
3262 */
3263
3264static int
3265attack3(int str, int *move)
3266{
3267 int color = board[str];
3268 int other = OTHER_COLOR(color);
3269 int adj, adjs[MAXCHAIN];
3270 int liberties;
3271 int libs[3];
3272 int r;
3273 int k;
3274 struct reading_moves moves;
3275 int savemove = 0;
3276 int savecode = 0;
3277 int pass;
3278 int suggest_move = NO_MOVE;
3279
3280 SETUP_TRACE_INFO("attack3", str);
3281 reading_node_counter++;
3282 moves.num = 0;
3283 moves.num_tried = 0;
3284
3285 ASSERT1(IS_STONE(board[str]), str);
3286
3287 ASSERT1(stackp <= depth, str);
3288
3289 for (pass = 0; pass < 4; pass++) {
3290
3291 switch (pass) {
3292 case 0:
3293 adj = chainlinks2(str, adjs, 1);
3294 for (r = 0; r < adj; r++) {
3295 int hpos;
3296 break_chain_moves(adjs[r], &moves);
3297
3298 findlib(adjs[r], 1, &hpos);
3299 ADD_CANDIDATE_MOVE(hpos, 0, moves, "save_boundary");
3300 }
3301
3302 /* Defend against double atari in the surrounding chain early. */
3303 double_atari_chain2_moves(str, &moves, stackp <= superstring_depth);
3304
3305 /* Get the three liberties of (str). */
3306 liberties = findlib(str, 3, libs);
3307 ASSERT1(liberties == 3, str);
3308
3309 for (k = 0; k < 3; k++) {
3310#if 0
3311 int libs2[2];
3312#endif
3313 int apos = libs[k];
3314 /* We only want to consider the move at (apos) if:
3315 * stackp <= backfill_depth
3316 * -or- stackp <= depth and it is an isolated stone
3317 * -or- it is not in immediate atari
3318 */
3319 if (stackp <= backfill_depth
3320 || (stackp <= depth
3321 && !has_neighbor(apos, other))
3322 || !is_self_atari(apos, other))
3323 ADD_CANDIDATE_MOVE(apos, 0, moves, "liberty");
3324
3325 edge_closing_backfill_moves(str, apos, &moves);
3326
3327#if 0
3328 /* Try backfilling if atari is impossible. */
3329 if (stackp <= backfill_depth
3330 && approxlib(apos, other, 2, libs2) == 1) {
3331 ADD_CANDIDATE_MOVE(libs2[0], 0, moves, "backfill");
3332 }
3333#endif
3334
3335 /* Look for edge blocking moves. */
3336 edge_block_moves(str, apos, &moves);
3337 }
3338
3339 /* Pick up some edge moves. */
3340 propose_edge_moves(str, libs, liberties, &moves, other);
3341 break;
3342
3343 case 1:
3344 /* The simple ataris didn't work. Try something more fancy. */
3345 if (stackp <= backfill_depth)
3346 find_cap_moves(str, &moves);
3347
3348 if (stackp <= fourlib_depth)
3349 draw_back_moves(str, &moves);
3350
3351 break;
3352
3353 case 2:
3354 /* Try to defend chain links with two liberties. */
3355 if (stackp <= backfill2_depth) {
3356 adj = chainlinks2(str, adjs, 2);
3357 for (r = 0; r < adj; r++) {
3358 int libs2[2];
3359 findlib(adjs[r], 2, libs2);
3360 if (approxlib(libs2[0], other, 4, NULL) > 3
3361 && approxlib(libs2[1], other, 4, NULL) > 3)
3362 continue;
3363 break_chain_moves(adjs[r], &moves);
3364 break_chain2_moves(adjs[r], &moves, 1, 0);
3365 for (k = 0; k < 2; k++)
3366 ADD_CANDIDATE_MOVE(libs2[k], 0, moves, "save_boundary-2");
3367 }
3368 }
3369 break;
3370
3371 case 3:
3372 /* If nothing else works, we try filling a liberty of the
3373 * super_string.
3374 */
3375 if (get_level() >= 8 && stackp <= backfill2_depth) {
3376 superstring_moves(str, &moves, 3, 1);
3377 squeeze_moves(str, &moves);
3378 }
3379 break;
3380
3381 default:
3382 abort();
3383 }
3384
3385 order_moves(str, &moves, other, read_function_name, *move);
3386 ATTACK_TRY_MOVES(1, &suggest_move);
3387 } /* for (pass... */
3388
3389 RETURN_RESULT(savecode, savemove, move, "saved move");
3390}
3391
3392
3393/* attack4 tries to capture a string with 4 liberties. */
3394
3395static int
3396attack4(int str, int *move)
3397{
3398 int color = board[str];
3399 int other = OTHER_COLOR(color);
3400 int r;
3401 int k;
3402 int liberties;
3403 int libs[4];
3404 int adj, adjs[MAXCHAIN];
3405 struct reading_moves moves;
3406 int savemove = 0;
3407 int savecode = 0;
3408 int pass;
3409 int suggest_move = NO_MOVE;
3410
3411 SETUP_TRACE_INFO("attack4", str);
3412
3413 ASSERT1(IS_STONE(board[str]), str);
3414 reading_node_counter++;
3415 moves.num = 0;
3416 moves.num_tried = 0;
3417
3418 if (stackp > depth) {
3419 SGFTRACE(0, 0, "stackp > depth");
3420 return 0;
3421 }
3422
3423 for (pass = 0; pass < 2; pass++) {
3424
3425 switch (pass) {
3426 case 0:
3427 adj = chainlinks2(str, adjs, 1);
3428 for (r = 0; r < adj; r++) {
3429 int hpos;
3430 break_chain_moves(adjs[r], &moves);
3431
3432 findlib(adjs[r], 1, &hpos);
3433 ADD_CANDIDATE_MOVE(hpos, 0, moves, "save_boundary");
3434 }
3435
3436 /* Defend against double atari in the surrounding chain early. */
3437 double_atari_chain2_moves(str, &moves, stackp <= superstring_depth);
3438
3439 /* Give a score bonus to the chain preserving moves. */
3440 for (k = 0; k < moves.num; k++)
3441 moves.score[k] += 5;
3442
3443 /* Get the four liberties of (str). */
3444 liberties = findlib(str, 4, libs);
3445 ASSERT1(liberties == 4, str);
3446
3447 for (k = 0; k < 4; k++) {
3448 int apos = libs[k];
3449 /* We only want to consider the move at (apos) if:
3450 * stackp <= backfill_depth
3451 * -or- stackp <= depth and it is an isolated stone
3452 * -or- it is not in immediate atari
3453 */
3454 if (stackp <= backfill_depth
3455 || (stackp <= depth
3456 && !has_neighbor(apos, other))
3457 || !is_self_atari(apos, other))
3458 ADD_CANDIDATE_MOVE(apos, 0, moves, "liberty");
3459
3460 edge_closing_backfill_moves(str, apos, &moves);
3461
3462 /* Look for edge blocking moves. */
3463 edge_block_moves(str, apos, &moves);
3464 }
3465
3466 /* Pick up some edge moves. */
3467 propose_edge_moves(str, libs, liberties, &moves, other);
3468 break;
3469
3470 case 1:
3471 if (stackp <= backfill_depth)
3472 find_cap_moves(str, &moves);
3473 break;
3474
3475 default:
3476 abort();
3477 }
3478
3479 order_moves(str, &moves, other, read_function_name, *move);
3480 ATTACK_TRY_MOVES(1, &suggest_move);
3481 } /* for (pass = ... */
3482
3483 RETURN_RESULT(savecode, savemove, move, "saved move");
3484}
3485
3486
3487/* If (str) points to a string with 2 - 4 liberties,
3488 * find_cap_moves(str, &moves)
3489 * looks for a configuration of the following type:
3490 *
3491 * Xa
3492 * b*
3493 *
3494 * where X are elements of the string in question and a and b are
3495 * two of its liberties.
3496 *
3497 * For larger strings, this can find moves like
3498 *
3499 * XXXXX
3500 * XX.XX
3501 * X.*.X
3502 * XX.XX
3503 * XXXXX
3504 *
3505 * even though they are not capping moves.
3506 */
3507
3508static void
3509find_cap_moves(int str, struct reading_moves *moves)
3510{
3511 int alib, blib;
3512 int numlibs;
3513 int libs[4];
3514 int i, j;
3515 int ai, aj;
3516 int bi, bj;
3517
3518 numlibs = findlib(str, 4, libs);
3519 if (numlibs > 4 || numlibs < 2)
3520 return;
3521
3522 for (i = 0; i < numlibs - 1; i++) {
3523 for (j = i + 1; j < numlibs; j++) {
3524 alib = libs[i];
3525 blib = libs[j];
3526
3527 /* Check if the two liberties are located like the figure above. */
3528 if (!DIAGONAL_NEIGHBORS(alib, blib))
3529 continue;
3530
3531 ai = I(alib);
3532 aj = J(alib);
3533 bi = I(blib);
3534 bj = J(blib);
3535 /* Which of the two corner points should we use? One of them is
3536 * always occupied by the string at (str), the other one is either
3537 * free or occupied by something else.
3538 */
3539 if (BOARD(bi, aj) == EMPTY)
3540 ADD_CANDIDATE_MOVE(POS(bi, aj), 10, *moves, "find_cap");
3541 else if (BOARD(ai, bj) == EMPTY)
3542 ADD_CANDIDATE_MOVE(POS(ai, bj), 10, *moves, "find_cap");
3543 }
3544 }
3545}
3546
3547
3548
3549/* In a situation like this:
3550 *
3551 * ----- the code that
3552 * cO.OX follows can find
3553 * XXOOX the attacking move
3554 * XO.OX at c.
3555 * XOOOX
3556 * XXXXX
3557 *
3558 * The name of the function corresponds to special_rescue2, which is
3559 * fairly similar to this situation.
3560 */
3561
3562static void
3563special_attack2_moves(int str, int libs[2], struct reading_moves *moves)
3564{
3565 int color = board[str];
3566 int other = OTHER_COLOR(color);
3567 int newlibs[3];
3568 int xpos;
3569 int k;
3570
3571 for (k = 0; k < 2; k++) {
3572 if (is_suicide(libs[k], other)
3573 && (approxlib(libs[k], color, 3, newlibs) == 2)) {
3574 if (newlibs[0] != libs[1-k])
3575 xpos = newlibs[0];
3576 else
3577 xpos = newlibs[1];
3578
3579 if (!is_self_atari(xpos, other)) {
3580 ADD_CANDIDATE_MOVE(xpos, 0, *moves, "special_attack2");
3581 }
3582 }
3583 }
3584}
3585
3586
3587/* In situations like these:
3588 *
3589 * ..XXX.. ...XX
3590 * .XX.XX. .cO.X
3591 * XXOOOXX ....X
3592 * XO.O.OX XOOXX
3593 * XO.c.OX XXXX.
3594 * -------
3595 *
3596 * the code that follows can find the attacking move at c.
3597 */
3598
3599static void
3600special_attack3_moves(int str, int libs[2], struct reading_moves *moves)
3601{
3602 int color = board[str];
3603 int other = OTHER_COLOR(color);
3604 int xpos;
3605 int apos;
3606 int bpos;
3607 int k;
3608
3609 ASSERT1(countlib(str) == 2, str);
3610
3611 for (k = 0; k < 2; k++) {
3612 apos = libs[k];
3613 bpos = libs[1-k];
3614
3615 if (apos == SOUTH(bpos) || apos == NORTH(bpos)) {
3616 if (board[WEST(apos)] == EMPTY)
3617 xpos = WEST(apos);
3618 else if (board[EAST(apos)] == EMPTY)
3619 xpos = EAST(apos);
3620 else
3621 continue;
3622 }
3623 else if (apos == WEST(bpos) || apos == EAST(bpos)) {
3624 if (board[SOUTH(apos)] == EMPTY)
3625 xpos = SOUTH(apos);
3626 else if (board[NORTH(apos)] == EMPTY)
3627 xpos = NORTH(apos);
3628 else
3629 continue;
3630 }
3631 else
3632 return; /* Incorrect configuration, give up. */
3633
3634 if (!is_self_atari(xpos, other))
3635 ADD_CANDIDATE_MOVE(xpos, 0, *moves, "special_attack3");
3636 }
3637}
3638
3639
3640/* In situations like these:
3641 *
3642 * ...O.O... ...O.O...
3643 * XXXXOOXXX XXXXOOXXX
3644 * XOOOXXO*. Xsssbbcd.
3645 * .X.O..... .X.sa.e..
3646 * --------- ---------
3647 *
3648 * the code that follows can find the attacking move at *.
3649 *
3650 * Also for situations in which c has three liberties, one of which in common
3651 * with b, the respective attacking move is found (see reading:52 for an
3652 * example).
3653 */
3654
3655static void
3656special_attack4_moves(int str, int libs[2], struct reading_moves *moves)
3657{
3658 int color = board[str];
3659 int other = OTHER_COLOR(color);
3660 int adj, adjs[MAXCHAIN];
3661 int adj2, adjs2[MAXCHAIN];
3662 int libs2[3];
3663 int apos;
3664 int bpos = 0;
3665 int cpos;
3666 int dpos;
3667 int epos;
3668 int clibs;
3669 int dlibs;
3670 int elibs;
3671 int bc_common_lib;
3672 int k, s, t, u;
3673
3674 ASSERT1(countlib(str) == 2, str);
3675
3676 /* To avoid making this too general, we require that both
3677 * liberties are self ataris for X.
3678 */
3679 if (!is_self_atari(libs[0], other)
3680 || !is_self_atari(libs[1], other))
3681 return;
3682
3683 /* Pick up chain links with 2 liberties. */
3684 adj = chainlinks2(str, adjs, 2);
3685
3686 for (k = 0; k < 2; k++) {
3687 apos = libs[k];
3688
3689 /* Check that (apos) also is a liberty of one of the two liberty
3690 * chain links.
3691 */
3692 for (s = 0; s < adj; s++)
3693 if (liberty_of_string(apos, adjs[s])) {
3694 bpos = adjs[s];
3695 break;
3696 }
3697
3698 /* Nothing found. */
3699 if (s == adj)
3700 continue;
3701
3702 /* Now require that (bpos) has a chain link, different from (str),
3703 * also with two liberties, or with three liberties, but one in common
3704 * with (bpos).
3705 */
3706 adj2 = chainlinks3(bpos, adjs2, 3);
3707
3708 for (s = 0; s < adj2; s++) {
3709 cpos = adjs2[s];
3710 if (same_string(cpos, str))
3711 continue;
3712
3713 /* Pick up the liberties of (cpos). */
3714 clibs = findlib(cpos, 3, libs2);
3715
3716 /* No need to do something fancy if it is in atari already. */
3717 if (clibs < 2)
3718 continue;
3719
3720 /* (cpos) has three liberties, none of which in commmon with (bpos)
3721 * attacking it seems too difficult. */
3722 bc_common_lib = have_common_lib(bpos, cpos, NULL);
3723 if (clibs > 2 && !bc_common_lib)
3724 continue;
3725
3726 /* Try playing at a liberty. Before doing this, verify that
3727 * (cpos) cannot get more than three liberties by answering on
3728 * another liberty and that we are not putting ourselves in atari.
3729 * We also should only allow ourselves to get fewer liberties than
3730 * the defender in case (bpos) and (cpos) have a common liberty.
3731 */
3732 for (t = 0; t < clibs; t++) {
3733 dpos = libs2[t];
3734
3735 if (is_self_atari(dpos, other))
3736 continue;
3737
3738 for (u = 0; u < clibs; u++) {
3739 if (t == u)
3740 continue;
3741
3742 epos = libs2[u];
3743
3744 elibs = approxlib(epos, color, 4, NULL);
3745 if (elibs > 3)
3746 break;
3747
3748 dlibs = approxlib(dpos, other, 3, NULL);
3749 if (elibs > dlibs && !bc_common_lib)
3750 break;
3751 }
3752
3753 if (u >= clibs) /* No break occurred. */
3754 ADD_CANDIDATE_MOVE(dpos, 0, *moves, "special_attack4");
3755 }
3756 }
3757 }
3758}
3759
3760
3761/*
3762 * If (str) points to a string, draw_back(str, &moves)
3763 * looks for a move in the following configuration which attacks
3764 * the string:
3765 *
3766 * X* X=attacker, O=defender
3767 * O.
3768 *
3769 * In the initial implementation we consider cases
3770 * where X has exactly 2 liberties.
3771 *
3772 */
3773
3774static void
3775draw_back_moves(int str, struct reading_moves *moves)
3776{
3777 int r, k;
3778 int adj, adjs[MAXCHAIN];
3779 int libs[2];
3780
3781 adj = chainlinks2(str, adjs, 2);
3782 for (r = 0; r < adj; r++) {
3783 findlib(adjs[r], 2, libs);
3784 for (k = 0; k < 2; k++) {
3785 if (!liberty_of_string(libs[k], str)
3786 && ((ON_BOARD1(SOUTH(libs[k]))
3787 && liberty_of_string(SOUTH(libs[k]), str))
3788 || (ON_BOARD1(WEST(libs[k]))
3789 && liberty_of_string(WEST(libs[k]), str))
3790 || (ON_BOARD1(NORTH(libs[k]))
3791 && liberty_of_string(NORTH(libs[k]), str))
3792 || (ON_BOARD1(EAST(libs[k]))
3793 && liberty_of_string(EAST(libs[k]), str)))) {
3794 ADD_CANDIDATE_MOVE(libs[k], 0, *moves, "draw_back");
3795 }
3796 }
3797 }
3798}
3799
3800/* In the following position the reading is much simplifed if we start
3801 * with the edge closing backfilling move at *.
3802 *
3803 * |OO...
3804 * |.OOO.
3805 * |.X.O.
3806 * |XXXO.
3807 * |.X.*.
3808 * +-----
3809 *
3810 * This function identifies the situation
3811 *
3812 * ?XOb
3813 * Xatc
3814 * ----
3815 *
3816 * where a is a liberty of the attacked string, t is the proposed move,
3817 * and b and c do not contain more O stones than X stones.
3818 */
3819
3820static void
3821edge_closing_backfill_moves(int str, int apos, struct reading_moves *moves)
3822{
3823 int color = board[str];
3824 int other = OTHER_COLOR(color);
3825 int k;
3826 int bpos;
3827 int cpos;
3828 int number_x, number_o;
3829
3830 for (k = 0; k < 4; k++) {
3831 int up = delta[k];
3832 int right = delta[(k+1)%4];
3833 if (ON_BOARD(apos - up))
3834 continue;
3835 if (board[apos + up] != color)
3836 return;
3837 if (board[apos + right] == EMPTY
3838 && (!ON_BOARD(apos - right)
3839 || board[apos - right] == color))
3840 ; /* Everything ok so far. */
3841 else if (board[apos - right] == EMPTY
3842 && (!ON_BOARD(apos + right)
3843 || board[apos + right] == color)) {
3844 /* Negate right direction. */
3845 right = -right;
3846 }
3847 else
3848 return;
3849
3850 if (board[apos + up + right] != other)
3851 return;
3852
3853 bpos = apos + up + 2 * right;
3854 if (!ON_BOARD(bpos))
3855 return;
3856
3857 cpos = apos + 2 * right;
3858
3859 number_x = 0;
3860 number_o = 0;
3861 if (board[bpos] == color)
3862 number_x++;
3863 else if (board[bpos] == other)
3864 number_o++;
3865
3866 if (board[cpos] == color)
3867 number_x++;
3868 else if (board[cpos] == other)
3869 number_o++;
3870
3871 if (number_o > number_x)
3872 return;
3873
3874 ADD_CANDIDATE_MOVE(apos + right, 0, *moves, "edge_closing_backfill");
3875 return;
3876 }
3877}
3878
3879
3880/* The first version of this function seemed to induce too many
3881 * variations and has therefore been replaced by a much more limited
3882 * version.
3883 */
3884#if 0
3885
3886/* In positions like
3887 *
3888 * OO...
3889 * XXO*.
3890 * x.X*.
3891 * -----
3892 *
3893 * where the X stones to the left are being attacked, it is often a
3894 * good idea to first consider either or both of the moves marked by *
3895 * in the diagram. Notice that propose_edge_moves() doesn't help with
3896 * this, since the rightmost X stone is not part of the attacked
3897 * string, only the corresponding superstring.
3898 *
3899 * This function identifies the situation
3900 *
3901 * ?XO.? ?bdf?
3902 * ?.X.o haceg
3903 * ----- -----
3904 *
3905 * where a is a liberty of the attacked string, b is a stone of the
3906 * attacked string, and e and f are the considered moves. Also
3907 * considered is the situation where the conditions to the right are
3908 * not correct but c has only two liberties anyway. If safe, the move
3909 * to make atari on c is proposed.
3910 *
3911 * Notice, this code is disabled, as commented above.
3912 */
3913
3914static void
3915edge_block_moves(int str, int apos, struct reading_moves *moves)
3916{
3917 int color = board[str];
3918 int other = OTHER_COLOR(color);
3919 int cpos;
3920 int dpos;
3921 int epos;
3922 int fpos;
3923 int gpos;
3924 int hpos;
3925 int score;
3926 int k, l;
3927
3928 /* Search for the right orientation. */
3929 for (k = 0; k < 4; k++) {
3930 int up = delta[k];
3931 if (ON_BOARD(apos - up))
3932 continue;
3933 if (board[apos + up] != color || !same_string(apos + up, str))
3934 return;
3935
3936 for (l = 0; l < 2; l++) {
3937 int right = delta[(k+1)%4];
3938 if (l == 1)
3939 right = -right;
3940
3941 cpos = apos + right;
3942 dpos = apos + right + up;
3943
3944 if (board[cpos] != color || board[dpos] != other)
3945 continue;
3946
3947 epos = cpos + right;
3948 fpos = dpos + right;
3949 gpos = epos + right;
3950 hpos = apos - right;
3951
3952 if (!ON_BOARD(epos))
3953 continue;
3954
3955 if (board[epos] == EMPTY && board[fpos] == EMPTY
3956 && (board[gpos] != color)) {
3957 /* Everything is set up, suggest moves at e and f. */
3958 if (!ON_BOARD(hpos) || board[hpos] == color)
3959 score = 0;
3960 else
3961 score = -5;
3962 if (countlib(str) == 2)
3963 score -= 10;
3964 ADD_CANDIDATE_MOVE(epos, score, *moves, "edge_block-A");
3965
3966 if (countlib(dpos) == 1)
3967 score = 25;
3968 else
3969 score = 0;
3970 if (countlib(str) == 2)
3971 score -= 10;
3972 ADD_CANDIDATE_MOVE(fpos, score, *moves, "edge_block-B");
3973 }
3974 else if (countlib(cpos) == 2 && countlib(dpos) > 1) {
3975 int libs[2];
3976 int move;
3977 findlib(cpos, 2, libs);
3978 if (libs[0] == apos)
3979 move = libs[1];
3980 else
3981 move = libs[0];
3982 if (!is_self_atari(move, other))
3983 ADD_CANDIDATE_MOVE(move, 0, *moves, "edge_block-C");
3984 }
3985 }
3986 }
3987}
3988
3989#else
3990
3991/* In positions like
3992 *
3993 * OOX..
3994 * XXO*.
3995 * x.X..
3996 * -----
3997 *
3998 * where the X stones to the left are being attacked, it is usually
3999 * important to start by considering the move at *. Thus we propose
4000 * the move at * with a high initial score.
4001 *
4002 * Also, it is often needed to prevent "crawling" along first line
4003 * which can eventually give defender more liberties, like here:
4004 *
4005 * O.OO..X
4006 * OXXO..X
4007 * ...X*..
4008 * -------
4009 *
4010 * This function identifies the situation
4011 *
4012 * XO.? bdf?
4013 * .X.o aceg
4014 * ---- ----
4015 *
4016 * where a is a liberty of the attacked string, b is a stone of the
4017 * attacked string, and e and f are the considered moves.
4018 */
4019
4020static void
4021edge_block_moves(int str, int apos, struct reading_moves *moves)
4022{
4023 int color = board[str];
4024 int other = OTHER_COLOR(color);
4025 int k;
4026
4027 /* Search for the right orientation. */
4028 for (k = 0; k < 4; k++) {
4029 int l;
4030 int up = delta[k];
4031
4032 if (ON_BOARD(apos - up))
4033 continue;
4034 if (board[apos + up] != color || !same_string(apos + up, str))
4035 return;
4036
4037 for (l = 0; l < 2; l++) {
4038 int right = delta[(k+1)%4];
4039 int cpos;
4040 int dpos;
4041 int epos;
4042 int fpos;
4043
4044 if (l == 1)
4045 right = -right;
4046
4047 cpos = apos + right;
4048 dpos = apos + right + up;
4049 epos = cpos + right;
4050 fpos = dpos + right;
4051
4052 if (board[cpos] == color && board[dpos] == other
4053 && board[epos] == EMPTY && board[fpos] == EMPTY) {
4054 if (countlib(dpos) == 1) {
4055 int gpos = epos + right;
4056
4057 /* Check if we have the first situation. */
4058 if (board[gpos] != color)
4059 ADD_CANDIDATE_MOVE(fpos, 30, *moves, "edge_block-A");
4060 }
4061 else {
4062 int edge_scan;
4063
4064 /* Look along board edge to see if the defender's string can
4065 * run away to a friend.
4066 */
4067 for (edge_scan = epos; ; edge_scan += right) {
4068 if (board[edge_scan] == color || board[edge_scan + up] == color) {
4069 ADD_CANDIDATE_MOVE(epos, 10, *moves, "edge_block-B");
4070 break;
4071 }
4072
4073 if (board[edge_scan] != EMPTY || board[edge_scan + up] != EMPTY)
4074 break;
4075 }
4076 }
4077 }
4078 }
4079 }
4080}
4081
4082#endif
4083
4084/* ================================================================ */
4085/* Defending by attacking surrounding strings */
4086/* ================================================================ */
4087
4088/* Add the chainbreaking moves relative to the string (str) to the
4089 * (moves) struct.
4090 */
4091static void
4092break_chain_moves(int str, struct reading_moves *moves)
4093{
4094 int r;
4095 int xpos;
4096 int adj, adjs[MAXCHAIN];
4097
4098 /* Find links in atari. */
4099 adj = chainlinks2(str, adjs, 1);
4100
4101 for (r = 0; r < adj; r++) {
4102 findlib(adjs[r], 1, &xpos);
4103 ADD_CANDIDATE_MOVE(xpos, 1, *moves, "break_chain");
4104 }
4105}
4106
4107
4108/* defend_secondary_chain1_moves() tries to break a chain by defending
4109 * "secondary chain", that is, own strings surrounding a given
4110 * opponent string (which is in turn a chainlink for another own
4111 * string, phew... :). It only defends own strings in atari.
4112 *
4113 * When defending is done by stretching, it is required that the defending
4114 * stone played gets at least `min_liberties', or one less if it is
4115 * adjacent to the opponent chainlink.
4116 *
4117 * Returns true if there where any secondary strings that needed defence
4118 * (which does not imply they actually where defended).
4119 */
4120static int
4121defend_secondary_chain1_moves(int str, struct reading_moves *moves,
4122 int min_liberties)
4123{
4124 int r, s;
4125 int color = OTHER_COLOR(board[str]);
4126 int xpos;
4127 int adj;
4128 int adj2;
4129 int adjs[MAXCHAIN];
4130 int adjs2[MAXCHAIN];
4131
4132 /* Find links in atari. */
4133 adj = chainlinks2(str, adjs, 1);
4134
4135 for (r = 0; r < adj; r++) {
4136 /* Stretch out. */
4137 findlib(adjs[r], 1, &xpos);
4138 if (approxlib(xpos, color, min_liberties, NULL)
4139 + neighbor_of_string(xpos, str) >= min_liberties)
4140 ADD_CANDIDATE_MOVE(xpos, 0, *moves, "defend_secondary_chain1-A");
4141
4142 /* Capture adjacent stones in atari, if any. */
4143 adj2 = chainlinks2(adjs[r], adjs2, 1);
4144 for (s = 0; s < adj2; s++) {
4145 findlib(adjs2[s], 1, &xpos);
4146 if (!is_self_atari(xpos, color))
4147 ADD_CANDIDATE_MOVE(xpos, 0, *moves, "defend_secondary_chain1-B");
4148 }
4149 }
4150
4151 return adj;
4152}
4153
4154
4155/* defend_secondary_chain2_moves() tries to break a chain by defending
4156 * "secondary chain", that is, own strings surrounding a given
4157 * opponent string (which is in turn a chainlink for another own
4158 * string, phew... :). It only defends own strings in
4159 * with two liberties.
4160 *
4161 * When defending is done by stretching, it is required that the defending
4162 * stone played gets at least `min_liberties', or one less if it is
4163 * adjacent to the opponent chainlink. Defence can also be done by capturing
4164 * opponent stones or trying to capture them with an atari.
4165 */
4166static void
4167defend_secondary_chain2_moves(int str, struct reading_moves *moves,
4168 int min_liberties)
4169{
4170 int r, s, t;
4171 int color = OTHER_COLOR(board[str]);
4172 int xpos;
4173 int adj;
4174 int adj2;
4175 int adjs[MAXCHAIN];
4176 int adjs2[MAXCHAIN];
4177 int libs[2];
4178
4179 /* Find links with two liberties. */
4180 adj = chainlinks2(str, adjs, 2);
4181
4182 for (r = 0; r < adj; r++) {
4183 if (!have_common_lib(str, adjs[r], NULL))
4184 continue;
4185
4186 /* Stretch out. */
4187 findlib(adjs[r], 2, libs);
4188 for (t = 0; t < 2; t++) {
4189 xpos = libs[t];
4190 if (approxlib(xpos, color, min_liberties, NULL)
4191 + neighbor_of_string(xpos, str) >= min_liberties)
4192 ADD_CANDIDATE_MOVE(xpos, 0, *moves, "defend_secondary_chain2-A");
4193 }
4194
4195 /* Capture adjacent stones in atari, if any. */
4196 adj2 = chainlinks2(adjs[r], adjs2, 1);
4197 for (s = 0; s < adj2; s++) {
4198 findlib(adjs2[s], 1, &xpos);
4199 if (!is_self_atari(xpos, color))
4200 ADD_CANDIDATE_MOVE(xpos, 0, *moves, "defend_secondary_chain2-B");
4201 }
4202
4203 /* Look for neighbours we can atari. */
4204 adj2 = chainlinks2(adjs[r], adjs2, 2);
4205 for (s = 0; s < adj2; s++) {
4206 findlib(adjs2[s], 2, libs);
4207 for (t = 0; t < 2; t++) {
4208 /* Only atari if target has no easy escape with his other liberty. */
4209 if (approxlib(libs[1-t], OTHER_COLOR(color), 3, NULL) < 3
4210 && !is_self_atari(libs[t], color)) {
4211 ADD_CANDIDATE_MOVE(libs[t], 0, *moves, "defend_secondary_chain2-C");
4212 }
4213 }
4214 }
4215 }
4216}
4217
4218
4219/*
4220 * Find moves which immediately capture chain links with 2
4221 * liberties, in the sense that the links cannot escape atari.
4222 *
4223 * The used heuristics are slightly sloppy, so useless moves may
4224 * appear occasionally. This should, however, only lead to slightly
4225 * worse performance but not to incorrect results.
4226 */
4227static void
4228break_chain2_efficient_moves(int str, struct reading_moves *moves)
4229{
4230 int r;
4231 int adj, adjs[MAXCHAIN];
4232
4233 /* Find links with 2 liberties. */
4234 adj = chainlinks2(str, adjs, 2);
4235
4236 for (r = 0; r < adj; r++)
4237 do_find_break_chain2_efficient_moves(str, adjs[r], moves);
4238}
4239
4240
4241/* Helper function for break_chain2_efficient_moves(). */
4242static void
4243do_find_break_chain2_efficient_moves(int str, int adj,
4244 struct reading_moves *moves)
4245{
4246 int color = board[str];
4247 int other = OTHER_COLOR(color);
4248 int k;
4249 int adj2, adjs2[MAXCHAIN];
4250 int libs[2];
4251 int pos1;
4252 int pos2;
4253 ASSERT1(countlib(adj) == 2, adj);
4254
4255 adj2 = chainlinks2(adj, adjs2, 1);
4256 if (adj2 == 1 && countlib(str) > 2) {
4257 int apos;
4258 break_chain_moves(adjs2[0], moves);
4259 findlib(adjs2[0], 1, &apos);
4260 if (!is_self_atari(apos, color))
4261 ADD_CANDIDATE_MOVE(apos, 0, *moves, "break_chain2_efficient-A");
4262 return;
4263 }
4264
4265 if (adj2 > 1)
4266 return;
4267
4268 findlib(adj, 2, libs);
4269 for (k = 0; k < 2; k++)
4270 if (approxlib(libs[k], other, 3, NULL) <= 2
4271 && !is_self_atari(libs[1 - k], color))
4272 ADD_CANDIDATE_MOVE(libs[1 - k], 0, *moves, "break_chain2_efficient-B");
4273
4274 /* A common special case is this kind of edge position
4275 *
4276 * ..XXX.
4277 * X.XOO.
4278 * XOOX*.
4279 * ......
4280 * ------
4281 *
4282 * where a move at * is most effective for saving the two stones
4283 * to the left.
4284 *
4285 * The code below tries to identify this case. We use the crude
4286 * heuristic that the two liberties of the X stone we want to
4287 * capture should be placed diagonally and that one liberty should
4288 * be on the edge. Then we propose to play the other liberty.
4289 * Notice that both moves may be proposed when attacking a stone
4290 * on 2-2.
4291 *
4292 * Update: This was too crude. Also require that the X stone is on
4293 * the second line and that the proposed move is not a self-atari.
4294 */
4295 if (!DIAGONAL_NEIGHBORS(libs[0], libs[1]))
4296 return;
4297
4298 /* Since we know that the two liberties are diagonal, the following
4299 * construction gives the two vertices "between" the liberties.
4300 */
4301 pos1 = NORTH(gg_max(libs[0], libs[1]));
4302 pos2 = SOUTH(gg_min(libs[0], libs[1]));
4303 if ((board[pos1] != other
4304 || !is_edge_vertex(pos2)
4305 || !same_string(pos1, adj))
4306 && (board[pos2] != other
4307 || !is_edge_vertex(pos1)
4308 || !same_string(pos2, adj)))
4309 return;
4310
4311 if (is_edge_vertex(libs[0]) && !is_self_atari(libs[1], color))
4312 ADD_CANDIDATE_MOVE(libs[1], 1, *moves, "break_chain2_efficient-C");
4313
4314 if (is_edge_vertex(libs[1]) && !is_self_atari(libs[0], color))
4315 ADD_CANDIDATE_MOVE(libs[0], 1, *moves, "break_chain2_efficient-C");
4316}
4317
4318
4319/* (str) points to a string with two or more liberties. break_chain2_moves()
4320 * tries to defend this string by attacking a neighbouring string with
4321 * two liberties.
4322 * This is done by playing on either of its liberties
4323 * (if (require_safe) is true these are only used if they are not
4324 * self-ataris), taking a neighbour out of atari or by backfilling if
4325 * both liberties are self-ataris.
4326 */
4327static void
4328break_chain2_moves(int str, struct reading_moves *moves, int require_safe,
4329 int be_aggressive)
4330{
4331 int color = board[str];
4332 int other = OTHER_COLOR(color);
4333 int r;
4334 int adj;
4335 int adjs[MAXCHAIN];
4336
4337 adj = chainlinks2(str, adjs, 2);
4338
4339 for (r = 0; r < adj; r++) {
4340 int k;
4341 int apos = adjs[r];
4342 int libs[2];
4343 int unsafe[2];
4344 int dummy_adjs[MAXCHAIN];
4345
4346 findlib(apos, 2, libs);
4347
4348 /* If stackp > backfill_depth, don't bother playing liberties of
4349 * 2-liberty strings if those also have at least one neighbor in
4350 * atari. This is intended to solve reading:171 and generally reduce
4351 * the number of nodes.
4352 */
4353 if (stackp > backfill_depth
4354 && chainlinks2(apos, dummy_adjs, 1) > 0)
4355 continue;
4356
4357 for (k = 0; k < 2; k++) {
4358 unsafe[k] = is_self_atari(libs[k], color);
4359 if (!unsafe[k]
4360 || is_ko(libs[k], color, NULL)
4361 || (!require_safe
4362 && approxlib(libs[k], other, 5, NULL) < 5))
4363 ADD_CANDIDATE_MOVE(libs[k], 0, *moves, "break_chain2-A");
4364 }
4365
4366 if (stackp <= break_chain_depth
4367 || (be_aggressive && stackp <= backfill_depth)) {
4368 /* If the chain link cannot escape easily, try to defend all adjacent
4369 * friendly stones in atari (if any). If there are none, defend
4370 * adjacent friendly stones with only two liberties.
4371 */
4372 if (approxlib(libs[0], other, 4, NULL) < 4
4373 && approxlib(libs[1], other, 4, NULL) < 4) {
4374 if (!defend_secondary_chain1_moves(adjs[r], moves, 2))
4375 defend_secondary_chain2_moves(adjs[r], moves, 2);
4376 }
4377 }
4378
4379 if (unsafe[0] && unsafe[1]
4380 && (stackp <= backfill2_depth || have_common_lib(str, apos, NULL))) {
4381 int lib;
4382
4383 /* Find backfilling moves. */
4384 for (k = 0; k < 2; k++) {
4385 int libs2[3];
4386 if (approxlib(libs[k], other, 3, libs2) == 2) {
4387 if (!is_self_atari(libs2[0], color))
4388 ADD_CANDIDATE_MOVE(libs2[0], 0, *moves, "break_chain2-B");
4389 if (!is_self_atari(libs2[1], color))
4390 ADD_CANDIDATE_MOVE(libs2[1], 0, *moves, "break_chain2-B");
4391 }
4392 }
4393
4394 /* Consider this case (reading:188):
4395 *
4396 * |.OOOXXX
4397 * |OXXXOOO
4398 * |.X.O...
4399 * +-------
4400 *
4401 * We cannot atari the corner X string immediatly, so we need to
4402 * backfill. However, to avoid generating too many variations,
4403 * we require that the opponent string is well restrained.
4404 * Otherwise it could just run away while we backfill.
4405 */
4406 if (approxlib(libs[0], other, 3, NULL) <= 2
4407 && approxlib(libs[1], other, 3, NULL) <= 2) {
4408 if (approxlib(libs[0], color, 1, &lib) == 1
4409 && approxlib(lib, color, 3, NULL) >= 3)
4410 ADD_CANDIDATE_MOVE(lib, 0, *moves, "break_chain2-C");
4411
4412 if (approxlib(libs[1], color, 1, &lib) == 1
4413 && approxlib(lib, color, 3, NULL) >= 3)
4414 ADD_CANDIDATE_MOVE(lib, 0, *moves, "break_chain2-C");
4415 }
4416 }
4417 }
4418}
4419
4420/*
4421 * (str) points to a group to be defended.
4422 * break_chain2_defense_moves is a wrapper around break_chain2_moves.
4423 * It devalues all entries by 2.
4424 *
4425 * Rationale: Otherwise, these moves get overvalued by order_moves. In
4426 * particular, if there is both a direct and a break_chain2 defense,
4427 * then the latter one might be just an irrelevant intermediate forcing
4428 * move. Hence, we should rather return the direct defense.
4429 */
4430
4431static void
4432break_chain2_defense_moves(int str, struct reading_moves *moves,
4433 int be_aggressive)
4434{
4435 int saved_num_moves = moves->num;
4436 int k;
4437
4438 break_chain2_moves(str, moves, !(stackp <= backfill_depth), be_aggressive);
4439 for (k = saved_num_moves; k < moves->num; k++)
4440 moves->score[k] = -2;
4441}
4442
4443
4444/* Helper function for break_chain3_moves() and
4445 * superstring_break_chain_moves().
4446 */
4447static void
4448do_find_break_chain3_moves(int *chain_links, int num_chain_links,
4449 struct reading_moves *moves, int be_aggressive,
4450 const char *caller_function_name)
4451{
4452 int other = board[chain_links[0]];
4453 int color = OTHER_COLOR(other);
4454 signed char move_added[BOARDMAX];
4455 int possible_moves[MAX_MOVES];
4456 int num_possible_moves = 0;
4457 int r;
4458 int k;
4459
4460 gg_assert(num_chain_links > 0);
4461
4462 memset(move_added, 0, sizeof move_added);
4463
4464 for (r = 0; r < num_chain_links; r++) {
4465 int lib1;
4466 int lib2;
4467 int lib3;
4468 int libs[3];
4469
4470 /* We make a list in the (adjs) array of the liberties
4471 * of boundary strings having exactly three liberties. We mark
4472 * each liberty in the mw array so that we do not list any
4473 * more than once.
4474 */
4475 findlib(chain_links[r], 3, libs);
4476
4477 /* If the 3 liberty chain easily can run away through one of the
4478 * liberties, we don't play on any of the other liberties.
4479 */
4480 lib1 = approxlib(libs[0], other, 4, NULL);
4481 lib2 = approxlib(libs[1], other, 4, NULL);
4482 if (lib1 >= 4 && lib2 >= 4)
4483 continue;
4484 lib3 = approxlib(libs[2], other, 4, NULL);
4485
4486 if ((lib1 >= 4 || lib2 >= 4) && lib3 >= 4)
4487 continue;
4488
4489 if (lib1 >= 4) {
4490 if (!move_added[libs[0]]) {
4491 possible_moves[num_possible_moves++] = libs[0];
4492 move_added[libs[0]] = 1;
4493 }
4494
4495 continue;
4496 }
4497
4498 if (lib2 >= 4) {
4499 if (!move_added[libs[1]]) {
4500 possible_moves[num_possible_moves++] = libs[1];
4501 move_added[libs[1]] = 1;
4502 }
4503
4504 continue;
4505 }
4506
4507 if (lib3 >= 4) {
4508 if (!move_added[libs[2]]) {
4509 possible_moves[num_possible_moves++] = libs[2];
4510 move_added[libs[2]] = 1;
4511 }
4512
4513 continue;
4514 }
4515
4516 /* No easy escape, try all liberties. */
4517 for (k = 0; k < 3; k++) {
4518 if (!move_added[libs[k]]) {
4519 possible_moves[num_possible_moves++] = libs[k];
4520 move_added[libs[k]] = 1;
4521 }
4522 }
4523
4524 if (stackp <= backfill2_depth
4525 || (be_aggressive && stackp <= backfill_depth))
4526 defend_secondary_chain1_moves(chain_links[r], moves, 3);
4527 }
4528
4529 for (k = 0; k < num_possible_moves; k++) {
4530 /* We do not wish to consider the move if it can be immediately
4531 * recaptured, unless stackp < backfill2_depth. Beyond
4532 * backfill2_depth, the necessary capturing move might not get
4533 * generated in follow-up for the attacker. (This currently only
4534 * makes a difference at stackp == backfill2_depth.)
4535 */
4536 int move = possible_moves[k];
4537
4538 if (stackp <= break_chain_depth
4539 || (be_aggressive && stackp <= backfill_depth)
4540 || approxlib(move, color, 2, NULL) > 1)
4541 /* We use a negative initial score here as we prefer to find
4542 * direct defense moves.
4543 */
4544 ADD_CANDIDATE_MOVE(move, -2, *moves, caller_function_name);
4545 }
4546}
4547
4548
4549/*
4550 * (str) points to a group.
4551 * If there is a string in the surrounding chain having
4552 * exactly three liberties whose attack leads to the rescue of
4553 * (str), break_chain3_moves(str, *moves) adds attack moves against
4554 * the surrounding string as candidate moves.
4555 */
4556
4557static void
4558break_chain3_moves(int str, struct reading_moves *moves, int be_aggressive)
4559{
4560 int chain_links[MAXCHAIN];
4561 int num_chain_links = chainlinks2(str, chain_links, 3);
4562
4563 if (num_chain_links > 0) {
4564 do_find_break_chain3_moves(chain_links, num_chain_links,
4565 moves, be_aggressive, "break_chain3");
4566 }
4567}
4568
4569
4570/*
4571 * (str) points to a group.
4572 * If there is a string in the surrounding chain having
4573 * exactly four liberties whose attack leads to the rescue of
4574 * (str), break_chain4_moves(str, *moves) adds attack moves against
4575 * the surrounding string as candidate moves.
4576 */
4577
4578static void
4579break_chain4_moves(int str, struct reading_moves *moves, int be_aggressive)
4580{
4581 int color = board[str];
4582 int other = OTHER_COLOR(color);
4583 int r;
4584 int k;
4585 int u = 0, v;
4586 int apos;
4587 int adj;
4588 int adjs[MAXCHAIN];
4589 int libs[4];
4590 int possible_moves[MAX_MOVES];
4591 int mw[BOARDMAX];
4592
4593 memset(mw, 0, sizeof(mw));
4594
4595 adj = chainlinks2(str, adjs, 4);
4596 for (r = 0; r < adj; r++) {
4597 int lib1 = 0, lib2 = 0, lib3 = 0, lib4 = 0;
4598 apos = adjs[r];
4599
4600 /* We make a list in the (adjs) array of the liberties
4601 * of boundary strings having exactly four liberties. We mark
4602 * each liberty in the mw array so that we do not list any
4603 * more than once.
4604 */
4605 findlib(apos, 4, libs);
4606
4607 /* If the 4 liberty chain easily can run away through one of the
4608 * liberties, we don't play on any of the other liberties.
4609 */
4610 lib1 = approxlib(libs[0], other, 5, NULL);
4611 lib2 = approxlib(libs[1], other, 5, NULL);
4612 if (lib1 >= 5 && lib2 >= 5)
4613 continue;
4614 lib3 = approxlib(libs[2], other, 5, NULL);
4615
4616 if ((lib1 >= 5 || lib2 >= 5) && lib3 >= 5)
4617 continue;
4618 lib4 = approxlib(libs[3], other, 5, NULL);
4619
4620 if ((lib1 >= 5 || lib2 >= 5 || lib3 >= 5) && lib4 >= 5)
4621 continue;
4622
4623 if (lib1 >= 5 && !mw[libs[0]]) {
4624 mw[libs[0]] = 1;
4625 possible_moves[u++] = libs[0];
4626 continue;
4627 }
4628
4629 if (lib2 >= 5 && !mw[libs[1]]) {
4630 mw[libs[1]] = 1;
4631 possible_moves[u++] = libs[1];
4632 continue;
4633 }
4634
4635 if (lib3 >= 5 && !mw[libs[2]]) {
4636 mw[libs[2]] = 1;
4637 possible_moves[u++] = libs[2];
4638 continue;
4639 }
4640
4641 if (lib4 >= 5 && !mw[libs[3]]) {
4642 mw[libs[3]] = 1;
4643 possible_moves[u++] = libs[3];
4644 continue;
4645 }
4646
4647 /* No easy escape, try all liberties. */
4648 for (k = 0; k < 4; k++) {
4649 if (!mw[libs[k]]) {
4650 mw[libs[k]] = 1;
4651 possible_moves[u++] = libs[k];
4652 }
4653 }
4654
4655 if (stackp <= backfill2_depth
4656 || (be_aggressive && stackp <= backfill_depth))
4657 defend_secondary_chain1_moves(adjs[r], moves, 4);
4658 }
4659
4660 for (v = 0; v < u; v++) {
4661 /* We do not wish to consider the move if it can be
4662 * immediately recaptured, unless stackp < backfill2_depth.
4663 * Beyond backfill2_depth, the necessary capturing move might not
4664 * get generated in follow-up for the attacker.
4665 * (This currently only makes a difference at stackp == backfill2_depth.)
4666 */
4667 int xpos = possible_moves[v];
4668 if (stackp <= break_chain_depth
4669 || (be_aggressive && stackp <= backfill_depth)
4670 || approxlib(xpos, color, 2, NULL) > 1)
4671 /* We use a negative initial score here as we prefer to find
4672 * direct defense moves.
4673 */
4674 ADD_CANDIDATE_MOVE(xpos, -2, *moves, "break_chain4");
4675 }
4676}
4677
4678/* This function looks for moves attacking those components
4679 * of the surrounding chain of the superstring (see find_superstring
4680 * for the definition) which have fewer than liberty_cap liberties,
4681 * and which are not adjacent to the string itself, since those
4682 * are tested by break_chain_moves.
4683 */
4684static void
4685superstring_break_chain_moves(int str, int liberty_cap,
4686 struct reading_moves *moves)
4687{
4688 int adj;
4689 int adjs[MAXCHAIN];
4690 int chain_links3[MAXCHAIN];
4691 int num_chain_links3 = 0;
4692 int k;
4693 int apos;
4694
4695 proper_superstring_chainlinks(str, &adj, adjs, liberty_cap);
4696 for (k = 0; k < adj; k++) {
4697 int liberties = countlib(adjs[k]);
4698 if (liberties == 1) {
4699 findlib(adjs[k], 1, &apos);
4700 ADD_CANDIDATE_MOVE(apos, 0, *moves, "superstring_break_chain");
4701 }
4702 else if (liberties == 2)
4703 do_find_break_chain2_efficient_moves(str, adjs[k], moves);
4704 else if (liberties == 3)
4705 chain_links3[num_chain_links3++] = adjs[k];
4706 }
4707
4708 if (num_chain_links3 > 0) {
4709 do_find_break_chain3_moves(chain_links3, num_chain_links3,
4710 moves, 0, "superstring_break_chain-3");
4711 }
4712}
4713
4714/*
4715 * If `str' points to a group, double_atari_chain2_moves() adds all
4716 * moves which make a double atari on some strings in the surrounding
4717 * chain to the moves[] array. In addition, if `generate_more_moves'
4718 * is set, it adds moves that make atari on a string in the
4719 * surrounding chain and are adjacent to another string with 3
4720 * liberties.
4721 */
4722
4723static void
4724double_atari_chain2_moves(int str, struct reading_moves *moves,
4725 int generate_more_moves)
4726{
4727 int r, k;
4728 int adj;
4729 int adjs[MAXCHAIN];
4730 int libs[3];
4731 int mw[BOARDMAX];
4732
4733 memset(mw, 0, sizeof(mw));
4734
4735 adj = chainlinks2(str, adjs, 2);
4736 for (r = 0; r < adj; r++) {
4737 findlib(adjs[r], 2, libs);
4738 for (k = 0; k < 2; k++) {
4739 mw[libs[k]]++;
4740 if (mw[libs[k]] == 2) {
4741 /* Found a double atari, but don't play there unless the move
4742 * is safe for the defender.
4743 */
4744 if (!is_self_atari(libs[k], board[str]))
4745 ADD_CANDIDATE_MOVE(libs[k], 1, *moves, "double_atari_chain2-A");
4746 }
4747 }
4748 }
4749
4750 if (generate_more_moves) {
4751 int adj3;
4752 int adjs3[MAXCHAIN];
4753
4754 adj3 = chainlinks2(str, adjs3, 3);
4755 for (r = 0; r < adj3; r++) {
4756 findlib(adjs3[r], 3, libs);
4757 for (k = 0; k < 3; k++) {
4758 if (mw[libs[k]] == 1) {
4759 mw[libs[k]] = 2;
4760 if (!is_self_atari(libs[k], board[str]))
4761 ADD_CANDIDATE_MOVE(libs[k], -3, *moves, "double_atari_chain2-B");
4762 }
4763 }
4764 }
4765 }
4766}
4767
4768
4769/* ================================================================ */
4770/* Restricted Attack and Defense */
4771/* ================================================================ */
4772
4773
4774/* These functions try to attack and defend a string, avoiding moves
4775 * from a certain set. It is assumed that as soon as the string gets
4776 * three liberties, it is alive.
4777 *
4778 * These functions can be used to generate backfilling moves as
4779 * follows: Suppose that we would like to make atari on a
4780 * string, but the atari is not safe until we make a backfilling
4781 * move. To find the backfilling move, we make a list of the
4782 * liberties of the string under attack, declaring these moves
4783 * forbidden. Neither player will play them while the restricted
4784 * functions are in effect. We fill the liberty, creating a
4785 * string which is under attack, and look for a defensive move
4786 * which avoids the forbidden moves. This is the backfilling
4787 * move.
4788 *
4789 * These are minimalist functions capable of reading a ladder
4790 * and not much more.
4791 */
4792
4793/* Given a list of moves, restricted_defend1 tries to find a
4794 * move that defends the string (str) with one liberty,
4795 * not considering moves from the list.
4796 */
4797int
4798restricted_defend1(int str, int *move,
4799 int num_forbidden_moves, int *forbidden_moves)
4800{
4801 int color = board[str];
4802 int other = OTHER_COLOR(color);
4803 int xpos;
4804 int lib;
4805 struct reading_moves moves;
4806 int savemove = 0;
4807 int savecode = 0;
4808 int liberties;
4809 int k;
4810
4811 SETUP_TRACE_INFO("restricted_defend1", str);
4812 reading_node_counter++;
4813 moves.num = 0;
4814
4815 ASSERT1(IS_STONE(board[str]), str);
4816 ASSERT1(countlib(str) == 1, str);
4817
4818 /* (lib) will be the liberty of the string. */
4819 liberties = findlib(str, 1, &lib);
4820 ASSERT1(liberties == 1, str);
4821
4822 /* Collect moves to try in the first batch.
4823 * 1. First order liberty.
4824 * 2. Chain breaking moves.
4825 * 3. Moves to set up a snapback.
4826 */
4827 moves.pos[0] = lib;
4828 moves.score[0] = 0;
4829 moves.message[0] = "liberty";
4830 moves.num = 1;
4831 moves.num_tried = 0;
4832
4833 break_chain_moves(str, &moves);
4834 set_up_snapback_moves(str, lib, &moves);
4835 order_moves(str, &moves, color, read_function_name, NO_MOVE);
4836
4837 for (k = 0; k < moves.num; k++) {
4838 int ko_capture;
4839
4840 xpos = moves.pos[k];
4841 if (in_list(xpos, num_forbidden_moves, forbidden_moves))
4842 continue;
4843 /* To avoid loops with double ko, we do not allow any ko captures,
4844 * even legal ones, if the opponent is komaster.
4845 */
4846 if (is_ko(xpos, color, NULL))
4847 ko_capture = 1;
4848 else
4849 ko_capture = 0;
4850
4851 if ((get_komaster() != other || !ko_capture)
4852 && trymove(xpos, color, moves.message[k], str)) {
4853 int libs = countlib(str);
4854 if (libs > 2) {
4855 popgo();
4856 SGFTRACE(xpos, WIN, "defense effective");
4857 if (move)
4858 *move = xpos;
4859 return WIN;
4860 }
4861 if (libs == 2) {
4862 int acode;
4863
4864 if (!ko_capture)
4865 acode = restricted_attack2(str, NULL,
4866 num_forbidden_moves, forbidden_moves);
4867 else
4868 acode = restricted_attack2(str, NULL,
4869 num_forbidden_moves, forbidden_moves);
4870 popgo();
4871 if (acode == 0) {
4872 SGFTRACE(xpos, WIN, "defense effective");
4873 if (move)
4874 *move = xpos;
4875 return WIN;
4876 }
4877 /* if the move works with ko we save it, then look for something
4878 * better.
4879 */
4880 UPDATE_SAVED_KO_RESULT(savecode, savemove, acode, xpos);
4881 }
4882 else
4883 popgo();
4884 }
4885 else {
4886 int ko_pos;
4887 if (stackp <= ko_depth
4888 && savecode == 0
4889 && (get_komaster() == EMPTY
4890 || (get_komaster() == color
4891 && get_kom_pos() == xpos))
4892 && is_ko(xpos, color, &ko_pos)
4893 && tryko(xpos, color, "restricted_defend1-B")) {
4894 int libs = countlib(str);
4895 if (libs > 2) {
4896 popgo();
4897 UPDATE_SAVED_KO_RESULT(savecode, savemove, 2, xpos);
4898 }
4899 else if (libs == 2) {
4900 int acode;
4901 acode = restricted_attack2(str, NULL,
4902 num_forbidden_moves, forbidden_moves);
4903 popgo();
4904 UPDATE_SAVED_KO_RESULT(savecode, savemove, acode, xpos);
4905 }
4906 else
4907 popgo();
4908 }
4909 }
4910 }
4911
4912 if (savecode != 0) {
4913 if (move)
4914 *move = savemove;
4915 SGFTRACE(savemove, savecode, "saved move");
4916 return savecode;
4917 }
4918
4919 SGFTRACE(0, 0, NULL);
4920 return 0;
4921}
4922
4923
4924/* Given a list of moves, restricted_attack2 tries to find a
4925 * move that attacks the string (str) with two liberties,
4926 * not considering moves from the list.
4927 */
4928int
4929restricted_attack2(int str, int *move,
4930 int num_forbidden_moves, int *forbidden_moves)
4931{
4932 int color = board[str];
4933 int other = OTHER_COLOR(color);
4934 int apos;
4935 int liberties;
4936 int libs[2];
4937 int savemove = 0;
4938 int savecode = 0;
4939 int k;
4940
4941 SETUP_TRACE_INFO("restricted_attack2", str);
4942 reading_node_counter++;
4943
4944 str = find_origin(str);
4945 ASSERT1(IS_STONE(board[str]), str);
4946 ASSERT1(countlib(str) == 2, str);
4947
4948 /* The attack may fail if a boundary string is in atari and cannot
4949 * be defended. First we must try defending such a string.
4950 */
4951 /* Get the two liberties of (str). */
4952 liberties = findlib(str, 2, libs);
4953 ASSERT1(liberties == 2, str);
4954
4955 for (k = 0; k < 2; k++) {
4956 int ko_pos;
4957 int ko_capture;
4958
4959 apos = libs[k];
4960 if (in_list(apos, num_forbidden_moves, forbidden_moves))
4961 continue;
4962 /* To avoid loops with double ko, we do not allow any ko captures,
4963 * even legal ones, if the opponent is komaster.
4964 */
4965 if (is_ko(apos, other, &ko_pos))
4966 ko_capture = 1;
4967 else
4968 ko_capture = 0;
4969
4970 if ((get_komaster() != color || !ko_capture)
4971 && trymove(apos, other, "restricted_attack2", str)) {
4972 if ((!ko_capture
4973 && !restricted_defend1(str, NULL,
4974 num_forbidden_moves, forbidden_moves))
4975 || (ko_capture
4976 && !restricted_defend1(str, NULL,
4977 num_forbidden_moves, forbidden_moves))) {
4978 popgo();
4979 SGFTRACE(apos, WIN, "attack effective");
4980 if (move)
4981 *move = apos;
4982 return WIN;
4983 }
4984 popgo();
4985 }
4986 else if (savecode == 0
4987 && (get_komaster() == EMPTY
4988 || (get_komaster() == other
4989 && get_kom_pos() == apos))
4990 && tryko(apos, other, "restricted_attack2")) {
4991 if (!restricted_defend1(str, NULL,
4992 num_forbidden_moves, forbidden_moves)) {
4993 popgo();
4994 savecode = KO_B;
4995 savemove = apos;
4996 }
4997 else
4998 popgo();
4999 }
5000 }
5001
5002 if (savecode != 0) {
5003 if (move)
5004 *move = savemove;
5005 SGFTRACE(savemove, savecode, "saved move");
5006 return savecode;
5007 }
5008
5009 SGFTRACE(0, 0, NULL);
5010 return 0;
5011}
5012
5013
5014/*
5015 * Returns true if the move is in a given list of moves.
5016 */
5017
5018static int
5019in_list(int move, int num_moves, int *moves)
5020{
5021 int k;
5022
5023 for (k = 0; k < num_moves; k++)
5024 if (moves[k] == move)
5025 return 1;
5026 return 0;
5027}
5028
5029
5030/* ================================================================ */
5031/* Move ordering */
5032/* ================================================================ */
5033
5034/* Parameters used in the ordering of moves to try in the tactical
5035 * reading.
5036 */
5037
5038/* 0 1 2 3 4 >4 */
5039static int defend_lib_score[6] = {-5, -4, 0, 3, 5, 50};
5040static int defend_not_adjacent_lib_score[5] = { 0, 0, 2, 3, 5};
5041static int defend_capture_score[6] = { 0, 6, 9, 13, 18, 24};
5042static int defend_atari_score[6] = { 0, 2, 4, 6, 7, 8};
5043static int defend_save_score[6] = { 0, 3, 6, 8, 10, 12};
5044static int defend_open_score[5] = { 0, 1, 2, 3, 4};
5045static int attack_own_lib_score[5] = {10, -4, 2, 3, 4};
5046static int attack_string_lib_score[6] = {-5, 2, 3, 7, 10, 19};
5047static int attack_capture_score[6] = {-4, 4, 10, 15, 20, 25};
5048static int attack_save_score[6] = { 0, 10, 13, 18, 21, 24};
5049static int attack_open_score[5] = { 0, 0, 2, 4, 4};
5050static int defend_not_edge_score = 5;
5051static int attack_not_edge_score = 1;
5052static int attack_ko_score = -15;
5053static int cannot_defend_penalty = -20;
5054static int safe_atari_score = 8;
5055
5056
5057static void
5058sgf_dumpmoves(struct reading_moves *moves, const char *funcname)
5059{
5060 char buf[500];
5061 char *pos;
5062 int i, chars;
5063 sprintf(buf, "Move order for %s: %n", funcname, &chars);
5064 pos = buf + chars;
5065 for (i = moves->num_tried; i < moves->num; i++) {
5066 sprintf(pos, "%c%d (%d) %n",
5067 J(moves->pos[i]) + 'A' + (J(moves->pos[i]) >= 8),
5068 board_size - I(moves->pos[i]), moves->score[i], &chars);
5069 pos += chars;
5070 }
5071 sgftreeAddComment(sgf_dumptree, buf);
5072}
5073
5074
5075/* The string at (str) is under attack. The moves.num moves in
5076 * (moves) for color have been deemed interesting in
5077 * the attack or defense of the group. Most of these moves will be
5078 * immediate liberties of the group.
5079 *
5080 * This function orders the moves in the order where the move most
5081 * likely to succeed to attack or defend the string will be first and
5082 * so on.
5083 *
5084 * Currently, this is defined as:
5085 * 1) Moves which let the defending string get more liberties are more
5086 * interesting.
5087 * 2) Moves adjacent to the most open liberties are more
5088 * interesting than those with fewer open liberties.
5089 * 3) Moves on the edge are less interesting.
5090 *
5091 * Moves below first_move are ignored and assumed to be sorted already.
5092 */
5093
5094static void
5095order_moves(int str, struct reading_moves *moves, int color,
5096 const char *funcname, int killer)
5097{
5098 int string_color = board[str];
5099 int string_libs = countlib(str);
5100 int r;
5101 int i, j;
5102
5103 /* Don't bother sorting if only one move, or none at all. */
5104 if (moves->num - moves->num_tried < 2) {
5105 /* But let's still have a single candidate in the sgf output */
5106 if (sgf_dumptree && moves->num > moves->num_tried)
5107 sgf_dumpmoves(moves, funcname);
5108 return;
5109 }
5110
5111 /* Assign a score to each move. */
5112 for (r = moves->num_tried; r < moves->num; r++) {
5113 int move = moves->pos[r];
5114
5115 /* Look at the neighbors of this move and count the things we
5116 * find. Friendly and opponent stones are related to color, i.e.
5117 * the player to move, not to the color of the string.
5118 */
5119 int number_edges = 0; /* outside board */
5120 int number_same_string = 0; /* the string being attacked */
5121 int number_own = 0; /* friendly stone */
5122 int number_opponent = 0; /* opponent stone */
5123 int captured_stones = 0; /* number of stones captured by this move */
5124 int threatened_stones = 0; /* number of stones threatened by this move */
5125 int saved_stones = 0; /* number of stones in atari saved */
5126 int number_open = 0; /* empty intersection */
5127
5128 /* We let the incremental_board code do the heavy work. */
5129 incremental_order_moves(move, color, str, &number_edges,
5130 &number_same_string, &number_own,
5131 &number_opponent, &captured_stones,
5132 &threatened_stones, &saved_stones, &number_open);
5133
5134 if (0)
5135 gprintf("%o %1m values: %d %d %d %d %d %d %d %d\n", move, number_edges,
5136 number_same_string, number_own, number_opponent, captured_stones,
5137 threatened_stones, saved_stones, number_open);
5138
5139 /* Different score strategies depending on whether the move is
5140 * attacking or defending the string.
5141 */
5142 if (color == string_color) {
5143 /* Defense move.
5144 *
5145 * 1) Add twice the number of liberties the group receives by
5146 * extending to the intersection of the move, if more than one.
5147 * Only applicable if the move is adjacent to the group.
5148 */
5149
5150 int libs = approxlib(move, color, 10, NULL);
5151 if (number_same_string > 0) {
5152 if (libs > 5 || (libs == 4 && stackp > fourlib_depth))
5153 moves->score[r] += defend_lib_score[5] + (libs - 4);
5154 else
5155 moves->score[r] += defend_lib_score[libs];
5156 }
5157 else {
5158 /* Add points for the number of liberties the played stone
5159 * obtains when not adjacent to the attacked string.
5160 */
5161 if (libs > 4)
5162 moves->score[r] += defend_not_adjacent_lib_score[4];
5163 else
5164 moves->score[r] += defend_not_adjacent_lib_score[libs];
5165 }
5166
5167 /* 2) Add the number of open liberties near the move to its score. */
5168 gg_assert(number_open <= 4);
5169 moves->score[r] += defend_open_score[number_open];
5170
5171 /* 3) Add a bonus if the move is not on the edge.
5172 */
5173 if (number_edges == 0 || captured_stones > 0)
5174 moves->score[r] += defend_not_edge_score;
5175
5176 /* 4) Add thrice the number of captured stones. */
5177 if (captured_stones <= 5)
5178 moves->score[r] += defend_capture_score[captured_stones];
5179 else
5180 moves->score[r] += defend_capture_score[5] + captured_stones;
5181
5182 /* 5) Add points for stones put into atari, unless this is a
5183 * self atari.
5184 */
5185 if (libs + captured_stones > 1) {
5186 if (threatened_stones <= 5)
5187 moves->score[r] += defend_atari_score[threatened_stones];
5188 else
5189 moves->score[r] += defend_atari_score[5] + threatened_stones;
5190 }
5191
5192 /* 6) Add a bonus for saved stones. */
5193 if (saved_stones <= 5)
5194 moves->score[r] += defend_save_score[saved_stones];
5195 else
5196 moves->score[r] += defend_save_score[5];
5197 }
5198 else {
5199 /* Attack move.
5200 *
5201 * 1) Add the number of liberties the attacker gets when playing
5202 * there, but never more than four.
5203 */
5204 int libs = approxlib(move, color, 4, NULL);
5205 if (libs > 4)
5206 libs = 4;
5207 moves->score[r] += attack_own_lib_score[libs];
5208
5209 if (libs == 0 && captured_stones == 1)
5210 moves->score[r] += attack_ko_score;
5211
5212 /* 2) If the move is not a self atari and adjacent to the
5213 * string, add the number of liberties the opponent would
5214 * gain by playing there. If the string has two liberties,
5215 * self-ataris are also ok since they may be snapbacks, but
5216 * only if a single stone is sacrificed.
5217 */
5218 if ((libs + captured_stones > 1 || (string_libs <= 2 && number_own == 0))
5219 && number_same_string > 0) {
5220 int safe_atari;
5221 int liberties = approxlib(move, string_color, 5, NULL);
5222 if (liberties > 5 || (liberties == 4 && stackp > fourlib_depth))
5223 liberties = 5;
5224 moves->score[r] += attack_string_lib_score[liberties];
5225
5226 safe_atari = (string_libs <= 2 && libs + captured_stones > 1);
5227 /* The defender can't play here without getting into atari, so
5228 * we probably souldn't either.
5229 */
5230 if (liberties == 1 && saved_stones == 0 && !safe_atari)
5231 moves->score[r] += cannot_defend_penalty;
5232
5233 /* Bonus if we put the attacked string into atari without
5234 * ourselves getting into atari.
5235 */
5236 if (safe_atari)
5237 moves->score[r] += safe_atari_score;
5238 }
5239
5240 /* 3) Add the number of open liberties near the move to its score. */
5241 gg_assert(number_open <= 4);
5242 moves->score[r] += attack_open_score[number_open];
5243
5244 /* 4) Add a bonus if the move is not on the edge. */
5245 if (number_edges == 0)
5246 moves->score[r] += attack_not_edge_score;
5247
5248 /* 5) Add twice the number of captured stones. */
5249 if (captured_stones <= 5)
5250 moves->score[r] += attack_capture_score[captured_stones];
5251 else
5252 moves->score[r] += attack_capture_score[5];
5253
5254 /* 6) Add a bonus for saved stones. */
5255 if (saved_stones <= 5)
5256 moves->score[r] += attack_save_score[saved_stones];
5257 else
5258 moves->score[r] += attack_save_score[5];
5259 }
5260 if (moves->pos[r] == killer)
5261 moves->score[r] += 50;
5262 }
5263
5264 /* Now sort the moves. We use selection sort since this array will
5265 * probably never be more than 10 moves long. In this case, the
5266 * overhead imposed by quicksort will probably overshadow the gains
5267 * given by the O(n*log(n)) behaviour over the O(n^2) behaviour of
5268 * selection sort.
5269 */
5270 for (i = moves->num_tried; i < moves->num-1; i++) {
5271 int maxscore = moves->score[i];
5272 int max_at = 0; /* This is slightly faster than max_at = i. */
5273
5274 /* Find the move with the biggest score. */
5275 for (j = i + 1; j < moves->num; j++) {
5276 if (moves->score[j] > maxscore) {
5277 maxscore = moves->score[j];
5278 max_at = j;
5279 }
5280 }
5281
5282 /* Now exchange the move at i with the move at max_at.
5283 * Don't forget to exchange the scores as well.
5284 */
5285 if (max_at != 0) {
5286 int temp = moves->pos[max_at];
5287 const char *temp_message = moves->message[max_at];
5288
5289 moves->pos[max_at] = moves->pos[i];
5290 moves->score[max_at] = moves->score[i];
5291 moves->message[max_at] = moves->message[i];
5292
5293 moves->pos[i] = temp;
5294 moves->score[i] = maxscore;
5295 moves->message[i] = temp_message;
5296 }
5297 }
5298
5299
5300 if (0) {
5301 gprintf("%oVariation %d:\n", count_variations);
5302 for (i = moves->num_tried; i < moves->num; i++)
5303 gprintf("%o %1M %d\n", moves->pos[i], moves->score[i]);
5304 }
5305
5306 if (sgf_dumptree)
5307 sgf_dumpmoves(moves, funcname);
5308}
5309
5310
5311/* Set new values for the move ordering parameters. */
5312void
5313tune_move_ordering(int params[MOVE_ORDERING_PARAMETERS])
5314{
5315 int k;
5316 for (k = 0; k < 6; k++) {
5317 defend_lib_score[k] = params[k];
5318 if (k < 5)
5319 defend_not_adjacent_lib_score[k] = params[k + 6];
5320 defend_capture_score[k] = params[k + 11];
5321 defend_atari_score[k] = params[k + 17];
5322 defend_save_score[k] = params[k + 23];
5323 if (k < 5) {
5324 defend_open_score[k] = params[k + 29];
5325 attack_own_lib_score[k] = params[k + 34];
5326 }
5327 attack_string_lib_score[k] = params[k + 39];
5328 attack_capture_score[k] = params[k + 45];
5329 attack_save_score[k] = params[k + 51];
5330 if (k < 5)
5331 attack_open_score[k] = params[k + 57];
5332 }
5333 defend_not_edge_score = params[62];
5334 attack_not_edge_score = params[63];
5335 attack_ko_score = params[64];
5336 cannot_defend_penalty = params[65];
5337 safe_atari_score = params[66];
5338
5339 if (verbose) {
5340 gprintf("static int defend_lib_score[6] = {%d, %d, %d, %d, %d, %d};\n",
5341 defend_lib_score[0], defend_lib_score[1],
5342 defend_lib_score[2], defend_lib_score[3],
5343 defend_lib_score[4], defend_lib_score[5]);
5344 gprintf("static int defend_not_adjacent_lib_score[5] = {%d, %d, %d, %d, %d};\n",
5345 defend_not_adjacent_lib_score[0], defend_not_adjacent_lib_score[1],
5346 defend_not_adjacent_lib_score[2], defend_not_adjacent_lib_score[3],
5347 defend_not_adjacent_lib_score[4]);
5348 gprintf("static int defend_capture_score[6] = {%d, %d, %d, %d, %d, %d};\n",
5349 defend_capture_score[0], defend_capture_score[1],
5350 defend_capture_score[2], defend_capture_score[3],
5351 defend_capture_score[4], defend_capture_score[5]);
5352 gprintf("static int defend_atari_score[6] = {%d, %d, %d, %d, %d, %d};\n",
5353 defend_atari_score[0], defend_atari_score[1],
5354 defend_atari_score[2], defend_atari_score[3],
5355 defend_atari_score[4], defend_atari_score[5]);
5356 gprintf("static int defend_save_score[6] = {%d, %d, %d, %d, %d, %d};\n",
5357 defend_save_score[0], defend_save_score[1],
5358 defend_save_score[2], defend_save_score[3],
5359 defend_save_score[4], defend_save_score[5]);
5360 gprintf("static int defend_open_score[5] = {%d, %d, %d, %d, %d};\n",
5361 defend_open_score[0], defend_open_score[1],
5362 defend_open_score[2], defend_open_score[3],
5363 defend_open_score[4]);
5364 gprintf("static int attack_own_lib_score[5] = {%d, %d, %d, %d, %d};\n",
5365 attack_own_lib_score[0], attack_own_lib_score[1],
5366 attack_own_lib_score[2], attack_own_lib_score[3],
5367 attack_own_lib_score[4]);
5368 gprintf("static int attack_string_lib_score[6] = {%d, %d, %d, %d, %d, %d};\n",
5369 attack_string_lib_score[0], attack_string_lib_score[1],
5370 attack_string_lib_score[2], attack_string_lib_score[3],
5371 attack_string_lib_score[4], attack_string_lib_score[5]);
5372 gprintf("static int attack_capture_score[6] = {%d, %d, %d, %d, %d, %d};\n",
5373 attack_capture_score[0], attack_capture_score[1],
5374 attack_capture_score[2], attack_capture_score[3],
5375 attack_capture_score[4], attack_capture_score[5]);
5376 gprintf("static int attack_save_score[6] = {%d, %d, %d, %d, %d, %d};\n",
5377 attack_save_score[0], attack_save_score[1],
5378 attack_save_score[2], attack_save_score[3],
5379 attack_save_score[4], attack_save_score[5]);
5380 gprintf("static int attack_open_score[5] = {%d, %d, %d, %d, %d};\n",
5381 attack_open_score[0], attack_open_score[1],
5382 attack_open_score[2], attack_open_score[3],
5383 attack_open_score[4]);
5384 gprintf("static int defend_not_edge_score = %d;\n", defend_not_edge_score);
5385 gprintf("static int attack_not_edge_score = %d;\n", attack_not_edge_score);
5386 gprintf("static int attack_ko_score = %d;\n", attack_ko_score);
5387 gprintf("static int cannot_defend_penalty = %d;\n", cannot_defend_penalty);
5388 gprintf("static int safe_atari_score = %d;\n", safe_atari_score);
5389 }
5390}
5391
5392
5393
5394/* ================================================================ */
5395/* Reading utilities */
5396/* ================================================================ */
5397
5398
5399static int safe_move_cache[BOARDMAX][2];
5400static int safe_move_cache_when[BOARDMAX][2];
5401static void clear_safe_move_cache(void);
5402
5403static void
5404clear_safe_move_cache(void)
5405{
5406 int k;
5407
5408 for (k = BOARDMIN; k < BOARDMAX; k++) {
5409 safe_move_cache_when[k][0] = -1;
5410 safe_move_cache_when[k][1] = -1;
5411 }
5412}
5413
5414/* safe_move(move, color) checks whether a move at (move) is illegal
5415 * or can immediately be captured. If stackp==0 the result is cached.
5416 * If the move only can be captured by a ko, it's considered safe.
5417 * This may or may not be a good convention.
5418 *
5419 * For performance reasons, the result of this function is cached.
5420 */
5421
5422int
5423safe_move(int move, int color)
5424{
5425 int safe = 0;
5426 static int initialized = 0;
5427 int ko_move;
5428
5429 if (!initialized) {
5430 clear_safe_move_cache();
5431 initialized = 1;
5432 }
5433
5434 /* If we have this position cached, use the previous value.
5435 * Only use cached values when stackp is 0 and reading is not being done
5436 * at a modified depth.
5437 */
5438 if (stackp == 0
5439 && depth_offset == 0
5440 && safe_move_cache_when[move][color == BLACK] == position_number)
5441 return safe_move_cache[move][color == BLACK];
5442
5443 /* Otherwise calculate the value... */
5444 if (komaster_trymove(move, color, "safe_move", 0, &ko_move, 1)) {
5445 safe = REVERSE_RESULT(attack(move, NULL));
5446 if (ko_move && safe != 0)
5447 safe = KO_B;
5448 popgo();
5449 }
5450
5451 /* ...and store it in the cache.
5452 * FIXME: Only store result in cache when we're working at
5453 * full depth.
5454 *
5455 * Comment: This is currently not a problem since no reduced depth
5456 * reading is performed.
5457 */
5458 if (stackp == 0 && depth_offset == 0) {
5459 if (0)
5460 gprintf("Safe move at %1m for %s cached when depth=%d, position number=%d\n",
5461 move, color_to_string(color), depth, position_number);
5462 safe_move_cache_when[move][color == BLACK] = position_number;
5463 safe_move_cache[move][color == BLACK] = safe;
5464 }
5465
5466 return safe;
5467}
5468
5469
5470/* Checks if a move by color makes an opponent move at pos a self atari.
5471 */
5472int
5473does_secure(int color, int move, int pos)
5474{
5475 int result = 0;
5476 if (trymove(move, color, NULL, NO_MOVE)) {
5477 if (is_self_atari(pos, OTHER_COLOR(color)))
5478 result = 1;
5479 popgo();
5480 }
5481
5482 return result;
5483}
5484
5485
5486/* ===================== Statistics ============================= */
5487
5488
5489/* Clear statistics. */
5490void
5491reset_reading_node_counter()
5492{
5493 reading_node_counter = 0;
5494}
5495
5496
5497/* Retrieve statistics. */
5498int
5499get_reading_node_counter()
5500{
5501 return reading_node_counter;
5502}
5503
5504/* ============ Reading shadow =============== */
5505
5506/* Draw the reading shadow, for debugging purposes */
5507
5508void
5509draw_reading_shadow()
5510{
5511 int i, j;
5512 int c = ' ';
5513 int pos;
5514
5515 start_draw_board();
5516
5517 for (i = 0; i < board_size; i++) {
5518 fprintf(stderr, "\n%2d", board_size - i);
5519
5520 for (j = 0; j < board_size; j++) {
5521 pos = POS(i, j);
5522 if (!shadow[pos] && board[pos] == EMPTY)
5523 c = '.';
5524 else if (!shadow[pos] && board[pos] == WHITE)
5525 c = 'O';
5526 else if (!shadow[pos] && board[pos] == BLACK)
5527 c = 'X';
5528 if (shadow[pos] && board[pos] == EMPTY)
5529 c = ',';
5530 else if (shadow[pos] && board[pos] == WHITE)
5531 c = 'o';
5532 else if (shadow[pos] && board[pos] == BLACK)
5533 c = 'x';
5534
5535 fprintf(stderr, " %c", c);
5536 }
5537
5538 fprintf(stderr, " %d", board_size - i);
5539 }
5540
5541 end_draw_board();
5542}
5543
5544
5545/* ================================================================ */
5546/* Code for special purposes. */
5547/* ================================================================ */
5548
5549/* simple_ladder(str, &move) tries to capture a string (str)
5550 * with exactly two liberties under simplified assumptions, which are
5551 * adequate in a ladder. The rules are as follows:
5552 *
5553 * 1. The attacker is allowed to play at each of the two liberties,
5554 * but no other move. If the move was legal, the string now has
5555 * exactly one liberty.
5556 * 2. The defender must move out of atari. This can only be done by
5557 * either extending at the liberty or capturing a neighboring
5558 * string which was in atari. All such moves may be tested.
5559 * 3. Depending on the resulting number of liberties of the string
5560 * after the defender's move, we value each node as follows:
5561 *
5562 * 3 or more liberties: the attack has failed
5563 * 2 liberties: recurse
5564 * 1 liberty: the attack has succeeded
5565 *
5566 * illegal move for the defender: successful attack
5567 * illegal move for the attacker: failed attack
5568 *
5569 * Return codes are as usual 0 for failure, WIN for success, KO_A for
5570 * a ko where the defender must make the first ko threat and KO_B for
5571 * a ko where the attacked has to make the first threat. If the attack
5572 * was successful, (*move) contains the attacking move, unless it is a
5573 * null pointer.
5574 *
5575 * The differences compared to the attack2()/defend1() combination for
5576 * reading ladders is that this one is a strict ladder reader which
5577 * never allows the defender to have more than one liberty when it's
5578 * in turn to move. This has a number of consequences.
5579 *
5580 * 1. This function will miss tactical captures involving other
5581 * techniques than the ladder.
5582 *
5583 * 2. This function is faster because it gives up faster when the
5584 * ladder doesn't work. In particular it can't branch out in a huge
5585 * tree of exotic variations.
5586 *
5587 * 3. This function always reads ladders to the very end. There are no
5588 * depth limits or other assumptions to stop reading prematurely.
5589 *
5590 * 4. If this function returns WIN, it is guaranteed that the defender
5591 * has no way whatsoever to escape, all possibilities are tried.
5592 * The converse is definitely not true.
5593 */
5594
5595int
5596simple_ladder(int str, int *move)
5597{
5598 int color = board[str];
5599 int other = OTHER_COLOR(color);
5600 int apos;
5601 int libs[2];
5602 int savemove = 0;
5603 int savecode = 0;
5604 int dcode;
5605 int k;
5606 struct reading_moves moves;
5607
5608 SETUP_TRACE_INFO("simple_ladder", str);
5609 reading_node_counter++;
5610 moves.num = 0;
5611 moves.num_tried = 0;
5612
5613 str = find_origin(str);
5614 ASSERT1(IS_STONE(board[str]), str);
5615 ASSERT1(countlib(str) == 2, str);
5616
5617 /* Give up if we attacked depending on ko for too long. */
5618 if (stackp > depth + 20 && get_komaster() == OTHER_COLOR(board[str])) {
5619 SGFTRACE(0, 0, NULL);
5620 if (move)
5621 *move = PASS_MOVE;
5622 return 0;
5623 }
5624
5625 /* Get the two liberties of (str). */
5626 findlib(str, 2, libs);
5627
5628 /* If the defender can get enough liberties by playing one of these
5629 * two, then we have no choice but to block there and consequently,
5630 * it is unnecesary to try the other liberty.
5631 */
5632
5633 if (approxlib(libs[0], color, 4, NULL) <= 3)
5634 ADD_CANDIDATE_MOVE(libs[1], 0, moves, "simple_ladder");
5635 if (approxlib(libs[1], color, 4, NULL) <= 3)
5636 ADD_CANDIDATE_MOVE(libs[0], 0, moves, "simple_ladder");
5637
5638 order_moves(str, &moves, other, read_function_name, NO_MOVE);
5639
5640 for (k = 0; k < moves.num; k++) {
5641 int ko_move;
5642
5643 apos = moves.pos[k];
5644 if (komaster_trymove(apos, other, moves.message[k], str,
5645 &ko_move, savecode == 0)) {
5646 if (!ko_move) {
5647 dcode = simple_ladder_defend(str, NULL);
5648 if (dcode != WIN) {
5649 if (dcode == 0) {
5650 popgo();
5651 SGFTRACE(apos, WIN, "attack effective");
5652 if (move)
5653 *move = apos;
5654 return WIN;
5655 }
5656 UPDATE_SAVED_KO_RESULT(savecode, savemove, dcode, apos);
5657 }
5658 }
5659 else {
5660 if (simple_ladder_defend(str, NULL) != WIN) {
5661 savemove = apos;
5662 savecode = KO_B;
5663 }
5664 }
5665 popgo();
5666 }
5667 }
5668
5669 RETURN_RESULT(savecode, savemove, move, "saved move");
5670}
5671
5672
5673static int
5674simple_ladder_defend(int str, int *move)
5675{
5676 int color = board[str];
5677 int xpos;
5678 int lib;
5679 struct reading_moves moves;
5680 int savemove = 0;
5681 int savecode = 0;
5682 int k;
5683
5684 SETUP_TRACE_INFO("simple_ladder_defend", str);
5685 reading_node_counter++;
5686
5687 ASSERT1(IS_STONE(board[str]), str);
5688 ASSERT1(countlib(str) == 1, str);
5689
5690 /* lib will be the liberty of the string. */
5691 findlib(str, 1, &lib);
5692
5693 moves.pos[0] = lib;
5694 moves.score[0] = 0;
5695 moves.message[0] = "liberty";
5696 moves.num = 1;
5697 moves.num_tried = 0;
5698
5699 break_chain_moves(str, &moves);
5700 order_moves(str, &moves, color, read_function_name, NO_MOVE);
5701
5702 for (k = 0; k < moves.num; k++) {
5703 int ko_move;
5704
5705 xpos = moves.pos[k];
5706 if (komaster_trymove(xpos, color, moves.message[k], str,
5707 &ko_move, savecode == 0)) {
5708 int acode;
5709 int new_libs = countlib(str);
5710 if (new_libs > 2)
5711 acode = 0;
5712 else if (new_libs < 2)
5713 acode = WIN;
5714 else
5715 acode = simple_ladder(str, NULL);
5716 popgo();
5717
5718 if (!ko_move)
5719 CHECK_RESULT(savecode, savemove, acode, xpos, move,
5720 "defense effective");
5721 else {
5722 if (acode != WIN) {
5723 savemove = xpos;
5724 savecode = KO_B;
5725 }
5726 }
5727 }
5728 }
5729
5730 RETURN_RESULT(savecode, savemove, move, "saved move");
5731}
5732
5733
5734/*
5735 * Local Variables:
5736 * tab-width: 8
5737 * c-basic-offset: 2
5738 * End:
5739 */