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 = 0; # 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) {
157 my $line = <UCIREAD>;
161 # don't update too often
162 Time::HiRes::alarm(0.2);
173 print UCILOG localtime() . " <= $line\n";
174 if ($line =~ /^info/) {
175 my (@infos) = split / /, $line;
180 if ($line =~ /^id/) {
181 my (@ids) = split / /, $line;
186 if ($line =~ /^bestmove/ && $uci_assume_full_compliance) {
187 if (defined($pos_waiting)) {
188 uciprint("position fen " . $pos_waiting->{'fen'});
189 uciprint("go infinite");
191 $pos_calculating = $pos_waiting;
192 $pos_waiting = undef;
201 while (scalar @x > 0) {
202 if ($x[0] =~ 'multipv') {
207 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
209 my $value = shift @x;
210 $uciinfo{$key} = $value;
213 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
215 my $value = shift @x;
216 $uciinfo{$key . $mpv} = $value;
219 if ($x[0] eq 'score') {
222 delete $uciinfo{'score_cp' . $mpv};
223 delete $uciinfo{'score_mate' . $mpv};
225 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
228 $uciinfo{'score_cp' . $mpv} = shift @x;
229 } elsif ($x[0] eq 'mate') {
231 $uciinfo{'score_mate' . $mpv} = shift @x;
239 $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
242 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
246 #print "unknown info '$x[0]', trying to recover...\n";
248 die "Unknown info '" . join(',', @x) . "'";
256 while (scalar @x > 0) {
257 if ($x[0] =~ /^(name|author)$/) {
259 my $value = join(' ', @x);
260 $uciid{$key} = $value;
272 my (@x) = split / /, $str;
274 $pos{'board'} = [ @x[1..8] ];
275 $pos{'toplay'} = $x[9];
278 my (@board) = @x[1..8];
279 for my $rank (0..7) {
280 $board[$rank] =~ s/(-+)/length($1)/ge;
282 my $fen = join('/', @board);
284 # white/black to move
290 $castling .= "K" if ($x[11] == 1);
291 $castling .= "Q" if ($x[12] == 1);
292 $castling .= "k" if ($x[13] == 1);
293 $castling .= "q" if ($x[14] == 1);
294 $castling = "-" if ($castling eq "");
302 my $nep = (qw(a b c d e f g h))[$col];
311 # Showing the en passant square when actually no capture can be made
312 # seems to confuse at least Rybka. Thus, check if there's actually
313 # a pawn of the opposite side that can do the en passant move, and if
314 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
315 # "right" thing as per the standard, though.
318 $ep = $nep if ($col > 0 && substr($pos{'board'}[4], $col-1, 1) eq 'p');
319 $ep = $nep if ($col < 7 && substr($pos{'board'}[4], $col+1, 1) eq 'p');
321 $ep = $nep if ($col > 0 && substr($pos{'board'}[3], $col-1, 1) eq 'P');
322 $ep = $nep if ($col < 7 && substr($pos{'board'}[3], $col+1, 1) eq 'P');
342 my ($board, @pvs) = @_;
344 if (scalar @pvs == 0 || !defined($pvs[0])) {
351 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
352 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
353 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
354 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
357 my $piece = substr($board->[$from_row], $from_col, 1);
363 # white short castling
364 if ($pv eq 'e1g1' && $piece eq 'K') {
366 substr($nb[7], 4, 1, '-');
367 substr($nb[7], 6, 1, $piece);
370 substr($nb[7], 7, 1, '-');
371 substr($nb[7], 5, 1, 'R');
373 return ('0-0', prettyprint_pv(\@nb, @pvs));
376 # white long castling
377 if ($pv eq 'e1c1' && $piece eq 'K') {
379 substr($nb[7], 4, 1, '-');
380 substr($nb[7], 2, 1, $piece);
383 substr($nb[7], 0, 1, '-');
384 substr($nb[7], 3, 1, 'R');
386 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
389 # black short castling
390 if ($pv eq 'e8g8' && $piece eq 'k') {
392 substr($nb[0], 4, 1, '-');
393 substr($nb[0], 6, 1, $piece);
396 substr($nb[0], 7, 1, '-');
397 substr($nb[0], 5, 1, 'r');
399 return ('0-0', prettyprint_pv(\@nb, @pvs));
402 # black long castling
403 if ($pv eq 'e8c8' && $piece eq 'k') {
405 substr($nb[0], 4, 1, '-');
406 substr($nb[0], 2, 1, $piece);
409 substr($nb[0], 0, 1, '-');
410 substr($nb[0], 3, 1, 'r');
412 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
415 # check if the from-piece is a pawn
416 if (lc($piece) eq 'p') {
418 if ($from_col != $to_col) {
419 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
422 if (substr($board->[$to_row], $to_col, 1) eq '-') {
424 substr($nb[$to_row + 1], $to_col, 1, '-');
426 substr($nb[$to_row - 1], $to_col, 1, '-');
430 $pretty = substr($pv, 2, 2);
432 if (length($pv) == 5) {
435 $pretty .= uc(substr($pv, 4, 1));
438 $piece = substr($pv, 4, 1);
440 $piece = uc(substr($pv, 4, 1));
445 $pretty = uc($piece);
447 # see how many of these pieces could go here, in all
451 next unless (substr($board->[$row], $col, 1) eq $piece);
452 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
456 # see how many of these pieces from the given row could go here
459 next unless (substr($board->[$from_row], $col, 1) eq $piece);
460 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
463 # and same for columns
466 next unless (substr($board->[$row], $from_col, 1) eq $piece);
467 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
470 # see if we need to disambiguate
471 if ($num_total > 1) {
473 $pretty .= substr($pv, 0, 1);
474 } elsif ($num_row == 1) {
475 $pretty .= substr($pv, 1, 1);
477 $pretty .= substr($pv, 0, 2);
482 if (substr($board->[$to_row], $to_col, 1) ne '-') {
486 $pretty .= substr($pv, 2, 2);
490 substr($nb[$from_row], $from_col, 1, '-');
491 substr($nb[$to_row], $to_col, 1, $piece);
495 } elsif (in_check(\@nb) ne 'none') {
499 return ($pretty, prettyprint_pv(\@nb, @pvs));
505 return if (!defined($pos_calculating));
508 # Check the PVs first. if they're invalid, just wait, as our data
509 # is most likely out of sync. This isn't a very good solution, as
510 # it can frequently miss stuff, but it's good enough for most users.
514 if (exists($uciinfo{'pv'})) {
515 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
519 while (exists($uciinfo{'pv' . $mpv})) {
520 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
531 if (exists($uciid{'name'})) {
532 $text .= "Analysis by $uciid{'name'}:\n\n";
534 $text .= "Analysis:\n\n";
537 return unless (exists($pos_calculating->{'board'}));
540 # Some programs _always_ report MultiPV, even with only one PV.
541 # In this case, we simply use that data as if MultiPV was never
544 if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
545 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
546 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
547 $uciinfo{$key} = $uciinfo{$key . '1'};
552 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
555 while (exists($uciinfo{'pv' . $mpv})) {
556 $text .= sprintf " PV%2u", $mpv;
557 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
558 $text .= " ($score)" if (defined($score));
561 if (exists($uciinfo{'tbhits' . $mpv})) {
562 $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
565 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
566 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
567 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
571 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
577 my $score = long_score(\%uciinfo, $pos_calculating, '');
578 $text .= " $score\n" if defined($score);
579 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
582 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
583 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
584 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
586 if (exists($uciinfo{'tbhits'})) {
587 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
589 if (exists($uciinfo{'seldepth'})) {
590 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
595 if ($last_text ne $text) {
596 print "
\e[H
\e[2J"; # clear the screen
601 # Now construct the tell text, if any
602 return if (!defined($telltarget));
606 if (exists($uciid{'name'})) {
607 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
609 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
612 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
615 while (exists($uciinfo{'pv' . $mpv})) {
616 $tell_text .= sprintf " PV%2u", $mpv;
617 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
618 $tell_text .= " ($score)" if (defined($score));
620 if (exists($uciinfo{'depth' . $mpv})) {
621 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
625 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
631 my $score = long_score(\%uciinfo, $pos_calculating, '');
632 $tell_text .= " $score\n" if defined($score);
633 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
634 if (exists($uciinfo{'depth'})) {
635 $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
640 # see if a new tell is called for -- it is if the delay has expired _and_
641 # this is not simply a repetition of the last one
642 if ($last_told_text ne $tell_text) {
644 for my $iv (@tell_intervals) {
645 last if ($now - $last_move < $iv);
646 next if ($last_tell - $last_move >= $iv);
648 for my $line (split /\n/, $tell_text) {
649 $t->print("tell $telltarget [$target] $line");
652 $last_told_text = $text;
662 my ($wkr, $wkc, $bkr, $bkc);
666 my $piece = substr($board->[$row], $col, 1);
668 ($wkr, $wkc) = ($row, $col);
669 } elsif ($piece eq 'k') {
670 ($bkr, $bkc) = ($row, $col);
675 return ($wkr, $wkc, $bkr, $bkc);
680 my $check = in_check($board);
681 return 0 if ($check eq 'none');
683 # try all possible moves for the side in check
686 my $piece = substr($board->[$row], $col, 1);
687 next if ($piece eq '-');
689 if ($check eq 'white') {
690 next if ($piece eq lc($piece));
692 next if ($piece eq uc($piece));
695 for my $dest_row (0..7) {
696 for my $dest_col (0..7) {
697 next if ($row == $dest_row && $col == $dest_col);
698 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
701 substr($nb[$row], $col, 1, '-');
702 substr($nb[$dest_row], $dest_col, 1, $piece);
704 my $new_check = in_check(\@nb);
705 return 0 if ($new_check ne $check && $new_check ne 'both');
711 # nothing to do; mate
717 my ($black_check, $white_check) = (0, 0);
719 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
721 # check all pieces for the possibility of threatening the two kings
724 my $piece = substr($board->[$row], $col, 1);
725 next if ($piece eq '-');
727 if (uc($piece) eq $piece) {
729 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
732 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
737 if ($black_check && $white_check) {
739 } elsif ($black_check) {
741 } elsif ($white_check) {
749 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
751 # can't eat your own piece
752 my $dest_piece = substr($board->[$to_row], $to_col, 1);
753 if ($dest_piece ne '-') {
754 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
757 if (lc($piece) eq 'k') {
758 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
760 if (lc($piece) eq 'r') {
761 return 0 unless ($from_row == $to_row || $from_col == $to_col);
763 # check that there's a clear passage
764 if ($from_row == $to_row) {
765 if ($from_col > $to_col) {
766 ($to_col, $from_col) = ($from_col, $to_col);
769 for my $c (($from_col+1)..($to_col-1)) {
770 my $middle_piece = substr($board->[$to_row], $c, 1);
771 return 0 if ($middle_piece ne '-');
776 if ($from_row > $to_row) {
777 ($to_row, $from_row) = ($from_row, $to_row);
780 for my $r (($from_row+1)..($to_row-1)) {
781 my $middle_piece = substr($board->[$r], $to_col, 1);
782 return 0 if ($middle_piece ne '-');
788 if (lc($piece) eq 'b') {
789 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
791 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
792 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
794 my $r = $from_row + $dr;
795 my $c = $from_col + $dc;
797 while ($r != $to_row) {
798 my $middle_piece = substr($board->[$r], $c, 1);
799 return 0 if ($middle_piece ne '-');
807 if (lc($piece) eq 'n') {
808 my $diff_r = abs($from_row - $to_row);
809 my $diff_c = abs($from_col - $to_col);
810 return 1 if ($diff_r == 2 && $diff_c == 1);
811 return 1 if ($diff_r == 1 && $diff_c == 2);
815 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
816 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
819 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
820 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
824 if ($to_col == $from_col && $to_row == $from_row + 1) {
825 return ($dest_piece eq '-');
827 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
828 return ($dest_piece ne '-');
834 if ($to_col == $from_col && $to_row == $from_row - 1) {
835 return ($dest_piece eq '-');
837 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
838 return ($dest_piece ne '-');
849 print UCIWRITE "$msg\n";
850 print UCILOG localtime() . " => $msg\n";
854 my ($uciinfo, $pos, $mpv) = @_;
856 if (defined($uciinfo{'score_mate' . $mpv})) {
857 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
859 if (exists($uciinfo{'score_cp' . $mpv})) {
860 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
861 if ($pos->{'toplay'} eq 'B') {
864 return sprintf "%+5.2f", $score;
872 my ($uciinfo, $pos, $mpv) = @_;
874 if (defined($uciinfo{'score_mate' . $mpv})) {
875 my $mate = $uciinfo{'score_mate' . $mpv};
876 if ($pos->{'toplay'} eq 'B') {
880 return sprintf "White mates in %u", $mate;
882 return sprintf "Black mates in %u", -$mate;
885 if (exists($uciinfo{'score_cp' . $mpv})) {
886 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
887 if ($pos->{'toplay'} eq 'B') {
890 return sprintf "Score: %+5.2f", $score;