]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
4abbe70f994a17757b29eb133c7fdfd777a1be4a
[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 $pv = shift @pvs;
259         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
260         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
261         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
262         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
263
264         my $pretty;
265         my $piece = substr($board->[$from_row], $from_col, 1);
266
267         # white short castling
268         if ($pv eq 'e1g1' && $piece eq 'K') {
269                 my @nb = @$board;
270
271                 # king
272                 substr($nb[7], 4, 1, '-');
273                 substr($nb[7], 6, 1, $piece);
274                 
275                 # rook
276                 substr($nb[7], 7, 1, '-');
277                 substr($nb[7], 5, 1, 'R');
278                                 
279                 return ('0-0', prettyprint_pv(\@nb, @pvs));
280         }
281
282         # white long castling
283         if ($pv eq 'e1c1' && $piece eq 'K') {
284                 my @nb = @$board;
285
286                 # king
287                 substr($nb[7], 4, 1, '-');
288                 substr($nb[7], 2, 1, $piece);
289                 
290                 # rook
291                 substr($nb[7], 0, 1, '-');
292                 substr($nb[7], 3, 1, 'R');
293                                 
294                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
295         }
296
297         # black short castling
298         if ($pv eq 'e8g8' && $piece eq 'k') {
299                 my @nb = @$board;
300
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                 my @nb = @$board;
315
316                 # king
317                 substr($nb[0], 4, 1, '-');
318                 substr($nb[0], 2, 1, $piece);
319                 
320                 # rook
321                 substr($nb[0], 0, 1, '-');
322                 substr($nb[0], 3, 1, 'R');
323                                 
324                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
325         }
326
327         # check if the from-piece is a pawn
328         if (lc($piece) eq 'p') {
329                 # attack?
330                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
331                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
332                 } else {
333                         $pretty = substr($pv, 2, 2);
334
335                         if (length($pv) == 5) {
336                                 # promotion
337                                 $pretty .= "=";
338                                 $pretty .= uc(substr($pv, 4, 1));
339
340                                 if ($piece eq 'p') {
341                                         $piece = substr($pv, 4, 1);
342                                 } else {
343                                         $piece = uc(substr($pv, 4, 1));
344                                 }
345                         }
346                 }
347         } else {
348                 $pretty = uc($piece);
349
350                 # see how many of these pieces could go here, in all
351                 my $num_total = 0;
352                 for my $col (0..7) {
353                         for my $row (0..7) {
354                                 next unless (substr($board->[$row], $col, 1) eq $piece);
355                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
356                         }
357                 }
358
359                 # see how many of these pieces from the given row could go here
360                 my $num_row = 0;
361                 for my $col (0..7) {
362                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
363                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
364                 }
365                 
366                 # and same for columns
367                 my $num_col = 0;
368                 for my $row (0..7) {
369                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
370                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
371                 }
372                 
373                 # see if we need to disambiguate
374                 if ($num_total > 1) {
375                         if ($num_col == 1) {
376                                 $pretty .= substr($pv, 0, 1);
377                         } elsif ($num_row == 1) {
378                                 $pretty .= substr($pv, 1, 1);
379                         } else {
380                                 $pretty .= substr($pv, 0, 2);
381                         }
382                 }
383
384                 # attack?
385                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
386                         $pretty .= 'x';
387                 }
388
389                 $pretty .= substr($pv, 2, 2);
390         }
391
392         # update the board
393         my @nb = @$board;
394         substr($nb[$from_row], $from_col, 1, '-');
395         substr($nb[$to_row], $to_col, 1, $piece);
396
397         if (in_mate(\@nb)) {
398                 $pretty .= '#';
399         } elsif (in_check(\@nb) ne 'none') {
400                 $pretty .= '+';
401         }
402
403         return ($pretty, prettyprint_pv(\@nb, @pvs));
404 }
405
406 sub output_screen {
407         #return;
408
409         print  "\ecAnalysis:\n";
410
411         return unless (exists($ficsinfo{'board'}));
412
413         if (exists($uciinfo{'pv1'})) {
414                 # multi-PV
415                 my $mpv = 1;
416                 while (exists($uciinfo{'pv' . $mpv})) {
417                         printf "  PV%2u", $mpv;
418
419                         if (defined($uciinfo{'score_mate' . $mpv})) {
420                                 printf " (M%3d)", $uciinfo{'score_mate' . $mpv};
421                         } else {
422                                 if (exists($uciinfo{'score_cp' . $mpv})) {
423                                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
424                                         if ($ficsinfo{'toplay'} eq 'B') {
425                                                 $score = -$score;
426                                         }
427                                         printf " (%+5.2f)", $score;
428                                 }
429                         }
430                         
431                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
432                                 printf " (%5u kn, %3u kn/s, %2u ply)",
433                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
434                         }
435
436                         print ":\n";
437                         print "  ", join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}})), "\n";
438                         print "\n";
439                         ++$mpv;
440                 }
441         } else {
442                 # single-PV
443                 if (defined($uciinfo{'score_mate'})) {
444                         printf "  Mate in %d\n", $uciinfo{'score_mate'};
445                 } else {
446                         if (exists($uciinfo{'score_cp'})) {
447                                 my $score = $uciinfo{'score_cp'} * 0.01;
448                                 if ($ficsinfo{'toplay'} eq 'B') {
449                                         $score = -$score;
450                                 }
451                                 printf "  Score: %+5.2f\n", $score;
452                         }
453                 }
454
455                 print  "  PV: ", join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
456                 print  "\n";
457
458                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
459                         printf "  %u nodes, %7u nodes/sec, depth %u ply",
460                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
461                 }
462                 if (exists($uciinfo{'tbhits'})) {
463                         printf ", %u Nalimov hits", $uciinfo{'tbhits'};
464                 }
465                 if (exists($uciinfo{'seldepth'})) {
466                         printf " (%u selective)", $uciinfo{'seldepth'};
467                 }
468                 print  "\n\n";
469         }
470 }
471
472 sub find_kings {
473         my $board = shift;
474         my ($wkr, $wkc, $bkr, $bkc);
475
476         for my $row (0..7) {
477                 for my $col (0..7) {
478                         my $piece = substr($board->[$row], $col, 1);
479                         if ($piece eq 'K') {
480                                 ($wkr, $wkc) = ($row, $col);
481                         } elsif ($piece eq 'k') {
482                                 ($bkr, $bkc) = ($row, $col);
483                         }
484                 }
485         }
486
487         return ($wkr, $wkc, $bkr, $bkc);
488 }
489
490 sub in_mate {
491         my $board = shift;
492         my $check = in_check($board);
493         return 0 if ($check eq 'none');
494
495         # try all possible moves for the side in check
496         for my $row (0..7) {
497                 for my $col (0..7) {
498                         my $piece = substr($board->[$row], $col, 1);
499                         next if ($piece eq '-');
500
501                         if ($check eq 'white') {
502                                 next if ($piece eq lc($piece));
503                         } else {
504                                 next if ($piece eq uc($piece));
505                         }
506
507                         for my $dest_row (0..7) {
508                                 for my $dest_col (0..7) {
509                                         next if ($row == $dest_row && $col == $dest_col);
510                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
511
512                                         my @nb = @$board;
513                                         substr($nb[$row], $col, 1, '-');
514                                         substr($nb[$dest_row], $dest_col, 1, $piece);
515
516                                         my $new_check = in_check(\@nb);
517                                         return 0 if ($new_check ne $check && $new_check ne 'both');
518                                 }
519                         }
520                 }
521         }
522
523         # nothing to do; mate
524         return 1;
525 }
526
527 sub in_check {
528         my $board = shift;
529         my ($black_check, $white_check) = (0, 0);
530
531         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
532
533         # check all pieces for the possibility of threatening the two kings
534         for my $row (0..7) {
535                 for my $col (0..7) {
536                         my $piece = substr($board->[$row], $col, 1);
537                         next if ($piece eq '-' || lc($piece) eq 'k');
538                 
539                         if (uc($piece) eq $piece) {
540                                 # white piece
541                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
542                         } else {
543                                 # black piece
544                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
545                         }
546                 }
547         }
548
549         if ($black_check && $white_check) {
550                 return 'both';
551         } elsif ($black_check) {
552                 return 'black';
553         } elsif ($white_check) {
554                 return 'white';
555         } else {
556                 return 'none';
557         }
558 }
559
560 sub can_reach {
561         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
562         
563         # can't eat your own piece
564         my $dest_piece = substr($board->[$to_row], $to_col, 1);
565         if ($dest_piece ne '-') {
566                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
567         }
568
569         if (lc($piece) eq 'k') {
570                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
571         }
572         if (lc($piece) eq 'r') {
573                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
574
575                 # check that there's a clear passage
576                 if ($from_row == $to_row) {
577                         if ($from_col > $to_col) {
578                                 ($to_col, $from_col) = ($from_col, $to_col);
579                         }
580
581                         for my $c (($from_col+1)..($to_col-1)) {
582                                 my $middle_piece = substr($board->[$to_row], $c, 1);
583                                 return 0 if ($middle_piece ne '-');     
584                         }
585
586                         return 1;
587                 } else {
588                         if ($from_row > $to_row) {
589                                 ($to_row, $from_row) = ($from_row, $to_row);
590                         }
591
592                         for my $r (($from_row+1)..($to_row-1)) {
593                                 my $middle_piece = substr($board->[$r], $to_col, 1);
594                                 return 0 if ($middle_piece ne '-');     
595                         }
596
597                         return 1;
598                 }
599         }
600         if (lc($piece) eq 'b') {
601                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
602
603                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
604                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
605
606                 my $r = $from_row + $dr;
607                 my $c = $from_col + $dc;
608
609                 while ($r != $to_row) {
610                         my $middle_piece = substr($board->[$r], $c, 1);
611                         return 0 if ($middle_piece ne '-');
612                         
613                         $r += $dr;
614                         $c += $dc;
615                 }
616
617                 return 1;
618         }
619         if (lc($piece) eq 'n') {
620                 my $diff_r = abs($from_row - $to_row);
621                 my $diff_c = abs($from_col - $to_col);
622                 return 1 if ($diff_r == 2 && $diff_c == 1);
623                 return 1 if ($diff_r == 1 && $diff_c == 2);
624                 return 0;
625         }
626         if ($piece eq 'q') {
627                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
628                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
629         }
630         if ($piece eq 'Q') {
631                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
632                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
633         }
634         if ($piece eq 'p') {
635                 # black pawn
636                 if ($to_col == $from_col && $to_row == $from_row + 1) {
637                         return ($dest_piece eq '-');
638                 }
639                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
640                         return ($dest_piece ne '-');
641                 }
642                 return 0;
643         }
644         if ($piece eq 'P') {
645                 # white pawn
646                 if ($to_col == $from_col && $to_row == $from_row - 1) {
647                         return ($dest_piece eq '-');
648                 }
649                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
650                         return ($dest_piece ne '-');
651                 }
652                 return 0;
653         }
654         
655         # unknown piece
656         return 0;
657 }
658
659 sub uciprint {
660         my $msg = shift;
661         print UCIWRITE "$msg\n";
662         print UCILOG "=> $msg\n";
663 }