我是一个非常新的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”。
答案 0 :(得分:0)
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