簡體   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