Start learning free

LESSON 668 OF 673 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in Python: A Two-Player Game Class

Practice Read the full explanation

Build a TicTacToe class for two players, X and O, on a 3 by 3 board. One object is one game: it remembers the board and whose turn it is, lets the players take turns, and tells who has won.

The board: rows and columns are numbered 0, 1 and 2. Cell (0, 0) is the top-left corner, (0, 2) the top-right, (2, 0) the bottom-left and (2, 2) the bottom-right. A cell holds 'X', 'O' or '.' when it is still empty.

Build:

  • A new game. The constructor __init__(self) stores the board as a list of three rows (each row a list of three '.') in self.board, and self.player = 'X'. Every row must be its own list (do not write [['.'] * 3] * 3, which repeats one row three times). All nine cells are empty and X moves first.
  • move(self, r, c) plays one turn at the given row and column (always between 0 and 2, so you do not need to check the range).
    • If the cell is not empty, ignore the call: nothing changes and it is still the same player's turn.
    • Otherwise put the current player's mark in the cell, then give the turn to the other player (X becomes O, O becomes X).
  • winner(self) returns the winner as a one-character string: 'X', 'O' or '.'.
    • A player wins by having the same mark in all three cells of a row, a column, or one of the two diagonals ((0,0), (1,1), (2,2) and (0,2), (1,1), (2,0)). Three empty cells in a line are not a win.
    • If nobody has three in a row, return '.'. That covers a game still in progress, an empty board and a draw.

You start with this code, which plays six games and prints the result of each one:

game = TicTacToe()
game.move(0, 0)
game.move(1, 0)
game.move(0, 1)
game.move(1, 1)
game.move(0, 2)
print(game.winner() + " wins!")
game = TicTacToe()
game.move(0, 0)
game.move(0, 1)
game.move(0, 0)
game.move(1, 0)
game.move(1, 1)
game.move(2, 2)
game.move(2, 1)
print(game.winner() + " wins!")
game = TicTacToe()
game.move(0, 0)
game.move(0, 1)
game.move(1, 1)
game.move(0, 2)
game.move(2, 2)
print(game.winner() + " wins!")
game = TicTacToe()
game.move(0, 2)
game.move(0, 0)
game.move(1, 1)
game.move(0, 1)
game.move(2, 0)
print(game.winner() + " wins!")
game = TicTacToe()
game.move(0, 0)
game.move(0, 1)
game.move(0, 2)
game.move(1, 1)
game.move(1, 0)
game.move(1, 2)
game.move(2, 1)
game.move(2, 0)
game.move(2, 2)
print("No winner: " + game.winner())
game = TicTacToe()
print("No winner: " + game.winner())

Games played: X fills the top row; then a game where X tries to play on a cell that is already taken (ignored, and still X's turn) and O wins the middle column; X on the main diagonal; X on the other diagonal; a full board with no three in a row; and a brand-new game.

Expected output:

X wins!
O wins!
X wins!
X wins!
No winner: .
No winner: .

There are eight winning lines: three rows, three columns and two diagonals. A loop over i from 0 to 2 can check row i and column i together; the two diagonals come after the loop. Skip a line whose first cell is empty.

Check for a taken cell first and leave the move method before touching the board or the turn. Only a successful move passes the turn to the other player.

class TicTacToe:
    def __init__(self):
        self.board = []
        for i in range(3):
            self.board.append(['.'] * 3)
        self.player = 'X'

    def move(self, r, c):
        if self.board[r][c] != '.':
            return
        self.board[r][c] = self.player
        if self.player == 'X':
            self.player = 'O'
        else:
            self.player = 'X'

    def winner(self):
        b = self.board
        for i in range(3):
            if b[i][0] != '.' and b[i][0] == b[i][1] and b[i][1] == b[i][2]:
                return b[i][0]
            if b[0][i] != '.' and b[0][i] == b[1][i] and b[1][i] == b[2][i]:
                return b[0][i]
        if b[0][0] != '.' and b[0][0] == b[1][1] and b[1][1] == b[2][2]:
            return b[0][0]
        if b[0][2] != '.' and b[0][2] == b[1][1] and b[1][1] == b[2][0]:
            return b[0][2]
        return '.'

STEP 1 OF 19
    Ctrl + Enter to check

    PYTHON · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in Python, explained

    Problem overview

    You build a TicTacToe class for two players, X and O, on a 3 by 3 board. One object is one game. It remembers the board and whose turn it is, lets the players move in turn and reports the winner.

    Rows and columns are numbered 0, 1 and 2, so cell (0, 0) is the top-left corner and (2, 2) the bottom-right. A cell holds 'X', 'O' or '.' when it is empty. The class has three parts:

    • __init__(self) stores the board in self.board as three separate rows of three dots, and sets self.player = 'X', because X moves first.
    • move(self, r, c) plays one turn. If the cell is taken, the call is ignored and it stays the same player's turn. Otherwise it places the current mark and hands the turn to the other player.
    • winner(self) returns 'X' or 'O' when that player has three marks in a row, column or diagonal, and '.' otherwise. That covers a game in progress, an empty board and a draw.

    Approach: board state, turn state and eight lines

    The object has two pieces of state: the board and the current player. move updates both, and winner only reads the board. It doesn't need to know whose turn it is.

    A win is three equal marks on one of eight lines: three rows, three columns and two diagonals. A loop over i from 0 to 2 checks row i and column i together, since the two checks are the same with the indexes swapped. The two diagonals don't depend on i, so they come after the loop. Every check starts by requiring the first cell to be not '.': three empty cells are equal to each other, but they aren't a win.

    The return value '.' means "no winner yet", which is how the driver prints No winner: . for a full board with no line and for a brand-new game.

    Step by step

    1. Declare the class TicTacToe. Each object created from it is one game with its own memory.
    2. Start the constructor, __init__(self). Python runs it on TicTacToe(), and self is the new game.
    3. Create the board as an empty list in self.board. Using self.board, not a bare board, stores it in the game so other methods can see it.
    4. Loop three times with for i in range(3), one pass per row.
    5. Append a row of three dots each pass: ['.'] * 3. After this, self.board[r][c] is the cell in row r, column c.
    6. Set self.player to 'X' below the loop, one indent less, so it runs once.
    7. Start move(self, r, c). The row and column are always 0 to 2, so no range check is needed.
    8. Guard against a taken cell. If self.board[r][c] is not a dot, return at once. Nothing changes, including the turn.
    9. Place the mark: put self.player in the cell.
    10. Pass the turn: if the player is 'X', make it 'O'.
    11. Add the else branch: otherwise the player becomes 'X'.
    12. Start winner(self), which returns a mark or a dot.
    13. Give the board a short name: b = self.board. It is the same list, not a copy, so b[i][0] reads the real board.
    14. Loop i over 0, 1 and 2. Each pass looks at row i and column i.
    15. Check row i: its first cell is not a dot, equals the second, and the second equals the third. If so, return that mark.
    16. Check column i the same way, with the two indexes swapped.
    17. After the loop, check the main diagonal: cells (0,0), (1,1) and (2,2).
    18. Check the other diagonal: (0,2), (1,1) and (2,0). The row goes up by one as the column goes down by one.
    19. Return '.' as the last line. Reaching it means every check failed.

    The solution in Python

    class TicTacToe:
        def __init__(self):
            self.board = []
            for i in range(3):
                self.board.append(['.'] * 3)
            self.player = 'X'
    
        def move(self, r, c):
            if self.board[r][c] != '.':
                return
            self.board[r][c] = self.player
            if self.player == 'X':
                self.player = 'O'
            else:
                self.player = 'X'
    
        def winner(self):
            b = self.board
            for i in range(3):
                if b[i][0] != '.' and b[i][0] == b[i][1] and b[i][1] == b[i][2]:
                    return b[i][0]
                if b[0][i] != '.' and b[0][i] == b[1][i] and b[1][i] == b[2][i]:
                    return b[0][i]
            if b[0][0] != '.' and b[0][0] == b[1][1] and b[1][1] == b[2][2]:
                return b[0][0]
            if b[0][2] != '.' and b[0][2] == b[1][1] and b[1][1] == b[2][0]:
                return b[0][2]
            return '.'
    
    game = TicTacToe()
    game.move(0, 0)
    game.move(1, 0)
    game.move(0, 1)
    game.move(1, 1)
    game.move(0, 2)
    print(game.winner() + " wins!")
    game = TicTacToe()
    game.move(0, 0)
    game.move(0, 1)
    game.move(0, 0)
    game.move(1, 0)
    game.move(1, 1)
    game.move(2, 2)
    game.move(2, 1)
    print(game.winner() + " wins!")
    game = TicTacToe()
    game.move(0, 0)
    game.move(0, 1)
    game.move(1, 1)
    game.move(0, 2)
    game.move(2, 2)
    print(game.winner() + " wins!")
    game = TicTacToe()
    game.move(0, 2)
    game.move(0, 0)
    game.move(1, 1)
    game.move(0, 1)
    game.move(2, 0)
    print(game.winner() + " wins!")
    game = TicTacToe()
    game.move(0, 0)
    game.move(0, 1)
    game.move(0, 2)
    game.move(1, 1)
    game.move(1, 0)
    game.move(1, 2)
    game.move(2, 1)
    game.move(2, 0)
    game.move(2, 2)
    print("No winner: " + game.winner())
    game = TicTacToe()
    print("No winner: " + game.winner())
    

    Python details worth a look

    • Each row must be its own list. ['.'] * 3 inside the loop builds a new list on every pass. The tempting shortcut [['.'] * 3] * 3 repeats one row object three times. With bad = [['.'] * 3] * 3, the assignment bad[0][0] = 'X' gives [['X', '.', '.'], ['X', '.', '.'], ['X', '.', '.']]: a mark in one row shows in all three. A list comprehension, [['.'] * 3 for _ in range(3)], is the compact way to write the same loop and gives the correct board.
    • Comparisons chain with and. Each win test is three conditions. If the first fails, the others don't run. The chain compares neighbours: first with second, second with third, so all three are equal.
    • return with no value. The guard in move uses a bare return, which ends the method and gives back None. The driver ignores that value.
    • Rows and columns share an index. b[i][0] walks along row i while b[0][i] walks down column i.

    Tracing the second game

    The second game contains a taken-cell move. The moves and the player whose turn it is afterwards are:

    MoveNext player
    (0, 0)O
    (0, 1)X
    (0, 0), already takenX
    (1, 0)O
    (1, 1)X
    (2, 2)O
    (2, 1)X

    The ignored move leaves the turn with X, who then plays (1, 0). The final board is:

    X O .
    X O .
    . O X
    

    Column 1 holds three O marks, so winner() returns 'O'.

    What the driver prints

    X wins!
    O wins!
    X wins!
    X wins!
    No winner: .
    No winner: .
    

    The games are: X on the top row, the game above, X on the main diagonal, X on the other diagonal, a full board with no line, and a game that hasn't started.

    Complexity

    The board has a fixed size, so move and winner each do a constant amount of work: O(1). The board takes constant space.

    Edge cases and common mistakes

    • Playing on a taken cell. The guard has to come before the mark is placed and before the turn changes. If the turn passed anyway, X would lose a move.
    • Empty lines. Without the check that the first cell isn't a dot, an empty row counts as three equal cells. On a board where row 0 is empty and row 1 is X X X, the loop would return '.' at row 0 and never reach X's winning row.
    • A full board with no line. The draw in the driver returns '.': the method can't tell a draw from a game in progress, and doesn't need to.
    • The shared-row board. Described above: build each row separately.
    • Forgetting self.. A local board or player in the constructor disappears when it ends, and move would fail with an AttributeError.
    • Swapped indexes. Row first, then column. Mixing them up checks the transposed board and breaks the diagonal tests.

    Testing

    • A new game: board is three rows of dots, player is 'X', and winner() is '.'.
    • move(1, 1) on it puts X in the centre and the turn becomes O. A second move(1, 1) changes nothing.
    • Moves (0,0), (1,0), (0,1), (1,1) leave no winner; adding (0,2) makes X win the top row.
    • The full-board game in the driver ends with the board X O X, X O O, O X X and no winner.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free