This is a game of Tic Tac Toe with a 3x3 board


In [2]:
def initialize_board():
    board = [1,2,3,4,5,6,7,8,9]
    return board

In [3]:
from IPython.display import clear_output

def board_representation(board):
    clear_output()
    print board[0],'|', board[1],'|', board[2]
    print '----------'
    print board[3],'|', board[4],'|', board[5]
    print '----------'
    print board[6],'|', board[7],'|', board[8]

In [12]:
board = initialize_board()
board_representation(board)


1 | 2 | 3
----------
4 | 5 | 6
----------
7 | 8 | 9

In [10]:
def make_move(board):
    marker = raw_input('Please input your marker type (x or o): ')
    # check if marker is valid
    if marker != 'x' and marker != 'o':
        print 'invalid marker type'
        return board
    position = int(raw_input('Please input the desired marker position (e.g. 3): '))
    #check if position is valid
    if position not in range(1,10):
        print 'invalid position'
    elif type(board[position-1]) != int:
        print 'That position was already chosen'
    else:
        board[position-1] = marker
    return board

In [13]:
make_move(board)


Please input your marker type (x or o): p
invalid marker type
Out[13]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In [14]:
def has_game_ended(board):
    if board[0] == board[1] == board[2]:
        print 'Symbol', board[0], 'won!'
        return True
    elif board[3] == board[4] == board[5]:
        print 'Symbol', board[3], 'won!'
        return True
    elif board[6] == board[7] == board[8]:
        print 'Symbol', board[6], 'won!'
        return True
    else:
        if board[0] == board[3] == board[6]:
            print 'Symbol', board[0], 'won!'
            return True
        elif board[1] == board[4] == board[7]:
            print 'Symbol', board[1], 'won!'
            return True
        elif board[2] == board[5] == board[8]:
            print 'Symbol', board[2], 'won!'
            return True
        elif board[0] == board[4] == board[8]:
            print 'Symbol', board[0], 'won!'
            return True
        elif board[2] == board[4] == board[6]:
            print 'Symbol', board[2], 'won!'
            return True
        else:
            if all(type(position) is str for position in board):
                print 'It\'s a tie!'
                return True
            else:
                return False

In [17]:
board = ['x',2,3,'x',4,5,6,7,8]
board_representation(board)
print has_game_ended(board)


x | 2 | 3
----------
x | 4 | 5
----------
6 | 7 | 8
False

In [ ]:


In [19]:
def play_game():
    board = initialize_board()
    board_representation(board)
    condition = False
    while condition == False:
        board = make_move(board)
        board_representation(board)
        condition = has_game_ended(board)

In [20]:
play_game()


1 | o | x
----------
4 | x | 6
----------
x | o | 9
Symbol x won!

In [ ]: