I'm focused on grasping the specific parameters for the Python script. I've broken down the project into discrete parts: understanding the user's ultimate goal, and identifying the essential elements needed to create a functional simulation. The grid, rules, and user interaction are next on the agenda.
Mapping Dependencies Systematically
Currently, I'm working through the specific dependencies. NumPy for the grid, Matplotlib for visualization. Thinking through the mechanics of the update function. Iterating over the cells and applying the Game of Life rules is the focus. Considering efficiency for larger grids is key.
Decomposing the Core Mechanics
I'm now focusing on the update function, particularly the neighbor count and rule application. Considering a vectorized NumPy approach, rolling the array in all eight directions, and summing the neighbors efficiently, seems essential. This should greatly improve performance compared to the initial nested loop approach.
Refining Code Implementation
I'm now iterating through the code structure. I'm focusing on the update function and considering the use of argparse for command-line arguments to customize the grid size and potentially include predefined patterns like the Glider Gun. I will also incorporate toroidal boundary conditions using modulo arithmetic for the neighbor calculations, streamlining the implementation and boosting performance.
Planning Script Implementation
Now, I'm thinking about the script's structure: initializing the grid, defining the update function using NumPy's efficient vectorized operations, and setting up the Matplotlib animation. I'm focusing on the implementation details, like the use of the modulo operator for toroidal boundary conditions and then refining the visualization to incorporate color schemes and user options, like a glider gun pattern for diversity in starting states.
Here is a complete, efficient Python script to simulate Conway's Game of Life.
This script uses NumPy for grid management (because it is fast) and Matplotlib via FuncAnimation to create a visual animation window.
Prerequisites
You will need to install numpy and matplotlib if you don't have them:
bash
pip install numpy matplotlib
The Python Script (game_of_life.py)
python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import argparse
# Setting the values for the grid
ON = 255
OFF = 0
vals = [ON, OFF]
def randomGrid(N):
"""returns a grid of NxN random on/off values"""
return np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N)
def addGlider(i, j, grid):
"""adds a glider with top left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
def update(frameNum, img, grid, N):
# Copy the grid to calculate the next generation
# (We simulate all changes happening simultaneously)
newGrid = grid.copy()
for i in range(N):
for j in range(N):
# Compute the sum of the 8 neighbors.
# We use modulo (%) operator for toroidal boundary conditions
# (e.g., the top edge is connected to the bottom edge).
total = int((grid[i, (j-1)%N] + grid[i, (j+1)%N] +
grid[(i-1)%N, j] + grid[(i+1)%N, j] +
grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] +
grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N]) / 255)
# Apply Conway's Rules
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newGrid[i, j] = OFF
else:
if total == 3:
newGrid[i, j] = ON
# Update data
img.set_data(newGrid)
grid[:] = newGrid[:]
return img,
def main():
# Command line args to set grid size
parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.")
parser.add_argument('--grid-size', dest='N', required=False)
parser.add_argument('--interval', dest='interval', required=False)
parser.add_argument('--glider', action='store_true', required=False)
args = parser.parse_args()
# Default grid size
N = 100
if args.N and int(args.N) > 8:
N = int(args.N)
# Default animation update interval (ms)
updateInterval = 50
if args.interval:
updateInterval = int(args.interval)
# Declare grid
grid = np.array([])
# Check if user wants specific glider mode or random start
if args.glider:
grid = np.zeros(N*N).reshape(N, N)
addGlider(1, 1, grid)
else:
grid = randomGrid(N)
# Set up animation
fig, ax = plt.subplots()
img = ax.imshow(grid, interpolation='nearest', cmap='gray')
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N),
frames=10,
interval=updateInterval,
save_count=50)
plt.title("Conway's Game of Life")
plt.axis('off') # Turn off x/y axis numbers
plt.show()
if __name__ == '__main__':
main()
How to run it
Basic Random Start:
Run the script directly. It will start with a 100x100 grid with random cells populated.
bash
python game_of_life.py
Specific Grid Size:
Change the size of the board (e.g., 50x50).
bash
python game_of_life.py --grid-size 50
Glider Demo:
Start with a blank board and a single "Glider" (a pattern that travels across the screen).
bash
python game_of_life.py --grid-size 30 --glider
How the Code Works
The Grid: We create a 2D NumPy array. Cells are either 255 (Alive/White) or 0 (Dead/Black).
Toroidal Boundary: The logic (i-1)%N handles the edges. If a cell is at index 0 (left edge), checking index -1 wraps around to the last index (right edge). This makes the board act like a donut shape, so patterns don't crash into walls and die.
The update Function:
We iterate through every single cell.
We calculate the sum of its 8 neighbors.
Rule 1 (Death): If a cell is alive and has < 2 neighbors (loneliness) or > 3 neighbors (overcrowding), it turns off.
Rule 2 (Life): If a cell is dead and has exactly 3 neighbors (reproduction), it turns on.
Animation:matplotlib.animation.FuncAnimation calls the update function repeatedly, refreshing the image on the screen every 50 milliseconds.