[英]Issue with Conway's Game of Life in 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 & Cell.neighbours <= 1:
Cell.state = 0
elif Cell.state == 1 & Cell.neighbours in [2,3]:
Cell.state = 1
elif Cell.state == 1 & Cell.neighbours == 4:
Cell.state = 0
elif Cell.state == 0 & 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)
```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.