Python 3.x Python Conway';人生的游戏
我正在尝试制作康威的生活游戏,在游戏中,用户输入他们想要的网格有多大,哪些细胞开始时是活的。以下是我所拥有的:Python 3.x Python Conway';人生的游戏,python-3.x,Python 3.x,我正在尝试制作康威的生活游戏,在游戏中,用户输入他们想要的网格有多大,哪些细胞开始时是活的。以下是我所拥有的: def firstBoard(rows, cols, array): myList = [[0]*cols for i in range(rows)] for i in myList: i.append(-1) i.insert(0,-1) myList.insert(0,[-1]* (cols+2)) myList.ap
def firstBoard(rows, cols, array):
myList = [[0]*cols for i in range(rows)]
for i in myList:
i.append(-1)
i.insert(0,-1)
myList.insert(0,[-1]* (cols+2))
myList.append([-1]* (cols+2))
while True:
rows = input("Enter the row or 'q': ")
if rows == 'q':
break
cols = input("Enter the column: ")
print()
myList[int(rows)][int(cols)] = 1
return myList
def nextGen(cols, rows, cur, nxt):
for i in range(1,rows-1):
for j in range(1,cols-1):
nxt[i][j] = processNeighbours(i, j, cur)
def processNeighbours(x, y, array):
nCount = 0
for j in range(y-1,y+2):
for i in range(x-1,x+2):
if not(i == x and j == y):
if array[i][j] != -1:
nCount += array[i][j]
if array[x][y] == 1 and nCount < 2:
return 0
if array[x][y] == 1 and nCount > 3:
return 0
if array[x][y] == 0 and nCount == 3:
return 1
else:
return array[x][y]
def printBoard(cols, rows, array):
for i in range(rows+2):
for j in range(cols+2):
if array[i][j] == -1:
print("#", end=" ")
elif array[i][j] == 1:
print(".", end=" ")
else:
print(" ", end=" ")
print()
def main():
rows = int(input("Please enter the number of rows: "))
cols = int(input("Please enter the number of columns: "))
myList = []
newList = []
myList = firstBoard(rows, cols, myList)
newList = myList
print()
generations = int(input("How many iterations should I run? "))+1
for gens in range(generations):
printBoard(cols, rows, myList)
nextGen(cols, rows, myList, newList)
myList, newList = newList, myList
main()
对于第二个和第四个框,点应该是水平的,而不是垂直的。请帮助我,我整天都在处理这个问题,我想不出来。问题在于您的阵列初始化:
newList = myList
这并不是复制myList
,而是让newList
引用myList
,这样您就只有一个数组了。可以像这样复制二维阵列:
from copy import copy, deepcopy
newList = deepcopy(myList)
from copy import copy, deepcopy
newList = deepcopy(myList)