Anonymous user
Maze generation: Difference between revisions
Improved D code
(Updated D code) |
(Improved D code) |
||
Line 512:
<lang d>import std.stdio, std.string, std.random, std.algorithm;
int[][] makeMaze(
pure static nothrow int[] getCandidateNeighbors(
in int i,
in int width,
in int height) {
int[] neighbors;
const int n = i - width;
if (n >= 0 && !maze[n].length)
neighbors ~= n;
const int s = i + width;
if (s < (height * width) && !maze[s].length)
neighbors ~= s;
const int e = i + 1;
if (e >= 0 && e / width == i / width && !maze[e].length)
neighbors ~= e;
const int w = i - 1;
if (w >= 0 && w / width == i / width && !maze[w].length)
neighbors ~= w;
Line 530 ⟶ 533:
}
const int totalCells = height * width;
auto maze = new int[][](totalCells);
int currentCell = uniform(0, totalCells);
Line 537 ⟶ 540:
while (visited < totalCells) {
width, height);
if (neighbors.length) {
const int ne = neighbors[uniform(0, neighbors.length)];
maze[currentCell] ~= ne;
maze[ne] ~= currentCell;
Line 554 ⟶ 558:
}
void showMaze(/*in*/ int[][] maze,
string s1, s2;
foreach (i; 0 .. height * width) {
Line 571 ⟶ 575:
void main() {
enum int height = 8, width = 11;
showMaze(makeMaze(
}</lang>
Output example:
|