]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
9aaa43d654574c8e134f4f597d18ae7cd598aa65
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
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.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use Net::Telnet;
13 use FileHandle;
14 use IPC::Open2;
15 use Time::HiRes;
16 use strict;
17 use warnings;
18
19 $SIG{ALRM} = sub { output_screen(); };
20
21 $| = 1;
22
23 my $server = "freechess.org";
24 my $target = "Sesse";
25 # my $engine = "/usr/games/toga2";
26 my $engine = "wine Rybkav2.3.2a.mp.w32.exe";
27
28 open(FICSLOG, ">ficslog.txt")
29         or die "ficslog.txt: $!";
30 print FICSLOG "Log starting.\n";
31 select(FICSLOG);
32 $| = 1;
33
34 open(UCILOG, ">ucilog.txt")
35         or die "ucilog.txt: $!";
36 print UCILOG "Log starting.\n";
37 select(UCILOG);
38 $| = 1;
39 select(STDOUT);
40
41 # open the chess engine
42 my $pid = IPC::Open2::open2(*UCIREAD, *UCIWRITE, $engine);
43 my %uciinfo = ();
44 my %ficsinfo = ();
45
46 uciprint("uci");
47
48 # gobble the options
49 while (<UCIREAD>) {
50         /uciok/ && last;
51 }
52
53 uciprint("setoption name UCI_AnalyseMode value true");
54 uciprint("setoption name NalimovPath value c:\\nalimov");
55 uciprint("setoption name NalimovUsage value Rarely");
56 uciprint("setoption name Hash value 1024");
57 # uciprint("setoption name MultiPV value 3");
58 # uciprint("setoption name Contempt value 1000");
59 # uciprint("setoption name Outlook value Ultra Optimistic");
60 uciprint("ucinewgame");
61
62 print "Chess engine ready.\n";
63
64 # now talk to FICS
65 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
66 $t->input_log(\*FICSLOG);
67 $t->open($server);
68 $t->print("guest");
69 $t->waitfor('/Press return to enter the server/');
70 $t->cmd("");
71
72 # set some options
73 $t->cmd("set shout 0");
74 $t->cmd("set seek 0");
75 $t->cmd("set style 12");
76 $t->cmd("observe $target");
77
78 # main loop
79 print "FICS ready.\n";
80 while (1) {
81         my $rin = '';
82         my $rout;
83         vec($rin, fileno(UCIREAD), 1) = 1;
84         vec($rin, fileno($t), 1) = 1;
85
86         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
87         my $sleep = 1.0;
88
89         while (1) {
90                 my $line = $t->getline(Timeout => 0, errmode => 'return');
91                 last if (!defined($line));
92
93                 chomp $line;
94                 $line =~ tr/\r//d;
95                 if ($line =~ /^<12> /) {
96                         my $fen = style12_to_fen($line);
97                         uciprint("stop");
98                         uciprint("position fen $fen");
99                         uciprint("go infinite");
100                 }
101                 #print "FICS: [$line]\n";
102                 $sleep = 0;
103         }
104         
105         # any fun on the UCI channel?
106         if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
107                 my $line = <UCIREAD>;
108                 chomp $line;
109                 $line =~ tr/\r//d;
110                 print UCILOG "<= $line\n";
111                 if ($line =~ /^info/) {
112                         my (@infos) = split / /, $line;
113                         shift @infos;
114
115                         parse_infos(@infos);
116                 }
117                 $sleep = 0;
118
119                 # don't update too often
120                 Time::HiRes::alarm(0.2);
121         }
122
123         sleep $sleep;
124 }
125
126 sub parse_infos {
127         my (@x) = @_;
128         my $mpv = '';
129
130         while (scalar @x > 0) {
131                 if ($x[0] =~ 'multipv') {
132                         shift @x;
133                         $mpv = shift @x;
134                         next;
135                 }
136                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
137                         my $key = shift @x;
138                         my $value = shift @x;
139                         $uciinfo{$key} = $value;
140                         next;
141                 }
142                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
143                         my $key = shift @x;
144                         my $value = shift @x;
145                         $uciinfo{$key . $mpv} = $value;
146                         next;
147                 }
148                 if ($x[0] eq 'score') {
149                         shift @x;
150
151                         delete $uciinfo{'score_cp' . $mpv};
152                         delete $uciinfo{'score_mate' . $mpv};
153
154                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
155                                 if ($x[0] eq 'cp') {
156                                         shift @x;
157                                         $uciinfo{'score_cp' . $mpv} = shift @x;
158                                 } elsif ($x[0] eq 'mate') {
159                                         shift @x;
160                                         $uciinfo{'score_mate' . $mpv} = shift @x;
161                                 } else {
162                                         shift @x;
163                                 }
164                         }
165                         next;
166                 }
167                 if ($x[0] eq 'pv') {
168                         $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
169                         last;
170                 }
171                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
172                         last;
173                 }
174
175                 #print "unknown info '$x[0]', trying to recover...\n";
176                 #shift @x;
177                 die "Unknown info '" . join(',', @x) . "'";
178
179         }
180 }
181
182 sub style12_to_fen {
183         my $str = shift; 
184         my (@x) = split / /, $str;
185         
186         $ficsinfo{'board'} = [ @x[1..8] ];
187         $ficsinfo{'toplay'} = $x[9];
188         
189         # the board itself
190         my (@board) = @x[1..8];
191         for my $rank (0..7) {
192                 $board[$rank] =~ s/(-+)/length($1)/ge;
193         }
194         my $fen = join('/', @board);
195
196         # white/black to move
197         $fen .= " ";
198         $fen .= lc($x[9]);
199
200         # castling
201         my $castling = "";
202         $castling .= "K" if ($x[11] == 1);
203         $castling .= "Q" if ($x[12] == 1);
204         $castling .= "k" if ($x[13] == 1);
205         $castling .= "q" if ($x[14] == 1);
206         $castling = "-" if ($castling eq "");
207         $fen .= " ";
208         $fen .= $castling;
209
210         # en passant
211         my $ep = "-";
212         if ($x[10] != -1) {
213                 my $col = $x[10];
214                 my $nep = (qw(a b c d e f g h))[$col];
215
216                 if ($x[9] eq 'B') {
217                         $nep .= "3";
218                 } else {
219                         $nep .= "6";
220                 }
221                 
222                 #
223                 # Showing the en passant square when actually no capture can be made
224                 # seems to confuse at least Rybka. Thus, check if there's actually
225                 # a pawn of the opposite side that can do the en passant move, and if
226                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
227                 # "right" thing as per the standard, though.
228                 #
229                 if ($x[9] eq 'B') {
230                         $ep = $nep if ($col > 0 && substr($board[4], $col-1, 1) eq 'p');
231                         $ep = $nep if ($col < 7 && substr($board[4], $col+1, 1) eq 'p');
232                 } else {
233                         $ep = $nep if ($col > 0 && substr($board[3], $col-1, 1) eq 'P');
234                         $ep = $nep if ($col < 7 && substr($board[3], $col+1, 1) eq 'P');
235                 }
236         }
237         $fen .= " ";
238         $fen .= $ep;
239
240         # half-move clock
241         $fen .= " ";
242         $fen .= $x[15];
243
244         # full-move clock
245         $fen .= " ";
246         $fen .= $x[26];
247
248         return $fen;
249 }
250
251 sub prettyprint_pv {
252         my ($board, @pvs) = @_;
253         
254         if (scalar @pvs == 0 || !defined($pvs[0])) {
255                 return ();
256         }
257         
258         my @nb = @$board;
259
260         my $pv = shift @pvs;
261         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
262         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
263         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
264         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
265
266         my $pretty;
267         my $piece = substr($board->[$from_row], $from_col, 1);
268
269         if ($piece eq '-') {
270                 die "Invalid move";
271         }
272
273         # white short castling
274         if ($pv eq 'e1g1' && $piece eq 'K') {
275                 # king
276                 substr($nb[7], 4, 1, '-');
277                 substr($nb[7], 6, 1, $piece);
278                 
279                 # rook
280                 substr($nb[7], 7, 1, '-');
281                 substr($nb[7], 5, 1, 'R');
282                                 
283                 return ('0-0', prettyprint_pv(\@nb, @pvs));
284         }
285
286         # white long castling
287         if ($pv eq 'e1c1' && $piece eq 'K') {
288                 # king
289                 substr($nb[7], 4, 1, '-');
290                 substr($nb[7], 2, 1, $piece);
291                 
292                 # rook
293                 substr($nb[7], 0, 1, '-');
294                 substr($nb[7], 3, 1, 'R');
295                                 
296                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
297         }
298
299         # black short castling
300         if ($pv eq 'e8g8' && $piece eq 'k') {
301                 # king
302                 substr($nb[0], 4, 1, '-');
303                 substr($nb[0], 6, 1, $piece);
304                 
305                 # rook
306                 substr($nb[0], 7, 1, '-');
307                 substr($nb[0], 5, 1, 'r');
308                                 
309                 return ('0-0', prettyprint_pv(\@nb, @pvs));
310         }
311
312         # black long castling
313         if ($pv eq 'e8c8' && $piece eq 'k') {
314                 # king
315                 substr($nb[0], 4, 1, '-');
316                 substr($nb[0], 2, 1, $piece);
317                 
318                 # rook
319                 substr($nb[0], 0, 1, '-');
320                 substr($nb[0], 3, 1, 'r');
321                                 
322                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
323         }
324
325         # check if the from-piece is a pawn
326         if (lc($piece) eq 'p') {
327                 # attack?
328                 if ($from_col != $to_col) {
329                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
330
331                         # en passant?
332                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
333                                 if ($piece eq 'p') {
334                                         substr($nb[$to_row + 1], $to_col, 1, '-');
335                                 } else {
336                                         substr($nb[$to_row - 1], $to_col, 1, '-');
337                                 }
338                         }
339                 } else {
340                         $pretty = substr($pv, 2, 2);
341
342                         if (length($pv) == 5) {
343                                 # promotion
344                                 $pretty .= "=";
345                                 $pretty .= uc(substr($pv, 4, 1));
346
347                                 if ($piece eq 'p') {
348                                         $piece = substr($pv, 4, 1);
349                                 } else {
350                                         $piece = uc(substr($pv, 4, 1));
351                                 }
352                         }
353                 }
354         } else {
355                 $pretty = uc($piece);
356
357                 # see how many of these pieces could go here, in all
358                 my $num_total = 0;
359                 for my $col (0..7) {
360                         for my $row (0..7) {
361                                 next unless (substr($board->[$row], $col, 1) eq $piece);
362                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
363                         }
364                 }
365
366                 # see how many of these pieces from the given row could go here
367                 my $num_row = 0;
368                 for my $col (0..7) {
369                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
370                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
371                 }
372                 
373                 # and same for columns
374                 my $num_col = 0;
375                 for my $row (0..7) {
376                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
377                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
378                 }
379                 
380                 # see if we need to disambiguate
381                 if ($num_total > 1) {
382                         if ($num_col == 1) {
383                                 $pretty .= substr($pv, 0, 1);
384                         } elsif ($num_row == 1) {
385                                 $pretty .= substr($pv, 1, 1);
386                         } else {
387                                 $pretty .= substr($pv, 0, 2);
388                         }
389                 }
390
391                 # attack?
392                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
393                         $pretty .= 'x';
394                 }
395
396                 $pretty .= substr($pv, 2, 2);
397         }
398
399         # update the board
400         substr($nb[$from_row], $from_col, 1, '-');
401         substr($nb[$to_row], $to_col, 1, $piece);
402
403         if (in_mate(\@nb)) {
404                 $pretty .= '#';
405         } elsif (in_check(\@nb) ne 'none') {
406                 $pretty .= '+';
407         }
408
409         return ($pretty, prettyprint_pv(\@nb, @pvs));
410 }
411
412 sub output_screen {
413         #return;
414
415         #
416         # Check the PVs first. if they're invalid, just wait, as our data
417         # is most likely out of sync. This isn't a very good solution, as
418         # it can frequently miss stuff, but it's good enough for most users.
419         #
420         eval {
421                 my $dummy;
422                 if (exists($uciinfo{'pv'})) {
423                         $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}});
424                 }
425         
426                 my $mpv = 1;
427                 while (exists($uciinfo{'pv' . $mpv})) {
428                         $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}});
429                         ++$mpv;
430                 }
431         };
432         if ($@) {
433                 return;
434         }
435
436         print  "\e[H\e[2JAnalysis:\n\n";
437
438         return unless (exists($ficsinfo{'board'}));
439
440         if (exists($uciinfo{'pv1'})) {
441                 # multi-PV
442                 my $mpv = 1;
443                 while (exists($uciinfo{'pv' . $mpv})) {
444                         printf "  PV%2u", $mpv;
445
446                         if (defined($uciinfo{'score_mate' . $mpv})) {
447                                 printf " (M%3d)", $uciinfo{'score_mate' . $mpv};
448                         } else {
449                                 if (exists($uciinfo{'score_cp' . $mpv})) {
450                                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
451                                         if ($ficsinfo{'toplay'} eq 'B') {
452                                                 $score = -$score;
453                                         }
454                                         printf " (%+5.2f)", $score;
455                                 }
456                         }
457                         
458                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
459                                 printf " (%5u kn, %3u kn/s, %2u ply)",
460                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
461                         }
462
463                         print ":\n";
464                         print "  ", join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}})), "\n";
465                         print "\n";
466                         ++$mpv;
467                 }
468         } else {
469                 # single-PV
470                 if (defined($uciinfo{'score_mate'})) {
471                         my $mate = $uciinfo{'score_mate'};
472                         if ($ficsinfo{'toplay'} eq 'B') {
473                                 $mate = -$mate;
474                         }
475                         if ($mate > 0) {
476                                 printf "  White mates in %u\n", $mate;
477                         } else {
478                                 printf "  Black mates in %u\n", -$mate;
479                         }
480                 } else {
481                         if (exists($uciinfo{'score_cp'})) {
482                                 my $score = $uciinfo{'score_cp'} * 0.01;
483                                 if ($ficsinfo{'toplay'} eq 'B') {
484                                         $score = -$score;
485                                 }
486                                 printf "  Score: %+5.2f\n", $score;
487                         }
488                 }
489
490                 print  "  PV: ", join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
491                 print  "\n";
492
493                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
494                         printf "  %u nodes, %7u nodes/sec, depth %u ply",
495                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
496                 }
497                 if (exists($uciinfo{'tbhits'})) {
498                         printf ", %u Nalimov hits", $uciinfo{'tbhits'};
499                 }
500                 if (exists($uciinfo{'seldepth'})) {
501                         printf " (%u selective)", $uciinfo{'seldepth'};
502                 }
503                 print  "\n\n";
504         }
505 }
506
507 sub find_kings {
508         my $board = shift;
509         my ($wkr, $wkc, $bkr, $bkc);
510
511         for my $row (0..7) {
512                 for my $col (0..7) {
513                         my $piece = substr($board->[$row], $col, 1);
514                         if ($piece eq 'K') {
515                                 ($wkr, $wkc) = ($row, $col);
516                         } elsif ($piece eq 'k') {
517                                 ($bkr, $bkc) = ($row, $col);
518                         }
519                 }
520         }
521
522         return ($wkr, $wkc, $bkr, $bkc);
523 }
524
525 sub in_mate {
526         my $board = shift;
527         my $check = in_check($board);
528         return 0 if ($check eq 'none');
529
530         # try all possible moves for the side in check
531         for my $row (0..7) {
532                 for my $col (0..7) {
533                         my $piece = substr($board->[$row], $col, 1);
534                         next if ($piece eq '-');
535
536                         if ($check eq 'white') {
537                                 next if ($piece eq lc($piece));
538                         } else {
539                                 next if ($piece eq uc($piece));
540                         }
541
542                         for my $dest_row (0..7) {
543                                 for my $dest_col (0..7) {
544                                         next if ($row == $dest_row && $col == $dest_col);
545                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
546
547                                         my @nb = @$board;
548                                         substr($nb[$row], $col, 1, '-');
549                                         substr($nb[$dest_row], $dest_col, 1, $piece);
550
551                                         my $new_check = in_check(\@nb);
552                                         return 0 if ($new_check ne $check && $new_check ne 'both');
553                                 }
554                         }
555                 }
556         }
557
558         # nothing to do; mate
559         return 1;
560 }
561
562 sub in_check {
563         my $board = shift;
564         my ($black_check, $white_check) = (0, 0);
565
566         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
567
568         # check all pieces for the possibility of threatening the two kings
569         for my $row (0..7) {
570                 for my $col (0..7) {
571                         my $piece = substr($board->[$row], $col, 1);
572                         next if ($piece eq '-');
573                 
574                         if (uc($piece) eq $piece) {
575                                 # white piece
576                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
577                         } else {
578                                 # black piece
579                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
580                         }
581                 }
582         }
583
584         if ($black_check && $white_check) {
585                 return 'both';
586         } elsif ($black_check) {
587                 return 'black';
588         } elsif ($white_check) {
589                 return 'white';
590         } else {
591                 return 'none';
592         }
593 }
594
595 sub can_reach {
596         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
597         
598         # can't eat your own piece
599         my $dest_piece = substr($board->[$to_row], $to_col, 1);
600         if ($dest_piece ne '-') {
601                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
602         }
603
604         if (lc($piece) eq 'k') {
605                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
606         }
607         if (lc($piece) eq 'r') {
608                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
609
610                 # check that there's a clear passage
611                 if ($from_row == $to_row) {
612                         if ($from_col > $to_col) {
613                                 ($to_col, $from_col) = ($from_col, $to_col);
614                         }
615
616                         for my $c (($from_col+1)..($to_col-1)) {
617                                 my $middle_piece = substr($board->[$to_row], $c, 1);
618                                 return 0 if ($middle_piece ne '-');     
619                         }
620
621                         return 1;
622                 } else {
623                         if ($from_row > $to_row) {
624                                 ($to_row, $from_row) = ($from_row, $to_row);
625                         }
626
627                         for my $r (($from_row+1)..($to_row-1)) {
628                                 my $middle_piece = substr($board->[$r], $to_col, 1);
629                                 return 0 if ($middle_piece ne '-');     
630                         }
631
632                         return 1;
633                 }
634         }
635         if (lc($piece) eq 'b') {
636                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
637
638                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
639                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
640
641                 my $r = $from_row + $dr;
642                 my $c = $from_col + $dc;
643
644                 while ($r != $to_row) {
645                         my $middle_piece = substr($board->[$r], $c, 1);
646                         return 0 if ($middle_piece ne '-');
647                         
648                         $r += $dr;
649                         $c += $dc;
650                 }
651
652                 return 1;
653         }
654         if (lc($piece) eq 'n') {
655                 my $diff_r = abs($from_row - $to_row);
656                 my $diff_c = abs($from_col - $to_col);
657                 return 1 if ($diff_r == 2 && $diff_c == 1);
658                 return 1 if ($diff_r == 1 && $diff_c == 2);
659                 return 0;
660         }
661         if ($piece eq 'q') {
662                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
663                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
664         }
665         if ($piece eq 'Q') {
666                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
667                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
668         }
669         if ($piece eq 'p') {
670                 # black pawn
671                 if ($to_col == $from_col && $to_row == $from_row + 1) {
672                         return ($dest_piece eq '-');
673                 }
674                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
675                         return ($dest_piece ne '-');
676                 }
677                 return 0;
678         }
679         if ($piece eq 'P') {
680                 # white pawn
681                 if ($to_col == $from_col && $to_row == $from_row - 1) {
682                         return ($dest_piece eq '-');
683                 }
684                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
685                         return ($dest_piece ne '-');
686                 }
687                 return 0;
688         }
689         
690         # unknown piece
691         return 0;
692 }
693
694 sub uciprint {
695         my $msg = shift;
696         print UCIWRITE "$msg\n";
697         print UCILOG "=> $msg\n";
698 }