<< Go Back

Cave generation

Rendered in Python, explained in English

By Dany Shaanan

This is an example of a process that can be used to create 2d cave-like patterns.

Initially, a random map of black and white pixels is generated, then, the following process is used to gradually darken the darker areas, and lighten the lighter ones:

Pixels are chosen randomly, and for each we check if it has more black neighboring pixels or white ones. Whichever it is, the pixel is changed to that color. If the numbers are equal, the pixel is not changed.

The first image is the original random map. The seventh image is what we get after a little over a million pixel checks.

After one million checked pixels, it seems that we have reached an equilibrium, which means that each pixel has at least 4 neighbors of its own color - no matter how many more checks we'll run through, nothing will ever change!

Since the pixels are randomly chosen, however, it is possible that we've missed a pixel that could still be changed... Have we?

See the code here

In order to avoid the problem of pixels on the edges of the image not actually having the same amount of neighbors, we 'wrap' the image around, meaning that the pixels on the top row are considered neighbors of pixels on the bottom row, and the same holds for the right-most and left-most columns. This means that the image tiles well! See a variation of the code, used to generate the background of this page, here.