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.
21 my $server = "freechess.org";
22 my $target = "GMCarlsen";
23 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
24 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
25 my $telltarget = undef; # undef to be silent
26 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960); # after each move
27 my $uci_assume_full_compliance = 0; # dangerous :-)
28 my $update_max_interval = 2.0;
29 my $second_engine_start_depth = 8;
39 $SIG{ALRM} = sub { output(); };
40 my $latest_update = undef;
44 open(FICSLOG, ">ficslog.txt")
45 or die "ficslog.txt: $!";
46 print FICSLOG "Log starting.\n";
50 open(UCILOG, ">ucilog.txt")
51 or die "ucilog.txt: $!";
52 print UCILOG "Log starting.\n";
57 # open the chess engine
58 my $engine = open_engine($engine_cmdline, 'E1');
59 my $engine2 = open_engine($engine2_cmdline, 'E2');
60 my ($last_move, $last_tell);
62 my $last_told_text = '';
63 my ($pos_waiting, $pos_calculating, $move_calculating_second_engine);
64 my %refutation_moves = ();
66 uciprint($engine, "setoption name UCI_AnalyseMode value true");
67 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
68 uciprint($engine, "setoption name NalimovUsage value Rarely");
69 uciprint($engine, "setoption name Hash value 1024");
70 # uciprint($engine, "setoption name MultiPV value 2");
71 uciprint($engine, "ucinewgame");
73 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
74 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
75 uciprint($engine2, "setoption name NalimovUsage value Rarely");
76 uciprint($engine2, "setoption name Hash value 1024");
77 uciprint($engine2, "setoption name Threads value 8");
78 # uciprint($engine2, "setoption name MultiPV value 2");
79 uciprint($engine2, "ucinewgame");
81 print "Chess engine ready.\n";
84 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
85 $t->input_log(\*FICSLOG);
87 $t->print("SesseBOT");
88 $t->waitfor('/Press return to enter the server/');
92 $t->cmd("set shout 0");
93 $t->cmd("set seek 0");
94 $t->cmd("set style 12");
95 $t->cmd("observe $target");
98 print "FICS ready.\n";
102 vec($rin, fileno($engine->{'read'}), 1) = 1;
103 vec($rin, fileno($engine2->{'read'}), 1) = 1;
104 vec($rin, fileno($t), 1) = 1;
106 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
110 my $line = $t->getline(Timeout => 0, errmode => 'return');
111 last if (!defined($line));
115 if ($line =~ /^<12> /) {
116 my $pos = style12_to_pos($line);
118 # if this is already in the queue, ignore it
119 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
121 # if we're already chewing on this and there's nothing else in the queue,
123 next if (!defined($pos_waiting) && defined($pos_calculating) &&
124 $pos->{'fen'} eq $pos_calculating->{'fen'});
126 # if we're already thinking on something, stop and wait for the engine
128 if (defined($pos_calculating)) {
129 if (!defined($pos_waiting)) {
130 uciprint($engine, "stop");
132 if ($uci_assume_full_compliance) {
135 uciprint($engine, "position fen " . $pos->{'fen'});
136 uciprint($engine, "go infinite");
137 $pos_calculating = $pos;
140 # it's wrong just to give the FEN (the move history is useful,
141 # and per the UCI spec, we should really have sent "ucinewgame"),
143 uciprint($engine, "position fen " . $pos->{'fen'});
144 uciprint($engine, "go infinite");
145 $pos_calculating = $pos;
148 %refutation_moves = calculate_refutation_moves($pos);
149 if (defined($move_calculating_second_engine)) {
150 uciprint($engine2, "stop");
151 $move_calculating_second_engine = undef;
153 give_new_move_to_second_engine($pos);
156 $engine->{'info'} = {};
157 $engine2->{'info'} = {};
161 # Output a command every move to note that we're
162 # still paying attention -- this is a good tradeoff,
163 # since if no move has happened in the last half
164 # hour, the analysis/relay has most likely stopped
165 # and we should stop hogging server resources.
169 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
170 my ($who, $msg) = ($1, $2);
172 next if (grep { $_ eq $who } (@masters) == 0);
174 if ($msg =~ /^fics (.*?)$/) {
175 $t->cmd("tell $who Executing '$1' on FICS.");
177 } elsif ($msg =~ /^uci (.*?)$/) {
178 $t->cmd("tell $who Sending '$1' to the engine.");
179 print { $engine->{'write'} } "$1\n";
181 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
184 #print "FICS: [$line]\n";
188 # any fun on the UCI channel?
189 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
190 my @lines = read_lines($engine);
191 for my $line (@lines) {
192 next if $line =~ /(upper|lower)bound/;
193 handle_uci($engine, $line, 1);
199 if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
200 my @lines = read_lines($engine2);
201 for my $line (@lines) {
202 next if $line =~ /(upper|lower)bound/;
203 handle_uci($engine2, $line, 0);
214 my ($engine, $line, $primary) = @_;
218 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
219 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
220 if ($line =~ /^info/) {
221 my (@infos) = split / /, $line;
224 parse_infos($engine, @infos);
226 if ($line =~ /^id/) {
227 my (@ids) = split / /, $line;
230 parse_ids($engine, @ids);
232 if ($line =~ /^bestmove/) {
234 return if (!$uci_assume_full_compliance);
235 if (defined($pos_waiting)) {
236 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
237 uciprint($engine, "go infinite");
239 $pos_calculating = $pos_waiting;
240 $pos_waiting = undef;
243 if (defined($move_calculating_second_engine)) {
244 my $move = $refutation_moves{$move_calculating_second_engine};
245 $move->{'pv'} = $engine->{'info'}{'pv'} // $engine->{'info'}{'pv1'};
246 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
247 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
248 $move->{'toplay'} = $pos_calculating->{'toplay'};
250 give_new_move_to_second_engine($pos_waiting // $pos_calculating);
256 my ($engine, @x) = @_;
259 my $info = $engine->{'info'};
261 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
262 for my $i (0..$#x - 1) {
263 if ($x[$i] =~ 'multipv') {
269 while (scalar @x > 0) {
270 if ($x[0] =~ 'multipv') {
276 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
278 my $value = shift @x;
279 $info->{$key} = $value;
282 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
284 my $value = shift @x;
285 $info->{$key . $mpv} = $value;
288 if ($x[0] eq 'score') {
291 delete $info->{'score_cp' . $mpv};
292 delete $info->{'score_mate' . $mpv};
294 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
297 $info->{'score_cp' . $mpv} = shift @x;
298 } elsif ($x[0] eq 'mate') {
300 $info->{'score_mate' . $mpv} = shift @x;
308 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
311 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
315 #print "unknown info '$x[0]', trying to recover...\n";
317 die "Unknown info '" . join(',', @x) . "'";
323 my ($engine, @x) = @_;
325 while (scalar @x > 0) {
326 if ($x[0] =~ /^(name|author)$/) {
328 my $value = join(' ', @x);
329 $engine->{'id'}{$key} = $value;
341 my (@x) = split / /, $str;
343 $pos{'board'} = [ @x[1..8] ];
344 $pos{'toplay'} = $x[9];
345 $pos{'ep_file_num'} = $x[10];
346 $pos{'white_castle_k'} = $x[11];
347 $pos{'white_castle_q'} = $x[12];
348 $pos{'black_castle_k'} = $x[13];
349 $pos{'black_castle_q'} = $x[14];
350 $pos{'time_to_100move_rule'} = $x[15];
351 $pos{'move_num'} = $x[26];
352 $pos{'last_move'} = $x[29];
353 $pos{'fen'} = make_fen(\%pos);
362 my (@board) = @{$pos->{'board'}};
363 for my $rank (0..7) {
364 $board[$rank] =~ s/(-+)/length($1)/ge;
366 my $fen = join('/', @board);
368 # white/black to move
370 $fen .= lc($pos->{'toplay'});
374 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
375 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
376 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
377 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
378 $castling = "-" if ($castling eq "");
379 # $castling = "-"; # chess960
385 if ($pos->{'ep_file_num'} != -1) {
386 my $col = $pos->{'ep_file_num'};
387 my $nep = (qw(a b c d e f g h))[$col];
389 if ($pos->{'toplay'} eq 'B') {
396 # Showing the en passant square when actually no capture can be made
397 # seems to confuse at least Rybka. Thus, check if there's actually
398 # a pawn of the opposite side that can do the en passant move, and if
399 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
400 # "right" thing as per the standard, though.
402 if ($pos->{'toplay'} eq 'B') {
403 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
404 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
406 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
407 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
415 $fen .= $pos->{'time_to_100move_rule'};
419 $fen .= $pos->{'move_num'};
425 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
426 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
427 my $piece = substr($board->[$from_row], $from_col, 1);
431 die "Invalid move $move";
434 # white short castling
435 if ($move eq 'e1g1' && $piece eq 'K') {
437 substr($nb[7], 4, 1, '-');
438 substr($nb[7], 6, 1, $piece);
441 substr($nb[7], 7, 1, '-');
442 substr($nb[7], 5, 1, 'R');
447 # white long castling
448 if ($move eq 'e1c1' && $piece eq 'K') {
450 substr($nb[7], 4, 1, '-');
451 substr($nb[7], 2, 1, $piece);
454 substr($nb[7], 0, 1, '-');
455 substr($nb[7], 3, 1, 'R');
460 # black short castling
461 if ($move eq 'e8g8' && $piece eq 'k') {
463 substr($nb[0], 4, 1, '-');
464 substr($nb[0], 6, 1, $piece);
467 substr($nb[0], 7, 1, '-');
468 substr($nb[0], 5, 1, 'r');
473 # black long castling
474 if ($move eq 'e8c8' && $piece eq 'k') {
476 substr($nb[0], 4, 1, '-');
477 substr($nb[0], 2, 1, $piece);
480 substr($nb[0], 0, 1, '-');
481 substr($nb[0], 3, 1, 'r');
486 # check if the from-piece is a pawn
487 if (lc($piece) eq 'p') {
489 if ($from_col != $to_col) {
491 if (substr($board->[$to_row], $to_col, 1) eq '-') {
493 substr($nb[$to_row + 1], $to_col, 1, '-');
495 substr($nb[$to_row - 1], $to_col, 1, '-');
510 substr($nb[$from_row], $from_col, 1, '-');
511 substr($nb[$to_row], $to_col, 1, $piece);
517 my ($board, @pvs) = @_;
519 if (scalar @pvs == 0 || !defined($pvs[0])) {
524 my $from_col = col_letter_to_num(substr($pv, 0, 1));
525 my $from_row = row_letter_to_num(substr($pv, 1, 1));
526 my $to_col = col_letter_to_num(substr($pv, 2, 1));
527 my $to_row = row_letter_to_num(substr($pv, 3, 1));
528 my $promo = substr($pv, 4, 1);
530 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
531 my $piece = substr($board->[$from_row], $from_col, 1);
534 die "Invalid move $pv";
537 # white short castling
538 if ($pv eq 'e1g1' && $piece eq 'K') {
539 return ('0-0', prettyprint_pv($nb, @pvs));
542 # white long castling
543 if ($pv eq 'e1c1' && $piece eq 'K') {
544 return ('0-0-0', prettyprint_pv($nb, @pvs));
547 # black short castling
548 if ($pv eq 'e8g8' && $piece eq 'k') {
549 return ('0-0', prettyprint_pv($nb, @pvs));
552 # black long castling
553 if ($pv eq 'e8c8' && $piece eq 'k') {
554 return ('0-0-0', prettyprint_pv($nb, @pvs));
559 # check if the from-piece is a pawn
560 if (lc($piece) eq 'p') {
562 if ($from_col != $to_col) {
563 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
565 $pretty = substr($pv, 2, 2);
567 if (length($pv) == 5) {
570 $pretty .= uc(substr($pv, 4, 1));
573 $piece = substr($pv, 4, 1);
575 $piece = uc(substr($pv, 4, 1));
580 $pretty = uc($piece);
582 # see how many of these pieces could go here, in all
586 next unless (substr($board->[$row], $col, 1) eq $piece);
587 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
591 # see how many of these pieces from the given row could go here
594 next unless (substr($board->[$from_row], $col, 1) eq $piece);
595 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
598 # and same for columns
601 next unless (substr($board->[$row], $from_col, 1) eq $piece);
602 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
605 # see if we need to disambiguate
606 if ($num_total > 1) {
608 $pretty .= substr($pv, 0, 1);
609 } elsif ($num_row == 1) {
610 $pretty .= substr($pv, 1, 1);
612 $pretty .= substr($pv, 0, 2);
617 if (substr($board->[$to_row], $to_col, 1) ne '-') {
621 $pretty .= substr($pv, 2, 2);
626 } elsif (in_check($nb) ne 'none') {
629 return ($pretty, prettyprint_pv($nb, @pvs));
635 return if (!defined($pos_calculating));
637 # Don't update too often.
638 my $age = Time::HiRes::tv_interval($latest_update);
639 if ($age < $update_max_interval) {
640 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
644 my $info = $engine->{'info'};
647 # Some programs _always_ report MultiPV, even with only one PV.
648 # In this case, we simply use that data as if MultiPV was never
651 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
652 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
653 if (exists($info->{$key . '1'})) {
654 $info->{$key} = $info->{$key . '1'};
660 # Check the PVs first. if they're invalid, just wait, as our data
661 # is most likely out of sync. This isn't a very good solution, as
662 # it can frequently miss stuff, but it's good enough for most users.
666 if (exists($info->{'pv'})) {
667 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
671 while (exists($info->{'pv' . $mpv})) {
672 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
677 $engine->{'info'} = {};
683 $latest_update = [Time::HiRes::gettimeofday];
687 my $info = $engine->{'info'};
688 my $id = $engine->{'id'};
690 my $text = 'Analysis';
691 if ($pos_calculating->{'last_move'} ne 'none') {
692 if ($pos_calculating->{'toplay'} eq 'W') {
693 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
695 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
697 if (exists($id->{'name'})) {
702 if (exists($id->{'name'})) {
703 $text .= " by $id->{'name'}:\n\n";
708 return unless (exists($pos_calculating->{'board'}));
710 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
713 while (exists($info->{'pv' . $mpv})) {
714 $text .= sprintf " PV%2u", $mpv;
715 my $score = short_score($info, $pos_calculating, $mpv);
716 $text .= " ($score)" if (defined($score));
719 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
720 if ($info->{'tbhits' . $mpv} == 1) {
721 $tbhits = ", 1 tbhit";
723 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
727 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
728 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
729 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
733 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
739 my $score = long_score($info, $pos_calculating, '');
740 $text .= " $score\n" if defined($score);
741 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
744 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
745 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
746 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
748 if (exists($info->{'seldepth'})) {
749 $text .= sprintf " (%u selective)", $info->{'seldepth'};
751 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
752 if ($info->{'tbhits'} == 1) {
753 $text .= ", one Nalimov hit";
755 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
761 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
763 my @refutation_lines = ();
764 for my $move (keys %refutation_moves) {
766 my $m = $refutation_moves{$move};
767 die if ($m->{'depth'} < $second_engine_start_depth);
768 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
769 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
770 if (scalar @pretty_pv > 5) {
771 @pretty_pv = @pretty_pv[0..4];
772 push @pretty_pv, "...";
774 #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
775 my $key = $pretty_move;
776 my $line = sprintf(" %-6s %6s %3s %s",
778 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
780 join(', ', @pretty_pv));
781 push @refutation_lines, [ $key, $line ];
785 if ($#refutation_lines >= 0) {
786 $text .= "Shallow search of all legal moves:\n\n";
787 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
788 $text .= $line->[1] . "\n";
793 if ($last_text ne $text) {
794 print "
\e[H
\e[2J"; # clear the screen
799 # Now construct the tell text, if any
800 return if (!defined($telltarget));
804 if (exists($id->{'name'})) {
805 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
807 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
810 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
813 while (exists($info->{'pv' . $mpv})) {
814 $tell_text .= sprintf " PV%2u", $mpv;
815 my $score = short_score($info, $pos_calculating, $mpv);
816 $tell_text .= " ($score)" if (defined($score));
818 if (exists($info->{'depth' . $mpv})) {
819 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
823 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
829 my $score = long_score($info, $pos_calculating, '');
830 $tell_text .= " $score\n" if defined($score);
831 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
832 if (exists($info->{'depth'})) {
833 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
838 # see if a new tell is called for -- it is if the delay has expired _and_
839 # this is not simply a repetition of the last one
840 if ($last_told_text ne $tell_text) {
842 for my $iv (@tell_intervals) {
843 last if ($now - $last_move < $iv);
844 next if ($last_tell - $last_move >= $iv);
846 for my $line (split /\n/, $tell_text) {
847 $t->print("tell $telltarget [$target] $line");
850 $last_told_text = $text;
859 my $info = $engine->{'info'};
862 $json->{'position'} = $pos_calculating;
863 $json->{'id'} = $engine->{'id'};
864 $json->{'score'} = long_score($info, $pos_calculating, '');
866 $json->{'nodes'} = $info->{'nodes'};
867 $json->{'nps'} = $info->{'nps'};
868 $json->{'depth'} = $info->{'depth'};
869 $json->{'tbhits'} = $info->{'tbhits'};
870 $json->{'seldepth'} = $info->{'seldepth'};
872 # single-PV only for now
873 $json->{'pv_uci'} = $info->{'pv'};
874 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
876 my %refutation_lines = ();
877 for my $move (keys %refutation_moves) {
878 my $m = $refutation_moves{$move};
879 my $pretty_move = "";
882 $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
883 @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
885 $refutation_lines{$move} = {
886 sort_key => $pretty_move,
887 depth => $m->{'depth'},
888 score_sort_key => score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1),
889 pretty_score => short_score($refutation_moves{$move}, $pos_calculating, '', 1),
890 pretty_move => $pretty_move,
891 pv_pretty => \@pretty_pv,
894 $refutation_lines{$move}->{'pv_uci'} = [ $move, @{$m->{'pv'}} ];
897 $json->{'refutation_lines'} = \%refutation_lines;
899 open my $fh, ">analysis.json.tmp"
901 print $fh JSON::XS::encode_json($json);
903 rename("analysis.json.tmp", "analysis.json");
908 my ($wkr, $wkc, $bkr, $bkc);
912 my $piece = substr($board->[$row], $col, 1);
914 ($wkr, $wkc) = ($row, $col);
915 } elsif ($piece eq 'k') {
916 ($bkr, $bkc) = ($row, $col);
921 return ($wkr, $wkc, $bkr, $bkc);
926 my $check = in_check($board);
927 return 0 if ($check eq 'none');
929 # try all possible moves for the side in check
932 my $piece = substr($board->[$row], $col, 1);
933 next if ($piece eq '-');
935 if ($check eq 'white') {
936 next if ($piece eq lc($piece));
938 next if ($piece eq uc($piece));
941 for my $dest_row (0..7) {
942 for my $dest_col (0..7) {
943 next if ($row == $dest_row && $col == $dest_col);
944 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
947 substr($nb[$row], $col, 1, '-');
948 substr($nb[$dest_row], $dest_col, 1, $piece);
950 my $new_check = in_check(\@nb);
951 return 0 if ($new_check ne $check && $new_check ne 'both');
957 # nothing to do; mate
963 my ($black_check, $white_check) = (0, 0);
965 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
967 # check all pieces for the possibility of threatening the two kings
970 my $piece = substr($board->[$row], $col, 1);
971 next if ($piece eq '-');
973 if (uc($piece) eq $piece) {
975 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
978 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
983 if ($black_check && $white_check) {
985 } elsif ($black_check) {
987 } elsif ($white_check) {
995 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
997 # can't eat your own piece
998 my $dest_piece = substr($board->[$to_row], $to_col, 1);
999 if ($dest_piece ne '-') {
1000 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1003 if (lc($piece) eq 'k') {
1004 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1006 if (lc($piece) eq 'r') {
1007 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1009 # check that there's a clear passage
1010 if ($from_row == $to_row) {
1011 if ($from_col > $to_col) {
1012 ($to_col, $from_col) = ($from_col, $to_col);
1015 for my $c (($from_col+1)..($to_col-1)) {
1016 my $middle_piece = substr($board->[$to_row], $c, 1);
1017 return 0 if ($middle_piece ne '-');
1022 if ($from_row > $to_row) {
1023 ($to_row, $from_row) = ($from_row, $to_row);
1026 for my $r (($from_row+1)..($to_row-1)) {
1027 my $middle_piece = substr($board->[$r], $to_col, 1);
1028 return 0 if ($middle_piece ne '-');
1034 if (lc($piece) eq 'b') {
1035 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1037 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1038 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1040 my $r = $from_row + $dr;
1041 my $c = $from_col + $dc;
1043 while ($r != $to_row) {
1044 my $middle_piece = substr($board->[$r], $c, 1);
1045 return 0 if ($middle_piece ne '-');
1053 if (lc($piece) eq 'n') {
1054 my $diff_r = abs($from_row - $to_row);
1055 my $diff_c = abs($from_col - $to_col);
1056 return 1 if ($diff_r == 2 && $diff_c == 1);
1057 return 1 if ($diff_r == 1 && $diff_c == 2);
1060 if ($piece eq 'q') {
1061 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1062 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1064 if ($piece eq 'Q') {
1065 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1066 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1070 if ($piece eq 'p') {
1072 if ($to_col == $from_col && $to_row == $from_row + 1) {
1073 return ($dest_piece eq '-');
1075 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1076 my $middle_piece = substr($board->[2], $to_col, 1);
1077 return ($dest_piece eq '-' && $middle_piece eq '-');
1079 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1080 return ($dest_piece ne '-');
1084 if ($piece eq 'P') {
1086 if ($to_col == $from_col && $to_row == $from_row - 1) {
1087 return ($dest_piece eq '-');
1089 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1090 my $middle_piece = substr($board->[5], $to_col, 1);
1091 return ($dest_piece eq '-' && $middle_piece eq '-');
1093 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1094 return ($dest_piece ne '-');
1104 my ($engine, $msg) = @_;
1105 print { $engine->{'write'} } "$msg\n";
1106 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1110 my ($info, $pos, $mpv, $invert) = @_;
1113 if ($pos->{'toplay'} eq 'B') {
1117 if (defined($info->{'score_mate' . $mpv})) {
1119 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1121 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1124 if (exists($info->{'score_cp' . $mpv})) {
1125 my $score = $info->{'score_cp' . $mpv} * 0.01;
1132 return sprintf "%+5.2f", $score;
1139 sub score_sort_key {
1140 my ($info, $pos, $mpv, $invert) = @_;
1142 if (defined($info->{'score_mate' . $mpv})) {
1144 return -(99999 - $info->{'score_mate' . $mpv});
1146 return 99999 - $info->{'score_mate' . $mpv};
1149 if (exists($info->{'score_cp' . $mpv})) {
1150 my $score = $info->{'score_cp' . $mpv};
1162 my ($info, $pos, $mpv) = @_;
1164 if (defined($info->{'score_mate' . $mpv})) {
1165 my $mate = $info->{'score_mate' . $mpv};
1166 if ($pos->{'toplay'} eq 'B') {
1170 return sprintf "White mates in %u", $mate;
1172 return sprintf "Black mates in %u", -$mate;
1175 if (exists($info->{'score_cp' . $mpv})) {
1176 my $score = $info->{'score_cp' . $mpv} * 0.01;
1177 if ($pos->{'toplay'} eq 'B') {
1180 return sprintf "Score: %+5.2f", $score;
1187 my %book_cache = ();
1189 my ($fen, $board, $toplay) = @_;
1191 if (exists($book_cache{$fen})) {
1192 return $book_cache{$fen};
1195 my $ret = `./booklook $fen`;
1196 return "" if ($ret =~ /Not found/ || $ret eq '');
1200 for my $m (split /\n/, $ret) {
1201 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1205 $pmove = '(current)';
1207 ($pmove) = prettyprint_pv($board, $move);
1208 $pmove .= $annotation;
1212 if ($toplay eq 'W') {
1213 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1215 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1217 my $n = $win + $draw + $lose;
1223 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1226 push @moves, [ $pmove, $n, $percent, $rating ];
1229 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1231 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1232 for my $m (@moves) {
1233 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1240 my ($cmdline, $tag) = @_;
1241 my ($uciread, $uciwrite);
1242 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1254 uciprint($engine, "uci");
1256 # gobble the options
1257 while (<$uciread>) {
1259 handle_uci($engine, $_);
1269 # Read until we've got a full line -- if the engine sends part of
1270 # a line and then stops we're pretty much hosed, but that should
1273 while ($engine->{'readbuf'} !~ /\n/) {
1275 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1277 if (!defined($ret)) {
1278 next if ($!{EINTR});
1279 die "error in reading from the UCI engine: $!";
1280 } elsif ($ret == 0) {
1281 die "EOF from UCI engine";
1284 $engine->{'readbuf'} .= $tmp;
1289 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1291 $line =~ tr/\r\n//d;
1297 # Find all possible legal moves.
1298 sub calculate_refutation_moves {
1300 my $board = $pos->{'board'};
1301 my %refutation_moves = ();
1302 for my $col (0..7) {
1303 for my $row (0..7) {
1304 my $piece = substr($board->[$row], $col, 1);
1306 # Check that there's a piece of the right color on this square.
1307 next if ($piece eq '-');
1308 if ($pos->{'toplay'} eq 'W') {
1309 next if ($piece ne uc($piece));
1311 next if ($piece ne lc($piece));
1314 for my $to_col (0..7) {
1315 for my $to_row (0..7) {
1316 next if ($col == $to_col && $row == $to_row);
1317 next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1319 my $promo = ""; # FIXME
1320 my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1321 my $check = in_check($nb);
1322 next if ($check eq 'both');
1323 if ($pos->{'toplay'} eq 'W') {
1324 next if ($check eq 'white');
1326 next if ($check eq 'black');
1328 my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1329 $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1334 return %refutation_moves;
1337 sub give_new_move_to_second_engine {
1340 # Find the move that's been analyzed the shortest but is most promising.
1341 # Tie-break on UCI move representation.
1342 my $best_move = undef;
1343 for my $move (sort keys %refutation_moves) {
1344 if (!defined($best_move)) {
1348 my $best = $refutation_moves{$best_move};
1349 my $this = $refutation_moves{$move};
1351 if ($this->{'depth'} < $best->{'depth'} ||
1352 ($this->{'depth'} == $best->{'depth'} && score_sort_key($this, $pos, '', 1) > score_sort_key($best, $pos, '', 1))) {
1358 my $m = $refutation_moves{$best_move};
1360 uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1361 uciprint($engine2, "go depth " . $m->{'depth'});
1362 $move_calculating_second_engine = $best_move;
1365 sub col_letter_to_num {
1366 return ord(shift) - ord('a');
1369 sub row_letter_to_num {
1370 return 7 - (ord(shift) - ord('1'));
1373 sub move_to_uci_notation {
1374 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1376 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);