Anonymous user
Maze generation: Difference between revisions
→First version
(→{{header|D}}: one more) |
|||
Line 296:
===First version===
{{works with|D|2}}
<lang d>import std.stdio
import std.random: uniform;
enum : uint {
struct
cell[][] maze;▼
}▼
void main() {▼
▲ build();
▲}
Cell[][] buildMaze(int width, int height) {
pure nothrow static void breakWall(ref
if (c.c == n.c) {
if (c.r < n.r) {
c.m &= ~
} else if (c.r > n.r) {
c.m &= ~
n.m &= ~SOUTH;
}
} else if (c.r == n.r) {
if (c.c < n.c) {
c.m &= ~
} else if (c.c > n.c) {
c.m &= ~
n.m &= ~EAST;
}
}
}
pure nothrow static bool deadEnd(
foreach (n; nbrs) {
if ((n.m &
return false;
}
Line 335 ⟶ 338:
}
nothrow void setNeighbors(
nbrs.length = 0;
if (c.r != 0)
nbrs ~= maze[c.c][c.r - 1]; // n
if (c.r
▲ }
if (c.r != h - 1) {▼
nbrs ~= maze[c.c][c.r + 1]; // s
if (c.c != w - 1) {▼
nbrs ~= maze[c.c + 1][c.r]; // e
}
void dig(ref
do {
n = nbrs[uniform(0, nbrs.length)];
} while ((n.m &
n.m |=
breakWall(c, n);
maze[c.c][c.r] = c;
Line 367 ⟶ 366:
// setup
maze = new
maze[c][r] =
▲ cell c = maze[uniform(0, w)][uniform(0, h)];
▲ c.m |= visited;
setNeighbors(c, nbrs);
dig(c, stack, nbrs);
// go
while (stack.length > 0) {
if (deadEnd(nbrs)) {
c = stack
stack.
setNeighbors(c, nbrs);
} else {
Line 389 ⟶ 387:
}
}
return maze;
}
maze[0][0].m &= ~north;▼
void printMaze(Cell[][] maze) {
immutable int
immutable int
if (c == w - 1) hori.put("+---+"); else hori.put("+---");▼
▲ } else {
foreach (r; 0 .. height) {
if (c == w - 1) hori.put("+ +"); else hori.put("+ ");▼
string hori,
▲ if (maze[c][r].m & east) {
vert ~= (c == 0) ? "| " : " ";
}
writeln(hori
}
foreach (c; 0 .. width)
write("+---");
writeln("+");
}
}</lang>▼
▲void main() {
printMaze(buildMaze(11, 8));
▲}</lang>
Output example:
<pre>+ +---+---+---+---+---+---+---+---+---+---+
| | | |
Line 434 ⟶ 444:
| | | |
+---+---+---+---+---+---+---+---+---+---+---+</pre>
===Second version===
{{works with|D|2.050}}
|