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{'player_w'} = $x[17];
353 $pos{'player_b'} = $x[18];
354 $pos{'player_w'} =~ s/^[IG]M//;
355 $pos{'player_b'} =~ s/^[IG]M//;
356 $pos{'move_num'} = $x[26];
357 if ($x[27] =~ /([a-h][1-8])-([a-h][1-8])/) {
358 $pos{'last_move_uci'} = $1 . $2;
360 $pos{'last_move_uci'} = undef;
362 $pos{'last_move'} = $x[29];
363 $pos{'fen'} = make_fen(\%pos);
372 my (@board) = @{$pos->{'board'}};
373 for my $rank (0..7) {
374 $board[$rank] =~ s/(-+)/length($1)/ge;
376 my $fen = join('/', @board);
378 # white/black to move
380 $fen .= lc($pos->{'toplay'});
384 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
385 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
386 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
387 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
388 $castling = "-" if ($castling eq "");
389 # $castling = "-"; # chess960
395 if ($pos->{'ep_file_num'} != -1) {
396 my $col = $pos->{'ep_file_num'};
397 my $nep = (qw(a b c d e f g h))[$col];
399 if ($pos->{'toplay'} eq 'B') {
406 # Showing the en passant square when actually no capture can be made
407 # seems to confuse at least Rybka. Thus, check if there's actually
408 # a pawn of the opposite side that can do the en passant move, and if
409 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
410 # "right" thing as per the standard, though.
412 if ($pos->{'toplay'} eq 'B') {
413 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
414 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
416 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
417 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
425 $fen .= $pos->{'time_to_100move_rule'};
429 $fen .= $pos->{'move_num'};
435 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
436 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
437 my $piece = substr($board->[$from_row], $from_col, 1);
441 die "Invalid move $move";
444 # white short castling
445 if ($move eq 'e1g1' && $piece eq 'K') {
447 substr($nb[7], 4, 1, '-');
448 substr($nb[7], 6, 1, $piece);
451 substr($nb[7], 7, 1, '-');
452 substr($nb[7], 5, 1, 'R');
457 # white long castling
458 if ($move eq 'e1c1' && $piece eq 'K') {
460 substr($nb[7], 4, 1, '-');
461 substr($nb[7], 2, 1, $piece);
464 substr($nb[7], 0, 1, '-');
465 substr($nb[7], 3, 1, 'R');
470 # black short castling
471 if ($move eq 'e8g8' && $piece eq 'k') {
473 substr($nb[0], 4, 1, '-');
474 substr($nb[0], 6, 1, $piece);
477 substr($nb[0], 7, 1, '-');
478 substr($nb[0], 5, 1, 'r');
483 # black long castling
484 if ($move eq 'e8c8' && $piece eq 'k') {
486 substr($nb[0], 4, 1, '-');
487 substr($nb[0], 2, 1, $piece);
490 substr($nb[0], 0, 1, '-');
491 substr($nb[0], 3, 1, 'r');
496 # check if the from-piece is a pawn
497 if (lc($piece) eq 'p') {
499 if ($from_col != $to_col) {
501 if (substr($board->[$to_row], $to_col, 1) eq '-') {
503 substr($nb[$to_row + 1], $to_col, 1, '-');
505 substr($nb[$to_row - 1], $to_col, 1, '-');
520 substr($nb[$from_row], $from_col, 1, '-');
521 substr($nb[$to_row], $to_col, 1, $piece);
527 my ($board, @pvs) = @_;
529 if (scalar @pvs == 0 || !defined($pvs[0])) {
534 my $from_col = col_letter_to_num(substr($pv, 0, 1));
535 my $from_row = row_letter_to_num(substr($pv, 1, 1));
536 my $to_col = col_letter_to_num(substr($pv, 2, 1));
537 my $to_row = row_letter_to_num(substr($pv, 3, 1));
538 my $promo = substr($pv, 4, 1);
540 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
541 my $piece = substr($board->[$from_row], $from_col, 1);
544 die "Invalid move $pv";
547 # white short castling
548 if ($pv eq 'e1g1' && $piece eq 'K') {
549 return ('0-0', prettyprint_pv($nb, @pvs));
552 # white long castling
553 if ($pv eq 'e1c1' && $piece eq 'K') {
554 return ('0-0-0', prettyprint_pv($nb, @pvs));
557 # black short castling
558 if ($pv eq 'e8g8' && $piece eq 'k') {
559 return ('0-0', prettyprint_pv($nb, @pvs));
562 # black long castling
563 if ($pv eq 'e8c8' && $piece eq 'k') {
564 return ('0-0-0', prettyprint_pv($nb, @pvs));
569 # check if the from-piece is a pawn
570 if (lc($piece) eq 'p') {
572 if ($from_col != $to_col) {
573 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
575 $pretty = substr($pv, 2, 2);
577 if (length($pv) == 5) {
580 $pretty .= uc(substr($pv, 4, 1));
583 $piece = substr($pv, 4, 1);
585 $piece = uc(substr($pv, 4, 1));
590 $pretty = uc($piece);
592 # see how many of these pieces could go here, in all
596 next unless (substr($board->[$row], $col, 1) eq $piece);
597 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
601 # see how many of these pieces from the given row could go here
604 next unless (substr($board->[$from_row], $col, 1) eq $piece);
605 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
608 # and same for columns
611 next unless (substr($board->[$row], $from_col, 1) eq $piece);
612 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
615 # see if we need to disambiguate
616 if ($num_total > 1) {
618 $pretty .= substr($pv, 0, 1);
619 } elsif ($num_row == 1) {
620 $pretty .= substr($pv, 1, 1);
622 $pretty .= substr($pv, 0, 2);
627 if (substr($board->[$to_row], $to_col, 1) ne '-') {
631 $pretty .= substr($pv, 2, 2);
636 } elsif (in_check($nb) ne 'none') {
639 return ($pretty, prettyprint_pv($nb, @pvs));
645 return if (!defined($pos_calculating));
647 # Don't update too often.
648 my $age = Time::HiRes::tv_interval($latest_update);
649 if ($age < $update_max_interval) {
650 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
654 my $info = $engine->{'info'};
657 # Some programs _always_ report MultiPV, even with only one PV.
658 # In this case, we simply use that data as if MultiPV was never
661 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
662 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
663 if (exists($info->{$key . '1'})) {
664 $info->{$key} = $info->{$key . '1'};
670 # Check the PVs first. if they're invalid, just wait, as our data
671 # is most likely out of sync. This isn't a very good solution, as
672 # it can frequently miss stuff, but it's good enough for most users.
676 if (exists($info->{'pv'})) {
677 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
681 while (exists($info->{'pv' . $mpv})) {
682 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
687 $engine->{'info'} = {};
693 $latest_update = [Time::HiRes::gettimeofday];
697 my $info = $engine->{'info'};
698 my $id = $engine->{'id'};
700 my $text = 'Analysis';
701 if ($pos_calculating->{'last_move'} ne 'none') {
702 if ($pos_calculating->{'toplay'} eq 'W') {
703 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
705 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
707 if (exists($id->{'name'})) {
712 if (exists($id->{'name'})) {
713 $text .= " by $id->{'name'}:\n\n";
718 return unless (exists($pos_calculating->{'board'}));
720 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
723 while (exists($info->{'pv' . $mpv})) {
724 $text .= sprintf " PV%2u", $mpv;
725 my $score = short_score($info, $pos_calculating, $mpv);
726 $text .= " ($score)" if (defined($score));
729 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
730 if ($info->{'tbhits' . $mpv} == 1) {
731 $tbhits = ", 1 tbhit";
733 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
737 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
738 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
739 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
743 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
749 my $score = long_score($info, $pos_calculating, '');
750 $text .= " $score\n" if defined($score);
751 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
754 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
755 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
756 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
758 if (exists($info->{'seldepth'})) {
759 $text .= sprintf " (%u selective)", $info->{'seldepth'};
761 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
762 if ($info->{'tbhits'} == 1) {
763 $text .= ", one Syzygy hit";
765 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
771 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
773 my @refutation_lines = ();
774 if (defined($engine2)) {
775 for (my $mpv = 1; $mpv < 500; ++$mpv) {
776 my $info = $engine2->{'info'};
777 last if (!exists($info->{'pv' . $mpv}));
779 my $pv = $info->{'pv' . $mpv};
781 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
782 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
783 if (scalar @pretty_pv > 5) {
784 @pretty_pv = @pretty_pv[0..4];
785 push @pretty_pv, "...";
787 my $key = $pretty_move;
788 my $line = sprintf(" %-6s %6s %3s %s",
790 short_score($info, $pos_calculating_second_engine, $mpv, 0),
791 "d" . $info->{'depth' . $mpv},
792 join(', ', @pretty_pv));
793 push @refutation_lines, [ $key, $line ];
798 if ($#refutation_lines >= 0) {
799 $text .= "Shallow search of all legal moves:\n\n";
800 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
801 $text .= $line->[1] . "\n";
806 if ($last_text ne $text) {
807 print "
\e[H
\e[2J"; # clear the screen
812 # Now construct the tell text, if any
813 return if (!defined($telltarget));
817 if (exists($id->{'name'})) {
818 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
820 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
823 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
826 while (exists($info->{'pv' . $mpv})) {
827 $tell_text .= sprintf " PV%2u", $mpv;
828 my $score = short_score($info, $pos_calculating, $mpv);
829 $tell_text .= " ($score)" if (defined($score));
831 if (exists($info->{'depth' . $mpv})) {
832 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
836 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
842 my $score = long_score($info, $pos_calculating, '');
843 $tell_text .= " $score\n" if defined($score);
844 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
845 if (exists($info->{'depth'})) {
846 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
851 # see if a new tell is called for -- it is if the delay has expired _and_
852 # this is not simply a repetition of the last one
853 if ($last_told_text ne $tell_text) {
855 for my $iv (@tell_intervals) {
856 last if ($now - $last_move < $iv);
857 next if ($last_tell - $last_move >= $iv);
859 for my $line (split /\n/, $tell_text) {
860 $t->print("tell $telltarget [$target] $line");
863 $last_told_text = $text;
872 my $info = $engine->{'info'};
875 $json->{'position'} = $pos_calculating;
876 $json->{'id'} = $engine->{'id'};
877 $json->{'score'} = long_score($info, $pos_calculating, '');
879 $json->{'nodes'} = $info->{'nodes'};
880 $json->{'nps'} = $info->{'nps'};
881 $json->{'depth'} = $info->{'depth'};
882 $json->{'tbhits'} = $info->{'tbhits'};
883 $json->{'seldepth'} = $info->{'seldepth'};
885 # single-PV only for now
886 $json->{'pv_uci'} = $info->{'pv'};
887 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
889 my %refutation_lines = ();
890 my @refutation_lines = ();
891 if (defined($engine2)) {
892 for (my $mpv = 1; $mpv < 500; ++$mpv) {
893 my $info = $engine2->{'info'};
894 my $pretty_move = "";
896 last if (!exists($info->{'pv' . $mpv}));
899 my $pv = $info->{'pv' . $mpv};
900 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
901 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
902 $refutation_lines{$pv->[0]} = {
903 sort_key => $pretty_move,
904 depth => $info->{'depth' . $mpv},
905 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
906 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
907 pretty_move => $pretty_move,
908 pv_pretty => \@pretty_pv,
910 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
914 $json->{'refutation_lines'} = \%refutation_lines;
916 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
918 print $fh JSON::XS::encode_json($json);
920 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
925 my ($wkr, $wkc, $bkr, $bkc);
929 my $piece = substr($board->[$row], $col, 1);
931 ($wkr, $wkc) = ($row, $col);
932 } elsif ($piece eq 'k') {
933 ($bkr, $bkc) = ($row, $col);
938 return ($wkr, $wkc, $bkr, $bkc);
943 my $check = in_check($board);
944 return 0 if ($check eq 'none');
946 # try all possible moves for the side in check
949 my $piece = substr($board->[$row], $col, 1);
950 next if ($piece eq '-');
952 if ($check eq 'white') {
953 next if ($piece eq lc($piece));
955 next if ($piece eq uc($piece));
958 for my $dest_row (0..7) {
959 for my $dest_col (0..7) {
960 next if ($row == $dest_row && $col == $dest_col);
961 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
964 substr($nb[$row], $col, 1, '-');
965 substr($nb[$dest_row], $dest_col, 1, $piece);
967 my $new_check = in_check(\@nb);
968 return 0 if ($new_check ne $check && $new_check ne 'both');
974 # nothing to do; mate
980 my ($black_check, $white_check) = (0, 0);
982 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
984 # check all pieces for the possibility of threatening the two kings
987 my $piece = substr($board->[$row], $col, 1);
988 next if ($piece eq '-');
990 if (uc($piece) eq $piece) {
992 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
995 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
1000 if ($black_check && $white_check) {
1002 } elsif ($black_check) {
1004 } elsif ($white_check) {
1012 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
1014 # can't eat your own piece
1015 my $dest_piece = substr($board->[$to_row], $to_col, 1);
1016 if ($dest_piece ne '-') {
1017 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1020 if (lc($piece) eq 'k') {
1021 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1023 if (lc($piece) eq 'r') {
1024 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1026 # check that there's a clear passage
1027 if ($from_row == $to_row) {
1028 if ($from_col > $to_col) {
1029 ($to_col, $from_col) = ($from_col, $to_col);
1032 for my $c (($from_col+1)..($to_col-1)) {
1033 my $middle_piece = substr($board->[$to_row], $c, 1);
1034 return 0 if ($middle_piece ne '-');
1039 if ($from_row > $to_row) {
1040 ($to_row, $from_row) = ($from_row, $to_row);
1043 for my $r (($from_row+1)..($to_row-1)) {
1044 my $middle_piece = substr($board->[$r], $to_col, 1);
1045 return 0 if ($middle_piece ne '-');
1051 if (lc($piece) eq 'b') {
1052 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1054 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1055 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1057 my $r = $from_row + $dr;
1058 my $c = $from_col + $dc;
1060 while ($r != $to_row) {
1061 my $middle_piece = substr($board->[$r], $c, 1);
1062 return 0 if ($middle_piece ne '-');
1070 if (lc($piece) eq 'n') {
1071 my $diff_r = abs($from_row - $to_row);
1072 my $diff_c = abs($from_col - $to_col);
1073 return 1 if ($diff_r == 2 && $diff_c == 1);
1074 return 1 if ($diff_r == 1 && $diff_c == 2);
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));
1081 if ($piece eq 'Q') {
1082 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1083 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
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 == 1 && $to_row == 3) {
1093 my $middle_piece = substr($board->[2], $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 '-');
1101 if ($piece eq 'P') {
1103 if ($to_col == $from_col && $to_row == $from_row - 1) {
1104 return ($dest_piece eq '-');
1106 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1107 my $middle_piece = substr($board->[5], $to_col, 1);
1108 return ($dest_piece eq '-' && $middle_piece eq '-');
1110 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1111 return ($dest_piece ne '-');
1121 my ($engine, $msg) = @_;
1122 print { $engine->{'write'} } "$msg\n";
1123 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1127 my ($info, $pos, $mpv, $invert) = @_;
1130 if ($pos->{'toplay'} eq 'B') {
1134 if (defined($info->{'score_mate' . $mpv})) {
1136 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1138 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1141 if (exists($info->{'score_cp' . $mpv})) {
1142 my $score = $info->{'score_cp' . $mpv} * 0.01;
1149 return sprintf "%+5.2f", $score;
1156 sub score_sort_key {
1157 my ($info, $pos, $mpv, $invert) = @_;
1159 if (defined($info->{'score_mate' . $mpv})) {
1161 return 99999 - $info->{'score_mate' . $mpv};
1163 return -(99999 - $info->{'score_mate' . $mpv});
1166 if (exists($info->{'score_cp' . $mpv})) {
1167 my $score = $info->{'score_cp' . $mpv};
1179 my ($info, $pos, $mpv) = @_;
1181 if (defined($info->{'score_mate' . $mpv})) {
1182 my $mate = $info->{'score_mate' . $mpv};
1183 if ($pos->{'toplay'} eq 'B') {
1187 return sprintf "White mates in %u", $mate;
1189 return sprintf "Black mates in %u", -$mate;
1192 if (exists($info->{'score_cp' . $mpv})) {
1193 my $score = $info->{'score_cp' . $mpv} * 0.01;
1195 return "Score: 0.00";
1197 if ($pos->{'toplay'} eq 'B') {
1200 return sprintf "Score: %+5.2f", $score;
1207 my %book_cache = ();
1209 my ($fen, $board, $toplay) = @_;
1211 if (exists($book_cache{$fen})) {
1212 return $book_cache{$fen};
1215 my $ret = `./booklook $fen`;
1216 return "" if ($ret =~ /Not found/ || $ret eq '');
1220 for my $m (split /\n/, $ret) {
1221 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1225 $pmove = '(current)';
1227 ($pmove) = prettyprint_pv($board, $move);
1228 $pmove .= $annotation;
1232 if ($toplay eq 'W') {
1233 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1235 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1237 my $n = $win + $draw + $lose;
1243 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1246 push @moves, [ $pmove, $n, $percent, $rating ];
1249 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1251 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1252 for my $m (@moves) {
1253 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1260 my ($cmdline, $tag) = @_;
1262 return undef if (!defined($cmdline));
1264 my ($uciread, $uciwrite);
1265 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1277 uciprint($engine, "uci");
1279 # gobble the options
1280 while (<$uciread>) {
1282 handle_uci($engine, $_);
1292 # Read until we've got a full line -- if the engine sends part of
1293 # a line and then stops we're pretty much hosed, but that should
1296 while ($engine->{'readbuf'} !~ /\n/) {
1298 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1300 if (!defined($ret)) {
1301 next if ($!{EINTR});
1302 die "error in reading from the UCI engine: $!";
1303 } elsif ($ret == 0) {
1304 die "EOF from UCI engine";
1307 $engine->{'readbuf'} .= $tmp;
1312 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1314 $line =~ tr/\r\n//d;
1320 sub col_letter_to_num {
1321 return ord(shift) - ord('a');
1324 sub row_letter_to_num {
1325 return 7 - (ord(shift) - ord('1'));
1328 sub move_to_uci_notation {
1329 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1331 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);