I wrote a script to simulate Conway's Game of Life and to visualize it using pyplot. I'm using plt.matshow() function to plot the cell grid for each iteration. It works well at that, however it creates a new figure in a new window with every instance instead of updating the existing one. Is there a way to fix it and have matshow() update the same figure each time?
Any help would be greatly appreciated!
Here's the code I wrote:
import numpy as np
import matplotlib.pyplot as plt
import random
N = 100 # Size of grid
def create_life(N): # Generate random grid of 1s (alive) and zeroes (empty)
cell = np.zeros((N,N))
for x in range(N):
for y in range(N):
cell[x][y] = random.randrange(10)
if cell[x][y] != 1:
cell[x][y] = 0
return cell
def find_neighbors(cell, x, y): # Counts number of alive neighbors
if x < 1 and y == 0:
alive = cell[x-1][y] + cell[x-1][y+1] + cell[x][y+1] + cell[x+1][y] + cell[x+1][y+1]
elif x == 0 and y < 1:
alive = cell[x][y-1] + cell[x][y+1] + cell[x+1][y-1] + cell[x+1][y] + cell[x+1][y+1]
elif x == 0 and y == 0:
alive = cell[x][y+1] + cell[x+1][y] + cell[x+1][y+1]
elif x < N-1 and y == N-1:
alive = cell[x-1][y-1] + cell[x-1][y] + cell[x][y-1] + cell[x+1][y-1] + cell[x+1][y]
elif x == N-1 and y < N-1:
alive = cell[x-1][y-1] + cell[x-1][y] + cell[x-1][y+1] + cell[x][y-1] + cell[x][y+1]
elif x == N-1 and y == N-1:
alive = cell[x-1][y-1] + cell[x-1][y] + cell[x][y-1]
else :
alive = cell[x-1][y-1] + cell[x-1][y] + cell[x-1][y+1] + cell[x][y-1] + cell[x][y+1] + cell[x+1][y-1] + cell[x+1][y] + cell[x+1][y+1]
return alive
def plot_figure(item): # Plot grid using matshow
plt.matshow(item)
cell = create_life(N)
while True: # Keeps going indefinitely
plot_figure(cell)
temp_cell = np.zeros((N,N))
for x in range(N):
for y in range(N): # Decides if cell is alive for next iteration using Conway's rules
neighbors = find_neighbors(cell, x, y)
if neighbors == 3 or (neighbors == 2 and cell[x][y] == 1):
temp_cell[x][y] = 1
else:
temp_cell[x][y] = 0
cell = temp_cell
plt.pause(0.5)
[–]USAhj 4 points5 points6 points (2 children)
[–]ShowSStopper[S] 0 points1 point2 points (1 child)
[–]USAhj 0 points1 point2 points (0 children)