Skip to content

Instantly share code, notes, and snippets.

@ebonneville
Created October 24, 2012 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebonneville/3949250 to your computer and use it in GitHub Desktop.
Save ebonneville/3949250 to your computer and use it in GitHub Desktop.
An algorithm used to handle unconnected regions of a map.
// this variable will be used to store the various unconnected caverns
var caverns = [];
// begin looping through the map
for(var x = 1; x<this.size.x; x++) {
for(var y = 1; y<this.size.y; y++) {
var cavern = [];
var totalCavern = [];
if(this.data[x][y].type != "dirty floor") {
// we've already been over this tile or it is already part of a cavern,
// no need to check it
continue;
}
cavern.push(this.data[x][y]);
totalCavern.push(this.data[x][y]);
while(cavern.length > 0) {
var n = cavern.pop();
if(n.type == "dirty floor") {
// set a flag on the tile indicating it has already been checked
n.setType("floor");
for(var i = 0; i<8; i++) {
var curTile = this.data[n.position.x + x_array[i]][n.position.y + y_array[i]];
if(curTile.type == "dirty floor") {
cavern.push(curTile);
totalCavern.push(curTile);
}
}
}
}
// add this cavern
caverns.push(totalCavern);
// sort the caverns
caverns.sort(function(a, b) {
return(b.length - a.length);
});
}
}
// remove the largest cavern, as it is the main cavern
caverns.shift();
// now that we've got the unconnected caverns, change their tile type
if(caverns.length > 0) {
for(var i = 0; i<caverns.length; i++) {
for(var j = 0; j<caverns[i].length; j++) {
caverns[i][j].setType("wall");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment