Skip to content

Instantly share code, notes, and snippets.

@gongzhitaao
Last active August 29, 2015 14:03
Show Gist options
  • Save gongzhitaao/78a12c5b26ab18299c06 to your computer and use it in GitHub Desktop.
Save gongzhitaao/78a12c5b26ab18299c06 to your computer and use it in GitHub Desktop.
Maze DFS

A maze pattern is generated by Depth-First Search (DFS) algorithm. To create more interesting/skewed maze, the probability to search for each direction, i.e. top, right, down and left is randomized. As a result sometimes it's more likely to go upward, if available, than right. This generator could be found in mazejs.

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js"></script>
<script src="https://gongzhitaao.github.io/mazejs/js/maze.js"></script>
<body>
<script>
var width = 960;
var height = 500;
var cellSize = 18;
var gridSize = 1;
var rectSize = cellSize + 2 * gridSize;
var W = width / rectSize;
var H = height / rectSize;
var g, ctx;
g = maze.generator.dfs(W, H);
// init canvas
var canvas = d3.select("body").insert("canvas", ":first-child")
.attr("width", width)
.attr("height", height);
ctx = canvas.node().getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = "#f00";
ctx.fillRect(gridSize, gridSize, cellSize, cellSize);
// `forward_rect` and `backward_rect` are needed to calculate what
// rect to fill because walls have different size than paths.
function forward_rect(c, n) {
var d = [n[0]-c[0], n[1]-c[1]];
var ret = [gridSize + rectSize * (n[1] - 1),
gridSize + rectSize * (n[0] - 1),
cellSize, cellSize]
var off = 2 * gridSize;
if (-1 === d[0])
return [ret[0], ret[1], ret[2], ret[3] + off];
else if (1 == d[1])
return [ret[0] - off, ret[1], ret[2] + off, ret[3]];
else if (1 == d[0])
return [ret[0], ret[1] - off, ret[2], ret[3] + off];
else
return [ret[0], ret[1], ret[2] + off, ret[3]];
}
function backward_rect(c, n) {
var d = [n[0] - c[0], n[1] - c[1]];
var ret = [gridSize + rectSize * (c[1] - 1),
gridSize + rectSize * (c[0] - 1),
cellSize, cellSize]
var off = 2 * gridSize;
if (-1 == d[0])
return [ret[0], ret[1] - off, ret[2], ret[3] + off];
else if (1 == d[1])
return [ret[0], ret[1], ret[2] + off, ret[3]];
else if (1 == d[0])
return [ret[0], ret[1], ret[2], ret[3] + off];
else
return [ret[0] - off, ret[1], ret[2] + off, ret[3]];
}
(function tick(){
if (!g.end()) {
var ret = g.next();
var s;
if (ret.forward) {
s = forward_rect(ret.current, ret.next);
ctx.fillStyle = "#ddd";
} else {
s = backward_rect(ret.current, ret.next);
ctx.fillStyle = "#fff";
}
if (!g.end()) {
ctx.fillRect(s[0], s[1], s[2], s[3]);
setTimeout(tick, 10);
}
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment