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