范围本地v全局

时间:2016-10-09 21:32:20

标签: python

我正在尝试重新创建康威的生命游戏,并意识到我必须创建两个版本的游戏板(代表一个嵌套数组),其中包含活细胞(1)和死细胞(0)的值。我正在使用IDLE来完成这个项目。 github链接是here

我正在努力创造两个不同的游戏板。我这样做的目的是防止更新的细胞影响其他细胞。即使我用一个值而不是另一个更新一个电路板,它们最终会有相同的值。下面是我的代码片段。我尝试使用更新的板创建一个名为board的全局变量,该变量与局部变量分开。虽然我没有在我的函数中直接更新它,但我对某些板如何更新有点神秘 - 我是否指定全局变量错了?感谢您的耐心,我仍然是初学者。

我在哪里创建局部变量upboard

Class checkState:
    """this class will update the neighboring cells according to Jon Conway's rules of the game of life"""
    def __init__(self, upboard, size):#updateBoard will provide the initial living cells, but this will selfupdate
        self.upboard=upboard
        self.size=size

    def rules(self): #cycle through array coordinates of the board and apply rules to each coordinate
        b=self.upboard
        global board
        neighborcells=[[i,j] for j in range(len(b[i])) for i in range(len(b))]
        #print('neighborcells are '+str(neighborcells)) #a list of board coordinates

启动程序的代码,我定义了board,我的全局变量

firstgame=newgame.updateBoard()#first  gameboard
print('this is firstgame '+str(firstgame))
board=firstgame #initially set board to firstgame value

#Print Board
print('this is out what the board looks like in the beginning')
startGame=printBoard(firstgame, size) #this is out what the board looks like in the beginning


print('print the board () refers to the instance we just created ')
startGame.pBoard() #print the board () refers to the instance we just created 


repeat=int(input('enter the number of times you would like this to repeat'))

x=checkState(firstgame, size) 
print('checkstate is the original value of x: ' + str(x))

###MAIN LOOP###

for i in range(repeat):

    print('i is ' + str(i))
    newboard=x.rules() #returns a NEW board
    x=checkState(newboard, size) #saves the state of NEW board for the next iteration

    ###PRINTS THE BOARD###
    printupdate=printBoard(newboard, size)
    printupdate.pBoard()

    board=newboard #for global variable of original board

    if i==repeat:
        break;

0 个答案:

没有答案