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