在井字游戏中选择位置的功能



我想弄清楚如何实现一个函数,将存储和打印用户想要放置"X"在井字游戏中如果有任何其他建议,你必须修复我的代码,这将是非常感激。我刚开始写代码,如果它看起来很糟糕,我很抱歉。

def print_board():
game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
print(game_board[0] + " | " + game_board[1] + " | " + game_board[2])
print(game_board[3] + " | " + game_board[4] + " | " + game_board[5])
print(game_board[6] + " | " + game_board[7] + " | " + game_board[8])
print_board()
#selecting a space on the board
selection = int(input("Select a square: "))
try:
if selection > 9 or  selection < 1:
print("Sorry, please select a number between 1 and 9.")
else:
print(selection)
except ValueError:
print("Oops! That's not a number. Try again...")

你只需要一直问,直到你得到一个有效的数字。此外,你还需要"尝试"语句来包装将失败的函数,在本例中是int函数。这里有一种不需要try/except的方法,这在这里真的不是最好的选择。

while True:
#selecting a space on the board
selection = input("Select a square: ")
if selection.isdigit():
selection = int(selection)
if 1 <= selection <= 9:
break
print("Sorry, please select a number between 1 and 9.")
else:
print("Oops! That's not a number. Try again...")

您的代码看起来不错,但有几件事要看。首先,你的内部存储game_board print_board()函数,所以你每次print_board gamestate重置()。此外,当用户键入数字时,您的代码不会更新电路板。这可以通过将板的相应值更改为"x"来固定,对于列表来说,这就像game_board[selection] = "X"一样简单。在这两次修改之后,你的文件可能看起来像这样:

game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
def print_board():
print(game_board[0] + " | " + game_board[1] + " | " + game_board[2])
print(game_board[3] + " | " + game_board[4] + " | " + game_board[5])
print(game_board[6] + " | " + game_board[7] + " | " + game_board[8])
print_board()
#selecting a space on the board
selection = int(input("Select a square: "))
try:
if selection > 9 or  selection < 1:
print("Sorry, please select a number between 1 and 9.")
else:
game_board[selection] = "X"
except ValueError:
print("Oops! That's not a number. Try again...")
print_board()

相关内容

  • 没有找到相关文章

最新更新