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 andplayerset 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'tmovebecausemoveis a Rust keyword.winner(&self) -> charreturns'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
- Declare
struct TicTacToe. One value of it is one game. - Add
board: Vec<Vec<char>>. Thenself.board[r][c]is the cell in rowr, columnc. - Add
player: char, the mark that moves next. - Open
impl TicTacToefor the functions. - Write
new, taking nothing and returning aTicTacToe. It has noself, so it's called asTicTacToe::new(). - Start the struct literal as its last expression.
- Set
boardtovec![vec!['.'; 3]; 3]. The innervec!is one row of three dots, and the outer one repeats it three times. - Set
playerto'X'. - Write
move_poswith&mut selfand twousizeparameters, sinceusizeis the type for positions in a list. - Guard against a taken cell: if
self.board[r][c]isn't a dot,return;. - Place the mark:
self.board[r][c] = self.player;. - Pass the turn. In Rust
ifis an expression, soself.player = if self.player == 'X' { 'O' } else { 'X' };assigns the other mark in one line. - Write
winnerwith&self, since it only reads, returning achar. - Loop
iover0..3. The range includes 0, 1 and 2, and leaves out 3. - Check row
i: the first cell isn't a dot, and it equals the second, which equals the third. If so, return that mark. - Check column
ithe same way, with the two indexes swapped. - Check the main diagonal after the loop: (0,0), (1,1), (2,2).
- Check the other diagonal: (0,2), (1,1), (2,0).
- End with
'.', with noreturnand 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 acceptsusizeindexes, 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 withindex out of bounds: the len is 3 but the index is 3. charliterals use single quotes.'X'is acharand"X"is a string, and they can't be compared with each other.- Cloning isn't needed. Returning
self.board[i][0]copies achar, becausecharis aCopytype. - The keyword
move.let move = 3;fails withexpected identifier, found keyword `move`, which is why the method ismove_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 makewinnerreturn'.'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_poskeeps 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.
