pattern_pdict_init(): Refresh pc when returning cached instance
[pachi.git] / tools / sgf2gtp.pl
blobc70995a16161efdac3a5dcc9fd9acaadd21db954
1 #!/usr/bin/perl -l
3 # sgf2gtp - Convert SGF game record to GTP command stream
5 # Usage: sgf2gtp [-g] [-n MOVENUM] [FILENAME]
7 # This is a naive Perl script that will convert SGF files to GTP
8 # format so that you can feed them to Pachi, insert genmove at
9 # the right places etc. Might not work on obscure SGF files,
10 # and of course there must be no variations.
12 # When called with a filename argument, it will create the output
13 # file with .gtp extension instead of .sgf.
15 # -g: Automatically append genmove command for the other color.
16 # -n MOVENUM: Output at most first MOVENUM moves.
18 use warnings;
20 my $genmove;
21 if ($ARGV[0] and $ARGV[0] eq '-g') {
22 shift @ARGV;
23 $genmove = 1;
26 my $maxmoves;
27 if ($ARGV[0] and $ARGV[0] eq '-n') {
28 shift @ARGV;
29 $maxmoves = shift @ARGV;
32 if ($ARGV[0]) {
33 open STDIN, "$ARGV[0]" or die "$ARGV[0]: $!";
34 my $ofile = $ARGV[0]; $ofile =~ s/sgf$//i; $ofile .= 'gtp';
35 open STDOUT, ">$ofile" or die "$ofile: $!";
38 local $/ = undef; my $sgf = <>;
39 my $size = ($sgf =~ /SZ\[(\d+)\]/)[0];
40 $size ||= 19;
41 $sgf =~ s/\bC\[.*?\]//gs; # no comments
42 #$sgf =~ s/\).*//gs; # cut at end of principal branch
44 print "boardsize " . $size;
45 print "clear_board";
46 if ($sgf =~ s/\bKM\[([\d.]+)\]//gs) {
47 print "komi $1";
49 if ($sgf =~ s/\bHA\[(\d+)\]//gs and $1 > 0) {
50 print "fixed_handicap $1";
53 my $abcd = "abcdefghijklmnopqrstuvwxyz";
54 my $movenum = 0;
55 my $last_color = 'w';
57 my @m = split /;/, $sgf;
58 foreach (@m) {
59 $maxmoves and $movenum >= $maxmoves and last;
61 if (/^([BW])\[\]/) {
62 $last_color = $1;
63 $movenum++;
64 print "play $1 pass";
65 next;
67 unless (/^([BW])\[(\w\w)\]/) {
68 next;
71 my ($color, $coord) = ($1, $2);
72 my ($x, $y) = split //, $coord;
73 ($x ge 'i') and $x++;
74 $y = $size - index($abcd, $y);
76 $last_color = $color;
77 $movenum++;
78 print "play $color $x$y";
81 if ($genmove) {
82 print "genmove ".(uc $last_color eq 'W' ? 'B' : 'W');