-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmaze.pl
More file actions
66 lines (59 loc) · 1.31 KB
/
maze.pl
File metadata and controls
66 lines (59 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/perl -w
# Maze generator in Perl
# Joe Wingbermuehle
# The size of the maze (must be odd).
$width = 39;
$height = 23;
@maze = ();
# Display the maze.
sub display_maze {
for (my $y = 0; $y < $height; $y++) {
for (my $x = 0; $x < $width; $x++) {
if ($maze[$y][$x] == 0) { print " " } else { print "[]" }
}
print "\n";
}
}
# Initialize the maze.
sub init_maze {
for (my $y = 0; $y < $height; $y++) {
for (my $x = 0; $x < $width; $x++) {
$maze[$y][$x] = 1;
}
}
}
# Carve the maze starting at x, y.
sub carve_maze {
my $x = shift;
my $y = shift;
$maze[$y][$x] = 0;
my $dir = int(rand(4)) % 4;
my $count = 0;
while ($count < 4) {
my $dx = 0, $dy = 0;
if ($dir == 0) { $dx = 1 }
elsif ($dir == 1) { $dy = 1 }
elsif ($dir == 2) { $dx = -1 }
else { $dy = -1 }
my $x1 = $x + $dx;
my $y1 = $y + $dy;
my $x2 = $x1 + $dx;
my $y2 = $y1 + $dy;
if ($x2 > 0 && $x2 < $width && $y2 > 0 && $y2 < $height) {
if ($maze[$y1][$x1] == 1 && $maze[$y2][$x2] == 1) {
$maze[$y1][$x1] = 0;
carve_maze($x2, $y2);
}
}
$count += 1;
$dir = ($dir + 1) % 4;
}
}
sub generate_maze {
init_maze();
carve_maze(1, 1);
$maze[0][1] = 0;
$maze[$height - 1][$width - 2] = 0;
}
generate_maze();
display_maze();