Search code examples
pythonnumpyconways-game-of-life

Conways Game of Life only switches between two frames - Python


So I am making Conway's game of life and I got most/all of it done, but all it does is switch between two frames. I am pretty sure that the logic is correct, since at the start of the animation some cells disappear, but nothing happens after that. I am really stuck here, so I hope you can help me out.

Here is my full code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
import random

Size=(60,60)
off=False
amount=0.3

def mapify():
    total=Size[0]*Size[1]
    arr=np.zeros(Size)
    while sum(sum(arr)) < int(total*amount):
        y=random.randrange(0, Size[1])
        x=random.randrange(0, Size[0])
        if arr[y][x]==0: arr[y][x]=1
    return arr

class cell:
    #Map = np.random.randint(2, size=Size)
    Map=mapify()
    cells=[[] for i in range(Size[0])]
    def __init__(self, row, col):
        self.r=row
        self.c=col
        self.stat=cell.Map[row][col]
        cell.cells[row].append(self)

    def findnb(self):
        Map=cell.Map
        li=[]
        for a in range(-1, 2):
            for b in range(-1, 2):
                try:
                    if a!=0 and b!=0: li.append(Map[self.r+a][self.c+b])
                except:
                    pass
                
        self.nb = sum(li)

    def apply(self):
        self.findnb()
        if self.stat and self.nb>1 and self.nb < 4:
            return 1
        elif not self.stat and self.nb==3:
            return 1
        else:
            return 0

for i in range(Size[0]):
    for j in range(Size[1]):
        cell(i, j)

ax = plt.axes()


while off==False:
    cell.Map=np.reshape(
        [[c.apply() for c in r] for r in cell.cells],
        Size)
    
    ax.matshow(cell.Map, cmap='Greys')
    plt.draw()
    try:
        plt.pause(0.01)
    except:
        break

EDIT: I solved it! I was a dummy with the logic gate here is the solution:

for a in range(-1, 2):
        for b in range(-1, 2):
            try:
                if not (a==0 and b==0):li.append(Map[self.r+a][self.c+b])
            except:
                pass

Solution

  • I messed up the if statement that checks for all neighbors, here is the working code

    for a in range(-1, 2):
            for b in range(-1, 2):
                try:
                    if not (a==0 and b==0):li.append(Map[self.r+a][self.c+b])
                except:
                    pass