如何在Python3中从字典键定义可能的input()变量



我刚刚开始在Python 3中使用字典而不是列表创建TicTacToe游戏。

游戏中可能的移动与键盘上的数字网格(1-9(相同,后者由字典定义。

我对游戏的运行方式很满意,除非我输入的值不在1-9之间,否则会产生错误。

我如何定义它,以便如果一个值是!= 1-9,而不是错误,它将是print('Sorry, that value is not valid.nPlease select a value between 1-9.n'),并给用户一个重试的机会?

下面是我的代码片段:

# Creating the board using dictionary, using numbers from a keyboard
game_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
board_keys = []
for key in game_board:
board_keys.append(key)
# Print updated board after every move
def print_board(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
# Gameplay functions
def game():
turn = 'X'
count = 0
for i in range(10):
print_board(game_board)
print("nIt's " + turn + "'s turn. Pick a move.n")
move = input()
if game_board[move] == ' ':
game_board[move] = turn
count += 1
else:
print('Sorry, that position has already been filled.nPlease pick another move.n')
continue

提前谢谢。

您有以下代码:

game_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
# ...
move = input()
if game_board[move] == ' ':
game_board[move] = turn
count += 1
else:
print('Sorry, that position has already been filled.nPlease pick another move.n')
continue

如果用户输入的不是1到9之间的数字,这将已经创建一个KeyError,因为查找game_board[move]将失败。

因此,您所要做的就是处理KeyError并创建所需的错误消息:

move = input()
try:
current_value = game_board[move]
except KeyError:
print('Sorry, that value is not valid.nPlease select a value between 1-9.n')
continue
if current_value == ' ':
game_board[move] = turn
count += 1
else:
print('Sorry, that position has already been filled.nPlease pick another move.n')
continue

这是while循环的一个很好的用例。move可能在每次用户输入移动时都是无效的。此外,我们需要确保用户的输入是一个有效的数字,并限制在正确的范围内。

"如果move无效,请重试">

def getMoveForPlayer(playerName: str) -> int:
move = -1 # Default invalid value so the loop runs
moveHasBeenEntered = False
print(f"It's {playerName}'s turn. Pick a move: ", end="")
while move < 1 or move > 9:
if moveHasBeenEntered:
print('Sorry, that value is not valid.nPlease select a value between 1-9: ', end="")
else:
moveHasBeenEntered = True
try:
move = int(input())
except ValueError:
pass
return move
# This line replaces "move = input()"
move = getMoveForPlayer("Sky")

请注意,从getMoveForPlayer返回的值是一个整数。如果您需要它是一个字符串,那么将返回的值强制转换为字符串:

move = str(getMoveForPlayer("Sky"))

最新更新