use warnings;
use strict;
my $rows = 21; # Must be odd and > 3
my $cols = 41; # Must be odd and > 3
my $cells = $rows * $cols;
my @dungeon = ('X') x $cells;
sub dAt
{
my ($x, $y) = @_;
return \$dungeon [$x + $y * $cols];
}
sub generatemap
{
my ($x, $y) = @_;
my $dirCount = 0;
my $dir = int rand (4);
while ($dirCount++ < 4)
{
$dir = 0 if $dir > 3;
my ($xInc, $yInc) = @{([0, 2], [2, 0], [0, -2], [-2, 0])[$dir]};
my ($xNew, $yNew) = ($x + $xInc, $y + $yInc);
next if $xNew < 0 || $xNew >= $cols || $yNew < 0 || $yNew >= $rows;
next if ${dAt ($xNew, $yNew)} eq '.';
${dAt ($x + $xInc / 2, $y + $yInc / 2)} = '.';
${dAt ($xNew, $yNew)} = '.';
generatemap ($xNew, $yNew);
}
continue {$dir = 0 if ++$dir > 3;}
}
sub printmap
{
my $first = 0;
while ($first < $cells)
{
print join "", @dungeon [$first..($first + $cols - 1)];
print "\n";
$first += $cols;
}
}
${dAt (1, 1)} = '.';
generatemap (1, 1); #Start in top left corner - gota go there anyway
printmap;
Perl is Huffman encoded by design.
|