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 my $pos = $pos_waiting // $pos_calculating;
243 uciprint($engine2, "position fen " . $pos->{'fen'});
244 uciprint($engine2, "go infinite");
245 $pos_calculating_second_engine = $pos;
251 my ($engine, @x) = @_;
254 my $info = $engine->{'info'};
256 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
257 for my $i (0..$#x - 1) {
258 if ($x[$i] =~ 'multipv') {
264 while (scalar @x > 0) {
265 if ($x[0] =~ 'multipv') {
271 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
273 my $value = shift @x;
274 $info->{$key} = $value;
277 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
279 my $value = shift @x;
280 $info->{$key . $mpv} = $value;
283 if ($x[0] eq 'score') {
286 delete $info->{'score_cp' . $mpv};
287 delete $info->{'score_mate' . $mpv};
289 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
292 $info->{'score_cp' . $mpv} = shift @x;
293 } elsif ($x[0] eq 'mate') {
295 $info->{'score_mate' . $mpv} = shift @x;
303 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
306 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
310 #print "unknown info '$x[0]', trying to recover...\n";
312 die "Unknown info '" . join(',', @x) . "'";
318 my ($engine, @x) = @_;
320 while (scalar @x > 0) {
321 if ($x[0] =~ /^(name|author)$/) {
323 my $value = join(' ', @x);
324 $engine->{'id'}{$key} = $value;
336 my (@x) = split / /, $str;
338 $pos{'board'} = [ @x[1..8] ];
339 $pos{'toplay'} = $x[9];
340 $pos{'ep_file_num'} = $x[10];
341 $pos{'white_castle_k'} = $x[11];
342 $pos{'white_castle_q'} = $x[12];
343 $pos{'black_castle_k'} = $x[13];
344 $pos{'black_castle_q'} = $x[14];
345 $pos{'time_to_100move_rule'} = $x[15];
346 $pos{'move_num'} = $x[26];
347 $pos{'last_move'} = $x[29];
348 $pos{'fen'} = make_fen(\%pos);
357 my (@board) = @{$pos->{'board'}};
358 for my $rank (0..7) {
359 $board[$rank] =~ s/(-+)/length($1)/ge;
361 my $fen = join('/', @board);
363 # white/black to move
365 $fen .= lc($pos->{'toplay'});
369 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
370 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
371 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
372 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
373 $castling = "-" if ($castling eq "");
374 # $castling = "-"; # chess960
380 if ($pos->{'ep_file_num'} != -1) {
381 my $col = $pos->{'ep_file_num'};
382 my $nep = (qw(a b c d e f g h))[$col];
384 if ($pos->{'toplay'} eq 'B') {
391 # Showing the en passant square when actually no capture can be made
392 # seems to confuse at least Rybka. Thus, check if there's actually
393 # a pawn of the opposite side that can do the en passant move, and if
394 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
395 # "right" thing as per the standard, though.
397 if ($pos->{'toplay'} eq 'B') {
398 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
399 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
401 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
402 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
410 $fen .= $pos->{'time_to_100move_rule'};
414 $fen .= $pos->{'move_num'};
420 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
421 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
422 my $piece = substr($board->[$from_row], $from_col, 1);
426 die "Invalid move $move";
429 # white short castling
430 if ($move eq 'e1g1' && $piece eq 'K') {
432 substr($nb[7], 4, 1, '-');
433 substr($nb[7], 6, 1, $piece);
436 substr($nb[7], 7, 1, '-');
437 substr($nb[7], 5, 1, 'R');
442 # white long castling
443 if ($move eq 'e1c1' && $piece eq 'K') {
445 substr($nb[7], 4, 1, '-');
446 substr($nb[7], 2, 1, $piece);
449 substr($nb[7], 0, 1, '-');
450 substr($nb[7], 3, 1, 'R');
455 # black short castling
456 if ($move eq 'e8g8' && $piece eq 'k') {
458 substr($nb[0], 4, 1, '-');
459 substr($nb[0], 6, 1, $piece);
462 substr($nb[0], 7, 1, '-');
463 substr($nb[0], 5, 1, 'r');
468 # black long castling
469 if ($move eq 'e8c8' && $piece eq 'k') {
471 substr($nb[0], 4, 1, '-');
472 substr($nb[0], 2, 1, $piece);
475 substr($nb[0], 0, 1, '-');
476 substr($nb[0], 3, 1, 'r');
481 # check if the from-piece is a pawn
482 if (lc($piece) eq 'p') {
484 if ($from_col != $to_col) {
486 if (substr($board->[$to_row], $to_col, 1) eq '-') {
488 substr($nb[$to_row + 1], $to_col, 1, '-');
490 substr($nb[$to_row - 1], $to_col, 1, '-');
505 substr($nb[$from_row], $from_col, 1, '-');
506 substr($nb[$to_row], $to_col, 1, $piece);
512 my ($board, @pvs) = @_;
514 if (scalar @pvs == 0 || !defined($pvs[0])) {
519 my $from_col = col_letter_to_num(substr($pv, 0, 1));
520 my $from_row = row_letter_to_num(substr($pv, 1, 1));
521 my $to_col = col_letter_to_num(substr($pv, 2, 1));
522 my $to_row = row_letter_to_num(substr($pv, 3, 1));
523 my $promo = substr($pv, 4, 1);
525 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
526 my $piece = substr($board->[$from_row], $from_col, 1);
529 die "Invalid move $pv";
532 # white short castling
533 if ($pv eq 'e1g1' && $piece eq 'K') {
534 return ('0-0', prettyprint_pv($nb, @pvs));
537 # white long castling
538 if ($pv eq 'e1c1' && $piece eq 'K') {
539 return ('0-0-0', prettyprint_pv($nb, @pvs));
542 # black short castling
543 if ($pv eq 'e8g8' && $piece eq 'k') {
544 return ('0-0', prettyprint_pv($nb, @pvs));
547 # black long castling
548 if ($pv eq 'e8c8' && $piece eq 'k') {
549 return ('0-0-0', prettyprint_pv($nb, @pvs));
554 # check if the from-piece is a pawn
555 if (lc($piece) eq 'p') {
557 if ($from_col != $to_col) {
558 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
560 $pretty = substr($pv, 2, 2);
562 if (length($pv) == 5) {
565 $pretty .= uc(substr($pv, 4, 1));
568 $piece = substr($pv, 4, 1);
570 $piece = uc(substr($pv, 4, 1));
575 $pretty = uc($piece);
577 # see how many of these pieces could go here, in all
581 next unless (substr($board->[$row], $col, 1) eq $piece);
582 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
586 # see how many of these pieces from the given row could go here
589 next unless (substr($board->[$from_row], $col, 1) eq $piece);
590 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
593 # and same for columns
596 next unless (substr($board->[$row], $from_col, 1) eq $piece);
597 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
600 # see if we need to disambiguate
601 if ($num_total > 1) {
603 $pretty .= substr($pv, 0, 1);
604 } elsif ($num_row == 1) {
605 $pretty .= substr($pv, 1, 1);
607 $pretty .= substr($pv, 0, 2);
612 if (substr($board->[$to_row], $to_col, 1) ne '-') {
616 $pretty .= substr($pv, 2, 2);
621 } elsif (in_check($nb) ne 'none') {
624 return ($pretty, prettyprint_pv($nb, @pvs));
630 return if (!defined($pos_calculating));
632 # Don't update too often.
633 my $age = Time::HiRes::tv_interval($latest_update);
634 if ($age < $update_max_interval) {
635 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
639 my $info = $engine->{'info'};
642 # Some programs _always_ report MultiPV, even with only one PV.
643 # In this case, we simply use that data as if MultiPV was never
646 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
647 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
648 if (exists($info->{$key . '1'})) {
649 $info->{$key} = $info->{$key . '1'};
655 # Check the PVs first. if they're invalid, just wait, as our data
656 # is most likely out of sync. This isn't a very good solution, as
657 # it can frequently miss stuff, but it's good enough for most users.
661 if (exists($info->{'pv'})) {
662 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
666 while (exists($info->{'pv' . $mpv})) {
667 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
672 $engine->{'info'} = {};
678 $latest_update = [Time::HiRes::gettimeofday];
682 my $info = $engine->{'info'};
683 my $id = $engine->{'id'};
685 my $text = 'Analysis';
686 if ($pos_calculating->{'last_move'} ne 'none') {
687 if ($pos_calculating->{'toplay'} eq 'W') {
688 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
690 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
692 if (exists($id->{'name'})) {
697 if (exists($id->{'name'})) {
698 $text .= " by $id->{'name'}:\n\n";
703 return unless (exists($pos_calculating->{'board'}));
705 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
708 while (exists($info->{'pv' . $mpv})) {
709 $text .= sprintf " PV%2u", $mpv;
710 my $score = short_score($info, $pos_calculating, $mpv);
711 $text .= " ($score)" if (defined($score));
714 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
715 if ($info->{'tbhits' . $mpv} == 1) {
716 $tbhits = ", 1 tbhit";
718 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
722 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
723 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
724 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
728 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
734 my $score = long_score($info, $pos_calculating, '');
735 $text .= " $score\n" if defined($score);
736 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
739 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
740 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
741 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
743 if (exists($info->{'seldepth'})) {
744 $text .= sprintf " (%u selective)", $info->{'seldepth'};
746 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
747 if ($info->{'tbhits'} == 1) {
748 $text .= ", one Nalimov hit";
750 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
756 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
758 my @refutation_lines = ();
759 for (my $mpv = 1; $mpv < 500; ++$mpv) {
760 my $info = $engine2->{'info'};
761 last if (!exists($info->{'pv' . $mpv}));
763 my $pv = $info->{'pv' . $mpv};
765 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
766 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
767 if (scalar @pretty_pv > 5) {
768 @pretty_pv = @pretty_pv[0..4];
769 push @pretty_pv, "...";
771 my $key = $pretty_move;
772 my $line = sprintf(" %-6s %6s %3s %s",
774 short_score($info, $pos_calculating_second_engine, $mpv, 1),
775 "d" . $info->{'depth' . $mpv},
776 join(', ', @pretty_pv));
777 push @refutation_lines, [ $key, $line ];
781 if ($#refutation_lines >= 0) {
782 $text .= "Shallow search of all legal moves:\n\n";
783 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
784 $text .= $line->[1] . "\n";
789 if ($last_text ne $text) {
790 print "
\e[H
\e[2J"; # clear the screen
795 # Now construct the tell text, if any
796 return if (!defined($telltarget));
800 if (exists($id->{'name'})) {
801 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
803 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
806 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
809 while (exists($info->{'pv' . $mpv})) {
810 $tell_text .= sprintf " PV%2u", $mpv;
811 my $score = short_score($info, $pos_calculating, $mpv);
812 $tell_text .= " ($score)" if (defined($score));
814 if (exists($info->{'depth' . $mpv})) {
815 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
819 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
825 my $score = long_score($info, $pos_calculating, '');
826 $tell_text .= " $score\n" if defined($score);
827 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
828 if (exists($info->{'depth'})) {
829 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
834 # see if a new tell is called for -- it is if the delay has expired _and_
835 # this is not simply a repetition of the last one
836 if ($last_told_text ne $tell_text) {
838 for my $iv (@tell_intervals) {
839 last if ($now - $last_move < $iv);
840 next if ($last_tell - $last_move >= $iv);
842 for my $line (split /\n/, $tell_text) {
843 $t->print("tell $telltarget [$target] $line");
846 $last_told_text = $text;
855 my $info = $engine->{'info'};
858 $json->{'position'} = $pos_calculating;
859 $json->{'id'} = $engine->{'id'};
860 $json->{'score'} = long_score($info, $pos_calculating, '');
862 $json->{'nodes'} = $info->{'nodes'};
863 $json->{'nps'} = $info->{'nps'};
864 $json->{'depth'} = $info->{'depth'};
865 $json->{'tbhits'} = $info->{'tbhits'};
866 $json->{'seldepth'} = $info->{'seldepth'};
868 # single-PV only for now
869 $json->{'pv_uci'} = $info->{'pv'};
870 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
872 my %refutation_lines = ();
873 my @refutation_lines = ();
874 for (my $mpv = 1; $mpv < 500; ++$mpv) {
875 my $info = $engine2->{'info'};
876 my $pretty_move = "";
878 last if (!exists($info->{'pv' . $mpv}));
881 my $pv = $info->{'pv' . $mpv};
882 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
883 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
884 $refutation_lines{$pv->[0]} = {
885 sort_key => $pretty_move,
886 depth => $info->{'depth' . $mpv},
887 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
888 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
889 pretty_move => $pretty_move,
890 pv_pretty => \@pretty_pv,
892 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
895 $json->{'refutation_lines'} = \%refutation_lines;
897 open my $fh, ">analysis.json.tmp"
899 print $fh JSON::XS::encode_json($json);
901 rename("analysis.json.tmp", "analysis.json");
906 my ($wkr, $wkc, $bkr, $bkc);
910 my $piece = substr($board->[$row], $col, 1);
912 ($wkr, $wkc) = ($row, $col);
913 } elsif ($piece eq 'k') {
914 ($bkr, $bkc) = ($row, $col);
919 return ($wkr, $wkc, $bkr, $bkc);
924 my $check = in_check($board);
925 return 0 if ($check eq 'none');
927 # try all possible moves for the side in check
930 my $piece = substr($board->[$row], $col, 1);
931 next if ($piece eq '-');
933 if ($check eq 'white') {
934 next if ($piece eq lc($piece));
936 next if ($piece eq uc($piece));
939 for my $dest_row (0..7) {
940 for my $dest_col (0..7) {
941 next if ($row == $dest_row && $col == $dest_col);
942 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
945 substr($nb[$row], $col, 1, '-');
946 substr($nb[$dest_row], $dest_col, 1, $piece);
948 my $new_check = in_check(\@nb);
949 return 0 if ($new_check ne $check && $new_check ne 'both');
955 # nothing to do; mate
961 my ($black_check, $white_check) = (0, 0);
963 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
965 # check all pieces for the possibility of threatening the two kings
968 my $piece = substr($board->[$row], $col, 1);
969 next if ($piece eq '-');
971 if (uc($piece) eq $piece) {
973 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
976 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
981 if ($black_check && $white_check) {
983 } elsif ($black_check) {
985 } elsif ($white_check) {
993 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
995 # can't eat your own piece
996 my $dest_piece = substr($board->[$to_row], $to_col, 1);
997 if ($dest_piece ne '-') {
998 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1001 if (lc($piece) eq 'k') {
1002 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1004 if (lc($piece) eq 'r') {
1005 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1007 # check that there's a clear passage
1008 if ($from_row == $to_row) {
1009 if ($from_col > $to_col) {
1010 ($to_col, $from_col) = ($from_col, $to_col);
1013 for my $c (($from_col+1)..($to_col-1)) {
1014 my $middle_piece = substr($board->[$to_row], $c, 1);
1015 return 0 if ($middle_piece ne '-');
1020 if ($from_row > $to_row) {
1021 ($to_row, $from_row) = ($from_row, $to_row);
1024 for my $r (($from_row+1)..($to_row-1)) {
1025 my $middle_piece = substr($board->[$r], $to_col, 1);
1026 return 0 if ($middle_piece ne '-');
1032 if (lc($piece) eq 'b') {
1033 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1035 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1036 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1038 my $r = $from_row + $dr;
1039 my $c = $from_col + $dc;
1041 while ($r != $to_row) {
1042 my $middle_piece = substr($board->[$r], $c, 1);
1043 return 0 if ($middle_piece ne '-');
1051 if (lc($piece) eq 'n') {
1052 my $diff_r = abs($from_row - $to_row);
1053 my $diff_c = abs($from_col - $to_col);
1054 return 1 if ($diff_r == 2 && $diff_c == 1);
1055 return 1 if ($diff_r == 1 && $diff_c == 2);
1058 if ($piece eq 'q') {
1059 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1060 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1062 if ($piece eq 'Q') {
1063 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1064 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1068 if ($piece eq 'p') {
1070 if ($to_col == $from_col && $to_row == $from_row + 1) {
1071 return ($dest_piece eq '-');
1073 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1074 my $middle_piece = substr($board->[2], $to_col, 1);
1075 return ($dest_piece eq '-' && $middle_piece eq '-');
1077 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1078 return ($dest_piece ne '-');
1082 if ($piece eq 'P') {
1084 if ($to_col == $from_col && $to_row == $from_row - 1) {
1085 return ($dest_piece eq '-');
1087 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1088 my $middle_piece = substr($board->[5], $to_col, 1);
1089 return ($dest_piece eq '-' && $middle_piece eq '-');
1091 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1092 return ($dest_piece ne '-');
1102 my ($engine, $msg) = @_;
1103 print { $engine->{'write'} } "$msg\n";
1104 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1108 my ($info, $pos, $mpv, $invert) = @_;
1111 if ($pos->{'toplay'} eq 'B') {
1115 if (defined($info->{'score_mate' . $mpv})) {
1117 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1119 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1122 if (exists($info->{'score_cp' . $mpv})) {
1123 my $score = $info->{'score_cp' . $mpv} * 0.01;
1130 return sprintf "%+5.2f", $score;
1137 sub score_sort_key {
1138 my ($info, $pos, $mpv, $invert) = @_;
1140 if (defined($info->{'score_mate' . $mpv})) {
1142 return -(99999 - $info->{'score_mate' . $mpv});
1144 return 99999 - $info->{'score_mate' . $mpv};
1147 if (exists($info->{'score_cp' . $mpv})) {
1148 my $score = $info->{'score_cp' . $mpv};
1160 my ($info, $pos, $mpv) = @_;
1162 if (defined($info->{'score_mate' . $mpv})) {
1163 my $mate = $info->{'score_mate' . $mpv};
1164 if ($pos->{'toplay'} eq 'B') {
1168 return sprintf "White mates in %u", $mate;
1170 return sprintf "Black mates in %u", -$mate;
1173 if (exists($info->{'score_cp' . $mpv})) {
1174 my $score = $info->{'score_cp' . $mpv} * 0.01;
1175 if ($pos->{'toplay'} eq 'B') {
1178 return sprintf "Score: %+5.2f", $score;
1185 my %book_cache = ();
1187 my ($fen, $board, $toplay) = @_;
1189 if (exists($book_cache{$fen})) {
1190 return $book_cache{$fen};
1193 my $ret = `./booklook $fen`;
1194 return "" if ($ret =~ /Not found/ || $ret eq '');
1198 for my $m (split /\n/, $ret) {
1199 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1203 $pmove = '(current)';
1205 ($pmove) = prettyprint_pv($board, $move);
1206 $pmove .= $annotation;
1210 if ($toplay eq 'W') {
1211 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1213 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1215 my $n = $win + $draw + $lose;
1221 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1224 push @moves, [ $pmove, $n, $percent, $rating ];
1227 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1229 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1230 for my $m (@moves) {
1231 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1238 my ($cmdline, $tag) = @_;
1239 my ($uciread, $uciwrite);
1240 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1252 uciprint($engine, "uci");
1254 # gobble the options
1255 while (<$uciread>) {
1257 handle_uci($engine, $_);
1267 # Read until we've got a full line -- if the engine sends part of
1268 # a line and then stops we're pretty much hosed, but that should
1271 while ($engine->{'readbuf'} !~ /\n/) {
1273 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1275 if (!defined($ret)) {
1276 next if ($!{EINTR});
1277 die "error in reading from the UCI engine: $!";
1278 } elsif ($ret == 0) {
1279 die "EOF from UCI engine";
1282 $engine->{'readbuf'} .= $tmp;
1287 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1289 $line =~ tr/\r\n//d;
1295 sub col_letter_to_num {
1296 return ord(shift) - ord('a');
1299 sub row_letter_to_num {
1300 return 7 - (ord(shift) - ord('1'));
1303 sub move_to_uci_notation {
1304 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1306 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);