Tic-Tac-Toe with Minimax in React
An unbeatable tic-tac-toe opponent in React shows why game logic as a pure function must know nothing about rendering – and why immutable moves fit React’s model.
Tic-Tac-Toe with Minimax in React
function score(board, depth) {
if (winnerOf(board) === COMPUTER) return 10 - depth;
if (winnerOf(board) === HUMAN) return depth - 10;
return 0;
}
An unbeatable tic-tac-toe opponent doesn’t need more evaluation than this. A board is worth 10 - depth if the computer has won, depth - 10 if the human has won, and zero for a draw. As a bonus, the search depth in the value provides playing style: a win in two moves counts more than one in four, and a loss in four moves is less bad than one in two. So the opponent wins as early as possible and loses as late as possible – if it can lose at all, which never happens with flawless play.
More striking than what is in the function is what is missing: no React, no DOM, no event handler, no this, no setState. A board goes in, a number comes out. That is exactly what this article is about. The game itself is trivial; every child learns it in five minutes. What’s interesting is the dividing line: the entire opponent is a set of pure functions over an array, and in the end React only renders state. If you don’t draw this line, you later have neither testable logic nor a replaceable UI.
I built the accompanying repository react-tic-tac-toe in October 2016, prompted by Carsten König’s Othello in Elm – a project that impressed me at the time because the same separation was a matter of course there. In Elm, there simply is no other option: game logic is one function, the view another. In JavaScript, you have to decide on it.
The board is an array, a move is a new board#
The data structure is as small as it sounds: an array with nine fields, each field 'X', 'O' or null. The indices 0 to 8 run row by row from top left to bottom right. The winning conditions are eight lines over these indices – three rows, three columns, two diagonals.
const HUMAN = 'X';
const COMPUTER = 'O';
const LINES = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
];
function winnerOf(board) {
const line = LINES.find(([a, b, c]) =>
board[a] && board[a] === board[b] && board[a] === board[c]);
return line ? board[line[0]] : null;
}
function movesFor(board) {
return board.reduce((moves, field, index) =>
field === null ? moves.concat(index) : moves, []);
}
function applyMove(board, index, player) {
const next = board.slice();
next[index] = player;
return next;
}
The most important decision is in applyMove: a move doesn’t change the board, it creates a new one. board.slice() copies the array, then one field is set, and the original stays untouched. For nine elements, that costs nothing, and it pays off twice.
First, for the search. Minimax tries moves hypothetically: What if the computer plays field 4 and the human then plays field 0? With mutation, every tried move would have to be taken back after the evaluation – classic do/undo with every opportunity to forget the undo part. With immutable boards, there is nothing to take back. Each branch of the game tree holds its own board, and when the recursion returns, the old board is still exactly the old board.
Second, for React. setState with a fresh array means: if you want to know whether something has changed, you compare references instead of contents. It is no coincidence that the official React tutorial – of all things also a tic-tac-toe – recommends slice() at the same spot. Immutable data is the currency React thinks in. That the same decision simplifies the search algorithm and serves the UI model at the same time was the real aha moment of this small project for me.
Minimax, told recursively#
The algorithm is older than any web framework and can be summed up in one sentence: I choose the move that maximizes my result, assuming that the opponent then chooses the move that minimizes my result – and so on, until the game is decided. Two players, alternating maximum and minimum, hence the name.
function minimax(board, player, depth) {
if (winnerOf(board) || movesFor(board).length === 0) {
return score(board, depth);
}
const values = movesFor(board).map(index =>
minimax(
applyMove(board, index, player),
player === COMPUTER ? HUMAN : COMPUTER,
depth + 1
));
return player === COMPUTER ? Math.max(...values) : Math.min(...values);
}
function bestMove(board) {
const moves = movesFor(board);
const values = moves.map(index =>
minimax(applyMove(board, index, COMPUTER), HUMAN, 1));
return moves[values.indexOf(Math.max(...values))];
}
The recursion has three building blocks, and all three are visible in the code:
- The base case: if someone has won or no field is free anymore,
scorereturns the value of the end state. - The step: for every free field,
applyMovecreates a successor board, which is evaluated with the player swapped and the depth increased by one. - The choice: if it is the computer’s turn, the maximum of the child values wins, otherwise the minimum.
bestMove is then just the top level of this search, written out: evaluate all of your own moves, return the index of the best one. A small game tree shows why the depth in the evaluation makes the difference between a correct and a smart opponent:
graph TD R["Board, O to move<br/>takes the maximum"] --> A["Move to field 2 blocks<br/>X to move, takes the minimum"] R --> B["Move to field 5<br/>O wins immediately: value +9"] A --> A1["X later forces the win<br/>value -6"] A --> A2["Draw<br/>value 0"] A -.-> AV["Minimum: -6"] B -.-> BV["Leaf: +9"]
Here, the computer faces the choice of blocking an opposing line or winning itself. Without the depth bonus, both wins would be worth the same, and the choice would depend on the order of evaluation. With 10 - depth, the immediate win is strictly better – the opponent doesn’t just play flawlessly, it plays purposefully.
For a sense of scale: from an empty board, there are around 255,000 possible games, and the tree shrinks drastically with every stone placed. A laptop evaluates that in milliseconds; optimization is computationally unnecessary. The repository still contains a variant with alpha-beta pruning, formulated non-recursively – that was curiosity following the Elm template, because for Othello with its 8×8 board, pruning is no longer a gimmick but a prerequisite. For this article, I deliberately stick with the recursive basic form: it is the version you can derive on a whiteboard, and simple beats elegant as long as the simple form is measurably enough.
React only renders state#
Only now does React come into play, and in a decidedly boring role. The entire game state is state.board, and the only place where this state changes is the click handler. The handler orchestrates two moves – the human’s, then the computer’s reply – and delegates everything of substance to the pure functions from above.
class Game extends React.Component {
constructor(props) {
super(props);
this.state = { board: Array(9).fill(null) };
this.handleClick = this.handleClick.bind(this);
}
handleClick(index) {
const afterHuman = applyMove(this.state.board, index, HUMAN);
const finished =
winnerOf(afterHuman) || movesFor(afterHuman).length === 0;
const nextBoard = finished
? afterHuman
: applyMove(afterHuman, bestMove(afterHuman), COMPUTER);
this.setState({ board: nextBoard });
}
render() {
return <Board board={this.state.board} onSquareClick={this.handleClick} />;
}
}
const Board = ({ board, onSquareClick }) => (
<div className="board">
{board.map((field, index) => (
<button
key={index}
disabled={field !== null || winnerOf(board) !== null}
onClick={() => onSquareClick(index)}
>
{field}
</button>
))}
</div>
);
Board is a stateless functional component: board in, nine buttons out. Game is a React 15 class with exactly one state field and exactly one handler. The setup around it is an ordinary create-react-app project – npm install, npm start, running on port 3000. In 2017, you no longer need more tooling than that for something like this, and that is a pleasant development.
The contrast to the official React tutorial is instructive. There, tic-tac-toe is the vehicle for explaining React: break down components, lift state up, pass props down, and at the end a time history. The opponent is a second human; the game logic is limited to checking for a winner. Here it is exactly the other way around: React is the vehicle, the algorithm is the center. Both perspectives are legitimate – but only the second forces you to draw the boundary between logic and presentation cleanly, because otherwise the logic immediately becomes unwieldy.
flowchart LR
subgraph core["Pure functions – no React import"]
score --> minimax
winnerOf --> minimax
movesFor --> minimax
applyMove --> minimax
minimax --> bestMove
end
subgraph ui["React 15"]
state["state.board"] --> render["render()"]
render --> onclick["onClick(index)"]
end
onclick -->|"applyMove + bestMove"| core
core -->|"new board"| setState["setState"]
setState --> stateThe arrows between the two boxes are the entire coupling: the handler calls functions and writes the result back into the state. No import runs in the opposite direction. You could replace the right box with a console application, with jQuery or, indeed, with Elm – the left box wouldn’t notice.
Tests without a browser#
This separation isn’t a matter of taste; it is measurable – most directly in the tests. The game logic runs in Node, without a DOM, without jsdom, without a mocked event system. Jest, which comes with create-react-app, runs something like this in milliseconds:
test('computer blocks an open line', () => {
const board = [
HUMAN, HUMAN, null,
COMPUTER, null, null,
null, null, null,
];
expect(bestMove(board)).toBe(2);
});
test('computer prefers the immediate win over the block', () => {
const board = [
HUMAN, HUMAN, null,
COMPUTER, COMPUTER, null,
null, null, null,
];
expect(bestMove(board)).toBe(5);
});
These aren’t unit tests in the fine-grained sense but game sense as a specification: the opponent must block an open line, and it must prefer its own win to the block. You can take such cases straight from games – every time the opponent behaves oddly while you try it out, the position becomes a test case. For me, it was exactly such a case at the beginning: without the depth component in score, the search kept postponing a certain win, because a win in four moves had the same value as one in two. The position from the second test above is the fossil of this bug.
Now the counter-check, and I have seen it in the wild often enough in reviews: the move logic sits in the click handler, the winner check in render, the computer’s move in a lifecycle hook such as componentDidUpdate. Functionally identical, but now the following applies:
- Every logic test needs a mounted component and simulated clicks – a function call turns into a browser ritual.
- The position from the bug case can’t be written down directly; it has to be played out through a sequence of clicks.
- Switching the UI library, or even just a larger restructuring of the component tree, drags the game logic along with it.
- The algorithm can no longer be read in one piece, because it is spread across handlers, render branches and lifecycle methods.
None of this is dramatic with three by three fields. But tic-tac-toe is only the lab animal here. Replace “game logic” with “price calculation”, “validation” or “planning rules”, and it is the same decision with the same consequences – except that the entangled version can no longer be untangled in an afternoon.
What I take away from it#
Hardly anyone will need minimax itself in everyday project work. What remains is the pattern underneath. The whole opponent is an evaluation function plus a search over immutable values – and because that is so, you can test it like a price formula and render it with whatever happens to be at hand. In this project, React has the role that suits it best in my view: take in state, turn it into a UI, report inputs back. Nothing more.
What I find remarkable is how well the parts fit together without being built for each other. Minimax demands immutable boards because otherwise the recursion would need bookkeeping. React rewards immutable state because otherwise comparisons would be expensive. An algorithm from the early days of game theory and a UI library from 2013 meet in the same discipline: no mutation, values instead of changes. That is no coincidence but a sign that this discipline is more fundamental than any single tool.
If you want to rebuild this: an array with nine fields, five pure functions, one class with one handler. One afternoon – and afterwards a precise sense of where the line between logic and presentation should run in your own, much larger applications. And a game you will never win again.
Further reading#
- Repository
react-tic-tac-toe(“Tic Tac Toe in React with Minimax-AI”): https://github.com/MikeBild/react-tic-tac-toe - Carsten König’s Othello in Elm, the source of inspiration: https://github.com/CarstenKoenig/ElmOthello
- The official React tutorial (tic-tac-toe, current version): https://react.dev/learn/tutorial-tic-tac-toe
- Minimax at a glance: https://en.wikipedia.org/wiki/Minimax
- Alpha-beta pruning: https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning
Revised and translated from German with the help of AI.