#!/usr/local/bin/perl 

%privOptions = (
	"s", "size: size of edge of field (default=8)",
	"w", "size: size of a single field (default=30)",
	"v", "handicap: number of draws (default=10)",
);

$WafeLib = $ENV{'WAFELIB'} || "/usr/lib/X11/wafe";
require "$WafeLib/perl/wafe.pl";

$size = $opt_s || 8;
$fieldWidth = $opt_w || 30;
$vorgabe = $opt_v || 10;
$totalWidth = $fieldWidth * $size;

&Xui(<<"__");
  Form f0 topLevel $backGround translations {#override
      <Key>q: exec(quit)
      <Key>r: exec(echo restart)
   }

     Label info f0 width $totalWidth $infoColors
     Form f f0 {
        width $totalWidth 
        height $totalWidth 
        defaultDistance 0 
        fromVert info
     }
   mergeResources topLevel {
     *Toggle.width $fieldWidth 
     *Toggle.height $fieldWidth 
     *Toggle.shadowWidth 2 
     *Toggle.label {}
     *Toggle.background gray
     *Toggle.callback {echo %w}
   }
__
for $i (0..$size-1) {
    for $j (0..$size-1) {
	&Xui("Toggle t$i-$j f "
	     ." horizDistance ".($i*$fieldWidth)
	     ." vertDistance  ".($j*$fieldWidth));
    }
}
&Xui("realize; deleteWindowProtocol quit");

sub Toggle {
    local($x,$y) = @_;
    &Xui("callActionProc t$x-$y {} toggle")
	unless 
	    $x < 0 || $x > $size-1 ||
	    $y < 0 || $y > $size-1 ;
}

sub report {
    &info("${size}x$size, Handicap: $vorgabe, ".
	  ($draws>0 ? "$draws Draws" : "first move"));
}

sub place {
    local($play,$x,$y) = @_;
    $draws++;
    &Toggle($x,$y) unless $play; 
    &Toggle($x+1,$y);
    &Toggle($x-1,$y);
    &Toggle($x,$y+1);
    &Toggle($x,$y-1);
}

sub start {
    srand(time|$$+$i++);
    for (1..$vorgabe) { &place(0,int(rand($size)),int(rand($size))); }
    $draws = 0;
    &info("New Game: ${size}x$size, Handicap: $vorgabe");
}

&start();
while ($_=&wafe'read) {
    &place(1,$x,$y),&report() if ($x,$y) = /^t(\d+)-(\d+)$/;
    &start() if /restart/;
}
