]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
36c38d8c6d60ae8251649b078fea0ce4dfb1ad75
[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 # Configuration
20 my $server = "freechess.org";
21 my $target = "GMCarlsen";
22 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
23 my $telltarget = undef;   # undef to be silent
24 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960);  # after each move
25 my $uci_assume_full_compliance = 0;                    # dangerous :-)
26 my @masters = (
27         'Sesse',
28         'Sessse',
29         'Sesssse',
30         'greatestguns',
31         'beuki'
32 );
33
34 # Program starts here
35 $SIG{ALRM} = sub { output_screen(); };
36
37 $| = 1;
38
39 open(FICSLOG, ">ficslog.txt")
40         or die "ficslog.txt: $!";
41 print FICSLOG "Log starting.\n";
42 select(FICSLOG);
43 $| = 1;
44
45 open(UCILOG, ">ucilog.txt")
46         or die "ucilog.txt: $!";
47 print UCILOG "Log starting.\n";
48 select(UCILOG);
49 $| = 1;
50 select(STDOUT);
51
52 # open the chess engine
53 my $engine = open_engine($engine_cmdline);
54 my %uciinfo = ();
55 my %uciid = ();
56 my ($last_move, $last_tell);
57 my $last_text = '';
58 my $last_told_text = '';
59 my ($pos_waiting, $pos_calculating);
60
61 uciprint($engine, "setoption name UCI_AnalyseMode value true");
62 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
63 uciprint($engine, "setoption name NalimovUsage value Rarely");
64 uciprint($engine, "setoption name Hash value 1024");
65 # uciprint($engine, "setoption name MultiPV value 2");
66 uciprint($engine, "ucinewgame");
67
68 print "Chess engine ready.\n";
69
70 # now talk to FICS
71 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
72 $t->input_log(\*FICSLOG);
73 $t->open($server);
74 $t->print("SesseBOT");
75 $t->waitfor('/Press return to enter the server/');
76 $t->cmd("");
77
78 # set some options
79 $t->cmd("set shout 0");
80 $t->cmd("set seek 0");
81 $t->cmd("set style 12");
82 $t->cmd("observe $target");
83
84 # main loop
85 print "FICS ready.\n";
86 while (1) {
87         my $rin = '';
88         my $rout;
89         vec($rin, fileno($engine->{'read'}), 1) = 1;
90         vec($rin, fileno($t), 1) = 1;
91
92         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
93         my $sleep = 1.0;
94
95         while (1) {
96                 my $line = $t->getline(Timeout => 0, errmode => 'return');
97                 last if (!defined($line));
98
99                 chomp $line;
100                 $line =~ tr/\r//d;
101                 if ($line =~ /^<12> /) {
102                         my $pos = style12_to_pos($line);
103                         
104                         # if this is already in the queue, ignore it
105                         next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
106
107                         # if we're already chewing on this and there's nothing else in the queue,
108                         # also ignore it
109                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
110                                  $pos->{'fen'} eq $pos_calculating->{'fen'});
111
112                         # if we're already thinking on something, stop and wait for the engine
113                         # to approve
114                         if (defined($pos_calculating)) {
115                                 if (!defined($pos_waiting)) {
116                                         uciprint($engine, "stop");
117                                 }
118                                 if ($uci_assume_full_compliance) {
119                                         $pos_waiting = $pos;
120                                 } else {
121                                         uciprint($engine, "position fen " . $pos->{'fen'});
122                                         uciprint($engine, "go infinite");
123                                         $pos_calculating = $pos;
124                                 }
125                         } else {
126                                 # it's wrong just to give the FEN (the move history is useful,
127                                 # and per the UCI spec, we should really have sent "ucinewgame"),
128                                 # but it's easier
129                                 uciprint($engine, "position fen " . $pos->{'fen'});
130                                 uciprint($engine, "go infinite");
131                                 $pos_calculating = $pos;
132                         }
133
134                         %uciinfo = ();
135                         $last_move = time;
136
137                         # 
138                         # Output a command every move to note that we're
139                         # still paying attention -- this is a good tradeoff,
140                         # since if no move has happened in the last half
141                         # hour, the analysis/relay has most likely stopped
142                         # and we should stop hogging server resources.
143                         #
144                         $t->cmd("date");
145                 }
146                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
147                         my ($who, $msg) = ($1, $2);
148
149                         next if (grep { $_ eq $who } (@masters) == 0);
150         
151                         if ($msg =~ /^fics (.*?)$/) {
152                                 $t->cmd("tell $who Executing '$1' on FICS.");
153                                 $t->cmd($1);
154                         } elsif ($msg =~ /^uci (.*?)$/) {
155                                 $t->cmd("tell $who Sending '$1' to the engine.");
156                                 print { $engine->{'write'} } "$1\n";
157                         } else {
158                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
159                         }
160                 }
161                 #print "FICS: [$line]\n";
162                 $sleep = 0;
163         }
164         
165         # any fun on the UCI channel?
166         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
167                 my $line = read_line($engine->{'read'});
168                 handle_uci($line);
169                 $sleep = 0;
170
171                 # don't update too often
172                 Time::HiRes::alarm(0.2);
173         }
174
175         sleep $sleep;
176 }
177
178 sub handle_uci {
179         my ($line) = @_;
180
181         chomp $line;
182         $line =~ tr/\r//d;
183         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
184         print UCILOG localtime() . " <= $line\n";
185         if ($line =~ /^info/) {
186                 my (@infos) = split / /, $line;
187                 shift @infos;
188
189                 parse_infos(@infos);
190         }
191         if ($line =~ /^id/) {
192                 my (@ids) = split / /, $line;
193                 shift @ids;
194
195                 parse_ids(@ids);
196         }
197         if ($line =~ /^bestmove/ && $uci_assume_full_compliance) {
198                 if (defined($pos_waiting)) {
199                         uciprint($engine, "position fen " . $pos_waiting->{'fen'});
200                         uciprint($engine, "go infinite");
201
202                         $pos_calculating = $pos_waiting;
203                         $pos_waiting = undef;
204                 }
205         }
206 }
207
208 sub parse_infos {
209         my (@x) = @_;
210         my $mpv = '';
211
212         while (scalar @x > 0) {
213                 if ($x[0] =~ 'multipv') {
214                         shift @x;
215                         $mpv = shift @x;
216                         next;
217                 }
218                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
219                         my $key = shift @x;
220                         my $value = shift @x;
221                         $uciinfo{$key} = $value;
222                         next;
223                 }
224                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
225                         my $key = shift @x;
226                         my $value = shift @x;
227                         $uciinfo{$key . $mpv} = $value;
228                         next;
229                 }
230                 if ($x[0] eq 'score') {
231                         shift @x;
232
233                         delete $uciinfo{'score_cp' . $mpv};
234                         delete $uciinfo{'score_mate' . $mpv};
235
236                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
237                                 if ($x[0] eq 'cp') {
238                                         shift @x;
239                                         $uciinfo{'score_cp' . $mpv} = shift @x;
240                                 } elsif ($x[0] eq 'mate') {
241                                         shift @x;
242                                         $uciinfo{'score_mate' . $mpv} = shift @x;
243                                 } else {
244                                         shift @x;
245                                 }
246                         }
247                         next;
248                 }
249                 if ($x[0] eq 'pv') {
250                         $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
251                         last;
252                 }
253                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
254                         last;
255                 }
256
257                 #print "unknown info '$x[0]', trying to recover...\n";
258                 #shift @x;
259                 die "Unknown info '" . join(',', @x) . "'";
260
261         }
262 }
263
264 sub parse_ids {
265         my (@x) = @_;
266
267         while (scalar @x > 0) {
268                 if ($x[0] =~ /^(name|author)$/) {
269                         my $key = shift @x;
270                         my $value = join(' ', @x);
271                         $uciid{$key} = $value;
272                         last;
273                 }
274
275                 # unknown
276                 shift @x;
277         }
278 }
279
280 sub style12_to_pos {
281         my $str = shift;
282         my %pos = ();
283         my (@x) = split / /, $str;
284         
285         $pos{'board'} = [ @x[1..8] ];
286         $pos{'toplay'} = $x[9];
287         $pos{'ep_file_num'} = $x[10];
288         $pos{'white_castle_k'} = $x[11];
289         $pos{'white_castle_q'} = $x[12];
290         $pos{'black_castle_k'} = $x[13];
291         $pos{'black_castle_q'} = $x[14];
292         $pos{'time_to_100move_rule'} = $x[15];
293         $pos{'move_num'} = $x[26];
294         $pos{'last_move'} = $x[29];
295         $pos{'fen'} = make_fen(\%pos);
296
297         return \%pos;
298 }
299
300 sub make_fen {
301         my $pos = shift;
302
303         # the board itself
304         my (@board) = @{$pos->{'board'}};
305         for my $rank (0..7) {
306                 $board[$rank] =~ s/(-+)/length($1)/ge;
307         }
308         my $fen = join('/', @board);
309
310         # white/black to move
311         $fen .= " ";
312         $fen .= lc($pos->{'toplay'});
313
314         # castling
315         my $castling = "";
316         $castling .= "K" if ($pos->{'white_castle_k'} == 1);
317         $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
318         $castling .= "k" if ($pos->{'black_castle_k'} == 1);
319         $castling .= "q" if ($pos->{'black_castle_q'} == 1);
320         $castling = "-" if ($castling eq "");
321         # $castling = "-"; # chess960
322         $fen .= " ";
323         $fen .= $castling;
324
325         # en passant
326         my $ep = "-";
327         if ($pos->{'ep_file_num'} != -1) {
328                 my $col = $pos->{'ep_file_num'};
329                 my $nep = (qw(a b c d e f g h))[$col];
330
331                 if ($pos->{'toplay'} eq 'B') {
332                         $nep .= "3";
333                 } else {
334                         $nep .= "6";
335                 }
336
337                 #
338                 # Showing the en passant square when actually no capture can be made
339                 # seems to confuse at least Rybka. Thus, check if there's actually
340                 # a pawn of the opposite side that can do the en passant move, and if
341                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
342                 # "right" thing as per the standard, though.
343                 #
344                 if ($pos->{'toplay'} eq 'B') {
345                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
346                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
347                 } else {
348                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
349                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
350                 }
351         }
352         $fen .= " ";
353         $fen .= $ep;
354
355         # half-move clock
356         $fen .= " ";
357         $fen .= $pos->{'time_to_100move_rule'};
358
359         # full-move clock
360         $fen .= " ";
361         $fen .= $pos->{'move_num'};
362
363         return $fen;
364 }
365
366 }
367
368 sub prettyprint_pv {
369         my ($board, @pvs) = @_;
370
371         if (scalar @pvs == 0 || !defined($pvs[0])) {
372                 return ();
373         }
374         
375         my @nb = @$board;
376
377         my $pv = shift @pvs;
378         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
379         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
380         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
381         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
382
383         my $pretty;
384         my $piece = substr($board->[$from_row], $from_col, 1);
385
386         if ($piece eq '-') {
387                 die "Invalid move $pv";
388         }
389
390         # white short castling
391         if ($pv eq 'e1g1' && $piece eq 'K') {
392                 # king
393                 substr($nb[7], 4, 1, '-');
394                 substr($nb[7], 6, 1, $piece);
395                 
396                 # rook
397                 substr($nb[7], 7, 1, '-');
398                 substr($nb[7], 5, 1, 'R');
399                                 
400                 return ('0-0', prettyprint_pv(\@nb, @pvs));
401         }
402
403         # white long castling
404         if ($pv eq 'e1c1' && $piece eq 'K') {
405                 # king
406                 substr($nb[7], 4, 1, '-');
407                 substr($nb[7], 2, 1, $piece);
408                 
409                 # rook
410                 substr($nb[7], 0, 1, '-');
411                 substr($nb[7], 3, 1, 'R');
412                                 
413                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
414         }
415
416         # black short castling
417         if ($pv eq 'e8g8' && $piece eq 'k') {
418                 # king
419                 substr($nb[0], 4, 1, '-');
420                 substr($nb[0], 6, 1, $piece);
421                 
422                 # rook
423                 substr($nb[0], 7, 1, '-');
424                 substr($nb[0], 5, 1, 'r');
425                                 
426                 return ('0-0', prettyprint_pv(\@nb, @pvs));
427         }
428
429         # black long castling
430         if ($pv eq 'e8c8' && $piece eq 'k') {
431                 # king
432                 substr($nb[0], 4, 1, '-');
433                 substr($nb[0], 2, 1, $piece);
434                 
435                 # rook
436                 substr($nb[0], 0, 1, '-');
437                 substr($nb[0], 3, 1, 'r');
438                                 
439                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
440         }
441
442         # check if the from-piece is a pawn
443         if (lc($piece) eq 'p') {
444                 # attack?
445                 if ($from_col != $to_col) {
446                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
447
448                         # en passant?
449                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
450                                 if ($piece eq 'p') {
451                                         substr($nb[$to_row + 1], $to_col, 1, '-');
452                                 } else {
453                                         substr($nb[$to_row - 1], $to_col, 1, '-');
454                                 }
455                         }
456                 } else {
457                         $pretty = substr($pv, 2, 2);
458
459                         if (length($pv) == 5) {
460                                 # promotion
461                                 $pretty .= "=";
462                                 $pretty .= uc(substr($pv, 4, 1));
463
464                                 if ($piece eq 'p') {
465                                         $piece = substr($pv, 4, 1);
466                                 } else {
467                                         $piece = uc(substr($pv, 4, 1));
468                                 }
469                         }
470                 }
471         } else {
472                 $pretty = uc($piece);
473
474                 # see how many of these pieces could go here, in all
475                 my $num_total = 0;
476                 for my $col (0..7) {
477                         for my $row (0..7) {
478                                 next unless (substr($board->[$row], $col, 1) eq $piece);
479                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
480                         }
481                 }
482
483                 # see how many of these pieces from the given row could go here
484                 my $num_row = 0;
485                 for my $col (0..7) {
486                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
487                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
488                 }
489                 
490                 # and same for columns
491                 my $num_col = 0;
492                 for my $row (0..7) {
493                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
494                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
495                 }
496                 
497                 # see if we need to disambiguate
498                 if ($num_total > 1) {
499                         if ($num_col == 1) {
500                                 $pretty .= substr($pv, 0, 1);
501                         } elsif ($num_row == 1) {
502                                 $pretty .= substr($pv, 1, 1);
503                         } else {
504                                 $pretty .= substr($pv, 0, 2);
505                         }
506                 }
507
508                 # attack?
509                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
510                         $pretty .= 'x';
511                 }
512
513                 $pretty .= substr($pv, 2, 2);
514         }
515
516         # update the board
517         substr($nb[$from_row], $from_col, 1, '-');
518         substr($nb[$to_row], $to_col, 1, $piece);
519
520         if (in_mate(\@nb)) {
521                 $pretty .= '#';
522         } elsif (in_check(\@nb) ne 'none') {
523                 $pretty .= '+';
524         }
525
526         return ($pretty, prettyprint_pv(\@nb, @pvs));
527 }
528
529 sub output_screen {
530         #return;
531         
532         return if (!defined($pos_calculating));
533
534         #
535         # Check the PVs first. if they're invalid, just wait, as our data
536         # is most likely out of sync. This isn't a very good solution, as
537         # it can frequently miss stuff, but it's good enough for most users.
538         #
539         eval {
540                 my $dummy;
541                 if (exists($uciinfo{'pv'})) {
542                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
543                 }
544         
545                 my $mpv = 1;
546                 while (exists($uciinfo{'pv' . $mpv})) {
547                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
548                         ++$mpv;
549                 }
550         };
551         if ($@) {
552                 %uciinfo = ();
553                 return;
554         }
555
556         my $text = 'Analysis';
557         if ($pos_calculating->{'last_move'} ne 'none') {
558                 if ($pos_calculating->{'toplay'} eq 'W') {
559                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
560                 } else {
561                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
562                 }
563                 if (exists($uciid{'name'})) {
564                         $text .= ',';
565                 }
566         }
567
568         if (exists($uciid{'name'})) {
569                 $text .= " by $uciid{'name'}:\n\n";
570         } else {
571                 $text .= ":\n\n";
572         }
573
574         return unless (exists($pos_calculating->{'board'}));
575                 
576         #
577         # Some programs _always_ report MultiPV, even with only one PV.
578         # In this case, we simply use that data as if MultiPV was never
579         # specified.
580         #
581         if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
582                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
583                         if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
584                                 $uciinfo{$key} = $uciinfo{$key . '1'};
585                         }
586                 }
587         }
588
589         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
590                 # multi-PV
591                 my $mpv = 1;
592                 while (exists($uciinfo{'pv' . $mpv})) {
593                         $text .= sprintf "  PV%2u", $mpv;
594                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
595                         $text .= "  ($score)" if (defined($score));
596
597                         my $tbhits = '';
598                         if (exists($uciinfo{'tbhits' . $mpv}) && $uciinfo{'tbhits' . $mpv} > 0) {
599                                 if ($uciinfo{'tbhits' . $mpv} == 1) {
600                                         $tbhits = ", 1 tbhit";
601                                 } else {
602                                         $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
603                                 }
604                         }
605
606                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
607                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
608                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
609                         }
610
611                         $text .= ":\n";
612                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
613                         $text .= "\n";
614                         ++$mpv;
615                 }
616         } else {
617                 # single-PV
618                 my $score = long_score(\%uciinfo, $pos_calculating, '');
619                 $text .= "  $score\n" if defined($score);
620                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
621                 $text .=  "\n";
622
623                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
624                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
625                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
626                 }
627                 if (exists($uciinfo{'tbhits'}) && $uciinfo{'tbhits'} > 0) {
628                         if ($uciinfo{'tbhits'} == 1) {
629                                 $text .= ", one Nalimov hit";
630                         } else {
631                                 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
632                         }
633                 }
634                 if (exists($uciinfo{'seldepth'})) {
635                         $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
636                 }
637                 $text .=  "\n\n";
638         }
639
640         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
641
642         if ($last_text ne $text) {
643                 print "\e[H\e[2J"; # clear the screen
644                 print $text;
645                 $last_text = $text;
646         }
647
648         # Now construct the tell text, if any
649         return if (!defined($telltarget));
650
651         my $tell_text = '';
652
653         if (exists($uciid{'name'})) {
654                 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
655         } else {
656                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
657         }
658
659         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
660                 # multi-PV
661                 my $mpv = 1;
662                 while (exists($uciinfo{'pv' . $mpv})) {
663                         $tell_text .= sprintf "  PV%2u", $mpv;
664                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
665                         $tell_text .= "  ($score)" if (defined($score));
666
667                         if (exists($uciinfo{'depth' . $mpv})) {
668                                 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
669                         }
670
671                         $tell_text .= ": ";
672                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
673                         $tell_text .= "\n";
674                         ++$mpv;
675                 }
676         } else {
677                 # single-PV
678                 my $score = long_score(\%uciinfo, $pos_calculating, '');
679                 $tell_text .= "  $score\n" if defined($score);
680                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
681                 if (exists($uciinfo{'depth'})) {
682                         $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
683                 }
684                 $tell_text .=  "\n";
685         }
686
687         # see if a new tell is called for -- it is if the delay has expired _and_
688         # this is not simply a repetition of the last one
689         if ($last_told_text ne $tell_text) {
690                 my $now = time;
691                 for my $iv (@tell_intervals) {
692                         last if ($now - $last_move < $iv);
693                         next if ($last_tell - $last_move >= $iv);
694
695                         for my $line (split /\n/, $tell_text) {
696                                 $t->print("tell $telltarget [$target] $line");
697                         }
698
699                         $last_told_text = $text;
700                         $last_tell = $now;
701
702                         last;
703                 }
704         }
705 }
706
707 sub find_kings {
708         my $board = shift;
709         my ($wkr, $wkc, $bkr, $bkc);
710
711         for my $row (0..7) {
712                 for my $col (0..7) {
713                         my $piece = substr($board->[$row], $col, 1);
714                         if ($piece eq 'K') {
715                                 ($wkr, $wkc) = ($row, $col);
716                         } elsif ($piece eq 'k') {
717                                 ($bkr, $bkc) = ($row, $col);
718                         }
719                 }
720         }
721
722         return ($wkr, $wkc, $bkr, $bkc);
723 }
724
725 sub in_mate {
726         my $board = shift;
727         my $check = in_check($board);
728         return 0 if ($check eq 'none');
729
730         # try all possible moves for the side in check
731         for my $row (0..7) {
732                 for my $col (0..7) {
733                         my $piece = substr($board->[$row], $col, 1);
734                         next if ($piece eq '-');
735
736                         if ($check eq 'white') {
737                                 next if ($piece eq lc($piece));
738                         } else {
739                                 next if ($piece eq uc($piece));
740                         }
741
742                         for my $dest_row (0..7) {
743                                 for my $dest_col (0..7) {
744                                         next if ($row == $dest_row && $col == $dest_col);
745                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
746
747                                         my @nb = @$board;
748                                         substr($nb[$row], $col, 1, '-');
749                                         substr($nb[$dest_row], $dest_col, 1, $piece);
750
751                                         my $new_check = in_check(\@nb);
752                                         return 0 if ($new_check ne $check && $new_check ne 'both');
753                                 }
754                         }
755                 }
756         }
757
758         # nothing to do; mate
759         return 1;
760 }
761
762 sub in_check {
763         my $board = shift;
764         my ($black_check, $white_check) = (0, 0);
765
766         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
767
768         # check all pieces for the possibility of threatening the two kings
769         for my $row (0..7) {
770                 for my $col (0..7) {
771                         my $piece = substr($board->[$row], $col, 1);
772                         next if ($piece eq '-');
773                 
774                         if (uc($piece) eq $piece) {
775                                 # white piece
776                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
777                         } else {
778                                 # black piece
779                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
780                         }
781                 }
782         }
783
784         if ($black_check && $white_check) {
785                 return 'both';
786         } elsif ($black_check) {
787                 return 'black';
788         } elsif ($white_check) {
789                 return 'white';
790         } else {
791                 return 'none';
792         }
793 }
794
795 sub can_reach {
796         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
797         
798         # can't eat your own piece
799         my $dest_piece = substr($board->[$to_row], $to_col, 1);
800         if ($dest_piece ne '-') {
801                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
802         }
803
804         if (lc($piece) eq 'k') {
805                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
806         }
807         if (lc($piece) eq 'r') {
808                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
809
810                 # check that there's a clear passage
811                 if ($from_row == $to_row) {
812                         if ($from_col > $to_col) {
813                                 ($to_col, $from_col) = ($from_col, $to_col);
814                         }
815
816                         for my $c (($from_col+1)..($to_col-1)) {
817                                 my $middle_piece = substr($board->[$to_row], $c, 1);
818                                 return 0 if ($middle_piece ne '-');     
819                         }
820
821                         return 1;
822                 } else {
823                         if ($from_row > $to_row) {
824                                 ($to_row, $from_row) = ($from_row, $to_row);
825                         }
826
827                         for my $r (($from_row+1)..($to_row-1)) {
828                                 my $middle_piece = substr($board->[$r], $to_col, 1);
829                                 return 0 if ($middle_piece ne '-');     
830                         }
831
832                         return 1;
833                 }
834         }
835         if (lc($piece) eq 'b') {
836                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
837
838                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
839                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
840
841                 my $r = $from_row + $dr;
842                 my $c = $from_col + $dc;
843
844                 while ($r != $to_row) {
845                         my $middle_piece = substr($board->[$r], $c, 1);
846                         return 0 if ($middle_piece ne '-');
847                         
848                         $r += $dr;
849                         $c += $dc;
850                 }
851
852                 return 1;
853         }
854         if (lc($piece) eq 'n') {
855                 my $diff_r = abs($from_row - $to_row);
856                 my $diff_c = abs($from_col - $to_col);
857                 return 1 if ($diff_r == 2 && $diff_c == 1);
858                 return 1 if ($diff_r == 1 && $diff_c == 2);
859                 return 0;
860         }
861         if ($piece eq 'q') {
862                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
863                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
864         }
865         if ($piece eq 'Q') {
866                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
867                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
868         }
869
870         # TODO: en passant
871         if ($piece eq 'p') {
872                 # black pawn
873                 if ($to_col == $from_col && $to_row == $from_row + 1) {
874                         return ($dest_piece eq '-');
875                 }
876                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
877                         my $middle_piece = substr($board->[2], $to_col, 1);
878                         return ($dest_piece eq '-' && $middle_piece eq '-');
879                 }
880                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
881                         return ($dest_piece ne '-');
882                 }
883                 return 0;
884         }
885         if ($piece eq 'P') {
886                 # white pawn
887                 if ($to_col == $from_col && $to_row == $from_row - 1) {
888                         return ($dest_piece eq '-');
889                 }
890                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
891                         my $middle_piece = substr($board->[5], $to_col, 1);
892                         return ($dest_piece eq '-' && $middle_piece eq '-');
893                 }
894                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
895                         return ($dest_piece ne '-');
896                 }
897                 return 0;
898         }
899         
900         # unknown piece
901         return 0;
902 }
903
904 sub uciprint {
905         my ($engine, $msg) = @_;
906         print { $engine->{'write'} } "$msg\n";
907         print UCILOG localtime() . " => $msg\n";
908 }
909
910 sub short_score {
911         my ($uciinfo, $pos, $mpv) = @_;
912
913         if (defined($uciinfo{'score_mate' . $mpv})) {
914                 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
915         } else {
916                 if (exists($uciinfo{'score_cp' . $mpv})) {
917                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
918                         if ($pos->{'toplay'} eq 'B') {
919                                 $score = -$score;
920                         }
921                         return sprintf "%+5.2f", $score;
922                 }
923         }
924
925         return undef;
926 }
927
928 sub long_score {
929         my ($uciinfo, $pos, $mpv) = @_;
930
931         if (defined($uciinfo{'score_mate' . $mpv})) {
932                 my $mate = $uciinfo{'score_mate' . $mpv};
933                 if ($pos->{'toplay'} eq 'B') {
934                         $mate = -$mate;
935                 }
936                 if ($mate > 0) {
937                         return sprintf "White mates in %u", $mate;
938                 } else {
939                         return sprintf "Black mates in %u", -$mate;
940                 }
941         } else {
942                 if (exists($uciinfo{'score_cp' . $mpv})) {
943                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
944                         if ($pos->{'toplay'} eq 'B') {
945                                 $score = -$score;
946                         }
947                         return sprintf "Score: %+5.2f", $score;
948                 }
949         }
950
951         return undef;
952 }
953
954 my %book_cache = ();
955 sub book_info {
956         my ($fen, $board, $toplay) = @_;
957
958         if (exists($book_cache{$fen})) {
959                 return $book_cache{$fen};
960         }
961
962         my $ret = `./booklook $fen`;
963         return "" if ($ret =~ /Not found/ || $ret eq '');
964
965         my @moves = ();
966
967         for my $m (split /\n/, $ret) {
968                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
969
970                 my $pmove;
971                 if ($move eq '')  {
972                         $pmove = '(current)';
973                 } else {
974                         ($pmove) = prettyprint_pv($board, $move);
975                         $pmove .= $annotation;
976                 }
977
978                 my $score;
979                 if ($toplay eq 'W') {
980                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
981                 } else {
982                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
983                 }
984                 my $n = $win + $draw + $lose;
985                 
986                 my $percent;
987                 if ($n == 0) {
988                         $percent = "     ";
989                 } else {
990                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
991                 }
992
993                 push @moves, [ $pmove, $n, $percent, $rating ];
994         }
995
996         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
997         
998         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
999         for my $m (@moves) {
1000                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1001         }
1002
1003         return $text;
1004 }
1005
1006 sub open_engine {
1007         my $cmdline = shift;
1008         my ($uciread, $uciwrite);
1009         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1010
1011         my $engine = {
1012                 pid => $pid,
1013                 read => $uciread,
1014                 write => $uciwrite
1015         };
1016
1017         uciprint($engine, "uci");
1018
1019         # gobble the options
1020         while (<$uciread>) {
1021                 /uciok/ && last;
1022                 handle_uci($_);
1023         }
1024         
1025         return $engine;
1026 }
1027
1028 sub read_line {
1029         my $fh = shift;
1030
1031         # 
1032         # Read until we've got a full line -- if the engine sends part of
1033         # a line and then stops we're pretty much hosed, but that should
1034         # never happen.
1035         #
1036         my $line = '';
1037         while ($line !~ /\n/) {
1038                 my $tmp;
1039                 my $ret = sysread $engine->{'read'}, $tmp, 1;
1040
1041                 if (!defined($ret)) {
1042                         next if ($!{EINTR});
1043                         die "error in reading from the UCI engine: $!";
1044                 } elsif ($ret == 0) {
1045                         die "EOF from UCI engine";
1046                 }
1047
1048                 $line .= $tmp;
1049         }
1050
1051         $line =~ tr/\r\n//d;
1052         return $line;
1053 }