Search code examples
pythondictionaryinputtic-tac-toe

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.

The possibles moves for the game are the same as the number grid on a keyboard (1-9), which are defined by a dictionary.

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.

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?

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.


Solution

  • 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.

    So all you have to do is handle the KeyError and create the desired error message:

    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