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
28 $SIG{ALRM} = sub { output_screen(); };
32 open(FICSLOG, ">ficslog.txt")
33 or die "ficslog.txt: $!";
34 print FICSLOG "Log starting.\n";
38 open(UCILOG, ">ucilog.txt")
39 or die "ucilog.txt: $!";
40 print UCILOG "Log starting.\n";
45 # open the chess engine
46 my $pid = IPC::Open2::open2(*UCIREAD, *UCIWRITE, $engine);
50 my ($last_move, $last_tell);
52 my $last_told_text = '';
53 my ($board_waiting, $board_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 $fen = style12_to_fen($line);
109 # if this is already in the queue, ignore it
110 next if (defined($board_waiting) && $fen eq $board_waiting);
112 # if we're already chewing on this and there's nothing else in the queue,
114 next if (!defined($board_waiting) && defined($board_calculating) &&
115 $fen eq $board_calculating);
117 # if we're already thinking on something, stop and wait for the engine
119 if (defined($board_calculating)) {
121 $board_waiting = $fen;
123 # it's wrong just to give the FEN (the move history is useful,
124 # and per the UCI spec, we should really have sent "ucinewgame"),
126 uciprint("position fen $fen");
127 uciprint("go infinite");
134 # Output a command every move to note that we're
135 # still paying attention -- this is a good tradeoff,
136 # since if no move has happened in the last half
137 # hour, the analysis/relay has most likely stopped
138 # and we should stop hogging server resources.
142 #print "FICS: [$line]\n";
146 # any fun on the UCI channel?
147 if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
148 my $line = <UCIREAD>;
152 # don't update too often
153 Time::HiRes::alarm(0.2);
164 print UCILOG "<= $line\n";
165 if ($line =~ /^info/) {
166 my (@infos) = split / /, $line;
171 if ($line =~ /^id/) {
172 my (@ids) = split / /, $line;
177 if ($line =~ /^bestmove/) {
178 if (defined($board_calculating)) {
179 uciprint("position fen $board_waiting");
180 uciprint("go infinite");
182 $board_calculating = $board_waiting;
183 $board_waiting = undef;
192 while (scalar @x > 0) {
193 if ($x[0] =~ 'multipv') {
198 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
200 my $value = shift @x;
201 $uciinfo{$key} = $value;
204 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
206 my $value = shift @x;
207 $uciinfo{$key . $mpv} = $value;
210 if ($x[0] eq 'score') {
213 delete $uciinfo{'score_cp' . $mpv};
214 delete $uciinfo{'score_mate' . $mpv};
216 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
219 $uciinfo{'score_cp' . $mpv} = shift @x;
220 } elsif ($x[0] eq 'mate') {
222 $uciinfo{'score_mate' . $mpv} = shift @x;
230 $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
233 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
237 #print "unknown info '$x[0]', trying to recover...\n";
239 die "Unknown info '" . join(',', @x) . "'";
247 while (scalar @x > 0) {
248 if ($x[0] =~ /^(name|author)$/) {
250 my $value = join(' ', @x);
251 $uciid{$key} = $value;
262 my (@x) = split / /, $str;
264 $ficsinfo{'board'} = [ @x[1..8] ];
265 $ficsinfo{'toplay'} = $x[9];
268 my (@board) = @x[1..8];
269 for my $rank (0..7) {
270 $board[$rank] =~ s/(-+)/length($1)/ge;
272 my $fen = join('/', @board);
274 # white/black to move
280 $castling .= "K" if ($x[11] == 1);
281 $castling .= "Q" if ($x[12] == 1);
282 $castling .= "k" if ($x[13] == 1);
283 $castling .= "q" if ($x[14] == 1);
284 $castling = "-" if ($castling eq "");
292 my $nep = (qw(a b c d e f g h))[$col];
301 # Showing the en passant square when actually no capture can be made
302 # seems to confuse at least Rybka. Thus, check if there's actually
303 # a pawn of the opposite side that can do the en passant move, and if
304 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
305 # "right" thing as per the standard, though.
308 $ep = $nep if ($col > 0 && substr($board[4], $col-1, 1) eq 'p');
309 $ep = $nep if ($col < 7 && substr($board[4], $col+1, 1) eq 'p');
311 $ep = $nep if ($col > 0 && substr($board[3], $col-1, 1) eq 'P');
312 $ep = $nep if ($col < 7 && substr($board[3], $col+1, 1) eq 'P');
330 my ($board, @pvs) = @_;
332 if (scalar @pvs == 0 || !defined($pvs[0])) {
339 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
340 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
341 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
342 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
345 my $piece = substr($board->[$from_row], $from_col, 1);
351 # white short castling
352 if ($pv eq 'e1g1' && $piece eq 'K') {
354 substr($nb[7], 4, 1, '-');
355 substr($nb[7], 6, 1, $piece);
358 substr($nb[7], 7, 1, '-');
359 substr($nb[7], 5, 1, 'R');
361 return ('0-0', prettyprint_pv(\@nb, @pvs));
364 # white long castling
365 if ($pv eq 'e1c1' && $piece eq 'K') {
367 substr($nb[7], 4, 1, '-');
368 substr($nb[7], 2, 1, $piece);
371 substr($nb[7], 0, 1, '-');
372 substr($nb[7], 3, 1, 'R');
374 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
377 # black short castling
378 if ($pv eq 'e8g8' && $piece eq 'k') {
380 substr($nb[0], 4, 1, '-');
381 substr($nb[0], 6, 1, $piece);
384 substr($nb[0], 7, 1, '-');
385 substr($nb[0], 5, 1, 'r');
387 return ('0-0', prettyprint_pv(\@nb, @pvs));
390 # black long castling
391 if ($pv eq 'e8c8' && $piece eq 'k') {
393 substr($nb[0], 4, 1, '-');
394 substr($nb[0], 2, 1, $piece);
397 substr($nb[0], 0, 1, '-');
398 substr($nb[0], 3, 1, 'r');
400 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
403 # check if the from-piece is a pawn
404 if (lc($piece) eq 'p') {
406 if ($from_col != $to_col) {
407 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
410 if (substr($board->[$to_row], $to_col, 1) eq '-') {
412 substr($nb[$to_row + 1], $to_col, 1, '-');
414 substr($nb[$to_row - 1], $to_col, 1, '-');
418 $pretty = substr($pv, 2, 2);
420 if (length($pv) == 5) {
423 $pretty .= uc(substr($pv, 4, 1));
426 $piece = substr($pv, 4, 1);
428 $piece = uc(substr($pv, 4, 1));
433 $pretty = uc($piece);
435 # see how many of these pieces could go here, in all
439 next unless (substr($board->[$row], $col, 1) eq $piece);
440 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
444 # see how many of these pieces from the given row could go here
447 next unless (substr($board->[$from_row], $col, 1) eq $piece);
448 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
451 # and same for columns
454 next unless (substr($board->[$row], $from_col, 1) eq $piece);
455 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
458 # see if we need to disambiguate
459 if ($num_total > 1) {
461 $pretty .= substr($pv, 0, 1);
462 } elsif ($num_row == 1) {
463 $pretty .= substr($pv, 1, 1);
465 $pretty .= substr($pv, 0, 2);
470 if (substr($board->[$to_row], $to_col, 1) ne '-') {
474 $pretty .= substr($pv, 2, 2);
478 substr($nb[$from_row], $from_col, 1, '-');
479 substr($nb[$to_row], $to_col, 1, $piece);
483 } elsif (in_check(\@nb) ne 'none') {
487 return ($pretty, prettyprint_pv(\@nb, @pvs));
494 # Check the PVs first. if they're invalid, just wait, as our data
495 # is most likely out of sync. This isn't a very good solution, as
496 # it can frequently miss stuff, but it's good enough for most users.
500 if (exists($uciinfo{'pv'})) {
501 $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}});
505 while (exists($uciinfo{'pv' . $mpv})) {
506 $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}});
517 if (exists($uciid{'name'})) {
518 $text .= "Analysis by $uciid{'name'}:\n\n";
520 $text .= "Analysis:\n\n";
523 return unless (exists($ficsinfo{'board'}));
526 # Some programs _always_ report MultiPV, even with only one PV.
527 # In this case, we simply use that data as if MultiPV was never
530 if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
531 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
532 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
533 $uciinfo{$key} = $uciinfo{$key . '1'};
538 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
541 while (exists($uciinfo{'pv' . $mpv})) {
542 $text .= sprintf " PV%2u", $mpv;
543 my $score = short_score(\%uciinfo, \%ficsinfo, $mpv);
544 $text .= " ($score)" if (defined($score));
546 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
547 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply)",
548 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
552 $text .= " " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
558 my $score = long_score(\%uciinfo, \%ficsinfo, '');
559 $text .= " $score\n" if defined($score);
560 $text .= " PV: " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
563 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
564 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
565 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
567 if (exists($uciinfo{'tbhits'})) {
568 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
570 if (exists($uciinfo{'seldepth'})) {
571 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
576 if ($last_text ne $text) {
577 print "
\e[H
\e[2J"; # clear the screen
582 # Now construct the tell text, if any
583 return if (!defined($telltarget));
587 if (exists($uciid{'name'})) {
588 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
590 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
593 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
596 while (exists($uciinfo{'pv' . $mpv})) {
597 $tell_text .= sprintf " PV%2u", $mpv;
598 my $score = short_score(\%uciinfo, \%ficsinfo, $mpv);
599 $tell_text .= " ($score)" if (defined($score));
601 if (exists($uciinfo{'depth' . $mpv})) {
602 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
606 $tell_text .= join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}}));
612 my $score = long_score(\%uciinfo, \%ficsinfo, '');
613 $tell_text .= " $score\n" if defined($score);
614 $tell_text .= " PV: " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
615 if (exists($uciinfo{'depth'})) {
616 $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
621 # see if a new tell is called for -- it is if the delay has expired _and_
622 # this is not simply a repetition of the last one
623 if ($last_told_text ne $tell_text) {
625 for my $iv (@tell_intervals) {
626 last if ($now - $last_move < $iv);
627 next if ($last_tell - $last_move >= $iv);
629 for my $line (split /\n/, $tell_text) {
630 $t->print("tell $telltarget [$target] $line");
633 $last_told_text = $text;
643 my ($wkr, $wkc, $bkr, $bkc);
647 my $piece = substr($board->[$row], $col, 1);
649 ($wkr, $wkc) = ($row, $col);
650 } elsif ($piece eq 'k') {
651 ($bkr, $bkc) = ($row, $col);
656 return ($wkr, $wkc, $bkr, $bkc);
661 my $check = in_check($board);
662 return 0 if ($check eq 'none');
664 # try all possible moves for the side in check
667 my $piece = substr($board->[$row], $col, 1);
668 next if ($piece eq '-');
670 if ($check eq 'white') {
671 next if ($piece eq lc($piece));
673 next if ($piece eq uc($piece));
676 for my $dest_row (0..7) {
677 for my $dest_col (0..7) {
678 next if ($row == $dest_row && $col == $dest_col);
679 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
682 substr($nb[$row], $col, 1, '-');
683 substr($nb[$dest_row], $dest_col, 1, $piece);
685 my $new_check = in_check(\@nb);
686 return 0 if ($new_check ne $check && $new_check ne 'both');
692 # nothing to do; mate
698 my ($black_check, $white_check) = (0, 0);
700 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
702 # check all pieces for the possibility of threatening the two kings
705 my $piece = substr($board->[$row], $col, 1);
706 next if ($piece eq '-');
708 if (uc($piece) eq $piece) {
710 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
713 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
718 if ($black_check && $white_check) {
720 } elsif ($black_check) {
722 } elsif ($white_check) {
730 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
732 # can't eat your own piece
733 my $dest_piece = substr($board->[$to_row], $to_col, 1);
734 if ($dest_piece ne '-') {
735 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
738 if (lc($piece) eq 'k') {
739 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
741 if (lc($piece) eq 'r') {
742 return 0 unless ($from_row == $to_row || $from_col == $to_col);
744 # check that there's a clear passage
745 if ($from_row == $to_row) {
746 if ($from_col > $to_col) {
747 ($to_col, $from_col) = ($from_col, $to_col);
750 for my $c (($from_col+1)..($to_col-1)) {
751 my $middle_piece = substr($board->[$to_row], $c, 1);
752 return 0 if ($middle_piece ne '-');
757 if ($from_row > $to_row) {
758 ($to_row, $from_row) = ($from_row, $to_row);
761 for my $r (($from_row+1)..($to_row-1)) {
762 my $middle_piece = substr($board->[$r], $to_col, 1);
763 return 0 if ($middle_piece ne '-');
769 if (lc($piece) eq 'b') {
770 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
772 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
773 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
775 my $r = $from_row + $dr;
776 my $c = $from_col + $dc;
778 while ($r != $to_row) {
779 my $middle_piece = substr($board->[$r], $c, 1);
780 return 0 if ($middle_piece ne '-');
788 if (lc($piece) eq 'n') {
789 my $diff_r = abs($from_row - $to_row);
790 my $diff_c = abs($from_col - $to_col);
791 return 1 if ($diff_r == 2 && $diff_c == 1);
792 return 1 if ($diff_r == 1 && $diff_c == 2);
796 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
797 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
800 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
801 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
805 if ($to_col == $from_col && $to_row == $from_row + 1) {
806 return ($dest_piece eq '-');
808 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
809 return ($dest_piece ne '-');
815 if ($to_col == $from_col && $to_row == $from_row - 1) {
816 return ($dest_piece eq '-');
818 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
819 return ($dest_piece ne '-');
830 print UCIWRITE "$msg\n";
831 print UCILOG "=> $msg\n";
835 my ($uciinfo, $ficsinfo, $mpv) = @_;
837 if (defined($uciinfo{'score_mate' . $mpv})) {
838 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
840 if (exists($uciinfo{'score_cp' . $mpv})) {
841 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
842 if ($ficsinfo{'toplay'} eq 'B') {
845 return sprintf "%+5.2f", $score;
853 my ($uciinfo, $ficsinfo, $mpv) = @_;
855 if (defined($uciinfo{'score_mate' . $mpv})) {
856 my $mate = $uciinfo{'score_mate' . $mpv};
857 if ($ficsinfo{'toplay'} eq 'B') {
861 return sprintf "White mates in %u", $mate;
863 return sprintf "Black mates in %u", -$mate;
866 if (exists($uciinfo{'score_cp' . $mpv})) {
867 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
868 if ($ficsinfo{'toplay'} eq 'B') {
871 return sprintf "Score: %+5.2f", $score;