Start learning free

LESSON 68 OF 69 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in Rust: 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. Rust has no constructors, so TicTacToe::new() returns a new game: board: Vec<Vec<char>> with three rows of three '.' and player: char set to 'X'. All nine cells are empty and X moves first.
  • fn move_pos(&mut self, r: usize, c: usize) (named move_pos because move is a Rust keyword) 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).
  • fn winner(&self) -> 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:

fn mainFunction() {
    let mut game = TicTacToe::new();
    game.move_pos(0, 0);
    game.move_pos(1, 0);
    game.move_pos(0, 1);
    game.move_pos(1, 1);
    game.move_pos(0, 2);
    println!("{} wins!", game.winner());
    game = TicTacToe::new();
    game.move_pos(0, 0);
    game.move_pos(0, 1);
    game.move_pos(0, 0);
    game.move_pos(1, 0);
    game.move_pos(1, 1);
    game.move_pos(2, 2);
    game.move_pos(2, 1);
    println!("{} wins!", game.winner());
    game = TicTacToe::new();
    game.move_pos(0, 0);
    game.move_pos(0, 1);
    game.move_pos(1, 1);
    game.move_pos(0, 2);
    game.move_pos(2, 2);
    println!("{} wins!", game.winner());
    game = TicTacToe::new();
    game.move_pos(0, 2);
    game.move_pos(0, 0);
    game.move_pos(1, 1);
    game.move_pos(0, 1);
    game.move_pos(2, 0);
    println!("{} wins!", game.winner());
    game = TicTacToe::new();
    game.move_pos(0, 0);
    game.move_pos(0, 1);
    game.move_pos(0, 2);
    game.move_pos(1, 1);
    game.move_pos(1, 0);
    game.move_pos(1, 2);
    game.move_pos(2, 1);
    game.move_pos(2, 0);
    game.move_pos(2, 2);
    println!("No winner: {}", game.winner());
    game = TicTacToe::new();
    println!("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.

struct TicTacToe {
    board: Vec<Vec<char>>,
    player: char,
}
impl TicTacToe {
    fn new() -> TicTacToe {
        TicTacToe {
            board: vec![vec!['.'; 3]; 3],
            player: 'X',
        }
    }
    fn move_pos(&mut self, r: usize, c: usize) {
        if self.board[r][c] != '.' {
            return;
        }
        self.board[r][c] = self.player;
        self.player = if self.player == 'X' { 'O' } else { 'X' };
    }
    fn winner(&self) -> char {
        for i in 0..3 {
            if self.board[i][0] != '.'
                && self.board[i][0] == self.board[i][1]
                && self.board[i][1] == self.board[i][2]
            {
                return self.board[i][0];
            }
            if self.board[0][i] != '.'
                && self.board[0][i] == self.board[1][i]
                && self.board[1][i] == self.board[2][i]
            {
                return self.board[0][i];
            }
        }
        if self.board[0][0] != '.'
            && self.board[0][0] == self.board[1][1]
            && self.board[1][1] == self.board[2][2]
        {
            return self.board[0][0];
        }
        if self.board[0][2] != '.'
            && self.board[0][2] == self.board[1][1]
            && self.board[1][1] == self.board[2][0]
        {
            return self.board[0][2];
        }
        '.'
    }
}

STEP 1 OF 19
    Ctrl + Enter to check

    RUST · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in Rust, explained

    Problem overview

    You build TicTacToe, a struct where one value is one game between X and O on a 3 by 3 board. 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, and cell (0, 0) is the top-left corner. The struct has two fields:

    • board: Vec<Vec<char>>, three rows of three characters: 'X', 'O' or '.' for an empty cell.
    • player: char, the mark whose turn it is. X moves first.

    And three functions:

    • TicTacToe::new() returns a fresh game: nine dots and player set to 'X'.
    • move_pos(&mut self, r: usize, c: usize) plays one turn. If the cell is taken, nothing happens and it is still the same player's turn. Otherwise it places the current mark and passes the turn. The name isn't move because move is a Rust keyword.
    • winner(&self) -> char returns 'X' or 'O' if that player has three in a row, a column or a diagonal, and '.' otherwise. That covers a game in progress, an empty board and a draw.

    The starter code plays six games. It fills the top row with X, plays a game where X tries a taken cell and O wins the middle column, wins on each diagonal, fills the board with no winner, and checks a new game. The expected output is:

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

    Approach: guard the move, check eight lines

    For move_pos, look first: if the cell isn't a dot, return before changing anything. That one early return guarantees that a rejected move changes neither the board nor the turn.

    For winner, a game can be won in eight ways: three rows, three columns and two diagonals. A loop over i from 0 to 2 can test row i and column i together, and the two diagonals follow the loop. Each test asks whether the first cell of the line isn't a dot and whether all three cells are equal. The first cell test matters: three empty cells are equal to each other, but they aren't a win.

    Step by step

    1. Declare struct TicTacToe. One value of it is one game.
    2. Add board: Vec<Vec<char>>. Then self.board[r][c] is the cell in row r, column c.
    3. Add player: char, the mark that moves next.
    4. Open impl TicTacToe for the functions.
    5. Write new, taking nothing and returning a TicTacToe. It has no self, so it's called as TicTacToe::new().
    6. Start the struct literal as its last expression.
    7. Set board to vec![vec!['.'; 3]; 3]. The inner vec! is one row of three dots, and the outer one repeats it three times.
    8. Set player to 'X'.
    9. Write move_pos with &mut self and two usize parameters, since usize is the type for positions in a list.
    10. Guard against a taken cell: if self.board[r][c] isn't a dot, return;.
    11. Place the mark: self.board[r][c] = self.player;.
    12. Pass the turn. In Rust if is an expression, so self.player = if self.player == 'X' { 'O' } else { 'X' }; assigns the other mark in one line.
    13. Write winner with &self, since it only reads, returning a char.
    14. Loop i over 0..3. The range includes 0, 1 and 2, and leaves out 3.
    15. Check row i: the first cell isn't a dot, and it equals the second, which equals the third. If so, return that mark.
    16. Check column i the same way, with the two indexes swapped.
    17. Check the main diagonal after the loop: (0,0), (1,1), (2,2).
    18. Check the other diagonal: (0,2), (1,1), (2,0).
    19. End with '.', with no return and no semicolon. If no check matched, that is the result.

    The solution in Rust

    struct TicTacToe {
        board: Vec<Vec<char>>,
        player: char,
    }
    impl TicTacToe {
        fn new() -> TicTacToe {
            TicTacToe {
                board: vec![vec!['.'; 3]; 3],
                player: 'X',
            }
        }
        fn move_pos(&mut self, r: usize, c: usize) {
            if self.board[r][c] != '.' {
                return;
            }
            self.board[r][c] = self.player;
            self.player = if self.player == 'X' { 'O' } else { 'X' };
        }
        fn winner(&self) -> char {
            for i in 0..3 {
                if self.board[i][0] != '.'
                    && self.board[i][0] == self.board[i][1]
                    && self.board[i][1] == self.board[i][2]
                {
                    return self.board[i][0];
                }
                if self.board[0][i] != '.'
                    && self.board[0][i] == self.board[1][i]
                    && self.board[1][i] == self.board[2][i]
                {
                    return self.board[0][i];
                }
            }
            if self.board[0][0] != '.'
                && self.board[0][0] == self.board[1][1]
                && self.board[1][1] == self.board[2][2]
            {
                return self.board[0][0];
            }
            if self.board[0][2] != '.'
                && self.board[0][2] == self.board[1][1]
                && self.board[1][1] == self.board[2][0]
            {
                return self.board[0][2];
            }
            '.'
        }
    }
    fn mainFunction() {
        let mut game = TicTacToe::new();
        game.move_pos(0, 0);
        game.move_pos(1, 0);
        game.move_pos(0, 1);
        game.move_pos(1, 1);
        game.move_pos(0, 2);
        println!("{} wins!", game.winner());
        game = TicTacToe::new();
        game.move_pos(0, 0);
        game.move_pos(0, 1);
        game.move_pos(0, 0);
        game.move_pos(1, 0);
        game.move_pos(1, 1);
        game.move_pos(2, 2);
        game.move_pos(2, 1);
        println!("{} wins!", game.winner());
        game = TicTacToe::new();
        game.move_pos(0, 0);
        game.move_pos(0, 1);
        game.move_pos(1, 1);
        game.move_pos(0, 2);
        game.move_pos(2, 2);
        println!("{} wins!", game.winner());
        game = TicTacToe::new();
        game.move_pos(0, 2);
        game.move_pos(0, 0);
        game.move_pos(1, 1);
        game.move_pos(0, 1);
        game.move_pos(2, 0);
        println!("{} wins!", game.winner());
        game = TicTacToe::new();
        game.move_pos(0, 0);
        game.move_pos(0, 1);
        game.move_pos(0, 2);
        game.move_pos(1, 1);
        game.move_pos(1, 0);
        game.move_pos(1, 2);
        game.move_pos(2, 1);
        game.move_pos(2, 0);
        game.move_pos(2, 2);
        println!("No winner: {}", game.winner());
        game = TicTacToe::new();
        println!("No winner: {}", game.winner());
    }
    

    Following one game

    The second game in the driver plays (0,0), (0,1), (0,0) again, (1,0), (1,1), (2,2), (2,1). After those calls the board and the next player are:

    XO.
    XO.
    .OX
    next: X
    

    The repeated (0,0) was ignored, so X was still on turn and played (1,0). O then holds all of column 1, so winner returns 'O'. A game with only the repeated move, (0,0) twice, leaves a board with a single X and next: O.

    Language details

    • Indexes are usize. self.board[r][c] only accepts usize indexes, which is why the parameters have that type.
    • Out-of-range moves panic. The lesson promises rows and columns between 0 and 2, so there's no range check. A call such as move_pos(3, 0) ends the program with index out of bounds: the len is 3 but the index is 3.
    • char literals use single quotes. 'X' is a char and "X" is a string, and they can't be compared with each other.
    • Cloning isn't needed. Returning self.board[i][0] copies a char, because char is a Copy type.
    • The keyword move. let move = 3; fails with expected identifier, found keyword `move`, which is why the method is move_pos.

    Complexity

    The board is a fixed 3 by 3 grid. move_pos does a constant amount of work, and winner tests eight lines of three cells, so both are O(1). The board takes constant space.

    Edge cases and common mistakes

    • Passing the turn on a rejected move. If the turn changed even when the cell was taken, X would lose a turn. The early return prevents it.
    • Treating empty lines as wins. Three dots in a row are equal to each other. Without the != '.' test, an empty row or column would make winner return '.' immediately, before the later lines are checked, so a real win further down could be missed.
    • Forgetting a line. A solution that checks the rows and columns but not the diagonals would fail the third and fourth games.
    • Draws. A full board with no three in a row returns '.', the same as an unfinished game. The function doesn't distinguish them.
    • Moves after a win. The lesson doesn't stop the game after a win: move_pos keeps accepting moves on empty cells. The tests never rely on this.

    Key takeaways

    • Keep a game's state in a struct: here the board and the current player.
    • Return early on invalid input so a rejected move changes nothing.
    • Count the winning lines (three rows, three columns, two diagonals) and check each, with a loop for the rows and columns.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free