繁体   English   中英

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

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

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

游戏的可能动作与键盘上的数字网格(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返回的值是 integer。 如果您需要它是一个字符串,则将返回的值转换为一个字符串:

move = str(getMoveForPlayer("Sky"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM