Design Tic-Tac-Toe
Design a Tic-Tac-Toe game for any board size, with a clean split between board and game, a one-step win check using counters, and clear answers for invalid moves and extensions.
Tic-Tac-Toe looks like a toy, and that is exactly why interviewers like it. Everyone knows the rules, so the whole interview is about your design: how you split the work between classes, how you handle wrong moves, how you detect a win, and how easily your design grows. A good answer to this small problem shows you can think clearly, and a great answer adds one clever idea that makes it efficient.
We will use the seven-step method from Module 1 again. This time we will also discover a neat trick for checking a win in a single step.
01The problem
Design a Tic-Tac-Toe game. Two players take turns placing their mark on a 3 by 3 board. The first to complete a row, a column or a diagonal wins. If the board is full and nobody has won, it is a draw.
02Step 1: Clarify the requirements
| Question | Answer we assume |
|---|---|
| Is the board always 3 by 3? | No: make the size a parameter, so any N by N board works |
| How many players? | Two, called X and O. They alternate. X goes first |
| What counts as a win? | A full row, a full column or a full diagonal of one mark |
| What if a player plays in a taken cell or outside the board? | The move is rejected with a clear error, and it is still the same player's turn |
| What happens after the game ends? | No more moves are accepted |
| User interface, computer opponent, networking? | Out of scope. We will discuss how they fit in |
The requirements:
| Type | Requirement |
|---|---|
| Must do | Create a game with a board of size N and two players |
| Must do | Accept a move (row, column), alternating the players |
| Must do | Reject invalid moves without changing the turn |
| Must do | Detect a win or a draw, and stop accepting moves |
| Out of scope | Screen, computer player, network play, undo |
03Steps 2 and 3: Entities and responsibilities
The nouns are game, board, cell, player, mark, move, win and draw. Not all become classes: a cell is just a place in the board that holds a mark, so it stays inside Board.
| Class | What it knows | What it does |
|---|---|---|
Mark (enum) | The two marks, X and O | Gives players their symbol |
Player | A name and a mark | Identifies who plays |
Board | The size and the marks placed | Places a mark, rejects invalid moves, says whether the move won, says whether it is full |
GameStatus (enum) | IN_PROGRESS, WON or DRAW | Describes how the game stands |
Game | The board, the two players, whose turn it is, the status and the winner | Accepts moves, switches turns, decides when the game ends |
The important design decision is the split between Board and Game. The board knows the grid and the marks on it. The game knows the rules of play: turns, win, draw. This keeps each class small, and it means the board could be reused for another grid game.
04Step 4: The class diagram
Notice how few types we need. Resist adding classes such as Cell, Move or Rules unless the requirements ask for them. A simple design is easier to explain and to get right (KISS and YAGNI from Module 2).
05The clever part: detecting a win in one step
How should the board find out whether a move won the game? The obvious way is to scan: after each move, look at the move's row, column and diagonals and check whether all their cells are the same. That costs about N steps per move.
There is a neater way. Give every row, every column and both diagonals a counter:
- When X places a mark, add +1 to the counters of its row, its column and, if it lies on them, the two diagonals.
- When O places a mark, add -1 to the same counters.
- A line is won the moment its counter reaches +N (all X) or -N (all O).
If a line holds both X and O, the plus and minus cancel, so the counter can never reach N in size. And after a move, only up to four counters changed, so only those need checking.
The board shown has X in three corners of the diagonal, so the diagonal counter becomes +3, which equals the board size, and X wins. Only those few counters were examined. This idea is worth saying out loud in an interview, because it shows that you think about efficiency: one step for each move, however big the board is.
06Step 6: The key code
The small types first:
public enum Mark { X, O }
public enum GameStatus { IN_PROGRESS, WON, DRAW }
public record Player(String name, Mark mark) { }Now the board, which holds the grid and the counters:
public class Board {
private final int size;
private final Mark[][] cells;
private final int[] rowSums;
private final int[] colSums;
private int diagonalSum;
private int antiDiagonalSum;
private int movesMade;
public Board(int size) {
this.size = size;
this.cells = new Mark[size][size];
this.rowSums = new int[size];
this.colSums = new int[size];
}
/** Places the mark and returns true if this move completed a line. */
public boolean place(int row, int col, Mark mark) {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("That cell is outside the board");
}
if (cells[row][col] != null) {
throw new IllegalStateException("That cell is already taken");
}
cells[row][col] = mark;
movesMade++;
int delta = (mark == Mark.X) ? 1 : -1;
rowSums[row] += delta;
colSums[col] += delta;
if (row == col) diagonalSum += delta;
if (row + col == size - 1) antiDiagonalSum += delta;
return Math.abs(rowSums[row]) == size
|| Math.abs(colSums[col]) == size
|| Math.abs(diagonalSum) == size
|| Math.abs(antiDiagonalSum) == size;
}
public boolean isFull() {
return movesMade == size * size;
}
}Read place carefully. The checks for invalid moves come first, before anything is changed. That is why an invalid move leaves the board untouched.
And the game, which owns the turns and the outcome:
public class Game {
private final Board board;
private final Player[] players;
private int turn = 0;
private GameStatus status = GameStatus.IN_PROGRESS;
private Player winner;
public Game(int size, Player first, Player second) {
this.board = new Board(size);
this.players = new Player[] { first, second };
}
public void play(int row, int col) {
if (status != GameStatus.IN_PROGRESS) {
throw new IllegalStateException("The game is over");
}
Player current = players[turn];
boolean won = board.place(row, col, current.mark()); // may throw: turn unchanged
if (won) {
status = GameStatus.WON;
winner = current;
} else if (board.isFull()) {
status = GameStatus.DRAW;
} else {
turn = 1 - turn; // the other player's turn
}
}
public GameStatus status() { return status; }
public Player currentPlayer() { return players[turn]; }
public Optional<Player> winner() { return Optional.ofNullable(winner); }
}A short example of play:
Game game = new Game(3, new Player("Asha", Mark.X), new Player("Ravi", Mark.O));
game.play(0, 0); // X
game.play(0, 1); // O
game.play(1, 1); // X
game.play(0, 2); // O
game.play(2, 2); // X completes the diagonal
System.out.println(game.status()); // WON
System.out.println(game.winner().get().name()); // Asha07Step 5: Walk through the scenarios
| Scenario | What happens |
|---|---|
| X completes a diagonal | place returns true, status becomes WON, the winner is stored and the turn does not change ✔ |
| The ninth move, nobody has won | place returns false, isFull is true, status becomes DRAW ✔ |
| A player plays outside the board | place throws before changing anything. The exception reaches the caller, the status and the turn stay the same, so the player tries again ✔ |
| A player plays a taken cell | The same: an error, no change to the board or the turn ✔ |
| A move after the game ended | play refuses at the very start with "The game is over" ✔ |
| Board of size 5 | Everything works. The counters need to reach 5 ✔ |
Walking through these cases found that the order of checks matters: validation must come before any change. This is the kind of detail the walk-through step catches.
08Step 7: Extensions and trade-offs
| New requirement | How the design copes |
|---|---|
| A computer opponent | Give each Player a MoveStrategy interface with nextMove(Board). A human, a random player and a smart minimax player are different strategies. Game asks the current player's strategy for the move (Strategy pattern) |
| Undo | Make every move a Command with execute and undo, and keep a history stack (Command pattern). Undoing a move reverses the counters |
| Show the board on a screen | Keep the UI outside. The UI calls play and reads the status. Optionally, the game notifies listeners after each move (Observer) |
| K in a row on a big board (for example 4 in a row on 10 by 10) | The simple counters no longer work. After each move, look along the four directions from the last cell and count how many equal marks are connected |
| Many games on a server | Add a GameManager that creates games and holds them by id |
| Replay a finished game | Store the list of moves, and replay them on a new board |
You might also be asked whether GameStatus should use the State pattern. For three simple states, an enum with an if is enough. State would be over-engineering here. That is a good moment to show judgement: "I considered State, but with three states and almost no behaviour per state, an enum is simpler."
09Common mistakes in this interview question
- Hard-coding 3 by 3. Interviewers often ask "what about 5 by 5?". Make the size a parameter from the start.
- A win check that scans the whole board after every move. Check only the affected lines, or use counters.
- Changing the board before validating. Then a rejected move leaves the game in a broken state.
- Switching the turn after an invalid move. The same player must try again.
- Mixing the UI with the game rules. Printing and reading input belong outside
GameandBoard. - Too many classes.
Cell,Move,RulesandWinCheckerare usually unnecessary here.
10In the interview
- How would you add an AI player? Add a MoveStrategy interface for choosing the next move, with human, random and minimax implementations, and let each player hold one.
- How would you support undo? Represent each move as a command with execute and undo, keep them on a stack, and reverse the counters on undo.
- What changes for a game like Connect Four or five-in-a-row? The counter idea no longer fits, because a winning line is only part of a longer row. After each move, count connected equal marks in the four directions around the last cell.
11Check your understanding
Quiz · 4 questions
0 of 4 answered
1. Why does the Board keep row and column counters instead of scanning for a win?
2. In the counter idea, how are X and O told apart?
3. A player tries to play in a cell that is already taken. What should the design do?
4. How would you add an AI opponent without changing the Game class much?