The user wants Python code for procedural terrain generation using cellular automata. This usually implies generating a 2D map (like a grid of tiles) that looks like natural terrain (caves, land masses, etc.).
Cellular Automata (CA) are often used for this, specifically for generating "cave-like" or "island-like" structures. The most common algorithm is Conway's Game of Life or a variation of it (like the "4-5 rule" or smoothing iterations).
I should provide a complete, runnable script that:
Initializes a grid (random noise).
Applies cellular automata rules (smoothing).
Visualizes the result.
Since I need to show the result, I'll use matplotlib for visualization, or PIL (Pillow), or just ASCII art if external libraries are discouraged (but matplotlib is standard for this kind of task in Python). A tkinter window is also an option for "self-contained executable" feel, but matplotlib is easier to code and more robust for data visualization. Actually, the prompt asks for "program code that generates..." and often implies a visual output.
Let's stick to matplotlib or numpy + PIL. numpy makes the CA logic much faster and cleaner. If the user wants a pure Python implementation without external libraries, that's possible but slower. I will provide the numpy + matplotlib version as it's the standard "Pythonic" way to do scientific/data generation.
Algorithm steps:
Grid Initialization: Create a 2D array of 0s and 1s (or True/False). Randomly assign values based on a probability (e.g., 45% walls).
Simulation Step: Iterate through the grid. For each cell, count its neighbors (usually 8 neighbors for Moore neighborhood).
Rule: If neighbors > threshold, become Wall. Else, become Floor.
Or the specific "Cave Generation" rule often used in Roguelikes: If a cell is a wall and has 4+ wall neighbors, stay wall. If a cell is a floor and has 5+ wall neighbors, become wall.
Repetition: Repeat the simulation step for n iterations (usually 4-6).
Visualization: Display the array as an image.
Refining the Rule:
A simple "Smoothing" rule often works best for terrain.
Map: 0 = Water/Floor, 1 = Land/Wall.
Rule:
If cell is 1 (Land) and has < 2 neighbors, it erodes (becomes 0).
If cell is 0 (Water) and has > 4 land neighbors, it grows (becomes 1).
Actually, the standard "Caves" rule (which looks like terrain) is often:
Function simulation_step: Applies CA rules using convolution or slicing.
Main execution block to generate and show.
Self-Correction during thought process:
Maybe the user wants a GUI application? The prompt just says "program code". A script that saves an image or shows a plot is usually sufficient. I will stick to a script that uses matplotlib to display the map.
Optimization:
Using nested loops in Python is slow. I should use scipy.signal.convolve2d or scipy.ndimage for counting neighbors efficiently. Or just numpy slicing. Slicing is dependency-free (besides numpy) and fast enough. I'll write a function using numpy slicing to count neighbors.
Neighbor Counting Logic (Numpy):Count=Grid[0:−2,0:−2]+
This is verbose.
Alternatively, allow . It makes the code much shorter. I'll use with a kernel of ones.
I will also add comments explaining the logic so the user understands how to tweak it (e.g., changing initial fill probability or iteration count).
Final Polish:
The code should be copy-paste runnable. I will check for library imports.
Let's write the code.
python
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import convolve
# Config
WIDTH = 100
HEIGHT = 100
ITERATIONS = 10
SEED = 42
# Logic
# ...
Wait, what if the user wants a generic terrain (multiple biomes)? CA usually generates binary masks (Cave/Not Cave, Water/Land). If they want "Mountains" and "Plains", that's usually Perlin Noise. The prompt specifically asks for Cellular Automata. CA produces organic, blob-like shapes. I will stick to the binary "Land vs Water" or "Cave vs Wall" approach, as that is the definition of CA terrain generation. I can perhaps color it to look nice (Blue/Green).
I will provide two approaches in the explanation:
The basic logic.
The code implementation using numpy and matplotlib.
Let's refine the "Rule" to be a robust terrain smoother.
Standard rule: B678/S345678 (Birth if 6,7,8 neighbors / Survive if 3,4,5,6,7,8 neighbors) creates nice caves.
Or simply:
if neighbors > 4: wall else: floor (Majority rules).
Majority rules is the easiest to implement and understand for terrain smoothing.
Neighbor counting without Scipy (to reduce dependencies if user doesn't have scipy, though they likely do if they do python procgen):
Actually, scipy is heavy. I can do it with numpy only.
np.roll is an easy way to get neighbors.
Sum of 8 rolls.
Code:
total = (np.roll(grid, 1, axis=0) + ...)
That handles wrapping. For terrain, we usually want solid borders or fixed borders. scipy handles boundaries better (mode='constant'). I'll stick to scipy as it's cleaner, but mention numpy roll as an alternative. Actually, I'll just use scipy because it's the standard for this type of math. If I write the loop manually in numpy it's verbose.
Let's try to do it with just numpy slicing to be dependency-light (no scipy).
It's about 8 lines of code to count neighbors manually with array slices.
python
def count_neighbors(grid):
# Add up all the shifted grids
# Handle edges by ignoring them or assuming 0
# Let's assume 0 (water) padding for simplicity
# Actually, let's just use scipy in the solution, it's standard practice.
pass
Okay, I will use scipy for elegance but verify the logic.
Let's structure the output.
Explanation of CA in terrain.
The Python Code (using numpy, matplotlib, scipy).
Explanation of parameters to tweak.
Code check:
Input: Dimensions.
Init: np.random.choice([0, 1], size=(w, h), p=[1-fill, fill])
Loop:
k = [[1,1,1],[1,1,1],[1,1,1]]neighbor_count = convolve(grid, k, mode='constant', cval=0)birth = (neighbor_count > 4)survive = ...
Actually, the simplest smoothing rule is:
grid = (neighbor_count >= 5).astype(int) (Wait, this includes the center cell? No, kernel usually includes center).
If kernel is all 1s: sum is N+C.
If we want majority of neighbors:
If threshold is 5: N+C≥5⟹.
If , .
If , .
This creates a smoothing effect.
Let's use the "Cave" rule which is robust:
If (neighbors, not including center), set to 1.
Else set to 0.
Wait, using a kernel with a 0 in the center makes it easier.
Kernel:
1 1 1
1 0 1
1 1 1
Then is a nice aggressive smoother.
Or for smoother blobs.
Let's go with kernel including center for simplicity of code, and threshold > 4.
kernel = [[1,1,1],[1,1,1],[1,1,1]]count = convolutiongrid = (count > 4).astype(int)
This essentially turns a cell "on" if it and its neighbors are > 50% "on".
Result visualization:
Use plt.imshow with a colormap (cmap='terrain').
Double check prompt: "Python code that generates a procedural terrain map using cellular automata."
I should ensure the code runs.
Summary of Code to be provided:
python
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import convolve
# ... logic ...
I will also include a version that doesn't use scipy? No, that complicates the code. I'll assume the user can pip install scipy. It is the standard way. I will stick to one clear, high-quality solution.
Wait, I should double check if I can do neighbor counting purely in numpy efficiently without the scipy dependency, as it reduces friction for the user.
Yes, using np.roll.
But np.roll connects edges (wraps). Terrain usually shouldn't wrap (unless it's a map for a game like Civilization).
I will stick to scipy with mode='constant' as it's the most correct for maps.
Final check of the steps.
Import numpy, matplotlib, scipy.ndimage.
Define class or functions.
Generate noise.
Loop CA rules.
Plot.
Parameters to tweak:
fill_probability: Controls how much land vs water initially.
iterations: More iterations = smoother blobs.
threshold: The rule logic.
I will create a nice, commented script.
One aesthetic touch: Apply the 'terrain' colormap in matplotlib.
0 -> Water (Blue)
1 -> Land (Green)
This maps perfectly to cmap='terrain' if values are normalized or using a specific colormap. Actually terrain in mpl goes from blue (low) to green (mid) to white (high).
If data is binary 0/1, terrain might look okay (Blue for 0, Green for 1).
Or cmap='Greens_r'.
I'll just let imshow handle it or specify terrain.
Code structure:
python
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import convolve
def generate_terrain(width=100, height=100, fill_prob=0.5, iterations=10, seed=None):
# Set seed
if seed:
np.random.seed(seed)
# Init Grid
# CA Loop
# Return grid
def visualize(grid):
# Show plot
if __name__ == "__main__":
# Run
Looks good.
Here is complete, executable Python code to generate a procedural terrain map.
This script uses the "4-5" Cellular Automata rule, which is a standard algorithm for generating organic cave-like or island-like terrain structures. It uses numpy for grid manipulation, scipy for efficient neighbor counting, and matplotlib to visualize the result.
Prerequisites
You will need to install the necessary libraries if you haven't already:
bash
pip install numpy matplotlib scipy
Python Code
python
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import convolve
def generate_terrain(width=100, height=100, fill_prob=0.45, iterations=10, seed=None):
"""
Generates a 2D terrain map using Cellular Automata.
Parameters:
- width, height: Dimensions of the map.
- fill_prob: Initial probability of a cell being a "wall" (land).
- iterations: Number of smoothing passes. Higher = smoother blobs.
- seed: Random seed for reproducibility.
"""
if seed is not None:
np.random.seed(seed)
# 1. Initialize Grid with Random Noise
# 1 represents Land/Wall, 0 represents Water/Floor
grid = np.random.choice([1, 0], size=(height, width), p=[fill_prob, 1 - fill_prob])
# 2. Define the Cellular Automata Kernel (Moore Neighborhood)
# This 3x3 matrix checks the 8 surrounding neighbors plus the cell itself.
kernel = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
# 3. Iterate (Simulate)
for i in range(iterations):
# Count neighbors for every cell simultaneously using convolution
# We use mode='constant', cval=0 so edges assume water neighbors
neighbor_count = convolve(grid, kernel, mode='constant', cval=0)
# Apply Rules:
# Rule 1: If a cell has 5 or more neighbors, it becomes land (or stays land).
# Rule 2: If a cell has 4 or fewer neighbors, it becomes water.
# This specific logic (Birth: 5, Survival: 4-5) creates smooth caves.
grid = np.where(neighbor_count >= 5, 1, 0)
return grid
def visualize_terrain(grid):
"""Displays the grid using Matplotlib."""
plt.figure(figsize=(10, 10))
# Use a colormap: 'terrain' works well (Blue for low/0, Green/Brown for high/1)
# 0 = Water (Blue), 1 = Land (Green)
plt.imshow(grid, cmap='terrain', interpolation='nearest')
plt.title("Procedural Terrain (Cellular Automata)")
plt.axis('off') # Hide X/Y axis ticks
plt.show()
if __name__ == "__main__":
# Configuration
MAP_WIDTH = 150
MAP_HEIGHT = 150
SMOOTHNESS = 8 # Iterations (5-10 is usually good)
DENSITY = 0.5 # Initial noise density (0.4 - 0.5)
print("Generating terrain...")
terrain_map = generate_terrain(
width=MAP_WIDTH,
height=MAP_HEIGHT,
fill_prob=DENSITY,
iterations=SMOOTHNESS,
seed=42 # Set to None for random results every time
)
print("Visualization ready.")
visualize_terrain(terrain_map)
How it Works
Initialization: The script starts by creating a grid of random noise, where roughly 45-50% of the pixels are "Land" (1) and the rest are "Water" (0).
Convolution: Instead of looping through every pixel one by one (which is slow in Python), we use scipy.ndimage.convolve. This calculates how many "Land" neighbors every pixel has in a single operation.
The Rules: We apply a specific rule known as the B678/S345678 variation (commonly simplified to neighbors >= 5):
If a cell has 4 or fewer land neighbors, it dies (becomes water). This eats away small noise and creates lakes.
If a cell has 5 or more land neighbors, it lives (becomes land). This fills small gaps and connects islands.
Visualization: We map the final grid using matplotlib with the 'terrain' color map, which renders the 0s as ocean blue and 1s as land green.
Tweaking the Results
Make it more rugged: Decrease the SMOOTHNESS (iterations) to 3 or 4.
Make it more puddle-like: Increase DENSITY (fill_prob) to 0.55 or 0.6.
Create Islands: In the generate_terrain function, change mode='constant', cval=0 to mode='wrap'. This will make the map tile seamlessly (toroidal array).