PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1. Create the data structure – Nine slots that can each contain an X, an O, or a blank. – To represent the board with a dictionary, you can assign each slot a string-value key. – String values in the key-value pair to represent what’s in each slot on the board: ■ 'X' ■ 'O' ■ ‘ ‘ 2. Create a function to print the board dictionary onto the screen 3. Add the code that allows the players to enter their moves (Note: This isn’t a complete tic-tac-toe game — for instance, it doesn’t ever check whether a player has won — but it’s enough to see how data structures can be used in programs. )
turn = 'X'
# Board taken as dictionary where key as string value and key value
is space default
theBoard = {'1': ' ', '2': ' ', '3': ' ',
'4': ' ', '5': ' ', '6': ' ',
'7': ' ', '8': ' ', '9': ' '}
def printBoard(board):
"""
This function print nine slot with space
:param board:
:return: None
"""
print(board["1"] + '|' + board["2"] + '|' + board["3"])
print('-+-+-')
print(board["4"] + '|' + board["5"] + '|' + board["6"])
print('-+-+-')
print(board["7"] + '|' + board["8"] + '|' + board["9"])
for i in range(9):
# Iterate i value upto 9
# Print board
printBoard(theBoard)
print('Turn for :' + turn + ' Choose a (1 to 9): ')
# user input
move = input()
while not theBoard[move] == ' ':
print('Do not try to steal a place! ')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = '0'
else:
turn = 'X'
printBoard(theBoard)
Get Answers For Free
Most questions answered within 1 hours.