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 :-)
29 $SIG{ALRM} = sub { output_screen(); };
33 open(FICSLOG, ">ficslog.txt")
34 or die "ficslog.txt: $!";
35 print FICSLOG "Log starting.\n";
39 open(UCILOG, ">ucilog.txt")
40 or die "ucilog.txt: $!";
41 print UCILOG "Log starting.\n";
46 # open the chess engine
47 my $pid = IPC::Open2::open2(*UCIREAD, *UCIWRITE, $engine);
50 my ($last_move, $last_tell);
52 my $last_told_text = '';
53 my ($pos_waiting, $pos_calculating);
63 uciprint("setoption name UCI_AnalyseMode value true");
64 # uciprint("setoption name Preserve Analysis value true");
65 uciprint("setoption name NalimovPath value c:\\nalimov");
66 uciprint("setoption name NalimovUsage value Rarely");
67 uciprint("setoption name Hash value 1024");
68 uciprint("setoption name MultiPV value 3");
69 # uciprint("setoption name Contempt value 1000");
70 # uciprint("setoption name Outlook value Ultra Optimistic");
71 uciprint("ucinewgame");
73 print "Chess engine ready.\n";
76 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
77 $t->input_log(\*FICSLOG);
80 $t->waitfor('/Press return to enter the server/');
84 $t->cmd("set shout 0");
85 $t->cmd("set seek 0");
86 $t->cmd("set style 12");
87 $t->cmd("observe $target");
90 print "FICS ready.\n";
94 vec($rin, fileno(UCIREAD), 1) = 1;
95 vec($rin, fileno($t), 1) = 1;
97 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
101 my $line = $t->getline(Timeout => 0, errmode => 'return');
102 last if (!defined($line));
106 if ($line =~ /^<12> /) {
107 my $pos = style12_to_fen($line);
109 # if this is already in the queue, ignore it
110 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
112 # if we're already chewing on this and there's nothing else in the queue,
114 next if (!defined($pos_waiting) && defined($pos_calculating) &&
115 $pos->{'fen'} eq $pos_calculating->{'fen'});
117 # if we're already thinking on something, stop and wait for the engine
119 if (defined($pos_calculating)) {
120 if (!defined($pos_waiting)) {
123 if ($uci_assume_full_compliance) {
126 uciprint("position fen " . $pos->{'fen'});
127 uciprint("go infinite");
128 $pos_calculating = $pos;
131 # it's wrong just to give the FEN (the move history is useful,
132 # and per the UCI spec, we should really have sent "ucinewgame"),
134 uciprint("position fen " . $pos->{'fen'});
135 uciprint("go infinite");
136 $pos_calculating = $pos;
143 # Output a command every move to note that we're
144 # still paying attention -- this is a good tradeoff,
145 # since if no move has happened in the last half
146 # hour, the analysis/relay has most likely stopped
147 # and we should stop hogging server resources.
151 #print "FICS: [$line]\n";
155 # any fun on the UCI channel?
156 if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
158 # Read until we've got a full line -- if the engine sends part of
159 # a line and then stops we're pretty much hosed, but that should
163 while ($line !~ /\n/) {
165 my $ret = sysread UCIREAD, $tmp, 1;
167 if (!defined($ret)) {
169 die "error in reading from the UCI engine: $!";
170 } elsif ($ret == 0) {
171 die "EOF from UCI engine";
181 # don't update too often
182 Time::HiRes::alarm(0.2);
193 print UCILOG localtime() . " <= $line\n";
194 if ($line =~ /^info/) {
195 my (@infos) = split / /, $line;
200 if ($line =~ /^id/) {
201 my (@ids) = split / /, $line;
206 if ($line =~ /^bestmove/ && $uci_assume_full_compliance) {
207 if (defined($pos_waiting)) {
208 uciprint("position fen " . $pos_waiting->{'fen'});
209 uciprint("go infinite");
211 $pos_calculating = $pos_waiting;
212 $pos_waiting = undef;
221 while (scalar @x > 0) {
222 if ($x[0] =~ 'multipv') {
227 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
229 my $value = shift @x;
230 $uciinfo{$key} = $value;
233 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
235 my $value = shift @x;
236 $uciinfo{$key . $mpv} = $value;
239 if ($x[0] eq 'score') {
242 delete $uciinfo{'score_cp' . $mpv};
243 delete $uciinfo{'score_mate' . $mpv};
245 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
248 $uciinfo{'score_cp' . $mpv} = shift @x;
249 } elsif ($x[0] eq 'mate') {
251 $uciinfo{'score_mate' . $mpv} = shift @x;
259 $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
262 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
266 #print "unknown info '$x[0]', trying to recover...\n";
268 die "Unknown info '" . join(',', @x) . "'";
276 while (scalar @x > 0) {
277 if ($x[0] =~ /^(name|author)$/) {
279 my $value = join(' ', @x);
280 $uciid{$key} = $value;
292 my (@x) = split / /, $str;
294 $pos{'board'} = [ @x[1..8] ];
295 $pos{'toplay'} = $x[9];
298 my (@board) = @x[1..8];
299 for my $rank (0..7) {
300 $board[$rank] =~ s/(-+)/length($1)/ge;
302 my $fen = join('/', @board);
304 # white/black to move
310 $castling .= "K" if ($x[11] == 1);
311 $castling .= "Q" if ($x[12] == 1);
312 $castling .= "k" if ($x[13] == 1);
313 $castling .= "q" if ($x[14] == 1);
314 $castling = "-" if ($castling eq "");
322 my $nep = (qw(a b c d e f g h))[$col];
331 # Showing the en passant square when actually no capture can be made
332 # seems to confuse at least Rybka. Thus, check if there's actually
333 # a pawn of the opposite side that can do the en passant move, and if
334 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
335 # "right" thing as per the standard, though.
338 $ep = $nep if ($col > 0 && substr($pos{'board'}[4], $col-1, 1) eq 'p');
339 $ep = $nep if ($col < 7 && substr($pos{'board'}[4], $col+1, 1) eq 'p');
341 $ep = $nep if ($col > 0 && substr($pos{'board'}[3], $col-1, 1) eq 'P');
342 $ep = $nep if ($col < 7 && substr($pos{'board'}[3], $col+1, 1) eq 'P');
362 my ($board, @pvs) = @_;
364 if (scalar @pvs == 0 || !defined($pvs[0])) {
371 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
372 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
373 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
374 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
377 my $piece = substr($board->[$from_row], $from_col, 1);
383 # white short castling
384 if ($pv eq 'e1g1' && $piece eq 'K') {
386 substr($nb[7], 4, 1, '-');
387 substr($nb[7], 6, 1, $piece);
390 substr($nb[7], 7, 1, '-');
391 substr($nb[7], 5, 1, 'R');
393 return ('0-0', prettyprint_pv(\@nb, @pvs));
396 # white long castling
397 if ($pv eq 'e1c1' && $piece eq 'K') {
399 substr($nb[7], 4, 1, '-');
400 substr($nb[7], 2, 1, $piece);
403 substr($nb[7], 0, 1, '-');
404 substr($nb[7], 3, 1, 'R');
406 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
409 # black short castling
410 if ($pv eq 'e8g8' && $piece eq 'k') {
412 substr($nb[0], 4, 1, '-');
413 substr($nb[0], 6, 1, $piece);
416 substr($nb[0], 7, 1, '-');
417 substr($nb[0], 5, 1, 'r');
419 return ('0-0', prettyprint_pv(\@nb, @pvs));
422 # black long castling
423 if ($pv eq 'e8c8' && $piece eq 'k') {
425 substr($nb[0], 4, 1, '-');
426 substr($nb[0], 2, 1, $piece);
429 substr($nb[0], 0, 1, '-');
430 substr($nb[0], 3, 1, 'r');
432 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
435 # check if the from-piece is a pawn
436 if (lc($piece) eq 'p') {
438 if ($from_col != $to_col) {
439 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
442 if (substr($board->[$to_row], $to_col, 1) eq '-') {
444 substr($nb[$to_row + 1], $to_col, 1, '-');
446 substr($nb[$to_row - 1], $to_col, 1, '-');
450 $pretty = substr($pv, 2, 2);
452 if (length($pv) == 5) {
455 $pretty .= uc(substr($pv, 4, 1));
458 $piece = substr($pv, 4, 1);
460 $piece = uc(substr($pv, 4, 1));
465 $pretty = uc($piece);
467 # see how many of these pieces could go here, in all
471 next unless (substr($board->[$row], $col, 1) eq $piece);
472 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
476 # see how many of these pieces from the given row could go here
479 next unless (substr($board->[$from_row], $col, 1) eq $piece);
480 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
483 # and same for columns
486 next unless (substr($board->[$row], $from_col, 1) eq $piece);
487 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
490 # see if we need to disambiguate
491 if ($num_total > 1) {
493 $pretty .= substr($pv, 0, 1);
494 } elsif ($num_row == 1) {
495 $pretty .= substr($pv, 1, 1);
497 $pretty .= substr($pv, 0, 2);
502 if (substr($board->[$to_row], $to_col, 1) ne '-') {
506 $pretty .= substr($pv, 2, 2);
510 substr($nb[$from_row], $from_col, 1, '-');
511 substr($nb[$to_row], $to_col, 1, $piece);
515 } elsif (in_check(\@nb) ne 'none') {
519 return ($pretty, prettyprint_pv(\@nb, @pvs));
525 return if (!defined($pos_calculating));
528 # Check the PVs first. if they're invalid, just wait, as our data
529 # is most likely out of sync. This isn't a very good solution, as
530 # it can frequently miss stuff, but it's good enough for most users.
534 if (exists($uciinfo{'pv'})) {
535 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
539 while (exists($uciinfo{'pv' . $mpv})) {
540 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
551 if (exists($uciid{'name'})) {
552 $text .= "Analysis by $uciid{'name'}:\n\n";
554 $text .= "Analysis:\n\n";
557 return unless (exists($pos_calculating->{'board'}));
560 # Some programs _always_ report MultiPV, even with only one PV.
561 # In this case, we simply use that data as if MultiPV was never
564 if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
565 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
566 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
567 $uciinfo{$key} = $uciinfo{$key . '1'};
572 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
575 while (exists($uciinfo{'pv' . $mpv})) {
576 $text .= sprintf " PV%2u", $mpv;
577 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
578 $text .= " ($score)" if (defined($score));
581 if (exists($uciinfo{'tbhits' . $mpv})) {
582 $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
585 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
586 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
587 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
591 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
597 my $score = long_score(\%uciinfo, $pos_calculating, '');
598 $text .= " $score\n" if defined($score);
599 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
602 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
603 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
604 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
606 if (exists($uciinfo{'tbhits'})) {
607 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
609 if (exists($uciinfo{'seldepth'})) {
610 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
615 if ($last_text ne $text) {
616 print "
\e[H
\e[2J"; # clear the screen
621 # Now construct the tell text, if any
622 return if (!defined($telltarget));
626 if (exists($uciid{'name'})) {
627 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
629 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
632 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
635 while (exists($uciinfo{'pv' . $mpv})) {
636 $tell_text .= sprintf " PV%2u", $mpv;
637 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
638 $tell_text .= " ($score)" if (defined($score));
640 if (exists($uciinfo{'depth' . $mpv})) {
641 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
645 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
651 my $score = long_score(\%uciinfo, $pos_calculating, '');
652 $tell_text .= " $score\n" if defined($score);
653 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
654 if (exists($uciinfo{'depth'})) {
655 $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
660 # see if a new tell is called for -- it is if the delay has expired _and_
661 # this is not simply a repetition of the last one
662 if ($last_told_text ne $tell_text) {
664 for my $iv (@tell_intervals) {
665 last if ($now - $last_move < $iv);
666 next if ($last_tell - $last_move >= $iv);
668 for my $line (split /\n/, $tell_text) {
669 $t->print("tell $telltarget [$target] $line");
672 $last_told_text = $text;
682 my ($wkr, $wkc, $bkr, $bkc);
686 my $piece = substr($board->[$row], $col, 1);
688 ($wkr, $wkc) = ($row, $col);
689 } elsif ($piece eq 'k') {
690 ($bkr, $bkc) = ($row, $col);
695 return ($wkr, $wkc, $bkr, $bkc);
700 my $check = in_check($board);
701 return 0 if ($check eq 'none');
703 # try all possible moves for the side in check
706 my $piece = substr($board->[$row], $col, 1);
707 next if ($piece eq '-');
709 if ($check eq 'white') {
710 next if ($piece eq lc($piece));
712 next if ($piece eq uc($piece));
715 for my $dest_row (0..7) {
716 for my $dest_col (0..7) {
717 next if ($row == $dest_row && $col == $dest_col);
718 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
721 substr($nb[$row], $col, 1, '-');
722 substr($nb[$dest_row], $dest_col, 1, $piece);
724 my $new_check = in_check(\@nb);
725 return 0 if ($new_check ne $check && $new_check ne 'both');
731 # nothing to do; mate
737 my ($black_check, $white_check) = (0, 0);
739 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
741 # check all pieces for the possibility of threatening the two kings
744 my $piece = substr($board->[$row], $col, 1);
745 next if ($piece eq '-');
747 if (uc($piece) eq $piece) {
749 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
752 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
757 if ($black_check && $white_check) {
759 } elsif ($black_check) {
761 } elsif ($white_check) {
769 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
771 # can't eat your own piece
772 my $dest_piece = substr($board->[$to_row], $to_col, 1);
773 if ($dest_piece ne '-') {
774 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
777 if (lc($piece) eq 'k') {
778 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
780 if (lc($piece) eq 'r') {
781 return 0 unless ($from_row == $to_row || $from_col == $to_col);
783 # check that there's a clear passage
784 if ($from_row == $to_row) {
785 if ($from_col > $to_col) {
786 ($to_col, $from_col) = ($from_col, $to_col);
789 for my $c (($from_col+1)..($to_col-1)) {
790 my $middle_piece = substr($board->[$to_row], $c, 1);
791 return 0 if ($middle_piece ne '-');
796 if ($from_row > $to_row) {
797 ($to_row, $from_row) = ($from_row, $to_row);
800 for my $r (($from_row+1)..($to_row-1)) {
801 my $middle_piece = substr($board->[$r], $to_col, 1);
802 return 0 if ($middle_piece ne '-');
808 if (lc($piece) eq 'b') {
809 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
811 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
812 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
814 my $r = $from_row + $dr;
815 my $c = $from_col + $dc;
817 while ($r != $to_row) {
818 my $middle_piece = substr($board->[$r], $c, 1);
819 return 0 if ($middle_piece ne '-');
827 if (lc($piece) eq 'n') {
828 my $diff_r = abs($from_row - $to_row);
829 my $diff_c = abs($from_col - $to_col);
830 return 1 if ($diff_r == 2 && $diff_c == 1);
831 return 1 if ($diff_r == 1 && $diff_c == 2);
835 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
836 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
839 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
840 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
844 if ($to_col == $from_col && $to_row == $from_row + 1) {
845 return ($dest_piece eq '-');
847 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
848 return ($dest_piece ne '-');
854 if ($to_col == $from_col && $to_row == $from_row - 1) {
855 return ($dest_piece eq '-');
857 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
858 return ($dest_piece ne '-');
869 print UCIWRITE "$msg\n";
870 print UCILOG localtime() . " => $msg\n";
874 my ($uciinfo, $pos, $mpv) = @_;
876 if (defined($uciinfo{'score_mate' . $mpv})) {
877 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
879 if (exists($uciinfo{'score_cp' . $mpv})) {
880 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
881 if ($pos->{'toplay'} eq 'B') {
884 return sprintf "%+5.2f", $score;
892 my ($uciinfo, $pos, $mpv) = @_;
894 if (defined($uciinfo{'score_mate' . $mpv})) {
895 my $mate = $uciinfo{'score_mate' . $mpv};
896 if ($pos->{'toplay'} eq 'B') {
900 return sprintf "White mates in %u", $mate;
902 return sprintf "Black mates in %u", -$mate;
905 if (exists($uciinfo{'score_cp' . $mpv})) {
906 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
907 if ($pos->{'toplay'} eq 'B') {
910 return sprintf "Score: %+5.2f", $score;