Created
March 29, 2023 12:13
-
-
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 ✨
This file contains 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
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() |
Author
s4nyam
commented
Mar 29, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment