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