4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 # analysis, or for live analysis of relayed games. (Do not use for
6 # cheating! Cheating is bad for your karma, and your abuser flag.)
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
21 my $server = "freechess.org";
22 my $target = "GMCarlsen";
23 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
24 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
25 my $telltarget = undef; # undef to be silent
26 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960); # after each move
27 my $uci_assume_full_compliance = 0; # dangerous :-)
28 my $update_max_interval = 2.0;
29 my $second_engine_start_depth = 8;
39 $SIG{ALRM} = sub { output(); };
40 my $latest_update = undef;
44 open(FICSLOG, ">ficslog.txt")
45 or die "ficslog.txt: $!";
46 print FICSLOG "Log starting.\n";
50 open(UCILOG, ">ucilog.txt")
51 or die "ucilog.txt: $!";
52 print UCILOG "Log starting.\n";
57 # open the chess engine
58 my $engine = open_engine($engine_cmdline, 'E1');
59 my $engine2 = open_engine($engine2_cmdline, 'E2');
60 my ($last_move, $last_tell);
62 my $last_told_text = '';
63 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
65 uciprint($engine, "setoption name UCI_AnalyseMode value true");
66 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
67 uciprint($engine, "setoption name NalimovUsage value Rarely");
68 uciprint($engine, "setoption name Hash value 1024");
69 # uciprint($engine, "setoption name MultiPV value 2");
70 uciprint($engine, "ucinewgame");
72 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
73 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
74 uciprint($engine2, "setoption name NalimovUsage value Rarely");
75 uciprint($engine2, "setoption name Hash value 1024");
76 uciprint($engine2, "setoption name Threads value 8");
77 uciprint($engine2, "setoption name MultiPV value 500");
78 uciprint($engine2, "ucinewgame");
80 print "Chess engine ready.\n";
83 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
84 $t->input_log(\*FICSLOG);
86 $t->print("SesseBOT");
87 $t->waitfor('/Press return to enter the server/');
91 $t->cmd("set shout 0");
92 $t->cmd("set seek 0");
93 $t->cmd("set style 12");
94 $t->cmd("observe $target");
97 print "FICS ready.\n";
101 vec($rin, fileno($engine->{'read'}), 1) = 1;
102 vec($rin, fileno($engine2->{'read'}), 1) = 1;
103 vec($rin, fileno($t), 1) = 1;
105 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
109 my $line = $t->getline(Timeout => 0, errmode => 'return');
110 last if (!defined($line));
114 if ($line =~ /^<12> /) {
115 my $pos = style12_to_pos($line);
117 # if this is already in the queue, ignore it
118 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
120 # if we're already chewing on this and there's nothing else in the queue,
122 next if (!defined($pos_waiting) && defined($pos_calculating) &&
123 $pos->{'fen'} eq $pos_calculating->{'fen'});
125 # if we're already thinking on something, stop and wait for the engine
127 if (defined($pos_calculating)) {
128 if (!defined($pos_waiting)) {
129 uciprint($engine, "stop");
131 if ($uci_assume_full_compliance) {
134 uciprint($engine, "position fen " . $pos->{'fen'});
135 uciprint($engine, "go infinite");
136 $pos_calculating = $pos;
139 # it's wrong just to give the FEN (the move history is useful,
140 # and per the UCI spec, we should really have sent "ucinewgame"),
142 uciprint($engine, "position fen " . $pos->{'fen'});
143 uciprint($engine, "go infinite");
144 $pos_calculating = $pos;
147 if (defined($pos_calculating_second_engine)) {
148 uciprint($engine2, "stop");
150 uciprint($engine2, "position fen " . $pos->{'fen'});
151 uciprint($engine2, "go infinite");
152 $pos_calculating_second_engine = $pos;
155 $engine->{'info'} = {};
156 $engine2->{'info'} = {};
160 # Output a command every move to note that we're
161 # still paying attention -- this is a good tradeoff,
162 # since if no move has happened in the last half
163 # hour, the analysis/relay has most likely stopped
164 # and we should stop hogging server resources.
168 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
169 my ($who, $msg) = ($1, $2);
171 next if (grep { $_ eq $who } (@masters) == 0);
173 if ($msg =~ /^fics (.*?)$/) {
174 $t->cmd("tell $who Executing '$1' on FICS.");
176 } elsif ($msg =~ /^uci (.*?)$/) {
177 $t->cmd("tell $who Sending '$1' to the engine.");
178 print { $engine->{'write'} } "$1\n";
180 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
183 #print "FICS: [$line]\n";
187 # any fun on the UCI channel?
188 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
189 my @lines = read_lines($engine);
190 for my $line (@lines) {
191 next if $line =~ /(upper|lower)bound/;
192 handle_uci($engine, $line, 1);
198 if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
199 my @lines = read_lines($engine2);
200 for my $line (@lines) {
201 next if $line =~ /(upper|lower)bound/;
202 handle_uci($engine2, $line, 0);
213 my ($engine, $line, $primary) = @_;
217 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
218 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
219 if ($line =~ /^info/) {
220 my (@infos) = split / /, $line;
223 parse_infos($engine, @infos);
225 if ($line =~ /^id/) {
226 my (@ids) = split / /, $line;
229 parse_ids($engine, @ids);
231 if ($line =~ /^bestmove/) {
233 return if (!$uci_assume_full_compliance);
234 if (defined($pos_waiting)) {
235 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
236 uciprint($engine, "go infinite");
238 $pos_calculating = $pos_waiting;
239 $pos_waiting = undef;
242 $engine2->{'info'} = {};
243 my $pos = $pos_waiting // $pos_calculating;
244 uciprint($engine2, "position fen " . $pos->{'fen'});
245 uciprint($engine2, "go infinite");
246 $pos_calculating_second_engine = $pos;
252 my ($engine, @x) = @_;
255 my $info = $engine->{'info'};
257 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
258 for my $i (0..$#x - 1) {
259 if ($x[$i] =~ 'multipv') {
265 while (scalar @x > 0) {
266 if ($x[0] =~ 'multipv') {
272 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
274 my $value = shift @x;
275 $info->{$key} = $value;
278 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
280 my $value = shift @x;
281 $info->{$key . $mpv} = $value;
284 if ($x[0] eq 'score') {
287 delete $info->{'score_cp' . $mpv};
288 delete $info->{'score_mate' . $mpv};
290 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
293 $info->{'score_cp' . $mpv} = shift @x;
294 } elsif ($x[0] eq 'mate') {
296 $info->{'score_mate' . $mpv} = shift @x;
304 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
307 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
311 #print "unknown info '$x[0]', trying to recover...\n";
313 die "Unknown info '" . join(',', @x) . "'";
319 my ($engine, @x) = @_;
321 while (scalar @x > 0) {
322 if ($x[0] =~ /^(name|author)$/) {
324 my $value = join(' ', @x);
325 $engine->{'id'}{$key} = $value;
337 my (@x) = split / /, $str;
339 $pos{'board'} = [ @x[1..8] ];
340 $pos{'toplay'} = $x[9];
341 $pos{'ep_file_num'} = $x[10];
342 $pos{'white_castle_k'} = $x[11];
343 $pos{'white_castle_q'} = $x[12];
344 $pos{'black_castle_k'} = $x[13];
345 $pos{'black_castle_q'} = $x[14];
346 $pos{'time_to_100move_rule'} = $x[15];
347 $pos{'move_num'} = $x[26];
348 $pos{'last_move'} = $x[29];
349 $pos{'fen'} = make_fen(\%pos);
358 my (@board) = @{$pos->{'board'}};
359 for my $rank (0..7) {
360 $board[$rank] =~ s/(-+)/length($1)/ge;
362 my $fen = join('/', @board);
364 # white/black to move
366 $fen .= lc($pos->{'toplay'});
370 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
371 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
372 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
373 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
374 $castling = "-" if ($castling eq "");
375 # $castling = "-"; # chess960
381 if ($pos->{'ep_file_num'} != -1) {
382 my $col = $pos->{'ep_file_num'};
383 my $nep = (qw(a b c d e f g h))[$col];
385 if ($pos->{'toplay'} eq 'B') {
392 # Showing the en passant square when actually no capture can be made
393 # seems to confuse at least Rybka. Thus, check if there's actually
394 # a pawn of the opposite side that can do the en passant move, and if
395 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
396 # "right" thing as per the standard, though.
398 if ($pos->{'toplay'} eq 'B') {
399 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
400 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
402 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
403 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
411 $fen .= $pos->{'time_to_100move_rule'};
415 $fen .= $pos->{'move_num'};
421 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
422 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
423 my $piece = substr($board->[$from_row], $from_col, 1);
427 die "Invalid move $move";
430 # white short castling
431 if ($move eq 'e1g1' && $piece eq 'K') {
433 substr($nb[7], 4, 1, '-');
434 substr($nb[7], 6, 1, $piece);
437 substr($nb[7], 7, 1, '-');
438 substr($nb[7], 5, 1, 'R');
443 # white long castling
444 if ($move eq 'e1c1' && $piece eq 'K') {
446 substr($nb[7], 4, 1, '-');
447 substr($nb[7], 2, 1, $piece);
450 substr($nb[7], 0, 1, '-');
451 substr($nb[7], 3, 1, 'R');
456 # black short castling
457 if ($move eq 'e8g8' && $piece eq 'k') {
459 substr($nb[0], 4, 1, '-');
460 substr($nb[0], 6, 1, $piece);
463 substr($nb[0], 7, 1, '-');
464 substr($nb[0], 5, 1, 'r');
469 # black long castling
470 if ($move eq 'e8c8' && $piece eq 'k') {
472 substr($nb[0], 4, 1, '-');
473 substr($nb[0], 2, 1, $piece);
476 substr($nb[0], 0, 1, '-');
477 substr($nb[0], 3, 1, 'r');
482 # check if the from-piece is a pawn
483 if (lc($piece) eq 'p') {
485 if ($from_col != $to_col) {
487 if (substr($board->[$to_row], $to_col, 1) eq '-') {
489 substr($nb[$to_row + 1], $to_col, 1, '-');
491 substr($nb[$to_row - 1], $to_col, 1, '-');
506 substr($nb[$from_row], $from_col, 1, '-');
507 substr($nb[$to_row], $to_col, 1, $piece);
513 my ($board, @pvs) = @_;
515 if (scalar @pvs == 0 || !defined($pvs[0])) {
520 my $from_col = col_letter_to_num(substr($pv, 0, 1));
521 my $from_row = row_letter_to_num(substr($pv, 1, 1));
522 my $to_col = col_letter_to_num(substr($pv, 2, 1));
523 my $to_row = row_letter_to_num(substr($pv, 3, 1));
524 my $promo = substr($pv, 4, 1);
526 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
527 my $piece = substr($board->[$from_row], $from_col, 1);
530 die "Invalid move $pv";
533 # white short castling
534 if ($pv eq 'e1g1' && $piece eq 'K') {
535 return ('0-0', prettyprint_pv($nb, @pvs));
538 # white long castling
539 if ($pv eq 'e1c1' && $piece eq 'K') {
540 return ('0-0-0', prettyprint_pv($nb, @pvs));
543 # black short castling
544 if ($pv eq 'e8g8' && $piece eq 'k') {
545 return ('0-0', prettyprint_pv($nb, @pvs));
548 # black long castling
549 if ($pv eq 'e8c8' && $piece eq 'k') {
550 return ('0-0-0', prettyprint_pv($nb, @pvs));
555 # check if the from-piece is a pawn
556 if (lc($piece) eq 'p') {
558 if ($from_col != $to_col) {
559 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
561 $pretty = substr($pv, 2, 2);
563 if (length($pv) == 5) {
566 $pretty .= uc(substr($pv, 4, 1));
569 $piece = substr($pv, 4, 1);
571 $piece = uc(substr($pv, 4, 1));
576 $pretty = uc($piece);
578 # see how many of these pieces could go here, in all
582 next unless (substr($board->[$row], $col, 1) eq $piece);
583 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
587 # see how many of these pieces from the given row could go here
590 next unless (substr($board->[$from_row], $col, 1) eq $piece);
591 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
594 # and same for columns
597 next unless (substr($board->[$row], $from_col, 1) eq $piece);
598 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
601 # see if we need to disambiguate
602 if ($num_total > 1) {
604 $pretty .= substr($pv, 0, 1);
605 } elsif ($num_row == 1) {
606 $pretty .= substr($pv, 1, 1);
608 $pretty .= substr($pv, 0, 2);
613 if (substr($board->[$to_row], $to_col, 1) ne '-') {
617 $pretty .= substr($pv, 2, 2);
622 } elsif (in_check($nb) ne 'none') {
625 return ($pretty, prettyprint_pv($nb, @pvs));
631 return if (!defined($pos_calculating));
633 # Don't update too often.
634 my $age = Time::HiRes::tv_interval($latest_update);
635 if ($age < $update_max_interval) {
636 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
640 my $info = $engine->{'info'};
643 # Some programs _always_ report MultiPV, even with only one PV.
644 # In this case, we simply use that data as if MultiPV was never
647 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
648 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
649 if (exists($info->{$key . '1'})) {
650 $info->{$key} = $info->{$key . '1'};
656 # Check the PVs first. if they're invalid, just wait, as our data
657 # is most likely out of sync. This isn't a very good solution, as
658 # it can frequently miss stuff, but it's good enough for most users.
662 if (exists($info->{'pv'})) {
663 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
667 while (exists($info->{'pv' . $mpv})) {
668 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
673 $engine->{'info'} = {};
679 $latest_update = [Time::HiRes::gettimeofday];
683 my $info = $engine->{'info'};
684 my $id = $engine->{'id'};
686 my $text = 'Analysis';
687 if ($pos_calculating->{'last_move'} ne 'none') {
688 if ($pos_calculating->{'toplay'} eq 'W') {
689 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
691 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
693 if (exists($id->{'name'})) {
698 if (exists($id->{'name'})) {
699 $text .= " by $id->{'name'}:\n\n";
704 return unless (exists($pos_calculating->{'board'}));
706 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
709 while (exists($info->{'pv' . $mpv})) {
710 $text .= sprintf " PV%2u", $mpv;
711 my $score = short_score($info, $pos_calculating, $mpv);
712 $text .= " ($score)" if (defined($score));
715 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
716 if ($info->{'tbhits' . $mpv} == 1) {
717 $tbhits = ", 1 tbhit";
719 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
723 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
724 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
725 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
729 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
735 my $score = long_score($info, $pos_calculating, '');
736 $text .= " $score\n" if defined($score);
737 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
740 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
741 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
742 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
744 if (exists($info->{'seldepth'})) {
745 $text .= sprintf " (%u selective)", $info->{'seldepth'};
747 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
748 if ($info->{'tbhits'} == 1) {
749 $text .= ", one Nalimov hit";
751 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
757 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
759 my @refutation_lines = ();
760 for (my $mpv = 1; $mpv < 500; ++$mpv) {
761 my $info = $engine2->{'info'};
762 last if (!exists($info->{'pv' . $mpv}));
764 my $pv = $info->{'pv' . $mpv};
766 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
767 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
768 if (scalar @pretty_pv > 5) {
769 @pretty_pv = @pretty_pv[0..4];
770 push @pretty_pv, "...";
772 my $key = $pretty_move;
773 my $line = sprintf(" %-6s %6s %3s %s",
775 short_score($info, $pos_calculating_second_engine, $mpv, 1),
776 "d" . $info->{'depth' . $mpv},
777 join(', ', @pretty_pv));
778 push @refutation_lines, [ $key, $line ];
782 if ($#refutation_lines >= 0) {
783 $text .= "Shallow search of all legal moves:\n\n";
784 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
785 $text .= $line->[1] . "\n";
790 if ($last_text ne $text) {
791 print "
\e[H
\e[2J"; # clear the screen
796 # Now construct the tell text, if any
797 return if (!defined($telltarget));
801 if (exists($id->{'name'})) {
802 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
804 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
807 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
810 while (exists($info->{'pv' . $mpv})) {
811 $tell_text .= sprintf " PV%2u", $mpv;
812 my $score = short_score($info, $pos_calculating, $mpv);
813 $tell_text .= " ($score)" if (defined($score));
815 if (exists($info->{'depth' . $mpv})) {
816 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
820 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
826 my $score = long_score($info, $pos_calculating, '');
827 $tell_text .= " $score\n" if defined($score);
828 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
829 if (exists($info->{'depth'})) {
830 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
835 # see if a new tell is called for -- it is if the delay has expired _and_
836 # this is not simply a repetition of the last one
837 if ($last_told_text ne $tell_text) {
839 for my $iv (@tell_intervals) {
840 last if ($now - $last_move < $iv);
841 next if ($last_tell - $last_move >= $iv);
843 for my $line (split /\n/, $tell_text) {
844 $t->print("tell $telltarget [$target] $line");
847 $last_told_text = $text;
856 my $info = $engine->{'info'};
859 $json->{'position'} = $pos_calculating;
860 $json->{'id'} = $engine->{'id'};
861 $json->{'score'} = long_score($info, $pos_calculating, '');
863 $json->{'nodes'} = $info->{'nodes'};
864 $json->{'nps'} = $info->{'nps'};
865 $json->{'depth'} = $info->{'depth'};
866 $json->{'tbhits'} = $info->{'tbhits'};
867 $json->{'seldepth'} = $info->{'seldepth'};
869 # single-PV only for now
870 $json->{'pv_uci'} = $info->{'pv'};
871 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
873 my %refutation_lines = ();
874 my @refutation_lines = ();
875 for (my $mpv = 1; $mpv < 500; ++$mpv) {
876 my $info = $engine2->{'info'};
877 my $pretty_move = "";
879 last if (!exists($info->{'pv' . $mpv}));
882 my $pv = $info->{'pv' . $mpv};
883 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
884 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
885 $refutation_lines{$pv->[0]} = {
886 sort_key => $pretty_move,
887 depth => $info->{'depth' . $mpv},
888 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
889 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
890 pretty_move => $pretty_move,
891 pv_pretty => \@pretty_pv,
893 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
896 $json->{'refutation_lines'} = \%refutation_lines;
898 open my $fh, ">analysis.json.tmp"
900 print $fh JSON::XS::encode_json($json);
902 rename("analysis.json.tmp", "analysis.json");
907 my ($wkr, $wkc, $bkr, $bkc);
911 my $piece = substr($board->[$row], $col, 1);
913 ($wkr, $wkc) = ($row, $col);
914 } elsif ($piece eq 'k') {
915 ($bkr, $bkc) = ($row, $col);
920 return ($wkr, $wkc, $bkr, $bkc);
925 my $check = in_check($board);
926 return 0 if ($check eq 'none');
928 # try all possible moves for the side in check
931 my $piece = substr($board->[$row], $col, 1);
932 next if ($piece eq '-');
934 if ($check eq 'white') {
935 next if ($piece eq lc($piece));
937 next if ($piece eq uc($piece));
940 for my $dest_row (0..7) {
941 for my $dest_col (0..7) {
942 next if ($row == $dest_row && $col == $dest_col);
943 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
946 substr($nb[$row], $col, 1, '-');
947 substr($nb[$dest_row], $dest_col, 1, $piece);
949 my $new_check = in_check(\@nb);
950 return 0 if ($new_check ne $check && $new_check ne 'both');
956 # nothing to do; mate
962 my ($black_check, $white_check) = (0, 0);
964 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
966 # check all pieces for the possibility of threatening the two kings
969 my $piece = substr($board->[$row], $col, 1);
970 next if ($piece eq '-');
972 if (uc($piece) eq $piece) {
974 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
977 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
982 if ($black_check && $white_check) {
984 } elsif ($black_check) {
986 } elsif ($white_check) {
994 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
996 # can't eat your own piece
997 my $dest_piece = substr($board->[$to_row], $to_col, 1);
998 if ($dest_piece ne '-') {
999 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1002 if (lc($piece) eq 'k') {
1003 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1005 if (lc($piece) eq 'r') {
1006 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1008 # check that there's a clear passage
1009 if ($from_row == $to_row) {
1010 if ($from_col > $to_col) {
1011 ($to_col, $from_col) = ($from_col, $to_col);
1014 for my $c (($from_col+1)..($to_col-1)) {
1015 my $middle_piece = substr($board->[$to_row], $c, 1);
1016 return 0 if ($middle_piece ne '-');
1021 if ($from_row > $to_row) {
1022 ($to_row, $from_row) = ($from_row, $to_row);
1025 for my $r (($from_row+1)..($to_row-1)) {
1026 my $middle_piece = substr($board->[$r], $to_col, 1);
1027 return 0 if ($middle_piece ne '-');
1033 if (lc($piece) eq 'b') {
1034 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1036 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1037 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1039 my $r = $from_row + $dr;
1040 my $c = $from_col + $dc;
1042 while ($r != $to_row) {
1043 my $middle_piece = substr($board->[$r], $c, 1);
1044 return 0 if ($middle_piece ne '-');
1052 if (lc($piece) eq 'n') {
1053 my $diff_r = abs($from_row - $to_row);
1054 my $diff_c = abs($from_col - $to_col);
1055 return 1 if ($diff_r == 2 && $diff_c == 1);
1056 return 1 if ($diff_r == 1 && $diff_c == 2);
1059 if ($piece eq 'q') {
1060 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1061 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
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));
1069 if ($piece eq 'p') {
1071 if ($to_col == $from_col && $to_row == $from_row + 1) {
1072 return ($dest_piece eq '-');
1074 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1075 my $middle_piece = substr($board->[2], $to_col, 1);
1076 return ($dest_piece eq '-' && $middle_piece eq '-');
1078 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1079 return ($dest_piece ne '-');
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 == 6 && $to_row == 4) {
1089 my $middle_piece = substr($board->[5], $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 '-');
1103 my ($engine, $msg) = @_;
1104 print { $engine->{'write'} } "$msg\n";
1105 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1109 my ($info, $pos, $mpv, $invert) = @_;
1112 if ($pos->{'toplay'} eq 'B') {
1116 if (defined($info->{'score_mate' . $mpv})) {
1118 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1120 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1123 if (exists($info->{'score_cp' . $mpv})) {
1124 my $score = $info->{'score_cp' . $mpv} * 0.01;
1131 return sprintf "%+5.2f", $score;
1138 sub score_sort_key {
1139 my ($info, $pos, $mpv, $invert) = @_;
1141 if (defined($info->{'score_mate' . $mpv})) {
1143 return -(99999 - $info->{'score_mate' . $mpv});
1145 return 99999 - $info->{'score_mate' . $mpv};
1148 if (exists($info->{'score_cp' . $mpv})) {
1149 my $score = $info->{'score_cp' . $mpv};
1161 my ($info, $pos, $mpv) = @_;
1163 if (defined($info->{'score_mate' . $mpv})) {
1164 my $mate = $info->{'score_mate' . $mpv};
1165 if ($pos->{'toplay'} eq 'B') {
1169 return sprintf "White mates in %u", $mate;
1171 return sprintf "Black mates in %u", -$mate;
1174 if (exists($info->{'score_cp' . $mpv})) {
1175 my $score = $info->{'score_cp' . $mpv} * 0.01;
1176 if ($pos->{'toplay'} eq 'B') {
1179 return sprintf "Score: %+5.2f", $score;
1186 my %book_cache = ();
1188 my ($fen, $board, $toplay) = @_;
1190 if (exists($book_cache{$fen})) {
1191 return $book_cache{$fen};
1194 my $ret = `./booklook $fen`;
1195 return "" if ($ret =~ /Not found/ || $ret eq '');
1199 for my $m (split /\n/, $ret) {
1200 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1204 $pmove = '(current)';
1206 ($pmove) = prettyprint_pv($board, $move);
1207 $pmove .= $annotation;
1211 if ($toplay eq 'W') {
1212 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1214 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1216 my $n = $win + $draw + $lose;
1222 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1225 push @moves, [ $pmove, $n, $percent, $rating ];
1228 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1230 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1231 for my $m (@moves) {
1232 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1239 my ($cmdline, $tag) = @_;
1240 my ($uciread, $uciwrite);
1241 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1253 uciprint($engine, "uci");
1255 # gobble the options
1256 while (<$uciread>) {
1258 handle_uci($engine, $_);
1268 # Read until we've got a full line -- if the engine sends part of
1269 # a line and then stops we're pretty much hosed, but that should
1272 while ($engine->{'readbuf'} !~ /\n/) {
1274 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1276 if (!defined($ret)) {
1277 next if ($!{EINTR});
1278 die "error in reading from the UCI engine: $!";
1279 } elsif ($ret == 0) {
1280 die "EOF from UCI engine";
1283 $engine->{'readbuf'} .= $tmp;
1288 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1290 $line =~ tr/\r\n//d;
1296 sub col_letter_to_num {
1297 return ord(shift) - ord('a');
1300 sub row_letter_to_num {
1301 return 7 - (ord(shift) - ord('1'));
1304 sub move_to_uci_notation {
1305 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1307 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);