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