Python conway's game of life not updating result

Question:

I’m a beginner in python and I’m trying to make a conway’s game of life implementation.
I can’t find the problem in my code below, it’s like the nextstate of the plan is not updating it self, the output stays constant instead of varying.

import time, random, copy

W = 60   #width 
H = 20   #height 

nextstate = []
for x in range(W):
    cx = []  #new column
    for y in range(H):
        if random.randint(0, 1) == 0:
            cx.append('#')
        else:
            cx.append(' ')
    nextstate.append(cx)

while True:
    print('nnn')
    nowstate = copy.deepcopy(nextstate)

    for y in range(H):
        for x in range(W):
            print(nowstate[x][y], end='')
        print()
    #compute nextstep
    for x in range(W):
        for y in range(H): #get neighbor's coordinates
            Lc = (x-1) % W
            Rc = (x+1) % W
            UPc = (y-1) % H
            DOWNc = (y+1) % H

            aliveN = 0                 #counting number of alive neighbors
            if nowstate[Lc][UPc] == '#':
                aliveN += 1
            if nowstate[x][UPc] == '#':
                aliveN += 1
            if nowstate[Rc][UPc] == '#':
                aliveN += 1
            if nowstate[Lc][y] == '#':
                aliveN += 1
            if nowstate[Rc][y] == '#':
                aliveN += 1
            if nowstate[Lc][DOWNc] == '#':
                aliveN += 1
            if nowstate[x][DOWNc] == '#':
                aliveN += 1
            if nowstate[Rc][DOWNc] == '#':
                aliveN += 1
            
            #conway's rules
            if nowstate[x][y] == '#' and (aliveN == 2 or aliveN == 3):
                nextstate[x][y] == '#'
            elif nowstate[x][y] == ' ' and aliveN == 3:
                nextstate[x][y] == '#'
            else:
                nextstate[x][y] == ' '
    time.sleep(1)
Asked By: nis bn

||

Answers:

The problem is in your implementation of conway’s rules.

Remember that when we check for equality, to return a boolean value, we use ==. However, for assignment, we use the singular equals, =.

That means you should edit your code as so:

        #conway's rules
        if nowstate[x][y] == '#' and (aliveN == 2 or aliveN == 3):
            nextstate[x][y] = '#'
        elif nowstate[x][y] == ' ' and aliveN == 3:
            nextstate[x][y] = '#'
        else:

I believe this will fix your error. Let me know if you have any further questions or clarification!

Answered By: Aniketh Malyala
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.