Problem overview
The lesson builds a TicTacToe type for two players, X and O, on a 3 by 3 board. One value is one game. It remembers the board and whose turn it is, accepts moves 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 '.' when it is empty.
newTicTacToe() *TicTacToereturns a new game: nine empty cells, with X to move.move(row int, col int)plays the current player's mark in that cell and passes the turn. If the cell is taken, the call is ignored, and it stays the same player's turn. The row and column are always 0 to 2, so no range check is needed.winner() runereturns'X'or'O'when that player has three marks in a row, a column or a diagonal. It returns'.'otherwise: a game in progress, an empty board and a draw all give a dot. Three empty cells in a line are not a win.
The driver plays six games. In the second one, X tries to play on a cell that is already taken, and O then wins down the middle column. The expected output is X wins!, O wins!, X wins!, X wins!, then two lines of No winner: ..
Approach: a small state and eight lines to check
The state is two fields: the board, [3][3]rune, and player, the mark whose turn it is. A rune is Go's type for one character, and 'X' is a rune literal.
There are exactly eight winning lines: three rows, three columns and two diagonals. A single loop over i from 0 to 2 can test row i and column i together, and the two diagonals are checked after it. Each test asks three things: the first cell isn't a dot, the first equals the second, and the second equals the third. The first question matters, because three dots are equal to each other too.
Step by step
The type and the constructor
- Declare the struct with
board [3][3]rune(an array of three rows, each an array of three runes) andplayer rune. - Write
newTicTacToe, which returns a pointer to the game. Go has no constructors, so a plain function starting withnewdoes the job. - Create the game with
&TicTacToe{player: 'X'}. X moves first in every game. The board starts out holding zero runes, not dots, so it still needs filling. - Fill the board with two nested loops.
for row := range game.boardruns once per row, andfor col := range game.board[row]visits the three cells of that row. Each cell is set to'.'. - Return
game.
The move
- Declare
movewith a pointer receiver,(game *TicTacToe), since it changes the game. - Guard against a taken cell. If
game.board[row][col]isn't a dot,returnbefore touching anything. The board and the turn both stay as they were. - Place the mark:
game.board[row][col] = game.player. - Pass the turn. If the player is
'X'it becomes'O', otherwise it becomes'X'. Only a successful move gets this far.
The winner
- Declare
winnerwith a plainTicTacToereceiver. It only reads the game. - Loop
ifrom 0 to 2. Inside, check rowi(cells[i][0],[i][1],[i][2]) and columni(cells[0][i],[1][i],[2][i]), returning the mark on a match. - Check the main diagonal after the loop: cells (0,0), (1,1) and (2,2).
- Check the other diagonal: cells (0,2), (1,1) and (2,0). The row goes up by one as the column goes down by one.
- Return
'.'if nothing matched.
The solution in Go
type TicTacToe struct {
board [3][3]rune
player rune
}
func newTicTacToe() *TicTacToe {
game := &TicTacToe{player: 'X'}
for row := range game.board {
for col := range game.board[row] {
game.board[row][col] = '.'
}
}
return game
}
func (game *TicTacToe) move(row int, col int) {
if game.board[row][col] != '.' {
return
}
game.board[row][col] = game.player
if game.player == 'X' {
game.player = 'O'
} else {
game.player = 'X'
}
}
func (game TicTacToe) winner() rune {
for i := 0; i < 3; i++ {
if game.board[i][0] != '.' && game.board[i][0] == game.board[i][1] && game.board[i][1] == game.board[i][2] {
return game.board[i][0]
}
if game.board[0][i] != '.' && game.board[0][i] == game.board[1][i] && game.board[1][i] == game.board[2][i] {
return game.board[0][i]
}
}
if game.board[0][0] != '.' && game.board[0][0] == game.board[1][1] && game.board[1][1] == game.board[2][2] {
return game.board[0][0]
}
if game.board[0][2] != '.' && game.board[0][2] == game.board[1][1] && game.board[1][1] == game.board[2][0] {
return game.board[0][2]
}
return '.'
}
func mainFunction() {
game := newTicTacToe()
game.move(0, 0)
game.move(1, 0)
game.move(0, 1)
game.move(1, 1)
game.move(0, 2)
fmt.Printf("%c wins!\n", game.winner())
game = newTicTacToe()
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)
fmt.Printf("%c wins!\n", game.winner())
game = newTicTacToe()
game.move(0, 0)
game.move(0, 1)
game.move(1, 1)
game.move(0, 2)
game.move(2, 2)
fmt.Printf("%c wins!\n", game.winner())
game = newTicTacToe()
game.move(0, 2)
game.move(0, 0)
game.move(1, 1)
game.move(0, 1)
game.move(2, 0)
fmt.Printf("%c wins!\n", game.winner())
game = newTicTacToe()
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)
fmt.Printf("No winner: %c\n", game.winner())
game = newTicTacToe()
fmt.Printf("No winner: %c\n", game.winner())
}
The driver prints:
X wins!
O wins!
X wins!
X wins!
No winner: .
No winner: .
Tracing the second game
The second game plays (0,0), (0,1), (0,0), (1,0), (1,1), (2,2), (2,1). After the first two moves the board is:
XO.
...
...
The third move targets (0,0) again. The cell is taken, so the board is unchanged, and it is still X's turn. X plays (1,0) next, and the board after (1,1), (2,2) and (2,1) is:
XO.
XO.
.OX
Column 1 holds O in all three rows, so winner() returns 'O'.
The Go details worth knowing:
- Arrays are values.
[3][3]runeis an array, not a slice, and it is stored inside the struct. Assigning a struct copies the whole board, and the methodwinner, which has a value receiver, works on a copy. That is harmless for a reader. A value receiver onmovewould place the mark on a copy, and the real board would never change. - Zero runes are not dots. A new array holds the rune 0 in every cell. That is why the constructor fills the board with
'.'. Without the loops, the test!= '.'would treat every cell as taken, and no move would ever be accepted. rangeover an array.for row := range game.boardgives only the index when there is one variable on the left, sogame.board[row]is the row itself.- Runes are numbers.
'X'is the integer 88 and'.'is 46.fmt.Println(game.winner())prints46for a game with no winner.fmt.Printf("%c", ...)prints the character, and%qprints it quoted, as'.'. That is why the driver uses%c. - Rune literals and string literals.
'X'(single quotes) is a rune and"X"(double quotes) is a string. They are different types, sogame.player == "X"doesn't compile. Convert withstring(r)when you need text. - Comparing runes.
==works directly on runes, so the line tests need no helper function. - The pointer returned by the constructor.
game = newTicTacToe()in the driver reassigns the same variable to a new game, so each game starts from a clean board.
Complexity
Time: move is O(1). winner checks a fixed number of cells: eight lines of three. On a 3 by 3 board that is constant time, O(1). The constructor fills nine cells, also constant.
Space: The game stores nine runes and one more, which is O(1).
Edge cases and common mistakes
- Skipping the empty-cell test. Without
!= '.', an empty board would report a winner, because three dots are equal. The driver's last game catches this: a new game must giveNo winner: .. - Passing the turn on an ignored move. If the guard doesn't
returnearly, the turn changes even though the board didn't, and every later mark in that game goes to the wrong player. - Overwriting a taken cell. The guard must come before the assignment, or a repeated move replaces the earlier mark.
- Forgetting the second diagonal. A game won with (0,2), (1,1) and (2,0) would report no winner. The driver's fourth game covers it.
- A draw. A full board with no line, like the fifth game, gives
'.'. The function can't tell a draw from an unfinished game, and the lesson doesn't ask it to. - Moves after a win. This solution doesn't stop a game when someone has won. If more moves are played, they are still accepted, and
winner()keeps reporting from the board. The lesson's tests don't do this, and a full game would checkwinner()before each move. - Indexes out of range. The solution does not check the range, because the lesson promises 0 to 2. A call like
move(3, 0)panics withindex out of range [3] with length 3. - Mixing up row and column.
board[row][col]takes the row first. Swapping them transposes the game, which can turn a column win into a row win.
Key takeaways
- A struct with a fixed-size array field is a good fit for a board, but the array's cells start as zero values and need filling.
- Guard early: refuse a bad move before changing any state.
- Eight lines cover every win on a 3 by 3 board, and each test needs the first cell to be non-empty.
- A
runeis a number: print it with%cto see the character.
