1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import numpy as np import matplotlib.animation import matplotlib.pyplot as plt
def game_of_life(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
return Z
rabbits = np.array([[0., 0., 0., 0., 0., 0., 0., 0.], [0., 1., 1., 1., 1., 1., 1., 0.], [0., 1., 1., 1., 1., 1., 1., 0.], [0., 0., 0., 0., 0., 0., 0., 0.]])
glider = np.array([[0, 0, 0], [0, 0, 255], [255, 255, 255]]) / 255
def plot_game(Z): plt.imshow(Z, cmap=plt.cm.gray_r, interpolation='nearest') plt.xticks([]), plt.yticks([])
def update_game(frame_number, img, Z): newZ = game_of_life(Z) img.set_data(newZ)
return img,
np.random.seed(0) Z = np.random.randint(0, 2, size=(100, 100))
fig1 = plt.figure()
img = plt.imshow(Z, cmap=plt.cm.gray_r, interpolation='nearest')
anim = matplotlib.animation.FuncAnimation( fig1, update_game, fargs=( img, Z), frames=10, interval=200)
plt.show()
|