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