import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def count_neighbors(grid):
"""
Count the number of live neighbors for each cell using toroidal boundaries.
"""
# Sum of all 8 neighbors using np.roll for efficient wrap-around
neighbors = (
np.roll(np.roll(grid, -1, 0), -1, 1) + np.roll(grid, -1, 0) + np.roll(np.roll(grid, -1, 0), 1, 1) +
np.roll(grid, 0, -1) + np.roll(grid, 0, 1) +
np.roll(np.roll(grid, 1, 0), -1, 1) + np.roll(grid, 1, 0) + np.roll(np.roll(grid, 1, 0), 1, 1)
)
return neighbors
def next_generation(grid):
"""
Apply Conway's Game of Life rules to compute the next generation.
"""
neighbors = count_neighbors(grid)
# Birth: dead cell with exactly 3 live neighbors
birth = (grid == 0) & (neighbors == 3)
# Survival: live cell with 2 or 3 live neighbors
survival = (grid == 1) & ((neighbors == 2) | (neighbors == 3))
new_grid = birth | survival
return new_grid.astype(int)
def main():
# Configuration
grid_size = 100
live_density = 0.2 # Probability of a cell being alive initially
generations = 500 # Number of frames in animation
interval = 100 # Milliseconds between frames
# Initialize random grid (toroidal, so no edges matter)
grid = [np.random.choice([0, 1], size=(grid_size, grid_size), p=[1 - live_density, live_density])]
# Set up the plot
fig, ax = plt.subplots()
ax.set_title("Conway's Game of Life")
ax.set_xticks([])
ax.set_yticks([])
im = ax.imshow(grid[0], cmap='binary', interpolation='nearest')
def animate(frame):
grid[0] = next_generation(grid[0])
im.set_array(grid[0])
return [im]
# Create and run animation
ani = FuncAnimation(fig, animate, frames=generations, interval=interval, blit=True, repeat=True)
plt.show()
if __name__ == "__main__":
main()
How to Run
- Ensure you have
numpy and matplotlib installed:
pip install numpy matplotlib
- Save the script as
game_of_life.py and run:
python game_of_life.py
- A window will open showing the evolving grid. Close it to stop.
Features
- Toroidal boundaries: The grid wraps around edges.
- Efficient computation: Uses NumPy vectorization and rolling for neighbors.
- Customizable: Edit
grid_size, live_density, generations, interval in main().
- Smooth animation: 500 generations at 100ms/frame, loops forever.
- Preset patterns: For testing, replace random init with a glider:
glider = np.zeros((grid_size, grid_size))
glider[1:4, 1:4] = np.array([[0,1,0],[0,0,1],[1,1,1]])
grid = [glider]
This is a fully functional, performant simulator! 🚀