]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Factor out make_move() from prettyprint_pv().
[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 sub make_move {
367         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
368         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
369         my $piece = substr($board->[$from_row], $from_col, 1);
370         my @nb = @$board;
371
372         if ($piece eq '-') {
373                 die "Invalid move $move";
374         }
375
376         # white short castling
377         if ($move eq 'e1g1' && $piece eq 'K') {
378                 # king
379                 substr($nb[7], 4, 1, '-');
380                 substr($nb[7], 6, 1, $piece);
381                 
382                 # rook
383                 substr($nb[7], 7, 1, '-');
384                 substr($nb[7], 5, 1, 'R');
385                                 
386                 return \@nb;
387         }
388
389         # white long castling
390         if ($move eq 'e1c1' && $piece eq 'K') {
391                 # king
392                 substr($nb[7], 4, 1, '-');
393                 substr($nb[7], 2, 1, $piece);
394                 
395                 # rook
396                 substr($nb[7], 0, 1, '-');
397                 substr($nb[7], 3, 1, 'R');
398                                 
399                 return \@nb;
400         }
401
402         # black short castling
403         if ($move eq 'e8g8' && $piece eq 'k') {
404                 # king
405                 substr($nb[0], 4, 1, '-');
406                 substr($nb[0], 6, 1, $piece);
407                 
408                 # rook
409                 substr($nb[0], 7, 1, '-');
410                 substr($nb[0], 5, 1, 'r');
411                                 
412                 return \@nb;
413         }
414
415         # black long castling
416         if ($move eq 'e8c8' && $piece eq 'k') {
417                 # king
418                 substr($nb[0], 4, 1, '-');
419                 substr($nb[0], 2, 1, $piece);
420                 
421                 # rook
422                 substr($nb[0], 0, 1, '-');
423                 substr($nb[0], 3, 1, 'r');
424                                 
425                 return \@nb;
426         }
427
428         # check if the from-piece is a pawn
429         if (lc($piece) eq 'p') {
430                 # attack?
431                 if ($from_col != $to_col) {
432                         # en passant?
433                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
434                                 if ($piece eq 'p') {
435                                         substr($nb[$to_row + 1], $to_col, 1, '-');
436                                 } else {
437                                         substr($nb[$to_row - 1], $to_col, 1, '-');
438                                 }
439                         }
440                 } else {
441                         if ($promo ne '') {
442                                 if ($piece eq 'p') {
443                                         $piece = $promo;
444                                 } else {
445                                         $piece = uc($promo);
446                                 }
447                         }
448                 }
449         }
450
451         # update the board
452         substr($nb[$from_row], $from_col, 1, '-');
453         substr($nb[$to_row], $to_col, 1, $piece);
454
455         return \@nb;
456 }
457
458 sub prettyprint_pv {
459         my ($board, @pvs) = @_;
460
461         if (scalar @pvs == 0 || !defined($pvs[0])) {
462                 return ();
463         }
464
465         my $pv = shift @pvs;
466         my $from_col = col_letter_to_num(substr($pv, 0, 1));
467         my $from_row = row_letter_to_num(substr($pv, 1, 1));
468         my $to_col   = col_letter_to_num(substr($pv, 2, 1));
469         my $to_row   = row_letter_to_num(substr($pv, 3, 1));
470         my $promo    = substr($pv, 4, 1);
471
472         my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
473         my $piece = substr($board->[$from_row], $from_col, 1);
474
475         if ($piece eq '-') {
476                 die "Invalid move $pv";
477         }
478
479         # white short castling
480         if ($pv eq 'e1g1' && $piece eq 'K') {
481                 return ('0-0', prettyprint_pv($nb, @pvs));
482         }
483
484         # white long castling
485         if ($pv eq 'e1c1' && $piece eq 'K') {
486                 return ('0-0-0', prettyprint_pv($nb, @pvs));
487         }
488
489         # black short castling
490         if ($pv eq 'e8g8' && $piece eq 'k') {
491                 return ('0-0', prettyprint_pv($nb, @pvs));
492         }
493
494         # black long castling
495         if ($pv eq 'e8c8' && $piece eq 'k') {
496                 return ('0-0-0', prettyprint_pv($nb, @pvs));
497         }
498
499         my $pretty;
500
501         # check if the from-piece is a pawn
502         if (lc($piece) eq 'p') {
503                 # attack?
504                 if ($from_col != $to_col) {
505                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
506                 } else {
507                         $pretty = substr($pv, 2, 2);
508
509                         if (length($pv) == 5) {
510                                 # promotion
511                                 $pretty .= "=";
512                                 $pretty .= uc(substr($pv, 4, 1));
513
514                                 if ($piece eq 'p') {
515                                         $piece = substr($pv, 4, 1);
516                                 } else {
517                                         $piece = uc(substr($pv, 4, 1));
518                                 }
519                         }
520                 }
521         } else {
522                 $pretty = uc($piece);
523
524                 # see how many of these pieces could go here, in all
525                 my $num_total = 0;
526                 for my $col (0..7) {
527                         for my $row (0..7) {
528                                 next unless (substr($board->[$row], $col, 1) eq $piece);
529                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
530                         }
531                 }
532
533                 # see how many of these pieces from the given row could go here
534                 my $num_row = 0;
535                 for my $col (0..7) {
536                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
537                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
538                 }
539                 
540                 # and same for columns
541                 my $num_col = 0;
542                 for my $row (0..7) {
543                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
544                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
545                 }
546                 
547                 # see if we need to disambiguate
548                 if ($num_total > 1) {
549                         if ($num_col == 1) {
550                                 $pretty .= substr($pv, 0, 1);
551                         } elsif ($num_row == 1) {
552                                 $pretty .= substr($pv, 1, 1);
553                         } else {
554                                 $pretty .= substr($pv, 0, 2);
555                         }
556                 }
557
558                 # attack?
559                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
560                         $pretty .= 'x';
561                 }
562
563                 $pretty .= substr($pv, 2, 2);
564         }
565
566         if (in_mate($nb)) {
567                 $pretty .= '#';
568         } elsif (in_check($nb) ne 'none') {
569                 $pretty .= '+';
570         }
571         return ($pretty, prettyprint_pv($nb, @pvs));
572 }
573
574 sub output_screen {
575         #return;
576         
577         return if (!defined($pos_calculating));
578
579         #
580         # Check the PVs first. if they're invalid, just wait, as our data
581         # is most likely out of sync. This isn't a very good solution, as
582         # it can frequently miss stuff, but it's good enough for most users.
583         #
584         eval {
585                 my $dummy;
586                 if (exists($uciinfo{'pv'})) {
587                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
588                 }
589         
590                 my $mpv = 1;
591                 while (exists($uciinfo{'pv' . $mpv})) {
592                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
593                         ++$mpv;
594                 }
595         };
596         if ($@) {
597                 %uciinfo = ();
598                 return;
599         }
600
601         my $text = 'Analysis';
602         if ($pos_calculating->{'last_move'} ne 'none') {
603                 if ($pos_calculating->{'toplay'} eq 'W') {
604                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
605                 } else {
606                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
607                 }
608                 if (exists($uciid{'name'})) {
609                         $text .= ',';
610                 }
611         }
612
613         if (exists($uciid{'name'})) {
614                 $text .= " by $uciid{'name'}:\n\n";
615         } else {
616                 $text .= ":\n\n";
617         }
618
619         return unless (exists($pos_calculating->{'board'}));
620                 
621         #
622         # Some programs _always_ report MultiPV, even with only one PV.
623         # In this case, we simply use that data as if MultiPV was never
624         # specified.
625         #
626         if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
627                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
628                         if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
629                                 $uciinfo{$key} = $uciinfo{$key . '1'};
630                         }
631                 }
632         }
633
634         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
635                 # multi-PV
636                 my $mpv = 1;
637                 while (exists($uciinfo{'pv' . $mpv})) {
638                         $text .= sprintf "  PV%2u", $mpv;
639                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
640                         $text .= "  ($score)" if (defined($score));
641
642                         my $tbhits = '';
643                         if (exists($uciinfo{'tbhits' . $mpv}) && $uciinfo{'tbhits' . $mpv} > 0) {
644                                 if ($uciinfo{'tbhits' . $mpv} == 1) {
645                                         $tbhits = ", 1 tbhit";
646                                 } else {
647                                         $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
648                                 }
649                         }
650
651                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
652                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
653                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
654                         }
655
656                         $text .= ":\n";
657                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
658                         $text .= "\n";
659                         ++$mpv;
660                 }
661         } else {
662                 # single-PV
663                 my $score = long_score(\%uciinfo, $pos_calculating, '');
664                 $text .= "  $score\n" if defined($score);
665                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
666                 $text .=  "\n";
667
668                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
669                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
670                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
671                 }
672                 if (exists($uciinfo{'tbhits'}) && $uciinfo{'tbhits'} > 0) {
673                         if ($uciinfo{'tbhits'} == 1) {
674                                 $text .= ", one Nalimov hit";
675                         } else {
676                                 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
677                         }
678                 }
679                 if (exists($uciinfo{'seldepth'})) {
680                         $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
681                 }
682                 $text .=  "\n\n";
683         }
684
685         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
686
687         if ($last_text ne $text) {
688                 print "\e[H\e[2J"; # clear the screen
689                 print $text;
690                 $last_text = $text;
691         }
692
693         # Now construct the tell text, if any
694         return if (!defined($telltarget));
695
696         my $tell_text = '';
697
698         if (exists($uciid{'name'})) {
699                 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
700         } else {
701                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
702         }
703
704         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
705                 # multi-PV
706                 my $mpv = 1;
707                 while (exists($uciinfo{'pv' . $mpv})) {
708                         $tell_text .= sprintf "  PV%2u", $mpv;
709                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
710                         $tell_text .= "  ($score)" if (defined($score));
711
712                         if (exists($uciinfo{'depth' . $mpv})) {
713                                 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
714                         }
715
716                         $tell_text .= ": ";
717                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
718                         $tell_text .= "\n";
719                         ++$mpv;
720                 }
721         } else {
722                 # single-PV
723                 my $score = long_score(\%uciinfo, $pos_calculating, '');
724                 $tell_text .= "  $score\n" if defined($score);
725                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
726                 if (exists($uciinfo{'depth'})) {
727                         $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
728                 }
729                 $tell_text .=  "\n";
730         }
731
732         # see if a new tell is called for -- it is if the delay has expired _and_
733         # this is not simply a repetition of the last one
734         if ($last_told_text ne $tell_text) {
735                 my $now = time;
736                 for my $iv (@tell_intervals) {
737                         last if ($now - $last_move < $iv);
738                         next if ($last_tell - $last_move >= $iv);
739
740                         for my $line (split /\n/, $tell_text) {
741                                 $t->print("tell $telltarget [$target] $line");
742                         }
743
744                         $last_told_text = $text;
745                         $last_tell = $now;
746
747                         last;
748                 }
749         }
750 }
751
752 sub find_kings {
753         my $board = shift;
754         my ($wkr, $wkc, $bkr, $bkc);
755
756         for my $row (0..7) {
757                 for my $col (0..7) {
758                         my $piece = substr($board->[$row], $col, 1);
759                         if ($piece eq 'K') {
760                                 ($wkr, $wkc) = ($row, $col);
761                         } elsif ($piece eq 'k') {
762                                 ($bkr, $bkc) = ($row, $col);
763                         }
764                 }
765         }
766
767         return ($wkr, $wkc, $bkr, $bkc);
768 }
769
770 sub in_mate {
771         my $board = shift;
772         my $check = in_check($board);
773         return 0 if ($check eq 'none');
774
775         # try all possible moves for the side in check
776         for my $row (0..7) {
777                 for my $col (0..7) {
778                         my $piece = substr($board->[$row], $col, 1);
779                         next if ($piece eq '-');
780
781                         if ($check eq 'white') {
782                                 next if ($piece eq lc($piece));
783                         } else {
784                                 next if ($piece eq uc($piece));
785                         }
786
787                         for my $dest_row (0..7) {
788                                 for my $dest_col (0..7) {
789                                         next if ($row == $dest_row && $col == $dest_col);
790                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
791
792                                         my @nb = @$board;
793                                         substr($nb[$row], $col, 1, '-');
794                                         substr($nb[$dest_row], $dest_col, 1, $piece);
795
796                                         my $new_check = in_check(\@nb);
797                                         return 0 if ($new_check ne $check && $new_check ne 'both');
798                                 }
799                         }
800                 }
801         }
802
803         # nothing to do; mate
804         return 1;
805 }
806
807 sub in_check {
808         my $board = shift;
809         my ($black_check, $white_check) = (0, 0);
810
811         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
812
813         # check all pieces for the possibility of threatening the two kings
814         for my $row (0..7) {
815                 for my $col (0..7) {
816                         my $piece = substr($board->[$row], $col, 1);
817                         next if ($piece eq '-');
818                 
819                         if (uc($piece) eq $piece) {
820                                 # white piece
821                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
822                         } else {
823                                 # black piece
824                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
825                         }
826                 }
827         }
828
829         if ($black_check && $white_check) {
830                 return 'both';
831         } elsif ($black_check) {
832                 return 'black';
833         } elsif ($white_check) {
834                 return 'white';
835         } else {
836                 return 'none';
837         }
838 }
839
840 sub can_reach {
841         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
842         
843         # can't eat your own piece
844         my $dest_piece = substr($board->[$to_row], $to_col, 1);
845         if ($dest_piece ne '-') {
846                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
847         }
848
849         if (lc($piece) eq 'k') {
850                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
851         }
852         if (lc($piece) eq 'r') {
853                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
854
855                 # check that there's a clear passage
856                 if ($from_row == $to_row) {
857                         if ($from_col > $to_col) {
858                                 ($to_col, $from_col) = ($from_col, $to_col);
859                         }
860
861                         for my $c (($from_col+1)..($to_col-1)) {
862                                 my $middle_piece = substr($board->[$to_row], $c, 1);
863                                 return 0 if ($middle_piece ne '-');     
864                         }
865
866                         return 1;
867                 } else {
868                         if ($from_row > $to_row) {
869                                 ($to_row, $from_row) = ($from_row, $to_row);
870                         }
871
872                         for my $r (($from_row+1)..($to_row-1)) {
873                                 my $middle_piece = substr($board->[$r], $to_col, 1);
874                                 return 0 if ($middle_piece ne '-');     
875                         }
876
877                         return 1;
878                 }
879         }
880         if (lc($piece) eq 'b') {
881                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
882
883                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
884                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
885
886                 my $r = $from_row + $dr;
887                 my $c = $from_col + $dc;
888
889                 while ($r != $to_row) {
890                         my $middle_piece = substr($board->[$r], $c, 1);
891                         return 0 if ($middle_piece ne '-');
892                         
893                         $r += $dr;
894                         $c += $dc;
895                 }
896
897                 return 1;
898         }
899         if (lc($piece) eq 'n') {
900                 my $diff_r = abs($from_row - $to_row);
901                 my $diff_c = abs($from_col - $to_col);
902                 return 1 if ($diff_r == 2 && $diff_c == 1);
903                 return 1 if ($diff_r == 1 && $diff_c == 2);
904                 return 0;
905         }
906         if ($piece eq 'q') {
907                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
908                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
909         }
910         if ($piece eq 'Q') {
911                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
912                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
913         }
914
915         # TODO: en passant
916         if ($piece eq 'p') {
917                 # black pawn
918                 if ($to_col == $from_col && $to_row == $from_row + 1) {
919                         return ($dest_piece eq '-');
920                 }
921                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
922                         my $middle_piece = substr($board->[2], $to_col, 1);
923                         return ($dest_piece eq '-' && $middle_piece eq '-');
924                 }
925                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
926                         return ($dest_piece ne '-');
927                 }
928                 return 0;
929         }
930         if ($piece eq 'P') {
931                 # white pawn
932                 if ($to_col == $from_col && $to_row == $from_row - 1) {
933                         return ($dest_piece eq '-');
934                 }
935                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
936                         my $middle_piece = substr($board->[5], $to_col, 1);
937                         return ($dest_piece eq '-' && $middle_piece eq '-');
938                 }
939                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
940                         return ($dest_piece ne '-');
941                 }
942                 return 0;
943         }
944         
945         # unknown piece
946         return 0;
947 }
948
949 sub uciprint {
950         my ($engine, $msg) = @_;
951         print { $engine->{'write'} } "$msg\n";
952         print UCILOG localtime() . " => $msg\n";
953 }
954
955 sub short_score {
956         my ($uciinfo, $pos, $mpv) = @_;
957
958         if (defined($uciinfo{'score_mate' . $mpv})) {
959                 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
960         } else {
961                 if (exists($uciinfo{'score_cp' . $mpv})) {
962                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
963                         if ($pos->{'toplay'} eq 'B') {
964                                 $score = -$score;
965                         }
966                         return sprintf "%+5.2f", $score;
967                 }
968         }
969
970         return undef;
971 }
972
973 sub long_score {
974         my ($uciinfo, $pos, $mpv) = @_;
975
976         if (defined($uciinfo{'score_mate' . $mpv})) {
977                 my $mate = $uciinfo{'score_mate' . $mpv};
978                 if ($pos->{'toplay'} eq 'B') {
979                         $mate = -$mate;
980                 }
981                 if ($mate > 0) {
982                         return sprintf "White mates in %u", $mate;
983                 } else {
984                         return sprintf "Black mates in %u", -$mate;
985                 }
986         } else {
987                 if (exists($uciinfo{'score_cp' . $mpv})) {
988                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
989                         if ($pos->{'toplay'} eq 'B') {
990                                 $score = -$score;
991                         }
992                         return sprintf "Score: %+5.2f", $score;
993                 }
994         }
995
996         return undef;
997 }
998
999 my %book_cache = ();
1000 sub book_info {
1001         my ($fen, $board, $toplay) = @_;
1002
1003         if (exists($book_cache{$fen})) {
1004                 return $book_cache{$fen};
1005         }
1006
1007         my $ret = `./booklook $fen`;
1008         return "" if ($ret =~ /Not found/ || $ret eq '');
1009
1010         my @moves = ();
1011
1012         for my $m (split /\n/, $ret) {
1013                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1014
1015                 my $pmove;
1016                 if ($move eq '')  {
1017                         $pmove = '(current)';
1018                 } else {
1019                         ($pmove) = prettyprint_pv($board, $move);
1020                         $pmove .= $annotation;
1021                 }
1022
1023                 my $score;
1024                 if ($toplay eq 'W') {
1025                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1026                 } else {
1027                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1028                 }
1029                 my $n = $win + $draw + $lose;
1030                 
1031                 my $percent;
1032                 if ($n == 0) {
1033                         $percent = "     ";
1034                 } else {
1035                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1036                 }
1037
1038                 push @moves, [ $pmove, $n, $percent, $rating ];
1039         }
1040
1041         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1042         
1043         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1044         for my $m (@moves) {
1045                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1046         }
1047
1048         return $text;
1049 }
1050
1051 sub open_engine {
1052         my $cmdline = shift;
1053         my ($uciread, $uciwrite);
1054         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1055
1056         my $engine = {
1057                 pid => $pid,
1058                 read => $uciread,
1059                 write => $uciwrite
1060         };
1061
1062         uciprint($engine, "uci");
1063
1064         # gobble the options
1065         while (<$uciread>) {
1066                 /uciok/ && last;
1067                 handle_uci($_);
1068         }
1069         
1070         return $engine;
1071 }
1072
1073 sub read_line {
1074         my $fh = shift;
1075
1076         # 
1077         # Read until we've got a full line -- if the engine sends part of
1078         # a line and then stops we're pretty much hosed, but that should
1079         # never happen.
1080         #
1081         my $line = '';
1082         while ($line !~ /\n/) {
1083                 my $tmp;
1084                 my $ret = sysread $engine->{'read'}, $tmp, 1;
1085
1086                 if (!defined($ret)) {
1087                         next if ($!{EINTR});
1088                         die "error in reading from the UCI engine: $!";
1089                 } elsif ($ret == 0) {
1090                         die "EOF from UCI engine";
1091                 }
1092
1093                 $line .= $tmp;
1094         }
1095
1096         $line =~ tr/\r\n//d;
1097         return $line;
1098 }
1099
1100 sub col_letter_to_num {
1101         return ord(shift) - ord('a');
1102 }
1103
1104 sub row_letter_to_num {
1105         return 7 - (ord(shift) - ord('1'));
1106 }
1107
1108 sub move_to_uci_notation {
1109         my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1110         $promo //= "";
1111         return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);
1112 }