#!/usr/bin/perl -w
###############
# slidingBlock.pl 
# implements a sliding block puzzle.  
#
##############
use strict;
use CGI;
use CGI::Carp qw( fatalsToBrowser );

# --- define globals from input parameters -----

my $cgi		 = new CGI;
my $color        = "darkred";
my $url		 = $cgi->url( -relative=>1, -query=>0 );
my $size	 = $cgi->param("size") || 5;
my $puzzlestring = $cgi->param("puzzlestring") || makePuzzleString($size);

if ( $cgi->param("Change Size") ) {
  $size = $cgi->param("sizePopUp");
  $puzzlestring = makePuzzleString($size);
}

if ( $cgi->param("Scramble") ) {
  $size = $cgi->param("sizePopUp");
  $puzzlestring = makeRandomPuzzleString($size);
}

my $puzzle       = makePuzzle($puzzlestring,$size);
my $dashindex    = index($puzzlestring,"-");
my $rowdash      = int($dashindex/$size);
my $coldash      = $dashindex % $size;

# --- subroutines -----------------------

# modify string passed by swapping two characters.
sub swapChars {
 my ($string, $n1, $n2) = @_;
 my $char1 = substr( $string, $n1, 1);
 my $char2 = substr( $string, $n2, 1);
 substr( $string, $n1, 1) = $char2;
 substr( $string, $n2, 1) = $char1;
 return $string;
}

# Same as makePuzzleString below, but 
# initialize string in a random sequence.
sub makeRandomPuzzleString{
 my ($size) = @_;
 my $nrandomswaps = 2*$size*$size;  # random pair exchanges.
 my $sizesq = $size*$size;
 my $tmpPuzzle = makePuzzleString($size);
 for (my $i=0; $i<$nrandomswaps; $i++) {
   my $first = int rand $sizesq;
   my $second = $first;
   while ($first == $second) {$second = int rand $sizesq; }
   $tmpPuzzle = swapChars($tmpPuzzle,$first,$second);
 }
 return $tmpPuzzle;
}

# Usage: $puzzleString = makePuzzleString($size);
# Returns "ABCDEFGHIKLMNO-", $size*$size chars.
sub makePuzzleString {
  my ($size) = @_;
  my $char = "A";
  my $ncells = $size * $size;
  my $puzzlestring = "";
  do { 
    $puzzlestring .= $char;
    $char++;
  } while length($puzzlestring) < ($ncells-1);
  $puzzlestring .= "-";
  return $puzzlestring;
}

# Usage: $puzzle = makePuzzle($puzzlestring);
# Returns a 2-dimensional array of chars, 
# filling in $puzzlestring left-to-right and
# top-to-bottom.
sub makePuzzle {
  my ($puzzlestring,$size) = @_;
  my $puzzle;
  # my $b = substring($puzzle,2,1);   ######### UNCOMMENT THIS TO SEE CGI::Carp do its thing.
  my $n=0;
  for (my $y=0; $y<$size; $y++) {
    for (my $x=0; $x< $size; $x++) {
      $puzzle->[$y][$x] = substr($puzzlestring,$n,1);
      $n++;
    }
  }
  return $puzzle;
}

sub swapCharsUrl {
  my ($row1,$col1,$row2,$col2) = @_;
  my $newstring = $puzzlestring;
  $newstring = swapChars($newstring, $col1+$size*$row1, $col2+$size*$row2);
  return "<a href=" . 
            $url . "?puzzlestring=" . $newstring . 
                    "&size=" . $size . 
          ">";         
}

sub tryDashAt {
  my ($row,$col,$dr,$dc) = @_;
  if (  $row+$dr eq $rowdash and $col+$dc eq $coldash ) {
    print swapCharsUrl($row,$col,$row+$dr,$col+$dc);
    print $puzzle->[$row][$col];
    print "</a>";
    return 1;
    }
  else {
    return 0;
  }
}

# --- output the web page --------------

print $cgi->header;
print $cgi->start_html(
		       -title => "A Sliding Block Puzzle",
		       -alink => $color,
		       -link  => $color,
		       -vlink => $color,
		      );
print "
 <br><br>
 <i>A Sliding Block Puzzle</i>
 <br><br>\n
      ";

print "<table border=1>\n";
for (my $row=0; $row<$size; $row++) {
  print "<tr>";
  for (my $col=0; $col<$size; $col++) {

    my $char = $puzzle->[$row][$col];
    $char = "&nbsp;" if $char eq "-";

    print "<td bgcolor=lightblue><b>";
    if    ( tryDashAt($row,$col, 0, 1 ) ) {}
    elsif ( tryDashAt($row,$col, 0,-1 ) ) {}
    elsif ( tryDashAt($row,$col, 1, 0 ) ) {}
    elsif ( tryDashAt($row,$col,-1, 0 ) ) {}
    else {
      print "<font color=$color>";
      print $char;
      print "</font>";
    }
    print "</b></td>";

  }
  print "</tr>\n";
}
print "</table>\n";

# Form pop-up and buttons to resize and scrable.
print "<hr noshade size=1>";
print $cgi->start_form;
print $cgi->popup_menu( -name    => "sizePopUp", 
			-values  => ["3","4","5"],
		        -default => $size );
print $cgi->submit("Change Size");
print $cgi->submit("Scramble");
print $cgi->end_form;

print $cgi->end_html;
exit;

__END__

=head1 NAME

slidingBlock.cgi implements the classic puzzle as a cgi webpage.

=head1 SYNOPSIS

Just point your web browser at it and let-er rip.

=head1 AUTHOR

 Jim Mahoney (mahoney@marlboro.edu)
 Marlboro College

=head1 SEE ALSO

  perl, CGI.pm

=head1 COPYRIGHT

Copyright (c) 2000 Jim Mahoney

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

=cut

