Building a cellular automata script
The user asked for a Python script to simulate cellular automata, like Conway's Game of Life, but didn’t specify a UI. I’m thinking of a minimal script—maybe a CLI or simple text output, or even a matplotlib animation. I’ll create a generic 2D cellular automaton script with rule specifications and a preset for GoL. To keep things simple, I’ll include a terminal-based simulation with ASCII grid output, adding a matplotlib snippet as an option.Designing the script
I'm thinking about how to structure the script. I want to use numpy for array operations because it makes neighborhood calculations and convolution simpler and more efficient than plain lists. It's quite common to have numpy installed, so I’ll proceed with that, adding optional matplotlib for visualization. For the cellular automaton, the grid will represent 0s and 1s for dead and alive cells. I’ll support a custom rule notation like "B3/S23" for Conway's Game of Life and implement a function to handle grid steps with toroidal wrap-around for edges.Computing neighbor counts
To compute the neighbor counts in the grid, I'll use np.roll to shift the grid based on each neighbor's offset and sum them up. I'll sum the shifted grids for all eight neighbors, excluding the center cell. The next step is updating the grid: I'll create new_grid based on survival and birth conditions using boolean operations. Additionally, I'll implement a function to display the grid with '.' for dead cells and '█' for alive ones. The script will also parse arguments for width, height, steps, density, and rule, and I'll use argparse for this. I'll include instructions for running the script in a simple CLI format.Crafting the script
I’m starting to draft the script with necessary imports like argparse, time, os, and numpy. However, I’m considering whether to allow specifying an initial pattern from a file, but that might complicate things. To keep it manageable, I’ll avoid adding any dependencies beyond numpy. Since some users may not have numpy, I could write a pure Python version for neighbor counting, though it would be slower. However, for moderate grid sizes, that should be fine. I’ll opt for using list of lists instead of numpy arrays to ensure better portability. The complexity will remain reasonable, and it’s a good educational opportunity!Implementing the cellular automata code
The user prefers clarity over optimization, so I’m going with pure Python for the cellular automata script. The grid will be a list of lists for 0s and 1s. I’ll implement toroidal neighbor counting using loops and modulo indexing. Neighbors are recomputed for each cell, which is acceptable.
I need to parse the rule string, setting up the CLI with argparse for width, height, steps, rules, and initial density.
For boundaries, I'll implement wrap-around behavior and define functions to clear the screen and print the grid. I’ll also mention how to simulate different rules, and provide a succinct explanation for usage but keep it simple overall. Below is a self‑contained Python script that simulates 2D, binary cellular automata using rules like Conway’s Game of Life (B3/S23). It runs in the terminal, no extra libraries required.
#!/usr/bin/env python3
"""
Simple terminal cellular automaton simulator (Conway's Game of Life–style).
Features:
- Binary states (dead/alive)
- Moore neighborhood (8 neighbors)
- Wrap-around (toroidal) edges
- Rules in "B3/S23" format (birth/survival), e.g.:
- Game of Life: B3/S23
- HighLife: B36/S23
- Seeds: B2/S
"""
import argparse
import random
import time
import os
from typing import List, Set, Tuple
Grid = List[List[int]] # 0 = dead, 1 = alive
def parse_rule(rule_str: str) -> Tuple[Set[int], Set[int]]:
"""
Parse a rule string like "B3/S23" into (birth_set, survival_set).
birth_set: neighbor counts that cause a dead cell to become alive
survival_set: neighbor counts that keep a live cell alive
"""
rule_str = rule_str.upper().replace(" ", "")
if "/" not in rule_str:
raise ValueError(f"Invalid rule format: {rule_str!r} (expected 'Bx/Sy')")
b_part, s_part = rule_str.split("/")
if not (b_part.startswith("B") and s_part.startswith("S")):
raise ValueError(f"Invalid rule format: {rule_str!r} (expected 'Bx/Sy')")
birth = {int(ch) for ch in b_part[1:] if ch.isdigit()}
survive = {int(ch) for ch in s_part[1:] if ch.isdigit()}
return birth, survive
def create_random_grid(width: int, height: int, density: float) -> Grid:
"""
Create a random grid with given size and initial live-cell probability.
density: float in [0, 1], probability each cell starts alive.
"""
grid: Grid = []
for _ in range(height):
row = [1 if random.random() < density else 0 for _ in range(width)]
grid.append(row)
return grid
def count_neighbors(grid: Grid, x: int, y: int) -> int:
"""
Count live neighbors around cell (x, y) with wrap-around edges.
Moore neighborhood (8 surrounding cells).
"""
height = len(grid)
width = len(grid[0])
total = 0
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
if dx == 0 and dy == 0:
continue # skip the cell itself
nx = (x + dx) % width
ny = (y + dy) % height
total += grid[ny][nx]
return total
def step(grid: Grid, birth: Set[int], survive: Set[int]) -> Grid:
"""
Compute the next generation of the grid using rule (birth, survive).
"""
height = len(grid)
width = len(grid[0])
new_grid: Grid = [[0] * width for _ in range(height)]
for y in range(height):
for x in range(width):
alive = grid[y][x] == 1
neighbors = count_neighbors(grid, x, y)
if alive and neighbors in survive:
new_grid[y][x] = 1
elif (not alive) and neighbors in birth:
new_grid[y][x] = 1
else:
new_grid[y][x] = 0
return new_grid
def clear_screen() -> None:
"""
Clear the terminal screen.
"""
os.system("cls" if os.name == "nt" else "clear")
def print_grid(grid: Grid) -> None:
"""
Print the grid to the terminal using '█' for alive and ' ' for dead.
"""
lines = []
for row in grid:
line = "".join("█" if cell else " " for cell in row)
lines.append(line)
print("\n".join(lines))
def main() -> None:
parser = argparse.ArgumentParser(
description="2D cellular automaton simulator (Conway's Game of Life style)."
)
parser.add_argument("--width", type=int, default=40, help="Grid width")
parser.add_argument("--height", type=int, default=20, help="Grid height")
parser.add_argument(
"--density",
type=float,
default=0.25,
help="Initial live cell probability in [0,1] (default: 0.25)",
)
parser.add_argument(
"--rule",
type=str,
default="B3/S23",
help="Rule in Bx/Sy format (default: B3/S23 for Game of Life)",
)
parser.add_argument(
"--delay",
type=float,
default=0.1,
help="Delay between steps in seconds (default: 0.1)",
)
parser.add_argument(
"--steps",
type=int,
default=0,
help="Number of steps to run (0 = run until Ctrl+C)",
)
args = parser.parse_args()
birth, survive = parse_rule(args.rule)
grid = create_random_grid(args.width, args.height, args.density)
step_num = 0
try:
while True:
clear_screen()
print(f"Rule: {args.rule} | Step: {step_num}")
print_grid(grid)
grid = step(grid, birth, survive)
step_num += 1
if args.steps and step_num >= args.steps:
break
time.sleep(args.delay)
except KeyboardInterrupt:
pass # allow clean exit with Ctrl+C
if __name__ == "__main__":
main()
Usage examples (from the terminal):
# Standard Game of Life, 40x20, default density, runs until Ctrl+C
python game_of_life.py
# Larger grid, slower animation
python game_of_life.py --width 80 --height 40 --delay 0.2
# HighLife rule (B36/S23)
python game_of_life.py --rule B36/S23
# Run for exactly 200 steps, denser start
python game_of_life.py --steps 200 --density 0.4
If you’d like a version with graphical animation (matplotlib or pygame), or support for non-wrapping borders, I can add that as well.