Dungeon Generator
Uses BSP.
by Sonal Pinto
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/phaser/2.0.2/phaser.min.js"></script>
<div id="phaserCanvas"></div>
JavaScript
//~~~~~~~~~~~~~~~~~~~~
// Dungeon Mapper
//~~~~~~~~~~~~~~~~~~~~
// Random Plus!
function randPlus(low, high) {
return Math.floor((Math.random() * (high - low)) + low);
}
// Main Dungeon object
var Dungeon = {
map: null,
map_size: null,
rooms: [],
stats: null,
tree: [],
stack: [],
gid: 1,
minRoomSize: 5,
minSizeFactor: 0.3,
clear: function () {
this.map_size = null;
this.map = [];
this.rooms = [];
this.corridors = [];
this.stats = {};
this.drooms = [];
this.tree = {};
this.stack = [];
this.gid = 1;
},
generate: function (size) {
this.clear();
this.map_size = size;
// init the map array to null
for (var x = 0; x < this.map_size; x++) {
this.map[x] = [];
for (var y = 0; y < this.map_size; y++) {
this.map[x][y] = 0;
}
}
// First generate a BSP tree of the dungeon (Kinda looks like fractals)
// Algo - http://doryen.eptalys.net/articles/bsp-dungeon-generation/
var X = 1;
var Y = 1;
var W = this.map_size - 2;
var H = this.map_size - 2;
// Root Node
var rootBox = {};
rootBox.x = X;
rootBox.y = Y;
rootBox.w = W;
rootBox.h = H;
this.tree[this.gid] = rootBox;
this.gid++;
// Build Tree
this.buildTree(1);
// Next, build rooms in the leaf nodes of the tree
for (var nodeID in this.tree) {
var node = this.tree[nodeID];
if (node.hasOwnProperty("L")) {
continue;
}
var room = {};
room.w = randPlus(this.minRoomSize, node.w);
room.h = randPlus(this.minRoomSize, node.h);
room.x = node.x + Math.floor((node.w - room.w) / 2);
room.y = node.y + Math.floor((node.h - room.h) / 2);
room.center = {};
...