As a practice exercise, I implemented a cellular automaton (Conway's Game of Life) in python (with help from this tutorial).
I am very curious, if this code follows common best practices and I am wondering how to improve the code in terms of performance and readability.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
arr = []
size_grid_x = 6
size_grid_y = 6
universe = np.zeros((size_grid_x, size_grid_y))
new_universe = np.copy(universe)
beacon = [[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, 1]]
universe[1:5, 1:5] = beacon
def update(universe, x, y):
X = size_grid_x
Y = size_grid_y
neighbors = lambda x, y: [(x2, y2) for x2 in range(x - 1, x + 2)
for y2 in range(y - 1, y + 2)
if (-1 < x <= X and
-1 < y <= Y and
(x != x2 or y != y2) and
(0 <= x2 <= X) and
(0 <= y2 <= Y))]
num_neighbours = sum([universe[i] for i in neighbors(x, y)])
new_val = universe[x, y]
if universe[x, y] and not 2 <= num_neighbours <= 3:
new_val = 0
elif num_neighbours == 3:
new_val = 1
return new_val
for i in range(100):
for x in range(5):
for y in range(5):
new_universe[x, y] = update(universe, x, y)
universe[:, :] = new_universe[:, :]
arr.append(np.copy(universe))
fig = plt.figure()
i = 0
im = plt.imshow(arr[0], animated=True)
def update_figure(*args):
global i
if i < 99:
i += 1
else:
i = 0
im.set_array(arr[i])
return im,
ani = animation.FuncAnimation(fig, update_figure, blit=True)
plt.show()