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);
49 my ($last_move, $last_tell);
51 my $last_told_text = '';
52 my ($pos_waiting, $pos_calculating);
62 uciprint("setoption name UCI_AnalyseMode value true");
63 # uciprint("setoption name Preserve Analysis value true");
64 uciprint("setoption name NalimovPath value c:\\nalimov");
65 uciprint("setoption name NalimovUsage value Rarely");
66 uciprint("setoption name Hash value 1024");
67 uciprint("setoption name MultiPV value 3");
68 # uciprint("setoption name Contempt value 1000");
69 # uciprint("setoption name Outlook value Ultra Optimistic");
70 uciprint("ucinewgame");
72 print "Chess engine ready.\n";
75 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
76 $t->input_log(\*FICSLOG);
79 $t->waitfor('/Press return to enter the server/');
83 $t->cmd("set shout 0");
84 $t->cmd("set seek 0");
85 $t->cmd("set style 12");
86 $t->cmd("observe $target");
89 print "FICS ready.\n";
93 vec($rin, fileno(UCIREAD), 1) = 1;
94 vec($rin, fileno($t), 1) = 1;
96 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
100 my $line = $t->getline(Timeout => 0, errmode => 'return');
101 last if (!defined($line));
105 if ($line =~ /^<12> /) {
106 my $pos = style12_to_fen($line);
108 # if this is already in the queue, ignore it
109 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
111 # if we're already chewing on this and there's nothing else in the queue,
113 next if (!defined($pos_waiting) && defined($pos_calculating) &&
114 $pos->{'fen'} eq $pos_calculating->{'fen'});
116 # if we're already thinking on something, stop and wait for the engine
118 if (defined($pos_calculating)) {
119 if (!defined($pos_waiting)) {
124 # it's wrong just to give the FEN (the move history is useful,
125 # and per the UCI spec, we should really have sent "ucinewgame"),
127 uciprint("position fen " . $pos->{'fen'});
128 uciprint("go infinite");
129 $pos_calculating = $pos;
136 # Output a command every move to note that we're
137 # still paying attention -- this is a good tradeoff,
138 # since if no move has happened in the last half
139 # hour, the analysis/relay has most likely stopped
140 # and we should stop hogging server resources.
144 #print "FICS: [$line]\n";
148 # any fun on the UCI channel?
149 if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
150 my $line = <UCIREAD>;
154 # don't update too often
155 Time::HiRes::alarm(0.2);
166 print UCILOG localtime() . " <= $line\n";
167 if ($line =~ /^info/) {
168 my (@infos) = split / /, $line;
173 if ($line =~ /^id/) {
174 my (@ids) = split / /, $line;
179 if ($line =~ /^bestmove/) {
180 if (defined($pos_waiting)) {
181 uciprint("position fen " . $pos_waiting->{'fen'});
182 uciprint("go infinite");
184 $pos_calculating = $pos_waiting;
185 $pos_waiting = undef;
194 while (scalar @x > 0) {
195 if ($x[0] =~ 'multipv') {
200 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
202 my $value = shift @x;
203 $uciinfo{$key} = $value;
206 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
208 my $value = shift @x;
209 $uciinfo{$key . $mpv} = $value;
212 if ($x[0] eq 'score') {
215 delete $uciinfo{'score_cp' . $mpv};
216 delete $uciinfo{'score_mate' . $mpv};
218 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
221 $uciinfo{'score_cp' . $mpv} = shift @x;
222 } elsif ($x[0] eq 'mate') {
224 $uciinfo{'score_mate' . $mpv} = shift @x;
232 $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
235 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
239 #print "unknown info '$x[0]', trying to recover...\n";
241 die "Unknown info '" . join(',', @x) . "'";
249 while (scalar @x > 0) {
250 if ($x[0] =~ /^(name|author)$/) {
252 my $value = join(' ', @x);
253 $uciid{$key} = $value;
265 my (@x) = split / /, $str;
267 $pos{'board'} = [ @x[1..8] ];
268 $pos{'toplay'} = $x[9];
271 my (@board) = @x[1..8];
272 for my $rank (0..7) {
273 $board[$rank] =~ s/(-+)/length($1)/ge;
275 my $fen = join('/', @board);
277 # white/black to move
283 $castling .= "K" if ($x[11] == 1);
284 $castling .= "Q" if ($x[12] == 1);
285 $castling .= "k" if ($x[13] == 1);
286 $castling .= "q" if ($x[14] == 1);
287 $castling = "-" if ($castling eq "");
295 my $nep = (qw(a b c d e f g h))[$col];
304 # Showing the en passant square when actually no capture can be made
305 # seems to confuse at least Rybka. Thus, check if there's actually
306 # a pawn of the opposite side that can do the en passant move, and if
307 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
308 # "right" thing as per the standard, though.
311 $ep = $nep if ($col > 0 && substr($pos{'board'}[4], $col-1, 1) eq 'p');
312 $ep = $nep if ($col < 7 && substr($pos{'board'}[4], $col+1, 1) eq 'p');
314 $ep = $nep if ($col > 0 && substr($pos{'board'}[3], $col-1, 1) eq 'P');
315 $ep = $nep if ($col < 7 && substr($pos{'board'}[3], $col+1, 1) eq 'P');
335 my ($board, @pvs) = @_;
337 if (scalar @pvs == 0 || !defined($pvs[0])) {
344 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
345 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
346 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
347 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
350 my $piece = substr($board->[$from_row], $from_col, 1);
356 # white short castling
357 if ($pv eq 'e1g1' && $piece eq 'K') {
359 substr($nb[7], 4, 1, '-');
360 substr($nb[7], 6, 1, $piece);
363 substr($nb[7], 7, 1, '-');
364 substr($nb[7], 5, 1, 'R');
366 return ('0-0', prettyprint_pv(\@nb, @pvs));
369 # white long castling
370 if ($pv eq 'e1c1' && $piece eq 'K') {
372 substr($nb[7], 4, 1, '-');
373 substr($nb[7], 2, 1, $piece);
376 substr($nb[7], 0, 1, '-');
377 substr($nb[7], 3, 1, 'R');
379 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
382 # black short castling
383 if ($pv eq 'e8g8' && $piece eq 'k') {
385 substr($nb[0], 4, 1, '-');
386 substr($nb[0], 6, 1, $piece);
389 substr($nb[0], 7, 1, '-');
390 substr($nb[0], 5, 1, 'r');
392 return ('0-0', prettyprint_pv(\@nb, @pvs));
395 # black long castling
396 if ($pv eq 'e8c8' && $piece eq 'k') {
398 substr($nb[0], 4, 1, '-');
399 substr($nb[0], 2, 1, $piece);
402 substr($nb[0], 0, 1, '-');
403 substr($nb[0], 3, 1, 'r');
405 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
408 # check if the from-piece is a pawn
409 if (lc($piece) eq 'p') {
411 if ($from_col != $to_col) {
412 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
415 if (substr($board->[$to_row], $to_col, 1) eq '-') {
417 substr($nb[$to_row + 1], $to_col, 1, '-');
419 substr($nb[$to_row - 1], $to_col, 1, '-');
423 $pretty = substr($pv, 2, 2);
425 if (length($pv) == 5) {
428 $pretty .= uc(substr($pv, 4, 1));
431 $piece = substr($pv, 4, 1);
433 $piece = uc(substr($pv, 4, 1));
438 $pretty = uc($piece);
440 # see how many of these pieces could go here, in all
444 next unless (substr($board->[$row], $col, 1) eq $piece);
445 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
449 # see how many of these pieces from the given row could go here
452 next unless (substr($board->[$from_row], $col, 1) eq $piece);
453 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
456 # and same for columns
459 next unless (substr($board->[$row], $from_col, 1) eq $piece);
460 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
463 # see if we need to disambiguate
464 if ($num_total > 1) {
466 $pretty .= substr($pv, 0, 1);
467 } elsif ($num_row == 1) {
468 $pretty .= substr($pv, 1, 1);
470 $pretty .= substr($pv, 0, 2);
475 if (substr($board->[$to_row], $to_col, 1) ne '-') {
479 $pretty .= substr($pv, 2, 2);
483 substr($nb[$from_row], $from_col, 1, '-');
484 substr($nb[$to_row], $to_col, 1, $piece);
488 } elsif (in_check(\@nb) ne 'none') {
492 return ($pretty, prettyprint_pv(\@nb, @pvs));
498 return if (!defined($pos_calculating));
501 # Check the PVs first. if they're invalid, just wait, as our data
502 # is most likely out of sync. This isn't a very good solution, as
503 # it can frequently miss stuff, but it's good enough for most users.
507 if (exists($uciinfo{'pv'})) {
508 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
512 while (exists($uciinfo{'pv' . $mpv})) {
513 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
524 if (exists($uciid{'name'})) {
525 $text .= "Analysis by $uciid{'name'}:\n\n";
527 $text .= "Analysis:\n\n";
530 return unless (exists($pos_calculating->{'board'}));
533 # Some programs _always_ report MultiPV, even with only one PV.
534 # In this case, we simply use that data as if MultiPV was never
537 if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
538 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
539 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
540 $uciinfo{$key} = $uciinfo{$key . '1'};
545 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
548 while (exists($uciinfo{'pv' . $mpv})) {
549 $text .= sprintf " PV%2u", $mpv;
550 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
551 $text .= " ($score)" if (defined($score));
554 if (exists($uciinfo{'tbhits' . $mpv})) {
555 $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
558 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
559 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
560 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
564 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
570 my $score = long_score(\%uciinfo, $pos_calculating, '');
571 $text .= " $score\n" if defined($score);
572 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
575 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
576 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
577 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
579 if (exists($uciinfo{'tbhits'})) {
580 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
582 if (exists($uciinfo{'seldepth'})) {
583 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
588 if ($last_text ne $text) {
589 print "
\e[H
\e[2J"; # clear the screen
594 # Now construct the tell text, if any
595 return if (!defined($telltarget));
599 if (exists($uciid{'name'})) {
600 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
602 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
605 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
608 while (exists($uciinfo{'pv' . $mpv})) {
609 $tell_text .= sprintf " PV%2u", $mpv;
610 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
611 $tell_text .= " ($score)" if (defined($score));
613 if (exists($uciinfo{'depth' . $mpv})) {
614 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
618 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
624 my $score = long_score(\%uciinfo, $pos_calculating, '');
625 $tell_text .= " $score\n" if defined($score);
626 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
627 if (exists($uciinfo{'depth'})) {
628 $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
633 # see if a new tell is called for -- it is if the delay has expired _and_
634 # this is not simply a repetition of the last one
635 if ($last_told_text ne $tell_text) {
637 for my $iv (@tell_intervals) {
638 last if ($now - $last_move < $iv);
639 next if ($last_tell - $last_move >= $iv);
641 for my $line (split /\n/, $tell_text) {
642 $t->print("tell $telltarget [$target] $line");
645 $last_told_text = $text;
655 my ($wkr, $wkc, $bkr, $bkc);
659 my $piece = substr($board->[$row], $col, 1);
661 ($wkr, $wkc) = ($row, $col);
662 } elsif ($piece eq 'k') {
663 ($bkr, $bkc) = ($row, $col);
668 return ($wkr, $wkc, $bkr, $bkc);
673 my $check = in_check($board);
674 return 0 if ($check eq 'none');
676 # try all possible moves for the side in check
679 my $piece = substr($board->[$row], $col, 1);
680 next if ($piece eq '-');
682 if ($check eq 'white') {
683 next if ($piece eq lc($piece));
685 next if ($piece eq uc($piece));
688 for my $dest_row (0..7) {
689 for my $dest_col (0..7) {
690 next if ($row == $dest_row && $col == $dest_col);
691 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
694 substr($nb[$row], $col, 1, '-');
695 substr($nb[$dest_row], $dest_col, 1, $piece);
697 my $new_check = in_check(\@nb);
698 return 0 if ($new_check ne $check && $new_check ne 'both');
704 # nothing to do; mate
710 my ($black_check, $white_check) = (0, 0);
712 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
714 # check all pieces for the possibility of threatening the two kings
717 my $piece = substr($board->[$row], $col, 1);
718 next if ($piece eq '-');
720 if (uc($piece) eq $piece) {
722 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
725 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
730 if ($black_check && $white_check) {
732 } elsif ($black_check) {
734 } elsif ($white_check) {
742 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
744 # can't eat your own piece
745 my $dest_piece = substr($board->[$to_row], $to_col, 1);
746 if ($dest_piece ne '-') {
747 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
750 if (lc($piece) eq 'k') {
751 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
753 if (lc($piece) eq 'r') {
754 return 0 unless ($from_row == $to_row || $from_col == $to_col);
756 # check that there's a clear passage
757 if ($from_row == $to_row) {
758 if ($from_col > $to_col) {
759 ($to_col, $from_col) = ($from_col, $to_col);
762 for my $c (($from_col+1)..($to_col-1)) {
763 my $middle_piece = substr($board->[$to_row], $c, 1);
764 return 0 if ($middle_piece ne '-');
769 if ($from_row > $to_row) {
770 ($to_row, $from_row) = ($from_row, $to_row);
773 for my $r (($from_row+1)..($to_row-1)) {
774 my $middle_piece = substr($board->[$r], $to_col, 1);
775 return 0 if ($middle_piece ne '-');
781 if (lc($piece) eq 'b') {
782 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
784 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
785 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
787 my $r = $from_row + $dr;
788 my $c = $from_col + $dc;
790 while ($r != $to_row) {
791 my $middle_piece = substr($board->[$r], $c, 1);
792 return 0 if ($middle_piece ne '-');
800 if (lc($piece) eq 'n') {
801 my $diff_r = abs($from_row - $to_row);
802 my $diff_c = abs($from_col - $to_col);
803 return 1 if ($diff_r == 2 && $diff_c == 1);
804 return 1 if ($diff_r == 1 && $diff_c == 2);
808 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
809 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
812 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
813 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
817 if ($to_col == $from_col && $to_row == $from_row + 1) {
818 return ($dest_piece eq '-');
820 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
821 return ($dest_piece ne '-');
827 if ($to_col == $from_col && $to_row == $from_row - 1) {
828 return ($dest_piece eq '-');
830 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
831 return ($dest_piece ne '-');
842 print UCIWRITE "$msg\n";
843 print UCILOG localtime() . " => $msg\n";
847 my ($uciinfo, $pos, $mpv) = @_;
849 if (defined($uciinfo{'score_mate' . $mpv})) {
850 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
852 if (exists($uciinfo{'score_cp' . $mpv})) {
853 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
854 if ($pos->{'toplay'} eq 'B') {
857 return sprintf "%+5.2f", $score;
865 my ($uciinfo, $pos, $mpv) = @_;
867 if (defined($uciinfo{'score_mate' . $mpv})) {
868 my $mate = $uciinfo{'score_mate' . $mpv};
869 if ($pos->{'toplay'} eq 'B') {
873 return sprintf "White mates in %u", $mate;
875 return sprintf "Black mates in %u", -$mate;
878 if (exists($uciinfo{'score_cp' . $mpv})) {
879 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
880 if ($pos->{'toplay'} eq 'B') {
883 return sprintf "Score: %+5.2f", $score;