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.
20 my $server = "freechess.org";
22 # my $engine = "/usr/games/toga2";
23 my $engine = "wine Rybkav2.3.2a.mp.w32.exe";
24 my $telltarget = undef; # undef to be silent
25 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960); # after each move
26 my $uci_assume_full_compliance = 1; # dangerous :-)
34 $SIG{ALRM} = sub { output_screen(); };
38 open(FICSLOG, ">ficslog.txt")
39 or die "ficslog.txt: $!";
40 print FICSLOG "Log starting.\n";
44 open(UCILOG, ">ucilog.txt")
45 or die "ucilog.txt: $!";
46 print UCILOG "Log starting.\n";
51 # open the chess engine
52 my $pid = IPC::Open2::open2(*UCIREAD, *UCIWRITE, $engine);
55 my ($last_move, $last_tell);
57 my $last_told_text = '';
58 my ($pos_waiting, $pos_calculating);
68 uciprint("setoption name UCI_AnalyseMode value true");
69 # uciprint("setoption name Preserve Analysis value true");
70 uciprint("setoption name NalimovPath value c:\\nalimov");
71 uciprint("setoption name NalimovUsage value Rarely");
72 uciprint("setoption name Hash value 1024");
73 uciprint("setoption name MultiPV value 3");
74 # uciprint("setoption name Contempt value 1000");
75 # uciprint("setoption name Outlook value Ultra Optimistic");
76 uciprint("ucinewgame");
78 print "Chess engine ready.\n";
81 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
82 $t->input_log(\*FICSLOG);
85 $t->waitfor('/Press return to enter the server/');
89 $t->cmd("set shout 0");
90 $t->cmd("set seek 0");
91 $t->cmd("set style 12");
92 $t->cmd("observe $target");
95 print "FICS ready.\n";
99 vec($rin, fileno(UCIREAD), 1) = 1;
100 vec($rin, fileno($t), 1) = 1;
102 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
106 my $line = $t->getline(Timeout => 0, errmode => 'return');
107 last if (!defined($line));
111 if ($line =~ /^<12> /) {
112 my $pos = style12_to_fen($line);
114 # if this is already in the queue, ignore it
115 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
117 # if we're already chewing on this and there's nothing else in the queue,
119 next if (!defined($pos_waiting) && defined($pos_calculating) &&
120 $pos->{'fen'} eq $pos_calculating->{'fen'});
122 # if we're already thinking on something, stop and wait for the engine
124 if (defined($pos_calculating)) {
125 if (!defined($pos_waiting)) {
128 if ($uci_assume_full_compliance) {
131 uciprint("position fen " . $pos->{'fen'});
132 uciprint("go infinite");
133 $pos_calculating = $pos;
136 # it's wrong just to give the FEN (the move history is useful,
137 # and per the UCI spec, we should really have sent "ucinewgame"),
139 uciprint("position fen " . $pos->{'fen'});
140 uciprint("go infinite");
141 $pos_calculating = $pos;
148 # Output a command every move to note that we're
149 # still paying attention -- this is a good tradeoff,
150 # since if no move has happened in the last half
151 # hour, the analysis/relay has most likely stopped
152 # and we should stop hogging server resources.
156 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
157 my ($who, $msg) = ($1, $2);
159 next if (grep { $_ eq $who } (@masters) == 0);
161 if ($msg =~ /^fics (.*?)$/) {
162 $t->cmd("tell $who Executing '$1' on FICS.");
164 } elsif ($msg =~ /^uci (.*?)$/) {
165 $t->cmd("tell $who Sending '$1' to the engine.");
166 print UCIWRITE "$1\n";
168 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
171 #print "FICS: [$line]\n";
175 # any fun on the UCI channel?
176 if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
178 # Read until we've got a full line -- if the engine sends part of
179 # a line and then stops we're pretty much hosed, but that should
183 while ($line !~ /\n/) {
185 my $ret = sysread UCIREAD, $tmp, 1;
187 if (!defined($ret)) {
189 die "error in reading from the UCI engine: $!";
190 } elsif ($ret == 0) {
191 die "EOF from UCI engine";
201 # don't update too often
202 Time::HiRes::alarm(0.2);
213 print UCILOG localtime() . " <= $line\n";
214 if ($line =~ /^info/) {
215 my (@infos) = split / /, $line;
220 if ($line =~ /^id/) {
221 my (@ids) = split / /, $line;
226 if ($line =~ /^bestmove/ && $uci_assume_full_compliance) {
227 if (defined($pos_waiting)) {
228 uciprint("position fen " . $pos_waiting->{'fen'});
229 uciprint("go infinite");
231 $pos_calculating = $pos_waiting;
232 $pos_waiting = undef;
241 while (scalar @x > 0) {
242 if ($x[0] =~ 'multipv') {
247 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
249 my $value = shift @x;
250 $uciinfo{$key} = $value;
253 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
255 my $value = shift @x;
256 $uciinfo{$key . $mpv} = $value;
259 if ($x[0] eq 'score') {
262 delete $uciinfo{'score_cp' . $mpv};
263 delete $uciinfo{'score_mate' . $mpv};
265 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
268 $uciinfo{'score_cp' . $mpv} = shift @x;
269 } elsif ($x[0] eq 'mate') {
271 $uciinfo{'score_mate' . $mpv} = shift @x;
279 $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
282 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
286 #print "unknown info '$x[0]', trying to recover...\n";
288 die "Unknown info '" . join(',', @x) . "'";
296 while (scalar @x > 0) {
297 if ($x[0] =~ /^(name|author)$/) {
299 my $value = join(' ', @x);
300 $uciid{$key} = $value;
312 my (@x) = split / /, $str;
314 $pos{'board'} = [ @x[1..8] ];
315 $pos{'toplay'} = $x[9];
318 my (@board) = @x[1..8];
319 for my $rank (0..7) {
320 $board[$rank] =~ s/(-+)/length($1)/ge;
322 my $fen = join('/', @board);
324 # white/black to move
330 $castling .= "K" if ($x[11] == 1);
331 $castling .= "Q" if ($x[12] == 1);
332 $castling .= "k" if ($x[13] == 1);
333 $castling .= "q" if ($x[14] == 1);
334 $castling = "-" if ($castling eq "");
342 my $nep = (qw(a b c d e f g h))[$col];
351 # Showing the en passant square when actually no capture can be made
352 # seems to confuse at least Rybka. Thus, check if there's actually
353 # a pawn of the opposite side that can do the en passant move, and if
354 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
355 # "right" thing as per the standard, though.
358 $ep = $nep if ($col > 0 && substr($pos{'board'}[4], $col-1, 1) eq 'p');
359 $ep = $nep if ($col < 7 && substr($pos{'board'}[4], $col+1, 1) eq 'p');
361 $ep = $nep if ($col > 0 && substr($pos{'board'}[3], $col-1, 1) eq 'P');
362 $ep = $nep if ($col < 7 && substr($pos{'board'}[3], $col+1, 1) eq 'P');
377 $pos{'move_num'} = $x[26];
383 my ($move_num, $toplay) = @_;
385 if ($toplay eq 'B') {
386 return "$move_num. ..";
393 my ($board, $move_num, $toplay, @pvs) = @_;
395 if (!defined($board) || !defined($move_num) || !defined($toplay)) {
398 if (scalar @pvs == 0 || !defined($pvs[0])) {
402 my ($prefix, $next_move, $next_toplay);
403 if ($toplay eq 'W') {
404 $prefix = "$move_num.";
405 $next_move = $move_num;
409 $next_move = $move_num + 1;
416 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
417 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
418 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
419 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
422 my $piece = substr($board->[$from_row], $from_col, 1);
427 if ($piece eq uc($piece) && $toplay eq 'B') {
428 die "Black tried to move a white piece";
430 if ($piece eq lc($piece) && $toplay eq 'W') {
431 die "White tried to move a black piece";
434 # white short castling
435 if ($pv 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');
444 return ($prefix . '0-0', prettyprint_pv(\@nb, $next_move, $next_toplay, @pvs));
447 # white long castling
448 if ($pv 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');
457 return ($prefix . '0-0-0', prettyprint_pv(\@nb, $next_move, $next_toplay, @pvs));
460 # black short castling
461 if ($pv 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');
470 return ($prefix . '0-0', prettyprint_pv(\@nb, $next_move, $next_toplay, @pvs));
473 # black long castling
474 if ($pv 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');
483 return ($prefix . '0-0-0', prettyprint_pv(\@nb, $next_move, $next_toplay, @pvs));
486 # check if the from-piece is a pawn
487 if (lc($piece) eq 'p') {
489 if ($from_col != $to_col) {
490 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
493 if (substr($board->[$to_row], $to_col, 1) eq '-') {
495 substr($nb[$to_row + 1], $to_col, 1, '-');
497 substr($nb[$to_row - 1], $to_col, 1, '-');
501 $pretty = substr($pv, 2, 2);
503 if (length($pv) == 5) {
506 $pretty .= uc(substr($pv, 4, 1));
509 $piece = substr($pv, 4, 1);
511 $piece = uc(substr($pv, 4, 1));
516 $pretty = uc($piece);
518 # see how many of these pieces could go here, in all
522 next unless (substr($board->[$row], $col, 1) eq $piece);
523 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
527 # see how many of these pieces from the given row could go here
530 next unless (substr($board->[$from_row], $col, 1) eq $piece);
531 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
534 # and same for columns
537 next unless (substr($board->[$row], $from_col, 1) eq $piece);
538 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
541 # see if we need to disambiguate
542 if ($num_total > 1) {
544 $pretty .= substr($pv, 0, 1);
545 } elsif ($num_row == 1) {
546 $pretty .= substr($pv, 1, 1);
548 $pretty .= substr($pv, 0, 2);
553 if (substr($board->[$to_row], $to_col, 1) ne '-') {
557 $pretty .= substr($pv, 2, 2);
561 substr($nb[$from_row], $from_col, 1, '-');
562 substr($nb[$to_row], $to_col, 1, $piece);
566 } elsif (in_check(\@nb) ne 'none') {
570 return ($prefix . $pretty, prettyprint_pv(\@nb, $next_move, $next_toplay, @pvs));
576 return if (!defined($pos_calculating));
579 # Check the PVs first. if they're invalid, just wait, as our data
580 # is most likely out of sync. This isn't a very good solution, as
581 # it can frequently miss stuff, but it's good enough for most users.
585 if (exists($uciinfo{'pv'})) {
586 $dummy = prettyprint_pv($pos_calculating->{'board'},
587 $pos_calculating->{'move_num'},
588 $pos_calculating->{'toplay'},
593 while (exists($uciinfo{'pv' . $mpv})) {
594 $dummy = prettyprint_pv($pos_calculating->{'board'},
595 $pos_calculating->{'move_num'},
596 $pos_calculating->{'toplay'},
597 @{$uciinfo{'pv' . $mpv}});
608 if (exists($uciid{'name'})) {
609 $text .= "Analysis by $uciid{'name'}:\n\n";
611 $text .= "Analysis:\n\n";
614 return unless (exists($pos_calculating->{'board'}));
617 # Some programs _always_ report MultiPV, even with only one PV.
618 # In this case, we simply use that data as if MultiPV was never
621 if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
622 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
623 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
624 $uciinfo{$key} = $uciinfo{$key . '1'};
630 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
633 while (exists($uciinfo{'pv' . $mpv})) {
634 $text_pvs[$mpv] = prefix_pv($pos_calculating->{'move_num'}, $pos_calculating->{'toplay'}) .
635 join(' ', prettyprint_pv($pos_calculating->{'board'},
636 $pos_calculating->{'move_num'},
637 $pos_calculating->{'toplay'},
638 @{$uciinfo{'pv' . $mpv}}));
643 $text_pvs[0] = prefix_pv($pos_calculating->{'move_num'}, $pos_calculating->{'toplay'}) .
644 join(' ', prettyprint_pv($pos_calculating->{'board'},
645 $pos_calculating->{'move_num'},
646 $pos_calculating->{'toplay'},
650 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
653 while (exists($uciinfo{'pv' . $mpv})) {
654 $text .= sprintf " PV%2u", $mpv;
655 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
656 $text .= " ($score)" if (defined($score));
659 if (exists($uciinfo{'tbhits' . $mpv})) {
660 $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
663 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
664 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
665 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
669 $text .= " $text_pvs[$mpv]\n\n";
674 my $score = long_score(\%uciinfo, $pos_calculating, '');
675 $text .= " $score\n" if defined($score);
676 $text .= " PV: $text_pvs[0]\n";
678 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
679 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
680 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
682 if (exists($uciinfo{'tbhits'})) {
683 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
685 if (exists($uciinfo{'seldepth'})) {
686 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
691 if ($last_text ne $text) {
692 print "
\e[H
\e[2J"; # clear the screen
697 # Now construct the tell text, if any
698 return if (!defined($telltarget));
702 if (exists($uciid{'name'})) {
703 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
705 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
708 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
711 while (exists($uciinfo{'pv' . $mpv})) {
712 $tell_text .= sprintf " PV%2u", $mpv;
713 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
714 $tell_text .= " ($score)" if (defined($score));
716 if (exists($uciinfo{'depth' . $mpv})) {
717 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
720 $tell_text .= ": $text_pvs[$mpv]\n";
725 my $score = long_score(\%uciinfo, $pos_calculating, '');
726 $tell_text .= " $score\n" if defined($score);
727 $tell_text .= " PV: $text_pvs[0]";
728 if (exists($uciinfo{'depth'})) {
729 $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
734 # see if a new tell is called for -- it is if the delay has expired _and_
735 # this is not simply a repetition of the last one
736 if ($last_told_text ne $tell_text) {
738 for my $iv (@tell_intervals) {
739 last if ($now - $last_move < $iv);
740 next if ($last_tell - $last_move >= $iv);
742 for my $line (split /\n/, $tell_text) {
743 $t->print("tell $telltarget [$target] $line");
746 $last_told_text = $text;
756 my ($wkr, $wkc, $bkr, $bkc);
760 my $piece = substr($board->[$row], $col, 1);
762 ($wkr, $wkc) = ($row, $col);
763 } elsif ($piece eq 'k') {
764 ($bkr, $bkc) = ($row, $col);
769 return ($wkr, $wkc, $bkr, $bkc);
774 my $check = in_check($board);
775 return 0 if ($check eq 'none');
777 # try all possible moves for the side in check
780 my $piece = substr($board->[$row], $col, 1);
781 next if ($piece eq '-');
783 if ($check eq 'white') {
784 next if ($piece eq lc($piece));
786 next if ($piece eq uc($piece));
789 for my $dest_row (0..7) {
790 for my $dest_col (0..7) {
791 next if ($row == $dest_row && $col == $dest_col);
792 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
795 substr($nb[$row], $col, 1, '-');
796 substr($nb[$dest_row], $dest_col, 1, $piece);
798 my $new_check = in_check(\@nb);
799 return 0 if ($new_check ne $check && $new_check ne 'both');
805 # nothing to do; mate
811 my ($black_check, $white_check) = (0, 0);
813 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
815 # check all pieces for the possibility of threatening the two kings
818 my $piece = substr($board->[$row], $col, 1);
819 next if ($piece eq '-');
821 if (uc($piece) eq $piece) {
823 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
826 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
831 if ($black_check && $white_check) {
833 } elsif ($black_check) {
835 } elsif ($white_check) {
843 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
845 # can't eat your own piece
846 my $dest_piece = substr($board->[$to_row], $to_col, 1);
847 if ($dest_piece ne '-') {
848 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
851 if (lc($piece) eq 'k') {
852 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
854 if (lc($piece) eq 'r') {
855 return 0 unless ($from_row == $to_row || $from_col == $to_col);
857 # check that there's a clear passage
858 if ($from_row == $to_row) {
859 if ($from_col > $to_col) {
860 ($to_col, $from_col) = ($from_col, $to_col);
863 for my $c (($from_col+1)..($to_col-1)) {
864 my $middle_piece = substr($board->[$to_row], $c, 1);
865 return 0 if ($middle_piece ne '-');
870 if ($from_row > $to_row) {
871 ($to_row, $from_row) = ($from_row, $to_row);
874 for my $r (($from_row+1)..($to_row-1)) {
875 my $middle_piece = substr($board->[$r], $to_col, 1);
876 return 0 if ($middle_piece ne '-');
882 if (lc($piece) eq 'b') {
883 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
885 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
886 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
888 my $r = $from_row + $dr;
889 my $c = $from_col + $dc;
891 while ($r != $to_row) {
892 my $middle_piece = substr($board->[$r], $c, 1);
893 return 0 if ($middle_piece ne '-');
901 if (lc($piece) eq 'n') {
902 my $diff_r = abs($from_row - $to_row);
903 my $diff_c = abs($from_col - $to_col);
904 return 1 if ($diff_r == 2 && $diff_c == 1);
905 return 1 if ($diff_r == 1 && $diff_c == 2);
909 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
910 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
913 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
914 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
918 if ($to_col == $from_col && $to_row == $from_row + 1) {
919 return ($dest_piece eq '-');
921 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
922 return ($dest_piece ne '-');
928 if ($to_col == $from_col && $to_row == $from_row - 1) {
929 return ($dest_piece eq '-');
931 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
932 return ($dest_piece ne '-');
943 print UCIWRITE "$msg\n";
944 print UCILOG localtime() . " => $msg\n";
948 my ($uciinfo, $pos, $mpv) = @_;
950 if (defined($uciinfo{'score_mate' . $mpv})) {
951 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
953 if (exists($uciinfo{'score_cp' . $mpv})) {
954 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
955 if ($pos->{'toplay'} eq 'B') {
958 return sprintf "%+5.2f", $score;
966 my ($uciinfo, $pos, $mpv) = @_;
968 if (defined($uciinfo{'score_mate' . $mpv})) {
969 my $mate = $uciinfo{'score_mate' . $mpv};
970 if ($pos->{'toplay'} eq 'B') {
974 return sprintf "White mates in %u", $mate;
976 return sprintf "Black mates in %u", -$mate;
979 if (exists($uciinfo{'score_cp' . $mpv})) {
980 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
981 if ($pos->{'toplay'} eq 'B') {
984 return sprintf "Score: %+5.2f", $score;