Maze generation: Difference between revisions

Content added Content deleted
(Updated D code)
(Shorter first D version)
Line 807: Line 807:


=={{header|D}}==
=={{header|D}}==
{{trans|F#}}
{{trans|Python}}
<lang d>import std.stdio,std.random,std.algorithm,std.array,std.typecons;
<lang d>import std.stdio, std.algorithm, std.range, std.random,
std.string, std.typecons;


void main() {
void main() {
enum int W = 11, H = 8;
enum int w = 16, h = 8;
alias std.array.replicate R;
auto hWalls = new bool[][](W, H),
vWalls = new bool[][](W, H),
auto ver = array(map!((_){ return R(["| "], w) ~ ["|"]; })
seen = new bool[][](W, H);
(iota(h))) ~ [];
auto hor = array(map!((_){ return R(["+--"], w) ~ ["+"]; })
alias Tuple!(uint,"x", uint,"y") P;
(iota(h + 1)));
auto vis = new bool[][](h, w);


void visit(in int x, in int y) {
void walk(in int x, in int y) /*nothrow*/ {
seen[x][y] = true;
vis[y][x] = true;
P[] D = [P(x-1,y), P(x+1,y), P(x,y-1), P(x,y+1)];
alias Tuple!(uint,"x", uint,"y") P;
P[] ns = array(filter!((p){return p.x < W && p.y < H; })(D));
auto d = [P(x-1,y), P(x, y+1), P(x+1, y), P(x, y-1)];
while (ns.length) {
randomShuffle(d);
immutable n = ns[uniform(0, $)];
foreach (p; d) {
if (!seen[n.x][n.y]) {
if (p.x >= w || p.y >= h || vis[p.y][p.x]) continue;
(x != n.x ? hWalls[min(x, n.x)][y] :
if (p.x == x) hor[max(y, p.y)][x] = "+ ";
vWalls[x][min(y, n.y)]) = true;
if (p.y == y) ver[y][max(x, p.x)] = " ";
visit(n.tupleof);
walk(p.x, p.y);
}
ns = array(filter!((x){ return x != n; })(ns));
}
}
}
}
visit(uniform(0, W), uniform(0, H));


writeln("+", "--+".replicate(W));
walk(uniform(0, w), uniform(0, h));
foreach (y; 0 .. H) {
foreach (a, b; lockstep(hor, ver))
string s = "|";
writeln(join(a ~ ["\n"] ~ b));
foreach (x; 0 .. W)
s ~= hWalls[x][y] ? " " : " |";
s ~= "\n+";
foreach (x; 0 .. W)
s ~= vWalls[x][y] ? " +" : "--+";
writeln(s);
}
}</lang>
}</lang>
Output example:
Output example:
<pre>+--+--+--+--+--+--+--+--+--+--+--+
<pre>+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| | | | |
| | | | |
+ + + + + +--+--+ + + + +
+ +--+ + +--+--+ + + +--+ +--+ + +--+--+
| | | | | | | | | |
| | | | | | | | | | |
+ +--+ +--+--+ + +--+ + + +
+ + + + +--+ +--+--+ +--+--+ +--+ +--+ +
| | | | | | |
| | | | | | | |
+ +--+--+--+--+ +--+ + + +--+
+ +--+ +--+--+ +--+--+ +--+ +--+ +--+--+ +
| | | | | |
| | | | | | | | |
+ + + + +--+--+--+--+--+--+ +
+--+ +--+ +--+--+ + +--+ + +--+--+--+ + +
| | | | | |
| | | | | | | | | | |
+--+--+ + +--+--+ + + + + +
+ +--+ +--+ + + +--+ + +--+--+ + +--+ +
| | | | | | | | |
| | | | | | | |
+ + + +--+ +--+--+ + + +--+
+--+ +--+--+--+--+--+--+--+--+ +--+--+ + +--+
| | | | | | | |
| | | | | | | |
+ +--+--+ +--+ +--+--+--+ + +
+ +--+ +--+--+--+--+ + + + + +--+--+ + +
| | |
| | | | |
+--+--+--+--+--+--+--+--+--+--+--+</pre>
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+</pre>
===Alternative version ===
===Alternative version ===
See [[Maze_solving#D]]
See [[Maze_solving#D]]