
Dots & Boxes AI: A 13-Year Side Quest
Back in 2013, as I was wrapping up my undergrad studies, I took part in a coding competition – Microsoft's Bubble Cup – with 2 university peers. One of the problems that we worked on was implementing an "AI" for the game Dots & Boxes, which was then pitted against other teams' AIs to grade the solution and assign points. We probably put in more time than we should have into working on that problem – much of it during the night – but it paid off, because our solution did very well compared to other teams', and helped us actually win that year, which was also quite poetic given that it was both my first win and the last time competing.
I found myself enjoying the algorithms for that game quite a bit, so ever since I've wanted to spend some more time on them as a fun side project – solidifying the algorithm and building out new ones, making the code into a generic library, building out a nice demo site, things like that. But, as things usually go, I never found enough time for it, until 13 years later, when actually coding quickly with AI and LLMs came into the picture and made it so much easier to do all of these things.
So, I present to you Dots & Boxes AI, a TypeScript package that you can use both as a collection of algorithms and a simple UI for playing the game.
Just so that I don't link to things randomly in the middle of the post: the demo is here, the package is on npm, and the code lives on GitHub.
The game (in 30 seconds)
Players take turns drawing lines between adjacent dots on a grid. Completing the fourth side of a box claims it and grants another turn. When all boxes are claimed, the most boxes wins. Simple rules, surprisingly deep strategy: the endgame revolves around chains (forced capture sequences where taking one box hands you the next), and the real skill is controlling who gets forced to open each chain. Sacrificing two boxes now to win ten later is not just legal, it's often correct. (Try it live in the demo.)
The starting point
Believe it or not, I still had the original university code – a React 15 / webpack / Flow contraption with the UI in Serbian. It worked, but only barely: game results were printed to console.log, there was a single test file, and the whole thing was deployed by hand to a corner of this very site. Step one was dragging all of that into the modern era: TypeScript, Vite, an immutable rules engine with zero dependencies, 100+ tests, and a demo that deploys itself to GitHub Pages. The original four algorithms came along for the ride — and then, because the whole point of a 13-year side quest is overkill, the roster grew to nine. Here they all are, weakest first:
The roster
Random
Uniformly random legal move, every turn. It never completes a box on purpose and never avoids handing you one, which makes it the perfect baseline: it went 0–16 in the round-robin, as anything calling itself an AI should ensure. Its only real job is in the test suite and as the fallback every other AI delegates to when nothing better applies.
Greedy
Takes a box whenever one is available, otherwise plays at random. That "otherwise" is the whole story: with no notion of safety, it routinely draws the third side of a box and serves the box to its opponent on the next move. Textbook greedy algorithm behavior — locally optimal, globally oblivious — good for 4–12 and a lesson in why tactics matter.
Minimax
The ported competition veteran. It works on its own box-side map of the board, groups lines by how full their neighboring boxes are, and walks the board to classify open and closed chains, preferring the longest ones. Murky positions get resolved by a depth-limited minimax search (5 ply) that scores multi-box captures at face value, with smart-greedy as the fallback. Why it loses to plain greedy on 3×3: every heuristic in it was tuned for big boards — longest-chain preferences and face-value scoring misfire in small tactical positions where a single tempo move decides everything. On bigger boards it genuinely shines, which is exactly the environment it was built for.
Smart Greedy
Greedy with one rule added: when nothing completes, play only safe lines — lines whose neighboring boxes each have at most one side drawn, so the opponent can't take on the reply. Only when every legal line hands over a box does it shrug and play randomly. It never looks ahead a single move, yet safe play alone is worth 8–8: most games at this level are lost by giving boxes away, not by deep tactics. No literature to cite — just the folk wisdom every decent casual player rediscovers.
Q-Learning
A linear model over three features of each candidate move: boxes completed now, takeable boxes handed to the opponent, and a bias term. The weights came from offline self-play — 200,000 training games in about 20 seconds — where each move nudged the weights toward the final score difference, classic Q-learning. At play time it's pure greed over learned values with random tie-breaking: zero search, instant moves. It ties smart-greedy because it effectively learned smart-greedy — "take boxes, don't hand them over" falls right out of the features. Anything needing actual lookahead is beyond it by construction. You can retrain it yourself with npm run train.
MCTS
Grows a game tree one node per iteration, 1,000 per move, selecting lines with the UCT formula (exploration constant √2) to balance lines that simulated well against lines it has barely tried. Each simulation plays out with the smart-greedy policy and the final score difference flows back up the tree; the most-visited move wins. Positions with 12 or fewer lines skip sampling entirely and get solved exactly. This is textbook Monte Carlo tree search — and the honest confession stands: with plain random playouts the evaluations are noise, because random play resolves chains arbitrarily. That failure matches the published literature on this game, which is some consolation.
Alpha-Beta
No game knowledge at all — just search, done right. Depth 6 over quiet moves with a 50,000-node budget, alpha-beta pruning, a transposition table keyed on board plus side to move, and completing moves tried first for early cutoffs. The neat trick is free tactical extension: box completions don't consume depth, so forced capture sequences resolve exactly — a quiet nod to quiescence search. Past the horizon, quiet positions score zero. 11–5 with zero Dots & Boxes knowledge says a lot about how far brute force carries you.
Chain Control
The theory nerd, and the one I'm proudest of. Positions with 12 or fewer lines get solved exactly (depth 64, million-node budget, five-second cap). Earlier, at a two-box chain end, it weighs taking both boxes against the textbook loony sacrifice — deliberately giving them away so the opponent must move first afterward — by running 50 smart-greedy playouts per option and trusting the average. Everything else goes through the same search alpha-beta uses. The sacrifice logic is straight out of endgame control theory (Berlekamp's The Dots and Boxes Game is the canonical text, and "loony" is his word), and the 10–0 ablation duels against its non-sacrificing twin say the theory earns its keep. 12–4, second place.
Iterative Deepening
The same alpha-beta search, run at depth 1, then 2, then 3, until its one second expires — a million nodes per iteration, deepest completed search wins, slow positions still get a move. Shallow searches are cheap, so almost nothing is wasted, and strength scales directly with the clock: classic iterative deepening. Boring? Maybe. 14–2, strongest thing in the repo? Also yes — apparently the oldest trick in the book still beats everything fancier here.
How do they stack up? I ran a round-robin on 3×3 (2 games per pairing, sides swapped):
| AI | W | L | ms/move |
|---|---|---|---|
| deepening | 14 | 2 | 319.4 |
| chain-control | 12 | 4 | 14.4 |
| alpha-beta | 11 | 5 | 14.2 |
| mcts | 10 | 6 | 22.3 |
| smart-greedy | 8 | 8 | 0.0 |
| q-learning | 8 | 8 | 0.0 |
| minimax | 5 | 11 | 0.0 |
| greedy | 4 | 12 | 0.0 |
| random | 0 | 16 | 0.0 |
The timing column tells its own story: Q-learning ties smart-greedy while thinking just as fast, and deepening pays hundreds of milliseconds per move for the top spot.
Yes, the ported competition minimax loses to plain greedy on small boards. It was tuned for bigger ones, where it genuinely shines – but I kept the table honest rather than cherry-picking a board size that flatters the old-timer.
Things I got wrong along the way
Two stories, because the postmortem is always the best part. First: while modernizing, I "found" a scoring bug where already-claimed boxes would supposedly be counted twice. I wrote it up confidently – then fuzzed the exact legacy logic over 210 games and proved myself wrong. The check I thought was buggy can only ever match freshly completed boxes. The tests I wrote pin the correct behavior instead. Trust, but fuzz.
Second: my first Q-learning attempt lost 1–19 to greedy. The features overlapped and confused credit assignment; simplifying to three clean signals (boxes completed, boxes handed over, bias) took it to 15–5 against the same opponent. Feature engineering: still all you need, apparently.
Using it
The whole thing is one function type:
type AI = (state: GameState, rng?: () => number) => Move | null
Install it and play a move in four lines:
npm i dots-and-boxes-ai
import { chainControlAI, createGame, playMove } from 'dots-and-boxes-ai'
let state = createGame(3, 3)
const move = chainControlAI(state)
if (move !== null) {
state = playMove(state, move)
}
States are immutable snapshots, so games are trivially replayable, serializable (the demo's share links are just a move log in the URL hash), and React-friendly. There's also a presentational Board component in dots-and-boxes-ai/board if you want the UI without rebuilding it, and a seeded RNG if you want deterministic games.
What's next
Realistically? This one's done – it sat on the shelf for 13 years, it deserves to rest. But if I get weak again: keyboard play is in, E2E tests run in CI, the demo could still use an online mode, and someone with more patience than me could try the neural-network approaches from the literature. The repo is there; PRs welcome.
So – wish me luck finding the next 13-year project. Something tells me I won't have to wait that long this time.