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.)
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
20 my $server = "freechess.org";
21 my $target = "GMCarlsen";
22 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
23 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
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 my $update_max_interval = 2.0;
28 my $second_engine_start_depth = 8;
38 $SIG{ALRM} = sub { output_screen(); };
39 my $latest_update = undef;
43 open(FICSLOG, ">ficslog.txt")
44 or die "ficslog.txt: $!";
45 print FICSLOG "Log starting.\n";
49 open(UCILOG, ">ucilog.txt")
50 or die "ucilog.txt: $!";
51 print UCILOG "Log starting.\n";
56 # open the chess engine
57 my $engine = open_engine($engine_cmdline, 'E1');
58 my $engine2 = open_engine($engine2_cmdline, 'E2');
59 my ($last_move, $last_tell);
61 my $last_told_text = '';
62 my ($pos_waiting, $pos_calculating, $move_calculating_second_engine);
63 my %refutation_moves = ();
65 uciprint($engine, "setoption name UCI_AnalyseMode value true");
66 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
67 uciprint($engine, "setoption name NalimovUsage value Rarely");
68 uciprint($engine, "setoption name Hash value 1024");
69 # uciprint($engine, "setoption name MultiPV value 2");
70 uciprint($engine, "ucinewgame");
72 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
73 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
74 uciprint($engine2, "setoption name NalimovUsage value Rarely");
75 uciprint($engine2, "setoption name Hash value 1024");
76 uciprint($engine2, "setoption name Threads value 8");
77 # uciprint($engine2, "setoption name MultiPV value 2");
78 uciprint($engine2, "ucinewgame");
80 print "Chess engine ready.\n";
83 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
84 $t->input_log(\*FICSLOG);
86 $t->print("SesseBOT");
87 $t->waitfor('/Press return to enter the server/');
91 $t->cmd("set shout 0");
92 $t->cmd("set seek 0");
93 $t->cmd("set style 12");
94 $t->cmd("observe $target");
97 print "FICS ready.\n";
101 vec($rin, fileno($engine->{'read'}), 1) = 1;
102 vec($rin, fileno($engine2->{'read'}), 1) = 1;
103 vec($rin, fileno($t), 1) = 1;
105 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
109 my $line = $t->getline(Timeout => 0, errmode => 'return');
110 last if (!defined($line));
114 if ($line =~ /^<12> /) {
115 my $pos = style12_to_pos($line);
117 # if this is already in the queue, ignore it
118 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
120 # if we're already chewing on this and there's nothing else in the queue,
122 next if (!defined($pos_waiting) && defined($pos_calculating) &&
123 $pos->{'fen'} eq $pos_calculating->{'fen'});
125 # if we're already thinking on something, stop and wait for the engine
127 if (defined($pos_calculating)) {
128 if (!defined($pos_waiting)) {
129 uciprint($engine, "stop");
131 if ($uci_assume_full_compliance) {
134 uciprint($engine, "position fen " . $pos->{'fen'});
135 uciprint($engine, "go infinite");
136 $pos_calculating = $pos;
139 # it's wrong just to give the FEN (the move history is useful,
140 # and per the UCI spec, we should really have sent "ucinewgame"),
142 uciprint($engine, "position fen " . $pos->{'fen'});
143 uciprint($engine, "go infinite");
144 $pos_calculating = $pos;
147 %refutation_moves = calculate_refutation_moves($pos);
148 if (defined($move_calculating_second_engine)) {
149 uciprint($engine2, "stop");
150 $move_calculating_second_engine = undef;
152 give_new_move_to_second_engine($pos);
155 $engine->{'info'} = {};
156 $engine2->{'info'} = {};
160 # Output a command every move to note that we're
161 # still paying attention -- this is a good tradeoff,
162 # since if no move has happened in the last half
163 # hour, the analysis/relay has most likely stopped
164 # and we should stop hogging server resources.
168 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
169 my ($who, $msg) = ($1, $2);
171 next if (grep { $_ eq $who } (@masters) == 0);
173 if ($msg =~ /^fics (.*?)$/) {
174 $t->cmd("tell $who Executing '$1' on FICS.");
176 } elsif ($msg =~ /^uci (.*?)$/) {
177 $t->cmd("tell $who Sending '$1' to the engine.");
178 print { $engine->{'write'} } "$1\n";
180 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
183 #print "FICS: [$line]\n";
187 # any fun on the UCI channel?
188 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
189 my @lines = read_lines($engine);
190 for my $line (@lines) {
191 handle_uci($engine, $line, 1);
197 if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
198 my @lines = read_lines($engine2);
199 for my $line (@lines) {
200 handle_uci($engine2, $line, 0);
211 my ($engine, $line, $primary) = @_;
215 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
216 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
217 if ($line =~ /^info/) {
218 my (@infos) = split / /, $line;
221 parse_infos($engine, @infos);
223 if ($line =~ /^id/) {
224 my (@ids) = split / /, $line;
227 parse_ids($engine, @ids);
229 if ($line =~ /^bestmove/) {
231 return if (!$uci_assume_full_compliance);
232 if (defined($pos_waiting)) {
233 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
234 uciprint($engine, "go infinite");
236 $pos_calculating = $pos_waiting;
237 $pos_waiting = undef;
240 if (defined($move_calculating_second_engine)) {
241 my $move = $refutation_moves{$move_calculating_second_engine};
242 $move->{'pv'} = $engine->{'info'}{'pv'} // $engine->{'info'}{'pv1'};
243 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
244 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
245 $move->{'toplay'} = $pos_calculating->{'toplay'};
247 give_new_move_to_second_engine($pos_waiting // $pos_calculating);
253 my ($engine, @x) = @_;
256 my $info = $engine->{'info'};
258 while (scalar @x > 0) {
259 if ($x[0] =~ 'multipv') {
264 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
266 my $value = shift @x;
267 $info->{$key} = $value;
270 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
272 my $value = shift @x;
273 $info->{$key . $mpv} = $value;
276 if ($x[0] eq 'score') {
279 delete $info->{'score_cp' . $mpv};
280 delete $info->{'score_mate' . $mpv};
282 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
285 $info->{'score_cp' . $mpv} = shift @x;
286 } elsif ($x[0] eq 'mate') {
288 $info->{'score_mate' . $mpv} = shift @x;
296 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
299 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
303 #print "unknown info '$x[0]', trying to recover...\n";
305 die "Unknown info '" . join(',', @x) . "'";
311 my ($engine, @x) = @_;
313 while (scalar @x > 0) {
314 if ($x[0] =~ /^(name|author)$/) {
316 my $value = join(' ', @x);
317 $engine->{'id'}{$key} = $value;
329 my (@x) = split / /, $str;
331 $pos{'board'} = [ @x[1..8] ];
332 $pos{'toplay'} = $x[9];
333 $pos{'ep_file_num'} = $x[10];
334 $pos{'white_castle_k'} = $x[11];
335 $pos{'white_castle_q'} = $x[12];
336 $pos{'black_castle_k'} = $x[13];
337 $pos{'black_castle_q'} = $x[14];
338 $pos{'time_to_100move_rule'} = $x[15];
339 $pos{'move_num'} = $x[26];
340 $pos{'last_move'} = $x[29];
341 $pos{'fen'} = make_fen(\%pos);
350 my (@board) = @{$pos->{'board'}};
351 for my $rank (0..7) {
352 $board[$rank] =~ s/(-+)/length($1)/ge;
354 my $fen = join('/', @board);
356 # white/black to move
358 $fen .= lc($pos->{'toplay'});
362 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
363 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
364 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
365 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
366 $castling = "-" if ($castling eq "");
367 # $castling = "-"; # chess960
373 if ($pos->{'ep_file_num'} != -1) {
374 my $col = $pos->{'ep_file_num'};
375 my $nep = (qw(a b c d e f g h))[$col];
377 if ($pos->{'toplay'} eq 'B') {
384 # Showing the en passant square when actually no capture can be made
385 # seems to confuse at least Rybka. Thus, check if there's actually
386 # a pawn of the opposite side that can do the en passant move, and if
387 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
388 # "right" thing as per the standard, though.
390 if ($pos->{'toplay'} eq 'B') {
391 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
392 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
394 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
395 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
403 $fen .= $pos->{'time_to_100move_rule'};
407 $fen .= $pos->{'move_num'};
413 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
414 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
415 my $piece = substr($board->[$from_row], $from_col, 1);
419 die "Invalid move $move";
422 # white short castling
423 if ($move eq 'e1g1' && $piece eq 'K') {
425 substr($nb[7], 4, 1, '-');
426 substr($nb[7], 6, 1, $piece);
429 substr($nb[7], 7, 1, '-');
430 substr($nb[7], 5, 1, 'R');
435 # white long castling
436 if ($move eq 'e1c1' && $piece eq 'K') {
438 substr($nb[7], 4, 1, '-');
439 substr($nb[7], 2, 1, $piece);
442 substr($nb[7], 0, 1, '-');
443 substr($nb[7], 3, 1, 'R');
448 # black short castling
449 if ($move eq 'e8g8' && $piece eq 'k') {
451 substr($nb[0], 4, 1, '-');
452 substr($nb[0], 6, 1, $piece);
455 substr($nb[0], 7, 1, '-');
456 substr($nb[0], 5, 1, 'r');
461 # black long castling
462 if ($move eq 'e8c8' && $piece eq 'k') {
464 substr($nb[0], 4, 1, '-');
465 substr($nb[0], 2, 1, $piece);
468 substr($nb[0], 0, 1, '-');
469 substr($nb[0], 3, 1, 'r');
474 # check if the from-piece is a pawn
475 if (lc($piece) eq 'p') {
477 if ($from_col != $to_col) {
479 if (substr($board->[$to_row], $to_col, 1) eq '-') {
481 substr($nb[$to_row + 1], $to_col, 1, '-');
483 substr($nb[$to_row - 1], $to_col, 1, '-');
498 substr($nb[$from_row], $from_col, 1, '-');
499 substr($nb[$to_row], $to_col, 1, $piece);
505 my ($board, @pvs) = @_;
507 if (scalar @pvs == 0 || !defined($pvs[0])) {
512 my $from_col = col_letter_to_num(substr($pv, 0, 1));
513 my $from_row = row_letter_to_num(substr($pv, 1, 1));
514 my $to_col = col_letter_to_num(substr($pv, 2, 1));
515 my $to_row = row_letter_to_num(substr($pv, 3, 1));
516 my $promo = substr($pv, 4, 1);
518 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
519 my $piece = substr($board->[$from_row], $from_col, 1);
522 die "Invalid move $pv";
525 # white short castling
526 if ($pv eq 'e1g1' && $piece eq 'K') {
527 return ('0-0', prettyprint_pv($nb, @pvs));
530 # white long castling
531 if ($pv eq 'e1c1' && $piece eq 'K') {
532 return ('0-0-0', prettyprint_pv($nb, @pvs));
535 # black short castling
536 if ($pv eq 'e8g8' && $piece eq 'k') {
537 return ('0-0', prettyprint_pv($nb, @pvs));
540 # black long castling
541 if ($pv eq 'e8c8' && $piece eq 'k') {
542 return ('0-0-0', prettyprint_pv($nb, @pvs));
547 # check if the from-piece is a pawn
548 if (lc($piece) eq 'p') {
550 if ($from_col != $to_col) {
551 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
553 $pretty = substr($pv, 2, 2);
555 if (length($pv) == 5) {
558 $pretty .= uc(substr($pv, 4, 1));
561 $piece = substr($pv, 4, 1);
563 $piece = uc(substr($pv, 4, 1));
568 $pretty = uc($piece);
570 # see how many of these pieces could go here, in all
574 next unless (substr($board->[$row], $col, 1) eq $piece);
575 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
579 # see how many of these pieces from the given row could go here
582 next unless (substr($board->[$from_row], $col, 1) eq $piece);
583 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
586 # and same for columns
589 next unless (substr($board->[$row], $from_col, 1) eq $piece);
590 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
593 # see if we need to disambiguate
594 if ($num_total > 1) {
596 $pretty .= substr($pv, 0, 1);
597 } elsif ($num_row == 1) {
598 $pretty .= substr($pv, 1, 1);
600 $pretty .= substr($pv, 0, 2);
605 if (substr($board->[$to_row], $to_col, 1) ne '-') {
609 $pretty .= substr($pv, 2, 2);
614 } elsif (in_check($nb) ne 'none') {
617 return ($pretty, prettyprint_pv($nb, @pvs));
623 return if (!defined($pos_calculating));
625 # Don't update too often.
626 my $age = Time::HiRes::tv_interval($latest_update);
627 if ($age < $update_max_interval) {
628 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
631 $latest_update = [Time::HiRes::gettimeofday];
633 my $info = $engine->{'info'};
634 my $id = $engine->{'id'};
637 # Check the PVs first. if they're invalid, just wait, as our data
638 # is most likely out of sync. This isn't a very good solution, as
639 # it can frequently miss stuff, but it's good enough for most users.
643 if (exists($info->{'pv'})) {
644 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
648 while (exists($info->{'pv' . $mpv})) {
649 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
654 $engine->{'info'} = {};
658 my $text = 'Analysis';
659 if ($pos_calculating->{'last_move'} ne 'none') {
660 if ($pos_calculating->{'toplay'} eq 'W') {
661 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
663 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
665 if (exists($id->{'name'})) {
670 if (exists($id->{'name'})) {
671 $text .= " by $id->{'name'}:\n\n";
676 return unless (exists($pos_calculating->{'board'}));
679 # Some programs _always_ report MultiPV, even with only one PV.
680 # In this case, we simply use that data as if MultiPV was never
683 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
684 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
685 if (exists($info->{$key . '1'}) && !exists($info->{$key})) {
686 $info->{$key} = $info->{$key . '1'};
691 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
694 while (exists($info->{'pv' . $mpv})) {
695 $text .= sprintf " PV%2u", $mpv;
696 my $score = short_score($info, $pos_calculating, $mpv);
697 $text .= " ($score)" if (defined($score));
700 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
701 if ($info->{'tbhits' . $mpv} == 1) {
702 $tbhits = ", 1 tbhit";
704 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
708 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
709 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
710 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
714 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
720 my $score = long_score($info, $pos_calculating, '');
721 $text .= " $score\n" if defined($score);
722 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
725 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
726 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
727 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
729 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
730 if ($info->{'tbhits'} == 1) {
731 $text .= ", one Nalimov hit";
733 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
736 if (exists($info->{'seldepth'})) {
737 $text .= sprintf " (%u selective)", $info->{'seldepth'};
742 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
744 my @refutation_lines = ();
745 for my $move (keys %refutation_moves) {
747 my $m = $refutation_moves{$move};
748 die if ($m->{'depth'} < $second_engine_start_depth);
749 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
750 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
751 if (scalar @pretty_pv > 5) {
752 @pretty_pv = @pretty_pv[0..4];
753 push @pretty_pv, "...";
755 #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
756 my $key = $pretty_move;
757 my $line = sprintf(" %-6s %6s %3s %s",
759 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
761 join(', ', @pretty_pv));
762 push @refutation_lines, [ $key, $line ];
766 if ($#refutation_lines >= 0) {
767 $text .= "Shallow search of all legal moves:\n\n";
768 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
769 $text .= $line->[1] . "\n";
774 if ($last_text ne $text) {
775 print "
\e[H
\e[2J"; # clear the screen
780 # Now construct the tell text, if any
781 return if (!defined($telltarget));
785 if (exists($id->{'name'})) {
786 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
788 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
791 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
794 while (exists($info->{'pv' . $mpv})) {
795 $tell_text .= sprintf " PV%2u", $mpv;
796 my $score = short_score($info, $pos_calculating, $mpv);
797 $tell_text .= " ($score)" if (defined($score));
799 if (exists($info->{'depth' . $mpv})) {
800 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
804 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
810 my $score = long_score($info, $pos_calculating, '');
811 $tell_text .= " $score\n" if defined($score);
812 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
813 if (exists($info->{'depth'})) {
814 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
819 # see if a new tell is called for -- it is if the delay has expired _and_
820 # this is not simply a repetition of the last one
821 if ($last_told_text ne $tell_text) {
823 for my $iv (@tell_intervals) {
824 last if ($now - $last_move < $iv);
825 next if ($last_tell - $last_move >= $iv);
827 for my $line (split /\n/, $tell_text) {
828 $t->print("tell $telltarget [$target] $line");
831 $last_told_text = $text;
841 my ($wkr, $wkc, $bkr, $bkc);
845 my $piece = substr($board->[$row], $col, 1);
847 ($wkr, $wkc) = ($row, $col);
848 } elsif ($piece eq 'k') {
849 ($bkr, $bkc) = ($row, $col);
854 return ($wkr, $wkc, $bkr, $bkc);
859 my $check = in_check($board);
860 return 0 if ($check eq 'none');
862 # try all possible moves for the side in check
865 my $piece = substr($board->[$row], $col, 1);
866 next if ($piece eq '-');
868 if ($check eq 'white') {
869 next if ($piece eq lc($piece));
871 next if ($piece eq uc($piece));
874 for my $dest_row (0..7) {
875 for my $dest_col (0..7) {
876 next if ($row == $dest_row && $col == $dest_col);
877 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
880 substr($nb[$row], $col, 1, '-');
881 substr($nb[$dest_row], $dest_col, 1, $piece);
883 my $new_check = in_check(\@nb);
884 return 0 if ($new_check ne $check && $new_check ne 'both');
890 # nothing to do; mate
896 my ($black_check, $white_check) = (0, 0);
898 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
900 # check all pieces for the possibility of threatening the two kings
903 my $piece = substr($board->[$row], $col, 1);
904 next if ($piece eq '-');
906 if (uc($piece) eq $piece) {
908 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
911 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
916 if ($black_check && $white_check) {
918 } elsif ($black_check) {
920 } elsif ($white_check) {
928 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
930 # can't eat your own piece
931 my $dest_piece = substr($board->[$to_row], $to_col, 1);
932 if ($dest_piece ne '-') {
933 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
936 if (lc($piece) eq 'k') {
937 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
939 if (lc($piece) eq 'r') {
940 return 0 unless ($from_row == $to_row || $from_col == $to_col);
942 # check that there's a clear passage
943 if ($from_row == $to_row) {
944 if ($from_col > $to_col) {
945 ($to_col, $from_col) = ($from_col, $to_col);
948 for my $c (($from_col+1)..($to_col-1)) {
949 my $middle_piece = substr($board->[$to_row], $c, 1);
950 return 0 if ($middle_piece ne '-');
955 if ($from_row > $to_row) {
956 ($to_row, $from_row) = ($from_row, $to_row);
959 for my $r (($from_row+1)..($to_row-1)) {
960 my $middle_piece = substr($board->[$r], $to_col, 1);
961 return 0 if ($middle_piece ne '-');
967 if (lc($piece) eq 'b') {
968 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
970 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
971 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
973 my $r = $from_row + $dr;
974 my $c = $from_col + $dc;
976 while ($r != $to_row) {
977 my $middle_piece = substr($board->[$r], $c, 1);
978 return 0 if ($middle_piece ne '-');
986 if (lc($piece) eq 'n') {
987 my $diff_r = abs($from_row - $to_row);
988 my $diff_c = abs($from_col - $to_col);
989 return 1 if ($diff_r == 2 && $diff_c == 1);
990 return 1 if ($diff_r == 1 && $diff_c == 2);
994 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
995 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
998 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
999 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1003 if ($piece eq 'p') {
1005 if ($to_col == $from_col && $to_row == $from_row + 1) {
1006 return ($dest_piece eq '-');
1008 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1009 my $middle_piece = substr($board->[2], $to_col, 1);
1010 return ($dest_piece eq '-' && $middle_piece eq '-');
1012 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1013 return ($dest_piece ne '-');
1017 if ($piece eq 'P') {
1019 if ($to_col == $from_col && $to_row == $from_row - 1) {
1020 return ($dest_piece eq '-');
1022 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1023 my $middle_piece = substr($board->[5], $to_col, 1);
1024 return ($dest_piece eq '-' && $middle_piece eq '-');
1026 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1027 return ($dest_piece ne '-');
1037 my ($engine, $msg) = @_;
1038 print { $engine->{'write'} } "$msg\n";
1039 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1043 my ($info, $pos, $mpv, $invert) = @_;
1046 if ($pos->{'toplay'} eq 'B') {
1050 if (defined($info->{'score_mate' . $mpv})) {
1052 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1054 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1057 if (exists($info->{'score_cp' . $mpv})) {
1058 my $score = $info->{'score_cp' . $mpv} * 0.01;
1062 return sprintf "%+5.2f", $score;
1069 sub score_sort_key {
1070 my ($info, $pos, $mpv, $invert) = @_;
1073 if ($pos->{'toplay'} eq 'B') {
1077 if (defined($info->{'score_mate' . $mpv})) {
1079 return -(99999 - $info->{'score_mate' . $mpv});
1081 return 99999 - $info->{'score_mate' . $mpv};
1084 if (exists($info->{'score_cp' . $mpv})) {
1085 my $score = $info->{'score_cp' . $mpv};
1097 my ($info, $pos, $mpv) = @_;
1099 if (defined($info->{'score_mate' . $mpv})) {
1100 my $mate = $info->{'score_mate' . $mpv};
1101 if ($pos->{'toplay'} eq 'B') {
1105 return sprintf "White mates in %u", $mate;
1107 return sprintf "Black mates in %u", -$mate;
1110 if (exists($info->{'score_cp' . $mpv})) {
1111 my $score = $info->{'score_cp' . $mpv} * 0.01;
1112 if ($pos->{'toplay'} eq 'B') {
1115 return sprintf "Score: %+5.2f", $score;
1122 my %book_cache = ();
1124 my ($fen, $board, $toplay) = @_;
1126 if (exists($book_cache{$fen})) {
1127 return $book_cache{$fen};
1130 my $ret = `./booklook $fen`;
1131 return "" if ($ret =~ /Not found/ || $ret eq '');
1135 for my $m (split /\n/, $ret) {
1136 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1140 $pmove = '(current)';
1142 ($pmove) = prettyprint_pv($board, $move);
1143 $pmove .= $annotation;
1147 if ($toplay eq 'W') {
1148 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1150 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1152 my $n = $win + $draw + $lose;
1158 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1161 push @moves, [ $pmove, $n, $percent, $rating ];
1164 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1166 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1167 for my $m (@moves) {
1168 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1175 my ($cmdline, $tag) = @_;
1176 my ($uciread, $uciwrite);
1177 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1189 uciprint($engine, "uci");
1191 # gobble the options
1192 while (<$uciread>) {
1194 handle_uci($engine, $_);
1204 # Read until we've got a full line -- if the engine sends part of
1205 # a line and then stops we're pretty much hosed, but that should
1208 while ($engine->{'readbuf'} !~ /\n/) {
1210 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1212 if (!defined($ret)) {
1213 next if ($!{EINTR});
1214 die "error in reading from the UCI engine: $!";
1215 } elsif ($ret == 0) {
1216 die "EOF from UCI engine";
1219 $engine->{'readbuf'} .= $tmp;
1224 while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1226 $line =~ tr/\r\n//d;
1232 # Find all possible legal moves.
1233 sub calculate_refutation_moves {
1235 my $board = $pos->{'board'};
1236 my %refutation_moves = ();
1237 for my $col (0..7) {
1238 for my $row (0..7) {
1239 my $piece = substr($board->[$row], $col, 1);
1241 # Check that there's a piece of the right color on this square.
1242 next if ($piece eq '-');
1243 if ($pos->{'toplay'} eq 'W') {
1244 next if ($piece ne uc($piece));
1246 next if ($piece ne lc($piece));
1249 for my $to_col (0..7) {
1250 for my $to_row (0..7) {
1251 next if ($col == $to_col && $row == $to_row);
1252 next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1254 my $promo = ""; # FIXME
1255 my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1256 my $check = in_check($nb);
1257 next if ($check eq 'both');
1258 if ($pos->{'toplay'} eq 'W') {
1259 next if ($check eq 'white');
1261 next if ($check eq 'black');
1263 my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1264 $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1269 return %refutation_moves;
1272 sub give_new_move_to_second_engine {
1275 # Find the move that's been analyzed the shortest but is most promising.
1276 # Tie-break on UCI move representation.
1277 my $best_move = undef;
1278 for my $move (sort keys %refutation_moves) {
1279 if (!defined($best_move)) {
1283 my $best = $refutation_moves{$best_move};
1284 my $this = $refutation_moves{$move};
1286 if ($this->{'depth'} < $best->{'depth'} ||
1287 ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1293 my $m = $refutation_moves{$best_move};
1295 uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1296 uciprint($engine2, "go depth " . $m->{'depth'});
1297 $move_calculating_second_engine = $best_move;
1300 sub col_letter_to_num {
1301 return ord(shift) - ord('a');
1304 sub row_letter_to_num {
1305 return 7 - (ord(shift) - ord('1'));
1308 sub move_to_uci_notation {
1309 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1311 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);