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");
113 # Output a command every move to note that we're
114 # still paying attention -- this is a good tradeoff,
115 # since if no move has happened in the last half
116 # hour, the analysis/relay has most likely stopped
117 # and we should stop hogging server resources.
121 #print "FICS: [$line]\n";
125 # any fun on the UCI channel?
126 if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
127 my $line = <UCIREAD>;
131 # don't update too often
132 Time::HiRes::alarm(0.2);
143 print UCILOG "<= $line\n";
144 if ($line =~ /^info/) {
145 my (@infos) = split / /, $line;
150 if ($line =~ /^id/) {
151 my (@ids) = split / /, $line;
162 while (scalar @x > 0) {
163 if ($x[0] =~ 'multipv') {
168 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
170 my $value = shift @x;
171 $uciinfo{$key} = $value;
174 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
176 my $value = shift @x;
177 $uciinfo{$key . $mpv} = $value;
180 if ($x[0] eq 'score') {
183 delete $uciinfo{'score_cp' . $mpv};
184 delete $uciinfo{'score_mate' . $mpv};
186 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
189 $uciinfo{'score_cp' . $mpv} = shift @x;
190 } elsif ($x[0] eq 'mate') {
192 $uciinfo{'score_mate' . $mpv} = shift @x;
200 $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
203 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
207 #print "unknown info '$x[0]', trying to recover...\n";
209 die "Unknown info '" . join(',', @x) . "'";
217 while (scalar @x > 0) {
218 if ($x[0] =~ /^(name|author)$/) {
220 my $value = join(' ', @x);
221 $uciid{$key} = $value;
232 my (@x) = split / /, $str;
234 $ficsinfo{'board'} = [ @x[1..8] ];
235 $ficsinfo{'toplay'} = $x[9];
238 my (@board) = @x[1..8];
239 for my $rank (0..7) {
240 $board[$rank] =~ s/(-+)/length($1)/ge;
242 my $fen = join('/', @board);
244 # white/black to move
250 $castling .= "K" if ($x[11] == 1);
251 $castling .= "Q" if ($x[12] == 1);
252 $castling .= "k" if ($x[13] == 1);
253 $castling .= "q" if ($x[14] == 1);
254 $castling = "-" if ($castling eq "");
262 my $nep = (qw(a b c d e f g h))[$col];
271 # Showing the en passant square when actually no capture can be made
272 # seems to confuse at least Rybka. Thus, check if there's actually
273 # a pawn of the opposite side that can do the en passant move, and if
274 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
275 # "right" thing as per the standard, though.
278 $ep = $nep if ($col > 0 && substr($board[4], $col-1, 1) eq 'p');
279 $ep = $nep if ($col < 7 && substr($board[4], $col+1, 1) eq 'p');
281 $ep = $nep if ($col > 0 && substr($board[3], $col-1, 1) eq 'P');
282 $ep = $nep if ($col < 7 && substr($board[3], $col+1, 1) eq 'P');
300 my ($board, @pvs) = @_;
302 if (scalar @pvs == 0 || !defined($pvs[0])) {
309 my $from_col = ord(substr($pv, 0, 1)) - ord('a');
310 my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
311 my $to_col = ord(substr($pv, 2, 1)) - ord('a');
312 my $to_row = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
315 my $piece = substr($board->[$from_row], $from_col, 1);
321 # white short castling
322 if ($pv eq 'e1g1' && $piece eq 'K') {
324 substr($nb[7], 4, 1, '-');
325 substr($nb[7], 6, 1, $piece);
328 substr($nb[7], 7, 1, '-');
329 substr($nb[7], 5, 1, 'R');
331 return ('0-0', prettyprint_pv(\@nb, @pvs));
334 # white long castling
335 if ($pv eq 'e1c1' && $piece eq 'K') {
337 substr($nb[7], 4, 1, '-');
338 substr($nb[7], 2, 1, $piece);
341 substr($nb[7], 0, 1, '-');
342 substr($nb[7], 3, 1, 'R');
344 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
347 # black short castling
348 if ($pv eq 'e8g8' && $piece eq 'k') {
350 substr($nb[0], 4, 1, '-');
351 substr($nb[0], 6, 1, $piece);
354 substr($nb[0], 7, 1, '-');
355 substr($nb[0], 5, 1, 'r');
357 return ('0-0', prettyprint_pv(\@nb, @pvs));
360 # black long castling
361 if ($pv eq 'e8c8' && $piece eq 'k') {
363 substr($nb[0], 4, 1, '-');
364 substr($nb[0], 2, 1, $piece);
367 substr($nb[0], 0, 1, '-');
368 substr($nb[0], 3, 1, 'r');
370 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
373 # check if the from-piece is a pawn
374 if (lc($piece) eq 'p') {
376 if ($from_col != $to_col) {
377 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
380 if (substr($board->[$to_row], $to_col, 1) eq '-') {
382 substr($nb[$to_row + 1], $to_col, 1, '-');
384 substr($nb[$to_row - 1], $to_col, 1, '-');
388 $pretty = substr($pv, 2, 2);
390 if (length($pv) == 5) {
393 $pretty .= uc(substr($pv, 4, 1));
396 $piece = substr($pv, 4, 1);
398 $piece = uc(substr($pv, 4, 1));
403 $pretty = uc($piece);
405 # see how many of these pieces could go here, in all
409 next unless (substr($board->[$row], $col, 1) eq $piece);
410 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
414 # see how many of these pieces from the given row could go here
417 next unless (substr($board->[$from_row], $col, 1) eq $piece);
418 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
421 # and same for columns
424 next unless (substr($board->[$row], $from_col, 1) eq $piece);
425 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
428 # see if we need to disambiguate
429 if ($num_total > 1) {
431 $pretty .= substr($pv, 0, 1);
432 } elsif ($num_row == 1) {
433 $pretty .= substr($pv, 1, 1);
435 $pretty .= substr($pv, 0, 2);
440 if (substr($board->[$to_row], $to_col, 1) ne '-') {
444 $pretty .= substr($pv, 2, 2);
448 substr($nb[$from_row], $from_col, 1, '-');
449 substr($nb[$to_row], $to_col, 1, $piece);
453 } elsif (in_check(\@nb) ne 'none') {
457 return ($pretty, prettyprint_pv(\@nb, @pvs));
464 # Check the PVs first. if they're invalid, just wait, as our data
465 # is most likely out of sync. This isn't a very good solution, as
466 # it can frequently miss stuff, but it's good enough for most users.
470 if (exists($uciinfo{'pv'})) {
471 $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}});
475 while (exists($uciinfo{'pv' . $mpv})) {
476 $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}});
486 if (exists($uciid{'name'})) {
487 $text .= "Analysis by $uciid{'name'}:\n\n";
489 $text .= "Analysis:\n\n";
492 return unless (exists($ficsinfo{'board'}));
494 if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
497 while (exists($uciinfo{'pv' . $mpv})) {
498 $text .= sprintf " PV%2u", $mpv;
500 if (defined($uciinfo{'score_mate' . $mpv})) {
501 $text .= sprintf " (M%3d)", $uciinfo{'score_mate' . $mpv};
503 if (exists($uciinfo{'score_cp' . $mpv})) {
504 my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
505 if ($ficsinfo{'toplay'} eq 'B') {
508 $text .= sprintf " (%+5.2f)", $score;
512 if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
513 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply)",
514 $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
518 $text .= " " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
524 # Some programs _always_ report MultiPV, even with only one PV.
525 # In this case, we simply use that data as if MultiPV was never
528 if (exists($uciinfo{'pv1'})) {
529 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
530 if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
531 $uciinfo{$key} = $uciinfo{$key . '1'};
537 if (defined($uciinfo{'score_mate'})) {
538 my $mate = $uciinfo{'score_mate'};
539 if ($ficsinfo{'toplay'} eq 'B') {
543 $text .= sprintf " White mates in %u\n", $mate;
545 $text .= sprintf " Black mates in %u\n", -$mate;
548 if (exists($uciinfo{'score_cp'})) {
549 my $score = $uciinfo{'score_cp'} * 0.01;
550 if ($ficsinfo{'toplay'} eq 'B') {
553 $text .= sprintf " Score: %+5.2f\n", $score;
557 $text .= " PV: " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
560 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
561 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
562 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
564 if (exists($uciinfo{'tbhits'})) {
565 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
567 if (exists($uciinfo{'seldepth'})) {
568 $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
573 if ($last_text ne $text) {
574 print "
\e[H
\e[2J"; # clear the screen
579 # see if a new tell is called for -- it is if the delay has expired _and_
580 # this is not simply a repetition of the last one
581 if ($last_told_text ne $text && defined($telltarget)) {
583 for my $iv (@tell_intervals) {
584 last if ($now - $last_move < $iv);
585 next if ($last_tell - $last_move >= $iv);
587 for my $line (split /\n/, $text) {
588 $t->print("tell $telltarget [$target] $line");
591 $last_told_text = $text;
601 my ($wkr, $wkc, $bkr, $bkc);
605 my $piece = substr($board->[$row], $col, 1);
607 ($wkr, $wkc) = ($row, $col);
608 } elsif ($piece eq 'k') {
609 ($bkr, $bkc) = ($row, $col);
614 return ($wkr, $wkc, $bkr, $bkc);
619 my $check = in_check($board);
620 return 0 if ($check eq 'none');
622 # try all possible moves for the side in check
625 my $piece = substr($board->[$row], $col, 1);
626 next if ($piece eq '-');
628 if ($check eq 'white') {
629 next if ($piece eq lc($piece));
631 next if ($piece eq uc($piece));
634 for my $dest_row (0..7) {
635 for my $dest_col (0..7) {
636 next if ($row == $dest_row && $col == $dest_col);
637 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
640 substr($nb[$row], $col, 1, '-');
641 substr($nb[$dest_row], $dest_col, 1, $piece);
643 my $new_check = in_check(\@nb);
644 return 0 if ($new_check ne $check && $new_check ne 'both');
650 # nothing to do; mate
656 my ($black_check, $white_check) = (0, 0);
658 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
660 # check all pieces for the possibility of threatening the two kings
663 my $piece = substr($board->[$row], $col, 1);
664 next if ($piece eq '-');
666 if (uc($piece) eq $piece) {
668 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
671 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
676 if ($black_check && $white_check) {
678 } elsif ($black_check) {
680 } elsif ($white_check) {
688 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
690 # can't eat your own piece
691 my $dest_piece = substr($board->[$to_row], $to_col, 1);
692 if ($dest_piece ne '-') {
693 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
696 if (lc($piece) eq 'k') {
697 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
699 if (lc($piece) eq 'r') {
700 return 0 unless ($from_row == $to_row || $from_col == $to_col);
702 # check that there's a clear passage
703 if ($from_row == $to_row) {
704 if ($from_col > $to_col) {
705 ($to_col, $from_col) = ($from_col, $to_col);
708 for my $c (($from_col+1)..($to_col-1)) {
709 my $middle_piece = substr($board->[$to_row], $c, 1);
710 return 0 if ($middle_piece ne '-');
715 if ($from_row > $to_row) {
716 ($to_row, $from_row) = ($from_row, $to_row);
719 for my $r (($from_row+1)..($to_row-1)) {
720 my $middle_piece = substr($board->[$r], $to_col, 1);
721 return 0 if ($middle_piece ne '-');
727 if (lc($piece) eq 'b') {
728 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
730 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
731 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
733 my $r = $from_row + $dr;
734 my $c = $from_col + $dc;
736 while ($r != $to_row) {
737 my $middle_piece = substr($board->[$r], $c, 1);
738 return 0 if ($middle_piece ne '-');
746 if (lc($piece) eq 'n') {
747 my $diff_r = abs($from_row - $to_row);
748 my $diff_c = abs($from_col - $to_col);
749 return 1 if ($diff_r == 2 && $diff_c == 1);
750 return 1 if ($diff_r == 1 && $diff_c == 2);
754 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
755 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
758 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
759 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
763 if ($to_col == $from_col && $to_row == $from_row + 1) {
764 return ($dest_piece eq '-');
766 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
767 return ($dest_piece ne '-');
773 if ($to_col == $from_col && $to_row == $from_row - 1) {
774 return ($dest_piece eq '-');
776 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
777 return ($dest_piece ne '-');
788 print UCIWRITE "$msg\n";
789 print UCILOG "=> $msg\n";