简体   繁体   中英

All cells in Conway's game of life are alive

I tried to implement Conway's game of life in Python-3.6 with this code:

import numpy as np
import time

screen = np.zeros((25,25),dtype=np.int)
while True:
    print(screen)
    command = input('command?')
    if command[0] == 'x':
        command = command.split(' ')
        x = int(command[0][1:])
        y = int(command[1][1:])
        if screen[x][y] == 0:
            screen[x][y] = 1
        else:
            screen[x][y] = 0
    elif command == 'start':
        break

while True:
    for x in range(len(screen)):
        for y in range(len(screen[x])):
            neighbors = 0
            if x != len(screen)-1:
                neighbors += screen[x+1][y]
            if x != 0:
                neighbors += screen[x-1][y]
            if y != len(screen[x])-1:
                neighbors += screen[x][y+1]
            if y != 0:
                neighbors += screen[x][y-1]
            if x != len(screen)-1 and y != len(screen[x])-1:
                neighbors += screen[x+1][y+1]
            if x != 0 and y != 0:
                neighbors += screen[x-1][y-1]
            if 0 and y != len(screen[x])-1:
                neighbors += screen[x-1][y+1]
            if x != len(screen)-1 and y != 0:
                neighbors += screen[x+1][y-1]

            if screen[x][y] == 0 and neighbors == 3:
                screen[x][y] = 1
            elif screen[x][y] == 1 and neighbors < 2:
                screen[x][y] == 0
            elif screen[x][y] == 1 and neighbors > 3:
                screen[x][y] == 0
            elif screen[x][y] == 1 and neighbors == 2 or 3:
                screen[x][y] = 1
    print(screen)
    time.sleep(0.1)

The Problem is that when I try to run this code with any figure, all the cells are immediately set to 1 in the first generation and won't die off.

Can someone tell me were the issue in my code is and how to solve it?

Your problem seems to be here:

        elif screen[x][y] == 1 and neighbors == 2 or 3:

You can't do that (well, you can, but it doesn't do what you expect). Instead try:

        elif screen[x][y] == 1 and neighbors in (2 , 3):

(or in {2, 3} ).

Check this question for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM