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)) {
122 # it's wrong just to give the FEN (the move history is useful,
123 # and per the UCI spec, we should really have sent "ucinewgame"),
125 uciprint("position fen " . $pos->{'fen'});
126 uciprint("go infinite");
127 $pos_calculating = $pos;
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($pos_waiting)) {
179 uciprint("position fen " . $pos_waiting->{'fen'});
180 uciprint("go infinite");
182 $pos_calculating = $pos_waiting;
183 $pos_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;
263 my (@x) = split / /, $str;
265 $pos{'board'} = [ @x[1..8] ];
266 $pos{'toplay'} = $x[9];
269 my (@board) = @x[1..8];
270 for my $rank (0..7) {
271 $board[$rank] =~ s/(-+)/length($1)/ge;
273 my $fen = join('/', @board);
275 # white/black to move
281 $castling .= "K" if ($x[11] == 1);
282 $castling .= "Q" if ($x[12] == 1);
283 $castling .= "k" if ($x[13] == 1);
284 $castling .= "q" if ($x[14] == 1);
285 $castling = "-" if ($castling eq "");
293 my $nep = (qw(a b c d e f g h))[$col];
302 # Showing the en passant square when actually no capture can be made
303 # seems to confuse at least Rybka. Thus, check if there's actually
304 # a pawn of the opposite side that can do the en passant move, and if
305 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
306 # "right" thing as per the standard, though.
309 $ep = $nep if ($col > 0 && substr($pos{'board'}[4], $col-1, 1) eq 'p');
310 $ep = $nep if ($col < 7 && substr($pos{'board'}[4], $col+1, 1) eq 'p');
312 $ep = $nep if ($col > 0 && substr($pos{'board'}[3], $col-1, 1) eq 'P');
313 $ep = $nep if ($col < 7 && substr($pos{'board'}[3], $col+1, 1) eq 'P');
333 my ($board, @pvs) = @_;
335 if (scalar @pvs == 0 || !defined($pvs[0])) {
342 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
343 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
344 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
345 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
348 my $piece = substr($board->[$from_row], $from_col, 1);
354 # white short castling
355 if ($pv eq 'e1g1' && $piece eq 'K') {
357 substr($nb[7], 4, 1, '-');
358 substr($nb[7], 6, 1, $piece);
361 substr($nb[7], 7, 1, '-');
362 substr($nb[7], 5, 1, 'R');
364 return ('0-0', prettyprint_pv(\@nb, @pvs));
367 # white long castling
368 if ($pv eq 'e1c1' && $piece eq 'K') {
370 substr($nb[7], 4, 1, '-');
371 substr($nb[7], 2, 1, $piece);
374 substr($nb[7], 0, 1, '-');
375 substr($nb[7], 3, 1, 'R');
377 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
380 # black short castling
381 if ($pv eq 'e8g8' && $piece eq 'k') {
383 substr($nb[0], 4, 1, '-');
384 substr($nb[0], 6, 1, $piece);
387 substr($nb[0], 7, 1, '-');
388 substr($nb[0], 5, 1, 'r');
390 return ('0-0', prettyprint_pv(\@nb, @pvs));
393 # black long castling
394 if ($pv eq 'e8c8' && $piece eq 'k') {
396 substr($nb[0], 4, 1, '-');
397 substr($nb[0], 2, 1, $piece);
400 substr($nb[0], 0, 1, '-');
401 substr($nb[0], 3, 1, 'r');
403 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
406 # check if the from-piece is a pawn
407 if (lc($piece) eq 'p') {
409 if ($from_col != $to_col) {
410 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
413 if (substr($board->[$to_row], $to_col, 1) eq '-') {
415 substr($nb[$to_row + 1], $to_col, 1, '-');
417 substr($nb[$to_row - 1], $to_col, 1, '-');
421 $pretty = substr($pv, 2, 2);
423 if (length($pv) == 5) {
426 $pretty .= uc(substr($pv, 4, 1));
429 $piece = substr($pv, 4, 1);
431 $piece = uc(substr($pv, 4, 1));
436 $pretty = uc($piece);
438 # see how many of these pieces could go here, in all
442 next unless (substr($board->[$row], $col, 1) eq $piece);
443 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
447 # see how many of these pieces from the given row could go here
450 next unless (substr($board->[$from_row], $col, 1) eq $piece);
451 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
454 # and same for columns
457 next unless (substr($board->[$row], $from_col, 1) eq $piece);
458 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
461 # see if we need to disambiguate
462 if ($num_total > 1) {
464 $pretty .= substr($pv, 0, 1);
465 } elsif ($num_row == 1) {
466 $pretty .= substr($pv, 1, 1);
468 $pretty .= substr($pv, 0, 2);
473 if (substr($board->[$to_row], $to_col, 1) ne '-') {
477 $pretty .= substr($pv, 2, 2);
481 substr($nb[$from_row], $from_col, 1, '-');
482 substr($nb[$to_row], $to_col, 1, $piece);
486 } elsif (in_check(\@nb) ne 'none') {
490 return ($pretty, prettyprint_pv(\@nb, @pvs));
496 return if (!defined($pos_calculating));
499 # Check the PVs first. if they're invalid, just wait, as our data
500 # is most likely out of sync. This isn't a very good solution, as
501 # it can frequently miss stuff, but it's good enough for most users.
505 if (exists($uciinfo{'pv'})) {
506 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
510 while (exists($uciinfo{'pv' . $mpv})) {
511 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
522 if (exists($uciid{'name'})) {
523 $text .= "Analysis by $uciid{'name'}:\n\n";
525 $text .= "Analysis:\n\n";
528 return unless (exists($pos_calculating->{'board'}));
531 # Some programs _always_ report MultiPV, even with only one PV.
532 # In this case, we simply use that data as if MultiPV was never
535 if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
536 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
537 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
538 $uciinfo{$key} = $uciinfo{$key . '1'};
543 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
546 while (exists($uciinfo{'pv' . $mpv})) {
547 $text .= sprintf " PV%2u", $mpv;
548 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
549 $text .= " ($score)" if (defined($score));
552 if (exists($uciinfo{'tbhits' . $mpv})) {
553 $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
556 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
557 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
558 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
562 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
568 my $score = long_score(\%uciinfo, $pos_calculating, '');
569 $text .= " $score\n" if defined($score);
570 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
573 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
574 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
575 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
577 if (exists($uciinfo{'tbhits'})) {
578 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
580 if (exists($uciinfo{'seldepth'})) {
581 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
586 if ($last_text ne $text) {
587 print "
\e[H
\e[2J"; # clear the screen
592 # Now construct the tell text, if any
593 return if (!defined($telltarget));
597 if (exists($uciid{'name'})) {
598 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
600 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
603 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
606 while (exists($uciinfo{'pv' . $mpv})) {
607 $tell_text .= sprintf " PV%2u", $mpv;
608 my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
609 $tell_text .= " ($score)" if (defined($score));
611 if (exists($uciinfo{'depth' . $mpv})) {
612 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
616 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
622 my $score = long_score(\%uciinfo, $pos_calculating, '');
623 $tell_text .= " $score\n" if defined($score);
624 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
625 if (exists($uciinfo{'depth'})) {
626 $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
631 # see if a new tell is called for -- it is if the delay has expired _and_
632 # this is not simply a repetition of the last one
633 if ($last_told_text ne $tell_text) {
635 for my $iv (@tell_intervals) {
636 last if ($now - $last_move < $iv);
637 next if ($last_tell - $last_move >= $iv);
639 for my $line (split /\n/, $tell_text) {
640 $t->print("tell $telltarget [$target] $line");
643 $last_told_text = $text;
653 my ($wkr, $wkc, $bkr, $bkc);
657 my $piece = substr($board->[$row], $col, 1);
659 ($wkr, $wkc) = ($row, $col);
660 } elsif ($piece eq 'k') {
661 ($bkr, $bkc) = ($row, $col);
666 return ($wkr, $wkc, $bkr, $bkc);
671 my $check = in_check($board);
672 return 0 if ($check eq 'none');
674 # try all possible moves for the side in check
677 my $piece = substr($board->[$row], $col, 1);
678 next if ($piece eq '-');
680 if ($check eq 'white') {
681 next if ($piece eq lc($piece));
683 next if ($piece eq uc($piece));
686 for my $dest_row (0..7) {
687 for my $dest_col (0..7) {
688 next if ($row == $dest_row && $col == $dest_col);
689 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
692 substr($nb[$row], $col, 1, '-');
693 substr($nb[$dest_row], $dest_col, 1, $piece);
695 my $new_check = in_check(\@nb);
696 return 0 if ($new_check ne $check && $new_check ne 'both');
702 # nothing to do; mate
708 my ($black_check, $white_check) = (0, 0);
710 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
712 # check all pieces for the possibility of threatening the two kings
715 my $piece = substr($board->[$row], $col, 1);
716 next if ($piece eq '-');
718 if (uc($piece) eq $piece) {
720 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
723 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
728 if ($black_check && $white_check) {
730 } elsif ($black_check) {
732 } elsif ($white_check) {
740 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
742 # can't eat your own piece
743 my $dest_piece = substr($board->[$to_row], $to_col, 1);
744 if ($dest_piece ne '-') {
745 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
748 if (lc($piece) eq 'k') {
749 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
751 if (lc($piece) eq 'r') {
752 return 0 unless ($from_row == $to_row || $from_col == $to_col);
754 # check that there's a clear passage
755 if ($from_row == $to_row) {
756 if ($from_col > $to_col) {
757 ($to_col, $from_col) = ($from_col, $to_col);
760 for my $c (($from_col+1)..($to_col-1)) {
761 my $middle_piece = substr($board->[$to_row], $c, 1);
762 return 0 if ($middle_piece ne '-');
767 if ($from_row > $to_row) {
768 ($to_row, $from_row) = ($from_row, $to_row);
771 for my $r (($from_row+1)..($to_row-1)) {
772 my $middle_piece = substr($board->[$r], $to_col, 1);
773 return 0 if ($middle_piece ne '-');
779 if (lc($piece) eq 'b') {
780 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
782 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
783 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
785 my $r = $from_row + $dr;
786 my $c = $from_col + $dc;
788 while ($r != $to_row) {
789 my $middle_piece = substr($board->[$r], $c, 1);
790 return 0 if ($middle_piece ne '-');
798 if (lc($piece) eq 'n') {
799 my $diff_r = abs($from_row - $to_row);
800 my $diff_c = abs($from_col - $to_col);
801 return 1 if ($diff_r == 2 && $diff_c == 1);
802 return 1 if ($diff_r == 1 && $diff_c == 2);
806 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
807 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
810 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
811 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
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 '-');
825 if ($to_col == $from_col && $to_row == $from_row - 1) {
826 return ($dest_piece eq '-');
828 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
829 return ($dest_piece ne '-');
840 print UCIWRITE "$msg\n";
841 print UCILOG "=> $msg\n";
845 my ($uciinfo, $pos, $mpv) = @_;
847 if (defined($uciinfo{'score_mate' . $mpv})) {
848 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
850 if (exists($uciinfo{'score_cp' . $mpv})) {
851 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
852 if ($pos->{'toplay'} eq 'B') {
855 return sprintf "%+5.2f", $score;
863 my ($uciinfo, $pos, $mpv) = @_;
865 if (defined($uciinfo{'score_mate' . $mpv})) {
866 my $mate = $uciinfo{'score_mate' . $mpv};
867 if ($pos->{'toplay'} eq 'B') {
871 return sprintf "White mates in %u", $mate;
873 return sprintf "Black mates in %u", -$mate;
876 if (exists($uciinfo{'score_cp' . $mpv})) {
877 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
878 if ($pos->{'toplay'} eq 'B') {
881 return sprintf "Score: %+5.2f", $score;