Start learning free

LESSON 69 OF 70 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in Scala: 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 '.' (read as board(r)(c)), and var player = 'X'. Every row must be its own array. All nine cells are empty and X moves first.
  • def move(r: Int, c: Int): Unit 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).
  • def 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 {
    def mainFunction(): Unit = {
        var game = TicTacToe()
        game.move(0, 0)
        game.move(1, 0)
        game.move(0, 1)
        game.move(1, 1)
        game.move(0, 2)
        println(s"${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(s"${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(s"${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(s"${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(s"No winner: ${game.winner()}")
        game = TicTacToe()
        println(s"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.fill(3)(Array.fill(3)('.'))
    private var player = 'X'

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

    def winner(): Char = {
        for (i <- 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

    SCALA · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in Scala, explained

    Problem overview

    You build a class TicTacToe where one object is one game on a 3 by 3 board. The object remembers the board and whose turn it is, lets two players, X and O, take turns, and reports the winner. Rows and columns are numbered 0 to 2, with cell (0, 0) at the top-left. A cell holds 'X', 'O' or '.' while empty.

    • A new game has nine empty cells, and X moves first.
    • move(r: Int, c: Int): Unit plays a turn. If the cell is taken, nothing changes 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 in a row, a column or one of the two diagonals, and '.' otherwise. That covers a game in progress, an empty board and a draw.

    The driver plays six games. In the first, X fills the top row. In the second, X tries to play on a taken cell: the call is ignored, and it is still X's turn, so X plays elsewhere and O ends up winning the middle column. The third and fourth games have X winning on each diagonal, the fifth is a full board with no line, and the sixth is a brand-new game:

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

    Approach: store the board, scan the eight lines

    The board is a two-dimensional array of Char, and board(r)(c) is the cell in row r, column c. The current player is a single Char variable that flips after every successful move.

    There are only eight ways to win: three rows, three columns and two diagonals. Rather than writing eight separate tests, one loop over i from 0 to 2 can check row i and column i together, and the two diagonals follow after the loop. Each test asks whether the first cell of the line is not empty and the three cells hold the same mark. The first-cell test matters: three empty cells are equal to each other, but they are not a win.

    Step by step

    1. Declare the class TicTacToe. Each object created from it is a separate game with its own memory.
    2. Add a private val board built with Array.fill(3)(Array.fill(3)('.')). The outer fill runs its second argument three times, and that argument builds a new inner array each time, so every row is its own array. It is a val because the cells change but the board is never replaced.
    3. Add private var player = 'X'. X moves first, and it must be a var because the turn changes.
    4. Write the header of move with row r and column c.
    5. Guard against a taken cell: if board(r)(c) is not '.', return at once. Neither the board nor the turn changes, so the same player tries again.
    6. Place the mark: board(r)(c) = player.
    7. Pass the turn. In Scala if is an expression, so player = if (player == 'X') 'O' else 'X' assigns the other mark in one line.
    8. Write the header of winner, returning a Char.
    9. Loop i over 0 until 3, which is 0, 1 and 2. Each pass looks at row i and column i.
    10. Check row i: first cell not a dot, first equals second, second equals third. If so, return that mark.
    11. Check column i the same way, with the two indexes swapped.
    12. After the loop, check the main diagonal: cells (0,0), (1,1) and (2,2).
    13. Check the other diagonal: cells (0,2), (1,1) and (2,0). The row increases by one while the column decreases by one.
    14. Return '.' as the last line: reaching it means all eight checks failed.

    The solution in Scala

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

    Scala details

    • Char literals use single quotes. 'X' is a Char and "X" is a String. Comparing the two with == is rejected at compile time: "Values of types Char and String cannot be compared with == or !=".
    • Two-dimensional arrays are arrays of arrays. board(r)(c) first gets row r, then cell c of that row. Assigning with board(r)(c) = player changes the array in place, which is why board can be a val.
    • Shared rows are a classic trap. Writing val row = Array.fill(3)('.') and then Array.fill(3)(row) gives three references to the same row. Setting cell (0, 0) to 'X' then changes all three rows, and the board prints as X../X../X... With Array.fill(3)(Array.fill(3)('.')), the inner expression is evaluated again for every row, so the same change gives X../.../....
    • return inside a for loop. The loop body is a function under the hood, so a return there is a "non local return": it leaves the whole winner method, which is what this solution relies on. Scala 3.5 compiles it and the lesson runs correctly, but the compiler prints a warning that non local returns are no longer supported and suggests scala.util.boundary. The warning is expected here.
    • 0 until 3 excludes 3, giving 0, 1, 2. 0 to 3 would include 3 and cause an out-of-bounds error.
    • String interpolation. The driver's s"${game.winner()} wins!" inserts the Char result into the text.

    Complexity

    The board has a fixed size, so move and winner each do a constant amount of work: move reads and writes one cell, and winner inspects at most the 8 lines of 3 cells. Both are O(1) time. The object stores 9 cells and one turn marker, which is O(1) space.

    Edge cases and common mistakes

    • Moving on a taken cell. The guard must come before any change. If the turn passed anyway, X would lose a turn after a mistake, and the second driver game would end differently. In that game, the ignored call leaves it X's turn.
    • Empty lines count as equal. Without the != '.' test, an empty board would report a winner, since three dots are equal. The final line of the driver, a brand-new game, checks for this.
    • A draw is not a win. A full board with no line returns '.', the same as a game in progress.
    • Passing the turn before placing the mark. Flip player only after writing it to the board, or the wrong mark lands in the cell.
    • Mixing up the anti-diagonal. It is (0,2), (1,1), (2,0): the row increases while the column decreases.
    • Using a String for the mark. The method's result is a Char, so the board and the player have to be Char too.

    Testing

    Besides the driver, try these:

    • One move at (1, 1) only: winner() returns '.'.
    • X at (0, 0), O at (0, 1), X at (1, 0), O at (1, 1), X at (2, 0): X owns the first column, so winner() returns 'X'.
    • Call move(0, 0) twice in a row: the second call is ignored, the cell holds X, and it is O's turn.

    Key takeaways

    • A game object keeps its board and turn in private fields, and its methods are the only way to change them.
    • Build a 2D array with a fresh inner Array.fill per row so the rows are not shared.
    • Eight lines decide every game, and the first-cell test keeps empty lines from counting.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free