4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 # analysis, or for live analysis of relayed games. (Do not use for
6 # cheating! Cheating is bad for your karma, and your abuser flag.)
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
20 my $server = "freechess.org";
21 my $target = "GMCarlsen";
22 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
23 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
24 my $telltarget = undef; # undef to be silent
25 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960); # after each move
26 my $uci_assume_full_compliance = 0; # dangerous :-)
27 my $update_max_interval = 2.0;
28 my $second_engine_start_depth = 8;
38 $SIG{ALRM} = sub { output_screen(); };
39 my $latest_update = undef;
43 open(FICSLOG, ">ficslog.txt")
44 or die "ficslog.txt: $!";
45 print FICSLOG "Log starting.\n";
49 open(UCILOG, ">ucilog.txt")
50 or die "ucilog.txt: $!";
51 print UCILOG "Log starting.\n";
56 # open the chess engine
57 my $engine = open_engine($engine_cmdline, 'E1');
58 my $engine2 = open_engine($engine2_cmdline, 'E2');
59 my ($last_move, $last_tell);
61 my $last_told_text = '';
62 my ($pos_waiting, $pos_calculating, $move_calculating_second_engine);
63 my %refutation_moves = ();
65 uciprint($engine, "setoption name UCI_AnalyseMode value true");
66 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
67 uciprint($engine, "setoption name NalimovUsage value Rarely");
68 uciprint($engine, "setoption name Hash value 1024");
69 # uciprint($engine, "setoption name MultiPV value 2");
70 uciprint($engine, "ucinewgame");
72 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
73 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
74 uciprint($engine2, "setoption name NalimovUsage value Rarely");
75 uciprint($engine2, "setoption name Hash value 1024");
76 uciprint($engine2, "setoption name Threads value 8");
77 # uciprint($engine2, "setoption name MultiPV value 2");
78 uciprint($engine2, "ucinewgame");
80 print "Chess engine ready.\n";
83 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
84 $t->input_log(\*FICSLOG);
86 $t->print("SesseBOT");
87 $t->waitfor('/Press return to enter the server/');
91 $t->cmd("set shout 0");
92 $t->cmd("set seek 0");
93 $t->cmd("set style 12");
94 $t->cmd("observe $target");
97 print "FICS ready.\n";
101 vec($rin, fileno($engine->{'read'}), 1) = 1;
102 vec($rin, fileno($engine2->{'read'}), 1) = 1;
103 vec($rin, fileno($t), 1) = 1;
105 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
109 my $line = $t->getline(Timeout => 0, errmode => 'return');
110 last if (!defined($line));
114 if ($line =~ /^<12> /) {
115 my $pos = style12_to_pos($line);
117 # if this is already in the queue, ignore it
118 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
120 # if we're already chewing on this and there's nothing else in the queue,
122 next if (!defined($pos_waiting) && defined($pos_calculating) &&
123 $pos->{'fen'} eq $pos_calculating->{'fen'});
125 # if we're already thinking on something, stop and wait for the engine
127 if (defined($pos_calculating)) {
128 if (!defined($pos_waiting)) {
129 uciprint($engine, "stop");
131 if ($uci_assume_full_compliance) {
134 uciprint($engine, "position fen " . $pos->{'fen'});
135 uciprint($engine, "go infinite");
136 $pos_calculating = $pos;
139 # it's wrong just to give the FEN (the move history is useful,
140 # and per the UCI spec, we should really have sent "ucinewgame"),
142 uciprint($engine, "position fen " . $pos->{'fen'});
143 uciprint($engine, "go infinite");
144 $pos_calculating = $pos;
147 %refutation_moves = calculate_refutation_moves($pos);
148 if (defined($move_calculating_second_engine)) {
149 uciprint($engine2, "stop");
150 $move_calculating_second_engine = undef;
152 give_new_move_to_second_engine($pos);
155 $engine->{'info'} = {};
156 $engine2->{'info'} = {};
160 # Output a command every move to note that we're
161 # still paying attention -- this is a good tradeoff,
162 # since if no move has happened in the last half
163 # hour, the analysis/relay has most likely stopped
164 # and we should stop hogging server resources.
168 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
169 my ($who, $msg) = ($1, $2);
171 next if (grep { $_ eq $who } (@masters) == 0);
173 if ($msg =~ /^fics (.*?)$/) {
174 $t->cmd("tell $who Executing '$1' on FICS.");
176 } elsif ($msg =~ /^uci (.*?)$/) {
177 $t->cmd("tell $who Sending '$1' to the engine.");
178 print { $engine->{'write'} } "$1\n";
180 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
183 #print "FICS: [$line]\n";
187 # any fun on the UCI channel?
188 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
189 my @lines = read_lines($engine);
190 for my $line (@lines) {
191 next if $line =~ /(upper|lower)bound/;
192 handle_uci($engine, $line, 1);
198 if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
199 my @lines = read_lines($engine2);
200 for my $line (@lines) {
201 next if $line =~ /(upper|lower)bound/;
202 handle_uci($engine2, $line, 0);
213 my ($engine, $line, $primary) = @_;
217 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
218 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
219 if ($line =~ /^info/) {
220 my (@infos) = split / /, $line;
223 parse_infos($engine, @infos);
225 if ($line =~ /^id/) {
226 my (@ids) = split / /, $line;
229 parse_ids($engine, @ids);
231 if ($line =~ /^bestmove/) {
233 return if (!$uci_assume_full_compliance);
234 if (defined($pos_waiting)) {
235 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
236 uciprint($engine, "go infinite");
238 $pos_calculating = $pos_waiting;
239 $pos_waiting = undef;
242 if (defined($move_calculating_second_engine)) {
243 my $move = $refutation_moves{$move_calculating_second_engine};
244 $move->{'pv'} = $engine->{'info'}{'pv'} // $engine->{'info'}{'pv1'};
245 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
246 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
247 $move->{'toplay'} = $pos_calculating->{'toplay'};
249 give_new_move_to_second_engine($pos_waiting // $pos_calculating);
255 my ($engine, @x) = @_;
258 my $info = $engine->{'info'};
260 while (scalar @x > 0) {
261 if ($x[0] =~ 'multipv') {
266 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
268 my $value = shift @x;
269 $info->{$key} = $value;
272 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
274 my $value = shift @x;
275 $info->{$key . $mpv} = $value;
278 if ($x[0] eq 'score') {
281 delete $info->{'score_cp' . $mpv};
282 delete $info->{'score_mate' . $mpv};
284 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
287 $info->{'score_cp' . $mpv} = shift @x;
288 } elsif ($x[0] eq 'mate') {
290 $info->{'score_mate' . $mpv} = shift @x;
298 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
301 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
305 #print "unknown info '$x[0]', trying to recover...\n";
307 die "Unknown info '" . join(',', @x) . "'";
313 my ($engine, @x) = @_;
315 while (scalar @x > 0) {
316 if ($x[0] =~ /^(name|author)$/) {
318 my $value = join(' ', @x);
319 $engine->{'id'}{$key} = $value;
331 my (@x) = split / /, $str;
333 $pos{'board'} = [ @x[1..8] ];
334 $pos{'toplay'} = $x[9];
335 $pos{'ep_file_num'} = $x[10];
336 $pos{'white_castle_k'} = $x[11];
337 $pos{'white_castle_q'} = $x[12];
338 $pos{'black_castle_k'} = $x[13];
339 $pos{'black_castle_q'} = $x[14];
340 $pos{'time_to_100move_rule'} = $x[15];
341 $pos{'move_num'} = $x[26];
342 $pos{'last_move'} = $x[29];
343 $pos{'fen'} = make_fen(\%pos);
352 my (@board) = @{$pos->{'board'}};
353 for my $rank (0..7) {
354 $board[$rank] =~ s/(-+)/length($1)/ge;
356 my $fen = join('/', @board);
358 # white/black to move
360 $fen .= lc($pos->{'toplay'});
364 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
365 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
366 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
367 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
368 $castling = "-" if ($castling eq "");
369 # $castling = "-"; # chess960
375 if ($pos->{'ep_file_num'} != -1) {
376 my $col = $pos->{'ep_file_num'};
377 my $nep = (qw(a b c d e f g h))[$col];
379 if ($pos->{'toplay'} eq 'B') {
386 # Showing the en passant square when actually no capture can be made
387 # seems to confuse at least Rybka. Thus, check if there's actually
388 # a pawn of the opposite side that can do the en passant move, and if
389 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
390 # "right" thing as per the standard, though.
392 if ($pos->{'toplay'} eq 'B') {
393 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
394 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
396 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
397 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
405 $fen .= $pos->{'time_to_100move_rule'};
409 $fen .= $pos->{'move_num'};
415 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
416 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
417 my $piece = substr($board->[$from_row], $from_col, 1);
421 die "Invalid move $move";
424 # white short castling
425 if ($move eq 'e1g1' && $piece eq 'K') {
427 substr($nb[7], 4, 1, '-');
428 substr($nb[7], 6, 1, $piece);
431 substr($nb[7], 7, 1, '-');
432 substr($nb[7], 5, 1, 'R');
437 # white long castling
438 if ($move eq 'e1c1' && $piece eq 'K') {
440 substr($nb[7], 4, 1, '-');
441 substr($nb[7], 2, 1, $piece);
444 substr($nb[7], 0, 1, '-');
445 substr($nb[7], 3, 1, 'R');
450 # black short castling
451 if ($move eq 'e8g8' && $piece eq 'k') {
453 substr($nb[0], 4, 1, '-');
454 substr($nb[0], 6, 1, $piece);
457 substr($nb[0], 7, 1, '-');
458 substr($nb[0], 5, 1, 'r');
463 # black long castling
464 if ($move eq 'e8c8' && $piece eq 'k') {
466 substr($nb[0], 4, 1, '-');
467 substr($nb[0], 2, 1, $piece);
470 substr($nb[0], 0, 1, '-');
471 substr($nb[0], 3, 1, 'r');
476 # check if the from-piece is a pawn
477 if (lc($piece) eq 'p') {
479 if ($from_col != $to_col) {
481 if (substr($board->[$to_row], $to_col, 1) eq '-') {
483 substr($nb[$to_row + 1], $to_col, 1, '-');
485 substr($nb[$to_row - 1], $to_col, 1, '-');
500 substr($nb[$from_row], $from_col, 1, '-');
501 substr($nb[$to_row], $to_col, 1, $piece);
507 my ($board, @pvs) = @_;
509 if (scalar @pvs == 0 || !defined($pvs[0])) {
514 my $from_col = col_letter_to_num(substr($pv, 0, 1));
515 my $from_row = row_letter_to_num(substr($pv, 1, 1));
516 my $to_col = col_letter_to_num(substr($pv, 2, 1));
517 my $to_row = row_letter_to_num(substr($pv, 3, 1));
518 my $promo = substr($pv, 4, 1);
520 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
521 my $piece = substr($board->[$from_row], $from_col, 1);
524 die "Invalid move $pv";
527 # white short castling
528 if ($pv eq 'e1g1' && $piece eq 'K') {
529 return ('0-0', prettyprint_pv($nb, @pvs));
532 # white long castling
533 if ($pv eq 'e1c1' && $piece eq 'K') {
534 return ('0-0-0', prettyprint_pv($nb, @pvs));
537 # black short castling
538 if ($pv eq 'e8g8' && $piece eq 'k') {
539 return ('0-0', prettyprint_pv($nb, @pvs));
542 # black long castling
543 if ($pv eq 'e8c8' && $piece eq 'k') {
544 return ('0-0-0', prettyprint_pv($nb, @pvs));
549 # check if the from-piece is a pawn
550 if (lc($piece) eq 'p') {
552 if ($from_col != $to_col) {
553 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
555 $pretty = substr($pv, 2, 2);
557 if (length($pv) == 5) {
560 $pretty .= uc(substr($pv, 4, 1));
563 $piece = substr($pv, 4, 1);
565 $piece = uc(substr($pv, 4, 1));
570 $pretty = uc($piece);
572 # see how many of these pieces could go here, in all
576 next unless (substr($board->[$row], $col, 1) eq $piece);
577 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
581 # see how many of these pieces from the given row could go here
584 next unless (substr($board->[$from_row], $col, 1) eq $piece);
585 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
588 # and same for columns
591 next unless (substr($board->[$row], $from_col, 1) eq $piece);
592 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
595 # see if we need to disambiguate
596 if ($num_total > 1) {
598 $pretty .= substr($pv, 0, 1);
599 } elsif ($num_row == 1) {
600 $pretty .= substr($pv, 1, 1);
602 $pretty .= substr($pv, 0, 2);
607 if (substr($board->[$to_row], $to_col, 1) ne '-') {
611 $pretty .= substr($pv, 2, 2);
616 } elsif (in_check($nb) ne 'none') {
619 return ($pretty, prettyprint_pv($nb, @pvs));
625 return if (!defined($pos_calculating));
627 # Don't update too often.
628 my $age = Time::HiRes::tv_interval($latest_update);
629 if ($age < $update_max_interval) {
630 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
633 $latest_update = [Time::HiRes::gettimeofday];
635 my $info = $engine->{'info'};
636 my $id = $engine->{'id'};
639 # Check the PVs first. if they're invalid, just wait, as our data
640 # is most likely out of sync. This isn't a very good solution, as
641 # it can frequently miss stuff, but it's good enough for most users.
645 if (exists($info->{'pv'})) {
646 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
650 while (exists($info->{'pv' . $mpv})) {
651 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
656 $engine->{'info'} = {};
660 my $text = 'Analysis';
661 if ($pos_calculating->{'last_move'} ne 'none') {
662 if ($pos_calculating->{'toplay'} eq 'W') {
663 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
665 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
667 if (exists($id->{'name'})) {
672 if (exists($id->{'name'})) {
673 $text .= " by $id->{'name'}:\n\n";
678 return unless (exists($pos_calculating->{'board'}));
681 # Some programs _always_ report MultiPV, even with only one PV.
682 # In this case, we simply use that data as if MultiPV was never
685 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
686 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
687 if (exists($info->{$key . '1'}) && !exists($info->{$key})) {
688 $info->{$key} = $info->{$key . '1'};
693 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
696 while (exists($info->{'pv' . $mpv})) {
697 $text .= sprintf " PV%2u", $mpv;
698 my $score = short_score($info, $pos_calculating, $mpv);
699 $text .= " ($score)" if (defined($score));
702 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
703 if ($info->{'tbhits' . $mpv} == 1) {
704 $tbhits = ", 1 tbhit";
706 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
710 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
711 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
712 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
716 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
722 my $score = long_score($info, $pos_calculating, '');
723 $text .= " $score\n" if defined($score);
724 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
727 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
728 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
729 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
731 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
732 if ($info->{'tbhits'} == 1) {
733 $text .= ", one Nalimov hit";
735 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
738 if (exists($info->{'seldepth'})) {
739 $text .= sprintf " (%u selective)", $info->{'seldepth'};
744 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
746 my @refutation_lines = ();
747 for my $move (keys %refutation_moves) {
749 my $m = $refutation_moves{$move};
750 die if ($m->{'depth'} < $second_engine_start_depth);
751 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
752 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
753 if (scalar @pretty_pv > 5) {
754 @pretty_pv = @pretty_pv[0..4];
755 push @pretty_pv, "...";
757 #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
758 my $key = $pretty_move;
759 my $line = sprintf(" %-6s %6s %3s %s",
761 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
763 join(', ', @pretty_pv));
764 push @refutation_lines, [ $key, $line ];
768 if ($#refutation_lines >= 0) {
769 $text .= "Shallow search of all legal moves:\n\n";
770 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
771 $text .= $line->[1] . "\n";
776 if ($last_text ne $text) {
777 print "
\e[H
\e[2J"; # clear the screen
782 # Now construct the tell text, if any
783 return if (!defined($telltarget));
787 if (exists($id->{'name'})) {
788 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
790 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
793 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
796 while (exists($info->{'pv' . $mpv})) {
797 $tell_text .= sprintf " PV%2u", $mpv;
798 my $score = short_score($info, $pos_calculating, $mpv);
799 $tell_text .= " ($score)" if (defined($score));
801 if (exists($info->{'depth' . $mpv})) {
802 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
806 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
812 my $score = long_score($info, $pos_calculating, '');
813 $tell_text .= " $score\n" if defined($score);
814 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
815 if (exists($info->{'depth'})) {
816 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
821 # see if a new tell is called for -- it is if the delay has expired _and_
822 # this is not simply a repetition of the last one
823 if ($last_told_text ne $tell_text) {
825 for my $iv (@tell_intervals) {
826 last if ($now - $last_move < $iv);
827 next if ($last_tell - $last_move >= $iv);
829 for my $line (split /\n/, $tell_text) {
830 $t->print("tell $telltarget [$target] $line");
833 $last_told_text = $text;
843 my ($wkr, $wkc, $bkr, $bkc);
847 my $piece = substr($board->[$row], $col, 1);
849 ($wkr, $wkc) = ($row, $col);
850 } elsif ($piece eq 'k') {
851 ($bkr, $bkc) = ($row, $col);
856 return ($wkr, $wkc, $bkr, $bkc);
861 my $check = in_check($board);
862 return 0 if ($check eq 'none');
864 # try all possible moves for the side in check
867 my $piece = substr($board->[$row], $col, 1);
868 next if ($piece eq '-');
870 if ($check eq 'white') {
871 next if ($piece eq lc($piece));
873 next if ($piece eq uc($piece));
876 for my $dest_row (0..7) {
877 for my $dest_col (0..7) {
878 next if ($row == $dest_row && $col == $dest_col);
879 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
882 substr($nb[$row], $col, 1, '-');
883 substr($nb[$dest_row], $dest_col, 1, $piece);
885 my $new_check = in_check(\@nb);
886 return 0 if ($new_check ne $check && $new_check ne 'both');
892 # nothing to do; mate
898 my ($black_check, $white_check) = (0, 0);
900 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
902 # check all pieces for the possibility of threatening the two kings
905 my $piece = substr($board->[$row], $col, 1);
906 next if ($piece eq '-');
908 if (uc($piece) eq $piece) {
910 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
913 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
918 if ($black_check && $white_check) {
920 } elsif ($black_check) {
922 } elsif ($white_check) {
930 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
932 # can't eat your own piece
933 my $dest_piece = substr($board->[$to_row], $to_col, 1);
934 if ($dest_piece ne '-') {
935 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
938 if (lc($piece) eq 'k') {
939 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
941 if (lc($piece) eq 'r') {
942 return 0 unless ($from_row == $to_row || $from_col == $to_col);
944 # check that there's a clear passage
945 if ($from_row == $to_row) {
946 if ($from_col > $to_col) {
947 ($to_col, $from_col) = ($from_col, $to_col);
950 for my $c (($from_col+1)..($to_col-1)) {
951 my $middle_piece = substr($board->[$to_row], $c, 1);
952 return 0 if ($middle_piece ne '-');
957 if ($from_row > $to_row) {
958 ($to_row, $from_row) = ($from_row, $to_row);
961 for my $r (($from_row+1)..($to_row-1)) {
962 my $middle_piece = substr($board->[$r], $to_col, 1);
963 return 0 if ($middle_piece ne '-');
969 if (lc($piece) eq 'b') {
970 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
972 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
973 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
975 my $r = $from_row + $dr;
976 my $c = $from_col + $dc;
978 while ($r != $to_row) {
979 my $middle_piece = substr($board->[$r], $c, 1);
980 return 0 if ($middle_piece ne '-');
988 if (lc($piece) eq 'n') {
989 my $diff_r = abs($from_row - $to_row);
990 my $diff_c = abs($from_col - $to_col);
991 return 1 if ($diff_r == 2 && $diff_c == 1);
992 return 1 if ($diff_r == 1 && $diff_c == 2);
996 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
997 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1000 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1001 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1005 if ($piece eq 'p') {
1007 if ($to_col == $from_col && $to_row == $from_row + 1) {
1008 return ($dest_piece eq '-');
1010 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1011 my $middle_piece = substr($board->[2], $to_col, 1);
1012 return ($dest_piece eq '-' && $middle_piece eq '-');
1014 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1015 return ($dest_piece ne '-');
1019 if ($piece eq 'P') {
1021 if ($to_col == $from_col && $to_row == $from_row - 1) {
1022 return ($dest_piece eq '-');
1024 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1025 my $middle_piece = substr($board->[5], $to_col, 1);
1026 return ($dest_piece eq '-' && $middle_piece eq '-');
1028 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1029 return ($dest_piece ne '-');
1039 my ($engine, $msg) = @_;
1040 print { $engine->{'write'} } "$msg\n";
1041 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1045 my ($info, $pos, $mpv, $invert) = @_;
1048 if ($pos->{'toplay'} eq 'B') {
1052 if (defined($info->{'score_mate' . $mpv})) {
1054 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1056 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1059 if (exists($info->{'score_cp' . $mpv})) {
1060 my $score = $info->{'score_cp' . $mpv} * 0.01;
1064 return sprintf "%+5.2f", $score;
1071 sub score_sort_key {
1072 my ($info, $pos, $mpv, $invert) = @_;
1075 if ($pos->{'toplay'} eq 'B') {
1079 if (defined($info->{'score_mate' . $mpv})) {
1081 return -(99999 - $info->{'score_mate' . $mpv});
1083 return 99999 - $info->{'score_mate' . $mpv};
1086 if (exists($info->{'score_cp' . $mpv})) {
1087 my $score = $info->{'score_cp' . $mpv};
1099 my ($info, $pos, $mpv) = @_;
1101 if (defined($info->{'score_mate' . $mpv})) {
1102 my $mate = $info->{'score_mate' . $mpv};
1103 if ($pos->{'toplay'} eq 'B') {
1107 return sprintf "White mates in %u", $mate;
1109 return sprintf "Black mates in %u", -$mate;
1112 if (exists($info->{'score_cp' . $mpv})) {
1113 my $score = $info->{'score_cp' . $mpv} * 0.01;
1114 if ($pos->{'toplay'} eq 'B') {
1117 return sprintf "Score: %+5.2f", $score;
1124 my %book_cache = ();
1126 my ($fen, $board, $toplay) = @_;
1128 if (exists($book_cache{$fen})) {
1129 return $book_cache{$fen};
1132 my $ret = `./booklook $fen`;
1133 return "" if ($ret =~ /Not found/ || $ret eq '');
1137 for my $m (split /\n/, $ret) {
1138 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1142 $pmove = '(current)';
1144 ($pmove) = prettyprint_pv($board, $move);
1145 $pmove .= $annotation;
1149 if ($toplay eq 'W') {
1150 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1152 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1154 my $n = $win + $draw + $lose;
1160 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1163 push @moves, [ $pmove, $n, $percent, $rating ];
1166 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1168 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1169 for my $m (@moves) {
1170 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1177 my ($cmdline, $tag) = @_;
1178 my ($uciread, $uciwrite);
1179 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1191 uciprint($engine, "uci");
1193 # gobble the options
1194 while (<$uciread>) {
1196 handle_uci($engine, $_);
1206 # Read until we've got a full line -- if the engine sends part of
1207 # a line and then stops we're pretty much hosed, but that should
1210 while ($engine->{'readbuf'} !~ /\n/) {
1212 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1214 if (!defined($ret)) {
1215 next if ($!{EINTR});
1216 die "error in reading from the UCI engine: $!";
1217 } elsif ($ret == 0) {
1218 die "EOF from UCI engine";
1221 $engine->{'readbuf'} .= $tmp;
1226 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1228 $line =~ tr/\r\n//d;
1234 # Find all possible legal moves.
1235 sub calculate_refutation_moves {
1237 my $board = $pos->{'board'};
1238 my %refutation_moves = ();
1239 for my $col (0..7) {
1240 for my $row (0..7) {
1241 my $piece = substr($board->[$row], $col, 1);
1243 # Check that there's a piece of the right color on this square.
1244 next if ($piece eq '-');
1245 if ($pos->{'toplay'} eq 'W') {
1246 next if ($piece ne uc($piece));
1248 next if ($piece ne lc($piece));
1251 for my $to_col (0..7) {
1252 for my $to_row (0..7) {
1253 next if ($col == $to_col && $row == $to_row);
1254 next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1256 my $promo = ""; # FIXME
1257 my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1258 my $check = in_check($nb);
1259 next if ($check eq 'both');
1260 if ($pos->{'toplay'} eq 'W') {
1261 next if ($check eq 'white');
1263 next if ($check eq 'black');
1265 my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1266 $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1271 return %refutation_moves;
1274 sub give_new_move_to_second_engine {
1277 # Find the move that's been analyzed the shortest but is most promising.
1278 # Tie-break on UCI move representation.
1279 my $best_move = undef;
1280 for my $move (sort keys %refutation_moves) {
1281 if (!defined($best_move)) {
1285 my $best = $refutation_moves{$best_move};
1286 my $this = $refutation_moves{$move};
1288 if ($this->{'depth'} < $best->{'depth'} ||
1289 ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1295 my $m = $refutation_moves{$best_move};
1297 uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1298 uciprint($engine2, "go depth " . $m->{'depth'});
1299 $move_calculating_second_engine = $best_move;
1302 sub col_letter_to_num {
1303 return ord(shift) - ord('a');
1306 sub row_letter_to_num {
1307 return 7 - (ord(shift) - ord('1'));
1310 sub move_to_uci_notation {
1311 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1313 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);