如何从 Python 3 中的字典键定义可能的 input() 变量?

How can I define possible input() variables from dictionary keys in Python 3?

我刚刚开始使用 字典在 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"))