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.
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
This is a good use case for a while loop. move
could be invalid every time the user enters their 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."
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. If you need it to be a string, then cast the returned value to a string:
move = str(getMoveForPlayer("Sky"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.