Jump to content

Maze generation: Difference between revisions

→‎{{header|Perl 6}}: make a bit more idiomatic
(→‎{{header|Perl 6}}: Added perl 6 solution)
(→‎{{header|Perl 6}}: make a bit more idiomatic)
Line 685:
<lang perl6>display( gen_maze( 11, 8 ) );
 
sub gen_maze ( $x_size,
next; $y_size,
$x_size,
$start_x = (^$x_size).rand.Intpick,
$y_size,
$start_y = (^$y_size).rand.Intpick )
$start_x = $x_size.rand.Int,
{
$start_y = $y_size.rand.Int
) {
my %walls;
my @maze;
for ^$y_size -> $x {
@maze[$x] = [ 1 xx $x_size];
%walls{'y'}[$x] = ['|' xx $x_size];
%walls{'x'}[$x] = ['---' xx $x_size];
}
my @stack;
my @current = ($start_y, $start_x);
while 1loop {
if my @next = get_unvisited_neighbors( @maze, @current ); {
unless @next[0]stack.definedpush: {[@current];
move( @maze, @next, @current, %walls );
@current := @next;
}
else {
last unless @stack;
@current := @stack.pop.list;
next;
}
last unless @current;
@stack.push( [@current] );
move( @maze, @next, @current, %walls );
@current = @next;
}
return %walls;
Line 718 ⟶ 716:
my ($x, $y) = @current;
my @neighbors;
@neighbors.push([ $x-1, $y ]) if ($x > 0) && and @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) && and @maze[$x][$y-1];
@neighbors.push([ $x, $y+1 ]) if ($y < +@maze[0]) &&and @maze[$x][$y+1];
return |@neighbors.roll(1) if +@neighbors;
}
 
sub move ($maze, $next, $current, $walls) {
$maze[$next[0]][$next[1]] = 0;
given ($next, $current) {
when $next[0] < $current[0] { $walls{'x'}[$next[0]][$current[1]] = ' '}
when $next[0] > $current[0] { $walls{'x'}[$current[0]][$current[1]] = ' '}
Line 736 ⟶ 734:
 
sub display ($walls) {
say '+' ~ ('---' xx $walls{'y'}[0]).join('+') ~ '+';
for ^$walls{'x'} -> $i {
say ~$walls{'y'}[$i].join(' ') ~ ' |';
say '+' ~ $walls{'x'}[$i].join('+') ~ '+';
}
}</lang>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.