A Python implementation of the Wave Function Collapse (WFC) algorithm for procedural terrain generation. This project creates tile-based terrain maps using a constraint-based generation system that produces natural-looking, connected landscapes.
- Procedural terrain generation using the WFC algorithm
- Customizable tile rules and connection constraints
- Support for custom tilesets/spritesheets
- Contextual weighting system for natural-looking terrain patterns
- Automatic handling of tile connections and constraints
- Built-in error handling and retry mechanism for failed generations
- Python 3.x
- Pillow (PIL) library
- Clone this repository
- Install the required dependencies:
pip install -r requirements.txtRun the script directly to generate a sample terrain:
python main.pyThis will:
- Generate a 100x100 tile terrain
- Save it as
generated_terrain.png - Attempt to display the generated image
You can customize the terrain generation by modifying the parameters in main.py:
terrain_img = generate_terrain_image(
width=100, # Width in tiles
height=100, # Height in tiles
tile_size=16, # Size of each tile in pixels
spritesheet_path="tilemap_packed.png" # Path to your tileset
)- Create a PNG spritesheet with your tiles arranged in a grid
- Update the tile coordinates in the
create_simple_tileset()function - Modify tile connections and weights to control generation patterns
- Pass your spritesheet path to
generate_terrain_image()
The Wave Function Collapse algorithm works by:
- Starting with all possibilities available for each tile
- Iteratively collapsing cells to specific tiles based on:
- Local constraints (valid connections to neighbors)
- Contextual weights (terrain patterns)
- Random selection from valid options
- Propagating constraints to maintain consistency
- Continuing until all cells are determined
The implementation includes special weighting for natural features, for example:
- Mountains tend to form ranges near edges
- Water forms coherent lakes in central areas
- Forests cluster together naturally
- Shore tiles appear around water bodies
The generator produces a PNG image where each tile is rendered according to the provided tileset. If no tileset is provided, it will use a basic colored dummy tileset for testing:
- Green: Grass tiles
- Dark Green: Forest tiles
- Brown: Hill tiles
- Gray: Mountain tiles
- Blue: Water tiles
- Sand: Shore tiles
The generator includes automatic retry logic for cases where the WFC algorithm reaches a contradiction. By default, it will attempt generation up to 10 times before failing.