Problem
I am trying to make a city generator for a game that creates blocks that have a type (residential, industrial, commercial). All of my streets will be at 90 degrees and there for I want it to be blocky (instead of zig zagging).
Approaches
My first approach was picking a starting point and then randomly moving around the map for X number of moves. If I hit a dead end I back tracked some random number, kind of like a maze generator but this left me with lots of areas where roads where next to roads and roads that didn't travel in straight lines. I've also looked at using perlin noise, but I believe this two would give me roads that zig zagged to often.
Current Solution
I have come up with an approach that gives me pretty much what I want but I think its more complex than it needs to be or at least less efficient than it can be. Currently if I try to scale it up to a larger map it can take a few seconds to process.
JS Fiddle
https://jsfiddle.net/jrj2211/0exe9jne/
Algorithm
- Make a 2D grid and populate with empty cells
- Get a list of all possible cells and shuffle it
- Loop through each cell in shuffled list
- Generate a randomly sized rectangle off of the cell and give it a unique ID
- Give each cell in the rectangle the unique ID
- Randomly pick its type (Residential, commercial, industrial)
- Scale the entire array up by 2
- Loop through the scaled up array and replace any tiles that have a neighboring tile with a different unique ID as a ROAD tile.
Scaling the array example (kind of like scaling an image):
[1, 2, 2] [1, 1, 2, 2, 2, 2]
[1, 3, 3] => [1, 1, 3, 3, 3 ,3]
[4, 4, 4] [4, 4, 4, 4, 4, 4]
The reason I scale up the grid is if I don't, any tile that was previously an area of 1x1 it would generate a map where two or more roads tiles would be neighbors.
Visualization
Final output
Note: This is not the same output as in the visualization
Summary
So to sum up my question, does anyone have any suggestions on how to make this more efficient or cleaner. I think its hard to write pseudo code for my current process so I think there's room for improvement. I also will have to make it even more complex to do things like removing cells that are 1x1 because no house would be surrounded by streets on all sides. I also don't want the city to be a perfect square (so I'd have to delete random zones along the border and close off their streets).