简体   繁体   English

无法从 function 正确返回 boolean 值

[英]Unable to return boolean value properly from a function

I am a very new python learner and trying to make a tic tac toe game in python. With my current lines of code I am unable to return boolean values properly.我是一个非常新的 python 学习者,正在尝试在 python 中制作井字游戏。使用我当前的代码行,我无法正确返回 boolean 值。

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()

This only has a single winning position but I will add that later.这只有一个中奖 position 但我稍后会添加。 The problem is that even after the board list has index 0 to index 2 as "X" the loop doesn't break/terminate but it still prints "Player X Won".问题是,即使在棋盘列表的索引 0 到索引 2 为“X”之后,循环也不会中断/终止,但它仍然会打印“Player X Won”。

The win_checker function is working properly. win_checker function 运行正常。 It is returning the boolean values.它返回 boolean 值。 But, you are not saving the returned boolean values to any variable.但是,您没有将返回的 boolean 值保存到任何变量。

Inside the while loop you have to save the returned value to a variable.在 while 循环中,您必须将返回值保存到一个变量中。 Change your play_game function with this,用这个改变你的play_game function,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM