Home > OS >  Cant properly update cell status in my Game Of Life
Cant properly update cell status in my Game Of Life

Time:04-27

cells not "dying" in may logocal loop. New cells geretion is normal, i think..

so cells not die

all calculations are into one numpy array, i dont have "second/old/new etc" arrays

sory for my bad English

def  updateCells(grid: np.ndarray):
    for i in range(GRID_WIDTH):
        for j in range(GRID_HEIGHT):
            #neighbours list contains 0, 1
            neighbours = getNeighbours(i, j, grid)
            
            #sum of alive neighbours
            count = sum(neighbours)

            if grid[i][j] == 1:
                if count < 2:
                    grid[i][j] = 0
                    continue

                if count == 2 or count == 3:
                    grid[i][j] = 1
                    continue

                if count > 3:
                    grid[i][j] = 0
                    continue

            if grid[i][j] == 0:
                if count == 3:
                    grid[i][j] = 1
                    continue

function for getting neighbours of one cell:

def getNeighbours(i, j, arr):
    ax_0_y = np.size(arr, 1)
    ax_1_x = np.size(arr, 0)
    n = []
    ofssets = [-1, 0, 1]

    for x in ofssets:
        for y in ofssets:
            if x == 0 and y == 0: continue
            if y j < 0 or y j == ax_0_y: continue
            if x i < 0 or x i == ax_1_x: continue
            n.append(arr[x i][y j])

    return  n

main loop:

def main():
    grid = np.zeros((GRID_WIDTH, GRID_HEIGHT), dtype=numpy.short)
    ....
    drawGrid(display) #drawing cells line separators

    randomise(grid) #random gereation alive cells

    while True:
        for i in pg.event.get():
            if i.type == pg.QUIT:
                quit()

        updateCells(grid)

        drawCells(display, grid) #drawing squares

        pg.display.update()
        fpsClock.tick(UPDATE_TIME)


if __name__ == "__main__":
    main()

CodePudding user response:

You can’t update the grid as you go, because then cells you get to later in the scan will have some neighbors from the current generation and some from the new one and will get the wrong neighbor count.

You have to do the whole grid as if it all updates at the same time, which means either having a second grid to build the new generation in or creating a list of changes to make to the grid at the end of the scan.

CodePudding user response:

Some of the cells might not die due to you changing the field before the checks, like mentioned in the previous answer. You also seem to have quiet a bit of unneccessary code, like

if count == 2 or count == 3:
    grid[i][j] = 1
    continue

For example. If there is no dying cells at all, i would like you to show us the code that calls your function.

  • Related