The user wants Python code to generate a procedural terrain map using cellular automata, but they didn't specify the CA rules. They might just need working code to visualize terrain in 2D. I think using numpy and matplotlib is a standard approach, though I shouldn't assume those dependencies are installed. I can also consider using pure Python with PIL. I'll provide a script that generates the map and displays it, possibly as ASCII or a color map.Outlining CA terrain generation
The easiest method for generating a height map is to treat it as integer values, applying a smoothing rule like averaging neighbors plus some noise. However, that's more of a smoothing technique than a cellular automata (CA) approach. With CA, each cell can adopt the state of the majority of its neighbors. I can implement a multi-state system: 0 for water, 1 for land, and 2 for mountains.
I’ll write a script using numpy for efficiency that initializes a grid, defines dimensions, and applies the CA rules over several iterations.Designing terrain generation
I’m thinking about a classic cave generation approach here. First, I could interpret land cells and create mountains using a second cellular automata (CA) pass focused on land. However, the user's request is just for a procedural terrain map, not specifically caves.
I can adjust thresholds to produce continents too or create multi-level terrain by using noise with CA. To keep it simple for the user, it might be best to implement a straightforward single-state CA for land versus water and then visualize that with color for a nice representation of islands and lakes.Preparing terrain map code
I’m planning to provide a Python code example for generating a procedural terrain map using cellular automata, as that's what the user requested. I’ll use numpy and matplotlib to display the map effectively.
The code will include adjustable parameters and several functions: one to generate the map, another to simulate the cellular automata, and a third to plot the map with appropriate colors for water and land. I’ll keep comments light but clear for better understanding, but I also want to avoid overwhelming explanations. Let’s get this crafted!Constructing neighbor counting code
In my example code, I'll start with importing numpy and matplotlib. However, I can't rely on SciPy for convolution, as it's not always available. Instead, I'll manually count neighbors using 2D convolution with numpy's padding or slicing techniques, which is straightforward.
I will implement a function to count neighbors using numpy, creating a kernel for the 3x3 neighborhood. Then, I’ll define parameters for generating a terrain map that resembles continents. I’ll ensure to customize the color map for better visualization and include an optional ASCII representation if needed. Let’s finalize this code! ```python
"""
Procedural terrain generation using a simple cellular automaton
(land vs water “continents” map).
Dependencies:
pip install numpy matplotlib
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
-------------------------------
Cellular automata core
-------------------------------
def random_map(width, height, land_chance=0.45, rng=None):
"""Initialize a random boolean map: True = land, False = water."""
if rng is None:
rng = np.random.default_rng()
return rng.random((height, width)) < land_chance
def count_alive_neighbors(grid):
"""
Count 8-neighborhood alive cells (True=1, False=0) for each cell.
Uses padding + slicing (no SciPy required).
"""
h, w = grid.shape
g = grid.astype(np.int8)
code
# Pad with zeros (water) around the edges
padded = np.pad(g, 1, mode="constant", constant_values=0)
# Sum all 3x3 neighborhoods then subtract the center cell
neighbors = np.zeros_like(g, dtype=np.int8)
for dy in range(3):
for dx in range(3):
if dx == 1 and dy == 1:
continue # skip center
neighbors += padded[dy:dy + h, dx:dx + w]
return neighbors
def step_ca(grid, birth_limit=4, death_limit=3):
"""
Apply one step of the cellular automaton.
code
Rules:
- If a land cell has < death_limit land neighbors, it becomes water.
- If a water cell has > birth_limit land neighbors, it becomes land.
- Otherwise, state stays the same.
"""
neighbors = count_alive_neighbors(grid)
birth = (grid == 0) & (neighbors > birth_limit)
survive = (grid == 1) & (neighbors >= death_limit)
new_grid = birth | survive
return new_grid
def simulate_ca(grid, steps=5, birth_limit=4, death_limit=3):
"""Run CA for a given number of steps."""
current = grid.copy()
for _ in range(steps):
current = step_ca(current, birth_limit, death_limit)
return current
-------------------------------
Visualization
-------------------------------
def show_terrain(grid):
"""
Display the terrain:
0 = water (blue)
1 = land (green)
"""
cmap = ListedColormap(["#1f4e79", "#2f8f46"]) # water, land
plt.figure(figsize=(8, 6))
plt.imshow(grid, cmap=cmap, interpolation="nearest")
plt.title("Procedural Terrain (Cellular Automata)")
plt.axis("off")
plt.show()
if name == "main":
# Parameters you can tweak:
width = 200
height = 150
land_chance = 0.45 # Initial random land probability
steps = 6 # Number of CA smoothing steps
birth_limit = 4
death_limit = 3
seed = 42 # Set to None for different terrain each run
This script:
1. Creates a random land/water map.
2. Applies an 8-neighbor cellular automaton several times to smooth it into continents and lakes.
3. Displays the final terrain using matplotlib.
Adjust `land_chance`, `steps`, `birth_limit`, and `death_limit` to get different styles of maps.