Проблема с игрой Конвея в жизнь на Python

#python #conways-game-of-life

#python #конвей — игра в жизнь

Вопрос:

Я пытался создать игру в жизнь на python, но я изо всех сил пытался получить правильный результат независимо от того, как я пишу правила, поэтому я не слишком уверен, где я ошибаюсь.

Я пытался написать свои правила для многократного перебора ячеек, написания базового кода для использования нескольких списков или использования списков классов, но каждый раз результат получается неправильным, и после 5 или около того итераций симуляция просто останавливается.

Вот мой исходный код:

 import os
import random
import time
 
class Cell():
    def __init__(self, ID, state, previous_state, neighbours, index):
        self.ID = ID
        self.state = state
        self.previous_state = previous_state
        self.neighbours = neighbours
        self.index = index
 
    def Get_Neighbours(self,grid):
        neighbours = 0
        index_y = self.index[0]
        index_x = self.index[1]
 
        if index_x < height - 1:
            if grid[index_x   1][index_y].state == 1:
                neighbours  = 1
        if index_x > 0:
            if grid[index_x - 1][index_y].state == 1:
                neighbours  = 1
        if index_y < width - 1:
            if grid[index_x][index_y   1].state == 1:
                neighbours  = 1
        if index_y > 0:
            if grid[index_x][index_y - 1].state == 1:
                neighbours  = 1
        return neighbours
 
def Draw_grid(grid):
    os.system("cls") 
    for Cells in Cell_grid:
        print_row = []
        for Cell in Cells:
            if Cell.state == 1:
                print_row.append("#")
            else:
                print_row.append(" ")
        print(" ".join(print_row))
    print(Cell_grid[1][1].neighbours)
    time.sleep(.5)
 
def Iterate_Cells(Cell_grid):
    for Cells in Cell_grid:
        for Cell in Cells:
            Cell.neighbours = Cell.Get_Neighbours(Cell_grid)
            if Cell.state == 1 amp; Cell.neighbours <= 1:
                Cell.state = 0
            elif Cell.state == 1 amp; Cell.neighbours in [2,3]:
                Cell.state = 1
            elif Cell.state == 1 amp; Cell.neighbours == 4:
                Cell.state = 0
            elif Cell.state == 0 amp; Cell.neighbours == 3:
                Cell.state = 1
 
"""
A cell dies if it has less than two living neighbors.
A cell survives until the next generation if it has two or three neighbors.
A cell with more than three neighbors dies.
A dead cell with exactly three neighbors turns into a living cell.
"""
 
width = 30
height = 30
interation = 0
 
Cell_grid = [[Cell(0,0,0,0,0) for i in range(width)] for j in range(height)]
counter = 0
 
""" initialize cells """
for i in range(width):
    for j in range(height):
 
        alive_seed = random.random()
        if alive_seed > .2:
            Cell_grid[i][j].state = 1
        else:
            Cell_grid[i][j].state = 0
 
        Cell_grid[i][j].index = (i,j)
 
        Cell_grid[i][j].ID = counter
        counter  = 1
 
while True:
    Draw_grid(Cell_grid)
    Iterate_Cells(Cell_grid)
    ```

  

Комментарии:

1. Вы должны создавать новую сетку с каждой итерацией, в отличие от обновления текущей (поскольку ваши новые и старые состояния смешиваются).

Ответ №1:

Одна проблема здесь и в подобных проверках:

 if Cell.state == 1 amp; Cell.neighbours <= 1
  

amp; является побитовым оператором AND, а не логическим AND. Глядя на правила приоритета операторов, это будет проанализировано как:

 if Cell.state == (1 amp; Cell.neighbours) <= 1
  

которая, благодаря цепочке сравнений, расширяется как:

 if Cell.state == (1 amp; Cell.neighbours) and (1 amp; Cell.neighbours) <= 1
  

Вместо этого вам нужно использовать and ключевое слово:

 if Cell.state == 1 and Cell.neighbours <= 1