Spaces:
Running
Running
/** | |
* @class Recursively divided maze, http://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_division_method | |
* @augments ROT.Map | |
*/ | |
ROT.Map.DividedMaze = function(width, height) { | |
ROT.Map.call(this, width, height); | |
this._stack = []; | |
} | |
ROT.Map.DividedMaze.extend(ROT.Map); | |
ROT.Map.DividedMaze.prototype.create = function(callback) { | |
var w = this._width; | |
var h = this._height; | |
this._map = []; | |
for (var i=0;i<w;i++) { | |
this._map.push([]); | |
for (var j=0;j<h;j++) { | |
var border = (i == 0 || j == 0 || i+1 == w || j+1 == h); | |
this._map[i].push(border ? 1 : 0); | |
} | |
} | |
this._stack = [ | |
[1, 1, w-2, h-2] | |
]; | |
this._process(); | |
for (var i=0;i<w;i++) { | |
for (var j=0;j<h;j++) { | |
callback(i, j, this._map[i][j]); | |
} | |
} | |
this._map = null; | |
return this; | |
} | |
ROT.Map.DividedMaze.prototype._process = function() { | |
while (this._stack.length) { | |
var room = this._stack.shift(); /* [left, top, right, bottom] */ | |
this._partitionRoom(room); | |
} | |
} | |
ROT.Map.DividedMaze.prototype._partitionRoom = function(room) { | |
var availX = []; | |
var availY = []; | |
for (var i=room[0]+1;i<room[2];i++) { | |
var top = this._map[i][room[1]-1]; | |
var bottom = this._map[i][room[3]+1]; | |
if (top && bottom && !(i % 2)) { availX.push(i); } | |
} | |
for (var j=room[1]+1;j<room[3];j++) { | |
var left = this._map[room[0]-1][j]; | |
var right = this._map[room[2]+1][j]; | |
if (left && right && !(j % 2)) { availY.push(j); } | |
} | |
if (!availX.length || !availY.length) { return; } | |
var x = availX.random(); | |
var y = availY.random(); | |
this._map[x][y] = 1; | |
var walls = []; | |
var w = []; walls.push(w); /* left part */ | |
for (var i=room[0]; i<x; i++) { | |
this._map[i][y] = 1; | |
w.push([i, y]); | |
} | |
var w = []; walls.push(w); /* right part */ | |
for (var i=x+1; i<=room[2]; i++) { | |
this._map[i][y] = 1; | |
w.push([i, y]); | |
} | |
var w = []; walls.push(w); /* top part */ | |
for (var j=room[1]; j<y; j++) { | |
this._map[x][j] = 1; | |
w.push([x, j]); | |
} | |
var w = []; walls.push(w); /* bottom part */ | |
for (var j=y+1; j<=room[3]; j++) { | |
this._map[x][j] = 1; | |
w.push([x, j]); | |
} | |
var solid = walls.random(); | |
for (var i=0;i<walls.length;i++) { | |
var w = walls[i]; | |
if (w == solid) { continue; } | |
var hole = w.random(); | |
this._map[hole[0]][hole[1]] = 0; | |
} | |
this._stack.push([room[0], room[1], x-1, y-1]); /* left top */ | |
this._stack.push([x+1, room[1], room[2], y-1]); /* right top */ | |
this._stack.push([room[0], y+1, x-1, room[3]]); /* left bottom */ | |
this._stack.push([x+1, y+1, room[2], room[3]]); /* right bottom */ | |
} | |