Design tic-tac-toe
Design a two-player tic-tac-toe game that can be extended to an N by N board.
Good first question for: Fresher
Requirements to confirm first
- Two players take turns placing their mark on an empty cell
- Detect a win (a full row, column or diagonal) or a draw after every move
- Reject a move on a taken cell, outside the board, or after the game has ended
- The board size N is given at the start, and the win rule is N in a line
- Ask: two humans only, or a computer player later?
Write your own class list on paper before you open the answer key. Ten minutes of your own design is the practice; reading the key is only the check.
Show the answer key (write yours first)
Classes and what each one owns
- Game
- Runs the turns and holds the status: in progress, won or draw
- Board
- Owns the grid, validates and applies a move, reports a win
- Player
- Has a name and a mark
- Move
- A row, a column and the player who made it
- MoveSource
- Interface for where the next move comes from: a human now, a computer later
How they connect
- Game has one Board and two Players and asks the current player's MoveSource for a move
- Board knows nothing about names or turn order; it only stores marks, so it can be reused
- A computer player is a new MoveSource with no change to Game or Board
Design patterns that fit, and why
- Strategy
- MoveSource lets a human and a computer player be swapped without touching the game loop.
- State
- Only if statuses grow (paused, timed out). For three statuses an enum and one check is clearer.
Code sketch in Java
The core types and one real method. It is a sketch to talk through, not a full program.
class Board {
private final int n;
private final int[][] cells; // 0 empty, +1 for X, -1 for O
private final int[] rows, cols; // running sum per row and per column
private int diag, antiDiag, filled;
// call only after checking the cell is empty; returns true when this move wins
boolean place(int r, int c, int sign) {
cells[r][c] = sign;
rows[r] += sign; cols[c] += sign;
if (r == c) diag += sign;
if (r + c == n - 1) antiDiag += sign;
filled++;
return Math.abs(rows[r]) == n || Math.abs(cols[c]) == n
|| Math.abs(diag) == n || Math.abs(antiDiag) == n;
}
boolean isFull() { return filled == n * n; }
}Edge cases to raise yourself
- A move outside the board or on a taken cell
- The last cell both fills the board and wins: check the win before the draw
- A move that arrives after the game is over
Where answers usually go wrong
- Scanning the whole board after every move. A running sum per row, column and diagonal makes the check constant time, and the interviewer usually asks for it.
- Letting Board know whose turn it is. Turn order belongs to Game; Board should work for any two marks.
- Hard-coding 3. Taking N from the start costs nothing and is the standard follow-up.
Follow-up questions
- Add a computer player
- Undo the last move
- Win with K in a line on an N by N board: why do the running sums stop working?