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 $second_engine_start_depth = 8;
37 $SIG{ALRM} = sub { output_screen(); };
41 open(FICSLOG, ">ficslog.txt")
42 or die "ficslog.txt: $!";
43 print FICSLOG "Log starting.\n";
47 open(UCILOG, ">ucilog.txt")
48 or die "ucilog.txt: $!";
49 print UCILOG "Log starting.\n";
54 # open the chess engine
55 my $engine = open_engine($engine_cmdline);
56 my $engine2 = open_engine($engine2_cmdline);
57 my ($last_move, $last_tell);
59 my $last_told_text = '';
60 my ($pos_waiting, $pos_calculating, $move_calculating_second_engine);
61 my %refutation_moves = ();
63 uciprint($engine, "setoption name UCI_AnalyseMode value true");
64 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
65 uciprint($engine, "setoption name NalimovUsage value Rarely");
66 uciprint($engine, "setoption name Hash value 1024");
67 # uciprint($engine, "setoption name MultiPV value 2");
68 uciprint($engine, "ucinewgame");
70 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
71 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
72 uciprint($engine2, "setoption name NalimovUsage value Rarely");
73 uciprint($engine2, "setoption name Hash value 1024");
74 uciprint($engine2, "setoption name Threads value 8");
75 # uciprint($engine2, "setoption name MultiPV value 2");
76 uciprint($engine2, "ucinewgame");
78 print "Chess engine ready.\n";
81 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
82 $t->input_log(\*FICSLOG);
84 $t->print("SesseBOT");
85 $t->waitfor('/Press return to enter the server/');
89 $t->cmd("set shout 0");
90 $t->cmd("set seek 0");
91 $t->cmd("set style 12");
92 $t->cmd("observe $target");
95 print "FICS ready.\n";
99 vec($rin, fileno($engine->{'read'}), 1) = 1;
100 vec($rin, fileno($engine2->{'read'}), 1) = 1;
101 vec($rin, fileno($t), 1) = 1;
103 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
107 my $line = $t->getline(Timeout => 0, errmode => 'return');
108 last if (!defined($line));
112 if ($line =~ /^<12> /) {
113 my $pos = style12_to_pos($line);
115 # if this is already in the queue, ignore it
116 next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
118 # if we're already chewing on this and there's nothing else in the queue,
120 next if (!defined($pos_waiting) && defined($pos_calculating) &&
121 $pos->{'fen'} eq $pos_calculating->{'fen'});
123 # if we're already thinking on something, stop and wait for the engine
125 if (defined($pos_calculating)) {
126 if (!defined($pos_waiting)) {
127 uciprint($engine, "stop");
129 if ($uci_assume_full_compliance) {
132 uciprint($engine, "position fen " . $pos->{'fen'});
133 uciprint($engine, "go infinite");
134 $pos_calculating = $pos;
137 # it's wrong just to give the FEN (the move history is useful,
138 # and per the UCI spec, we should really have sent "ucinewgame"),
140 uciprint($engine, "position fen " . $pos->{'fen'});
141 uciprint($engine, "go infinite");
142 $pos_calculating = $pos;
145 %refutation_moves = calculate_refutation_moves($pos);
146 if (defined($move_calculating_second_engine)) {
147 uciprint($engine2, "stop");
148 $move_calculating_second_engine = undef;
150 give_new_move_to_second_engine($pos);
153 $engine->{'info'} = {};
154 $engine2->{'info'} = {};
158 # Output a command every move to note that we're
159 # still paying attention -- this is a good tradeoff,
160 # since if no move has happened in the last half
161 # hour, the analysis/relay has most likely stopped
162 # and we should stop hogging server resources.
166 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
167 my ($who, $msg) = ($1, $2);
169 next if (grep { $_ eq $who } (@masters) == 0);
171 if ($msg =~ /^fics (.*?)$/) {
172 $t->cmd("tell $who Executing '$1' on FICS.");
174 } elsif ($msg =~ /^uci (.*?)$/) {
175 $t->cmd("tell $who Sending '$1' to the engine.");
176 print { $engine->{'write'} } "$1\n";
178 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
181 #print "FICS: [$line]\n";
185 # any fun on the UCI channel?
186 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
187 my $line = read_line($engine->{'read'});
188 handle_uci($engine, $line, 1);
191 # don't update too often
192 Time::HiRes::alarm(0.2);
194 if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
195 my $line = read_line($engine2->{'read'});
196 handle_uci($engine2, $line, 0);
199 # don't update too often
200 Time::HiRes::alarm(0.2);
207 my ($engine, $line, $primary) = @_;
211 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
212 print UCILOG localtime() . " <= $line\n";
213 if ($line =~ /^info/) {
214 my (@infos) = split / /, $line;
217 parse_infos($engine, @infos);
219 if ($line =~ /^id/) {
220 my (@ids) = split / /, $line;
223 parse_ids($engine, @ids);
225 if ($line =~ /^bestmove/) {
227 return if (!$uci_assume_full_compliance);
228 if (defined($pos_waiting)) {
229 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
230 uciprint($engine, "go infinite");
232 $pos_calculating = $pos_waiting;
233 $pos_waiting = undef;
236 if (defined($move_calculating_second_engine)) {
237 my $move = $refutation_moves{$move_calculating_second_engine};
238 $move->{'pv'} = $engine->{'info'}{'pv'};
239 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
240 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
241 $move->{'toplay'} = $pos_calculating->{'toplay'};
243 give_new_move_to_second_engine($pos_waiting // $pos_calculating);
249 my ($engine, @x) = @_;
252 my $info = $engine->{'info'};
254 while (scalar @x > 0) {
255 if ($x[0] =~ 'multipv') {
260 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
262 my $value = shift @x;
263 $info->{$key} = $value;
266 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
268 my $value = shift @x;
269 $info->{$key . $mpv} = $value;
272 if ($x[0] eq 'score') {
275 delete $info->{'score_cp' . $mpv};
276 delete $info->{'score_mate' . $mpv};
278 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
281 $info->{'score_cp' . $mpv} = shift @x;
282 } elsif ($x[0] eq 'mate') {
284 $info->{'score_mate' . $mpv} = shift @x;
292 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
295 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
299 #print "unknown info '$x[0]', trying to recover...\n";
301 die "Unknown info '" . join(',', @x) . "'";
307 my ($engine, @x) = @_;
309 while (scalar @x > 0) {
310 if ($x[0] =~ /^(name|author)$/) {
312 my $value = join(' ', @x);
313 $engine->{'id'}{$key} = $value;
325 my (@x) = split / /, $str;
327 $pos{'board'} = [ @x[1..8] ];
328 $pos{'toplay'} = $x[9];
329 $pos{'ep_file_num'} = $x[10];
330 $pos{'white_castle_k'} = $x[11];
331 $pos{'white_castle_q'} = $x[12];
332 $pos{'black_castle_k'} = $x[13];
333 $pos{'black_castle_q'} = $x[14];
334 $pos{'time_to_100move_rule'} = $x[15];
335 $pos{'move_num'} = $x[26];
336 $pos{'last_move'} = $x[29];
337 $pos{'fen'} = make_fen(\%pos);
346 my (@board) = @{$pos->{'board'}};
347 for my $rank (0..7) {
348 $board[$rank] =~ s/(-+)/length($1)/ge;
350 my $fen = join('/', @board);
352 # white/black to move
354 $fen .= lc($pos->{'toplay'});
358 $castling .= "K" if ($pos->{'white_castle_k'} == 1);
359 $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
360 $castling .= "k" if ($pos->{'black_castle_k'} == 1);
361 $castling .= "q" if ($pos->{'black_castle_q'} == 1);
362 $castling = "-" if ($castling eq "");
363 # $castling = "-"; # chess960
369 if ($pos->{'ep_file_num'} != -1) {
370 my $col = $pos->{'ep_file_num'};
371 my $nep = (qw(a b c d e f g h))[$col];
373 if ($pos->{'toplay'} eq 'B') {
380 # Showing the en passant square when actually no capture can be made
381 # seems to confuse at least Rybka. Thus, check if there's actually
382 # a pawn of the opposite side that can do the en passant move, and if
383 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
384 # "right" thing as per the standard, though.
386 if ($pos->{'toplay'} eq 'B') {
387 $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
388 $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
390 $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
391 $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
399 $fen .= $pos->{'time_to_100move_rule'};
403 $fen .= $pos->{'move_num'};
409 my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
410 my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
411 my $piece = substr($board->[$from_row], $from_col, 1);
415 die "Invalid move $move";
418 # white short castling
419 if ($move eq 'e1g1' && $piece eq 'K') {
421 substr($nb[7], 4, 1, '-');
422 substr($nb[7], 6, 1, $piece);
425 substr($nb[7], 7, 1, '-');
426 substr($nb[7], 5, 1, 'R');
431 # white long castling
432 if ($move eq 'e1c1' && $piece eq 'K') {
434 substr($nb[7], 4, 1, '-');
435 substr($nb[7], 2, 1, $piece);
438 substr($nb[7], 0, 1, '-');
439 substr($nb[7], 3, 1, 'R');
444 # black short castling
445 if ($move eq 'e8g8' && $piece eq 'k') {
447 substr($nb[0], 4, 1, '-');
448 substr($nb[0], 6, 1, $piece);
451 substr($nb[0], 7, 1, '-');
452 substr($nb[0], 5, 1, 'r');
457 # black long castling
458 if ($move eq 'e8c8' && $piece eq 'k') {
460 substr($nb[0], 4, 1, '-');
461 substr($nb[0], 2, 1, $piece);
464 substr($nb[0], 0, 1, '-');
465 substr($nb[0], 3, 1, 'r');
470 # check if the from-piece is a pawn
471 if (lc($piece) eq 'p') {
473 if ($from_col != $to_col) {
475 if (substr($board->[$to_row], $to_col, 1) eq '-') {
477 substr($nb[$to_row + 1], $to_col, 1, '-');
479 substr($nb[$to_row - 1], $to_col, 1, '-');
494 substr($nb[$from_row], $from_col, 1, '-');
495 substr($nb[$to_row], $to_col, 1, $piece);
501 my ($board, @pvs) = @_;
503 if (scalar @pvs == 0 || !defined($pvs[0])) {
508 my $from_col = col_letter_to_num(substr($pv, 0, 1));
509 my $from_row = row_letter_to_num(substr($pv, 1, 1));
510 my $to_col = col_letter_to_num(substr($pv, 2, 1));
511 my $to_row = row_letter_to_num(substr($pv, 3, 1));
512 my $promo = substr($pv, 4, 1);
514 my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
515 my $piece = substr($board->[$from_row], $from_col, 1);
518 die "Invalid move $pv";
521 # white short castling
522 if ($pv eq 'e1g1' && $piece eq 'K') {
523 return ('0-0', prettyprint_pv($nb, @pvs));
526 # white long castling
527 if ($pv eq 'e1c1' && $piece eq 'K') {
528 return ('0-0-0', prettyprint_pv($nb, @pvs));
531 # black short castling
532 if ($pv eq 'e8g8' && $piece eq 'k') {
533 return ('0-0', prettyprint_pv($nb, @pvs));
536 # black long castling
537 if ($pv eq 'e8c8' && $piece eq 'k') {
538 return ('0-0-0', prettyprint_pv($nb, @pvs));
543 # check if the from-piece is a pawn
544 if (lc($piece) eq 'p') {
546 if ($from_col != $to_col) {
547 $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
549 $pretty = substr($pv, 2, 2);
551 if (length($pv) == 5) {
554 $pretty .= uc(substr($pv, 4, 1));
557 $piece = substr($pv, 4, 1);
559 $piece = uc(substr($pv, 4, 1));
564 $pretty = uc($piece);
566 # see how many of these pieces could go here, in all
570 next unless (substr($board->[$row], $col, 1) eq $piece);
571 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
575 # see how many of these pieces from the given row could go here
578 next unless (substr($board->[$from_row], $col, 1) eq $piece);
579 ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
582 # and same for columns
585 next unless (substr($board->[$row], $from_col, 1) eq $piece);
586 ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
589 # see if we need to disambiguate
590 if ($num_total > 1) {
592 $pretty .= substr($pv, 0, 1);
593 } elsif ($num_row == 1) {
594 $pretty .= substr($pv, 1, 1);
596 $pretty .= substr($pv, 0, 2);
601 if (substr($board->[$to_row], $to_col, 1) ne '-') {
605 $pretty .= substr($pv, 2, 2);
610 } elsif (in_check($nb) ne 'none') {
613 return ($pretty, prettyprint_pv($nb, @pvs));
619 return if (!defined($pos_calculating));
621 my $info = $engine->{'info'};
622 my $id = $engine->{'id'};
625 # Check the PVs first. if they're invalid, just wait, as our data
626 # is most likely out of sync. This isn't a very good solution, as
627 # it can frequently miss stuff, but it's good enough for most users.
631 if (exists($info->{'pv'})) {
632 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
636 while (exists($info->{'pv' . $mpv})) {
637 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
642 $engine->{'info'} = {};
646 my $text = 'Analysis';
647 if ($pos_calculating->{'last_move'} ne 'none') {
648 if ($pos_calculating->{'toplay'} eq 'W') {
649 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
651 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
653 if (exists($id->{'name'})) {
658 if (exists($id->{'name'})) {
659 $text .= " by $id->{'name'}:\n\n";
664 return unless (exists($pos_calculating->{'board'}));
667 # Some programs _always_ report MultiPV, even with only one PV.
668 # In this case, we simply use that data as if MultiPV was never
671 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
672 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
673 if (exists($info->{$key . '1'}) && !exists($info->{$key})) {
674 $info->{$key} = $info->{$key . '1'};
679 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
682 while (exists($info->{'pv' . $mpv})) {
683 $text .= sprintf " PV%2u", $mpv;
684 my $score = short_score($info, $pos_calculating, $mpv);
685 $text .= " ($score)" if (defined($score));
688 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
689 if ($info->{'tbhits' . $mpv} == 1) {
690 $tbhits = ", 1 tbhit";
692 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
696 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
697 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
698 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
702 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
708 my $score = long_score($info, $pos_calculating, '');
709 $text .= " $score\n" if defined($score);
710 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
713 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
714 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
715 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
717 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
718 if ($info->{'tbhits'} == 1) {
719 $text .= ", one Nalimov hit";
721 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
724 if (exists($info->{'seldepth'})) {
725 $text .= sprintf " (%u selective)", $info->{'seldepth'};
730 #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
732 my @refutation_lines = ();
733 for my $move (keys %refutation_moves) {
735 my $m = $refutation_moves{$move};
736 next if ($m->{'depth'} < $second_engine_start_depth);
737 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
738 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
739 if (scalar @pretty_pv > 5) {
740 @pretty_pv = @pretty_pv[0..4];
741 push @pretty_pv, "...";
743 #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
744 my $key = $pretty_move;
745 my $line = sprintf(" %-6s %6s %3s %s",
747 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
749 join(', ', @pretty_pv));
750 push @refutation_lines, [ $key, $line ];
754 if ($#refutation_lines >= 0) {
755 $text .= "Shallow search of all legal moves:\n\n";
756 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
757 $text .= $line->[1] . "\n";
762 if ($last_text ne $text) {
763 print "
\e[H
\e[2J"; # clear the screen
768 # Now construct the tell text, if any
769 return if (!defined($telltarget));
773 if (exists($id->{'name'})) {
774 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
776 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
779 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
782 while (exists($info->{'pv' . $mpv})) {
783 $tell_text .= sprintf " PV%2u", $mpv;
784 my $score = short_score($info, $pos_calculating, $mpv);
785 $tell_text .= " ($score)" if (defined($score));
787 if (exists($info->{'depth' . $mpv})) {
788 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
792 $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
798 my $score = long_score($info, $pos_calculating, '');
799 $tell_text .= " $score\n" if defined($score);
800 $tell_text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
801 if (exists($info->{'depth'})) {
802 $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
807 # see if a new tell is called for -- it is if the delay has expired _and_
808 # this is not simply a repetition of the last one
809 if ($last_told_text ne $tell_text) {
811 for my $iv (@tell_intervals) {
812 last if ($now - $last_move < $iv);
813 next if ($last_tell - $last_move >= $iv);
815 for my $line (split /\n/, $tell_text) {
816 $t->print("tell $telltarget [$target] $line");
819 $last_told_text = $text;
829 my ($wkr, $wkc, $bkr, $bkc);
833 my $piece = substr($board->[$row], $col, 1);
835 ($wkr, $wkc) = ($row, $col);
836 } elsif ($piece eq 'k') {
837 ($bkr, $bkc) = ($row, $col);
842 return ($wkr, $wkc, $bkr, $bkc);
847 my $check = in_check($board);
848 return 0 if ($check eq 'none');
850 # try all possible moves for the side in check
853 my $piece = substr($board->[$row], $col, 1);
854 next if ($piece eq '-');
856 if ($check eq 'white') {
857 next if ($piece eq lc($piece));
859 next if ($piece eq uc($piece));
862 for my $dest_row (0..7) {
863 for my $dest_col (0..7) {
864 next if ($row == $dest_row && $col == $dest_col);
865 next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
868 substr($nb[$row], $col, 1, '-');
869 substr($nb[$dest_row], $dest_col, 1, $piece);
871 my $new_check = in_check(\@nb);
872 return 0 if ($new_check ne $check && $new_check ne 'both');
878 # nothing to do; mate
884 my ($black_check, $white_check) = (0, 0);
886 my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
888 # check all pieces for the possibility of threatening the two kings
891 my $piece = substr($board->[$row], $col, 1);
892 next if ($piece eq '-');
894 if (uc($piece) eq $piece) {
896 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
899 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
904 if ($black_check && $white_check) {
906 } elsif ($black_check) {
908 } elsif ($white_check) {
916 my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
918 # can't eat your own piece
919 my $dest_piece = substr($board->[$to_row], $to_col, 1);
920 if ($dest_piece ne '-') {
921 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
924 if (lc($piece) eq 'k') {
925 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
927 if (lc($piece) eq 'r') {
928 return 0 unless ($from_row == $to_row || $from_col == $to_col);
930 # check that there's a clear passage
931 if ($from_row == $to_row) {
932 if ($from_col > $to_col) {
933 ($to_col, $from_col) = ($from_col, $to_col);
936 for my $c (($from_col+1)..($to_col-1)) {
937 my $middle_piece = substr($board->[$to_row], $c, 1);
938 return 0 if ($middle_piece ne '-');
943 if ($from_row > $to_row) {
944 ($to_row, $from_row) = ($from_row, $to_row);
947 for my $r (($from_row+1)..($to_row-1)) {
948 my $middle_piece = substr($board->[$r], $to_col, 1);
949 return 0 if ($middle_piece ne '-');
955 if (lc($piece) eq 'b') {
956 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
958 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
959 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
961 my $r = $from_row + $dr;
962 my $c = $from_col + $dc;
964 while ($r != $to_row) {
965 my $middle_piece = substr($board->[$r], $c, 1);
966 return 0 if ($middle_piece ne '-');
974 if (lc($piece) eq 'n') {
975 my $diff_r = abs($from_row - $to_row);
976 my $diff_c = abs($from_col - $to_col);
977 return 1 if ($diff_r == 2 && $diff_c == 1);
978 return 1 if ($diff_r == 1 && $diff_c == 2);
982 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
983 can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
986 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
987 can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
993 if ($to_col == $from_col && $to_row == $from_row + 1) {
994 return ($dest_piece eq '-');
996 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
997 my $middle_piece = substr($board->[2], $to_col, 1);
998 return ($dest_piece eq '-' && $middle_piece eq '-');
1000 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1001 return ($dest_piece ne '-');
1005 if ($piece eq 'P') {
1007 if ($to_col == $from_col && $to_row == $from_row - 1) {
1008 return ($dest_piece eq '-');
1010 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1011 my $middle_piece = substr($board->[5], $to_col, 1);
1012 return ($dest_piece eq '-' && $middle_piece eq '-');
1014 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1015 return ($dest_piece ne '-');
1025 my ($engine, $msg) = @_;
1026 print { $engine->{'write'} } "$msg\n";
1027 print UCILOG localtime() . " => $msg\n";
1031 my ($info, $pos, $mpv, $invert) = @_;
1034 if ($pos->{'toplay'} eq 'B') {
1038 if (defined($info->{'score_mate' . $mpv})) {
1040 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1042 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1045 if (exists($info->{'score_cp' . $mpv})) {
1046 my $score = $info->{'score_cp' . $mpv} * 0.01;
1050 return sprintf "%+5.2f", $score;
1057 sub score_sort_key {
1058 my ($info, $pos, $mpv, $invert) = @_;
1061 if ($pos->{'toplay'} eq 'B') {
1065 if (defined($info->{'score_mate' . $mpv})) {
1067 return -(99999 - $info->{'score_mate' . $mpv});
1069 return 99999 - $info->{'score_mate' . $mpv};
1072 if (exists($info->{'score_cp' . $mpv})) {
1073 my $score = $info->{'score_cp' . $mpv};
1085 my ($info, $pos, $mpv) = @_;
1087 if (defined($info->{'score_mate' . $mpv})) {
1088 my $mate = $info->{'score_mate' . $mpv};
1089 if ($pos->{'toplay'} eq 'B') {
1093 return sprintf "White mates in %u", $mate;
1095 return sprintf "Black mates in %u", -$mate;
1098 if (exists($info->{'score_cp' . $mpv})) {
1099 my $score = $info->{'score_cp' . $mpv} * 0.01;
1100 if ($pos->{'toplay'} eq 'B') {
1103 return sprintf "Score: %+5.2f", $score;
1110 my %book_cache = ();
1112 my ($fen, $board, $toplay) = @_;
1114 if (exists($book_cache{$fen})) {
1115 return $book_cache{$fen};
1118 my $ret = `./booklook $fen`;
1119 return "" if ($ret =~ /Not found/ || $ret eq '');
1123 for my $m (split /\n/, $ret) {
1124 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1128 $pmove = '(current)';
1130 ($pmove) = prettyprint_pv($board, $move);
1131 $pmove .= $annotation;
1135 if ($toplay eq 'W') {
1136 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1138 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1140 my $n = $win + $draw + $lose;
1146 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1149 push @moves, [ $pmove, $n, $percent, $rating ];
1152 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1154 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1155 for my $m (@moves) {
1156 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1163 my $cmdline = shift;
1164 my ($uciread, $uciwrite);
1165 my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1175 uciprint($engine, "uci");
1177 # gobble the options
1178 while (<$uciread>) {
1180 handle_uci($engine, $_);
1190 # Read until we've got a full line -- if the engine sends part of
1191 # a line and then stops we're pretty much hosed, but that should
1195 while ($line !~ /\n/) {
1197 my $ret = sysread $fh, $tmp, 1;
1199 if (!defined($ret)) {
1200 next if ($!{EINTR});
1201 die "error in reading from the UCI engine: $!";
1202 } elsif ($ret == 0) {
1203 die "EOF from UCI engine";
1209 $line =~ tr/\r\n//d;
1213 # Find all possible legal moves.
1214 sub calculate_refutation_moves {
1216 my $board = $pos->{'board'};
1217 my %refutation_moves = ();
1218 for my $col (0..7) {
1219 for my $row (0..7) {
1220 my $piece = substr($board->[$row], $col, 1);
1222 # Check that there's a piece of the right color on this square.
1223 next if ($piece eq '-');
1224 if ($pos->{'toplay'} eq 'W') {
1225 next if ($piece ne uc($piece));
1227 next if ($piece ne lc($piece));
1230 for my $to_col (0..7) {
1231 for my $to_row (0..7) {
1232 next if ($col == $to_col && $row == $to_row);
1233 next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1235 my $promo = ""; # FIXME
1236 my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1237 my $check = in_check($nb);
1238 next if ($check eq 'both');
1239 if ($pos->{'toplay'} eq 'W') {
1240 next if ($check eq 'white');
1242 next if ($check eq 'black');
1244 my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1245 $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1250 return %refutation_moves;
1253 sub give_new_move_to_second_engine {
1256 # Find the move that's been analyzed the shortest but is most promising.
1257 # Tie-break on UCI move representation.
1258 my $best_move = undef;
1259 for my $move (sort keys %refutation_moves) {
1260 if (!defined($best_move)) {
1264 my $best = $refutation_moves{$best_move};
1265 my $this = $refutation_moves{$move};
1267 if ($this->{'depth'} < $best->{'depth'} ||
1268 ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1274 my $m = $refutation_moves{$best_move};
1276 uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1277 uciprint($engine2, "go depth " . $m->{'depth'});
1278 $move_calculating_second_engine = $best_move;
1281 sub col_letter_to_num {
1282 return ord(shift) - ord('a');
1285 sub row_letter_to_num {
1286 return 7 - (ord(shift) - ord('1'));
1289 sub move_to_uci_notation {
1290 my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1292 return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);