[英]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.