在python中满足条件时无法退出

时间:2018-09-09 06:11:25

标签: python-3.x while-loop

我正在尝试用python3制作井字游戏。我可以使游戏正常运行,但是当有人赢得游戏时,Ì无法获得终止代码。我尝试了很多方法,但是都没有用:

def find_winner(board,gameIsOn): 
if ((board[7]==board[8]==board[9]) and board[7]!= '') or ((board[4]==board[5]==board[6]) and board[4]!= '') or ((board[1]==board[2]==board[3]) and board[7]!= ''):
    gameIsOn = False
    print('winner!')


elif ((board[7]==board[4]==board[1]) and board[7]!= '') or ((board[8]==board[5]==board[2]) and board[8]!= '') or ((board[9]==board[6]==board[3]) and board[9]!= ''):
    gameIsOn = False
    print('winner!')


elif ((board[7]==board[5]==board[3]) and board[7]!= '') or ((board[9]==board[5]==board[1]) and board[7]!= ''):

    gameIsOn = False
    print('winner!')

这是我用来确定某人是否获胜的功能。如果有人赢了,gameIsOn变量将设置为False。否则为True

while(gameIsOn):
if(active_Player == player_1):
        position = int(input('Position?'))
        player_input(board,active_Player,position)
        print_board(board)
        find_winner(board,gameIsOn)
        active_Player = player_2           
else:
        position = int(input('Position?'))
        player_input(board,active_Player,position)
        print_board(board)
        find_winner(board,gameIsOn)**

上面的代码是游戏的主体。如果有人赢了游戏,则忽略其他功能,find_winner函数应将gameIsOn的值设置为False。但是即使有人赢了,比赛也不会结束。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您正在将gameIsOn变量传递给find_winner函数,该变量在那里成为局部变量,因此对gameIsOn的更改不会反映给调用者。您应该使find_winner将布尔值返回给调用方,并让调用方将返回值分配给其范围内的gameIsOn变量。

def find_winner(board):
    if ((board[7]==board[8]==board[9]) and board[7]!= '') or ((board[4]==board[5]==board[6]) and board[4]!= '') or ((board[1]==board[2]==board[3]) and board[7]!= ''):
        return False

    elif ((board[7]==board[4]==board[1]) and board[7]!= '') or ((board[8]==board[5]==board[2]) and board[8]!= '') or ((board[9]==board[6]==board[3]) and board[9]!= ''):
        return False

    elif ((board[7]==board[5]==board[3]) and board[7]!= '') or ((board[9]==board[5]==board[1]) and board[7]!= ''):
        return False
    return True

gameIsOn = True
while(gameIsOn):
    if(active_Player == player_1):
        position = int(input('Position?'))
        player_input(board,active_Player,position)
        print_board(board)
        gameIsOn = find_winner(board)
        active_Player = player_2           
    else:
        position = int(input('Position?'))
        player_input(board,active_Player,position)
        print_board(board)
        gameIsOn = find_winner(board)
        active_Player = player_1

答案 1 :(得分:0)

您可以使用sys.exit()exit()