我正在编写一种元胞自动机,它的邻居越多,它使细胞存活的机会就越高(1),但在尝试检查边缘或角落的细胞上的邻居数量时,显然会出现错误因为我无法检查例如最右侧单元格右侧的单元格是否存活,但我希望它然后绕到最左侧并检查这些单元格。
我知道我可以检查我正在查看的单元格在哪里,但这会将 amt() 中的代码量增加到大约 9 倍,我认为这太多了,我认为可能有一种方法可以做到这一点更整洁。
from random import randint
global board
board = []
csize = 69
rsize = 69
for col in range(csize):
board.append([])
for row in range(rsize):
#board[col].append(0)
if col == 0:
board[col].append(1)
else:
board[col].append(0)
def ranize():
for col in range(len(board)):
for row in range(len(board)):
board[col][row] = randint(0,1)
def check():
for col in range(len(board)):
for row in range(len(board)):
if board[col][row] == 1:
return True
return False
def show():
loc = "\n"
for col in range(len(board)):
for row in range(len(board[col])):
if board[col][row] == 1:
loc += "@ "
else:
loc += f"{amt(col, row)} "
loc += "\n"
print(loc, end = "\r")
def amt(col ,row):
loc = 0
if col != 0 and col != csize-1 and row != 0 and row != rsize-1: #Center board
if board[col-1][row-1] == 1: #Check Col-1
loc += 1
if board[col-1][row] == 1:
loc += 1
if board[col-1][row+1] == 1:
loc += 1
if board[col][row-1] == 1: #Check Col
loc += 1
if board[col][row+1] == 1:
loc += 1
if board[col+1][row-1] == 1: #check Col+1
loc += 1
if board[col+1][row] == 1:
loc += 1
if board[col+1][row+1] == 1:
loc += 1
return(loc)
def onestep():
if not check():
input("All cells dead, press Enter to randomize board: ")
ranize()
for col in range(len(board)):
for row in range(len(board[col])):
neighbors = amt(col, row)
ranum = randint(0, 8)
if board[col][row] == 1:
if 8-neighbors > ranum:
board[col][row] = 0
else:
if neighbors > ranum:
board[col][row] = 1
while True:
show()
onestep()
# input()
不要加 1,而是减 68(或一般情况下
size - 1
)。