Maze generation: Difference between revisions

→‎{{header|D}}: Not a dept first search
(Undo revision 98188 by 79.27.12.250 (talk))
(→‎{{header|D}}: Not a dept first search)
Line 295:
=={{header|D}}==
{{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;
import std.random: uniform;
Line 358 ⟶ 304:
uint m;
}
 
 
Cell[][] buildMaze(int width, int height) {
Line 496 ⟶ 441:
+---+---+---+---+---+---+---+---+---+---+---+</pre>
 
===Alternative version 2===
See [[Maze_solving#D]]
 
Anonymous user