Skip to main content
 首页 » 编程设计

Python之Conways 生命游戏

2024年10月24日10lidabo

<分区>

我的过程似乎不适用于下一次迭代。我在 main 中有深拷贝,我认为问题在于它们以及何时调用它们。

抱歉,间距有点小。

问题出在我的结果中,它用活细胞打印了第一次迭代。然后下一次迭代是空白的,并且显示单元格没有变化。

LIVING_CELL = 'A' 
DEAD_CELL = '.' 
 
#Get the alive cells from the user 
def getBoard(rows, cols, boardList): 
   myList = [[0]*cols for i in range(rows)] 
 
   while True: 
 
        aliveRows = input("Please enter a row of a cell to turn on (or q to exit): ") 
        if aliveRows == 'q': 
            break 
        aliveCols = input("Please enter a column for that cell: ") 
        print() 
        myList[int(aliveRows)][int(aliveCols)] = 1 
   return myList 
 
#next board cells 
def getNxtIter(cols, rows, cur, nxt): 
    for i in range(1,rows-1): 
        for j in range(1,cols-1): 
            nxt[i][j] = getNeighbors(i, j, cur) 
 
#Processing the neighbor cells 
def getNeighbors(x, y, boardList): 
    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 boardList[i][j] != -1: 
                    nCount += boardList[i][j] 
    if boardList[x][y] == 1 and nCount < 2: 
        return 0 
    if boardList[x][y] == 1 and nCount > 3: 
       return 1 
    else: 
        return boardList[x][y] 
 
#Printing and forming the actual board 
def printBoard(cols, rows, boardList): 
    for i in range(rows+2): 
        for j in range(cols+2): 
            if boardList[i][j] == -1: 
                print(DEAD_CELL, end=" ") 
            elif boardList[i][j] == 1: 
                print(LIVING_CELL, end=" ") 
            else: 
               print(DEAD_CELL, end=" ") 
        print() 
 
def main(): 
#Getting and validating the number of rows and columns 
    x = 1 
    while x ==1: 
 
        rows = int(input("Please enter the number of rows: ")) 
        if rows < 0: 
            x = 1 
        elif rows> 50: 
            x = 1 
        else: 
            x =0 
 
    n = 1 
    while n == 1: 
        cols = int(input("Please enter the number of columns: ")) 
        if cols < 0: 
            n = 1 
        elif cols > 50: 
            n = 1 
        else: 
            n = 0 
 
    boardList = [] 
    newBoardList = [] 
    boardList = getBoard(rows, cols, boardList) 
    newBoardList = [x[:] for x in boardList] 
 
    print() 
 
#Getting iterations to run, and validating if <= 0 
    a = 1 
    while a == 1: 
        iterations = int(input("How many iterations should I run? "))+1 
        if iterations <= 0: 
            a = 1 
        else: 
            a = 0 
    for count in range(iterations): 
        print() 
        print("Iteration:", count) 
        print() 
        printBoard(cols, rows, boardList) 
        getNxtIter(cols, rows, boardList, newBoardList) 
        boardList = [x[:] for x in newBoardList] 
        newBoardList = [x[:] for x in boardList] 
main()