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, $move_calculating_second_engine);
64 my %refutation_moves = ();
66 uciprint($engine, "setoption name UCI_AnalyseMode value true");
67 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
68 uciprint($engine, "setoption name NalimovUsage value Rarely");
69 uciprint($engine, "setoption name Hash value 1024");
70 # uciprint($engine, "setoption name MultiPV value 2");
71 uciprint($engine, "ucinewgame");
73 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
74 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
75 uciprint($engine2, "setoption name NalimovUsage value Rarely");
76 uciprint($engine2, "setoption name Hash value 1024");
77 uciprint($engine2, "setoption name Threads value 8");
78 # uciprint($engine2, "setoption name MultiPV value 2");
79 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 vec($rin, fileno($engine2->{'read'}), 1) = 1;
104 vec($rin, fileno($t), 1) = 1;
106 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
110 my $line = $t->getline(Timeout => 0, errmode => 'return');
111 last if (!defined($line));
115 if ($line =~ /^<12> /) {
116 my $pos = style12_to_pos($line);
118 # if this is already in the queue, ignore it
119 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
121 # if we're already chewing on this and there's nothing else in the queue,
123 next if (!defined($pos_waiting) && defined($pos_calculating) &&
124 $pos->{'fen'} eq $pos_calculating->{'fen'});
126 # if we're already thinking on something, stop and wait for the engine
128 if (defined($pos_calculating)) {
129 if (!defined($pos_waiting)) {
130 uciprint($engine, "stop");
132 if ($uci_assume_full_compliance) {
135 uciprint($engine, "position fen " . $pos->{'fen'});
136 uciprint($engine, "go infinite");
137 $pos_calculating = $pos;
140 # it's wrong just to give the FEN (the move history is useful,
141 # and per the UCI spec, we should really have sent "ucinewgame"),
143 uciprint($engine, "position fen " . $pos->{'fen'});
144 uciprint($engine, "go infinite");
145 $pos_calculating = $pos;
148 %refutation_moves = calculate_refutation_moves($pos);
149 if (defined($move_calculating_second_engine)) {
150 uciprint($engine2, "stop");
151 $move_calculating_second_engine = undef;
153 give_new_move_to_second_engine($pos);
156 $engine->{'info'} = {};
157 $engine2->{'info'} = {};
161 # Output a command every move to note that we're
162 # still paying attention -- this is a good tradeoff,
163 # since if no move has happened in the last half
164 # hour, the analysis/relay has most likely stopped
165 # and we should stop hogging server resources.
169 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
170 my ($who, $msg) = ($1, $2);
172 next if (grep { $_ eq $who } (@masters) == 0);
174 if ($msg =~ /^fics (.*?)$/) {
175 $t->cmd("tell $who Executing '$1' on FICS.");
177 } elsif ($msg =~ /^uci (.*?)$/) {
178 $t->cmd("tell $who Sending '$1' to the engine.");
179 print { $engine->{'write'} } "$1\n";
181 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
184 #print "FICS: [$line]\n";
188 # any fun on the UCI channel?
189 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
190 my @lines = read_lines($engine);
191 for my $line (@lines) {
192 next if $line =~ /(upper|lower)bound/;
193 handle_uci($engine, $line, 1);
199 if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
200 my @lines = read_lines($engine2);
201 for my $line (@lines) {
202 next if $line =~ /(upper|lower)bound/;
203 handle_uci($engine2, $line, 0);
214 my ($engine, $line, $primary) = @_;
218 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
219 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
220 if ($line =~ /^info/) {
221 my (@infos) = split / /, $line;
224 parse_infos($engine, @infos);
226 if ($line =~ /^id/) {
227 my (@ids) = split / /, $line;
230 parse_ids($engine, @ids);
232 if ($line =~ /^bestmove/) {
234 return if (!$uci_assume_full_compliance);
235 if (defined($pos_waiting)) {
236 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
237 uciprint($engine, "go infinite");
239 $pos_calculating = $pos_waiting;
240 $pos_waiting = undef;
243 if (defined($move_calculating_second_engine)) {
244 my $move = $refutation_moves{$move_calculating_second_engine};
245 $move->{'pv'} = $engine->{'info'}{'pv'} // $engine->{'info'}{'pv1'};
246 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
247 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
248 $move->{'toplay'} = $pos_calculating->{'toplay'};
250 give_new_move_to_second_engine($pos_waiting // $pos_calculating);
256 my ($engine, @x) = @_;
259 my $info = $engine->{'info'};
261 while (scalar @x > 0) {
262 if ($x[0] =~ 'multipv') {
267 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
269 my $value = shift @x;
270 $info->{$key} = $value;
273 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
275 my $value = shift @x;
276 $info->{$key . $mpv} = $value;
279 if ($x[0] eq 'score') {
282 delete $info->{'score_cp' . $mpv};
283 delete $info->{'score_mate' . $mpv};
285 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
288 $info->{'score_cp' . $mpv} = shift @x;
289 } elsif ($x[0] eq 'mate') {
291 $info->{'score_mate' . $mpv} = shift @x;
299 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
302 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
306 #print "unknown info '$x[0]', trying to recover...\n";
308 die "Unknown info '" . join(',', @x) . "'";
314 my ($engine, @x) = @_;
316 while (scalar @x > 0) {
317 if ($x[0] =~ /^(name|author)$/) {
319 my $value = join(' ', @x);
320 $engine->{'id'}{$key} = $value;
332 my (@x) = split / /, $str;
334 $pos{'board'} = [ @x[1..8] ];
335 $pos{'toplay'} = $x[9];
336 $pos{'ep_file_num'} = $x[10];
337 $pos{'white_castle_k'} = $x[11];
338 $pos{'white_castle_q'} = $x[12];
339 $pos{'black_castle_k'} = $x[13];
340 $pos{'black_castle_q'} = $x[14];
341 $pos{'time_to_100move_rule'} = $x[15];
342 $pos{'move_num'} = $x[26];
343 $pos{'last_move'} = $x[29];
344 $pos{'fen'} = make_fen(\%pos);
353 my (@board) = @{$pos->{'board'}};
354 for my $rank (0..7) {
355 $board[$rank] =~ s/(-+)/length($1)/ge;
357 my $fen = join('/', @board);
359 # white/black to move
361 $fen .= lc($pos->{'toplay'});
365 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
366 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
367 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
368 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
369 $castling = "-" if ($castling eq "");
370 # $castling = "-"; # chess960
376 if ($pos->{'ep_file_num'} != -1) {
377 my $col = $pos->{'ep_file_num'};
378 my $nep = (qw(a b c d e f g h))[$col];
380 if ($pos->{'toplay'} eq 'B') {
387 # Showing the en passant square when actually no capture can be made
388 # seems to confuse at least Rybka. Thus, check if there's actually
389 # a pawn of the opposite side that can do the en passant move, and if
390 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
391 # "right" thing as per the standard, though.
393 if ($pos->{'toplay'} eq 'B') {
394 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
395 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
397 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
398 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
406 $fen .= $pos->{'time_to_100move_rule'};
410 $fen .= $pos->{'move_num'};
416 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
417 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
418 my $piece = substr($board->[$from_row], $from_col, 1);
422 die "Invalid move $move";
425 # white short castling
426 if ($move eq 'e1g1' && $piece eq 'K') {
428 substr($nb[7], 4, 1, '-');
429 substr($nb[7], 6, 1, $piece);
432 substr($nb[7], 7, 1, '-');
433 substr($nb[7], 5, 1, 'R');
438 # white long castling
439 if ($move eq 'e1c1' && $piece eq 'K') {
441 substr($nb[7], 4, 1, '-');
442 substr($nb[7], 2, 1, $piece);
445 substr($nb[7], 0, 1, '-');
446 substr($nb[7], 3, 1, 'R');
451 # black short castling
452 if ($move eq 'e8g8' && $piece eq 'k') {
454 substr($nb[0], 4, 1, '-');
455 substr($nb[0], 6, 1, $piece);
458 substr($nb[0], 7, 1, '-');
459 substr($nb[0], 5, 1, 'r');
464 # black long castling
465 if ($move eq 'e8c8' && $piece eq 'k') {
467 substr($nb[0], 4, 1, '-');
468 substr($nb[0], 2, 1, $piece);
471 substr($nb[0], 0, 1, '-');
472 substr($nb[0], 3, 1, 'r');
477 # check if the from-piece is a pawn
478 if (lc($piece) eq 'p') {
480 if ($from_col != $to_col) {
482 if (substr($board->[$to_row], $to_col, 1) eq '-') {
484 substr($nb[$to_row + 1], $to_col, 1, '-');
486 substr($nb[$to_row - 1], $to_col, 1, '-');
501 substr($nb[$from_row], $from_col, 1, '-');
502 substr($nb[$to_row], $to_col, 1, $piece);
508 my ($board, @pvs) = @_;
510 if (scalar @pvs == 0 || !defined($pvs[0])) {
515 my $from_col = col_letter_to_num(substr($pv, 0, 1));
516 my $from_row = row_letter_to_num(substr($pv, 1, 1));
517 my $to_col = col_letter_to_num(substr($pv, 2, 1));
518 my $to_row = row_letter_to_num(substr($pv, 3, 1));
519 my $promo = substr($pv, 4, 1);
521 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
522 my $piece = substr($board->[$from_row], $from_col, 1);
525 die "Invalid move $pv";
528 # white short castling
529 if ($pv eq 'e1g1' && $piece eq 'K') {
530 return ('0-0', prettyprint_pv($nb, @pvs));
533 # white long castling
534 if ($pv eq 'e1c1' && $piece eq 'K') {
535 return ('0-0-0', prettyprint_pv($nb, @pvs));
538 # black short castling
539 if ($pv eq 'e8g8' && $piece eq 'k') {
540 return ('0-0', prettyprint_pv($nb, @pvs));
543 # black long castling
544 if ($pv eq 'e8c8' && $piece eq 'k') {
545 return ('0-0-0', prettyprint_pv($nb, @pvs));
550 # check if the from-piece is a pawn
551 if (lc($piece) eq 'p') {
553 if ($from_col != $to_col) {
554 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
556 $pretty = substr($pv, 2, 2);
558 if (length($pv) == 5) {
561 $pretty .= uc(substr($pv, 4, 1));
564 $piece = substr($pv, 4, 1);
566 $piece = uc(substr($pv, 4, 1));
571 $pretty = uc($piece);
573 # see how many of these pieces could go here, in all
577 next unless (substr($board->[$row], $col, 1) eq $piece);
578 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
582 # see how many of these pieces from the given row could go here
585 next unless (substr($board->[$from_row], $col, 1) eq $piece);
586 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
589 # and same for columns
592 next unless (substr($board->[$row], $from_col, 1) eq $piece);
593 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
596 # see if we need to disambiguate
597 if ($num_total > 1) {
599 $pretty .= substr($pv, 0, 1);
600 } elsif ($num_row == 1) {
601 $pretty .= substr($pv, 1, 1);
603 $pretty .= substr($pv, 0, 2);
608 if (substr($board->[$to_row], $to_col, 1) ne '-') {
612 $pretty .= substr($pv, 2, 2);
617 } elsif (in_check($nb) ne 'none') {
620 return ($pretty, prettyprint_pv($nb, @pvs));
626 return if (!defined($pos_calculating));
628 # Don't update too often.
629 my $age = Time::HiRes::tv_interval($latest_update);
630 if ($age < $update_max_interval) {
631 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
635 my $info = $engine->{'info'};
638 # Some programs _always_ report MultiPV, even with only one PV.
639 # In this case, we simply use that data as if MultiPV was never
642 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
643 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
644 if (exists($info->{$key . '1'})) {
645 $info->{$key} = $info->{$key . '1'};
651 # Check the PVs first. if they're invalid, just wait, as our data
652 # is most likely out of sync. This isn't a very good solution, as
653 # it can frequently miss stuff, but it's good enough for most users.
657 if (exists($info->{'pv'})) {
658 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
662 while (exists($info->{'pv' . $mpv})) {
663 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
668 $engine->{'info'} = {};
674 $latest_update = [Time::HiRes::gettimeofday];
678 my $info = $engine->{'info'};
679 my $id = $engine->{'id'};
681 my $text = 'Analysis';
682 if ($pos_calculating->{'last_move'} ne 'none') {
683 if ($pos_calculating->{'toplay'} eq 'W') {
684 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
686 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
688 if (exists($id->{'name'})) {
693 if (exists($id->{'name'})) {
694 $text .= " by $id->{'name'}:\n\n";
699 return unless (exists($pos_calculating->{'board'}));
701 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
704 while (exists($info->{'pv' . $mpv})) {
705 $text .= sprintf " PV%2u", $mpv;
706 my $score = short_score($info, $pos_calculating, $mpv);
707 $text .= " ($score)" if (defined($score));
710 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
711 if ($info->{'tbhits' . $mpv} == 1) {
712 $tbhits = ", 1 tbhit";
714 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
718 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
719 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
720 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
724 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
730 my $score = long_score($info, $pos_calculating, '');
731 $text .= " $score\n" if defined($score);
732 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
735 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
736 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
737 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
739 if (exists($info->{'seldepth'})) {
740 $text .= sprintf " (%u selective)", $info->{'seldepth'};
742 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
743 if ($info->{'tbhits'} == 1) {
744 $text .= ", one Nalimov hit";
746 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
752 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
754 my @refutation_lines = ();
755 for my $move (keys %refutation_moves) {
757 my $m = $refutation_moves{$move};
758 die if ($m->{'depth'} < $second_engine_start_depth);
759 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
760 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
761 if (scalar @pretty_pv > 5) {
762 @pretty_pv = @pretty_pv[0..4];
763 push @pretty_pv, "...";
765 #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
766 my $key = $pretty_move;
767 my $line = sprintf(" %-6s %6s %3s %s",
769 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
771 join(', ', @pretty_pv));
772 push @refutation_lines, [ $key, $line ];
776 if ($#refutation_lines >= 0) {
777 $text .= "Shallow search of all legal moves:\n\n";
778 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
779 $text .= $line->[1] . "\n";
784 if ($last_text ne $text) {
785 print "
\e[H
\e[2J"; # clear the screen
790 # Now construct the tell text, if any
791 return if (!defined($telltarget));
795 if (exists($id->{'name'})) {
796 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
798 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
801 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
804 while (exists($info->{'pv' . $mpv})) {
805 $tell_text .= sprintf " PV%2u", $mpv;
806 my $score = short_score($info, $pos_calculating, $mpv);
807 $tell_text .= " ($score)" if (defined($score));
809 if (exists($info->{'depth' . $mpv})) {
810 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
814 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
820 my $score = long_score($info, $pos_calculating, '');
821 $tell_text .= " $score\n" if defined($score);
822 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
823 if (exists($info->{'depth'})) {
824 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
829 # see if a new tell is called for -- it is if the delay has expired _and_
830 # this is not simply a repetition of the last one
831 if ($last_told_text ne $tell_text) {
833 for my $iv (@tell_intervals) {
834 last if ($now - $last_move < $iv);
835 next if ($last_tell - $last_move >= $iv);
837 for my $line (split /\n/, $tell_text) {
838 $t->print("tell $telltarget [$target] $line");
841 $last_told_text = $text;
850 my $info = $engine->{'info'};
853 $json->{'position'} = $pos_calculating;
854 $json->{'id'} = $engine->{'id'};
855 $json->{'score'} = long_score($info, $pos_calculating, '');
857 $json->{'nodes'} = $info->{'nodes'};
858 $json->{'nps'} = $info->{'nps'};
859 $json->{'depth'} = $info->{'depth'};
860 $json->{'tbhits'} = $info->{'tbhits'};
861 $json->{'seldepth'} = $info->{'seldepth'};
863 # single-PV only for now
864 $json->{'pv_uci'} = $info->{'pv'};
865 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
867 my %refutation_lines = ();
868 for my $move (keys %refutation_moves) {
869 my $m = $refutation_moves{$move};
870 my $pretty_move = "";
873 $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
874 @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
876 $refutation_lines{$move} = {
877 sort_key => $pretty_move,
878 depth => $m->{'depth'},
879 score_sort_key => score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1),
880 pretty_score => short_score($refutation_moves{$move}, $pos_calculating, '', 1),
881 pretty_move => $pretty_move,
882 pv_pretty => \@pretty_pv,
885 $refutation_lines{$move}->{'pv_uci'} = [ $move, @{$m->{'pv'}} ];
888 $json->{'refutation_lines'} = \%refutation_lines;
890 open my $fh, ">analysis.json.tmp"
892 print $fh JSON::XS::encode_json($json);
894 rename("analysis.json.tmp", "analysis.json");
899 my ($wkr, $wkc, $bkr, $bkc);
903 my $piece = substr($board->[$row], $col, 1);
905 ($wkr, $wkc) = ($row, $col);
906 } elsif ($piece eq 'k') {
907 ($bkr, $bkc) = ($row, $col);
912 return ($wkr, $wkc, $bkr, $bkc);
917 my $check = in_check($board);
918 return 0 if ($check eq 'none');
920 # try all possible moves for the side in check
923 my $piece = substr($board->[$row], $col, 1);
924 next if ($piece eq '-');
926 if ($check eq 'white') {
927 next if ($piece eq lc($piece));
929 next if ($piece eq uc($piece));
932 for my $dest_row (0..7) {
933 for my $dest_col (0..7) {
934 next if ($row == $dest_row && $col == $dest_col);
935 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
938 substr($nb[$row], $col, 1, '-');
939 substr($nb[$dest_row], $dest_col, 1, $piece);
941 my $new_check = in_check(\@nb);
942 return 0 if ($new_check ne $check && $new_check ne 'both');
948 # nothing to do; mate
954 my ($black_check, $white_check) = (0, 0);
956 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
958 # check all pieces for the possibility of threatening the two kings
961 my $piece = substr($board->[$row], $col, 1);
962 next if ($piece eq '-');
964 if (uc($piece) eq $piece) {
966 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
969 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
974 if ($black_check && $white_check) {
976 } elsif ($black_check) {
978 } elsif ($white_check) {
986 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
988 # can't eat your own piece
989 my $dest_piece = substr($board->[$to_row], $to_col, 1);
990 if ($dest_piece ne '-') {
991 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
994 if (lc($piece) eq 'k') {
995 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
997 if (lc($piece) eq 'r') {
998 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1000 # check that there's a clear passage
1001 if ($from_row == $to_row) {
1002 if ($from_col > $to_col) {
1003 ($to_col, $from_col) = ($from_col, $to_col);
1006 for my $c (($from_col+1)..($to_col-1)) {
1007 my $middle_piece = substr($board->[$to_row], $c, 1);
1008 return 0 if ($middle_piece ne '-');
1013 if ($from_row > $to_row) {
1014 ($to_row, $from_row) = ($from_row, $to_row);
1017 for my $r (($from_row+1)..($to_row-1)) {
1018 my $middle_piece = substr($board->[$r], $to_col, 1);
1019 return 0 if ($middle_piece ne '-');
1025 if (lc($piece) eq 'b') {
1026 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1028 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1029 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1031 my $r = $from_row + $dr;
1032 my $c = $from_col + $dc;
1034 while ($r != $to_row) {
1035 my $middle_piece = substr($board->[$r], $c, 1);
1036 return 0 if ($middle_piece ne '-');
1044 if (lc($piece) eq 'n') {
1045 my $diff_r = abs($from_row - $to_row);
1046 my $diff_c = abs($from_col - $to_col);
1047 return 1 if ($diff_r == 2 && $diff_c == 1);
1048 return 1 if ($diff_r == 1 && $diff_c == 2);
1051 if ($piece eq 'q') {
1052 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1053 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1055 if ($piece eq 'Q') {
1056 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1057 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1061 if ($piece eq 'p') {
1063 if ($to_col == $from_col && $to_row == $from_row + 1) {
1064 return ($dest_piece eq '-');
1066 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1067 my $middle_piece = substr($board->[2], $to_col, 1);
1068 return ($dest_piece eq '-' && $middle_piece eq '-');
1070 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1071 return ($dest_piece ne '-');
1075 if ($piece eq 'P') {
1077 if ($to_col == $from_col && $to_row == $from_row - 1) {
1078 return ($dest_piece eq '-');
1080 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1081 my $middle_piece = substr($board->[5], $to_col, 1);
1082 return ($dest_piece eq '-' && $middle_piece eq '-');
1084 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1085 return ($dest_piece ne '-');
1095 my ($engine, $msg) = @_;
1096 print { $engine->{'write'} } "$msg\n";
1097 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1101 my ($info, $pos, $mpv, $invert) = @_;
1104 if ($pos->{'toplay'} eq 'B') {
1108 if (defined($info->{'score_mate' . $mpv})) {
1110 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1112 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1115 if (exists($info->{'score_cp' . $mpv})) {
1116 my $score = $info->{'score_cp' . $mpv} * 0.01;
1123 return sprintf "%+5.2f", $score;
1130 sub score_sort_key {
1131 my ($info, $pos, $mpv, $invert) = @_;
1134 if ($pos->{'toplay'} eq 'B') {
1138 if (defined($info->{'score_mate' . $mpv})) {
1140 return -(99999 - $info->{'score_mate' . $mpv});
1142 return 99999 - $info->{'score_mate' . $mpv};
1145 if (exists($info->{'score_cp' . $mpv})) {
1146 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 # Find all possible legal moves.
1297 sub calculate_refutation_moves {
1299 my $board = $pos->{'board'};
1300 my %refutation_moves = ();
1301 for my $col (0..7) {
1302 for my $row (0..7) {
1303 my $piece = substr($board->[$row], $col, 1);
1305 # Check that there's a piece of the right color on this square.
1306 next if ($piece eq '-');
1307 if ($pos->{'toplay'} eq 'W') {
1308 next if ($piece ne uc($piece));
1310 next if ($piece ne lc($piece));
1313 for my $to_col (0..7) {
1314 for my $to_row (0..7) {
1315 next if ($col == $to_col && $row == $to_row);
1316 next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1318 my $promo = ""; # FIXME
1319 my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1320 my $check = in_check($nb);
1321 next if ($check eq 'both');
1322 if ($pos->{'toplay'} eq 'W') {
1323 next if ($check eq 'white');
1325 next if ($check eq 'black');
1327 my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1328 $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1333 return %refutation_moves;
1336 sub give_new_move_to_second_engine {
1339 # Find the move that's been analyzed the shortest but is most promising.
1340 # Tie-break on UCI move representation.
1341 my $best_move = undef;
1342 for my $move (sort keys %refutation_moves) {
1343 if (!defined($best_move)) {
1347 my $best = $refutation_moves{$best_move};
1348 my $this = $refutation_moves{$move};
1350 if ($this->{'depth'} < $best->{'depth'} ||
1351 ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1357 my $m = $refutation_moves{$best_move};
1359 uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1360 uciprint($engine2, "go depth " . $m->{'depth'});
1361 $move_calculating_second_engine = $best_move;
1364 sub col_letter_to_num {
1365 return ord(shift) - ord('a');
1368 sub row_letter_to_num {
1369 return 7 - (ord(shift) - ord('1'));
1372 sub move_to_uci_notation {
1373 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1375 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);