我/我是否将其作为函数递归?

时间:2015-03-28 22:37:32

标签: python tkinter

我有三个游戏功能,如下:

def round():
    global board
    board_copy = [[x for x in row] for row in board]
    for row in range(n):
        for col in range(n):
            if countNeighbors(row,col) == 3:
                board_copy[row][col] = LIVE
                canvas.itemconfigure(rect[row][col],fill='red')
            elif countNeighbors(row,col) > 3 or countNeighbors(row,col) < 2:
                board_copy[row][col] = DEAD
                canvas.itemconfigure(rect[row][col],fill='black')
    board = board_copy

def start():
    round()
    global alarm
    alarm = window.after(500,round)

def stop():
    global alarm
    window.after.cancel(alarm)

我希望start()函数每500毫秒运行一次round(),直到用户调用stop()(带一个按钮)。但是,在完全停止之前,调用start()只会给我两次round()的迭代。

1 个答案:

答案 0 :(得分:5)

你可以试试这个:

game_active = True

def round():
    global board, alarm, game_active

    if not game_active:
      return

    board_copy = [[x for x in row] for row in board]
    for row in range(n):
        for col in range(n):
            if countNeighbors(row,col) == 3:
                board_copy[row][col] = LIVE
                canvas.itemconfigure(rect[row][col],fill='red')
            elif countNeighbors(row,col) > 3 or countNeighbors(row,col) < 2:
                board_copy[row][col] = DEAD
                canvas.itemconfigure(rect[row][col],fill='black')
    board = board_copy

    alarm = window.after(500, round)

def start():
    global game_active
    game_active = True
    round()

def stop():
    global alarm, game_active
    window.after.cancel(alarm)
    game_active = False

基本上,我们一次又一次地进行圆函数调用。