]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Add some logging.
[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                 $ep = (qw(a b c d e f g h))[$x[10]];
194                 if ($x[9] eq 'B') {
195                         $ep .= "3";
196                 } else {
197                         $ep .= "6";
198                 }
199         }
200         $fen .= " ";
201         $fen .= $ep;
202
203         # half-move clock
204         $fen .= " ";
205         $fen .= $x[15];
206
207         # full-move clock
208         $fen .= " ";
209         $fen .= $x[26];
210
211         return $fen;
212 }
213
214 sub prettyprint_pv {
215         my ($board, @pvs) = @_;
216         
217         if (scalar @pvs == 0 || !defined($pvs[0])) {
218                 return ();
219         }
220
221         my $pv = shift @pvs;
222         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
223         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
224         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
225         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
226
227         my $pretty;
228         my $piece = substr($board->[$from_row], $from_col, 1);
229
230         # white short castling
231         if ($pv eq 'e1g1' && $piece eq 'K') {
232                 my @nb = @$board;
233
234                 # king
235                 substr($nb[7], 4, 1, '-');
236                 substr($nb[7], 6, 1, $piece);
237                 
238                 # rook
239                 substr($nb[7], 7, 1, '-');
240                 substr($nb[7], 5, 1, 'R');
241                                 
242                 return ('0-0', prettyprint_pv(\@nb, @pvs));
243         }
244
245         # white long castling
246         if ($pv eq 'e1b1' && $piece eq 'K') {
247                 my @nb = @$board;
248
249                 # king
250                 substr($nb[7], 4, 1, '-');
251                 substr($nb[7], 2, 1, $piece);
252                 
253                 # rook
254                 substr($nb[7], 0, 1, '-');
255                 substr($nb[7], 2, 1, 'R');
256                                 
257                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
258         }
259
260         # black short castling
261         if ($pv eq 'e8g8' && $piece eq 'k') {
262                 my @nb = @$board;
263
264                 # king
265                 substr($nb[0], 4, 1, '-');
266                 substr($nb[0], 6, 1, $piece);
267                 
268                 # rook
269                 substr($nb[0], 7, 1, '-');
270                 substr($nb[0], 5, 1, 'R');
271                                 
272                 return ('0-0', prettyprint_pv(\@nb, @pvs));
273         }
274
275         # black long castling
276         if ($pv eq 'e8b8' && $piece eq 'k') {
277                 my @nb = @$board;
278
279                 # king
280                 substr($nb[0], 4, 1, '-');
281                 substr($nb[0], 2, 1, $piece);
282                 
283                 # rook
284                 substr($nb[0], 0, 1, '-');
285                 substr($nb[0], 2, 1, 'R');
286                                 
287                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
288         }
289
290         # check if the from-piece is a pawn
291         if (lc($piece) eq 'p') {
292                 # attack?
293                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
294                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
295                 } else {
296                         $pretty = substr($pv, 2, 2);
297
298                         if (length($pv) == 5) {
299                                 # promotion
300                                 $pretty .= "=";
301                                 $pretty .= uc(substr($pv, 4, 1));
302
303                                 if ($piece eq 'p') {
304                                         $piece = substr($pv, 4, 1);
305                                 } else {
306                                         $piece = uc(substr($pv, 4, 1));
307                                 }
308                         }
309                 }
310         } else {
311                 $pretty = uc($piece);
312
313                 # see how many of these pieces could go here, in all
314                 my $num_total = 0;
315                 for my $col (0..7) {
316                         for my $row (0..7) {
317                                 next unless (substr($board->[$row], $col, 1) eq $piece);
318                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
319                         }
320                 }
321
322                 # see how many of these pieces from the given row could go here
323                 my $num_row = 0;
324                 for my $col (0..7) {
325                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
326                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
327                 }
328                 
329                 # and same for columns
330                 my $num_col = 0;
331                 for my $row (0..7) {
332                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
333                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
334                 }
335                 
336                 # see if we need to disambiguate
337                 if ($num_total > 1) {
338                         if ($num_col == 1) {
339                                 $pretty .= substr($pv, 0, 1);
340                         } elsif ($num_row == 1) {
341                                 $pretty .= substr($pv, 1, 1);
342                         } else {
343                                 $pretty .= substr($pv, 0, 2);
344                         }
345                 }
346
347                 # attack?
348                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
349                         $pretty .= 'x';
350                 }
351
352                 $pretty .= substr($pv, 2, 2);
353         }
354
355         # update the board
356         my @nb = @$board;
357         substr($nb[$from_row], $from_col, 1, '-');
358         substr($nb[$to_row], $to_col, 1, $piece);
359
360         if (in_mate(\@nb)) {
361                 $pretty .= '#';
362         } elsif (in_check(\@nb) ne 'none') {
363                 $pretty .= '+';
364         }
365
366         return ($pretty, prettyprint_pv(\@nb, @pvs));
367 }
368
369 sub output_screen {
370         #return;
371
372         print  "\ecAnalysis:\n";
373         if (defined($uciinfo{'score_mate'})) {
374                 printf "  Mate in %d\n", $uciinfo{'score_mate'};
375         } else {
376                 my $score = $uciinfo{'score_cp'} * 0.01;
377                 if ($ficsinfo{'toplay'} eq 'B') {
378                         $score = -$score;
379                 }
380                 printf "  Score: %+5.2f\n", $score;
381         }
382         print  "  PV: ", join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
383         print  "\n";
384         printf "  %u nodes, %7u nodes/sec, depth %u ply",
385                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
386         if (exists($uciinfo{'tbhits'})) {
387                 printf ", %u Nalimov hits", $uciinfo{'tbhits'};
388         }
389         if (exists($uciinfo{'seldepth'})) {
390                 printf " (%u selective)", $uciinfo{'seldepth'};
391         }
392         print  "\n\n";
393 }
394
395 sub find_kings {
396         my $board = shift;
397         my ($wkr, $wkc, $bkr, $bkc);
398
399         for my $row (0..7) {
400                 for my $col (0..7) {
401                         my $piece = substr($board->[$row], $col, 1);
402                         if ($piece eq 'K') {
403                                 ($wkr, $wkc) = ($row, $col);
404                         } elsif ($piece eq 'k') {
405                                 ($bkr, $bkc) = ($row, $col);
406                         }
407                 }
408         }
409
410         return ($wkr, $wkc, $bkr, $bkc);
411 }
412
413 sub in_mate {
414         my $board = shift;
415         my $check = in_check($board);
416         return 0 if ($check eq 'none');
417
418         # try all possible moves for the side in check
419         for my $row (0..7) {
420                 for my $col (0..7) {
421                         my $piece = substr($board->[$row], $col, 1);
422                         next if ($piece eq '-');
423
424                         if ($check eq 'white') {
425                                 next if ($piece eq lc($piece));
426                         } else {
427                                 next if ($piece eq uc($piece));
428                         }
429
430                         for my $dest_row (0..7) {
431                                 for my $dest_col (0..7) {
432                                         next if ($row == $dest_row && $col == $dest_col);
433                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
434
435                                         my @nb = @$board;
436                                         substr($nb[$row], $col, 1, '-');
437                                         substr($nb[$dest_row], $dest_col, 1, $piece);
438
439                                         my $new_check = in_check(\@nb);
440                                         return 0 if ($new_check ne $check && $new_check ne 'both');
441                                 }
442                         }
443                 }
444         }
445
446         # nothing to do; mate
447         return 1;
448 }
449
450 sub in_check {
451         my $board = shift;
452         my ($black_check, $white_check) = (0, 0);
453
454         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
455
456         # check all pieces for the possibility of threatening the two kings
457         for my $row (0..7) {
458                 for my $col (0..7) {
459                         my $piece = substr($board->[$row], $col, 1);
460                         next if ($piece eq '-' || lc($piece) eq 'k');
461                 
462                         if (uc($piece) eq $piece) {
463                                 # white piece
464                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
465                         } else {
466                                 # black piece
467                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
468                         }
469                 }
470         }
471
472         if ($black_check && $white_check) {
473                 return 'both';
474         } elsif ($black_check) {
475                 return 'black';
476         } elsif ($white_check) {
477                 return 'white';
478         } else {
479                 return 'none';
480         }
481 }
482
483 sub can_reach {
484         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
485         
486         # can't eat your own piece
487         my $dest_piece = substr($board->[$to_row], $to_col, 1);
488         if ($dest_piece ne '-') {
489                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
490         }
491
492         if (lc($piece) eq 'k') {
493                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
494         }
495         if (lc($piece) eq 'r') {
496                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
497
498                 # check that there's a clear passage
499                 if ($from_row == $to_row) {
500                         if ($from_col > $to_col) {
501                                 ($to_col, $from_col) = ($from_col, $to_col);
502                         }
503
504                         for my $c (($from_col+1)..($to_col-1)) {
505                                 my $middle_piece = substr($board->[$to_row], $c, 1);
506                                 return 0 if ($middle_piece ne '-');     
507                         }
508
509                         return 1;
510                 } else {
511                         if ($from_row > $to_row) {
512                                 ($to_row, $from_row) = ($from_row, $to_row);
513                         }
514
515                         for my $r (($from_row+1)..($to_row-1)) {
516                                 my $middle_piece = substr($board->[$r], $to_col, 1);
517                                 return 0 if ($middle_piece ne '-');     
518                         }
519
520                         return 1;
521                 }
522         }
523         if (lc($piece) eq 'b') {
524                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
525
526                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
527                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
528
529                 my $r = $from_row + $dr;
530                 my $c = $from_col + $dc;
531
532                 while ($r != $to_row) {
533                         my $middle_piece = substr($board->[$r], $c, 1);
534                         return 0 if ($middle_piece ne '-');
535                         
536                         $r += $dr;
537                         $c += $dc;
538                 }
539
540                 return 1;
541         }
542         if (lc($piece) eq 'n') {
543                 my $diff_r = abs($from_row - $to_row);
544                 my $diff_c = abs($from_col - $to_col);
545                 return 1 if ($diff_r == 2 && $diff_c == 1);
546                 return 1 if ($diff_r == 1 && $diff_c == 2);
547                 return 0;
548         }
549         if ($piece eq 'q') {
550                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
551                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
552         }
553         if ($piece eq 'Q') {
554                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
555                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
556         }
557         if ($piece eq 'p') {
558                 # black pawn
559                 if ($to_col == $from_col && $to_row == $from_row + 1) {
560                         return ($dest_piece eq '-');
561                 }
562                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
563                         return ($dest_piece ne '-');
564                 }
565                 return 0;
566         }
567         if ($piece eq 'P') {
568                 # white pawn
569                 if ($to_col == $from_col && $to_row == $from_row - 1) {
570                         return ($dest_piece eq '-');
571                 }
572                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
573                         return ($dest_piece ne '-');
574                 }
575                 return 0;
576         }
577         
578         # unknown piece
579         return 0;
580 }
581
582 sub uciprint {
583         my $msg = shift;
584         print UCIWRITE "$msg\n";
585         print UCILOG "=> $msg\n";
586 }