Search code examples
pythonpython-3.xnumpyconways-game-of-life

I want to convert the arrays into an image an then animate it


So I was trying to come up with a Conway's Game of Life code, and this lead me to this one. It may not be the most efficient one, but I'm a begginer coder and I wanted to keep things simple. All I want to do is to animate the game, and not only display the last generation of the game. Also, I'd like to know how to run the game indefinately, because as you can see this code has a pre determined number of generations. Thanks in advance for your help and here's my code:

import numpy as np
import matplotlib.pyplot as plt

x=np.random.randint(2, size=(50,50))

for b in range (0,100):
    y=np.zeros((50,50), dtype=np.int)
    for c in range(1,48):
        for d in range(1,48):
            if x[c][d]==1:
                if x[c][d-1]+x[c][d+1]+x[c-1][d-1]+x[c-1][d]+x[c-1][d+1]+x[c+1][d-1]+x[c+1][d]+x[c+1][d+1]<2 or x[c][d-1]+x[c][d+1]+x[c-1][d-1]+x[c-1][d]+x[c-1][d+1]+x[c+1][d-1]+x[c+1][d]+x[c+1][d+1]>3:
                    y[c][d]=0
                else:
                    y[c][d]=1
            if x[c][d]==0:
                if x[c][d-1]+x[c][d+1]+x[c-1][d-1]+x[c-1][d]+x[c-1][d+1]+x[c+1][d-1]+x[c+1][d]+x[c+1][d+1]==3:
                    y[c][d]=1
                else:
                    y[c][d]=0
    x=y.copy()

plt.imshow(x)
plt.grid(False)
plt.show()

Solution

  • I've had dreadful luck with the various animation examples out there (and related blocking/nonblocking examples), when running on a Macbook.

    A simple thing that works for me: ... x=np.random.randint(2, size=(50,50)) p = plt.imshow(x) ... x = y.copy() p.set_data(x) plt.pause(.1)