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.
21 if ($ARGV[0] and $ARGV[0] eq '-g') {
27 if ($ARGV[0] and $ARGV[0] eq '-n') {
29 $maxmoves = shift @ARGV;
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];
41 $sgf =~ s/\bC\[.*?\]//gs; # no comments
42 #$sgf =~ s/\).*//gs; # cut at end of principal branch
44 print "boardsize " . $size;
46 if ($sgf =~ s/\bKM\[([\d.]+)\]//gs) {
49 if ($sgf =~ s/\bHA\[(\d+)\]//gs and $1 > 0) {
50 print "fixed_handicap $1";
53 my $abcd = "abcdefghijklmnopqrstuvwxyz";
57 my @m = split /;/, $sgf;
59 $maxmoves and $movenum >= $maxmoves and last;
67 unless (/^([BW])\[(\w\w)\]/) {
71 my ($color, $coord) = ($1, $2);
72 my ($x, $y) = split //, $coord;
74 $y = $size - index($abcd, $y);
78 print "play $color $x$y";
82 print "genmove ".(uc $last_color eq 'W' ?
'B' : 'W');