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