Reputation: 137
I'm creating a small game and in order to generate a world, I need to add Room Objects to a World Object. My dilemma is that there needs to be a specific way of adding the Rooms, so that they all connect (i.e. no diagonals or "island" rooms). Picture below. (Ignore the colors, gray is empty space, colors are rooms)
What would be the best way of doing this? Currently I have something along the lines of
if (this.board[posx-1][posy].isOcc())
valid == true;
if (this.board[posx][posy-1].isOcc())
valid == true;
if (this.board[posx][posy+1].isOcc())
valid == true;
if (this.board[posx+1][posy].isOcc())
valid == true;
where if valid is true, it means that a Room is able to be placed there. Where this becomes an issue is in the edges, where it goes out of bounds.
I have an initial base which will place one Room in a random column on the top row of the 2D Array, so there will always be something to build off of.
Upvotes: 1
Views: 210
Reputation: 1761
Set up your "room" objects with references to their surrounding nodes for acceptable passage - i.e:
class Room {
bool isTraversable = false;
Room rooms = new Room[4]
}
Then, switch your map generator into being 2-pass, rather than just one. So, run your first generation (which may result in an invalid setup), then run a second pass over this which in short, checks if there's some sort of valid room to enter. If not, create a valid room.
So, a basic version of this would be;
hasValidPath = false;
foreach (Room r in rooms) {
if (r.isTraversable) {
hasValidPath = true;
break;
}
}
if (!hasValidPath) {
rooms[Mathf.Random(0,3)].isTraversable = true;
}
This would create a random traversable room where one of the connecting walls/blank areas are held. If you want to ensure you didn't just create "another island", run the same script over the newly traversable tile until a valid path is found.
Upvotes: 1