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