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"; # undef for none
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 = 1.0;
38 $SIG{ALRM} = sub { output(); };
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, $pos_calculating_second_engine);
64 uciprint($engine, "setoption name UCI_AnalyseMode value true");
65 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
66 uciprint($engine, "setoption name NalimovUsage value Rarely");
67 uciprint($engine, "setoption name Hash value 1024");
68 # uciprint($engine, "setoption name MultiPV value 2");
69 uciprint($engine, "ucinewgame");
71 if (defined($engine2)) {
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");
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 if (defined($engine2)) {
104 vec($rin, fileno($engine2->{'read'}), 1) = 1;
106 vec($rin, fileno($t), 1) = 1;
108 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
112 my $line = $t->getline(Timeout => 0, errmode => 'return');
113 last if (!defined($line));
117 if ($line =~ /^<12> /) {
118 my $pos = style12_to_pos($line);
120 # if this is already in the queue, ignore it
121 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
123 # if we're already chewing on this and there's nothing else in the queue,
125 next if (!defined($pos_waiting) && defined($pos_calculating) &&
126 $pos->{'fen'} eq $pos_calculating->{'fen'});
128 # if we're already thinking on something, stop and wait for the engine
130 if (defined($pos_calculating)) {
131 if (!defined($pos_waiting)) {
132 uciprint($engine, "stop");
134 if ($uci_assume_full_compliance) {
137 uciprint($engine, "position fen " . $pos->{'fen'});
138 uciprint($engine, "go infinite");
139 $pos_calculating = $pos;
142 # it's wrong just to give the FEN (the move history is useful,
143 # and per the UCI spec, we should really have sent "ucinewgame"),
145 uciprint($engine, "position fen " . $pos->{'fen'});
146 uciprint($engine, "go infinite");
147 $pos_calculating = $pos;
150 if (defined($engine2)) {
151 if (defined($pos_calculating_second_engine)) {
152 uciprint($engine2, "stop");
154 uciprint($engine2, "position fen " . $pos->{'fen'});
155 uciprint($engine2, "go infinite");
156 $pos_calculating_second_engine = $pos;
158 $engine2->{'info'} = {};
161 $engine->{'info'} = {};
165 # Output a command every move to note that we're
166 # still paying attention -- this is a good tradeoff,
167 # since if no move has happened in the last half
168 # hour, the analysis/relay has most likely stopped
169 # and we should stop hogging server resources.
173 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
174 my ($who, $msg) = ($1, $2);
176 next if (grep { $_ eq $who } (@masters) == 0);
178 if ($msg =~ /^fics (.*?)$/) {
179 $t->cmd("tell $who Executing '$1' on FICS.");
181 } elsif ($msg =~ /^uci (.*?)$/) {
182 $t->cmd("tell $who Sending '$1' to the engine.");
183 print { $engine->{'write'} } "$1\n";
185 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
188 #print "FICS: [$line]\n";
192 # any fun on the UCI channel?
193 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
194 my @lines = read_lines($engine);
195 for my $line (@lines) {
196 next if $line =~ /(upper|lower)bound/;
197 handle_uci($engine, $line, 1);
203 if (defined($engine2) && $nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
204 my @lines = read_lines($engine2);
205 for my $line (@lines) {
206 next if $line =~ /(upper|lower)bound/;
207 handle_uci($engine2, $line, 0);
218 my ($engine, $line, $primary) = @_;
222 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
223 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
224 if ($line =~ /^info/) {
225 my (@infos) = split / /, $line;
228 parse_infos($engine, @infos);
230 if ($line =~ /^id/) {
231 my (@ids) = split / /, $line;
234 parse_ids($engine, @ids);
236 if ($line =~ /^bestmove/) {
238 return if (!$uci_assume_full_compliance);
239 if (defined($pos_waiting)) {
240 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
241 uciprint($engine, "go infinite");
243 $pos_calculating = $pos_waiting;
244 $pos_waiting = undef;
247 $engine2->{'info'} = {};
248 my $pos = $pos_waiting // $pos_calculating;
249 uciprint($engine2, "position fen " . $pos->{'fen'});
250 uciprint($engine2, "go infinite");
251 $pos_calculating_second_engine = $pos;
257 my ($engine, @x) = @_;
260 my $info = $engine->{'info'};
262 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
263 for my $i (0..$#x - 1) {
264 if ($x[$i] =~ 'multipv') {
270 while (scalar @x > 0) {
271 if ($x[0] =~ 'multipv') {
277 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
279 my $value = shift @x;
280 $info->{$key} = $value;
283 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
285 my $value = shift @x;
286 $info->{$key . $mpv} = $value;
289 if ($x[0] eq 'score') {
292 delete $info->{'score_cp' . $mpv};
293 delete $info->{'score_mate' . $mpv};
295 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
298 $info->{'score_cp' . $mpv} = shift @x;
299 } elsif ($x[0] eq 'mate') {
301 $info->{'score_mate' . $mpv} = shift @x;
309 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
312 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
316 #print "unknown info '$x[0]', trying to recover...\n";
318 die "Unknown info '" . join(',', @x) . "'";
324 my ($engine, @x) = @_;
326 while (scalar @x > 0) {
327 if ($x[0] =~ /^(name|author)$/) {
329 my $value = join(' ', @x);
330 $engine->{'id'}{$key} = $value;
342 my (@x) = split / /, $str;
344 $pos{'board'} = [ @x[1..8] ];
345 $pos{'toplay'} = $x[9];
346 $pos{'ep_file_num'} = $x[10];
347 $pos{'white_castle_k'} = $x[11];
348 $pos{'white_castle_q'} = $x[12];
349 $pos{'black_castle_k'} = $x[13];
350 $pos{'black_castle_q'} = $x[14];
351 $pos{'time_to_100move_rule'} = $x[15];
352 $pos{'move_num'} = $x[26];
353 if ($x[27] =~ /([a-h][1-8])-([a-h][1-8])/) {
354 $pos{'last_move_uci'} = $1 . $2;
356 $pos{'last_move_uci'} = undef;
358 $pos{'last_move'} = $x[29];
359 $pos{'fen'} = make_fen(\%pos);
368 my (@board) = @{$pos->{'board'}};
369 for my $rank (0..7) {
370 $board[$rank] =~ s/(-+)/length($1)/ge;
372 my $fen = join('/', @board);
374 # white/black to move
376 $fen .= lc($pos->{'toplay'});
380 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
381 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
382 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
383 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
384 $castling = "-" if ($castling eq "");
385 # $castling = "-"; # chess960
391 if ($pos->{'ep_file_num'} != -1) {
392 my $col = $pos->{'ep_file_num'};
393 my $nep = (qw(a b c d e f g h))[$col];
395 if ($pos->{'toplay'} eq 'B') {
402 # Showing the en passant square when actually no capture can be made
403 # seems to confuse at least Rybka. Thus, check if there's actually
404 # a pawn of the opposite side that can do the en passant move, and if
405 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
406 # "right" thing as per the standard, though.
408 if ($pos->{'toplay'} eq 'B') {
409 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
410 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
412 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
413 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
421 $fen .= $pos->{'time_to_100move_rule'};
425 $fen .= $pos->{'move_num'};
431 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
432 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
433 my $piece = substr($board->[$from_row], $from_col, 1);
437 die "Invalid move $move";
440 # white short castling
441 if ($move eq 'e1g1' && $piece eq 'K') {
443 substr($nb[7], 4, 1, '-');
444 substr($nb[7], 6, 1, $piece);
447 substr($nb[7], 7, 1, '-');
448 substr($nb[7], 5, 1, 'R');
453 # white long castling
454 if ($move eq 'e1c1' && $piece eq 'K') {
456 substr($nb[7], 4, 1, '-');
457 substr($nb[7], 2, 1, $piece);
460 substr($nb[7], 0, 1, '-');
461 substr($nb[7], 3, 1, 'R');
466 # black short castling
467 if ($move eq 'e8g8' && $piece eq 'k') {
469 substr($nb[0], 4, 1, '-');
470 substr($nb[0], 6, 1, $piece);
473 substr($nb[0], 7, 1, '-');
474 substr($nb[0], 5, 1, 'r');
479 # black long castling
480 if ($move eq 'e8c8' && $piece eq 'k') {
482 substr($nb[0], 4, 1, '-');
483 substr($nb[0], 2, 1, $piece);
486 substr($nb[0], 0, 1, '-');
487 substr($nb[0], 3, 1, 'r');
492 # check if the from-piece is a pawn
493 if (lc($piece) eq 'p') {
495 if ($from_col != $to_col) {
497 if (substr($board->[$to_row], $to_col, 1) eq '-') {
499 substr($nb[$to_row + 1], $to_col, 1, '-');
501 substr($nb[$to_row - 1], $to_col, 1, '-');
516 substr($nb[$from_row], $from_col, 1, '-');
517 substr($nb[$to_row], $to_col, 1, $piece);
523 my ($board, @pvs) = @_;
525 if (scalar @pvs == 0 || !defined($pvs[0])) {
530 my $from_col = col_letter_to_num(substr($pv, 0, 1));
531 my $from_row = row_letter_to_num(substr($pv, 1, 1));
532 my $to_col = col_letter_to_num(substr($pv, 2, 1));
533 my $to_row = row_letter_to_num(substr($pv, 3, 1));
534 my $promo = substr($pv, 4, 1);
536 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
537 my $piece = substr($board->[$from_row], $from_col, 1);
540 die "Invalid move $pv";
543 # white short castling
544 if ($pv eq 'e1g1' && $piece eq 'K') {
545 return ('0-0', prettyprint_pv($nb, @pvs));
548 # white long castling
549 if ($pv eq 'e1c1' && $piece eq 'K') {
550 return ('0-0-0', prettyprint_pv($nb, @pvs));
553 # black short castling
554 if ($pv eq 'e8g8' && $piece eq 'k') {
555 return ('0-0', prettyprint_pv($nb, @pvs));
558 # black long castling
559 if ($pv eq 'e8c8' && $piece eq 'k') {
560 return ('0-0-0', prettyprint_pv($nb, @pvs));
565 # check if the from-piece is a pawn
566 if (lc($piece) eq 'p') {
568 if ($from_col != $to_col) {
569 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
571 $pretty = substr($pv, 2, 2);
573 if (length($pv) == 5) {
576 $pretty .= uc(substr($pv, 4, 1));
579 $piece = substr($pv, 4, 1);
581 $piece = uc(substr($pv, 4, 1));
586 $pretty = uc($piece);
588 # see how many of these pieces could go here, in all
592 next unless (substr($board->[$row], $col, 1) eq $piece);
593 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
597 # see how many of these pieces from the given row could go here
600 next unless (substr($board->[$from_row], $col, 1) eq $piece);
601 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
604 # and same for columns
607 next unless (substr($board->[$row], $from_col, 1) eq $piece);
608 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
611 # see if we need to disambiguate
612 if ($num_total > 1) {
614 $pretty .= substr($pv, 0, 1);
615 } elsif ($num_row == 1) {
616 $pretty .= substr($pv, 1, 1);
618 $pretty .= substr($pv, 0, 2);
623 if (substr($board->[$to_row], $to_col, 1) ne '-') {
627 $pretty .= substr($pv, 2, 2);
632 } elsif (in_check($nb) ne 'none') {
635 return ($pretty, prettyprint_pv($nb, @pvs));
641 return if (!defined($pos_calculating));
643 # Don't update too often.
644 my $age = Time::HiRes::tv_interval($latest_update);
645 if ($age < $update_max_interval) {
646 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
650 my $info = $engine->{'info'};
653 # Some programs _always_ report MultiPV, even with only one PV.
654 # In this case, we simply use that data as if MultiPV was never
657 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
658 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
659 if (exists($info->{$key . '1'})) {
660 $info->{$key} = $info->{$key . '1'};
666 # Check the PVs first. if they're invalid, just wait, as our data
667 # is most likely out of sync. This isn't a very good solution, as
668 # it can frequently miss stuff, but it's good enough for most users.
672 if (exists($info->{'pv'})) {
673 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
677 while (exists($info->{'pv' . $mpv})) {
678 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
683 $engine->{'info'} = {};
689 $latest_update = [Time::HiRes::gettimeofday];
693 my $info = $engine->{'info'};
694 my $id = $engine->{'id'};
696 my $text = 'Analysis';
697 if ($pos_calculating->{'last_move'} ne 'none') {
698 if ($pos_calculating->{'toplay'} eq 'W') {
699 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
701 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
703 if (exists($id->{'name'})) {
708 if (exists($id->{'name'})) {
709 $text .= " by $id->{'name'}:\n\n";
714 return unless (exists($pos_calculating->{'board'}));
716 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
719 while (exists($info->{'pv' . $mpv})) {
720 $text .= sprintf " PV%2u", $mpv;
721 my $score = short_score($info, $pos_calculating, $mpv);
722 $text .= " ($score)" if (defined($score));
725 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
726 if ($info->{'tbhits' . $mpv} == 1) {
727 $tbhits = ", 1 tbhit";
729 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
733 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
734 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
735 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
739 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
745 my $score = long_score($info, $pos_calculating, '');
746 $text .= " $score\n" if defined($score);
747 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
750 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
751 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
752 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
754 if (exists($info->{'seldepth'})) {
755 $text .= sprintf " (%u selective)", $info->{'seldepth'};
757 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
758 if ($info->{'tbhits'} == 1) {
759 $text .= ", one Nalimov hit";
761 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
767 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
769 my @refutation_lines = ();
770 if (defined($engine2)) {
771 for (my $mpv = 1; $mpv < 500; ++$mpv) {
772 my $info = $engine2->{'info'};
773 last if (!exists($info->{'pv' . $mpv}));
775 my $pv = $info->{'pv' . $mpv};
777 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
778 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
779 if (scalar @pretty_pv > 5) {
780 @pretty_pv = @pretty_pv[0..4];
781 push @pretty_pv, "...";
783 my $key = $pretty_move;
784 my $line = sprintf(" %-6s %6s %3s %s",
786 short_score($info, $pos_calculating_second_engine, $mpv, 0),
787 "d" . $info->{'depth' . $mpv},
788 join(', ', @pretty_pv));
789 push @refutation_lines, [ $key, $line ];
794 if ($#refutation_lines >= 0) {
795 $text .= "Shallow search of all legal moves:\n\n";
796 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
797 $text .= $line->[1] . "\n";
802 if ($last_text ne $text) {
803 print "
\e[H
\e[2J"; # clear the screen
808 # Now construct the tell text, if any
809 return if (!defined($telltarget));
813 if (exists($id->{'name'})) {
814 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
816 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
819 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
822 while (exists($info->{'pv' . $mpv})) {
823 $tell_text .= sprintf " PV%2u", $mpv;
824 my $score = short_score($info, $pos_calculating, $mpv);
825 $tell_text .= " ($score)" if (defined($score));
827 if (exists($info->{'depth' . $mpv})) {
828 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
832 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
838 my $score = long_score($info, $pos_calculating, '');
839 $tell_text .= " $score\n" if defined($score);
840 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
841 if (exists($info->{'depth'})) {
842 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
847 # see if a new tell is called for -- it is if the delay has expired _and_
848 # this is not simply a repetition of the last one
849 if ($last_told_text ne $tell_text) {
851 for my $iv (@tell_intervals) {
852 last if ($now - $last_move < $iv);
853 next if ($last_tell - $last_move >= $iv);
855 for my $line (split /\n/, $tell_text) {
856 $t->print("tell $telltarget [$target] $line");
859 $last_told_text = $text;
868 my $info = $engine->{'info'};
871 $json->{'position'} = $pos_calculating;
872 $json->{'id'} = $engine->{'id'};
873 $json->{'score'} = long_score($info, $pos_calculating, '');
875 $json->{'nodes'} = $info->{'nodes'};
876 $json->{'nps'} = $info->{'nps'};
877 $json->{'depth'} = $info->{'depth'};
878 $json->{'tbhits'} = $info->{'tbhits'};
879 $json->{'seldepth'} = $info->{'seldepth'};
881 # single-PV only for now
882 $json->{'pv_uci'} = $info->{'pv'};
883 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
885 my %refutation_lines = ();
886 my @refutation_lines = ();
887 if (defined($engine2)) {
888 for (my $mpv = 1; $mpv < 500; ++$mpv) {
889 my $info = $engine2->{'info'};
890 my $pretty_move = "";
892 last if (!exists($info->{'pv' . $mpv}));
895 my $pv = $info->{'pv' . $mpv};
896 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
897 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
898 $refutation_lines{$pv->[0]} = {
899 sort_key => $pretty_move,
900 depth => $info->{'depth' . $mpv},
901 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
902 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
903 pretty_move => $pretty_move,
904 pv_pretty => \@pretty_pv,
906 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
910 $json->{'refutation_lines'} = \%refutation_lines;
912 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
914 print $fh JSON::XS::encode_json($json);
916 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
921 my ($wkr, $wkc, $bkr, $bkc);
925 my $piece = substr($board->[$row], $col, 1);
927 ($wkr, $wkc) = ($row, $col);
928 } elsif ($piece eq 'k') {
929 ($bkr, $bkc) = ($row, $col);
934 return ($wkr, $wkc, $bkr, $bkc);
939 my $check = in_check($board);
940 return 0 if ($check eq 'none');
942 # try all possible moves for the side in check
945 my $piece = substr($board->[$row], $col, 1);
946 next if ($piece eq '-');
948 if ($check eq 'white') {
949 next if ($piece eq lc($piece));
951 next if ($piece eq uc($piece));
954 for my $dest_row (0..7) {
955 for my $dest_col (0..7) {
956 next if ($row == $dest_row && $col == $dest_col);
957 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
960 substr($nb[$row], $col, 1, '-');
961 substr($nb[$dest_row], $dest_col, 1, $piece);
963 my $new_check = in_check(\@nb);
964 return 0 if ($new_check ne $check && $new_check ne 'both');
970 # nothing to do; mate
976 my ($black_check, $white_check) = (0, 0);
978 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
980 # check all pieces for the possibility of threatening the two kings
983 my $piece = substr($board->[$row], $col, 1);
984 next if ($piece eq '-');
986 if (uc($piece) eq $piece) {
988 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
991 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
996 if ($black_check && $white_check) {
998 } elsif ($black_check) {
1000 } elsif ($white_check) {
1008 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
1010 # can't eat your own piece
1011 my $dest_piece = substr($board->[$to_row], $to_col, 1);
1012 if ($dest_piece ne '-') {
1013 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1016 if (lc($piece) eq 'k') {
1017 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1019 if (lc($piece) eq 'r') {
1020 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1022 # check that there's a clear passage
1023 if ($from_row == $to_row) {
1024 if ($from_col > $to_col) {
1025 ($to_col, $from_col) = ($from_col, $to_col);
1028 for my $c (($from_col+1)..($to_col-1)) {
1029 my $middle_piece = substr($board->[$to_row], $c, 1);
1030 return 0 if ($middle_piece ne '-');
1035 if ($from_row > $to_row) {
1036 ($to_row, $from_row) = ($from_row, $to_row);
1039 for my $r (($from_row+1)..($to_row-1)) {
1040 my $middle_piece = substr($board->[$r], $to_col, 1);
1041 return 0 if ($middle_piece ne '-');
1047 if (lc($piece) eq 'b') {
1048 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1050 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1051 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1053 my $r = $from_row + $dr;
1054 my $c = $from_col + $dc;
1056 while ($r != $to_row) {
1057 my $middle_piece = substr($board->[$r], $c, 1);
1058 return 0 if ($middle_piece ne '-');
1066 if (lc($piece) eq 'n') {
1067 my $diff_r = abs($from_row - $to_row);
1068 my $diff_c = abs($from_col - $to_col);
1069 return 1 if ($diff_r == 2 && $diff_c == 1);
1070 return 1 if ($diff_r == 1 && $diff_c == 2);
1073 if ($piece eq 'q') {
1074 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1075 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1077 if ($piece eq 'Q') {
1078 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1079 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1083 if ($piece eq 'p') {
1085 if ($to_col == $from_col && $to_row == $from_row + 1) {
1086 return ($dest_piece eq '-');
1088 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1089 my $middle_piece = substr($board->[2], $to_col, 1);
1090 return ($dest_piece eq '-' && $middle_piece eq '-');
1092 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1093 return ($dest_piece ne '-');
1097 if ($piece eq 'P') {
1099 if ($to_col == $from_col && $to_row == $from_row - 1) {
1100 return ($dest_piece eq '-');
1102 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1103 my $middle_piece = substr($board->[5], $to_col, 1);
1104 return ($dest_piece eq '-' && $middle_piece eq '-');
1106 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1107 return ($dest_piece ne '-');
1117 my ($engine, $msg) = @_;
1118 print { $engine->{'write'} } "$msg\n";
1119 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1123 my ($info, $pos, $mpv, $invert) = @_;
1126 if ($pos->{'toplay'} eq 'B') {
1130 if (defined($info->{'score_mate' . $mpv})) {
1132 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1134 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1137 if (exists($info->{'score_cp' . $mpv})) {
1138 my $score = $info->{'score_cp' . $mpv} * 0.01;
1145 return sprintf "%+5.2f", $score;
1152 sub score_sort_key {
1153 my ($info, $pos, $mpv, $invert) = @_;
1155 if (defined($info->{'score_mate' . $mpv})) {
1157 return 99999 - $info->{'score_mate' . $mpv};
1159 return -(99999 - $info->{'score_mate' . $mpv});
1162 if (exists($info->{'score_cp' . $mpv})) {
1163 my $score = $info->{'score_cp' . $mpv};
1175 my ($info, $pos, $mpv) = @_;
1177 if (defined($info->{'score_mate' . $mpv})) {
1178 my $mate = $info->{'score_mate' . $mpv};
1179 if ($pos->{'toplay'} eq 'B') {
1183 return sprintf "White mates in %u", $mate;
1185 return sprintf "Black mates in %u", -$mate;
1188 if (exists($info->{'score_cp' . $mpv})) {
1189 my $score = $info->{'score_cp' . $mpv} * 0.01;
1191 return "Score: 0.00";
1193 if ($pos->{'toplay'} eq 'B') {
1196 return sprintf "Score: %+5.2f", $score;
1203 my %book_cache = ();
1205 my ($fen, $board, $toplay) = @_;
1207 if (exists($book_cache{$fen})) {
1208 return $book_cache{$fen};
1211 my $ret = `./booklook $fen`;
1212 return "" if ($ret =~ /Not found/ || $ret eq '');
1216 for my $m (split /\n/, $ret) {
1217 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1221 $pmove = '(current)';
1223 ($pmove) = prettyprint_pv($board, $move);
1224 $pmove .= $annotation;
1228 if ($toplay eq 'W') {
1229 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1231 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1233 my $n = $win + $draw + $lose;
1239 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1242 push @moves, [ $pmove, $n, $percent, $rating ];
1245 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1247 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1248 for my $m (@moves) {
1249 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1256 my ($cmdline, $tag) = @_;
1258 return undef if (!defined($cmdline));
1260 my ($uciread, $uciwrite);
1261 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1273 uciprint($engine, "uci");
1275 # gobble the options
1276 while (<$uciread>) {
1278 handle_uci($engine, $_);
1288 # Read until we've got a full line -- if the engine sends part of
1289 # a line and then stops we're pretty much hosed, but that should
1292 while ($engine->{'readbuf'} !~ /\n/) {
1294 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1296 if (!defined($ret)) {
1297 next if ($!{EINTR});
1298 die "error in reading from the UCI engine: $!";
1299 } elsif ($ret == 0) {
1300 die "EOF from UCI engine";
1303 $engine->{'readbuf'} .= $tmp;
1308 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1310 $line =~ tr/\r\n//d;
1316 sub col_letter_to_num {
1317 return ord(shift) - ord('a');
1320 sub row_letter_to_num {
1321 return 7 - (ord(shift) - ord('1'));
1324 sub move_to_uci_notation {
1325 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1327 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);