The user wants a cellular automata simulation like Conway's Game of Life. I'll create a comprehensive implementation with a graphical interface using Pygame. This will include:
-
Conway's Game of Life rules:
- Any live cell with 2 or 3 neighbors survives
- Any dead cell with exactly 3 neighbors becomes alive
- All other cells die or stay dead
-
Features to include:
- Grid-based visualization
- Click to toggle cells
- Start/Stop simulation
- Speed control
- Clear/Random fill
- Different patterns (glider, blinker, etc.)
- Color schemes
- Grid on/off toggle
- Generation counter
-
I'll use Pygame for the GUI since it's well-suited for this type of simulation and doesn't require external assets.
Let me create a complete, polished implementation:
Conway's Game of Life - Cellular Automata Simulator
Here's a complete Python implementation with a beautiful graphical interface using Pygame:
import pygame
import numpy as np
import random
import sys
from collections import deque
# Initialize Pygame
pygame.init()
# ==================== CONFIGURATION ====================
class Config:
# Window settings
WINDOW_WIDTH = 1200
WINDOW_HEIGHT = 800
# Grid settings
CELL_SIZE = 10
GRID_WIDTH = WINDOW_WIDTH // CELL_SIZE
GRID_HEIGHT = WINDOW_HEIGHT // CELL_SIZE
# Colors
BG_COLOR = (15, 15, 25)
GRID_COLOR = (30, 30, 45)
CELL_COLOR = (0, 255, 136)
CELL_GLOW = (0, 200, 100)
DYING_COLOR = (255, 100, 50)
BORN_COLOR = (100, 255, 200)
# UI Colors
UI_BG = (25, 25, 40)
UI_BORDER = (60, 60, 90)
UI_TEXT = (200, 200, 220)
UI_HIGHLIGHT = (0, 255, 136)
BUTTON_COLOR = (40, 40, 60)
BUTTON_HOVER = (60, 60, 90)
# Simulation
FPS = 60
DEFAULT_SPEED = 10 # Generations per second
# ==================== CELLULAR AUTOMATON ENGINE ====================
class CellularAutomaton:
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = np.zeros((height, width), dtype=np.int8)
self.prev_grid = np.zeros((height, width), dtype=np.int8)
self.generation = 0
self.population_history = deque(maxlen=100)
def clear(self):
"""Clear the grid"""
self.grid.fill(0)
self.prev_grid.fill(0)
self.generation = 0
self.population_history.clear()
def randomize(self, density=0.3):
"""Randomly populate the grid"""
self.grid = (np.random.random((self.height, self.width)) < density).astype(np.int8)
self.prev_grid = self.grid.copy()
self.generation = 0
self.population_history.clear()
def toggle_cell(self, x, y):
"""Toggle a cell's state"""
if 0 <= x < self.width and 0 <= y < self.height:
self.grid[y, x] = 1 - self.grid[y, x]
def set_cell(self, x, y, state=1):
"""Set a cell's state"""
if 0 <= x < self.width and 0 <= y < self.height:
self.grid[y, x] = state
def get_neighbors(self, x, y):
"""Count live neighbors using toroidal wrapping"""
count = 0
for dy in [-1, 0, 1]:
for dx in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
nx = (x + dx) % self.width
ny = (y + dy) % self.height
count += self.grid[ny, nx]
return count
def step(self):
"""Advance one generation using Conway's rules"""
self.prev_grid = self.grid.copy()
new_grid = np.zeros((self.height, self.width), dtype=np.int8)
for y in range(self.height):
for x in range(self.width):
neighbors = self.get_neighbors(x, y)
current = self.grid[y, x]
# Conway's Game of Life rules:
# 1. Any live cell with 2 or 3 neighbors survives
# 2. Any dead cell with exactly 3 neighbors becomes alive
# 3. All other cells die or stay dead
if current == 1:
if neighbors in [2, 3]:
new_grid[y, x] = 1
else:
if neighbors == 3:
new_grid[y, x] = 1
self.grid = new_grid
self.generation += 1
self.population_history.append(np.sum(self.grid))
def get_cell_state(self, x, y):
"""Get cell state for rendering (current, born, dying)"""
if 0 <= x < self.width and 0 <= y < self.height:
current = self.grid[y, x]
prev = self.prev_grid[y, x]
if current == 1 and prev == 0:
return 'born'
elif current == 0 and prev == 1:
return 'dying'
return 'alive' if current == 1 else 'dead'
return 'dead'
def get_population(self):
"""Get current population"""
return np.sum(self.grid)
def load_pattern(self, pattern, offset_x=None, offset_y=None):
"""Load a predefined pattern"""
if offset_x is None:
offset_x = self.width // 2 - len(pattern[0]) // 2
if offset_y is None:
offset_y = self.height // 2 - len(pattern) // 2
for y, row in enumerate(pattern):
for x, cell in enumerate(row):
if 0 <= offset_y + y < self.height and 0 <= offset_x + x < self.width:
self.grid[offset_y + y, offset_x + x] = cell
# ==================== PREDEFINED PATTERNS ====================
PATTERNS = {
'Glider': [
[0, 1, 0],
[0, 0, 1],
[1, 1, 1]
],
'Blinker': [
[1, 1, 1]
],
'Toad': [
[0, 1, 1, 1],
[1, 1, 1, 0]
],
'Beacon': [
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 1]
],
'Pulsar': [
[0,0,1,1,1,0,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,1,0,1,0,0,0,0,1],
[1,0,0,0,0,1,0,1,0,0,0,0,1],
[1,0,0,0,0,1,0,1,0,0,0,0,1],
[0,0,1,1,1,0,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,0,0,0,1,1,1,0,0],
[1,0,0,0,0,1,0,1,0,0,0,0,1],
[1,0,0,0,0,1,0,1,0,0,0,0,1],
[1,0,0,0,0,1,0,1,0,0,0,0,1],
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,0,0,0,1,1,1,0,0]
],
'LWSS': [ # Light-weight spaceship
[0, 1, 0, 0, 1],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 0]
],
'Gosper Gun': [ # Gosper Glider Gun
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0],
[1,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,1,0,0,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
],
'Pentadecathlon': [
[0,0,1,0,0,0,0,1,0,0],
[1,1,0,1,1,1,1,0,1,1],
[0,0,1,0,0,0,0,1,0,0]
]
}
# ==================== UI COMPONENTS ====================
class Button:
def __init__(self, x, y, width, height, text, action=None):
self.rect = pygame.Rect(x, y, width, height)
self.text = text
self.action = action
self.hovered = False
self.font = pygame.font.Font(None, 24)
def draw(self, surface):
color = Config.BUTTON_HOVER if self.hovered else Config.BUTTON_COLOR
pygame.draw.rect(surface, color, self.rect, border_radius=5)
pygame.draw.rect(surface, Config.UI_BORDER, self.rect, 2, border_radius=5)
text_surface = self.font.render(self.text, True, Config.UI_TEXT)
text_rect = text_surface.get_rect(center=self.rect.center)
surface.blit(text_surface, text_rect)
def handle_event(self, event):
if event.type == pygame.MOUSEMOTION:
self.hovered = self.rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos) and self.action:
self.action()
return True
return False
class Slider:
def __init__(self, x, y, width, min_val, max_val, initial, label):
self.rect = pygame.Rect(x, y, width, 20)
self.min_val = min_val
self.max_val = max_val
self.value = initial
self.label = label
self.dragging = False
self.font = pygame.font.Font(None, 20)
def draw(self, surface):
# Label
label_text = self.font.render(f"{self.label}: {self.value}", True, Config.UI_TEXT)
surface.blit(label_text, (self.rect.x, self.rect.y - 20))
# Track
pygame.draw.rect(surface, Config.BUTTON_COLOR, self.rect, border_radius=5)
# Fill
fill_width = int((self.value - self.min_val) / (self.max_val - self.min_val) * self.rect.width)
fill_rect = pygame.Rect(self.rect.x, self.rect.y, fill_width, self.rect.height)
pygame.draw.rect(surface, Config.UI_HIGHLIGHT, fill_rect, border_radius=5)
# Handle
handle_x = self.rect.x + fill_width
pygame.draw.circle(surface, Config.UI_TEXT, (handle_x, self.rect.centery), 10)
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.dragging = True
self._update_value(event.pos[0])
elif event.type == pygame.MOUSEBUTTONUP:
self.dragging = False
elif event.type == pygame.MOUSEMOTION:
if self.dragging:
self._update_value(event.pos[0])
def _update_value(self, x):
rel_x = max(0, min(x - self.rect.x, self.rect.width))
self.value = int(self.min_val + (rel_x / self.rect.width) * (self.max_val - self.min_val))
# ==================== MAIN APPLICATION ====================
class GameOfLife:
def __init__(self):
self.screen = pygame.display.set_mode((Config.WINDOW_WIDTH, Config.WINDOW_HEIGHT))
pygame.display.set_caption("Conway's Game of Life - Cellular Automaton Simulator")
self.clock = pygame.time.Clock()
# Initialize automaton
self.automaton = CellularAutomaton(Config.GRID_WIDTH, Config.GRID_HEIGHT)
# State
self.running = False
self.speed = Config.DEFAULT_SPEED
self.show_grid = True
self.show_help = False
self.last_step_time = 0
self.pattern_menu_open = False
# Drawing
self.drawing = False
self.erasing = False
# Fonts
self.font_large = pygame.font.Font(None, 36)
self.font_medium = pygame.font.Font(None, 28)
self.font_small = pygame.font.Font(None, 22)
# Create UI
self._create_ui()
def _create_ui(self):
"""Create UI elements"""
ui_x = 10
ui_y = 10
btn_width = 100
btn_height = 35
spacing = 45
self.buttons = [
Button(ui_x, ui_y, btn_width, btn_height, "Start/Pause", self.toggle_running),
Button(ui_x + 110, ui_y, btn_width, btn_height, "Step", self.step_once),
Button(ui_x + 220, ui_y, btn_width, btn_height, "Clear", self.clear_grid),
Button(ui_x + 330, ui_y, btn_width, btn_height, "Random", self.randomize),
Button(ui_x + 440, ui_y, btn_width, btn_height, "Patterns", self.toggle_pattern_menu),
Button(ui_x + 550, ui_y, btn_width, btn_height, "Help", self.toggle_help),
]
self.speed_slider = Slider(ui_x, ui_y + 60, 200, 1, 60, self.speed, "Speed (gen/s)")
def toggle_running(self):
self.running = not self.running
def step_once(self):
self.automaton.step()
def clear_grid(self):
self.automaton.clear()
self.running = False
def randomize(self):
self.automaton.randomize(0.25)
self.running = False
def toggle_pattern_menu(self):
self.pattern_menu_open = not self.pattern_menu_open
def toggle_help(self):
self.show_help = not self.show_help
def load_pattern(self, pattern_name):
self.automaton.clear()
self.automaton.load_pattern(PATTERNS[pattern_name])
self.pattern_menu_open = False
self.running = False
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
# Handle UI events
for button in self.buttons:
button.handle_event(event)
self.speed_slider.handle_event(event)
# Handle pattern menu
if self.pattern_menu_open and event.type == pygame.MOUSEBUTTONDOWN:
self._handle_pattern_menu_click(event.pos)
# Handle keyboard
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.toggle_running()
elif event.key == pygame.K_n:
self.step_once()
elif event.key == pygame.K_c:
self.clear_grid()
elif event.key == pygame.K_r:
self.randomize()
elif event.key == pygame.K_g:
self.show_grid = not self.show_grid
elif event.key == pygame.K_h:
self.toggle_help()
elif event.key == pygame.K_ESCAPE:
self.pattern_menu_open = False
self.show_help = False
# Handle mouse for drawing
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left click
if self._is_on_grid(event.pos):
self.drawing = True
x, y = self._get_grid_pos(event.pos)
self.automaton.toggle_cell(x, y)
elif event.button == 3: # Right click
if self._is_on_grid(event.pos):
self.erasing = True
x, y = self._get_grid_pos(event.pos)
self.automaton.set_cell(x, y, 0)
elif event.type == pygame.MOUSEBUTTONUP:
self.drawing = False
self.erasing = False
elif event.type == pygame.MOUSEMOTION:
if self.drawing and self._is_on_grid(event.pos):
x, y = self._get_grid_pos(event.pos)
self.automaton.set_cell(x, y, 1)
elif self.erasing and self._is_on_grid(event.pos):
x, y = self._get_grid_pos(event.pos)
self.automaton.set_cell(x, y, 0)
return True
def _is_on_grid(self, pos):
"""Check if position is on the grid (not UI area)"""
return pos[1] > 100
def _get_grid_pos(self, pos):
"""Convert screen position to grid position"""
return pos[0] // Config.CELL_SIZE, (pos[1] - 100) // Config.CELL_SIZE
def _handle_pattern_menu_click(self, pos):
"""Handle clicks on the pattern menu"""
menu_x, menu_y = 440, 50
menu_width = 150
item_height = 30
if menu_x <= pos[0] <= menu_x + menu_width:
patterns = list(PATTERNS.keys())
for i, pattern in enumerate(patterns):
if menu_y + i * item_height <= pos[1] <= menu_y + (i + 1) * item_height:
self.load_pattern(pattern)
return
self.pattern_menu_open = False
def update(self):
"""Update simulation"""
self.speed = self.speed_slider.value
if self.running:
current_time = pygame.time.get_ticks()
if current_time - self.last_step_time >= 1000 / self.speed:
self.automaton.step()
self.last_step_time = current_time
def draw(self):
"""Render everything"""
self.screen.fill(Config.BG_COLOR)
# Draw grid area background
grid_area = pygame.Rect(0, 100, Config.WINDOW_WIDTH, Config.WINDOW_HEIGHT - 100)
pygame.draw.rect(self.screen, (10, 10, 20), grid_area)
# Draw grid lines
if self.show_grid:
for x in range(0, Config.WINDOW_WIDTH, Config.CELL_SIZE):
pygame.draw.line(self.screen, Config.GRID_COLOR, (x, 100), (x, Config.WINDOW_HEIGHT))
for y in range(100, Config.WINDOW_HEIGHT, Config.CELL_SIZE):
pygame.draw.line(self.screen, Config.GRID_COLOR, (0, y), (Config.WINDOW_WIDTH, y))
# Draw cells
for y in range(Config.GRID_HEIGHT):
for x in range(Config.GRID_WIDTH):
state = self.automaton.get_cell_state(x, y)
if state != 'dead':
rect = pygame.Rect(
x * Config.CELL_SIZE + 1,
y * Config.CELL_SIZE + 101,
Config.CELL_SIZE - 2,
Config.CELL_SIZE - 2
)
if state == 'born':
color = Config.BORN_COLOR
elif state == 'dying':
color = Config.DYING_COLOR
else:
color = Config.CELL_COLOR
# Draw cell with glow effect
if state == 'alive':
glow_rect = rect.inflate(2, 2)
pygame.draw.rect(self.screen, Config.CELL_GLOW, glow_rect, border_radius=2)
pygame.draw.rect(self.screen, color, rect, border_radius=2)
# Draw UI background
ui_bg = pygame.Rect(0, 0, Config.WINDOW_WIDTH, 95)
pygame.draw.rect(self.screen, Config.UI_BG, ui_bg)
pygame.draw.line(self.screen, Config.UI_BORDER, (0, 95), (Config.WINDOW_WIDTH, 95), 2)
# Draw buttons
for button in self.buttons:
button.draw(self.screen)
# Draw slider
self.speed_slider.draw(self.screen)
# Draw stats
self._draw_stats()
# Draw pattern menu
if self.pattern_menu_open:
self._draw_pattern_menu()
# Draw help
if self.show_help:
self._draw_help()
pygame.display.flip()
def _draw_stats(self):
"""Draw statistics panel"""
stats_x = 700
stats_y = 15
# Generation
gen_text = self.font_medium.render(f"Generation: {self.automaton.generation}", True, Config.UI_HIGHLIGHT)
self.screen.blit(gen_text, (stats_x, stats_y))
# Population
pop = self.automaton.get_population()
pop_text = self.font_medium.render(f"Population: {pop}", True, Config.UI_TEXT)
self.screen.blit(pop_text, (stats_x, stats_y + 25))
# Status
status = "Running" if self.running else "Paused"
status_color = Config.UI_HIGHLIGHT if self.running else Config.DYING_COLOR
status_text = self.font_medium.render(f"Status: {status}", True, status_color)
self.screen.blit(status_text, (stats_x + 200, stats_y))
# Draw mini population graph
if len(self.automaton.population_history) > 1:
graph_x = stats_x + 200
graph_y = stats_y + 25
graph_width = 150
graph_height = 40
pygame.draw.rect(self.screen, Config.BUTTON_COLOR,
(graph_x, graph_y, graph_width, graph_height), border_radius=3)
history = list(self.automaton.population_history)
max_pop = max(history) if max(history) > 0 else 1
points = []
for i, val in enumerate(history):
px = graph_x + (i / len(history)) * graph_width
py = graph_y + graph_height - (val / max_pop) * graph_height
points.append((px, py))
if len(points) > 1:
pygame.draw.lines(self.screen, Config.UI_HIGHLIGHT, False, points, 2)
def _draw_pattern_menu(self):
"""Draw pattern selection menu"""
menu_x, menu_y = 440, 50
menu_width = 150
item_height = 30
patterns = list(PATTERNS.keys())
menu_height = len(patterns) * item_height
# Background
pygame.draw.rect(self.screen, Config.UI_BG,
(menu_x, menu_y, menu_width, menu_height), border_radius=5)
pygame.draw.rect(self.screen, Config.UI_BORDER,
(menu_x, menu_y, menu_width, menu_height), 2, border_radius=5)
# Items
mouse_pos = pygame.mouse.get_pos()
for i, pattern in enumerate(patterns):
item_rect = pygame.Rect(menu_x, menu_y + i * item_height, menu_width, item_height)
color = Config.BUTTON_HOVER if item_rect.collidepoint(mouse_pos) else Config.UI_BG
pygame.draw.rect(self.screen, color, item_rect)
text = self.font_small.render(pattern, True, Config.UI_TEXT)
text_rect = text.get_rect(midleft=(menu_x + 10, item_rect.centery))
self.screen.blit(text, text_rect)
def _draw_help(self):
"""Draw help overlay"""
overlay = pygame.Surface((Config.WINDOW_WIDTH, Config.WINDOW_HEIGHT))
overlay.fill((0, 0, 0))
overlay.set_alpha(200)
self.screen.blit(overlay, (0, 0))
help_text = [
"CONWAY'S GAME OF LIFE",
"",
"Rules:",
"• A live cell with 2 or 3 neighbors survives",
"• A dead cell with exactly 3 neighbors becomes alive",
"• All other cells die or stay dead",
"",
"Controls:",
"• Left Click: Draw cells",
"• Right Click: Erase cells",
"• Space: Start/Pause simulation",
"• N: Step forward one generation",
"• C: Clear grid",
"• R: Randomize grid",
"• G: Toggle grid lines",
"• H: Toggle this help",
"• ESC: Close menus",
"",
"Press H or click anywhere to close"
]
y = 100
for line in help_text:
if line.startswith("CONWAY") or line.startswith("Rules") or line.startswith("Controls"):
text = self.font_large.render(line, True, Config.UI_HIGHLIGHT)
else:
text = self.font_medium.render(line, True, Config.UI_TEXT)
text_rect = text.get_rect(center=(Config.WINDOW_WIDTH // 2, y))
self.screen.blit(text, text_rect)
y += 35
def run(self):
"""Main game loop"""
running = True
while running:
running = self.handle_events()
self.update()
self.draw()
self.clock.tick(Config.FPS)
pygame.quit()
sys.exit()
# ==================== ENTRY POINT ====================
if __name__ == "__main__":
print("=" * 50)
print("CONWAY'S GAME OF LIFE")
print("=" * 50)
print("\nStarting simulation...")
print("\nControls:")
print(" Left Click - Draw cells")
print(" Right Click - Erase cells")
print(" Space - Start/Pause")
print(" N - Step forward")
print(" C - Clear grid")
print(" R - Randomize")
print(" G - Toggle grid")
print(" H - Help")
print("=" * 50)
game = GameOfLife()
game.run()
Installation
Install the required packages with:
pip install pygame numpy
Features
🎮 Interactive Controls
- Left-click to draw live cells
- Right-click to erase cells
- Drag to paint continuously
⌨️ Keyboard Shortcuts
| Key | Action |
|---|
| Space | Start/Pause simulation |
| N | Step forward one generation |
| C | Clear the grid |
| R | Randomize cells |
| G | Toggle grid lines |
| H | Show help |
🧬 Pre-built Patterns
- Glider - Classic moving pattern
- Blinker - Simple oscillator
- Toad - Period-2 oscillator
- Beacon - Period-2 oscillator
- Pulsar - Beautiful period-3 oscillator
- LWSS - Light-weight spaceship
- Gosper Gun - Infinite glider generator
- Pentadecathlon - Period-15 oscillator
📊 Visual Features
- Color-coded cells (newborn = cyan, dying = orange)
- Real-time population graph
- Generation counter
- Speed control slider (1-60 generations/second)
- Glow effects on live cells
🔬 Conway's Rules
- A live cell with 2 or 3 neighbors survives
- A dead cell with exactly 3 neighbors becomes alive
- All other cells die or stay dead
Run the script and watch emergent complexity arise from simple rules! 🧫