Tic Tac Toe

Home   »   Tic Tac Toe


board = [
    [' ', ' ', ' '],
    [' ', ' ', ' '],
    [' ', ' ', ' '],
]

def printBoard():
    print(
        'Current board:\n' +
        board[0][0] + '|' + board[0][1] + '|' + board[0][2] + '\n' +
        '-+-+-\n' +
        board[1][0] + '|' + board[1][1] + '|' + board[1][2] + '\n' +
        '-+-+-\n' +
        board[2][0] + '|' + board[2][1] + '|' + board[2][2] + '\n'
    )

def play():
    player = 'x'
    spots = 9

    while True:
        printBoard()
        print('Player ' + player + '\'s turn. Where do you want to move?')
        coords = input()
        if type(coords) != tuple:
            print('Please enter a valid position.')
            continue
        x_coord = int(coords[0])
        y_coord = int(coords[1])

        if x_coord not in [0, 1, 2] or y_coord not in [0, 1, 2]:
            print('Please enter a valid position.')
            continue
        if board[x_coord][y_coord] == ' ':
            board[x_coord][y_coord] = player;
            player = 'y' if player == 'x' else 'x'
            spots -= 1
        else:
            print('That spot is already taken.')
            continue

        if board[0][0] == board[0][1] == board[0][2] != ' ':
            printBoard()
            print('Player ' + board[0][0] + 'wins!')
            break
        elif board[1][0] == board[1][1] == board[1][2] != ' ':
            printBoard()
            print('Player ' + board[1][0] + ' wins!')
            break
        elif board[2][0] == board[2][1] == board[2][2] != ' ':
            printBoard()
            print('Player ' + board[2][0] + ' wins!')
            break
        elif board[0][0] == board[1][0] == board[2][0] != ' ':
            printBoard()
            print('Player ' + board[0][0] + ' wins!')
            break
        elif board[0][1] == board[1][1] == board[2][1] != ' ':
            printBoard()
            print('Player ' + board[0][1] + ' wins!')
            break
        elif board[0][2] == board[1][2] == board[2][2] != ' ':
            printBoard()
            print('Player ' + board[0][2] + ' wins!')
            break
        elif board[0][0] == board[1][1] == board[2][2] != ' ':
            printBoard()
            print('Player ' + board[0][0] + ' wins!')
            break
        elif board[0][2] == board[1][1] == board[2][0] != ' ':
            printBoard()
            print('Player ' + board[0][2] + ' wins!')
            break
        elif spots == 0:
            printBoard()
            print('It\'s a tie!')
            break

play()

Leave a Reply

Your email address will not be published. Required fields are marked *