我只是想验证一个tic tac toe board,其值在列表列表中。
board = ([1, 2, 0], [2, 1, 0], [2, 1, 2])
def print_winner(variable):
if variable == 1:
return print("Winner of this board is Player1")
else:
return print("Winner of this board is Player2")
def interpret(game_board):
if game_board[0][0] != 0:
if game_board[0][1] and game_board[0][2] == game_board[0][0]:
print(print_winner(game_board[0][0]))
elif game_board[1][0] and game_board[2][0] == game_board[0][0]:
print(print_winner(game_board[0][0]))
elif game_board[1][1] and game_board[2][2] == game_board[0][0]:
print(print_winner(game_board[0][0]))
elif game_board[0][1] != 0:
if game_board[1][1] and game_board[2][1] == game_board[0][1]:
print(print_winner(game_board[0][0]))
elif game_board[0][2] != 0:
if game_board[1][2] and game_board[2][2] == game_board[0][2]:
print(print_winner(game_board[0][0]))
elif game_board[1][2] and game_board[2][0]:
print(print_winner(game_board[0][0]))
elif game_board[1][0] != 0:
if game_board[1][1] and game_board[1][2] == game_board[1][0]:
print(print_winner(game_board[0][0]))
elif game_board[2][0] != 0:
if game_board[2][1] and game_board[2][2] == game_board[2][0]:
print(print_winner(game_board[0][0]))
else:
print("No Winner")
interpret(board)
上面代码的问题是我不知道如何在我的第一个嵌套if语句失败后指示我的程序继续使用剩下的代码。因为我的代码没有给出任何输出。
预期输出为"No winner"
。
答案 0 :(得分:1)
第一个问题是您错误地使用了and
。您需要在and
的任一操作数上指定条件。例如:
if game_board[0][1] == game_board[0][0] and game_board[0][2] == game_board[0][0]
OR
if game_board[0][1] == game_board[0][2] == game_board[0][0]
而不是:
if game_board[0][1] and game_board[0][2] == game_board[0][0]
但是,您也可以使用set
并检查它是否只包含一个数字:
if len({game_board[0][0], game_board[0][1], game_board[0][2]}) == 1:
关于
的实际问题一旦我的第一个嵌套if语句失败,如何指示我的程序继续使用剩下的代码
实际上非常简单。如果一个条件匹配,请使用普通if
和return
。
与其他一些改进(你总是打印game_board[0][0]
)一起,它看起来像这样:
def interpret(game_board):
if game_board[0][0] != 0:
if len({game_board[0][0], game_board[0][1], game_board[0][2]}) == 1:
return print(print_winner(game_board[0][0]))
elif len({game_board[0][0], game_board[1][0], game_board[2][0]}) == 1:
return print(print_winner(game_board[0][0]))
elif len({game_board[0][0], game_board[1][1], game_board[2][2]}) == 1:
return print(print_winner(game_board[0][0]))
if game_board[0][1] != 0:
if len({game_board[0][1], game_board[1][1], game_board[2][1]}) == 1:
return print(print_winner(game_board[0][1]))
if game_board[0][2] != 0:
if len({game_board[0][2], game_board[1][2], game_board[2][2]}) == 1:
return print(print_winner(game_board[0][2]))
elif len({game_board[0][2], game_board[1][1], game_board[2][0]}) == 1:
return print(print_winner(game_board[0][2]))
if game_board[1][0] != 0:
if len({game_board[1][0], game_board[1][1], game_board[1][2]}) == 1:
return print(print_winner(game_board[1][0]))
if game_board[2][0] != 0:
if len({game_board[2][0], game_board[2][1], game_board[2][2]}) == 1:
return print(print_winner(game_board[2][0]))
return print("No Winner")
这是有效的,因为print
会返回None
并打印到stdout
。