import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
class TerrainGenerator:
def __init__(self, width, height, seed=None):
self.width = width
self.height = height
if seed:
np.random.seed(seed)
def generate_binary_mask(self, fill_percent=0.45):
"""
Creates the initial chaos state.
1 = Land, 0 = Water.
"""
# Create random grid of 0s and 1s
grid = np.random.choice(
[0.0, 1.0],
size=(self.width, self.height),
p=[1-fill_percent, fill_percent]
)
return grid
def apply_binary_ca(self, grid, iterations=5, neighbor_threshold=4):
"""
Standard Cellular Automata specific to cave/land generation.
Rule: If a cell has > 4 neighbors, it becomes land, else water.
"""
for _ in range(iterations):
new_grid = grid.copy()
# Using roll to vectorize neighbor counting (much faster than loops)
# Sum up all 8 neighbors
total_neighbors = (
np.roll(grid, 1, axis=0) + np.roll(grid, -1, axis=0) +
np.roll(grid, 1, axis=1) + np.roll(grid, -1, axis=1) +
np.roll(grid, (1, 1), axis=(0, 1)) + np.roll(grid, (1, -1), axis=(0, 1)) +
np.roll(grid, (-1, 1), axis=(0, 1)) + np.roll(grid, (-1, -1), axis=(0, 1))
)
# Apply the 4-5 rule
# If neighbors > 4, become 1 (Land). If < 4, become 0 (Water)
new_grid[total_neighbors > neighbor_threshold] = 1.0
new_grid[total_neighbors < neighbor_threshold] = 0.0
grid = new_grid
return grid
def apply_smoothing_ca(self, grid, iterations=5):
"""
Continuous CA. Converts binary cliffs into slopes.
This acts as a box-blur filter.
"""
for _ in range(iterations):
# Sum of neighbors + self (9 cells total)
total = (
grid +
np.roll(grid, 1, axis=0) + np.roll(grid, -1, axis=0) +
np.roll(grid, 1, axis=1) + np.roll(grid, -1, axis=1) +
np.roll(grid, (1, 1), axis=(0, 1)) + np.roll(grid, (1, -1), axis=(0, 1)) +
np.roll(grid, (-1, 1), axis=(0, 1)) + np.roll(grid, (-1, -1), axis=(0, 1))
)
# Average the values
grid = total / 9.0
return grid
def normalize_map(self, grid):
"""Normalize values to be strictly between 0.0 and 1.0"""
min_val = np.min(grid)
max_val = np.max(grid)
return (grid - min_val) / (max_val - min_val)
def generate(self, binary_iters=5, smooth_iters=10):
# Step 1: Chaos
terrain = self.generate_binary_mask(fill_percent=0.48)
# Step 2: Form Continents (Binary CA)
terrain = self.apply_binary_ca(terrain, iterations=binary_iters)
# Step 3: Erode Cliffs (Smoothing CA)
terrain = self.apply_smoothing_ca(terrain, iterations=smooth_iters)
return self.normalize_map(terrain)
def visualize_terrain(grid):
plt.figure(figsize=(10, 10))
# Create a custom colormap relative to height
# Deep Water -> Water -> Sand -> Grass -> Forest -> Mountain -> Snow
colors = [
(0.0, "#1a2b5e"), # Deep Water
(0.45, "#2a5b9e"), # Shallow Water
(0.50, "#d6c98e"), # Sand (Beach)
(0.55, "#5e8c3f"), # Grass
(0.70, "#2d5e2e"), # Forest
(0.85, "#5c5c5c"), # Mountain
(1.0, "#ffffff"), # Snow
]
cmap = LinearSegmentedColormap.from_list("terrain_map", colors)
plt.imshow(grid, cmap=cmap)
plt.colorbar(label='Elevation')
plt.title("Procedural Terrain via Cellular Automata")
plt.axis('off')
plt.show()
# --- Execution ---
if __name__ == "__main__":
# Settings
WIDTH = 200
HEIGHT = 200
SEED = 42 # Change this number to get a new map
gen = TerrainGenerator(WIDTH, HEIGHT, SEED)
# Generate map
# binary_iters: Controls how "clumpy" the islands are
# smooth_iters: Controls how wide/gradual the beaches and hills are
terrain_map = gen.generate(binary_iters=4, smooth_iters=15)
# Visualize
visualize_terrain(terrain_map)