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 = 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 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
72 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
73 uciprint($engine2, "setoption name NalimovUsage value Rarely");
74 uciprint($engine2, "setoption name Hash value 1024");
75 uciprint($engine2, "setoption name Threads value 8");
76 uciprint($engine2, "setoption name MultiPV value 500");
77 uciprint($engine2, "ucinewgame");
79 print "Chess engine ready.\n";
82 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
83 $t->input_log(\*FICSLOG);
85 $t->print("SesseBOT");
86 $t->waitfor('/Press return to enter the server/');
90 $t->cmd("set shout 0");
91 $t->cmd("set seek 0");
92 $t->cmd("set style 12");
93 $t->cmd("observe $target");
96 print "FICS ready.\n";
100 vec($rin, fileno($engine->{'read'}), 1) = 1;
101 vec($rin, fileno($engine2->{'read'}), 1) = 1;
102 vec($rin, fileno($t), 1) = 1;
104 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
108 my $line = $t->getline(Timeout => 0, errmode => 'return');
109 last if (!defined($line));
113 if ($line =~ /^<12> /) {
114 my $pos = style12_to_pos($line);
116 # if this is already in the queue, ignore it
117 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
119 # if we're already chewing on this and there's nothing else in the queue,
121 next if (!defined($pos_waiting) && defined($pos_calculating) &&
122 $pos->{'fen'} eq $pos_calculating->{'fen'});
124 # if we're already thinking on something, stop and wait for the engine
126 if (defined($pos_calculating)) {
127 if (!defined($pos_waiting)) {
128 uciprint($engine, "stop");
130 if ($uci_assume_full_compliance) {
133 uciprint($engine, "position fen " . $pos->{'fen'});
134 uciprint($engine, "go infinite");
135 $pos_calculating = $pos;
138 # it's wrong just to give the FEN (the move history is useful,
139 # and per the UCI spec, we should really have sent "ucinewgame"),
141 uciprint($engine, "position fen " . $pos->{'fen'});
142 uciprint($engine, "go infinite");
143 $pos_calculating = $pos;
146 if (defined($pos_calculating_second_engine)) {
147 uciprint($engine2, "stop");
149 uciprint($engine2, "position fen " . $pos->{'fen'});
150 uciprint($engine2, "go infinite");
151 $pos_calculating_second_engine = $pos;
154 $engine->{'info'} = {};
155 $engine2->{'info'} = {};
159 # Output a command every move to note that we're
160 # still paying attention -- this is a good tradeoff,
161 # since if no move has happened in the last half
162 # hour, the analysis/relay has most likely stopped
163 # and we should stop hogging server resources.
167 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
168 my ($who, $msg) = ($1, $2);
170 next if (grep { $_ eq $who } (@masters) == 0);
172 if ($msg =~ /^fics (.*?)$/) {
173 $t->cmd("tell $who Executing '$1' on FICS.");
175 } elsif ($msg =~ /^uci (.*?)$/) {
176 $t->cmd("tell $who Sending '$1' to the engine.");
177 print { $engine->{'write'} } "$1\n";
179 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
182 #print "FICS: [$line]\n";
186 # any fun on the UCI channel?
187 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
188 my @lines = read_lines($engine);
189 for my $line (@lines) {
190 next if $line =~ /(upper|lower)bound/;
191 handle_uci($engine, $line, 1);
197 if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
198 my @lines = read_lines($engine2);
199 for my $line (@lines) {
200 next if $line =~ /(upper|lower)bound/;
201 handle_uci($engine2, $line, 0);
212 my ($engine, $line, $primary) = @_;
216 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
217 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
218 if ($line =~ /^info/) {
219 my (@infos) = split / /, $line;
222 parse_infos($engine, @infos);
224 if ($line =~ /^id/) {
225 my (@ids) = split / /, $line;
228 parse_ids($engine, @ids);
230 if ($line =~ /^bestmove/) {
232 return if (!$uci_assume_full_compliance);
233 if (defined($pos_waiting)) {
234 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
235 uciprint($engine, "go infinite");
237 $pos_calculating = $pos_waiting;
238 $pos_waiting = undef;
241 $engine2->{'info'} = {};
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 if ($x[27] =~ /([a-h][1-8])-([a-h][1-8])/) {
348 $pos{'last_move_uci'} = $1 . $2;
350 $pos{'last_move_uci'} = undef;
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 $mpv = 1; $mpv < 500; ++$mpv) {
765 my $info = $engine2->{'info'};
766 last if (!exists($info->{'pv' . $mpv}));
768 my $pv = $info->{'pv' . $mpv};
770 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
771 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
772 if (scalar @pretty_pv > 5) {
773 @pretty_pv = @pretty_pv[0..4];
774 push @pretty_pv, "...";
776 my $key = $pretty_move;
777 my $line = sprintf(" %-6s %6s %3s %s",
779 short_score($info, $pos_calculating_second_engine, $mpv, 0),
780 "d" . $info->{'depth' . $mpv},
781 join(', ', @pretty_pv));
782 push @refutation_lines, [ $key, $line ];
786 if ($#refutation_lines >= 0) {
787 $text .= "Shallow search of all legal moves:\n\n";
788 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
789 $text .= $line->[1] . "\n";
794 if ($last_text ne $text) {
795 print "
\e[H
\e[2J"; # clear the screen
800 # Now construct the tell text, if any
801 return if (!defined($telltarget));
805 if (exists($id->{'name'})) {
806 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
808 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
811 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
814 while (exists($info->{'pv' . $mpv})) {
815 $tell_text .= sprintf " PV%2u", $mpv;
816 my $score = short_score($info, $pos_calculating, $mpv);
817 $tell_text .= " ($score)" if (defined($score));
819 if (exists($info->{'depth' . $mpv})) {
820 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
824 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
830 my $score = long_score($info, $pos_calculating, '');
831 $tell_text .= " $score\n" if defined($score);
832 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
833 if (exists($info->{'depth'})) {
834 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
839 # see if a new tell is called for -- it is if the delay has expired _and_
840 # this is not simply a repetition of the last one
841 if ($last_told_text ne $tell_text) {
843 for my $iv (@tell_intervals) {
844 last if ($now - $last_move < $iv);
845 next if ($last_tell - $last_move >= $iv);
847 for my $line (split /\n/, $tell_text) {
848 $t->print("tell $telltarget [$target] $line");
851 $last_told_text = $text;
860 my $info = $engine->{'info'};
863 $json->{'position'} = $pos_calculating;
864 $json->{'id'} = $engine->{'id'};
865 $json->{'score'} = long_score($info, $pos_calculating, '');
867 $json->{'nodes'} = $info->{'nodes'};
868 $json->{'nps'} = $info->{'nps'};
869 $json->{'depth'} = $info->{'depth'};
870 $json->{'tbhits'} = $info->{'tbhits'};
871 $json->{'seldepth'} = $info->{'seldepth'};
873 # single-PV only for now
874 $json->{'pv_uci'} = $info->{'pv'};
875 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
877 my %refutation_lines = ();
878 my @refutation_lines = ();
879 for (my $mpv = 1; $mpv < 500; ++$mpv) {
880 my $info = $engine2->{'info'};
881 my $pretty_move = "";
883 last if (!exists($info->{'pv' . $mpv}));
886 my $pv = $info->{'pv' . $mpv};
887 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
888 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
889 $refutation_lines{$pv->[0]} = {
890 sort_key => $pretty_move,
891 depth => $info->{'depth' . $mpv},
892 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
893 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
894 pretty_move => $pretty_move,
895 pv_pretty => \@pretty_pv,
897 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
900 $json->{'refutation_lines'} = \%refutation_lines;
902 open my $fh, ">analysis.json.tmp"
904 print $fh JSON::XS::encode_json($json);
906 rename("analysis.json.tmp", "analysis.json");
911 my ($wkr, $wkc, $bkr, $bkc);
915 my $piece = substr($board->[$row], $col, 1);
917 ($wkr, $wkc) = ($row, $col);
918 } elsif ($piece eq 'k') {
919 ($bkr, $bkc) = ($row, $col);
924 return ($wkr, $wkc, $bkr, $bkc);
929 my $check = in_check($board);
930 return 0 if ($check eq 'none');
932 # try all possible moves for the side in check
935 my $piece = substr($board->[$row], $col, 1);
936 next if ($piece eq '-');
938 if ($check eq 'white') {
939 next if ($piece eq lc($piece));
941 next if ($piece eq uc($piece));
944 for my $dest_row (0..7) {
945 for my $dest_col (0..7) {
946 next if ($row == $dest_row && $col == $dest_col);
947 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
950 substr($nb[$row], $col, 1, '-');
951 substr($nb[$dest_row], $dest_col, 1, $piece);
953 my $new_check = in_check(\@nb);
954 return 0 if ($new_check ne $check && $new_check ne 'both');
960 # nothing to do; mate
966 my ($black_check, $white_check) = (0, 0);
968 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
970 # check all pieces for the possibility of threatening the two kings
973 my $piece = substr($board->[$row], $col, 1);
974 next if ($piece eq '-');
976 if (uc($piece) eq $piece) {
978 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
981 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
986 if ($black_check && $white_check) {
988 } elsif ($black_check) {
990 } elsif ($white_check) {
998 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
1000 # can't eat your own piece
1001 my $dest_piece = substr($board->[$to_row], $to_col, 1);
1002 if ($dest_piece ne '-') {
1003 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1006 if (lc($piece) eq 'k') {
1007 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1009 if (lc($piece) eq 'r') {
1010 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1012 # check that there's a clear passage
1013 if ($from_row == $to_row) {
1014 if ($from_col > $to_col) {
1015 ($to_col, $from_col) = ($from_col, $to_col);
1018 for my $c (($from_col+1)..($to_col-1)) {
1019 my $middle_piece = substr($board->[$to_row], $c, 1);
1020 return 0 if ($middle_piece ne '-');
1025 if ($from_row > $to_row) {
1026 ($to_row, $from_row) = ($from_row, $to_row);
1029 for my $r (($from_row+1)..($to_row-1)) {
1030 my $middle_piece = substr($board->[$r], $to_col, 1);
1031 return 0 if ($middle_piece ne '-');
1037 if (lc($piece) eq 'b') {
1038 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1040 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1041 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1043 my $r = $from_row + $dr;
1044 my $c = $from_col + $dc;
1046 while ($r != $to_row) {
1047 my $middle_piece = substr($board->[$r], $c, 1);
1048 return 0 if ($middle_piece ne '-');
1056 if (lc($piece) eq 'n') {
1057 my $diff_r = abs($from_row - $to_row);
1058 my $diff_c = abs($from_col - $to_col);
1059 return 1 if ($diff_r == 2 && $diff_c == 1);
1060 return 1 if ($diff_r == 1 && $diff_c == 2);
1063 if ($piece eq 'q') {
1064 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1065 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1067 if ($piece eq 'Q') {
1068 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1069 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1073 if ($piece eq 'p') {
1075 if ($to_col == $from_col && $to_row == $from_row + 1) {
1076 return ($dest_piece eq '-');
1078 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1079 my $middle_piece = substr($board->[2], $to_col, 1);
1080 return ($dest_piece eq '-' && $middle_piece eq '-');
1082 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1083 return ($dest_piece ne '-');
1087 if ($piece eq 'P') {
1089 if ($to_col == $from_col && $to_row == $from_row - 1) {
1090 return ($dest_piece eq '-');
1092 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1093 my $middle_piece = substr($board->[5], $to_col, 1);
1094 return ($dest_piece eq '-' && $middle_piece eq '-');
1096 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1097 return ($dest_piece ne '-');
1107 my ($engine, $msg) = @_;
1108 print { $engine->{'write'} } "$msg\n";
1109 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1113 my ($info, $pos, $mpv, $invert) = @_;
1116 if ($pos->{'toplay'} eq 'B') {
1120 if (defined($info->{'score_mate' . $mpv})) {
1122 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1124 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1127 if (exists($info->{'score_cp' . $mpv})) {
1128 my $score = $info->{'score_cp' . $mpv} * 0.01;
1135 return sprintf "%+5.2f", $score;
1142 sub score_sort_key {
1143 my ($info, $pos, $mpv, $invert) = @_;
1145 if (defined($info->{'score_mate' . $mpv})) {
1147 return -(99999 - $info->{'score_mate' . $mpv});
1149 return 99999 - $info->{'score_mate' . $mpv};
1152 if (exists($info->{'score_cp' . $mpv})) {
1153 my $score = $info->{'score_cp' . $mpv};
1165 my ($info, $pos, $mpv) = @_;
1167 if (defined($info->{'score_mate' . $mpv})) {
1168 my $mate = $info->{'score_mate' . $mpv};
1169 if ($pos->{'toplay'} eq 'B') {
1173 return sprintf "White mates in %u", $mate;
1175 return sprintf "Black mates in %u", -$mate;
1178 if (exists($info->{'score_cp' . $mpv})) {
1179 my $score = $info->{'score_cp' . $mpv} * 0.01;
1180 if ($pos->{'toplay'} eq 'B') {
1183 return sprintf "Score: %+5.2f", $score;
1190 my %book_cache = ();
1192 my ($fen, $board, $toplay) = @_;
1194 if (exists($book_cache{$fen})) {
1195 return $book_cache{$fen};
1198 my $ret = `./booklook $fen`;
1199 return "" if ($ret =~ /Not found/ || $ret eq '');
1203 for my $m (split /\n/, $ret) {
1204 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1208 $pmove = '(current)';
1210 ($pmove) = prettyprint_pv($board, $move);
1211 $pmove .= $annotation;
1215 if ($toplay eq 'W') {
1216 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1218 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1220 my $n = $win + $draw + $lose;
1226 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1229 push @moves, [ $pmove, $n, $percent, $rating ];
1232 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1234 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1235 for my $m (@moves) {
1236 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1243 my ($cmdline, $tag) = @_;
1244 my ($uciread, $uciwrite);
1245 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1257 uciprint($engine, "uci");
1259 # gobble the options
1260 while (<$uciread>) {
1262 handle_uci($engine, $_);
1272 # Read until we've got a full line -- if the engine sends part of
1273 # a line and then stops we're pretty much hosed, but that should
1276 while ($engine->{'readbuf'} !~ /\n/) {
1278 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1280 if (!defined($ret)) {
1281 next if ($!{EINTR});
1282 die "error in reading from the UCI engine: $!";
1283 } elsif ($ret == 0) {
1284 die "EOF from UCI engine";
1287 $engine->{'readbuf'} .= $tmp;
1292 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1294 $line =~ tr/\r\n//d;
1300 sub col_letter_to_num {
1301 return ord(shift) - ord('a');
1304 sub row_letter_to_num {
1305 return 7 - (ord(shift) - ord('1'));
1308 sub move_to_uci_notation {
1309 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1311 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);