]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Show the engine ID in the footer.
[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 AnyEvent;
13 use AnyEvent::Handle;
14 use AnyEvent::HTTP;
15 use Chess::PGN::Parse;
16 use EV;
17 use Net::Telnet;
18 use FileHandle;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 require 'Position.pm';
23 require 'Engine.pm';
24 use strict;
25 use warnings;
26
27 # Configuration
28 my $server = "freechess.org";
29 my $target = "GMCarlsen";
30 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
31 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";  # undef for none
32 my $uci_assume_full_compliance = 0;                    # dangerous :-)
33 my $update_max_interval = 1.0;
34 my @masters = (
35         'Sesse',
36         'Sessse',
37         'Sesssse',
38         'greatestguns',
39         'beuki'
40 );
41
42 # Program starts here
43 $SIG{ALRM} = sub { output(); };
44 my $latest_update = undef;
45 my $http_timer = undef;
46
47 $| = 1;
48
49 open(FICSLOG, ">ficslog.txt")
50         or die "ficslog.txt: $!";
51 print FICSLOG "Log starting.\n";
52 select(FICSLOG);
53 $| = 1;
54
55 open(UCILOG, ">ucilog.txt")
56         or die "ucilog.txt: $!";
57 print UCILOG "Log starting.\n";
58 select(UCILOG);
59 $| = 1;
60 select(STDOUT);
61
62 # open the chess engine
63 my $engine = open_engine($engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
64 my $engine2 = open_engine($engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
65 my $last_move;
66 my $last_text = '';
67 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
68
69 uciprint($engine, "setoption name UCI_AnalyseMode value true");
70 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
71 uciprint($engine, "setoption name NalimovUsage value Rarely");
72 uciprint($engine, "setoption name Hash value 1024");
73 # uciprint($engine, "setoption name MultiPV value 2");
74 uciprint($engine, "ucinewgame");
75
76 if (defined($engine2)) {
77         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
78         # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
79         uciprint($engine2, "setoption name NalimovUsage value Rarely");
80         uciprint($engine2, "setoption name Hash value 1024");
81         uciprint($engine2, "setoption name Threads value 8");
82         uciprint($engine2, "setoption name MultiPV value 500");
83         uciprint($engine2, "ucinewgame");
84 }
85
86 print "Chess engine ready.\n";
87
88 # now talk to FICS
89 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
90 $t->input_log(\*FICSLOG);
91 $t->open($server);
92 $t->print("SesseBOT");
93 $t->waitfor('/Press return to enter the server/');
94 $t->cmd("");
95
96 # set some options
97 $t->cmd("set shout 0");
98 $t->cmd("set seek 0");
99 $t->cmd("set style 12");
100 $t->cmd("observe $target");
101 print "FICS ready.\n";
102
103 my $ev1 = AnyEvent->io(
104         fh => fileno($t),
105         poll => 'r',
106         cb => sub {    # what callback to execute
107                 while (1) {
108                         my $line = $t->getline(Timeout => 0, errmode => 'return');
109                         return if (!defined($line));
110
111                         chomp $line;
112                         $line =~ tr/\r//d;
113                         handle_fics($line);
114                 }
115         }
116 );
117 # Engine events have already been set up by Engine.pm.
118 EV::run;
119
120 sub handle_uci {
121         my ($engine, $line, $primary) = @_;
122
123         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
124         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
125         if ($line =~ /^info/) {
126                 my (@infos) = split / /, $line;
127                 shift @infos;
128
129                 parse_infos($engine, @infos);
130         }
131         if ($line =~ /^id/) {
132                 my (@ids) = split / /, $line;
133                 shift @ids;
134
135                 parse_ids($engine, @ids);
136         }
137         if ($line =~ /^bestmove/) {
138                 if ($primary) {
139                         return if (!$uci_assume_full_compliance);
140                         if (defined($pos_waiting)) {
141                                 uciprint($engine, "position fen " . $pos_waiting->fen());
142                                 uciprint($engine, "go infinite");
143
144                                 $pos_calculating = $pos_waiting;
145                                 $pos_waiting = undef;
146                         }
147                 } else {
148                         $engine2->{'info'} = {};
149                         my $pos = $pos_waiting // $pos_calculating;
150                         uciprint($engine2, "position fen " . $pos->fen());
151                         uciprint($engine2, "go infinite");
152                         $pos_calculating_second_engine = $pos;
153                 }
154         }
155         output();
156 }
157
158 sub handle_fics {
159         my $line = shift;
160         if ($line =~ /^<12> /) {
161                 handle_position(Position->new($line));
162         }
163         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
164                 my ($who, $msg) = ($1, $2);
165
166                 next if (grep { $_ eq $who } (@masters) == 0);
167
168                 if ($msg =~ /^fics (.*?)$/) {
169                         $t->cmd("tell $who Executing '$1' on FICS.");
170                         $t->cmd($1);
171                 } elsif ($msg =~ /^uci (.*?)$/) {
172                         $t->cmd("tell $who Sending '$1' to the engine.");
173                         print { $engine->{'write'} } "$1\n";
174                 } elsif ($msg =~ /^pgn (.*?)$/) {
175                         my $url = $1;
176                         $t->cmd("tell $who Starting to poll '$url'.");
177                         AnyEvent::HTTP::http_get($url, sub {
178                                 handle_pgn(@_, $url);
179                         });
180                 } elsif ($msg =~ /^stoppgn$/) {
181                         $t->cmd("tell $who Stopping poll.");
182                         $http_timer = undef;
183                 } elsif ($msg =~ /^quit$/) {
184                         $t->cmd("tell $who Bye bye.");
185                         exit;
186                 } else {
187                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
188                 }
189         }
190         #print "FICS: [$line]\n";
191 }
192
193 sub handle_pgn {
194         my ($body, $header, $url) = @_;
195         my $pgn = Chess::PGN::Parse->new(undef, $body);
196         if (!defined($pgn) || !$pgn->read_game()) {
197                 warn "Error in parsing PGN from $url\n";
198         } else {
199                 $pgn->quick_parse_game;
200                 my $pos = Position->start_pos($pgn->white, $pgn->black);
201                 my $moves = $pgn->moves;
202                 for my $move (@$moves) {
203                         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
204                         $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
205                 }
206                 handle_position($pos);
207         }
208         
209         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
210                 AnyEvent::HTTP::http_get($url, sub {
211                         handle_pgn(@_, $url);
212                 });
213         });
214 }
215
216 sub handle_position {
217         my ($pos) = @_;
218                 
219         # if this is already in the queue, ignore it
220         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
221
222         # if we're already chewing on this and there's nothing else in the queue,
223         # also ignore it
224         return if (!defined($pos_waiting) && defined($pos_calculating) &&
225                  $pos->fen() eq $pos_calculating->fen());
226
227         # if we're already thinking on something, stop and wait for the engine
228         # to approve
229         if (defined($pos_calculating)) {
230                 if (!defined($pos_waiting)) {
231                         uciprint($engine, "stop");
232                 }
233                 if ($uci_assume_full_compliance) {
234                         $pos_waiting = $pos;
235                 } else {
236                         uciprint($engine, "position fen " . $pos->fen());
237                         uciprint($engine, "go infinite");
238                         $pos_calculating = $pos;
239                 }
240         } else {
241                 # it's wrong just to give the FEN (the move history is useful,
242                 # and per the UCI spec, we should really have sent "ucinewgame"),
243                 # but it's easier
244                 uciprint($engine, "position fen " . $pos->fen());
245                 uciprint($engine, "go infinite");
246                 $pos_calculating = $pos;
247         }
248
249         if (defined($engine2)) {
250                 if (defined($pos_calculating_second_engine)) {
251                         uciprint($engine2, "stop");
252                 } else {
253                         uciprint($engine2, "position fen " . $pos->fen());
254                         uciprint($engine2, "go infinite");
255                         $pos_calculating_second_engine = $pos;
256                 }
257                 $engine2->{'info'} = {};
258         }
259
260         $engine->{'info'} = {};
261         $last_move = time;
262
263         # 
264         # Output a command every move to note that we're
265         # still paying attention -- this is a good tradeoff,
266         # since if no move has happened in the last half
267         # hour, the analysis/relay has most likely stopped
268         # and we should stop hogging server resources.
269         #
270         $t->cmd("date");
271 }
272
273 sub parse_infos {
274         my ($engine, @x) = @_;
275         my $mpv = '';
276
277         my $info = $engine->{'info'};
278
279         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
280         for my $i (0..$#x - 1) {
281                 if ($x[$i] eq 'multipv') {
282                         $mpv = $x[$i + 1];
283                         next;
284                 }
285         }
286
287         while (scalar @x > 0) {
288                 if ($x[0] eq 'multipv') {
289                         # Dealt with above
290                         shift @x;
291                         shift @x;
292                         next;
293                 }
294                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
295                         my $key = shift @x;
296                         my $value = shift @x;
297                         $info->{$key} = $value;
298                         next;
299                 }
300                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
301                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
302                     $x[0] eq 'tbhits') {
303                         my $key = shift @x;
304                         my $value = shift @x;
305                         $info->{$key . $mpv} = $value;
306                         next;
307                 }
308                 if ($x[0] eq 'score') {
309                         shift @x;
310
311                         delete $info->{'score_cp' . $mpv};
312                         delete $info->{'score_mate' . $mpv};
313
314                         while ($x[0] eq 'cp' || $x[0] eq 'mate' || $x[0] eq 'lowerbound' || $x[0] eq 'upperbound') {
315                                 if ($x[0] eq 'cp') {
316                                         shift @x;
317                                         $info->{'score_cp' . $mpv} = shift @x;
318                                 } elsif ($x[0] eq 'mate') {
319                                         shift @x;
320                                         $info->{'score_mate' . $mpv} = shift @x;
321                                 } else {
322                                         shift @x;
323                                 }
324                         }
325                         next;
326                 }
327                 if ($x[0] eq 'pv') {
328                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
329                         last;
330                 }
331                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
332                         last;
333                 }
334
335                 #print "unknown info '$x[0]', trying to recover...\n";
336                 #shift @x;
337                 die "Unknown info '" . join(',', @x) . "'";
338
339         }
340 }
341
342 sub parse_ids {
343         my ($engine, @x) = @_;
344
345         while (scalar @x > 0) {
346                 if ($x[0] =~ /^(name|author)$/) {
347                         my $key = shift @x;
348                         my $value = join(' ', @x);
349                         $engine->{'id'}{$key} = $value;
350                         last;
351                 }
352
353                 # unknown
354                 shift @x;
355         }
356 }
357
358 sub prettyprint_pv_no_cache {
359         my ($board, @pvs) = @_;
360
361         if (scalar @pvs == 0 || !defined($pvs[0])) {
362                 return ();
363         }
364
365         my $pv = shift @pvs;
366         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
367         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
368         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
369 }
370
371 sub prettyprint_pv {
372         my ($pos, @pvs) = @_;
373
374         my $cachekey = join('', @pvs);
375         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
376                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
377         } else {
378                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
379                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
380                 return @res;
381         }
382 }
383
384 sub output {
385         #return;
386
387         return if (!defined($pos_calculating));
388
389         # Don't update too often.
390         my $age = Time::HiRes::tv_interval($latest_update);
391         if ($age < $update_max_interval) {
392                 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
393                 return;
394         }
395         
396         my $info = $engine->{'info'};
397         
398         #
399         # Some programs _always_ report MultiPV, even with only one PV.
400         # In this case, we simply use that data as if MultiPV was never
401         # specified.
402         #
403         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
404                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
405                         if (exists($info->{$key . '1'})) {
406                                 $info->{$key} = $info->{$key . '1'};
407                         }
408                 }
409         }
410         
411         #
412         # Check the PVs first. if they're invalid, just wait, as our data
413         # is most likely out of sync. This isn't a very good solution, as
414         # it can frequently miss stuff, but it's good enough for most users.
415         #
416         eval {
417                 my $dummy;
418                 if (exists($info->{'pv'})) {
419                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
420                 }
421         
422                 my $mpv = 1;
423                 while (exists($info->{'pv' . $mpv})) {
424                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
425                         ++$mpv;
426                 }
427         };
428         if ($@) {
429                 $engine->{'info'} = {};
430                 return;
431         }
432
433         output_screen();
434         output_json();
435         $latest_update = [Time::HiRes::gettimeofday];
436 }
437
438 sub output_screen {
439         my $info = $engine->{'info'};
440         my $id = $engine->{'id'};
441
442         my $text = 'Analysis';
443         if ($pos_calculating->{'last_move'} ne 'none') {
444                 if ($pos_calculating->{'toplay'} eq 'W') {
445                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
446                 } else {
447                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
448                 }
449                 if (exists($id->{'name'})) {
450                         $text .= ',';
451                 }
452         }
453
454         if (exists($id->{'name'})) {
455                 $text .= " by $id->{'name'}:\n\n";
456         } else {
457                 $text .= ":\n\n";
458         }
459
460         return unless (exists($pos_calculating->{'board'}));
461                 
462         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
463                 # multi-PV
464                 my $mpv = 1;
465                 while (exists($info->{'pv' . $mpv})) {
466                         $text .= sprintf "  PV%2u", $mpv;
467                         my $score = short_score($info, $pos_calculating, $mpv);
468                         $text .= "  ($score)" if (defined($score));
469
470                         my $tbhits = '';
471                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
472                                 if ($info->{'tbhits' . $mpv} == 1) {
473                                         $tbhits = ", 1 tbhit";
474                                 } else {
475                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
476                                 }
477                         }
478
479                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
480                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
481                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
482                         }
483
484                         $text .= ":\n";
485                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
486                         $text .= "\n";
487                         ++$mpv;
488                 }
489         } else {
490                 # single-PV
491                 my $score = long_score($info, $pos_calculating, '');
492                 $text .= "  $score\n" if defined($score);
493                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
494                 $text .=  "\n";
495
496                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
497                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
498                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
499                 }
500                 if (exists($info->{'seldepth'})) {
501                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
502                 }
503                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
504                         if ($info->{'tbhits'} == 1) {
505                                 $text .= ", one Syzygy hit";
506                         } else {
507                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
508                         }
509                 }
510                 $text .= "\n\n";
511         }
512
513         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
514
515         my @refutation_lines = ();
516         if (defined($engine2)) {
517                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
518                         my $info = $engine2->{'info'};
519                         last if (!exists($info->{'pv' . $mpv}));
520                         eval {
521                                 my $pv = $info->{'pv' . $mpv};
522
523                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
524                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
525                                 if (scalar @pretty_pv > 5) {
526                                         @pretty_pv = @pretty_pv[0..4];
527                                         push @pretty_pv, "...";
528                                 }
529                                 my $key = $pretty_move;
530                                 my $line = sprintf("  %-6s %6s %3s  %s",
531                                         $pretty_move,
532                                         short_score($info, $pos_calculating_second_engine, $mpv, 0),
533                                         "d" . $info->{'depth' . $mpv},
534                                         join(', ', @pretty_pv));
535                                 push @refutation_lines, [ $key, $line ];
536                         };
537                 }
538         }
539
540         if ($#refutation_lines >= 0) {
541                 $text .= "Shallow search of all legal moves:\n\n";
542                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
543                         $text .= $line->[1] . "\n";
544                 }
545                 $text .= "\n\n";        
546         }       
547
548         if ($last_text ne $text) {
549                 print "\e[H\e[2J"; # clear the screen
550                 print $text;
551                 $last_text = $text;
552         }
553 }
554
555 sub output_json {
556         my $info = $engine->{'info'};
557
558         my $json = {};
559         $json->{'position'} = $pos_calculating->to_json_hash();
560         $json->{'id'} = $engine->{'id'};
561         $json->{'score'} = long_score($info, $pos_calculating, '');
562
563         $json->{'nodes'} = $info->{'nodes'};
564         $json->{'nps'} = $info->{'nps'};
565         $json->{'depth'} = $info->{'depth'};
566         $json->{'tbhits'} = $info->{'tbhits'};
567         $json->{'seldepth'} = $info->{'seldepth'};
568
569         # single-PV only for now
570         $json->{'pv_uci'} = $info->{'pv'};
571         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
572
573         my %refutation_lines = ();
574         my @refutation_lines = ();
575         if (defined($engine2)) {
576                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
577                         my $info = $engine2->{'info'};
578                         my $pretty_move = "";
579                         my @pretty_pv = ();
580                         last if (!exists($info->{'pv' . $mpv}));
581
582                         eval {
583                                 my $pv = $info->{'pv' . $mpv};
584                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
585                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
586                                 $refutation_lines{$pv->[0]} = {
587                                         sort_key => $pretty_move,
588                                         depth => $info->{'depth' . $mpv},
589                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
590                                         pretty_score => short_score($info, $pos_calculating, $mpv, 0),
591                                         pretty_move => $pretty_move,
592                                         pv_pretty => \@pretty_pv,
593                                 };
594                                 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
595                         };
596                 }
597         }
598         $json->{'refutation_lines'} = \%refutation_lines;
599
600         open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
601                 or return;
602         print $fh JSON::XS::encode_json($json);
603         close $fh;
604         rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
605 }
606
607 sub uciprint {
608         my ($engine, $msg) = @_;
609         $engine->print($msg);
610         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
611 }
612
613 sub short_score {
614         my ($info, $pos, $mpv, $invert) = @_;
615
616         $invert //= 0;
617         if ($pos->{'toplay'} eq 'B') {
618                 $invert = !$invert;
619         }
620
621         if (defined($info->{'score_mate' . $mpv})) {
622                 if ($invert) {
623                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
624                 } else {
625                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
626                 }
627         } else {
628                 if (exists($info->{'score_cp' . $mpv})) {
629                         my $score = $info->{'score_cp' . $mpv} * 0.01;
630                         if ($score == 0) {
631                                 return " 0.00";
632                         }
633                         if ($invert) {
634                                 $score = -$score;
635                         }
636                         return sprintf "%+5.2f", $score;
637                 }
638         }
639
640         return undef;
641 }
642
643 sub score_sort_key {
644         my ($info, $pos, $mpv, $invert) = @_;
645
646         if (defined($info->{'score_mate' . $mpv})) {
647                 if ($invert) {
648                         return 99999 - $info->{'score_mate' . $mpv};
649                 } else {
650                         return -(99999 - $info->{'score_mate' . $mpv});
651                 }
652         } else {
653                 if (exists($info->{'score_cp' . $mpv})) {
654                         my $score = $info->{'score_cp' . $mpv};
655                         if ($invert) {
656                                 $score = -$score;
657                         }
658                         return $score;
659                 }
660         }
661
662         return undef;
663 }
664
665 sub long_score {
666         my ($info, $pos, $mpv) = @_;
667
668         if (defined($info->{'score_mate' . $mpv})) {
669                 my $mate = $info->{'score_mate' . $mpv};
670                 if ($pos->{'toplay'} eq 'B') {
671                         $mate = -$mate;
672                 }
673                 if ($mate > 0) {
674                         return sprintf "White mates in %u", $mate;
675                 } else {
676                         return sprintf "Black mates in %u", -$mate;
677                 }
678         } else {
679                 if (exists($info->{'score_cp' . $mpv})) {
680                         my $score = $info->{'score_cp' . $mpv} * 0.01;
681                         if ($score == 0) {
682                                 return "Score:  0.00";
683                         }
684                         if ($pos->{'toplay'} eq 'B') {
685                                 $score = -$score;
686                         }
687                         return sprintf "Score: %+5.2f", $score;
688                 }
689         }
690
691         return undef;
692 }
693
694 my %book_cache = ();
695 sub book_info {
696         my ($fen, $board, $toplay) = @_;
697
698         if (exists($book_cache{$fen})) {
699                 return $book_cache{$fen};
700         }
701
702         my $ret = `./booklook $fen`;
703         return "" if ($ret =~ /Not found/ || $ret eq '');
704
705         my @moves = ();
706
707         for my $m (split /\n/, $ret) {
708                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
709
710                 my $pmove;
711                 if ($move eq '')  {
712                         $pmove = '(current)';
713                 } else {
714                         ($pmove) = prettyprint_pv_no_cache($board, $move);
715                         $pmove .= $annotation;
716                 }
717
718                 my $score;
719                 if ($toplay eq 'W') {
720                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
721                 } else {
722                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
723                 }
724                 my $n = $win + $draw + $lose;
725                 
726                 my $percent;
727                 if ($n == 0) {
728                         $percent = "     ";
729                 } else {
730                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
731                 }
732
733                 push @moves, [ $pmove, $n, $percent, $rating ];
734         }
735
736         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
737         
738         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
739         for my $m (@moves) {
740                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
741         }
742
743         return $text;
744 }
745
746 sub open_engine {
747         my ($cmdline, $tag, $cb) = @_;
748         return undef if (!defined($cmdline));
749         return Engine->open($cmdline, $tag, $cb);
750 }
751
752 sub col_letter_to_num {
753         return ord(shift) - ord('a');
754 }
755
756 sub row_letter_to_num {
757         return 7 - (ord(shift) - ord('1'));
758 }
759
760 sub parse_uci_move {
761         my $move = shift;
762         my $from_col = col_letter_to_num(substr($move, 0, 1));
763         my $from_row = row_letter_to_num(substr($move, 1, 1));
764         my $to_col   = col_letter_to_num(substr($move, 2, 1));
765         my $to_row   = row_letter_to_num(substr($move, 3, 1));
766         my $promo    = substr($move, 4, 1);
767         return ($from_col, $from_row, $to_col, $to_row, $promo);
768 }