Start learning free

LESSON 69 OF 70 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in Kotlin: 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 class has two private fields, set up when the object is created: board, a 3 by 3 array of Char filled with '.', and var player = 'X'. Every row must be its own array. All nine cells are empty and X moves first.
  • fun move(r: Int, c: Int) 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).
  • fun winner(): Char returns the winner as a Char: '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:

class Solution {
    fun mainFunction() {
        var game = TicTacToe()
        game.move(0, 0)
        game.move(1, 0)
        game.move(0, 1)
        game.move(1, 1)
        game.move(0, 2)
        println("${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)
        println("${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)
        println("${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)
        println("${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)
        println("No winner: ${game.winner()}")
        game = TicTacToe()
        println("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 {
    private val board = Array(3) { CharArray(3) { '.' } }
    private var player = 'X'

    fun move(r: Int, c: Int) {
        if (board[r][c] != '.') return
        board[r][c] = player
        player = if (player == 'X') 'O' else 'X'
    }

    fun winner(): Char {
        for (i in 0 until 3) {
            if (board[i][0] != '.' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return board[i][0]
            if (board[0][i] != '.' && board[0][i] == board[1][i] && board[1][i] == board[2][i]) return board[0][i]
        }
        if (board[0][0] != '.' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) return board[0][0]
        if (board[0][2] != '.' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) return board[0][2]
        return '.'
    }
}

STEP 1 OF 14
    Ctrl + Enter to check

    KOTLIN · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in Kotlin, explained

    Problem overview

    The lesson asks for a TicTacToe class where one object is one game. It remembers a 3 by 3 board and whose turn it is. Rows and columns are numbered 0 to 2, with cell (0, 0) in the top-left corner. A cell holds 'X', 'O' or '.' for an empty cell. X moves first.

    • move(r: Int, c: Int) plays one turn. If the cell is taken, the call is ignored and it is still the same player's turn. Otherwise the current player's mark goes in the cell and the turn passes to the other player.
    • winner(): Char returns 'X' or 'O' when that player has three marks in a row, a column or a diagonal. In every other case it returns '.': a game in progress, an empty board or a draw.

    The driver plays six games. X fills the top row. In the second game X tries to play on a cell that is already taken, the call is ignored, and O wins the middle column. X then wins on each diagonal. A full board has no three in a row, and a brand-new game has no winner either:

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

    Approach

    There are only eight lines that can win: three rows, three columns and two diagonals. After any move, winner can simply look at all eight, without caring who moved last.

    A line wins when its three cells hold the same mark and that mark is not a dot. The dot check matters: three empty cells are equal to each other, but they are not a win.

    A single loop over i from 0 to 2 can test row i and column i together, which covers six of the eight lines. The two diagonals do not depend on i, so they are tested once after the loop. If nothing matched, the answer is a dot.

    For move, the order of checks matters. First reject a taken cell and leave right away, before touching the board or the turn. Only a move that succeeds changes the board and passes the turn.

    Step by step

    1. Declare the class. Each TicTacToe() is a separate game with its own memory.
    2. Build the board as private val board = Array(3) { CharArray(3) { '.' } }. The block after Array(3) runs once for each of the three rows, so every row is a fresh CharArray(3) { '.' }. The cell at row r, column c is board[r][c].
    3. Track the turn with private var player = 'X'. It is a var because it changes after every move.
    4. Start move(r: Int, c: Int).
    5. Guard a taken cell. If board[r][c] is not a dot, return. Nothing changes and the turn stays.
    6. Place the mark: board[r][c] = player.
    7. Pass the turn. In Kotlin, if is an expression, so one line can assign its result: player = if (player == 'X') 'O' else 'X'.
    8. Start winner(): Char.
    9. Loop i over 0 until 3, which is 0, 1 and 2.
    10. Check row i: its first cell is not a dot, equals the second, and the second equals the third. If so, return that mark.
    11. Check column i, the same test with the two indexes swapped.
    12. Check the main diagonal (0,0), (1,1), (2,2) after the loop.
    13. Check the other diagonal (0,2), (1,1), (2,0). The row goes up from 0 to 2 while the column goes down from 2 to 0.
    14. Return a dot. If this line runs, every check above failed.

    The solution in Kotlin

    class TicTacToe {
        private val board = Array(3) { CharArray(3) { '.' } }
        private var player = 'X'
    
        fun move(r: Int, c: Int) {
            if (board[r][c] != '.') return
            board[r][c] = player
            player = if (player == 'X') 'O' else 'X'
        }
    
        fun winner(): Char {
            for (i in 0 until 3) {
                if (board[i][0] != '.' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return board[i][0]
                if (board[0][i] != '.' && board[0][i] == board[1][i] && board[1][i] == board[2][i]) return board[0][i]
            }
            if (board[0][0] != '.' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) return board[0][0]
            if (board[0][2] != '.' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) return board[0][2]
            return '.'
        }
    }
    
    class Solution {
        fun mainFunction() {
            var game = TicTacToe()
            game.move(0, 0)
            game.move(1, 0)
            game.move(0, 1)
            game.move(1, 1)
            game.move(0, 2)
            println("${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)
            println("${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)
            println("${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)
            println("${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)
            println("No winner: ${game.winner()}")
            game = TicTacToe()
            println("No winner: ${game.winner()}")
        }
    }
    

    Kotlin details

    • Array of arrays. Array(3) { ... } takes a function that builds each element from its index. CharArray(3) { '.' } works the same way for a primitive character array, with the block giving each cell's starting value.
    • Why a fresh row each time. Every row must be its own array. If one row is created first and reused, as in val row = CharArray(3) { '.' } then Array(3) { row }, all three entries are the same array. Setting cell (0, 0) to 'X' then shows X.. on all three rows. Creating the row inside the block avoids that.
    • Char literals use single quotes, 'X', and strings use double quotes. == compares chars by value.
    • 0 until 3 excludes 3, so i takes 0, 1 and 2. 0..3 would include 3 and go out of bounds.
    • Early return. move returns nothing, so the bare return in its guard just leaves the method. In winner, each return hands back a Char.
    • String templates. "${game.winner()} wins!" puts an expression inside a string.
    • Private members. Callers cannot read the board or set player. All changes go through move, which is what stops a player from overwriting a cell.

    Complexity

    move does a fixed number of steps, so it is O(1). winner checks a fixed set of eight lines on a board that is always 3 by 3, so it is also constant time. The board takes constant space, nine cells.

    Edge cases and common mistakes

    • Empty lines. Without the != '.' test, a new game would report a win, because three dots in a row are equal. The brand-new game must print No winner: ..
    • Taken cell. In the second game, X plays (0, 0) and O plays (0, 1). X's second try at (0, 0) is ignored and the turn does not pass, so X's next moves are (1, 0) and (2, 2), and O's are (1, 1) and (2, 1). That gives O the whole middle column. If the guard passed the turn anyway, the marks would land for the wrong players and X would not be the one playing (1, 0).
    • Turn passed too early. Change player only after the mark is placed. If the turn is passed first, the cell receives the other player's mark.
    • Draw. A full board with no line returns a dot, just like a game in progress. The method cannot tell the two apart, and the lesson does not ask it to.
    • The anti-diagonal. Its cells are (0,2), (1,1), (2,0). Using (0,0), (1,1), (2,2) for both diagonals is an easy slip.
    • Moves after a win. This solution does not stop the game when someone wins. Further moves are accepted, and winner still reports the first line it finds.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free