Anonymous user
Maze generation: Difference between revisions
→{{header|D}}
Line 295:
=={{header|D}}==
{{works with|D|2}}
<lang d>import std.stdio
int[][] makeMaze(const int height, const int width) {
int[] getCandidateNeighbors(const int[][] maze, const int i) {
int[] neighbors;
int
if (n >= 0 && !maze[n].length)
neighbors ~= n;
int s = i + width;
if (s < (height * width) && !maze[s].length)
neighbors ~= s;
int e = i + 1;
if (e >= 0 && e / width == i / width && !maze[e].length)
int w = i
if (w >= 0 && w / width
neighbors
return
}
int totalCells = height * width;
auto maze = new
int currentCell = uniform(0, totalCells);
int visited = 1;
int[]
while (visited < totalCells) {
int[] neighbors = getCandidateNeighbors(maze, currentCell);
if (
cellstack ~= currentCell;
currentCell = ne;
visited++;
} else {
cellstack.length -= 1;
}
}
Line 389 ⟶ 339:
}
void showMaze(int[][] maze, const int height, const int width) {
string s1, s2;
foreach (i; 0 .. height * width) {
if (i % width == 0) {
writeln(s1);
writeln(s2);
s2 = "|";
}
s2 ~= (indexOf(maze[i], i + 1) != -1) ? " " : " |";
}
writeln("+", repeat("--+", width));
}
void main() {
enum int height = 8, width = 11;
showMaze(makeMaze(height, width), height, width);
}</lang>
Output example:
<pre>
+--+--+--+--+--+--+--+--+--+--+--+
| | | |
+ +--+--+ + +--+--+ + + +--+
| | | | | | | |
+ + + +--+ +--+--+ + +--+ +
| | | | | | | |
+ + +--+--+ + + + +--+ + +
| | | | | | | |
+ + + + +--+ +--+--+--+--+ +
| | | | | | | |
+ + + +--+ +--+ + +--+ +--+
| | | | | | |
+ +--+--+ + + +--+--+ +--+ +
| | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+</pre>
===Alternative version ===
See [[Maze_solving#D]]
|