Start learning free

LESSON 68 OF 69 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in Go: A Two-Player Game Struct

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. Go has no constructors, so func newTicTacToe() *TicTacToe returns a new game: the struct has a board [3][3]rune filled with '.' by two nested loops and a player rune set to 'X'. All nine cells are empty and X moves first.
  • func (game *TicTacToe) move(row int, col 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).
  • func (game TicTacToe) winner() rune returns the winner as a rune: '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:

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())
}

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.

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 '.'
}

STEP 1 OF 21
    Ctrl + Enter to check

    GO · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in Go, explained

    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() *TicTacToe returns 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() rune returns '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

    1. Declare the struct with board [3][3]rune (an array of three rows, each an array of three runes) and player rune.
    2. Write newTicTacToe, which returns a pointer to the game. Go has no constructors, so a plain function starting with new does the job.
    3. 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.
    4. Fill the board with two nested loops. for row := range game.board runs once per row, and for col := range game.board[row] visits the three cells of that row. Each cell is set to '.'.
    5. Return game.

    The move

    1. Declare move with a pointer receiver, (game *TicTacToe), since it changes the game.
    2. Guard against a taken cell. If game.board[row][col] isn't a dot, return before touching anything. The board and the turn both stay as they were.
    3. Place the mark: game.board[row][col] = game.player.
    4. Pass the turn. If the player is 'X' it becomes 'O', otherwise it becomes 'X'. Only a successful move gets this far.

    The winner

    1. Declare winner with a plain TicTacToe receiver. It only reads the game.
    2. Loop i from 0 to 2. Inside, check row i (cells [i][0], [i][1], [i][2]) and column i (cells [0][i], [1][i], [2][i]), returning the mark on a match.
    3. Check the main diagonal after the loop: cells (0,0), (1,1) and (2,2).
    4. 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.
    5. 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]rune is an array, not a slice, and it is stored inside the struct. Assigning a struct copies the whole board, and the method winner, which has a value receiver, works on a copy. That is harmless for a reader. A value receiver on move would 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.
    • range over an array. for row := range game.board gives only the index when there is one variable on the left, so game.board[row] is the row itself.
    • Runes are numbers. 'X' is the integer 88 and '.' is 46. fmt.Println(game.winner()) prints 46 for a game with no winner. fmt.Printf("%c", ...) prints the character, and %q prints 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, so game.player == "X" doesn't compile. Convert with string(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 give No winner: ..
    • Passing the turn on an ignored move. If the guard doesn't return early, 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 check winner() 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 with index 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 rune is a number: print it with %c to see the character.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free