简体   繁体   English

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

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

I am just starting out and creating a TicTacToe game in Python 3 using a dictionary instead of a list.我刚刚开始并使用字典而不是列表在Python 3中创建井字游戏。

The possibles moves for the game are the same as the number grid on a keyboard (1-9), which are defined by a dictionary.游戏的可能动作与键盘上的数字网格(1-9)相同,由字典定义。

I'm happy with how the game runs, except if I input a value that is not between 1-9, it will produce an error.我对游戏的运行方式感到满意,除非我输入的值不在 1-9 之间,否则会产生错误。

How do I define it so that if a value that is != 1-9 , instead of an error it will print('Sorry, that value is not valid.\nPlease select a value between 1-9.\n') and give the user an opportunity to try again?如何定义它,以便如果一个值为!= 1-9的值,而不是错误,它将print('Sorry, that value is not valid.\nPlease select a value between 1-9.\n')和给用户再试一次的机会?

Below is a snippet of my code:下面是我的代码片段:

# 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

Thankyou in advance.先感谢您。

You have this code:你有这个代码:

 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

If the users enters anything else than a digit between 1 and 9 this will already create a KeyError because the lookup game_board[move] will fail.如果用户输入的不是 1 到 9 之间的数字,这将创建一个KeyError ,因为查找game_board[move]将失败。

So all you have to do is handle the KeyError and create the desired error message:因此,您所要做的就是处理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

This is a good use case for a while loop.这是 while 循环的一个很好的用例。 move could be invalid every time the user enters their move.每次用户输入他们的移动时move可能是无效的。 Plus we need to make sure the user's input is a valid number and constrained to the correct range.另外,我们需要确保用户的输入是一个有效的数字并且限制在正确的范围内。

"While move is not valid, try again." “虽然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")

Note that the value returned from getMoveForPlayer is an integer.请注意,从getMoveForPlayer返回的值是 integer。 If you need it to be a string, then cast the returned value to a string:如果您需要它是一个字符串,则将返回的值转换为一个字符串:

move = str(getMoveForPlayer("Sky"))

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

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