Skip to content

Instantly share code, notes, and snippets.

@limitedeternity
Last active January 3, 2022 08:31
Show Gist options
  • Select an option

  • Save limitedeternity/25014924beda4c63bfd9eb627c335bf1 to your computer and use it in GitHub Desktop.

Select an option

Save limitedeternity/25014924beda4c63bfd9eb627c335bf1 to your computer and use it in GitHub Desktop.
Conway's Game of Life implemented using NumPy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Z = np.random.randint(2, size=(300, 600))
def update(*args):
global Z
N = (Z[0:-2, 0:-2] + Z[0:-2, 1:-1] + Z[0:-2, 2:] +
Z[1:-1, 0:-2] + Z[1:-1, 2:] +
Z[2: , 0:-2] + Z[2: , 1:-1] + Z[2: , 2:])
birth = (N == 3) & (Z[1:-1, 1:-1] == 0)
survive = ((N == 2) | (N == 3)) & (Z[1:-1, 1:-1] == 1)
Z[...] = 0
Z[1:-1, 1:-1][birth | survive] = 1
im.set_data(Z)
size = np.array(Z.shape)
dpi = 80.0
figsize = size[::-1] / dpi
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False)
im = plt.imshow(Z, interpolation='nearest', cmap=plt.cm.gray_r, vmin=0, vmax=1)
plt.xticks([]), plt.yticks([])
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, bitrate=1800)
anim = animation.FuncAnimation(fig, update, interval=10, frames=100)
anim.save('output.mp4', writer=writer)
plt.show()
@limitedeternity
Copy link
Copy Markdown
Author

output.mp4

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