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, $pos_calculating_second_engine);
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 500");
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 if (defined($pos_calculating_second_engine)) {
148 uciprint($engine2, "stop");
150 uciprint($engine2, "position fen " . $pos->{'fen'});
151 uciprint($engine2, "go infinite");
152 $pos_calculating_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 $engine2->{'info'} = {};
243 my $pos = $pos_waiting // $pos_calculating;
244 uciprint($engine2, "position fen " . $pos->{'fen'});
245 uciprint($engine2, "go infinite");
246 $pos_calculating_second_engine = $pos;
252 my ($engine, @x) = @_;
255 my $info = $engine->{'info'};
257 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
258 for my $i (0..$#x - 1) {
259 if ($x[$i] =~ 'multipv') {
265 while (scalar @x > 0) {
266 if ($x[0] =~ 'multipv') {
272 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
274 my $value = shift @x;
275 $info->{$key} = $value;
278 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
280 my $value = shift @x;
281 $info->{$key . $mpv} = $value;
284 if ($x[0] eq 'score') {
287 delete $info->{'score_cp' . $mpv};
288 delete $info->{'score_mate' . $mpv};
290 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
293 $info->{'score_cp' . $mpv} = shift @x;
294 } elsif ($x[0] eq 'mate') {
296 $info->{'score_mate' . $mpv} = shift @x;
304 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
307 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
311 #print "unknown info '$x[0]', trying to recover...\n";
313 die "Unknown info '" . join(',', @x) . "'";
319 my ($engine, @x) = @_;
321 while (scalar @x > 0) {
322 if ($x[0] =~ /^(name|author)$/) {
324 my $value = join(' ', @x);
325 $engine->{'id'}{$key} = $value;
337 my (@x) = split / /, $str;
339 $pos{'board'} = [ @x[1..8] ];
340 $pos{'toplay'} = $x[9];
341 $pos{'ep_file_num'} = $x[10];
342 $pos{'white_castle_k'} = $x[11];
343 $pos{'white_castle_q'} = $x[12];
344 $pos{'black_castle_k'} = $x[13];
345 $pos{'black_castle_q'} = $x[14];
346 $pos{'time_to_100move_rule'} = $x[15];
347 $pos{'move_num'} = $x[26];
348 if ($x[27] =~ /([a-h][1-8])-([a-h][1-8])/) {
349 $pos{'last_move_uci'} = $1 . $2;
351 $pos{'last_move_uci'} = undef;
353 $pos{'last_move'} = $x[29];
354 $pos{'fen'} = make_fen(\%pos);
363 my (@board) = @{$pos->{'board'}};
364 for my $rank (0..7) {
365 $board[$rank] =~ s/(-+)/length($1)/ge;
367 my $fen = join('/', @board);
369 # white/black to move
371 $fen .= lc($pos->{'toplay'});
375 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
376 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
377 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
378 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
379 $castling = "-" if ($castling eq "");
380 # $castling = "-"; # chess960
386 if ($pos->{'ep_file_num'} != -1) {
387 my $col = $pos->{'ep_file_num'};
388 my $nep = (qw(a b c d e f g h))[$col];
390 if ($pos->{'toplay'} eq 'B') {
397 # Showing the en passant square when actually no capture can be made
398 # seems to confuse at least Rybka. Thus, check if there's actually
399 # a pawn of the opposite side that can do the en passant move, and if
400 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
401 # "right" thing as per the standard, though.
403 if ($pos->{'toplay'} eq 'B') {
404 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
405 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
407 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
408 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
416 $fen .= $pos->{'time_to_100move_rule'};
420 $fen .= $pos->{'move_num'};
426 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
427 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
428 my $piece = substr($board->[$from_row], $from_col, 1);
432 die "Invalid move $move";
435 # white short castling
436 if ($move eq 'e1g1' && $piece eq 'K') {
438 substr($nb[7], 4, 1, '-');
439 substr($nb[7], 6, 1, $piece);
442 substr($nb[7], 7, 1, '-');
443 substr($nb[7], 5, 1, 'R');
448 # white long castling
449 if ($move eq 'e1c1' && $piece eq 'K') {
451 substr($nb[7], 4, 1, '-');
452 substr($nb[7], 2, 1, $piece);
455 substr($nb[7], 0, 1, '-');
456 substr($nb[7], 3, 1, 'R');
461 # black short castling
462 if ($move eq 'e8g8' && $piece eq 'k') {
464 substr($nb[0], 4, 1, '-');
465 substr($nb[0], 6, 1, $piece);
468 substr($nb[0], 7, 1, '-');
469 substr($nb[0], 5, 1, 'r');
474 # black long castling
475 if ($move eq 'e8c8' && $piece eq 'k') {
477 substr($nb[0], 4, 1, '-');
478 substr($nb[0], 2, 1, $piece);
481 substr($nb[0], 0, 1, '-');
482 substr($nb[0], 3, 1, 'r');
487 # check if the from-piece is a pawn
488 if (lc($piece) eq 'p') {
490 if ($from_col != $to_col) {
492 if (substr($board->[$to_row], $to_col, 1) eq '-') {
494 substr($nb[$to_row + 1], $to_col, 1, '-');
496 substr($nb[$to_row - 1], $to_col, 1, '-');
511 substr($nb[$from_row], $from_col, 1, '-');
512 substr($nb[$to_row], $to_col, 1, $piece);
518 my ($board, @pvs) = @_;
520 if (scalar @pvs == 0 || !defined($pvs[0])) {
525 my $from_col = col_letter_to_num(substr($pv, 0, 1));
526 my $from_row = row_letter_to_num(substr($pv, 1, 1));
527 my $to_col = col_letter_to_num(substr($pv, 2, 1));
528 my $to_row = row_letter_to_num(substr($pv, 3, 1));
529 my $promo = substr($pv, 4, 1);
531 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
532 my $piece = substr($board->[$from_row], $from_col, 1);
535 die "Invalid move $pv";
538 # white short castling
539 if ($pv eq 'e1g1' && $piece eq 'K') {
540 return ('0-0', prettyprint_pv($nb, @pvs));
543 # white long castling
544 if ($pv eq 'e1c1' && $piece eq 'K') {
545 return ('0-0-0', prettyprint_pv($nb, @pvs));
548 # black short castling
549 if ($pv eq 'e8g8' && $piece eq 'k') {
550 return ('0-0', prettyprint_pv($nb, @pvs));
553 # black long castling
554 if ($pv eq 'e8c8' && $piece eq 'k') {
555 return ('0-0-0', prettyprint_pv($nb, @pvs));
560 # check if the from-piece is a pawn
561 if (lc($piece) eq 'p') {
563 if ($from_col != $to_col) {
564 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
566 $pretty = substr($pv, 2, 2);
568 if (length($pv) == 5) {
571 $pretty .= uc(substr($pv, 4, 1));
574 $piece = substr($pv, 4, 1);
576 $piece = uc(substr($pv, 4, 1));
581 $pretty = uc($piece);
583 # see how many of these pieces could go here, in all
587 next unless (substr($board->[$row], $col, 1) eq $piece);
588 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
592 # see how many of these pieces from the given row could go here
595 next unless (substr($board->[$from_row], $col, 1) eq $piece);
596 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
599 # and same for columns
602 next unless (substr($board->[$row], $from_col, 1) eq $piece);
603 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
606 # see if we need to disambiguate
607 if ($num_total > 1) {
609 $pretty .= substr($pv, 0, 1);
610 } elsif ($num_row == 1) {
611 $pretty .= substr($pv, 1, 1);
613 $pretty .= substr($pv, 0, 2);
618 if (substr($board->[$to_row], $to_col, 1) ne '-') {
622 $pretty .= substr($pv, 2, 2);
627 } elsif (in_check($nb) ne 'none') {
630 return ($pretty, prettyprint_pv($nb, @pvs));
636 return if (!defined($pos_calculating));
638 # Don't update too often.
639 my $age = Time::HiRes::tv_interval($latest_update);
640 if ($age < $update_max_interval) {
641 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
645 my $info = $engine->{'info'};
648 # Some programs _always_ report MultiPV, even with only one PV.
649 # In this case, we simply use that data as if MultiPV was never
652 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
653 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
654 if (exists($info->{$key . '1'})) {
655 $info->{$key} = $info->{$key . '1'};
661 # Check the PVs first. if they're invalid, just wait, as our data
662 # is most likely out of sync. This isn't a very good solution, as
663 # it can frequently miss stuff, but it's good enough for most users.
667 if (exists($info->{'pv'})) {
668 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
672 while (exists($info->{'pv' . $mpv})) {
673 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
678 $engine->{'info'} = {};
684 $latest_update = [Time::HiRes::gettimeofday];
688 my $info = $engine->{'info'};
689 my $id = $engine->{'id'};
691 my $text = 'Analysis';
692 if ($pos_calculating->{'last_move'} ne 'none') {
693 if ($pos_calculating->{'toplay'} eq 'W') {
694 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
696 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
698 if (exists($id->{'name'})) {
703 if (exists($id->{'name'})) {
704 $text .= " by $id->{'name'}:\n\n";
709 return unless (exists($pos_calculating->{'board'}));
711 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
714 while (exists($info->{'pv' . $mpv})) {
715 $text .= sprintf " PV%2u", $mpv;
716 my $score = short_score($info, $pos_calculating, $mpv);
717 $text .= " ($score)" if (defined($score));
720 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
721 if ($info->{'tbhits' . $mpv} == 1) {
722 $tbhits = ", 1 tbhit";
724 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
728 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
729 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
730 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
734 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
740 my $score = long_score($info, $pos_calculating, '');
741 $text .= " $score\n" if defined($score);
742 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
745 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
746 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
747 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
749 if (exists($info->{'seldepth'})) {
750 $text .= sprintf " (%u selective)", $info->{'seldepth'};
752 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
753 if ($info->{'tbhits'} == 1) {
754 $text .= ", one Nalimov hit";
756 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
762 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
764 my @refutation_lines = ();
765 for (my $mpv = 1; $mpv < 500; ++$mpv) {
766 my $info = $engine2->{'info'};
767 last if (!exists($info->{'pv' . $mpv}));
769 my $pv = $info->{'pv' . $mpv};
771 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
772 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
773 if (scalar @pretty_pv > 5) {
774 @pretty_pv = @pretty_pv[0..4];
775 push @pretty_pv, "...";
777 my $key = $pretty_move;
778 my $line = sprintf(" %-6s %6s %3s %s",
780 short_score($info, $pos_calculating_second_engine, $mpv, 0),
781 "d" . $info->{'depth' . $mpv},
782 join(', ', @pretty_pv));
783 push @refutation_lines, [ $key, $line ];
787 if ($#refutation_lines >= 0) {
788 $text .= "Shallow search of all legal moves:\n\n";
789 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
790 $text .= $line->[1] . "\n";
795 if ($last_text ne $text) {
796 print "
\e[H
\e[2J"; # clear the screen
801 # Now construct the tell text, if any
802 return if (!defined($telltarget));
806 if (exists($id->{'name'})) {
807 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
809 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
812 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
815 while (exists($info->{'pv' . $mpv})) {
816 $tell_text .= sprintf " PV%2u", $mpv;
817 my $score = short_score($info, $pos_calculating, $mpv);
818 $tell_text .= " ($score)" if (defined($score));
820 if (exists($info->{'depth' . $mpv})) {
821 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
825 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
831 my $score = long_score($info, $pos_calculating, '');
832 $tell_text .= " $score\n" if defined($score);
833 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
834 if (exists($info->{'depth'})) {
835 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
840 # see if a new tell is called for -- it is if the delay has expired _and_
841 # this is not simply a repetition of the last one
842 if ($last_told_text ne $tell_text) {
844 for my $iv (@tell_intervals) {
845 last if ($now - $last_move < $iv);
846 next if ($last_tell - $last_move >= $iv);
848 for my $line (split /\n/, $tell_text) {
849 $t->print("tell $telltarget [$target] $line");
852 $last_told_text = $text;
861 my $info = $engine->{'info'};
864 $json->{'position'} = $pos_calculating;
865 $json->{'id'} = $engine->{'id'};
866 $json->{'score'} = long_score($info, $pos_calculating, '');
868 $json->{'nodes'} = $info->{'nodes'};
869 $json->{'nps'} = $info->{'nps'};
870 $json->{'depth'} = $info->{'depth'};
871 $json->{'tbhits'} = $info->{'tbhits'};
872 $json->{'seldepth'} = $info->{'seldepth'};
874 # single-PV only for now
875 $json->{'pv_uci'} = $info->{'pv'};
876 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
878 my %refutation_lines = ();
879 my @refutation_lines = ();
880 for (my $mpv = 1; $mpv < 500; ++$mpv) {
881 my $info = $engine2->{'info'};
882 my $pretty_move = "";
884 last if (!exists($info->{'pv' . $mpv}));
887 my $pv = $info->{'pv' . $mpv};
888 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
889 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
890 $refutation_lines{$pv->[0]} = {
891 sort_key => $pretty_move,
892 depth => $info->{'depth' . $mpv},
893 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
894 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
895 pretty_move => $pretty_move,
896 pv_pretty => \@pretty_pv,
898 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
901 $json->{'refutation_lines'} = \%refutation_lines;
903 open my $fh, ">analysis.json.tmp"
905 print $fh JSON::XS::encode_json($json);
907 rename("analysis.json.tmp", "analysis.json");
912 my ($wkr, $wkc, $bkr, $bkc);
916 my $piece = substr($board->[$row], $col, 1);
918 ($wkr, $wkc) = ($row, $col);
919 } elsif ($piece eq 'k') {
920 ($bkr, $bkc) = ($row, $col);
925 return ($wkr, $wkc, $bkr, $bkc);
930 my $check = in_check($board);
931 return 0 if ($check eq 'none');
933 # try all possible moves for the side in check
936 my $piece = substr($board->[$row], $col, 1);
937 next if ($piece eq '-');
939 if ($check eq 'white') {
940 next if ($piece eq lc($piece));
942 next if ($piece eq uc($piece));
945 for my $dest_row (0..7) {
946 for my $dest_col (0..7) {
947 next if ($row == $dest_row && $col == $dest_col);
948 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
951 substr($nb[$row], $col, 1, '-');
952 substr($nb[$dest_row], $dest_col, 1, $piece);
954 my $new_check = in_check(\@nb);
955 return 0 if ($new_check ne $check && $new_check ne 'both');
961 # nothing to do; mate
967 my ($black_check, $white_check) = (0, 0);
969 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
971 # check all pieces for the possibility of threatening the two kings
974 my $piece = substr($board->[$row], $col, 1);
975 next if ($piece eq '-');
977 if (uc($piece) eq $piece) {
979 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
982 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
987 if ($black_check && $white_check) {
989 } elsif ($black_check) {
991 } elsif ($white_check) {
999 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
1001 # can't eat your own piece
1002 my $dest_piece = substr($board->[$to_row], $to_col, 1);
1003 if ($dest_piece ne '-') {
1004 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1007 if (lc($piece) eq 'k') {
1008 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1010 if (lc($piece) eq 'r') {
1011 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1013 # check that there's a clear passage
1014 if ($from_row == $to_row) {
1015 if ($from_col > $to_col) {
1016 ($to_col, $from_col) = ($from_col, $to_col);
1019 for my $c (($from_col+1)..($to_col-1)) {
1020 my $middle_piece = substr($board->[$to_row], $c, 1);
1021 return 0 if ($middle_piece ne '-');
1026 if ($from_row > $to_row) {
1027 ($to_row, $from_row) = ($from_row, $to_row);
1030 for my $r (($from_row+1)..($to_row-1)) {
1031 my $middle_piece = substr($board->[$r], $to_col, 1);
1032 return 0 if ($middle_piece ne '-');
1038 if (lc($piece) eq 'b') {
1039 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1041 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1042 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1044 my $r = $from_row + $dr;
1045 my $c = $from_col + $dc;
1047 while ($r != $to_row) {
1048 my $middle_piece = substr($board->[$r], $c, 1);
1049 return 0 if ($middle_piece ne '-');
1057 if (lc($piece) eq 'n') {
1058 my $diff_r = abs($from_row - $to_row);
1059 my $diff_c = abs($from_col - $to_col);
1060 return 1 if ($diff_r == 2 && $diff_c == 1);
1061 return 1 if ($diff_r == 1 && $diff_c == 2);
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));
1068 if ($piece eq 'Q') {
1069 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1070 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1074 if ($piece eq 'p') {
1076 if ($to_col == $from_col && $to_row == $from_row + 1) {
1077 return ($dest_piece eq '-');
1079 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1080 my $middle_piece = substr($board->[2], $to_col, 1);
1081 return ($dest_piece eq '-' && $middle_piece eq '-');
1083 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1084 return ($dest_piece ne '-');
1088 if ($piece eq 'P') {
1090 if ($to_col == $from_col && $to_row == $from_row - 1) {
1091 return ($dest_piece eq '-');
1093 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1094 my $middle_piece = substr($board->[5], $to_col, 1);
1095 return ($dest_piece eq '-' && $middle_piece eq '-');
1097 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1098 return ($dest_piece ne '-');
1108 my ($engine, $msg) = @_;
1109 print { $engine->{'write'} } "$msg\n";
1110 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1114 my ($info, $pos, $mpv, $invert) = @_;
1117 if ($pos->{'toplay'} eq 'B') {
1121 if (defined($info->{'score_mate' . $mpv})) {
1123 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1125 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1128 if (exists($info->{'score_cp' . $mpv})) {
1129 my $score = $info->{'score_cp' . $mpv} * 0.01;
1136 return sprintf "%+5.2f", $score;
1143 sub score_sort_key {
1144 my ($info, $pos, $mpv, $invert) = @_;
1146 if (defined($info->{'score_mate' . $mpv})) {
1148 return -(99999 - $info->{'score_mate' . $mpv});
1150 return 99999 - $info->{'score_mate' . $mpv};
1153 if (exists($info->{'score_cp' . $mpv})) {
1154 my $score = $info->{'score_cp' . $mpv};
1166 my ($info, $pos, $mpv) = @_;
1168 if (defined($info->{'score_mate' . $mpv})) {
1169 my $mate = $info->{'score_mate' . $mpv};
1170 if ($pos->{'toplay'} eq 'B') {
1174 return sprintf "White mates in %u", $mate;
1176 return sprintf "Black mates in %u", -$mate;
1179 if (exists($info->{'score_cp' . $mpv})) {
1180 my $score = $info->{'score_cp' . $mpv} * 0.01;
1181 if ($pos->{'toplay'} eq 'B') {
1184 return sprintf "Score: %+5.2f", $score;
1191 my %book_cache = ();
1193 my ($fen, $board, $toplay) = @_;
1195 if (exists($book_cache{$fen})) {
1196 return $book_cache{$fen};
1199 my $ret = `./booklook $fen`;
1200 return "" if ($ret =~ /Not found/ || $ret eq '');
1204 for my $m (split /\n/, $ret) {
1205 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1209 $pmove = '(current)';
1211 ($pmove) = prettyprint_pv($board, $move);
1212 $pmove .= $annotation;
1216 if ($toplay eq 'W') {
1217 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1219 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1221 my $n = $win + $draw + $lose;
1227 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1230 push @moves, [ $pmove, $n, $percent, $rating ];
1233 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1235 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1236 for my $m (@moves) {
1237 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1244 my ($cmdline, $tag) = @_;
1245 my ($uciread, $uciwrite);
1246 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1258 uciprint($engine, "uci");
1260 # gobble the options
1261 while (<$uciread>) {
1263 handle_uci($engine, $_);
1273 # Read until we've got a full line -- if the engine sends part of
1274 # a line and then stops we're pretty much hosed, but that should
1277 while ($engine->{'readbuf'} !~ /\n/) {
1279 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1281 if (!defined($ret)) {
1282 next if ($!{EINTR});
1283 die "error in reading from the UCI engine: $!";
1284 } elsif ($ret == 0) {
1285 die "EOF from UCI engine";
1288 $engine->{'readbuf'} .= $tmp;
1293 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1295 $line =~ tr/\r\n//d;
1301 sub col_letter_to_num {
1302 return ord(shift) - ord('a');
1305 sub row_letter_to_num {
1306 return 7 - (ord(shift) - ord('1'));
1309 sub move_to_uci_notation {
1310 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1312 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);