]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
2c4bb9e8247be699bbd11cc21a5fd326a6389232
[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 = "Sesse";
22 # my $engine = "/usr/games/toga2";
23 my $engine = "wine Rybkav2.3.2a.mp.w32.exe";
24 my $telltarget = undef;   # undef to be silent
25 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960);  # after each move
26
27 # Program starts here
28 $SIG{ALRM} = sub { output_screen(); };
29
30 $| = 1;
31
32 open(FICSLOG, ">ficslog.txt")
33         or die "ficslog.txt: $!";
34 print FICSLOG "Log starting.\n";
35 select(FICSLOG);
36 $| = 1;
37
38 open(UCILOG, ">ucilog.txt")
39         or die "ucilog.txt: $!";
40 print UCILOG "Log starting.\n";
41 select(UCILOG);
42 $| = 1;
43 select(STDOUT);
44
45 # open the chess engine
46 my $pid = IPC::Open2::open2(*UCIREAD, *UCIWRITE, $engine);
47 my %uciinfo = ();
48 my %uciid = ();
49 my %ficsinfo = ();
50 my ($last_move, $last_tell);
51 my $last_text = '';
52 my $last_told_text = '';
53
54 uciprint("uci");
55
56 # gobble the options
57 while (<UCIREAD>) {
58         /uciok/ && last;
59         handle_uci($_);
60 }
61
62 uciprint("setoption name UCI_AnalyseMode value true");
63 uciprint("setoption name NalimovPath value c:\\nalimov");
64 uciprint("setoption name NalimovUsage value Rarely");
65 uciprint("setoption name Hash value 1024");
66 uciprint("setoption name MultiPV value 3");
67 # uciprint("setoption name Contempt value 1000");
68 # uciprint("setoption name Outlook value Ultra Optimistic");
69 uciprint("ucinewgame");
70
71 print "Chess engine ready.\n";
72
73 # now talk to FICS
74 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
75 $t->input_log(\*FICSLOG);
76 $t->open($server);
77 $t->print("guest");
78 $t->waitfor('/Press return to enter the server/');
79 $t->cmd("");
80
81 # set some options
82 $t->cmd("set shout 0");
83 $t->cmd("set seek 0");
84 $t->cmd("set style 12");
85 $t->cmd("observe $target");
86
87 # main loop
88 print "FICS ready.\n";
89 while (1) {
90         my $rin = '';
91         my $rout;
92         vec($rin, fileno(UCIREAD), 1) = 1;
93         vec($rin, fileno($t), 1) = 1;
94
95         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
96         my $sleep = 1.0;
97
98         while (1) {
99                 my $line = $t->getline(Timeout => 0, errmode => 'return');
100                 last if (!defined($line));
101
102                 chomp $line;
103                 $line =~ tr/\r//d;
104                 if ($line =~ /^<12> /) {
105                         my $fen = style12_to_fen($line);
106                         uciprint("stop");
107                         uciprint("position fen $fen");
108                         uciprint("go infinite");
109
110                         %uciinfo = ();
111                         $last_move = time;
112
113                         # 
114                         # Output a command every move to note that we're
115                         # still paying attention -- this is a good tradeoff,
116                         # since if no move has happened in the last half
117                         # hour, the analysis/relay has most likely stopped
118                         # and we should stop hogging server resources.
119                         #
120                         $t->cmd("date");
121                 }
122                 #print "FICS: [$line]\n";
123                 $sleep = 0;
124         }
125         
126         # any fun on the UCI channel?
127         if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
128                 my $line = <UCIREAD>;
129                 handle_uci($line);
130                 $sleep = 0;
131
132                 # don't update too often
133                 Time::HiRes::alarm(0.2);
134         }
135
136         sleep $sleep;
137 }
138
139 sub handle_uci {
140         my ($line) = @_;
141
142         chomp $line;
143         $line =~ tr/\r//d;
144         print UCILOG "<= $line\n";
145         if ($line =~ /^info/) {
146                 my (@infos) = split / /, $line;
147                 shift @infos;
148
149                 parse_infos(@infos);
150         }
151         if ($line =~ /^id/) {
152                 my (@ids) = split / /, $line;
153                 shift @ids;
154
155                 parse_ids(@ids);
156         }
157 }
158
159 sub parse_infos {
160         my (@x) = @_;
161         my $mpv = '';
162
163         while (scalar @x > 0) {
164                 if ($x[0] =~ 'multipv') {
165                         shift @x;
166                         $mpv = shift @x;
167                         next;
168                 }
169                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
170                         my $key = shift @x;
171                         my $value = shift @x;
172                         $uciinfo{$key} = $value;
173                         next;
174                 }
175                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
176                         my $key = shift @x;
177                         my $value = shift @x;
178                         $uciinfo{$key . $mpv} = $value;
179                         next;
180                 }
181                 if ($x[0] eq 'score') {
182                         shift @x;
183
184                         delete $uciinfo{'score_cp' . $mpv};
185                         delete $uciinfo{'score_mate' . $mpv};
186
187                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
188                                 if ($x[0] eq 'cp') {
189                                         shift @x;
190                                         $uciinfo{'score_cp' . $mpv} = shift @x;
191                                 } elsif ($x[0] eq 'mate') {
192                                         shift @x;
193                                         $uciinfo{'score_mate' . $mpv} = shift @x;
194                                 } else {
195                                         shift @x;
196                                 }
197                         }
198                         next;
199                 }
200                 if ($x[0] eq 'pv') {
201                         $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
202                         last;
203                 }
204                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
205                         last;
206                 }
207
208                 #print "unknown info '$x[0]', trying to recover...\n";
209                 #shift @x;
210                 die "Unknown info '" . join(',', @x) . "'";
211
212         }
213 }
214
215 sub parse_ids {
216         my (@x) = @_;
217
218         while (scalar @x > 0) {
219                 if ($x[0] =~ /^(name|author)$/) {
220                         my $key = shift @x;
221                         my $value = join(' ', @x);
222                         $uciid{$key} = $value;
223                         last;
224                 }
225
226                 # unknown
227                 shift @x;
228         }
229 }
230
231 sub style12_to_fen {
232         my $str = shift; 
233         my (@x) = split / /, $str;
234         
235         $ficsinfo{'board'} = [ @x[1..8] ];
236         $ficsinfo{'toplay'} = $x[9];
237         
238         # the board itself
239         my (@board) = @x[1..8];
240         for my $rank (0..7) {
241                 $board[$rank] =~ s/(-+)/length($1)/ge;
242         }
243         my $fen = join('/', @board);
244
245         # white/black to move
246         $fen .= " ";
247         $fen .= lc($x[9]);
248
249         # castling
250         my $castling = "";
251         $castling .= "K" if ($x[11] == 1);
252         $castling .= "Q" if ($x[12] == 1);
253         $castling .= "k" if ($x[13] == 1);
254         $castling .= "q" if ($x[14] == 1);
255         $castling = "-" if ($castling eq "");
256         $fen .= " ";
257         $fen .= $castling;
258
259         # en passant
260         my $ep = "-";
261         if ($x[10] != -1) {
262                 my $col = $x[10];
263                 my $nep = (qw(a b c d e f g h))[$col];
264
265                 if ($x[9] eq 'B') {
266                         $nep .= "3";
267                 } else {
268                         $nep .= "6";
269                 }
270                 
271                 #
272                 # Showing the en passant square when actually no capture can be made
273                 # seems to confuse at least Rybka. Thus, check if there's actually
274                 # a pawn of the opposite side that can do the en passant move, and if
275                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
276                 # "right" thing as per the standard, though.
277                 #
278                 if ($x[9] eq 'B') {
279                         $ep = $nep if ($col > 0 && substr($board[4], $col-1, 1) eq 'p');
280                         $ep = $nep if ($col < 7 && substr($board[4], $col+1, 1) eq 'p');
281                 } else {
282                         $ep = $nep if ($col > 0 && substr($board[3], $col-1, 1) eq 'P');
283                         $ep = $nep if ($col < 7 && substr($board[3], $col+1, 1) eq 'P');
284                 }
285         }
286         $fen .= " ";
287         $fen .= $ep;
288
289         # half-move clock
290         $fen .= " ";
291         $fen .= $x[15];
292
293         # full-move clock
294         $fen .= " ";
295         $fen .= $x[26];
296
297         return $fen;
298 }
299
300 sub prettyprint_pv {
301         my ($board, @pvs) = @_;
302         
303         if (scalar @pvs == 0 || !defined($pvs[0])) {
304                 return ();
305         }
306         
307         my @nb = @$board;
308
309         my $pv = shift @pvs;
310         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
311         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
312         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
313         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
314
315         my $pretty;
316         my $piece = substr($board->[$from_row], $from_col, 1);
317
318         if ($piece eq '-') {
319                 die "Invalid move";
320         }
321
322         # white short castling
323         if ($pv eq 'e1g1' && $piece eq 'K') {
324                 # king
325                 substr($nb[7], 4, 1, '-');
326                 substr($nb[7], 6, 1, $piece);
327                 
328                 # rook
329                 substr($nb[7], 7, 1, '-');
330                 substr($nb[7], 5, 1, 'R');
331                                 
332                 return ('0-0', prettyprint_pv(\@nb, @pvs));
333         }
334
335         # white long castling
336         if ($pv eq 'e1c1' && $piece eq 'K') {
337                 # king
338                 substr($nb[7], 4, 1, '-');
339                 substr($nb[7], 2, 1, $piece);
340                 
341                 # rook
342                 substr($nb[7], 0, 1, '-');
343                 substr($nb[7], 3, 1, 'R');
344                                 
345                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
346         }
347
348         # black short castling
349         if ($pv eq 'e8g8' && $piece eq 'k') {
350                 # king
351                 substr($nb[0], 4, 1, '-');
352                 substr($nb[0], 6, 1, $piece);
353                 
354                 # rook
355                 substr($nb[0], 7, 1, '-');
356                 substr($nb[0], 5, 1, 'r');
357                                 
358                 return ('0-0', prettyprint_pv(\@nb, @pvs));
359         }
360
361         # black long castling
362         if ($pv eq 'e8c8' && $piece eq 'k') {
363                 # king
364                 substr($nb[0], 4, 1, '-');
365                 substr($nb[0], 2, 1, $piece);
366                 
367                 # rook
368                 substr($nb[0], 0, 1, '-');
369                 substr($nb[0], 3, 1, 'r');
370                                 
371                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
372         }
373
374         # check if the from-piece is a pawn
375         if (lc($piece) eq 'p') {
376                 # attack?
377                 if ($from_col != $to_col) {
378                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
379
380                         # en passant?
381                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
382                                 if ($piece eq 'p') {
383                                         substr($nb[$to_row + 1], $to_col, 1, '-');
384                                 } else {
385                                         substr($nb[$to_row - 1], $to_col, 1, '-');
386                                 }
387                         }
388                 } else {
389                         $pretty = substr($pv, 2, 2);
390
391                         if (length($pv) == 5) {
392                                 # promotion
393                                 $pretty .= "=";
394                                 $pretty .= uc(substr($pv, 4, 1));
395
396                                 if ($piece eq 'p') {
397                                         $piece = substr($pv, 4, 1);
398                                 } else {
399                                         $piece = uc(substr($pv, 4, 1));
400                                 }
401                         }
402                 }
403         } else {
404                 $pretty = uc($piece);
405
406                 # see how many of these pieces could go here, in all
407                 my $num_total = 0;
408                 for my $col (0..7) {
409                         for my $row (0..7) {
410                                 next unless (substr($board->[$row], $col, 1) eq $piece);
411                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
412                         }
413                 }
414
415                 # see how many of these pieces from the given row could go here
416                 my $num_row = 0;
417                 for my $col (0..7) {
418                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
419                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
420                 }
421                 
422                 # and same for columns
423                 my $num_col = 0;
424                 for my $row (0..7) {
425                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
426                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
427                 }
428                 
429                 # see if we need to disambiguate
430                 if ($num_total > 1) {
431                         if ($num_col == 1) {
432                                 $pretty .= substr($pv, 0, 1);
433                         } elsif ($num_row == 1) {
434                                 $pretty .= substr($pv, 1, 1);
435                         } else {
436                                 $pretty .= substr($pv, 0, 2);
437                         }
438                 }
439
440                 # attack?
441                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
442                         $pretty .= 'x';
443                 }
444
445                 $pretty .= substr($pv, 2, 2);
446         }
447
448         # update the board
449         substr($nb[$from_row], $from_col, 1, '-');
450         substr($nb[$to_row], $to_col, 1, $piece);
451
452         if (in_mate(\@nb)) {
453                 $pretty .= '#';
454         } elsif (in_check(\@nb) ne 'none') {
455                 $pretty .= '+';
456         }
457
458         return ($pretty, prettyprint_pv(\@nb, @pvs));
459 }
460
461 sub output_screen {
462         #return;
463
464         #
465         # Check the PVs first. if they're invalid, just wait, as our data
466         # is most likely out of sync. This isn't a very good solution, as
467         # it can frequently miss stuff, but it's good enough for most users.
468         #
469         eval {
470                 my $dummy;
471                 if (exists($uciinfo{'pv'})) {
472                         $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}});
473                 }
474         
475                 my $mpv = 1;
476                 while (exists($uciinfo{'pv' . $mpv})) {
477                         $dummy = prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}});
478                         ++$mpv;
479                 }
480         };
481         if ($@) {
482                 %uciinfo = ();
483                 return;
484         }
485
486         my $text = '';
487
488         if (exists($uciid{'name'})) {
489                 $text .= "Analysis by $uciid{'name'}:\n\n";
490         } else {
491                 $text .= "Analysis:\n\n";
492         }
493
494         return unless (exists($ficsinfo{'board'}));
495                 
496         #
497         # Some programs _always_ report MultiPV, even with only one PV.
498         # In this case, we simply use that data as if MultiPV was never
499         # specified.
500         #
501         if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
502                 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
503                         if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
504                                 $uciinfo{$key} = $uciinfo{$key . '1'};
505                         }
506                 }
507         }
508
509         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
510                 # multi-PV
511                 my $mpv = 1;
512                 while (exists($uciinfo{'pv' . $mpv})) {
513                         $text .= sprintf "  PV%2u", $mpv;
514                         my $score = short_score(\%uciinfo, \%ficsinfo, $mpv);
515                         $text .= "  ($score)" if (defined($score));
516
517                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
518                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply)",
519                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
520                         }
521
522                         $text .= ":\n";
523                         $text .= "  " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
524                         $text .= "\n";
525                         ++$mpv;
526                 }
527         } else {
528                 # single-PV
529                 my $score = long_score(\%uciinfo, \%ficsinfo, '');
530                 $text .= "  $score\n" if defined($score);
531                 $text .=  "  PV: " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
532                 $text .=  "\n";
533
534                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
535                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
536                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
537                 }
538                 if (exists($uciinfo{'tbhits'})) {
539                         $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
540                 }
541                 if (exists($uciinfo{'seldepth'})) {
542                         $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
543                 }
544                 $text .=  "\n\n";
545         }
546
547         if ($last_text ne $text) {
548                 print "\e[H\e[2J"; # clear the screen
549                 print $text;
550                 $last_text = $text;
551         }
552
553         # Now construct the tell text, if any
554         return if (!defined($telltarget));
555
556         my $tell_text = '';
557
558         if (exists($uciid{'name'})) {
559                 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
560         } else {
561                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
562         }
563
564         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
565                 # multi-PV
566                 my $mpv = 1;
567                 while (exists($uciinfo{'pv' . $mpv})) {
568                         $tell_text .= sprintf "  PV%2u", $mpv;
569                         my $score = short_score(\%uciinfo, \%ficsinfo, $mpv);
570                         $tell_text .= "  ($score)" if (defined($score));
571
572                         if (exists($uciinfo{'depth' . $mpv})) {
573                                 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
574                         }
575
576                         $tell_text .= ": ";
577                         $tell_text .= join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv' . $mpv}}));
578                         $tell_text .= "\n";
579                         ++$mpv;
580                 }
581         } else {
582                 # single-PV
583                 my $score = long_score(\%uciinfo, \%ficsinfo, '');
584                 $tell_text .= "  $score\n" if defined($score);
585                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($ficsinfo{'board'}, @{$uciinfo{'pv'}}));
586                 if (exists($uciinfo{'depth'})) {
587                         $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
588                 }
589                 $tell_text .=  "\n";
590         }
591
592         # see if a new tell is called for -- it is if the delay has expired _and_
593         # this is not simply a repetition of the last one
594         if ($last_told_text ne $tell_text) {
595                 my $now = time;
596                 for my $iv (@tell_intervals) {
597                         last if ($now - $last_move < $iv);
598                         next if ($last_tell - $last_move >= $iv);
599
600                         for my $line (split /\n/, $tell_text) {
601                                 $t->print("tell $telltarget [$target] $line");
602                         }
603
604                         $last_told_text = $text;
605                         $last_tell = $now;
606
607                         last;
608                 }
609         }
610 }
611
612 sub find_kings {
613         my $board = shift;
614         my ($wkr, $wkc, $bkr, $bkc);
615
616         for my $row (0..7) {
617                 for my $col (0..7) {
618                         my $piece = substr($board->[$row], $col, 1);
619                         if ($piece eq 'K') {
620                                 ($wkr, $wkc) = ($row, $col);
621                         } elsif ($piece eq 'k') {
622                                 ($bkr, $bkc) = ($row, $col);
623                         }
624                 }
625         }
626
627         return ($wkr, $wkc, $bkr, $bkc);
628 }
629
630 sub in_mate {
631         my $board = shift;
632         my $check = in_check($board);
633         return 0 if ($check eq 'none');
634
635         # try all possible moves for the side in check
636         for my $row (0..7) {
637                 for my $col (0..7) {
638                         my $piece = substr($board->[$row], $col, 1);
639                         next if ($piece eq '-');
640
641                         if ($check eq 'white') {
642                                 next if ($piece eq lc($piece));
643                         } else {
644                                 next if ($piece eq uc($piece));
645                         }
646
647                         for my $dest_row (0..7) {
648                                 for my $dest_col (0..7) {
649                                         next if ($row == $dest_row && $col == $dest_col);
650                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
651
652                                         my @nb = @$board;
653                                         substr($nb[$row], $col, 1, '-');
654                                         substr($nb[$dest_row], $dest_col, 1, $piece);
655
656                                         my $new_check = in_check(\@nb);
657                                         return 0 if ($new_check ne $check && $new_check ne 'both');
658                                 }
659                         }
660                 }
661         }
662
663         # nothing to do; mate
664         return 1;
665 }
666
667 sub in_check {
668         my $board = shift;
669         my ($black_check, $white_check) = (0, 0);
670
671         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
672
673         # check all pieces for the possibility of threatening the two kings
674         for my $row (0..7) {
675                 for my $col (0..7) {
676                         my $piece = substr($board->[$row], $col, 1);
677                         next if ($piece eq '-');
678                 
679                         if (uc($piece) eq $piece) {
680                                 # white piece
681                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
682                         } else {
683                                 # black piece
684                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
685                         }
686                 }
687         }
688
689         if ($black_check && $white_check) {
690                 return 'both';
691         } elsif ($black_check) {
692                 return 'black';
693         } elsif ($white_check) {
694                 return 'white';
695         } else {
696                 return 'none';
697         }
698 }
699
700 sub can_reach {
701         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
702         
703         # can't eat your own piece
704         my $dest_piece = substr($board->[$to_row], $to_col, 1);
705         if ($dest_piece ne '-') {
706                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
707         }
708
709         if (lc($piece) eq 'k') {
710                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
711         }
712         if (lc($piece) eq 'r') {
713                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
714
715                 # check that there's a clear passage
716                 if ($from_row == $to_row) {
717                         if ($from_col > $to_col) {
718                                 ($to_col, $from_col) = ($from_col, $to_col);
719                         }
720
721                         for my $c (($from_col+1)..($to_col-1)) {
722                                 my $middle_piece = substr($board->[$to_row], $c, 1);
723                                 return 0 if ($middle_piece ne '-');     
724                         }
725
726                         return 1;
727                 } else {
728                         if ($from_row > $to_row) {
729                                 ($to_row, $from_row) = ($from_row, $to_row);
730                         }
731
732                         for my $r (($from_row+1)..($to_row-1)) {
733                                 my $middle_piece = substr($board->[$r], $to_col, 1);
734                                 return 0 if ($middle_piece ne '-');     
735                         }
736
737                         return 1;
738                 }
739         }
740         if (lc($piece) eq 'b') {
741                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
742
743                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
744                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
745
746                 my $r = $from_row + $dr;
747                 my $c = $from_col + $dc;
748
749                 while ($r != $to_row) {
750                         my $middle_piece = substr($board->[$r], $c, 1);
751                         return 0 if ($middle_piece ne '-');
752                         
753                         $r += $dr;
754                         $c += $dc;
755                 }
756
757                 return 1;
758         }
759         if (lc($piece) eq 'n') {
760                 my $diff_r = abs($from_row - $to_row);
761                 my $diff_c = abs($from_col - $to_col);
762                 return 1 if ($diff_r == 2 && $diff_c == 1);
763                 return 1 if ($diff_r == 1 && $diff_c == 2);
764                 return 0;
765         }
766         if ($piece eq 'q') {
767                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
768                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
769         }
770         if ($piece eq 'Q') {
771                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
772                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
773         }
774         if ($piece eq 'p') {
775                 # black pawn
776                 if ($to_col == $from_col && $to_row == $from_row + 1) {
777                         return ($dest_piece eq '-');
778                 }
779                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
780                         return ($dest_piece ne '-');
781                 }
782                 return 0;
783         }
784         if ($piece eq 'P') {
785                 # white pawn
786                 if ($to_col == $from_col && $to_row == $from_row - 1) {
787                         return ($dest_piece eq '-');
788                 }
789                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
790                         return ($dest_piece ne '-');
791                 }
792                 return 0;
793         }
794         
795         # unknown piece
796         return 0;
797 }
798
799 sub uciprint {
800         my $msg = shift;
801         print UCIWRITE "$msg\n";
802         print UCILOG "=> $msg\n";
803 }
804
805 sub short_score {
806         my ($uciinfo, $ficsinfo, $mpv) = @_;
807
808         if (defined($uciinfo{'score_mate' . $mpv})) {
809                 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
810         } else {
811                 if (exists($uciinfo{'score_cp' . $mpv})) {
812                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
813                         if ($ficsinfo{'toplay'} eq 'B') {
814                                 $score = -$score;
815                         }
816                         return sprintf "%+5.2f", $score;
817                 }
818         }
819
820         return undef;
821 }
822
823 sub long_score {
824         my ($uciinfo, $ficsinfo, $mpv) = @_;
825
826         if (defined($uciinfo{'score_mate' . $mpv})) {
827                 my $mate = $uciinfo{'score_mate' . $mpv};
828                 if ($ficsinfo{'toplay'} eq 'B') {
829                         $mate = -$mate;
830                 }
831                 if ($mate > 0) {
832                         return sprintf "White mates in %u", $mate;
833                 } else {
834                         return sprintf "Black mates in %u", -$mate;
835                 }
836         } else {
837                 if (exists($uciinfo{'score_cp' . $mpv})) {
838                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
839                         if ($ficsinfo{'toplay'} eq 'B') {
840                                 $score = -$score;
841                         }
842                         return sprintf "Score: %+5.2f", $score;
843                 }
844         }
845
846         return undef;
847 }