Python Conway的生命游戏

时间:2015-04-08 02:07:29

标签: 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.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()

如果对于行和列,我输入五个,如果我填写3,4 4,4 5,4我得到这个:

# # # # # # #
#           #  
#           #
#       .   #
#       .   #
#       .   #
# # # # # # #
# # # # # # #
#           #
#           #
#       .   #
#       .   #
#       .   #
# # # # # # #
# # # # # # #
#           #
#           #
#       .   #
#       .   #
#       .   #
# # # # # # #
# # # # # # #
#           #
#           #
#       .   #
#       .   #
#       .   #
# # # # # # #

对于第二个和第四个框,点应该是水平的而不是垂直的。请帮助我一整天都在努力,我无法弄清楚。

1 个答案:

答案 0 :(得分:1)

问题在于数组初始化:

newList = myList

这不是myList的副本,它只是让newList引用myList,所以你只有一个数组。您可以像这样复制2D数组:

from copy import copy, deepcopy

newList = deepcopy(myList)