import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update(frame_number, img, grid, N):
new_grid = grid.copy()
for i in range(N):
for j in range(N):
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])/255)
if grid[i, j] == 255:
if (total < 2) or (total > 3):
new_grid[i, j] = 0
else:
if total == 3:
new_grid[i, j] = 255
img.set_data(new_grid)
grid[:] = new_grid[:]
return img,
N = 100
grid = np.random.choice([0, 255], (N, N))
fig, ax = plt.subplots()
img = ax.imshow(grid, interpolation='nearest')
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N), frames=10,
save_count=50)
plt.show()