import random
def generate_terrain(width=80, height=40, iterations=8, wall_prob=0.45, smooth_iterations=1):
"""
Generates a procedural 2D terrain map using cellular automata.
This uses a cave-generation style CA algorithm, which produces natural-looking
terrain clusters (e.g., mountains/land as '#' and valleys/water as ' ').
Args:
width (int): Width of the map.
height (int): Height of the map.
iterations (int): Number of CA iterations for generation.
wall_prob (float): Initial probability of a cell being a wall ('#').
smooth_iterations (int): Additional smoothing passes.
Returns:
list of lists: The generated terrain grid (1 = wall/land, 0 = floor/water).
"""
# Initialize random grid: 1 = wall (land/mountain), 0 = floor (water/valley)
grid = [[1 if random.random() < wall_prob else 0 for _ in range(width)] for _ in range(height)]
def count_neighbors(x, y):
"""Count Moore neighborhood (8 surrounding cells, excluding self)."""
count = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
nx, ny = x + dx, y + dy
if 0 <= nx < height and 0 <= ny < width:
count += grid[nx][ny]
return count
# CA rules for natural cave/terrain formation:
# - Floor (0) becomes wall if >=5 wall neighbors (filling in isolated floors).
# - Wall (1) becomes floor if <4 wall neighbors (eroding isolated walls).
for _ in range(iterations):
new_grid = [row[:] for row in grid]
for i in range(height):
for j in range(width):
neighbors = count_neighbors(i, j)
if grid[i][j] == 0 and neighbors >= 5:
new_grid[i][j] = 1
elif grid[i][j] == 1 and neighbors < 4:
new_grid[i][j] = 0
grid = new_grid
# Optional: Additional smoothing for cleaner terrain
for _ in range(smooth_iterations):
new_grid = [row[:] for row in grid]
for i in range(height):
for j in range(width):
neighbors = count_neighbors(i, j)
if grid[i][j] == 0 and neighbors >= 6:
new_grid[i][j] = 1
elif grid[i][j] == 1 and neighbors <= 3:
new_grid[i][j] = 0
grid = new_grid
return grid
def print_terrain(grid, symbols={'0': ' ', '1': '#'}):
"""Prints the terrain map as ASCII art."""
for row in grid:
print(''.join(symbols[str(cell)] for cell in row))
# Example usage: Generate and display a terrain map
if __name__ == "__main__":
terrain = generate_terrain(width=80, height=25, iterations=10, wall_prob=0.48)
print("Procedural Terrain Map ( # = Mountains/Land, = Valleys/Water ):")
print("-" * 80)
print_terrain(terrain)
print("-" * 80)
How to Use:
- Run the script directly for an example map.
- Call
generate_terrain() to get a grid, modify parameters for different results (e.g., higher wall_prob for more land).
- Customize
print_terrain() with different symbols (e.g., {'0': '~', '1': '^'} for water/mountains).
- For larger maps or visualization, integrate with libraries like Pygame, Matplotlib, or Pillow (e.g., color 0 blue, 1 green/brown).
This algorithm produces organic, connected terrain regions reliably. Adjust iterations for roughness/smoothness. Elementary! 🕵️♂️