python - 康威在 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)
```
解决方案
推荐阅读
- javascript - 对 FCM 执行 POST 请求时服务器密钥无效?
- java - 在 Java 中观察关于 OutOfMemoryError 的奇怪行为
- javascript - 如何将 DataTable 与对象数组一起使用?
- python - 如何在 Python 中的简单 Compsci 101 APT 中修复我的代码
- python - 在python中组合两个csv - 如果在较新的csv中存在则更新
- .net - 如何正确访问 .cshtml 中条件的 ViewModel 属性
- python - sqlalchemy.orm.scoping.scoped_session 代理能力是如何实现的?
- monaco-editor - 在 monaco 编辑器中关闭 Completion Modal 的命令 (editor.action)
- java - 如何在 Java/Hibernate 中获取实体类的列名称字符串
- numpy - numpy / 线性代数 - 快速 16 位直方图