]> git.sesse.net Git - remoteglot-book/blob - www/opening-stats.pl
Fix a sort-of rare and silly castling bug.
[remoteglot-book] / www / opening-stats.pl
1 #! /usr/bin/perl
2 use strict;
3 use warnings;
4 use CGI;
5 use JSON::XS;
6 use lib '..';
7 use Position;
8 use IPC::Open2;
9
10 our %openings = ();
11 read_openings();
12
13 my $cgi = CGI->new;
14 my ($chld_out, $chld_in);
15 my $pid = IPC::Open2::open2($chld_out, $chld_in, "../binlookup", "../open.mtbl", "40");
16
17 # Root position. Basically ignore everything except the opening (and later some root game stuff).
18 my $fen = $cgi->param('fen') // 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
19 my $pos = Position->from_fen($fen);
20 my $hex = unpack('H*', $pos->bitpacked_fen);
21 print $chld_in $hex, "\n";
22 chomp (my $line = <$chld_out>);
23
24 my ($white, $draw, $black, $opening_num, $white_avg_elo, $black_avg_elo, $num_elo, $timestamp, @moves) = split / /, $line;
25 my $opening = $openings{$opening_num} // 'A00: Start position';
26
27 # Explore one move out.
28 my @json_moves = ();
29 for my $move (@moves) {
30         my ($np, $uci_move) = $pos->make_pretty_move($move);
31         my $hex = unpack('H*', $np->bitpacked_fen);
32         print $chld_in $hex, "\n";
33         my $line = <$chld_out>;
34         my ($white, $draw, $black, $opening_num, $white_avg_elo, $black_avg_elo, $num_elo) = split / /, $line;
35         push @json_moves, {
36                 move => $move,
37                 white => $white * 1,
38                 draw => $draw * 1,
39                 black => $black * 1,
40                 white_avg_elo => $white_avg_elo * 1,
41                 black_avg_elo => $black_avg_elo * 1,
42                 num_elo => $num_elo * 1
43         };
44 }
45
46 print $cgi->header(-type=>'application/json');
47 print JSON::XS::encode_json({ moves => \@json_moves, opening => $opening });
48
49 sub num {
50         my $x = shift;
51         return $x->{'white'} + $x->{'draw'} + $x->{'black'};
52 }
53
54 sub read_openings {
55         open my $fh, "../openings.txt"
56                 or die "../openings.txt: $!";
57         for my $line (<$fh>) {
58                 chomp $line;
59                 my ($hash, $eco, $opening, $variation, $subvariation) = split /\t/, $line;
60                 if ($variation eq '') {
61                         $openings{$hash} = $eco . ": " . $opening;
62                 } else {
63                         $openings{$hash} = $eco . ": " . $opening . ": " . $variation;
64                 }
65         }
66         close $fh;
67 }