In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib nbagg
from matplotlib import animation, rc, cm
rc('animation', html='html5')
In [2]:
class GoL:
"""
A game of life class.
"""
def __init__(self, X0):
self.X = np.array(X0).astype(np.int64)
def neighbors(self):
"""
Returns the number of neigbors of each cell.
"""
X0 = self.X
N = np.zeros_like(X0) # Neighbors matrix
N[:-1, : ] += X0[1: , : ] # Living cells south
N[: , :-1] += X0[ : ,1: ] # Living cells east
N[1: , : ] += X0[ :-1, : ] # Living cells north
N[: ,1: ] += X0[ : , :-1] # Living cells west
N[:-1, :-1] += X0[1: ,1: ] # Living cells south east
N[1: , :-1] += X0[ :-1,1: ] # Living cells north east
N[1: , 1: ] += X0[ :-1, :-1] # Living cells north west
N[:-1, 1: ] += X0[1: , :-1] # Living cells south west
return N
def iterate(self):
"""
Iterates one time.
"""
X0 = self.X
N = self.neighbors()
X = np.where(N == 2, X0, 0) # If a cell has 2 neighbors, it keeps its current state.
X += np.where(N == 3, 1, 0 ) # If a cell has 3 neighbors, it gets alive !
self.X = X
In [3]:
X0 = (np.random.rand(50, 50) >.7) * 1
X0
Out[3]:
In [4]:
def updatefig(*args):
g.iterate()
im.set_array(g.X)
return im,
g = GoL(X0)
fig = plt.figure()
im = plt.imshow(g.X, interpolation = "nearest", cmap = cm.binary, animated=True)
anim = animation.FuncAnimation(fig, updatefig, frames=200, interval=50, blit=True)
plt.show()
In [5]:
def updatefig(*args):
g.iterate()
im.set_array(g.X)
return im,
g = GoL(X0)
fig = plt.figure()
im = plt.imshow(g.X, interpolation = "nearest", cmap = cm.binary, animated=True)
#plt.show()
anim = animation.FuncAnimation(fig, updatefig, frames=200, interval=50, blit=True)
plt.close()
anim
Out[5]: