Problem overview
The lesson asks for 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.
Rows and columns are numbered 0, 1 and 2, and cell (0, 0) is the top-left corner. A cell holds 'X', 'O' or '.' when it is still empty. The class has:
- a field
board: string[][]with three rows of three dots, and a fieldplayer: stringthat starts as'X', because X moves first; move(r: number, c: number): void, which marks a cell for the current player and then passes the turn. If the cell is taken, the call is ignored: nothing changes and it is still the same player's turn;winner(): string, which returns'X'or'O'when that player has three marks in a row, a column or a diagonal, and'.'otherwise. A game in progress, an empty board and a draw all give'.'.
The driver plays six games. In the first, X takes the top row while O plays below. In the second, X tries to play on the cell it already holds, which is ignored, and O wins the middle column. The third and fourth games are won by X on each diagonal, the fifth fills the board with no winner, and the sixth is a new game with no moves.
Approach: store the board, switch the player, scan eight lines
The board is an array of three rows, each an array of three strings, so this.board[r][c] is the cell in row r, column c. Using '.' for an empty cell keeps every cell a one-character string.
A move has two jobs: refuse a taken cell, and otherwise write the mark and give the turn to the other player. Because the refusal returns before the turn changes, a rejected move leaves the same player to try again.
A tic-tac-toe board has exactly eight winning lines: three rows, three columns and two diagonals. winner checks them one by one. A line wins when its first cell is not a dot and all three cells hold the same mark. The first-cell test matters: three empty cells are equal to each other too, but three dots are not a win. A loop over i from 0 to 2 covers row i and column i together, and the two diagonals follow it. If nothing matched, the method returns a dot.
Step by step
- Declare the class
TicTacToeand its closing brace. Each object created later is its own game with its own memory. - Declare the board as
board: string[][], built withArray.from({length: 3}, () => Array(3).fill('.')).Array.fromcalls the function once for each of the three slots, so each row is a fresh array.Array(3).fill('.')makes one row of three dots. - Declare
player: string = 'X', the mark whose turn it is. - Start
move(r, c)with two number parameters and the return typevoid. - Guard against a taken cell: if
this.board[r][c]is not'.', return at once. - Place the mark: store
this.playerin that cell. - Pass the turn with a conditional expression: if the player was
'X', it becomes'O', otherwise'X'. - Start
winner(), returning astring. - Give the board a short name:
const b: string[][] = this.board;. This is the same array, not a copy, so it only shortens the lines below. - Loop
ifrom 0 to 2. Each pass checks rowiand columni. - Check row
i: the first cell isn't a dot, equals the second, and the second equals the third. If so, return that mark. - Check column
ithe same way, with the two indexes swapped. - After the loop, check the main diagonal: cells (0,0), (1,1), (2,2).
- Check the other diagonal: cells (0,2), (1,1), (2,0). The row goes up by one as the column goes down.
- Return
'.'as the last line: every check failed, so nobody has won.
The solution in TypeScript
class TicTacToe {
board: string[][] = Array.from({length: 3}, () => Array(3).fill('.'));
player: string = 'X';
move(r: number, c: number): void {
if (this.board[r][c] !== '.') return;
this.board[r][c] = this.player;
this.player = this.player === 'X' ? 'O' : 'X';
}
winner(): string {
const b: string[][] = this.board;
for (let i = 0; i < 3; i++) {
if (b[i][0] !== '.' && b[i][0] === b[i][1] && b[i][1] === b[i][2]) return b[i][0];
if (b[0][i] !== '.' && b[0][i] === b[1][i] && b[1][i] === b[2][i]) return b[0][i];
}
if (b[0][0] !== '.' && b[0][0] === b[1][1] && b[1][1] === b[2][2]) return b[0][0];
if (b[0][2] !== '.' && b[0][2] === b[1][1] && b[1][1] === b[2][0]) return b[0][2];
return '.';
}
}
let game: TicTacToe = new TicTacToe();
game.move(0, 0);
game.move(1, 0);
game.move(0, 1);
game.move(1, 1);
game.move(0, 2);
console.log(game.winner() + " wins!");
game = new 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);
console.log(game.winner() + " wins!");
game = new TicTacToe();
game.move(0, 0);
game.move(0, 1);
game.move(1, 1);
game.move(0, 2);
game.move(2, 2);
console.log(game.winner() + " wins!");
game = new TicTacToe();
game.move(0, 2);
game.move(0, 0);
game.move(1, 1);
game.move(0, 1);
game.move(2, 0);
console.log(game.winner() + " wins!");
game = new 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);
console.log("No winner: " + game.winner());
game = new TicTacToe();
console.log("No winner: " + game.winner());
It prints:
X wins!
O wins!
X wins!
X wins!
No winner: .
No winner: .
The games on the board
Printing each row of board as a string shows where the marks end up. In the first game, X holds the top row and O has two marks below it:
XXX
OO.
...
In the second game, after the repeated move(0, 0) was ignored and the other moves were played, O holds the middle column:
XO.
XO.
.OX
The third and fourth games end like this, with X on the main diagonal and then on the other one:
XOO
.X.
..X
OOX
.X.
X..
The fifth game fills every cell and nobody has three in a line:
XOX
XOO
OXX
TypeScript details worth knowing
- Each row must be its own array.
Array(3).fill(Array(3).fill('.'))puts one and the same row into all three slots. Afterbad[0][0] = 'X', the three rows print asX..|X..|X... WithArray.from({length: 3}, () => Array(3).fill('.'))the same assignment givesX..|...|..., because the function runs again for every row. - Two-dimensional arrays.
string[][]is an array of arrays.b[1][2]first takes row 1, then cell 2 of it. !==and===. They compare without converting types. For single-character strings they simply compare the characters.&&short-circuits. In each chain, the first comparison is the "not a dot" test, so the rest runs only for a marked first cell.- The conditional expression.
test ? a : bgivesawhen the test is true andbotherwise. It is an expression, so its result can be assigned directly tothis.player. this.playeris read before it changes. Inmove, the mark is written first and the player is switched second. Switching first would put the wrong mark on the board.- Types don't check the range.
randcare plainnumbers, and the compiler can't tell 0 to 2 from 7. The lesson promises valid values.
Complexity
Time. move is O(1): one read, one write, one switch. winner looks at a fixed number of cells: three passes of the loop plus two diagonals, so it is O(1) for a 3 by 3 board. (For an n by n board the same scan would cost O(n²).) Space. The board holds nine cells and one player mark, which is O(1).
Edge cases and common mistakes
- Empty lines are not wins. Without the
!== '.'test, a new game would report a winner, because three dots are equal: comparing a row of an empty board givestrue. The sixth driver game covers this. - Passing the turn on a refused move. If the guard doesn't return before the turn changes, a player who picks a taken cell loses the turn. In the second game, the repeated
move(0, 0)is X's attempt and must leave X to play next, so the following moves, X at (1, 0), O at (1, 1), X at (2, 2) and O at (2, 1), keep their order. - Overwriting a mark. Without the guard, a move onto a marked cell replaces the mark: if O played on a cell X holds, X's mark would be lost.
- Sharing rows. Building the board with
fillon an array of arrays makes all three rows the same row, as shown above. - Swapped indexes.
b[r][c]is row then column. The column check usesb[0][i],b[1][i],b[2][i], which is the row check with the indexes swapped. - Checking only one diagonal, or putting the diagonals inside the loop. They don't depend on
i, so they run once, after it. - Draws. A full board with no line returns
'.', the same answer as a game still in progress.winnerdoesn't say whether the game is over. - Moves after a win. The class doesn't stop play. After X completes the top row, a further
move(2, 2)by O is still accepted andwinner()still saysX. - Out-of-range indexes.
move(3, 0)throws aTypeError(Cannot read properties of undefined), because there is no row 3.move(0, 3)is ignored silently, because the missing cell is not'.'. The lesson never calls either.
Testing
- A new game:
winner()is'.'. - Moves (0,0), (1,0), (0,1), (1,1), (0,2): X has the top row, and
winner()is'X'. - Moves (0,0), (0,1), (0,0), (1,0), (1,1), (2,2), (2,1): the repeated (0,0) is ignored and
winner()is'O'. - Moves (0,0), (0,1), (1,1), (0,2), (2,2): X has the main diagonal,
'X'. - Moves (0,2), (0,0), (1,1), (0,1), (2,0): X has the other diagonal,
'X'. - The nine-move game from the driver ends with a full board and
'.'.
