【问题标题】:Unable to return boolean value properly from a function无法从函数正确返回布尔值
【发布时间】:2020-09-20 14:19:03
【问题描述】:

我是一个非常新的 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”。

【问题讨论】:

  • 您的代码还存在一些其他问题,您很快就会发现 - 但最直接的问题是因为您从未在循环内更新 game_running 的值。您应该将这些对win_checker() 的调用替换为game_running = win_checker(),以便使用返回值。 (编辑:你还需要在你的函数中 global game_running 才能工作。)
  • 制作一个测试用例,玩家 O 拥有其中一个方块。
  • 如前所述,这里有很多问题。另一个是“获胜”测试:if board[0] and board[1] and board[2] == "X" 将检查 board[1] 是否设置为任何值,与 board[2] 相同,然后它会查看 board[3] == "X",所以基本上,因为位置 1 和 2始终设置(即使设置为“-”),一旦位置 3 设置为“X”,这将是正确的。
  • if board[0] and board[1] and board[2] == "X" 不是检查所有这些值是否都等于 X 的正确方法。试试if board[0] == board[1] == board[2] == "X"
  • 谢谢大家,非常感谢您抽出宝贵的时间来回答。

标签: python loops return break


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-02-03
    • 2018-08-11
    • 2013-09-15
    • 2013-03-11
    • 2013-09-11
    • 2020-07-25
    • 2017-06-07
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多