Maze generation: Difference between revisions
Content added Content deleted
Line 295: | Line 295: | ||
=={{header|D}}== |
=={{header|D}}== |
||
{{works with|D|2}} |
{{works with|D|2}} |
||
<lang d>import std.stdio, std.random, std.string; |
|||
enum { N = 1, S = 2, E = 4, W = 8 } |
|||
uint[][] maze; |
|||
enum DX = [E: 1, W: -1, N: 0, S: 0]; |
|||
enum DY = [E: 0, W: 0, N: -1, S: 1]; |
|||
enum INVERSE = [E: W, W: E, N: S, S: N]; |
|||
void generateMaze(int cx, int cy) { |
|||
auto directions = [N, S, E, W]; |
|||
randomShuffle(directions); |
|||
foreach (direction; directions) { |
|||
auto nx = cx + DX[direction]; |
|||
auto ny = cy + DY[direction]; |
|||
if (0 <= ny && ny < maze.length && |
|||
0 <= nx && nx < maze[0].length && maze[ny][nx] == 0) { |
|||
maze[cy][cx] |= direction; |
|||
maze[ny][nx] |= INVERSE[direction]; |
|||
generateMaze(nx, ny); |
|||
} |
|||
} |
|||
} |
|||
void printMaze() { |
|||
writeln(" " ~ repeat("_", maze[0].length * 2 - 1)); |
|||
foreach (y; 0 .. maze.length) { |
|||
write('|'); |
|||
foreach (x; 0 .. maze[0].length) { |
|||
write(((maze[y][x] & S) != 0) ? ' ' : '_'); |
|||
if ((maze[y][x] & E) != 0) |
|||
write((((maze[y][x] | maze[y][x+1]) & S) != 0) ? ' ' : '_'); |
|||
else |
|||
write('|'); |
|||
} |
|||
writeln(); |
|||
} |
|||
} |
|||
void main() { |
|||
maze = new uint[][](8, 11); |
|||
generateMaze(0, 0); |
|||
printMaze(); |
|||
}</lang> |
|||
Output: |
|||
<pre> _____________________ |
|||
|___ |_ _______ | | |
|||
| ___| _| ___ |_ | |
|||
|___ | ___| _| | | | |
|||
| _| |_ ___| _| | | |
|||
| | _| _| | |_____| |
|||
| |_ | _| | |_ _ | |
|||
| | _|_| _|_ |_| | |
|||
|_________|_________|_|</pre> |
|||
===Alternative version 1=== |
|||
<lang d>import std.stdio: write, writeln; |
<lang d>import std.stdio: write, writeln; |
||
import std.random: uniform; |
import std.random: uniform; |
||
Line 442: | Line 496: | ||
+---+---+---+---+---+---+---+---+---+---+---+</pre> |
+---+---+---+---+---+---+---+---+---+---+---+</pre> |
||
===Alternative=== |
===Alternative version 2=== |
||
See [[Maze_solving#D]] |
See [[Maze_solving#D]] |
||