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