Last active
January 29, 2025 21:21
-
-
Save AndrewBarfield/8fabd046e83ab99bbd4dc6d09a785331 to your computer and use it in GitHub Desktop.
Conway's Game of Life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Here's a simple implementation of Conway's Game of Life in Python using the numpy | |
# library for managing the grid and matplotlib for visualizing the evolution of the | |
# cells. If you haven't installed these libraries yet, you can do so using pip: | |
# pip install numpy matplotlib | |
# Conway's Game of Life Implementation | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import matplotlib.animation as animation | |
def update(frameNum, img, grid, N): | |
# Create an updated grid | |
newGrid = np.copy(grid) | |
for i in range(N): | |
for j in range(N): | |
# Count the number of alive neighbors | |
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])) | |
# Apply Conway's rules | |
if grid[i, j] == 1: | |
if total < 2 or total > 3: | |
newGrid[i, j] = 0 # Cell dies | |
else: | |
if total == 3: | |
newGrid[i, j] = 1 # Cell becomes alive | |
img.set_data(newGrid) | |
grid[:] = newGrid[:] | |
return img, | |
def main(): | |
# Grid size | |
N = 100 | |
# Create a random grid | |
grid = np.random.choice([0, 1], N*N, p=[0.8, 0.2]).reshape(N, N) | |
# Set up the figure for animation | |
fig, ax = plt.subplots() | |
img = ax.imshow(grid, interpolation='nearest', cmap='binary') | |
plt.axis('off') | |
# Create the animation | |
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N), | |
frames=10, interval=100, save_count=50) | |
plt.show() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment