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): Unitplays 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(): Charreturns'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
- Declare the class
TicTacToe. Each object created from it is a separate game with its own memory. - Add a private
val boardbuilt withArray.fill(3)(Array.fill(3)('.')). The outerfillruns its second argument three times, and that argument builds a new inner array each time, so every row is its own array. It is avalbecause the cells change but the board is never replaced. - Add
private var player = 'X'. X moves first, and it must be avarbecause the turn changes. - Write the header of
movewith rowrand columnc. - 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. - Place the mark:
board(r)(c) = player. - Pass the turn. In Scala
ifis an expression, soplayer = if (player == 'X') 'O' else 'X'assigns the other mark in one line. - Write the header of
winner, returning aChar. - Loop
iover0 until 3, which is 0, 1 and 2. Each pass looks at rowiand columni. - Check row
i: first cell not a dot, first equals second, second equals third. If so, return that mark. - Check column
ithe same way, with the two indexes swapped. - After the loop, check the main diagonal: cells (0,0), (1,1) and (2,2).
- Check the other diagonal: cells (0,2), (1,1) and (2,0). The row increases by one while the column decreases by one.
- 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
Charliterals use single quotes.'X'is aCharand"X"is aString. 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 rowr, then cellcof that row. Assigning withboard(r)(c) = playerchanges the array in place, which is whyboardcan be aval. - Shared rows are a classic trap. Writing
val row = Array.fill(3)('.')and thenArray.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 asX../X../X... WithArray.fill(3)(Array.fill(3)('.')), the inner expression is evaluated again for every row, so the same change givesX../.../.... returninside aforloop. The loop body is a function under the hood, so areturnthere is a "non local return": it leaves the wholewinnermethod, 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 suggestsscala.util.boundary. The warning is expected here.0 until 3excludes 3, giving 0, 1, 2.0 to 3would include 3 and cause an out-of-bounds error.- String interpolation. The driver's
s"${game.winner()} wins!"inserts theCharresult 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
playeronly 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
Stringfor the mark. The method's result is aChar, so the board and the player have to beChartoo.
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.fillper row so the rows are not shared. - Eight lines decide every game, and the first-cell test keeps empty lines from counting.
