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 = '';
62 uciprint("setoption name UCI_AnalyseMode value true");
63 uciprint("setoption name NalimovPath value c:\\nalimov");
64 uciprint("setoption name NalimovUsage value Rarely");
65 uciprint("setoption name Hash value 1024");
66 uciprint("setoption name MultiPV value 3");
67 # uciprint("setoption name Contempt value 1000");
68 # uciprint("setoption name Outlook value Ultra Optimistic");
69 uciprint("ucinewgame");
71 print "Chess engine ready.\n";
74 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
75 $t->input_log(\*FICSLOG);
78 $t->waitfor('/Press return to enter the server/');
82 $t->cmd("set shout 0");
83 $t->cmd("set seek 0");
84 $t->cmd("set style 12");
85 $t->cmd("observe $target");
88 print "FICS ready.\n";
92 vec($rin, fileno(UCIREAD), 1) = 1;
93 vec($rin, fileno($t), 1) = 1;
95 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
99 my $line = $t->getline(Timeout => 0, errmode => 'return');
100 last if (!defined($line));
104 if ($line =~ /^<12> /) {
105 my $fen = style12_to_fen($line);
107 uciprint("position fen $fen");
108 uciprint("go infinite");
114 # Output a command every move to note that we're
115 # still paying attention -- this is a good tradeoff,
116 # since if no move has happened in the last half
117 # hour, the analysis/relay has most likely stopped
118 # and we should stop hogging server resources.
122 #print "FICS: [$line]\n";
126 # any fun on the UCI channel?
127 if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
128 my $line = <UCIREAD>;
132 # don't update too often
133 Time::HiRes::alarm(0.2);
144 print UCILOG "<= $line\n";
145 if ($line =~ /^info/) {
146 my (@infos) = split / /, $line;
151 if ($line =~ /^id/) {
152 my (@ids) = split / /, $line;
163 while (scalar @x > 0) {
164 if ($x[0] =~ 'multipv') {
169 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
171 my $value = shift @x;
172 $uciinfo{$key} = $value;
175 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
177 my $value = shift @x;
178 $uciinfo{$key . $mpv} = $value;
181 if ($x[0] eq 'score') {
184 delete $uciinfo{'score_cp' . $mpv};
185 delete $uciinfo{'score_mate' . $mpv};
187 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
190 $uciinfo{'score_cp' . $mpv} = shift @x;
191 } elsif ($x[0] eq 'mate') {
193 $uciinfo{'score_mate' . $mpv} = shift @x;
201 $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
204 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
208 #print "unknown info '$x[0]', trying to recover...\n";
210 die "Unknown info '" . join(',', @x) . "'";
218 while (scalar @x > 0) {
219 if ($x[0] =~ /^(name|author)$/) {
221 my $value = join(' ', @x);
222 $uciid{$key} = $value;
233 my (@x) = split / /, $str;
235 $ficsinfo{'board'} = [ @x[1..8] ];
236 $ficsinfo{'toplay'} = $x[9];
239 my (@board) = @x[1..8];
240 for my $rank (0..7) {
241 $board[$rank] =~ s/(-+)/length($1)/ge;
243 my $fen = join('/', @board);
245 # white/black to move
251 $castling .= "K" if ($x[11] == 1);
252 $castling .= "Q" if ($x[12] == 1);
253 $castling .= "k" if ($x[13] == 1);
254 $castling .= "q" if ($x[14] == 1);
255 $castling = "-" if ($castling eq "");
263 my $nep = (qw(a b c d e f g h))[$col];
272 # Showing the en passant square when actually no capture can be made
273 # seems to confuse at least Rybka. Thus, check if there's actually
274 # a pawn of the opposite side that can do the en passant move, and if
275 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
276 # "right" thing as per the standard, though.
279 $ep = $nep if ($col > 0 && substr($board[4], $col-1, 1) eq 'p');
280 $ep = $nep if ($col < 7 && substr($board[4], $col+1, 1) eq 'p');
282 $ep = $nep if ($col > 0 && substr($board[3], $col-1, 1) eq 'P');
283 $ep = $nep if ($col < 7 && substr($board[3], $col+1, 1) eq 'P');
301 my ($board, @pvs) = @_;
303 if (scalar @pvs == 0 || !defined($pvs[0])) {
310 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
311 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
312 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
313 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
316 my $piece = substr($board->[$from_row], $from_col, 1);
322 # white short castling
323 if ($pv eq 'e1g1' && $piece eq 'K') {
325 substr($nb[7], 4, 1, '-');
326 substr($nb[7], 6, 1, $piece);
329 substr($nb[7], 7, 1, '-');
330 substr($nb[7], 5, 1, 'R');
332 return ('0-0', prettyprint_pv(\@nb, @pvs));
335 # white long castling
336 if ($pv eq 'e1c1' && $piece eq 'K') {
338 substr($nb[7], 4, 1, '-');
339 substr($nb[7], 2, 1, $piece);
342 substr($nb[7], 0, 1, '-');
343 substr($nb[7], 3, 1, 'R');
345 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
348 # black short castling
349 if ($pv eq 'e8g8' && $piece eq 'k') {
351 substr($nb[0], 4, 1, '-');
352 substr($nb[0], 6, 1, $piece);
355 substr($nb[0], 7, 1, '-');
356 substr($nb[0], 5, 1, 'r');
358 return ('0-0', prettyprint_pv(\@nb, @pvs));
361 # black long castling
362 if ($pv eq 'e8c8' && $piece eq 'k') {
364 substr($nb[0], 4, 1, '-');
365 substr($nb[0], 2, 1, $piece);
368 substr($nb[0], 0, 1, '-');
369 substr($nb[0], 3, 1, 'r');
371 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
374 # check if the from-piece is a pawn
375 if (lc($piece) eq 'p') {
377 if ($from_col != $to_col) {
378 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
381 if (substr($board->[$to_row], $to_col, 1) eq '-') {
383 substr($nb[$to_row + 1], $to_col, 1, '-');
385 substr($nb[$to_row - 1], $to_col, 1, '-');
389 $pretty = substr($pv, 2, 2);
391 if (length($pv) == 5) {
394 $pretty .= uc(substr($pv, 4, 1));
397 $piece = substr($pv, 4, 1);
399 $piece = uc(substr($pv, 4, 1));
404 $pretty = uc($piece);
406 # see how many of these pieces could go here, in all
410 next unless (substr($board->[$row], $col, 1) eq $piece);
411 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
415 # see how many of these pieces from the given row could go here
418 next unless (substr($board->[$from_row], $col, 1) eq $piece);
419 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
422 # and same for columns
425 next unless (substr($board->[$row], $from_col, 1) eq $piece);
426 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
429 # see if we need to disambiguate
430 if ($num_total > 1) {
432 $pretty .= substr($pv, 0, 1);
433 } elsif ($num_row == 1) {
434 $pretty .= substr($pv, 1, 1);
436 $pretty .= substr($pv, 0, 2);
441 if (substr($board->[$to_row], $to_col, 1) ne '-') {
445 $pretty .= substr($pv, 2, 2);
449 substr($nb[$from_row], $from_col, 1, '-');
450 substr($nb[$to_row], $to_col, 1, $piece);
454 } elsif (in_check(\@nb) ne 'none') {
458 return ($pretty, prettyprint_pv(\@nb, @pvs));
465 # Check the PVs first. if they're invalid, just wait, as our data
466 # is most likely out of sync. This isn't a very good solution, as
467 # it can frequently miss stuff, but it's good enough for most users.
471 if (exists($uciinfo{'pv'})) {
472 $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}});
476 while (exists($uciinfo{'pv' . $mpv})) {
477 $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}});
488 if (exists($uciid{'name'})) {
489 $text .= "Analysis by $uciid{'name'}:\n\n";
491 $text .= "Analysis:\n\n";
494 return unless (exists($ficsinfo{'board'}));
497 # Some programs _always_ report MultiPV, even with only one PV.
498 # In this case, we simply use that data as if MultiPV was never
501 if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
502 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
503 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
504 $uciinfo{$key} = $uciinfo{$key . '1'};
509 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
512 while (exists($uciinfo{'pv' . $mpv})) {
513 $text .= sprintf " PV%2u", $mpv;
514 my $score = short_score(\%uciinfo, \%ficsinfo, $mpv);
515 $text .= " ($score)" if (defined($score));
517 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
518 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply)",
519 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
523 $text .= " " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
529 my $score = long_score(\%uciinfo, \%ficsinfo, '');
530 $text .= " $score\n" if defined($score);
531 $text .= " PV: " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
534 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
535 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
536 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
538 if (exists($uciinfo{'tbhits'})) {
539 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
541 if (exists($uciinfo{'seldepth'})) {
542 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
547 if ($last_text ne $text) {
548 print "
\e[H
\e[2J"; # clear the screen
553 # Now construct the tell text, if any
554 return if (!defined($telltarget));
558 if (exists($uciid{'name'})) {
559 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
561 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
564 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
567 while (exists($uciinfo{'pv' . $mpv})) {
568 $tell_text .= sprintf " PV%2u", $mpv;
569 my $score = short_score(\%uciinfo, \%ficsinfo, $mpv);
570 $tell_text .= " ($score)" if (defined($score));
572 if (exists($uciinfo{'depth' . $mpv})) {
573 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
577 $tell_text .= join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}}));
583 my $score = long_score(\%uciinfo, \%ficsinfo, '');
584 $tell_text .= " $score\n" if defined($score);
585 $tell_text .= " PV: " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
586 if (exists($uciinfo{'depth'})) {
587 $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
592 # see if a new tell is called for -- it is if the delay has expired _and_
593 # this is not simply a repetition of the last one
594 if ($last_told_text ne $tell_text) {
596 for my $iv (@tell_intervals) {
597 last if ($now - $last_move < $iv);
598 next if ($last_tell - $last_move >= $iv);
600 for my $line (split /\n/, $tell_text) {
601 $t->print("tell $telltarget [$target] $line");
604 $last_told_text = $text;
614 my ($wkr, $wkc, $bkr, $bkc);
618 my $piece = substr($board->[$row], $col, 1);
620 ($wkr, $wkc) = ($row, $col);
621 } elsif ($piece eq 'k') {
622 ($bkr, $bkc) = ($row, $col);
627 return ($wkr, $wkc, $bkr, $bkc);
632 my $check = in_check($board);
633 return 0 if ($check eq 'none');
635 # try all possible moves for the side in check
638 my $piece = substr($board->[$row], $col, 1);
639 next if ($piece eq '-');
641 if ($check eq 'white') {
642 next if ($piece eq lc($piece));
644 next if ($piece eq uc($piece));
647 for my $dest_row (0..7) {
648 for my $dest_col (0..7) {
649 next if ($row == $dest_row && $col == $dest_col);
650 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
653 substr($nb[$row], $col, 1, '-');
654 substr($nb[$dest_row], $dest_col, 1, $piece);
656 my $new_check = in_check(\@nb);
657 return 0 if ($new_check ne $check && $new_check ne 'both');
663 # nothing to do; mate
669 my ($black_check, $white_check) = (0, 0);
671 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
673 # check all pieces for the possibility of threatening the two kings
676 my $piece = substr($board->[$row], $col, 1);
677 next if ($piece eq '-');
679 if (uc($piece) eq $piece) {
681 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
684 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
689 if ($black_check && $white_check) {
691 } elsif ($black_check) {
693 } elsif ($white_check) {
701 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
703 # can't eat your own piece
704 my $dest_piece = substr($board->[$to_row], $to_col, 1);
705 if ($dest_piece ne '-') {
706 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
709 if (lc($piece) eq 'k') {
710 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
712 if (lc($piece) eq 'r') {
713 return 0 unless ($from_row == $to_row || $from_col == $to_col);
715 # check that there's a clear passage
716 if ($from_row == $to_row) {
717 if ($from_col > $to_col) {
718 ($to_col, $from_col) = ($from_col, $to_col);
721 for my $c (($from_col+1)..($to_col-1)) {
722 my $middle_piece = substr($board->[$to_row], $c, 1);
723 return 0 if ($middle_piece ne '-');
728 if ($from_row > $to_row) {
729 ($to_row, $from_row) = ($from_row, $to_row);
732 for my $r (($from_row+1)..($to_row-1)) {
733 my $middle_piece = substr($board->[$r], $to_col, 1);
734 return 0 if ($middle_piece ne '-');
740 if (lc($piece) eq 'b') {
741 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
743 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
744 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
746 my $r = $from_row + $dr;
747 my $c = $from_col + $dc;
749 while ($r != $to_row) {
750 my $middle_piece = substr($board->[$r], $c, 1);
751 return 0 if ($middle_piece ne '-');
759 if (lc($piece) eq 'n') {
760 my $diff_r = abs($from_row - $to_row);
761 my $diff_c = abs($from_col - $to_col);
762 return 1 if ($diff_r == 2 && $diff_c == 1);
763 return 1 if ($diff_r == 1 && $diff_c == 2);
767 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
768 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
771 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
772 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
776 if ($to_col == $from_col && $to_row == $from_row + 1) {
777 return ($dest_piece eq '-');
779 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
780 return ($dest_piece ne '-');
786 if ($to_col == $from_col && $to_row == $from_row - 1) {
787 return ($dest_piece eq '-');
789 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
790 return ($dest_piece ne '-');
801 print UCIWRITE "$msg\n";
802 print UCILOG "=> $msg\n";
806 my ($uciinfo, $ficsinfo, $mpv) = @_;
808 if (defined($uciinfo{'score_mate' . $mpv})) {
809 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
811 if (exists($uciinfo{'score_cp' . $mpv})) {
812 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
813 if ($ficsinfo{'toplay'} eq 'B') {
816 return sprintf "%+5.2f", $score;
824 my ($uciinfo, $ficsinfo, $mpv) = @_;
826 if (defined($uciinfo{'score_mate' . $mpv})) {
827 my $mate = $uciinfo{'score_mate' . $mpv};
828 if ($ficsinfo{'toplay'} eq 'B') {
832 return sprintf "White mates in %u", $mate;
834 return sprintf "Black mates in %u", -$mate;
837 if (exists($uciinfo{'score_cp' . $mpv})) {
838 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
839 if ($ficsinfo{'toplay'} eq 'B') {
842 return sprintf "Score: %+5.2f", $score;