Skip to content

Instantly share code, notes, and snippets.

@s4nyam
Created March 29, 2023 12:13
Show Gist options
  • Save s4nyam/8b4cc3ec6636119df99836f1a85ad898 to your computer and use it in GitHub Desktop.
Save s4nyam/8b4cc3ec6636119df99836f1a85ad898 to your computer and use it in GitHub Desktop.
Watch a glider take flight in a 2D world with the power of Python and Matplotlib's animation magic ✨
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import PillowWriter
# Define the initial state of the grid
grid = np.zeros((100, 100))
grid[1, 2] = 1
grid[2, 3] = 1
grid[3, 1:4] = 1
# Define the function that updates the grid
def update(frame):
global grid
new_grid = np.zeros((100, 100))
for i in range(100):
for j in range(100):
# Count the number of live neighbors
num_neighbors = (
grid[(i - 1) % 100, (j - 1) % 100]
+ grid[(i - 1) % 100, j]
+ grid[(i - 1) % 100, (j + 1) % 100]
+ grid[i, (j - 1) % 100]
+ grid[i, (j + 1) % 100]
+ grid[(i + 1) % 100, (j - 1) % 100]
+ grid[(i + 1) % 100, j]
+ grid[(i + 1) % 100, (j + 1) % 100]
)
# Update the cell according to the rules of Conway's Game of Life
if grid[i, j] == 1 and (num_neighbors == 2 or num_neighbors == 3):
new_grid[i, j] = 1
elif grid[i, j] == 0 and num_neighbors == 3:
new_grid[i, j] = 1
# Update the grid
grid = new_grid
# Plot the grid
plt.clf()
plt.imshow(grid, cmap="binary")
plt.title("Glider Simulation")
plt.axis("off")
# Create the animation
ani = FuncAnimation(plt.gcf(), update, frames=100, interval=50)
# Create a writer object to save the animation as a GIF
writer = PillowWriter(fps=20)
ani.save("glider.gif", writer=writer)
# Show the animation
plt.show()
@s4nyam
Copy link
Author

s4nyam commented Mar 29, 2023

c3df83cd-99f7-41a2-b76c-e77a89abf9b5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment