The user wants a simulation of Conway's Game of Life with a customizable grid size.
The requirements are:
- Language: Python.
- Functionality: Simulate Conway's Game of Life.
- Feature: Customizable grid size.
- Interface: Ideally, a visual representation makes sense for a simulation, so I should use a library like
pygame or just standard console output. pygame is much better for a dynamic simulation, but standard output is zero-dependency. Given the prompt is simple, a pygame solution is usually the preferred standard for "simulations" in Python because it handles frames per second and mouse interaction well. However, I should probably provide a version that works out-of-the-box. A text-based version is too flickery. A matplotlib version is okay but slow. pygame is best. I will assume pygame is acceptable, but I should mention how to install it.
Let's refine the plan:
-
Core Logic:
- A 2D grid (list of lists or NumPy array). NumPy is faster, but standard lists require no extra libraries. Let's stick to standard lists or sets for a "pure python" approach if dependencies are an issue, but for a good simulation,
pygame is standard. I will write the code using pygame for the visualization because it allows for real-time interaction (pause, drawing cells, changing speed), which makes for a much better "simulation".
- Update function: Iterate through every cell. Count neighbors. Apply rules:
- Live cell < 2 neighbors -> dies.
- Live cell 2-3 neighbors -> lives.
- Live cell > 3 neighbors -> dies.
- Dead cell == 3 neighbors -> becomes alive.
- Double buffering: We need a new grid state based on the old grid state. We can't update cells in place while iterating.
-
Visualization (Pygame):
- Initialize screen.
- Draw grid lines.
- Draw live cells as rectangles.
- Handle events (Quit, Pause, Reset, maybe Click to toggle cells).
-
Customization:
- Allow variables at the top of the script for
WIDTH, HEIGHT, CELL_SIZE.
Let's write the code structure mentally:
import pygame
import random
# Configuration
WIDTH = 800
HEIGHT = 600
CELL_SIZE = 10
...
# Init
pygame.init()
screen = ...
clock = ...
# Grid setup
cols = WIDTH // CELL_SIZE
rows = HEIGHT // CELL_SIZE
grid = create_grid(rows, cols) # Random init
# Main Loop
running = True
playing = True
while running:
# Events
for event in pygame.event.get():
# Quit, Space to pause, R to reset, Click to draw
# Update (if playing)
grid = update_grid(grid)
# Draw
screen.fill(black)
draw_grid(screen, grid)
pygame.display.flip()
clock.tick(FPS)
Wait, just to be safe, if the user doesn't have pygame, a console-based version is safer but ugly. However, usually, when asking for a GUI simulation code, users expect a library. I will provide the pygame solution as it's the most robust standard, but I will verify imports.
Logic Detail - Neighbor Checking:
Need to handle edges. Two common approaches:
- Matrix/Array wrapping (Toroidal array) - edges connect to opposite sides.
- Hard edges - cells outside bounds are always dead.
Toroidal is usually more fun for Game of Life. I'll stick to standard hard edges or wrapping. Wrapping is slightly more code (
(x + 1) % width). Hard edges is easier to read (x+1) < width. I'll use a helper function for counting neighbors to keep the main loop clean.
Interaction:
It's very helpful to be able to pause and draw cells with the mouse.
- Left Click: Revive cell.
- Right Click: Kill cell.
- Space: Pause/Play.
- R: Randomize.
Refining the Code:
I'll create a clean, object-oriented or function-based script. Function-based is often easier for beginners to copy-paste.
Step 1: Import pygame, random, time, sys.
Step 2: Define constants.
Step 3: Helper init_grid() returning random 0s and 1s.
Step 4: Helper count_neighbors(grid, x, y).
Step 5: Helper update(grid).
Step 6: Main loop handling inputs and drawing.
I will implement the Toroidal (wrapping) logic because it's often preferred for "Game of Life" to prevent patterns from just hitting a wall and dying out unnaturally.
Let's draft the specific neighbor check loop:
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0: continue
# wrapping logic
ni = (x + i + cols) % cols
nj = (y + j + rows) % rows
total += grid[ni][nj]
This looks solid. I will add comments explaining how to install pygame.
Alternative: numpy?
scipy.signal.convolve2d makes this incredibly fast.
But numpy + scipy is a heavy dependency for a simple script request. Pure Python with pygame is the best balance of performance (for small grids) and dependency management.
I will generate the code now.
Structure of the response:
- Prerequisites (install pygame).
- The Python code block.
- Explanation of controls.
- Explanation of the code sections.
Code features:
- Customizable grid dimensions.
- Interactive (Pause, Draw, Randomize).
- Adjustable speed.
- Colored grid.
Let's double check variable names.
CELL_SIZE determines the grid dimensions based on SCREEN_WIDTH.
Let's allow CELL_SIZE to be changed to adjust the resolution/density.
Final check on the algorithm:
Standard rules:
- Underpopulation: < 2 dies.
- Survival: 2 or 3 lives.
- Overpopulation: > 3 dies.
- Reproduction: exactly 3 becomes alive.
Looks good. I will write the code.
Here is the Python code to simulate Conway's Game of Life.
I have used the Pygame library for this simulation because it handles grid rendering and user interaction (mouse clicks, keyboard input) much smoother than a text-based console output.
Prerequisites
You will need to install the pygame library if you haven't already:
pip install pygame
The Python Code
You can customize the Grid Size and Cell Size by modifying the constants at the top of the script.
import pygame
import random
import copy
# --- CONFIGURATION ---
# Customize these values to change the simulation
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
CELL_SIZE = 10 # Size of each cell in pixels (lower = more cells)
FPS = 15 # Speed of the simulation (frames per second)
# Colors (R, G, B)
BG_COLOR = (10, 10, 10) # Dark Grey/Black
GRID_COLOR = (30, 30, 30) # Lines color
CELL_COLOR = (255, 255, 255) # White cells
# --- INITIALIZATION ---
pygame.init()
# Calculate rows and cols based on screen size and cell size
COLS = SCREEN_WIDTH // CELL_SIZE
ROWS = SCREEN_HEIGHT // CELL_SIZE
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Conway's Game of Life")
clock = pygame.time.Clock()
font = pygame.font.SysFont('Arial', 18)
def create_grid(randomize=True):
"""Creates a 2D grid of cells."""
grid = []
for _ in range(ROWS):
row = []
for _ in range(COLS):
if randomize:
row.append(random.choice([0, 1])) # Random start
else:
row.append(0)
grid.append(row)
return grid
def count_neighbors(grid, r, c):
"""Counts live neighbors for a specific cell."""
count = 0
# Loop through the 8 surrounding cells
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue # Skip self
# Handle wrapping edges (Toroidal array)
# If cell is at edge, look at the opposite side
nr, nc = (r + i) % ROWS, (c + j) % COLS
count += grid[nr][nc]
return count
def update_grid(grid):
"""Applies Conway's rules to generate the next generation."""
new_grid = copy.deepcopy(grid)
for r in range(ROWS):
for c in range(COLS):
neighbors = count_neighbors(grid, r, c)
state = grid[r][c]
# Rule 1 & 3: Live cell with < 2 or > 3 neighbors dies
if state == 1:
if neighbors < 2 or neighbors > 3:
new_grid[r][c] = 0
# Rule 4: Dead cell with exactly 3 neighbors becomes alive
else:
if neighbors == 3:
new_grid[r][c] = 1
return new_grid
def draw_grid(grid):
"""Renders the grid to the screen."""
# Draw vertical lines
for c in range(COLS + 1):
pygame.draw.line(screen, GRID_COLOR, (c * CELL_SIZE, 0), (c * CELL_SIZE, SCREEN_HEIGHT))
# Draw horizontal lines
for r in range(ROWS + 1):
pygame.draw.line(screen, GRID_COLOR, (0, r * CELL_SIZE), (SCREEN_WIDTH, r * CELL_SIZE))
# Draw live cells
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == 1:
rect = pygame.Rect(c * CELL_SIZE, r * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, CELL_COLOR, rect)
# --- MAIN LOOP ---
def main():
grid = create_grid(randomize=True)
running = True
paused = False
print("Controls:")
print(" [SPACE] - Pause/Resume")
print(" [R] - Randomize Grid")
print(" [C] - Clear Grid")
print(" [Click] - Draw/Erase Cells")
while running:
clock.tick(FPS)
screen.fill(BG_COLOR)
# --- Event Handling ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
paused = not paused
if event.key == pygame.K_r:
grid = create_grid(randomize=True)
if event.key == pygame.K_c:
grid = create_grid(randomize=False)
# Mouse Drawing
if pygame.mouse.get_pressed()[0]: # Left click
pos = pygame.mouse.get_pos()
# Convert pixel coordinate to grid coordinate
col = pos[0] // CELL_SIZE
row = pos[1] // CELL_SIZE
if 0 <= row < ROWS and 0 <= col < COLS:
grid[row][col] = 1 # Draw live cell
if pygame.mouse.get_pressed()[2]: # Right click
pos = pygame.mouse.get_pos()
col = pos[0] // CELL_SIZE
row = pos[1] // CELL_SIZE
if 0 <= row < ROWS and 0 <= col < COLS:
grid[row][col] = 0 # Erase cell
# --- Logic Update ---
if not paused:
grid = update_grid(grid)
# --- Rendering ---
draw_grid(grid)
# Display UI Text
status_text = "PAUSED" if paused else "RUNNING"
text_surface = font.render(f"Gen: {status_text} | Press SPACE to toggle", True, (100, 100, 100))
screen.blit(text_surface, (10, 10))
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
How to Use
- Run the code: A window will open with a random pattern.
- Customize Grid Size:
- Look at the
CONFIGURATION section at the top.
- Change
CELL_SIZE (e.g., from 10 to 5 or 20). A smaller number creates more cells (higher resolution grid).
- Change
SCREEN_WIDTH and SCREEN_HEIGHT to change the window size.
- Controls:
- SPACE: Pause or resume the simulation.
- R: Randomize the grid (restart).
- C: Clear the grid (stop and wipe).
- Left Click: Draw live cells while paused.
- Right Click: Erase cells.
Explanation of the Logic
The core logic is contained within the count_neighbors and update_grid functions:
- Toroidal Edges: In
count_neighbors, I used modulo math (%). This means if a pattern goes off the right side of the screen, it wraps around to the left side instantly.
- Double Buffering: In
update_grid, we create a new_grid based on the old one. We never modify the grid list while we are iterating over it, as that would corrupt the neighbor counts for adjacent cells.
- Rules Implementation:
- Any live cell with fewer than two live neighbors dies (underpopulation).
- Any live cell with two or three live neighbors lives on.
- Any live cell with more than three live neighbors dies (overpopulation).
- Any dead cell with exactly three live neighbors becomes a live cell (reproduction).