我正在编写一个脚本,它生成一个包含三维空间中立方体位置的字典,计算每个立方体的邻居,然后根据康威的生命游戏中的规则计算新的迭代。我的网格是偶数元组的字典,如下所示:
grid = {(0, 0, 0): True, (0, 0, 2): True, (2, 0, 0): True, (2, 0, 2): True, (0, 2, 0): True, (0, 2, 2): True, (2, 2, 0): True, (2, 2, 2): True}True或False表示单元格是alive还是dead。
为了计算每个立方体的摩尔邻居,我编写了以下函数:
# Calculates the neighbors of a cell
def get_neighbors(grid, x,y,z):
count = 0
for pos in (
# List out all possible neighbours of cell
(x-2,y-2,z-2),
(x-2,y-2,z),
(x-2,y-2,z+2),
(x-2,y,z-2),
(x-2,y,z),
(x-2,y,z+2),
(x-2,y+2,z-2),
(x-2,y+2,z),
(x-2,y+2,z+2),
(x,y-2,z-2),
(x,y-2,z),
(x,y-2,z+2),
(x,y,z-2),
(x,y,z+2),
(x,y+2,z-2),
(x,y+2,z),
(x,y+2,z+2),
(x+2,y-2,z-2),
(x+2,y-2,z),
(x+2,y-2,z+2),
(x+2,y,z-2),
(x+2,y,z),
(x+2,y,z+2),
(x+2,y+2,z-2),
(x+2,y+2,z),
(x+2,y+2,z+2)):
if pos in grid:
# If the neighbour is alive, add 1 to the count
if grid[pos] == True:
count += 1
return count
# Checks if a cell is alive
def is_alive(grid, x,y,z):
if (x,y,z) in grid:
if grid[(x,y,z)] == True:
return True
return False这将正确地输出邻居数,并返回给定的元组是否有True或False。为了计算下一次迭代并包含生命游戏规则,我写道:
# Calculates the next iteration of the game
def next_iteration(grid):
new_grid = {}
length = len(grid)
# Iterate through the grid with range step size of 2,
# since we only have even numbers in the tuples.
for x in range(0,length, 2):
for y in range(0,length, 2):
for z in range(0,length, 2):
# Get the number of neighbors of the cell
neighbors = get_neighbors(grid, x,y,z)
if is_alive(grid, x,y,z):
# If the cell is alive, check if it should die
if neighbors < 2:
new_grid[(x,y,z)] = False
elif neighbors > 3:
new_grid[(x,y,z)] = False
else:
new_grid[(x,y,z)] = True
else:
# If the cell is dead, check if it should be alive
if neighbors == 3:
new_grid[(x,y,z)] = True
else:
new_grid[(x,y,z)] = False
return new_grid但是,如果我生成一个2x2x2网格并尝试计算三次迭代,就会得到这 (仅附加输出的一部分),其中everything是False。这似乎不对。
我的代码做错了什么?我是否没有正确计算邻居,还是规则没有得到正确的检查?
如何正确地实现这个三维生命游戏?
我的完整脚本是这里
发布于 2021-10-22 04:20:59
实际上,您的代码有时会产生一些True值--取决于初始配置。但是,几乎所有的值都是False,因为在每次迭代时,您都在扩展网格,包括许多远离任何活单元的单元格,因此它们的值必须是False。具体情况如下:
https://stackoverflow.com/questions/69671042
复制相似问题