无法从函数中正确地 return 布尔值
Unable to return boolean value properly from a function
我是一个非常新的 python 学习者,正在尝试在 python 中制作井字游戏。使用我当前的代码行,我无法正确 return 布尔值。
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”,循环也不会 break/terminate 但它仍然打印“Player X Won”。
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
我是一个非常新的 python 学习者,正在尝试在 python 中制作井字游戏。使用我当前的代码行,我无法正确 return 布尔值。
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”,循环也不会 break/terminate 但它仍然打印“Player X Won”。
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