Problem overview
The lesson asks for a TicTacToe class for 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 reports the winner.
Rows and columns are numbered 0 to 2, with cell (0, 0) at the top left and (2, 2) at the bottom right. A cell holds "X", "O" or "." when it is empty. The class has:
- two private properties:
board, a 3 by 3 array ofCharacterfilled with dots, andplayer: Character = "X", so X moves first; move(_ row: Int, _ column: Int), which ignores a taken cell, and otherwise marks it and passes the turn;winner() -> Character, which returns"X"or"O"for three in a row (a row, a column or either diagonal), and"."otherwise.
The driver plays six games. In the first, X fills the top row. In the second, X tries to play on cell (0, 0) when it is already taken. That call is ignored and it is still X's turn, and in the end O wins the middle column. Then come the two diagonals, a full board with no line, and a fresh game. The expected output is:
X wins!
O wins!
X wins!
X wins!
No winner: .
No winner: .
In the second game, X plays (0,0) and O plays (0,1). X's repeated (0,0) is ignored, so X then plays (1,0), O plays (1,1), X plays (2,2) and O plays (2,1). O now holds (0,1), (1,1) and (2,1), the middle column.
Approach: store the grid, check eight lines
The board is a nested array, so board[row][column] is one cell. A move is a small update to that grid. A win check is a search for three equal, non-empty marks along any of the eight winning lines: three rows, three columns and two diagonals.
The check doesn't need to know who just moved. It looks at the whole board and returns whichever mark completes a line. Dots must be excluded: three empty cells in a line are equal to each other, but they aren't a win.
Step by step
- Declare the class and write its closing brace at once. Each object is its own game with its own memory.
- Add the board as a private
var:Array(repeating: Array(repeating: Character("."), count: 3), count: 3). The inner call builds a row of three dots, and the outer one repeats that row three times. - Add
player, a privateCharacterstarting as"X". Every new game starts with X to move. - Start
move, taking the row and the column, each 0, 1 or 2. - Guard against a taken cell: if
board[row][column]isn't a dot, leave withreturnbefore changing anything, so it stays the same player's turn. - Place the mark:
board[row][column] = player. - Pass the turn with one conditional expression: if the player was
"X"it becomes"O", otherwise"X". - Start
winner, returning aCharacter. - Loop
indexover0..<3. Each pass checks rowindexand columnindextogether. - Check the row: its first cell isn't a dot, and equals the second, which equals the third. If so, return that mark.
- Check the column the 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: (0,2), (1,1) and (2,0).
- Return
".". Reaching it means every check failed.
The solution in Swift
class TicTacToe {
private var board = Array(repeating: Array(repeating: Character("."), count: 3), count: 3)
private var player: Character = "X"
func move(_ row: Int, _ column: Int) {
if board[row][column] != "." { return }
board[row][column] = player
player = player == "X" ? "O" : "X"
}
func winner() -> Character {
for index in 0..<3 {
if board[index][0] != "." && board[index][0] == board[index][1] && board[index][1] == board[index][2] { return board[index][0] }
if board[0][index] != "." && board[0][index] == board[1][index] && board[1][index] == board[2][index] { return board[0][index] }
}
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 {
func mainFunction() {
var 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())")
}
}
Details worth knowing
CharacterversusString. The board holdsCharactervalues, and Swift won't compare aCharacterwith aString:winner == swheresis aStringfails withbinary operator '==' cannot be applied to operands of type 'Character' and 'String'. A bare literal such as"X"adapts toCharacterwhere one is expected. That is whyplayer == "X"andreturn "."both work.- Printing a
Character. Interpolation shows the mark itself, so"\(game.winner()) wins!"printsX wins!, and a dot for no winner givesNo winner: .. - Every row is its own array. Swift arrays are value types. When the outer
Array(repeating:count:)repeats the row, each copy is independent. Settingboard[0][0] = "X"changes only the top row. - Ternary for the turn.
player = player == "X" ? "O" : "X"reads as: compare, then choose. The comparison binds tighter than the assignment, so it works as written. - The driver's
var game. It isvarbecause the driver assigns a newTicTacToe()to it for each game.
Complexity
The board has a fixed size, so each move and each winner call takes constant time: a move touches one cell, and the check looks at at most eight lines. The object stores nine cells and one mark, which is constant space.
Edge cases and common mistakes
- Forgetting the empty-cell test in
winner. Without!= ".", three empty cells in a row look like a line, and the method returns the dot straight away. A game where only row 1 is filled with X would then report no winner, because empty row 0 is checked first and returns early. - Moving on a taken cell. The guard must come before the mark is placed and before the turn changes. If the turn changed anyway, X's repeated move in the second game would hand the turn to O and everything after it would be wrong.
- Passing the turn on every call. Only a successful move changes
player. - Missing a diagonal. The loop covers rows and columns only. The two diagonals need their own checks after it.
- Wrong anti-diagonal cells. The second diagonal is (0,2), (1,1), (2,0): the row goes up by one while the column goes down by one.
- A full board with no line. The fifth game ends with all nine cells filled and nobody with three in a row, so
winner()falls through to".". - Playing after a win. This class doesn't stop moves after someone wins. It only reports the line it finds, which is fine for the lesson's tests.
Testing
These games, played on a fresh TicTacToe each time, give the lesson's results. Here is a diagonal win:
var 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!")
X wins!
X holds (0,0), (1,1) and (2,2), the main diagonal, while O's marks at (0,1) and (0,2) don't make a line. A brand-new game gives No winner: ..
