Maze generation: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: Added perl 6 solution)
(→‎{{header|Perl 6}}: make a bit more idiomatic)
Line 685: Line 685:
<lang perl6>display( gen_maze( 11, 8 ) );
<lang perl6>display( gen_maze( 11, 8 ) );


sub gen_maze (
sub gen_maze ( $x_size,
$y_size,
$x_size,
$start_x = (^$x_size).pick,
$y_size,
$start_y = (^$y_size).pick )
$start_x = $x_size.rand.Int,
{
$start_y = $y_size.rand.Int
) {
my %walls;
my %walls;
my @maze;
my @maze;
for ^$y_size -> $x {
for ^$y_size -> $x {
@maze[$x] = [ 1 xx $x_size];
@maze[$x] = [ 1 xx $x_size];
%walls{'y'}[$x] = ['|' xx $x_size];
%walls{'y'}[$x] = ['|' xx $x_size];
%walls{'x'}[$x] = ['---' xx $x_size];
%walls{'x'}[$x] = ['---' xx $x_size];
}
}
my @stack;
my @stack;
my @current = ($start_y, $start_x);
my @current = $start_y, $start_x;
while 1 {
loop {
my @next = get_unvisited_neighbors( @maze, @current );
if my @next = get_unvisited_neighbors( @maze, @current ) {
unless @next[0].defined {
@stack.push: [@current];
move( @maze, @next, @current, %walls );
@current := @next;
}
else {
last unless @stack;
last unless @stack;
@current = @stack.pop.list;
@current := @stack.pop;
next;
}
}
last unless @current;
@stack.push( [@current] );
move( @maze, @next, @current, %walls );
@current = @next;
}
}
return %walls;
return %walls;
Line 718: Line 716:
my ($x, $y) = @current;
my ($x, $y) = @current;
my @neighbors;
my @neighbors;
@neighbors.push([ $x-1, $y ]) if ($x > 0) && @maze[$x-1][$y];
@neighbors.push([ $x-1, $y ]) if $x > 0 and @maze[$x-1][$y];
@neighbors.push([ $x+1, $y ]) if ($x < +@maze) && @maze[$x+1][$y];
@neighbors.push([ $x+1, $y ]) if $x < @maze and @maze[$x+1][$y];
@neighbors.push([ $x, $y-1 ]) if ($y > 0) && @maze[$x][$y-1];
@neighbors.push([ $x, $y-1 ]) if $y > 0 and @maze[$x][$y-1];
@neighbors.push([ $x, $y+1 ]) if ($y < +@maze[0]) && @maze[$x][$y+1];
@neighbors.push([ $x, $y+1 ]) if $y < @maze[0] and @maze[$x][$y+1];
return |@neighbors.roll(1) if +@neighbors;
return |@neighbors.roll(1) if @neighbors;
}
}


sub move ($maze, $next, $current, $walls) {
sub move ($maze, $next, $current, $walls) {
$maze[$next[0]][$next[1]] = 0;
$maze[$next[0]][$next[1]] = 0;
given ($next, $current) {
given () {
when $next[0] < $current[0] { $walls{'x'}[$next[0]][$current[1]] = ' '}
when $next[0] < $current[0] { $walls{'x'}[$next[0]][$current[1]] = ' '}
when $next[0] > $current[0] { $walls{'x'}[$current[0]][$current[1]] = ' '}
when $next[0] > $current[0] { $walls{'x'}[$current[0]][$current[1]] = ' '}
Line 736: Line 734:


sub display ($walls) {
sub display ($walls) {
say '+'~('---' xx $walls{'y'}[0]).join('+')~'+';
say '+' ~ ('---' xx $walls{'y'}[0]).join('+') ~ '+';
for ^$walls{'x'} -> $i {
for ^$walls{'x'} -> $i {
say ~$walls{'y'}[$i].join(' ')~' |';
say ~$walls{'y'}[$i].join(' ') ~ ' |';
say '+'~$walls{'x'}[$i].join('+')~'+';
say '+' ~ $walls{'x'}[$i].join('+') ~ '+';
}
}
}</lang>
}</lang>