首页 > 解决方案 > 无法从函数正确返回布尔值

问题描述

我是一个非常新的 Python 学习者,正在尝试用 Python 制作井字游戏。使用我当前的代码行,我无法正确返回布尔值。

board = ['-', '-', '-',
         '-', '-', '-',
         '-', '-', '-']


def display_board():
    print(f"{board[0]} | {board[1]} | {board[2]}")
    print(f"{board[3]} | {board[4]} | {board[5]}")
    print(f"{board[6]} | {board[7]} | {board[8]}")


def win_checker():
    if board[0] and board[1] and board[2] == "X":
        print("Player X Won!")
        return False
    else:
        return True


game_running = win_checker()


def play_game():
    while game_running:
        player_move = int(input("Select from 1 - 9: "))
        board[player_move - 1] = "X"
        display_board()
        win_checker()
        player_move = int(input("Select from 1 - 9: "))
        board[player_move - 1] = "0"
        display_board()
        win_checker()


display_board()
play_game()

这只有一个获胜位置,但我稍后会添加。问题是,即使在棋盘列表的索引 0 到索引 2 为“X”之后,循环也不会中断/终止,但仍会打印“Player X Won”。

标签: pythonloopsreturnbreak

解决方案


win_checker功能工作正常。它正在返回布尔值。但是,您不会将返回的布尔值保存到任何变量中。

在 while 循环中,您必须将返回的值保存到变量中。用这个改变你的play_game功能,

def play_game():
while game_running:
    player_move = int(input("Select from 1 - 9: "))
    board[player_move - 1] = "X"
    display_board()
    game_running = win_checker() # updated
    player_move = int(input("Select from 1 - 9: "))
    board[player_move - 1] = "0"
    display_board() 
    game_running = win_checker()# updated

推荐阅读