python - 无法从函数正确返回布尔值
问题描述
我是一个非常新的 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”。
解决方案
该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
推荐阅读
- c# - 可以明确定义电子邮件的 S/MIME 内容类型吗?
- angular - 如何从子组件获取输入事件到父组件上的指令
- java - java - 如何使用三元运算符将有时可能为空的字符串转换为Java中的整数?
- java - 使用 Java 进行大约 20 次 HTTP 调用并将数据传递到数据库
- c++ - 如果未注释 C++ 方法,则强制 Doxygen 弹出警告
- javascript - Fabricjs - 在一个文档中渲染多个画布
- ios - 为独立构建的目标文件 (BlackBerry Dynamics iOS SDK)
- javascript - 为什么使用相同的代码,Firestore 不能在 NodeJS 中工作,但在浏览器中工作?
- jenkins - 我们可以覆盖来自 Jenkins 的文件吗
- extjs - 如何在 ExtJs 中从 tpl 调用函数