Experience of implementing Cave Generator using cellular automaton
There are many algorithms of generating level maps. I wanna tell you about generating cave levels via cellular automaton
Getting started
So what actually is a cellular automaton? Simplified, cellular automaton is a grid of cells, each with one of different finite states. Cell's states are switching according to some set of rules. We will have "Wall" and "Empty" states. Initial states of cells would be chosen randomly. When generating caves usually use rules of these kind:
- "Wall" becomes "Empty" if there are less than X "Walls"
- "Empty" becomes "Wall" if there are more than Y "Walls"
Implementation
But we are here not to stare at entertaining cell's state switching forever. We can't let our map to be too full or too empty. So we need to limit our cellular automaton lifetime. I.e. we need to launch our cellular automaton only for T rounds.
Now we can characterize our automaton by three variables (X, Y, T). You can play with it (and with starting initialization) to find interesting results, but I use X = 4, Y = 4, T = 5 in Galactic Looter.
That's all? So easy?
Actually, no. The problem is that generated cave is usually disconnected. So we need to find all disconnected caves (rooms) (I use Floodfill algorithm) and connect them into one big cave. The simplest solution is to make all possible connections between rooms. But there is such problem:
As you see on the screen connection between Cave 1 and Cave 3 goes through Cave 2. We can deal with by two ways:
- Start from one of the caves, add the closest one, than add the closest one to our already connected caves from the remaining and so on. It's called Prim's algorithm.
- You can find all possible connections between rooms, find the shortest one between two caves, that are not yet connected directly or through other caves, make it, and than do it again, until there will be one big connected cave. It's called Kruskal's algorithm.
So we have connected cave. Is it all? My answer is no, because this cave is a little bit boring: it doesn't have any cycles! Walking in this cave you will never go to place, where you've already been. We can easily fix this by doing more connections on each step of Kruskal's or Prim's algorithms, e.g. 5. So, on each step we have a chance to connect already connected cave and make a cycle.
I hope, this article was helpful for you. If you first time hear about some algorithms, you can find more on next sources:
Also, I recommend you to read the book of Th.Cormen "Introduction to algorithms".
Bye!
Комментарии
Отправить комментарий