Part I · Terminology
The vocabulary of the game: chains, loops, control, the double cross, and the rest — each term with diagrams.
Dots and Boxes terminology
Plain definitions for the words that keep coming up in endgame discussion — what each thing looks like, how to spot it, and how it differs from the term next to it. Every term has a few small diagrams in the same style.
How to read the diagrams
- Line — a side that has been drawn.
- Blank space — a side not yet drawn.
- Green box — a box belonging to the component being shown.
- Orange line — the move being played in that example.
- Amber box — a box being given away / left behind.
- Dark green box with × — a box already taken.
Shapes — what is sitting on the board
Chain
ShapeA connected path of boxes, linked by undrawn shared sides, in which every box has exactly two sides drawn. Because the shared sides are missing, the boxes hang together: once one box in the chain can be taken, taking it hands you the next one, and so on to the end of the path.
- Chains are counted by boxes: a 2-chain, a 4-chain, and so on.
- A chain has two ends — that is what separates it from a loop.
- It can run straight, turn corners, or run vertically; the shape doesn't matter, the connections do.
Long chain
ShapeA chain long enough for control to matter — a chain of three boxes or more. Even the shortest long chain, a 3-chain, can be double-crossed: take 1, leave 2, and keep control. Longer chains are worth far more than the give-back, so whoever takes one can afford to give 2 back and still come out well ahead. Capturing the long chain usually decides the game.
- The working idea is longer than the 2-box give-back, so the double cross leaves the taker ahead — if only by a single box in a 3-chain.
- Short chains (1 or 2 boxes) are the opposite case: a 2-chain is exactly give-back size, so double-crossing it hands over the whole chain and takes nothing from it first — which is exactly where the take-vs-leave decision gets tight.
Loop
ShapeA chain that closes back on itself to form a ring. Every box has two sides drawn, the shared sides around the ring are undrawn, and — unlike a chain — a loop has no ends. Once one box in the loop can be taken, taking runs all the way around the ring.
- The smallest loop is the 4-loop: a solid 2×2 block of boxes.
- Bigger loops are rings around an empty middle — an 8-loop rings a single box, a 10-loop rings two, and so on.
- Loops behave like chains when taken, but the give-back inside a loop is 4 boxes, not 2 (see Give-back).
Closed chain
StateA chain that has not been opened yet: every box in it has exactly two sides drawn and no box has three, so nothing in it can be taken. It is sitting intact, waiting for someone to be the first to play inside it.
- “Closed” describes the state, “chain” describes the shape — so you can equally have a closed loop: a loop in the same untouched state.
- A closed chain is safe for now, but dangerous to touch: the first move inside it hands it to the opponent (see Open a chain).
Open chain
StateA chain that has been opened: at least one box in it now has three sides, so the player to move can take that box — and taking it creates a three-sided box next door, so the whole chain can be taken in one turn.
- An open chain is a closed chain after somebody's opening move; the shape hasn't changed, the state has.
- The three-sided box is the entry point. It is usually at an end of the chain, because the opening move is normally played at an end.
Offer
StateA component — a chain or a loop — that contains at least one box with three sides, so the player to move has boxes they can take from it. The three-sided box is only the way in: taking it ripens the next box, and the next, so the offer is really the whole component, not just the one ripe box.
- Offers are counted by component: there can be one offer out, or two or three offers out at once. A position with no offers out is quiet (see Quiet play).
- A closed chain or loop is not an offer. It becomes one only when a box in it gains a third side — when somebody opens it, or ripens a box in it.
- With several offers out, the player to move chooses which component to play on — and how each one is handled decides who has to open the next, which is where control is won and lost.
Decomposed position
State of the whole boardAn endgame position in which the board has split completely into separate chains and loops. Every remaining box belongs to one component, no undrawn side joins two components, and there are no safe moves left — any move a player makes must open a component and hand it to the opponent.
- Before decomposition there is usually still a shapeless area of boxes with fewer than two sides (sometimes called the “blob”) where harmless moves can be played. Decomposition is the point where that area is gone.
- Because the components no longer interact, the position can be valued component by component: work out what happens in each chain and loop, in the order they are opened, and add it up.
Quiet play
State of the whole boardPlay while there are no offers on the board: no box anywhere has three sides, so nobody can take anything. Every move is a safe move — a side added where it completes nothing and ripens nothing — and simply hands the turn over. Quiet play lasts until the safe moves run out and someone is forced to ripen a box or open a component.
- Quiet play is the opposite condition from a decomposed position: there, no safe moves remain at all. In quiet play, safe moves are all there is — nothing is takable yet.
- The moment a move gives some box its third side, quiet play is over: there is an offer out, and the endgame machinery — sweeps, give-backs, control — takes over.
- Quiet moves are not free of consequences: where they are played shapes which chains and loops eventually form, and how big they are.
Moves — things a player does
Open a chain
MoveTo make the first move inside a closed chain or loop. You draw a third side on one of its boxes — you take nothing on that move — and the chain becomes an open chain that your opponent can now sweep. Opening a component effectively donates it.
- The player who does this is the opener of that component (see Control).
- You normally only open a chain when you have no safe move anywhere else, or as part of a deliberate give-back.
- “Open” is also used for loops: you open the loop in exactly the same way.
Ripen
MoveTo add the third side to a box, making it “ripe” — ready to be taken — without completing it. A ripening move draws a box's third side, never its fourth, so the player who ripens takes no box on that move.
- Ripen vs. open: they are often the same physical move described at different levels. Ripen describes what happens to one box (it gains a third side); open describes what that does to the whole component (it becomes takable).
- Ripening is the mechanic inside the double cross: you ripen a box in the boxes you are giving back, so the opponent can take them and is then forced to open the next component.
Sweep / take-all
MoveTo take every box in an open component in a single turn. Completing a box earns another move, and each box you close gives the next box in the component its third side, so a sweep runs box after box until the chain or loop is exhausted — and you keep all of them.
- Sweeping is the opposite choice from the double cross, where you stop short and give the last boxes back.
- Take-all is the right choice when control is worth less than the boxes you would give back — for example when what remains after this component splits evenly anyway.
Give-back
Move / amountThe boxes a player deliberately leaves behind at the end of a sweep and hands to the opponent, instead of taking them. The amount is fixed by the shape: leave 2 in a chain, leave 4 in a loop. The opponent gets those boxes — but taking them uses up their turn's work, and they must then open the next component.
- Why 2 in a chain? A chain has an end, so a move can be played inside the last two boxes that ripens one without completing any — two is enough to hand over.
- Why 4 in a loop? A loop has no end. Four is the smallest remainder (a 2×2 block) that lets you play a side inside it without completing a box yourself.
- If the component is exactly give-back size — a 2-chain or a 4-loop — the give-back is the whole component: you take nothing from it first.
Double cross
TacticThe control tactic built out of a sweep plus a give-back: take most of a component, then refuse the last boxes — instead of completing them, play a move inside them that hands them to the opponent. The opponent collects the gift and is forced to open the next component, which you then take. You have “crossed” them: the boxes that looked like a gift cost them the next component.
- Sweep most of it — take the component box by box, but stop with 2 left (chain) or 4 left (loop).
- Play inside the remainder — draw a side inside one of the remaining boxes (ripening it) rather than the side that would complete it. Your turn ends with boxes still on the table.
- Opponent takes the gift, then opens — they collect the left-behind boxes and must make the first move inside the next component, handing it to you.
When it fails: the double cross buys control at the price of the give-back. If control of what remains is worth nothing — because the rest splits evenly whoever controls it — the price is paid for nothing, and plain take-all was better.
Chain double cross
MoveThe double cross as played in a chain — the specific move that makes the chain's give-back of 2. With exactly two boxes left in the chain, instead of taking them, play the end edge of the last box: the far end of the pair, away from the box you were about to take. That gives the last box its third side as well, so both remaining boxes stand ripe for the opponent — and your turn ends without taking either of them.
- The opponent takes both boxes — and then, which is the point of the move, must open the next component for you. You have traded 2 boxes for control.
- It is the chain counterpart of the double loony: same job — the give-back that keeps control — different shape. A chain has an end to play at; a loop doesn't.
- If the whole chain is only 2 boxes long, the chain double cross gives away the entire chain: there was nothing to take from it first. Whether that is worth doing depends entirely on what control buys next.
Double loony
MoveThe double cross as played in a loop — the move that makes the loop's give-back of 4. Play a side shared by two boxes of the loop, so that both boxes gain their third side at the same time. The move completes no box, so your turn simply ends, with two ripe boxes sitting in front of the opponent.
- The opponent takes the two ripe boxes — and taking them ripens the other two boxes of the remaining 2×2 block, so they take all four, then must open the next component. Four boxes buy control: exactly the loop's give-back.
- It is called double because one move ripens two boxes at once. Mechanically it is a loony move — it hands boxes to the opponent — played deliberately, and doubled.
- A loop has no end to play at, which is why its give-back needs this move while a chain can use its end edge instead (see Chain double cross). The same shared-side move also turns up in a short chain with a ripe box at each end: play the side shared by the two middle boxes, and both go ripe together.
Control
StrategyControl is the endgame advantage of being the player who will take the last — usually the largest — remaining component, because your opponent is the one forced to open it. Control is not a pile of boxes; it is about who has to open what. It is bought with the double cross: you give back 2 (or 4) boxes now so that the opening duty, and therefore the next big component, falls your way.
The controller
The player who holds control: they made the give-back, they will receive the next component when it is opened, and — if they keep control to the end — they take the final, biggest component. The controller's job is to keep the exchange going on those terms.
The opener
The player who is forced to open a component: they must make the first move inside a closed chain or loop, take nothing on that move, and hand the component to the other player. After taking any give-back boxes, the opener of one component typically becomes the opener of the next — that is what it means to have lost control.
- The roles swap component by component in one specific way: whoever takes the give-back becomes the next opener. That single link is the whole mechanism of control.
- Control has a value, and it varies: with a dominant component still to come (say a 15-loop against a 4-loop) control is worth a lot; with balanced components that split evenly either way, control can be worth zero — and then paying a give-back for it loses boxes.
Loony move
MoveA move that leaves a box with three sides for the opponent to take — a move that gives a box away. In ordinary play it is a blunder (hence the name), and if the three-sided box belongs to a chain or loop it is much worse: it offers the opponent the whole component.
- The very same shape of move is sometimes correct: opening a component and making a give-back are both, mechanically, loony moves. The difference is whether the sacrifice was forced or buys control worth more than it costs.
- So “loony” describes the move's immediate effect — a box handed over — not whether, in context, it was a mistake.
The four stages of a board
ProgressionFour mechanical tests sort every position into exactly one stage, and a game normally walks them in order: the safe moves run out, the last stragglers ripen into a decomposed position, and the components that block the Allcock formula get swept away. The four snapshots below are one real 5×3 board at four moments of a single playout, so the same boxes can be followed through all four stages.
- The tests, in order. Stage 1: a safe move exists. Stage 2: no safe move exists, but some unclaimed box has fewer than 2 sides. Stage 3: every unclaimed box has at least 2 sides, but some component is opened, short, or a singleton. Stage 4: every component is a fresh chain of 3 or more, or a loop of 4 or more.
- Two of the doors are one-way. Side counts never decrease, so safe moves never come back — stage 1 → 2 is permanent — and once a board is decomposed it stays decomposed — stage 2 → 3 is permanent. Stages 3 and 4 trade places freely: opening a fresh component drops 4 → 3, and sweeping the offending component restores 3 → 4, exactly as the snapshots do.
- Stages can be skipped. One move can end quiet play and complete decomposition at once (1 → 3), and a board can decompose straight into the Allcock domain (2 → 4) when every component happens to be fresh.
- Who plays exactly, where. Stages 1–2 are general-search territory: the heuristic's quiet opener works there, and its deepest mistakes live there too — test cases 13 and 14 sit at the end of stage 1, where the remaining safe moves must be counted exactly. In stage 3 the micro-game evaluator is exact but the Allcock formula and the heuristic's fixed control rules are at their weakest (case 20 is a stage-3 position). In stage 4, Allcock is exact and instant — it is Step 1 for Intermediate and Advanced.
The stage test, as pseudocode
function stageOf(board):
if existsSafeMove(board): # some edge touches only boxes with < 2 sides
return 1 # quiet
if any unclaimed box has < 2 sides:
return 2 # no quiet moves, not decomposed
if any component is opened, short, or a singleton:
return 3 # decomposed, not Allcock
return 4 # every component fresh and long
At a glance
One line per term, for quick reference mid-discussion.
- Chain
- A connected path of two-sided boxes; take one and the rest follow.
- Long chain
- A chain of 3 or more boxes — long enough that control over it is worth a give-back.
- Loop
- A chain closed into a ring, with no ends; smallest is the 2×2 4-loop.
- Closed chain
- A chain not yet opened — every box has exactly 2 sides, nothing takable.
- Open chain
- A chain that has been opened — a box has 3 sides, so the whole chain can be taken.
- Offer
- A chain or loop containing a three-sided box — the player to move can take from it, and the whole component is at stake.
- Decomposed position
- The board has split entirely into separate chains and loops; no safe moves remain.
- Quiet play
- Play with no offers out: no box has three sides, so every move is a safe move that takes and ripens nothing.
- Open a chain
- To play the first move inside a closed component, handing it to the opponent.
- Ripen
- To give a box its third side, ready to be taken, without completing it.
- Sweep / take-all
- To take every box in an open component in one turn, keeping them all.
- Give-back
- Boxes deliberately handed to the opponent at the end of a sweep: 2 from a chain, 4 from a loop.
- Double cross
- Take most of a component, then play inside the last 2 (or 4) boxes to give them away and keep control.
- Chain double cross
- The chain's give-back move: with two boxes left, play the far end edge so the opponent takes both and must open the next component.
- Double loony
- The loop's give-back move: play a side shared by two boxes so both go ripe at once; the opponent takes all four remaining boxes.
- Control
- The advantage of taking the last/biggest component because your opponent must open it. Controller receives; opener donates.
- Loony move
- A move that leaves a box three-sided for the opponent — a blunder, unless it is a deliberate opening or give-back.
Part II · The Heuristic
The baseline move-maker: local rules for captures, controller play, and the quiet opener — fast, understandable, and wrong in specific, measurable places.
The heuristic: strong local rules, no lookahead.
The heuristic is the engine's rule-based player. It does not search a game tree and it does not compute the exact value of a position. Instead, it classifies what the board is offering right now — a box to take, a component to control, or nothing yet — and applies a small set of strategies that experienced Dots and Boxes players recognise.
Two questions, asked in order
Every call to chooseFallbackMove(h, v) first counts how many sides every unclaimed box already has. That one count divides all positions into two modes:
The important point is what is not here. There is no minimax tree, no rollout, no learned score, and no comparison of the exact values of control and take-all. The strategy is encoded directly as rules. That makes the heuristic fast and understandable, but it also means a rule fires — or does not fire — for structural reasons, even when the surrounding position changes whether the strategy is actually profitable.
The dispatch, as pseudocode
function chooseFallbackMove(board):
threes = boxes with 3 sides
if threes is not empty: # an offered position
move = oneMoveCapture(board) # §3 — fires on any board
if move: return move
move = enclosedTripletSweep(board) # §3 — sweep a {3, 1, 1}
if move: return move
move = controllerMove(threes) # §4 — may decline
if move: return move
return greedyTake(threes) # §5
return openerMove() # §6 — nothing is offered
How the heuristic reads the board
Function names in the code: countSquares, buildRegions, isLoop, controllerMove, and openerMove.
First, take a complete one-move capture
Before the controller rules run, oneMoveCapture looks for either of these shapes — on any board, decomposed or not:
If several qualify, one is chosen at random. If none qualifies, enclosedTripletSweep checks for an enclosed triplet — a region of three boxes with exactly two 3-sided ends and one 2-sided middle, {3, 1, 1} — and takes one of its ends, again chosen at random among the qualifying ends. An unripe singleton, {single: 2}, deliberately does not qualify for the capture: it cannot be taken yet, and playing inside it hands the turn over — it is a tempo and parity object, not a free capture. Case 18 in Part III is built around exactly that distinction.
The capture checks, as pseudocode
function oneMoveCapture(board):
candidates = closing edges of ready singletons {single: 1}
+ shared edges of enclosed dominoes {2, 1, 1}
if candidates is empty: return null
return a random candidate
# an unripe singleton {single: 2} is deliberately NOT a candidate
function enclosedTripletSweep(board):
# a region of length 3 with two 3-sided ends and one 2-sided middle
candidates = the sole untaken edge of each 3-sided end whose
far box is the 2-sided middle
if candidates is empty: return null
return a random candidate
Both rules are theorems, not heuristics: taking a ready singleton or enclosed domino first is always optimal on any board, and sweeping an enclosed triplet first is always optimal too (sweep-first for n ≤ 3). The proof is that the closing edge touches no unclaimed box with 2 or more sides, only adds a side to a loose neighbour, and never creates a new offered box. The triplet rule was added after case 23 showed the old capture-only version taking a trap box one time in three.
The controller: take most, hand back a little
The controller handles offered regions — one, or several. With exactly one offered region and at least one other significant region of size 3 or more still waiting, it applies the control rules below. When several regions are offered at once, it first sweeps all but one — taking an offered box keeps the turn, so sweeping is free — and leaves the last one to be controlled, preferring to leave a chain (whose give-back is 2) over a loop (whose give-back is 4). Its strategic aim is the familiar control strategy from Part I:
The actual rules
| Offered shape | Heuristic action | Why |
|---|---|---|
| Multiple offered regions | Sweep all but one: take a box from a region other than the designated last one, leaving one region (a chain if any is offered, else a loop) to be controlled by the rules below. | Taking an offered box keeps the turn, so sweeping is free; handing the turn over while offers remain lets the opponent pocket them. |
| Chain with one opening, size > 2 | Close the 3-sided box. Repeated calls continue down the chain. | Keep sweeping while the component is still long enough to support a later give-back. |
| Chain reduced to 2 boxes | Chain double cross: draw an end edge of the remaining 2-sided box, making both boxes 3-sided, and pass them to the opponent. | This is the chain's give-back of 2. |
| Loop larger than 4 | Take one 3-sided box, preferring a move that closes one box rather than two. Repeated calls reduce the loop. | Move toward the loop's control threshold without collapsing the whole ring at once. |
| Loop of exactly 4 | Double loony: draw an edge shared by two 2-sided boxes, ripening both without taking either. | This is the loop's give-back of 4: the opponent must take the ring and open what follows. |
| Short opened shape with two or more openings, size ≤ 4 | Try a double loony; if that shape is unavailable, try a chain double cross. | Once a short component has been opened in more than one place, ripening the residue is preferred to a piecemeal take. |
| Opened shape larger than 4 with two or more openings | Take one box first. | Reduce it until one of the short-shape control rules can apply. |
| Single offered box | Decline the controller and take it greedily. | There is no residue to control. |
The safe-move guard
A give-back only works if the opponent, after taking the gifted boxes, is forced to open another component. If a safe move exists anywhere else — a line that creates no 3-sided box — the opponent could pocket the gift, play safe, and keep the initiative. So the controller checks existsSafeMove() before a double cross or double loony. If a safe move exists, it declines the giveaway and the position falls through to greedy taking.
The controller, as pseudocode
function controllerMove(offered):
if more than one region is offered:
last = first chain, else first loop # give-back 2 beats 4
return take one box from a region other than last
if offered is not exactly one region: return null
if no other region of size 3 or more remains: return null
canGive = not existsSafeMove() # a safe move lets the opponent pocket the gift
if offered is a loop larger than 4:
return take one 3-sided box, preferring a single-box close
if offered is a loop of exactly 4:
return doubleLoony() if canGive else null
if offered is a chain:
if 2 boxes remain: return chainDoubleCross() if canGive else null
return close the 3-sided box and keep sweeping
if offered is a short shape with 2+ openings, size at most 4:
return doubleLoony() or chainDoubleCross() if canGive else null
if offered is a larger shape with 2+ openings:
return take one box first
return null # a single offered box: greedy takes it instead
When the controller declines: greedy taking
The controller returns no move in several ordinary situations: no other significant component remains, a give-back is blocked by the safe-move guard, or the offered shape does not match a control rule. The heuristic then uses greedyTake:
Greedy taking, as pseudocode
function greedyTake(threes):
edges = the last undrawn edge of every 3-sided box
return a uniformly random edge from edges
Randomness is part of the design throughout the heuristic. When its rules identify several moves as equivalent — equivalent captures, safe moves, takes, or openings — it generally picks uniformly among them rather than pretending it can rank them exactly.
The opener: delay the gift, then make it small
If no box has 3 sides, nobody can take anything yet. The opener's first goal is simply not to change that:
The opener, as pseudocode
function openerMove():
safe = all safe moves # an edge whose neighbours both have < 2 sides
if safe is not empty: return a random safe move
area = smallest connected area of 2-sided boxes
chains = pendant chains in area, after stripping junction boxes
if chains is not empty:
chain = a smallest chain
return a random playable edge of chain # an end edge or an interior shared edge
return a random undrawn edge of a random box in area # e.g. a pure loop
What the rules cannot price
Two test cases make the limits concrete
| Case | What happens | Lesson |
|---|---|---|
| 19 | Beginner opens the 3-chain and misses the optimal first move. Intermediate and Advanced open the ring through Allcock and pass. | An opener failure: smallest area is not cheapest opening. |
| 20 | All levels close the opened chain's end box — the correct first move. In full play, Beginner and Intermediate sweep two boxes and double-cross the last two, finishing the tail at 0 instead of +4. Advanced takes all and passes. | A controller failure, deferred until the give-back: the fixed double cross donates 2 boxes when the remaining position gives the opponent no opening burden worth buying. |
The current first-move record over cases 1–27 (26 scored — case 13's E=20 position aborts the exact solver) is Beginner 14/26, Intermediate 15/26, Advanced 26/26, counting only cases where every sampled run was optimal; Beginner is partial on cases 14 and 26, Intermediate partial on case 26. Case 20 is deliberately not a first-move separator: its separation appears only when the heuristic reaches the double-cross decision later in the same component.
Is "sweep, then double-cross" always optimal on a decomposed board outside the Allcock domain?
No — and it fails in both directions. The priced rule is the one Allcock's recursion uses in Part III §3–§4: giving back 2 (control) is right exactly when V(rest) < −2, where V(rest) is the value of the remaining components to the player who moves after the give-back. "Sweep, then double-cross" hard-codes one answer to a comparison that varies with the companions. Three measured counterexamples, all priced by the production component solver:
Outside the Allcock domain there is no safe fixed rule — the position is still exactly solvable, but only by the micro-game evaluator pricing the actual components, which is what the decomposition cutoff in Part V does. "Sweep, then double-cross" is the heuristic's fixed-control error in a shorter sentence: sometimes it happens to be the priced answer, and sometimes it costs 4 to 10 points.
Is every step always optimal?
Each row below is one step of chooseFallbackMove, in the order the code tries them. "Always optimal" means the step's move is worth V — the exact-solver value of the position — in every position where the step fires. A No means at least one such position exists, and the proving test case is named: play it in the game with AI (beginner) and watch the heuristic lose exactly the amount the solver says it should win. Two rows are steps the code can never reach at all, marked never runs. The Yes rows rest on a theorem or a forcing argument, each checked against the exact solver on the positions where the step can fire. The last column shows the step's pseudocode — the exact rule the code applies when the step fires.
| Step | Always optimal? | Proving case / evidence | Pseudocode |
|---|---|---|---|
| One-move capture — take a ready singleton {single: 1} or an enclosed domino {2, 1, 1} | Yes | Theorem: the closing edge touches no unclaimed box with 2+ sides, only adds a side to a loose neighbour, and never creates a new offered box. Checked on 599 junction-singleton takes, 0 suboptimal. | candidates = closes({single: 1}) + shared({2, 1, 1}) return random candidate |
| Enclosed triplet sweep — take one end of a {3, 1, 1} | Yes | Theorem: sweep-first is always optimal for n ≤ 3 (ready singleton, enclosed domino, enclosed triplet). | ends = 3-sided ends of {3, 1, 1} return random end's sole edge |
| Controller, multiple offered regions — sweep all but one | Yes | Theorem: taking an offered box keeps the turn, so sweeping the other regions is free; controlling the first region is worse than controlling the last by twice the remaining offered boxes. Case 27: the new controller sweeps the loop and controls the 2-chain, 100/100 optimal; old greedy took the 2-chain first 36/100. The final control call on the last region is still the unpriced fixed double-cross — see the chain1 n=2 row. | last = first chain, else first loop return takeOne(first other region) |
| Controller, loop n > 4 — take one box | Yes | Forcing argument: with one offered region and no safe move, any move outside the region hands the opponent the offered component plus the turn, and any non-take inside it offers boxes immediately. No failure in 3,555,264 searched positions. | take one 3-sided box, prefer a single-box close |
| Controller, loop n ≤ 4 — ripen (double loony) | No | Case 24. Offered 4-loop + 4-chain + lone box, V = +7. The heuristic ripens with v,1,1 (−7); taking an offered loop box is +7. A 14-box gap, the largest of any case. | doubleLoony(): edge shared by two 2-sided boxes in R |
| Controller, chain with 1 opening, n > 2 — take the offered box | Yes | Forcing argument, same as the loop take: taking an end box is the only move that loses nothing, and the two ends are equivalent. No failure in 3,555,264 searched positions. | close the 3-sided box; repeat on the next call |
| Controller, chain with 1 opening, n = 2 — double-cross | No | Cases 10, 11, 18. The double cross of a 2-chain donates both boxes: case 18 is −5 against an optimal take of +5, a 10-box swing, and the unripe singleton there is a parity token the rule cannot price. | chainDoubleCross(): end edge of the 2-sided box |
| Controller, chain with 2+ openings, n > 4 — take one box | Never runs | Dead code. A region with 2+ openings never leaks — its end boxes are 3-sided with their sole untaken edge internal, and middle boxes have both untaken edges internal — so isLoop is always true there, and the chain branch can never execute. | takeOne() — never reached |
| Controller, chain with 2+ openings, n ≤ 4 — double loony or chain double cross | Never runs | Dead code, same proof: every 2+-opening region is classified as a loop, so the chain branches for 2+ openings are unreachable. Zero occurrences in 3,555,264 searched positions and 1,834 decomposed layouts. | doubleLoony() or chainDoubleCross() — never reached |
| Controller declines — no other region of size ≥ 3, so greedy takes | No | Case 16. The controller bails and greedy takes a box worth −3 while declining it is +3 — a 6-box gap, with the take's residue (two boxes sharing their last edge) doing the damage. | if no other region ≥ 3: return null → greedyTake |
| Safe-move guard — refuse the give-back while a safe move exists | No | Cases 21, 22. The controller declines because safe moves exist, and greedy sweeps (−2) while ripening is +2. The safe moves merge into the fresh chain, so the rest stays one long chain and the priced control rule still applies. | canGive = !existsSafeMove() if !canGive: return null |
| Greedy take — a random 3-sided box | No | Cases 16, 21, 22, 23. Greedy treats every single-box take as equivalent and they are not: case 23's trap take is −2 against +4 for a free box, and cases 21/22 sweep where ripening wins. | edges = last edge of every 3-sided box; return random |
| Opener: safe move — a random safe edge | No | Cases 13, 14. Safe moves are not equivalent either: case 14 has 3 optimal safe moves among 18, and the heuristic hits one only about 1 time in 10. | safe = edges whose neighbours both have < 2 sides; return random safe move |
| Opener: smallest area / smallest pendant chain, random edge | No | Cases 19, 25, 26. Case 19 and case 25 pick the wrong area (a 3-chain over a 4-loop; a lone box over a 2-box area). Case 26 picks the right chain but the wrong edge: the interior shared edge is +5, the end edges −5, and the heuristic plays an end edge about two times in three. | area = smallest 2-sided area chain = smallest pendant chain return random playable edge |
The pattern is sharp: the first two steps are theorems, the two take-one steps are forced, and everything after them is structural guesswork that never prices V(rest) — the value of what remains after the give-back. That is why the same step can be right on one board and wrong by 4 to 14 boxes on another, and why the exact methods in Parts III and V exist: they price the comparison the heuristic's fixed rules skip.
One heuristic, three different AIs
The three playable levels are not three unrelated engines. They are three prefixes of the same cascade in AIEngine.move. Every level that reaches Step 3 uses the heuristic described on this page.
| Cascade step | Beginner | Intermediate | Advanced |
|---|---|---|---|
| Step 1 — Allcock Exact formula on a fully decomposed board with every component in the Allcock domain. | Skipped | Used | Used |
| Step 2 — Minimax Deterministic alpha-beta search with a decomposition cutoff; attempted only when the GateModel screen does not predict a hopeless solve, under a flat 5-second budget, with salvage and the heuristic move as its floor. | Skipped | Skipped | Used |
| Step 3 — Heuristic One-move captures, controller or greedy play when offered, and safe/smallest-area opener play when quiet. | Used | Used | Used as fallback |
Measured separation
| Comparison | Result | Interpretation |
|---|---|---|
| Beginner vs Intermediate — 304 pooled games | Intermediate 158 · Beginner 140 · ties 6 | Allcock adds a small, real edge, concentrated where its domain actually occurs. |
| Intermediate vs Advanced — 76 games | Advanced 68 · Intermediate 6 · ties 2 | Minimax is the large discontinuity: it rescues positions where fixed heuristic rules price the board incorrectly. |
| 27-case first-move suite (26 scored) | Beginner 14 · Intermediate 15 · Advanced 26 | Case 19 separates Beginner from Intermediate; cases 21–26 separate both from Advanced. |
Which part describes which level?
| Part of this guide | Beginner | Intermediate | Advanced | Role |
|---|---|---|---|---|
| Part I — Terminology | Language | Language | Language | Defines chains, loops, offers, control, the double cross, quiet play, and the other ideas every level's rules use. It is not itself a move generator. |
| Part II — The Heuristic | Whole engine | Step 3 | Step 3 + minimax floor | The rule-based player on this page: the whole of Beginner, the fallback for the other levels, and the baseline Advanced's search must beat or salvage against. |
| Part III — The Allcock Algorithm | — | Step 1 | Step 1 | Exact play for fresh, long, fully decomposed positions. This is the only exact step Intermediate has. |
| Part IV — MCTS Tutorial and Reference | — | — | — | No current level uses MCTS. It is the tutorial and research record for Monte Carlo Tree Search. Advanced's Step 2 is the deterministic minimax of Part V — not random rollouts or UCT selection. |
| Part V — Minimax | — | — | Step 2 | Advanced's general exact search: negamax with alpha-beta pruning, a decomposition cutoff, the GateModel screen, and salvage under a 5-second budget. |
Implementation map: Player.js selects the level; AIEngine.js runs the cascade; ControlValue.js supplies Allcock and the decomposed evaluator; SolverCutoff.js supplies Advanced's minimax; AIEngineHeuristic.js supplies the heuristic.
Part III · The Allcock Algorithm
The first exact step up: a closed-form recursion that prices fresh, fully decomposed endgames exactly, repairing the heuristic's opener and control mistakes inside its domain — and saying nothing outside it.
The Allcock algorithm: exact play after geometry stops mattering.
When a Dots and Boxes position has fully decomposed into long chains and loops, you no longer need to search lines on a board. A multiset of numbers — “one 7-chain and one 5-loop” — is the whole position, and a two-line recursion prices it exactly. This is how your engine does it.
Throw the board away
Midgame, Dots and Boxes is geometry: which line, which box, which region touches which. Late in the game that stops being true. Once every unclaimed box already has at least two sides, the unclaimed boxes link up — through their shared untaken edges — into components that are each just a path (a chain) or a cycle (a loop). Inside a component, every box looks like every other box. There is no tactics left inside it, only arithmetic:
The idea is named for the control strategy it formalises — the classic endgame technique, associated with the analysis of Joseph Allcock and the wider Dots and Boxes literature, where the player who sweeps a long chain or loop deliberately gives a few boxes back to stay in control of who opens what remains. Your engine turns that folk strategy into a proved recursion with a precise domain.
When it applies — the domain test
allcockF is only valid when both tests pass. If either fails, the position falls through to something more general (§8). There is no partial credit and no approximation at the boundary.
Test 1 — Fully decomposed
Every box on the board has ≥ 2 sides (claimed boxes have 4). No box has 0 or 1 sides. In code: isDecomposed(sides). Only then does the board split cleanly into chains and loops with nothing left over.
Test 2 — Every component is fresh and long
Implementation: allcockInDomain(state) checks exactly this — every component satisfies (ring && ring ≥ 4) || (n ≥ 3 && a == 2 && b == 2). allcockMove additionally requires the board itself to be decomposed before it even extracts components.
The domain test, as pseudocode
function inDomain(state): # state = multiset of micro components
for each component c in state:
if c is a loop: require c.n >= 4
elif c is a chain: require c.n >= 3 and c.a == 2 and c.b == 2
else: return false # a singleton, or anything else, is out
return true
Control vs take-all: the sweeper decides
Play in this domain has a fixed script with exactly two decision-makers:
g = 2 for a chain g = 4 for a loop
Why g differs: a loop needs a bigger hand-back to keep control — giving back only 2 from a ring doesn't preserve the parity the sweeper needs, so the control play in a loop concedes 4. A chain's control play concedes 2. Those two numbers, 2 and 4, are the entire “strategy” content of the algorithm; the recursion handles the rest.
F: the value of a multiset
Define F(S) = the eventual (opener − sweeper) net box differential over the unclaimed boxes in multiset S, under optimal play, where “opener” means the player about to move. Banked boxes are the caller's business; F only prices what's left.
For a non-empty S, try opening each component c in S, with size s and give-back g (2 for a chain, 4 for a loop). Let rest = S without c. The sweeper's two replies are worth, from the opener's perspective:
Inner min: the sweeper chooses. Outer max: the opener chooses which component to expose to that choice. That's the whole algorithm — a maximin over components, recursing on strictly smaller multisets until the base case.
The recursion, as pseudocode
function allcockF(S): # S = multiset of components; returns F(S)
if S is empty: return 0
if memo has key(S): return memo[key(S)]
best = -infinity
for each distinct component c in S:
rest = S without c
control = 2*g(c) - size(c) + allcockF(rest)
takeAll = -size(c) - allcockF(rest)
best = max(best, min(control, takeAll)) # sweeper picks the min, opener the max
memo[key(S)] = best
return best
Implementation notes from your code
Memoised on the multiset. allcockF caches by a sorted key like "C7 L5" (C = chain, L = loop), so each distinct multiset is priced once no matter how many move orders reach it; the memo clears past 200,000 entries. Duplicate components are tried once per node (a seen set) — opening either of two identical 5-chains is the same decision. Termination is trivial: every recursion removes one component, so depth is at most the component count — nothing like the depth of a line-by-line search.
One 7-chain and one 5-loop: F = −4
Position: S = { chain 7, loop 5 }. Twelve boxes remain. You are the opener. Which do you open? Price both options, bottom-up. First the two one-component values you'll need — both are the lone-component case from §4:
Control: 2·2 − 7 + (−5) = −8 — the sweeper keeps 5, hands you 2, and you must open the loop, which is worth −5 to whoever opens it.
Take-all: −7 − (−5) = −2 — the sweeper takes all 7, then opens the loop and suffers its −5 himself, which is +5 for you, netting −2.
Sweeper picks the min: −8 (control). Opening the chain is worth −8 to you.
Control: 2·4 − 5 + (−7) = −4 — the sweeper keeps just 1, hands you 4, and you open the chain next.
Take-all: −5 − (−7) = +2 — the sweeper takes all 5, then must open the 7-chain, worth −7 to him.
Sweeper picks the min: −4 (control). Opening the loop is worth −4 to you.
Every number above is the production recursion evaluated by hand — you can reproduce it, and vary it, in the calculator below.
Try it: the F calculator
Add chains (size 3–12) and loops (size 4–12) — the in-domain ranges — and watch the recursion price the position and name the optimal opening. This runs the same allcockF logic as ControlValue.js, memo and all.
Reading the output: for each candidate opening, control and take-all are the sweeper's two priced replies; the sweeper takes the smaller, and F is the largest of those minima. Negative F means the position favours the sweeper — normal for the player forced to open.
allcockMove: which line do you actually play?
allcockF prices a position but doesn't name a board move. allcockMove(b, hBits, vBits, sides) in ControlValue.js bridges that gap, in four steps:
allcockMove, as pseudocode
function allcockMove(board):
if not isDecomposed(board): return null
state = extractComponents(board) in micro form
if not inDomain(state): return null
best = the component c maximising
min(2*g(c) - size(c) + F(rest), -size(c) - F(rest))
return the lowest-id untaken line belonging to best
Allcock vs minimax vs the micro-game
Your engine contains three exact methods. They don't compete — they nest, each handling the positions the one above it finds expensive.
| Minimax (SolverCutoff) | Micro-game search | Allcock recursion | |
|---|---|---|---|
| State | The actual board: lines taken, turn, each box's side count | A multiset of micro components: {ring: n}, {n, a, b}, {single: u} | A multiset of sizes only: {chain 7, loop 5} |
| Branches over | Individual legal lines, captures keep the turn; alpha-beta + transposition table | Single-edge draws inside components (splits, ripens, closes); alpha-beta + bound-typed TT | Which component to open — one branch per distinct component |
| Applies when | Any position (if the gate admits it and the clock allows) | Any fully decomposed position | Fully decomposed and every component fresh & long (§2) |
| Returns | An actual line to play, with an exact root value if it finishes | The exact value of the decomposed tail | The exact value F — and via allcockMove, the component to open + a canonical line |
| Cost | Exponential in open lines; production runs are gated and capped at 5 s | Small state space, but still a search — worst recorded single call ~0.2 s after the PR #80 prunings | Memoised recursion over subsets of the component list; effectively instant |
How they nest in practice
So Allcock is simultaneously a standalone move-picker (for Intermediate and Advanced) and a fast path buried inside Advanced's minimax. Same recursion, two call sites.
Where Allcock sits: the three-step cascade
Every move in AIEngine.move is decided by exactly one step of a cascade, checked in order. Allcock is Step 1 — tried before any search, because when it applies it is both exact and free.
| Level | Step 1 · Allcock | Step 2 · Minimax | Step 3 · Heuristic | Character |
|---|---|---|---|---|
| Beginner | — | — | ✓ | Pure heuristic. No exact play anywhere. |
| Intermediate | ✓ | — | ✓ | Allcock is its only exact play — the old beginner, renamed in the 2026-11-07 three-level split (PR #91). |
| Advanced | ✓ | ✓ | ✓ | The full cascade. |
Validation & speed
A closed form you can't check is just a guess with good notation. This one was checked against the search evaluator it replaces, on the day it landed (2026-11-06):
That last point is the practical payoff: inside minimax, decomposed nodes that used to cost a micro-game search now cost a memo lookup, and at the top level, in-domain endgames are decided before the gate or the clock are even consulted.
Test cases by AI level
A cell is Pass when that level plays the optimal move on that case, Miss otherwise; a partial result (the optimal move in only some sampled runs) is marked Miss, as Case 14 is. Results are from the first-move suite, 10 runs per level against the exact solver, re-run 2026-11-23 after cases 21–27 were added (PRs #100, #101) — except Case 13, whose E=20 position aborts the exact solver, so its row keeps the verified three-level profile from 2026-11-07 (PR #91). An earlier version of this table used that profile for cases 1–18 too, but its optimal-move list was too narrow: it marked Cases 1, 2, 3, 6, and 9 as misses for Beginner and Intermediate when the level had in fact played a different optimal move. The rows below are the corrected, solver-valued results. Case 19 is a decomposed position designed to separate Beginner from Intermediate, shipped 2026-11-10 (PR #92) and worked in full in §12. Case 20, also shipped 2026-11-10 (PR #93), is a 6×4 decomposed position whose only out-of-domain component is a pure opened chain — see the note below the table. Cases 21–26 are non-decomposed separators for the heuristic's controller, gate, and opener steps. Case 27 is a decomposed multi-offer position (4-loop + {2,1,2} 2-chain + fresh 3-chain, value +5): the controller sweeps all but one offered region, and all three levels pass.
| Test case | Beginner | Intermediate | Advanced |
|---|---|---|---|
| Case 1 | Pass | Pass | Pass |
| Case 2 | Pass | Pass | Pass |
| Case 3 | Pass | Pass | Pass |
| Case 4 | Pass | Pass | Pass |
| Case 5 | Pass | Pass | Pass |
| Case 6 | Pass | Pass | Pass |
| Case 7 | Pass | Pass | Pass |
| Case 8 | Pass | Pass | Pass |
| Case 9 | Pass | Pass | Pass |
| Case 10 | Miss | Miss | Pass |
| Case 11 | Miss | Miss | Pass |
| Case 12 | Miss | Miss | Pass |
| Case 13 | Miss | Miss | Pass |
| Case 14 | Miss | Miss | Pass |
| Case 15 | Pass | Pass | Pass |
| Case 16 | Miss | Miss | Pass |
| Case 17 | Pass | Pass | Pass |
| Case 18 | Miss | Miss | Pass |
| Case 19 — the separator (decomposed) | Miss | Pass | Pass |
| Case 20 — opened 4-chain {4, 1, 2} + fresh 4-chain {4, 2, 2} + ring 4 (6×4, decomposed · value +4 · unique optimal v,0,3) | Pass | Pass | Pass |
| Case 21 — ripen beats sweep, safe moves (4×3 · value +2 · unique optimal v,0,2) | Miss | Miss | Pass |
| Case 22 — ripen beats sweep, loose pair (4×3 · value +2 · unique optimal v,0,2) | Miss | Miss | Pass |
| Case 23 — free box before chain end (4×3 · value +4 · optimal h,2,1, v,0,3) | Pass | Pass | Pass |
| Case 24 — loop ripen loses (3×3 · value +7 · optimal h,0,2, h,1,2) | Miss | Miss | Pass |
| Case 25 — opener picks wrong area (3×3 · value +3 · optimal h,1,2, h,2,2, v,1,2, v,2,2) | Miss | Miss | Pass |
| Case 26 — opener picks wrong chain edge (3×3 · value +5 · unique optimal h,1,1) | Miss | Miss | Pass |
| Case 27 — multi-offer sweep (3×3 · value +5 · optimal h,2,2, v,1,1) | Pass | Pass | Pass |
| Total | 14 / 27 | 15 / 27 | 27 / 27 |
Case 19: the decomposed separator
Cases 1–18 can't tell Beginner from Intermediate, because none of them is in the Allcock domain when the move is chosen (§11). So this case was designed backwards from the requirement: start from a position that is already fully decomposed and in-domain, so Intermediate's Step 1 fires — and Beginner, which has no Step 1, is left with its heuristic opener. Then make the two openers disagree.
The position
A 6×4 position with 12 boxes still unclaimed and the player to move as opener. Every unclaimed box already has ≥ 2 sides, and the board splits into exactly three components:
Domain check (§2): fully decomposed ✓ · ring of 4 ≥ 4 ✓ · both chains fresh {n, 2, 2} with n ≥ 3 ✓. So allcockInDomain is true and allcockMove decides the move for Intermediate (and for Advanced, whose cascade tries Allcock first). Beginner never runs that check at all.
Pricing the three openings
You'll need F({chain 3, chain 5}) = −4, F({loop 4, chain 5}) = −1, and F({loop 4, chain 3}) = −1 — each a two-component case of the same recursion. Then:
Control: 2·4 − 4 + (−4) = 0 — the sweeper keeps 0 boxes, hands all 4 back, and you open the chains.
Take-all: −4 − (−4) = 0 — the sweeper takes all 4, then opens the chains and suffers their −4 himself.
Both replies price at 0. The sweeper is indifferent — which means the opener can't be hurt. Value: 0.
Control: 2·2 − 3 + (−1) = 0. Take-all: −3 − (−1) = −2.
Sweeper picks the min: −2 (take-all). Opening the smallest chain is worth −2 to you.
Control: 2·2 − 5 + (−1) = −2. Take-all: −5 − (−1) = −4.
Sweeper picks the min: −4 (take-all). Opening the big chain is the worst move on the board.
What each level plays
Reproduce every number above in the §6 calculator — the “Load Case 19” button there sets up exactly this multiset. Shipped as part of the test suite 2026-11-10 (PR #92); with Cases 21–27 added (§11), suite totals are now Beginner 14/27, Intermediate 15/27, Advanced 27/27. One case proves the mechanism separates the levels; how much that mechanism is worth across whole games remains the league's question (§11).
Keep this open while you work
Domain checklist
- Fully decomposed: every box has ≥ 2 sides.
- Every loop is a ring of ≥ 4.
- Every chain is fresh {n, 2, 2} with n ≥ 3.
- Anything else — singleton, short path, opened end — goes to the micro-game search, not the formula.
Key functions
allcockF(comps) — memoised value recursion
allcockInDomain(state) — the domain test
allcockMove(board…) — component pick + canonical line, or null
microGameValue(state) — dispatches: Allcock if in-domain, else alpha-beta
controlValue(board…) — value + components for any decomposed position
Glossary
Decomposed — every unclaimed box has ≥ 2 sides; the board is only chains and loops. Chain — a path component. Loop / ring — a cycle component. Fresh — unopened: both chain ends still have 2 untaken edges. Opener — the player forced to open a component (the player to move, at each recursion level). Sweeper — the player who takes the opened component and chooses control vs take-all. Control — take size − g, give back g, opponent opens the rest. g — the give-back: 2 for chains, 4 for loops. F(S) — (opener − sweeper) net differential over the unclaimed boxes in S, under optimal play.
The one-sentence version
When nothing is left but long, fresh chains and loops, forget the board: the opener picks the component whose worst sweeper reply — control at 2g − s + F(rest), take-all at −s − F(rest) — hurts least, and that maximin, memoised over multisets, is the exact value of the endgame.
Exact here — silent everywhere else
Inside its domain, Allcock has no suboptimal move to apologise for. The recursion is exact: on a fully decomposed board of fresh, long chains and loops, the move it returns is the optimal move, not an approximation of one. If this part has a weakness, it is not accuracy. It is coverage.
Where suboptimal play survives Allcock
What the next method tries to add
MCTS (Part IV) gives up Allcock's exactness in exchange for generality: it can look ahead from any position — not decomposed, out of domain, parity tokens and all — by sampling continuations instead of refusing to answer. On this project's E=20 benchmark, sampled lookahead did beat the bare heuristic (79.1% optimal picks for the epsilon control vs 65.1%). But the trade is real: inside the Allcock domain, MCTS can at best tie a formula that is already exact, and outside it, its grades are estimates whose biases Part IV examines in detail. Broader is not the same as stronger — which is why the guide's final method, minimax (Part V), keeps MCTS's generality and removes the sampling.
The fixed-rule version of this question — on a decomposed board outside the domain, is sweep-then-double-cross always optimal? — is answered in Part II §7: no, in either direction, with three priced counterexamples (case 20, an offered 6-chain with a fresh 4-chain, and case 18).
Part IV · MCTS Tutorial and Reference
General lookahead by sampling: UCT and rollouts can search any position, but the grades are statistical and rollout-biased, so suboptimal moves survive even as the budget grows.
Monte Carlo Tree Search, without the hand-waving.
How MCTS actually decides — selection, UCT, expansion, evaluation, epsilon, and backpropagation — explained through the Dots and Boxes engine you built, measured, and broke in instructive ways.
Four phases, repeated thousands of times
One iteration is one trip around this loop. After the budget — time or iterations — runs out, you play a move from the root. Nothing else is MCTS; everything else is how you implement each phase.
The loop, as pseudocode
root = node(start position, player to move)
repeat until the budget (time or iterations) runs out:
path = select(root) # descend by UCT — §2
leaf = expand(path) # add one untried move; positions merge by key (§4)
result = evaluate(leaf) # rollout, or the exact tail if decomposed (§5)
backpropagate(path, result) # visits += 1; totals += result, root-player view
play the most-visited child of the root # the robust child, not the best mean
UCT: exploit what looks good, explore what you haven't tried
Mean value is exploitation. The square-root term is the exploration bonus — large for rarely-visited children, shrinking as they get visits. An unvisited child has infinite bonus, so everything is tried at least once. cp tunes the balance; you use cp = 1.41 = √2.
Your values are always stored from the root player's perspective. So at root-player nodes selection maximizes (value + bonus) — UCB — and at opponent nodes it minimizes (value − bonus) — LCB. Forget the flip and the opponent helpfully picks your best moves for you. You shipped this bug once; all pre-fix numbers were invalid.
Two implementation details that matter
Normalization: your code divides the value term by squaresLeft (boxes remaining) so the bonus stays comparable early vs late — a 2-box edge means something different with 9 boxes left than with 2.
Root pick ≠ best mean. After the budget ends you play the most-visited root move — the “robust child.” A high-mean, low-visit move may just be lucky. Max-visits proved more reliable than your earlier max-value pick.
Selection, as pseudocode
function selectChild(node):
if random() < eselect: return a random child # selection epsilon
for each child of node:
if child.visits == 0: return child # infinite bonus: try everything once
bonus = cp * sqrt(ln(node.visits) / child.visits)
score = child.mean + bonus if node is the root player's turn
score = child.mean - bonus if node is the opponent's turn
return the child with the best score # max at root-player nodes, min at opponent nodes
Try it: UCT calculator
Drag cp and watch who wins. With the preset below, C wins despite the worst mean — until its visits catch up.
Children (fixed from the worked example):
A — mean 0.60, 500 visits · B — mean 0.55, 100 visits · C — mean 0.50, 10 visits
Why UCT picks the worst-looking move
The arithmetic (ln 1000 = 6.908): A = 0.60 + 1.41·√(6.908/500) = 0.60 + 0.166 = 0.766 · B = 0.55 + 1.41·√(6.908/100) = 0.921 · C = 0.50 + 1.41·√(6.908/10) = 1.672.
C wins because it is under-tried. That is not a flaw — it is the guarantee. The bonus shrinks like √(ln N / n), so the genuinely best child eventually absorbs nearly all visits, while neglected children are still revisited occasionally. That guarantee is what makes the convergence argument in §10 work.
Your tree isn't a tree — it's a DAG
Textbook MCTS grows a tree: one path, one node. In Dots and Boxes, different move orders reach the same position constantly. Your engine merges them: nodes are keyed by position + player to move (a transposition table), forming a directed acyclic graph.
Merging is sound because your stored value has a clean meaning: “future boxes for the root player from this state.” It doesn't depend on how you got there. One new node is still added per iteration — it just may be shared by many parents, so statistics pool across move orders instead of being learned separately.
Selection gets the attention. Evaluation decides the games.
The rollout ladder
Your key innovation: the decomposition cutoff
A position is decomposed when every unclaimed box belongs to a chain or loop component. From there, optimal endgame value is computable, not estimable — via the control value: the player forced to open a chain of length L keeps L−2 boxes (L−4 for a loop) under the control strategy.
This is the only mechanism in the project that ever priced endgame parity correctly — because it computes rather than plays. Remember that sentence; §7 and §8 are its consequences.
The rollout, as pseudocode
function evaluate(node):
if node is decomposed:
return exact tail value # control value, computed not played
position = node.position
while position is not terminal:
if position is decomposed:
return exact tail value # truncate the rollout here
if random() < esim: move = a random legal line
else: move = policy(position) # take a box if offered, else a safe move
position = play(position, move)
return final box differential, from the root player's point of view
Other leaf evaluators, generally
Exact solver: perfect, too slow midgame (fine at low edges-remaining, which is how all your picks are judged). Learned value network: QDab / AlphaZero style — replace the rollout with a network that estimates the leaf; the network is only an evaluator, the search stays MCTS. Your own NN discussion landed on a clean spec for this: 220 edge inputs → 220 per-edge values, trained first on solver labels.
Two knobs with the same Greek letter. Do not conflate them.
eselect = 1 → 39–49% optimal
Best grid cells: eselect ≈ 0.05–0.15. Pure random selection destroys the search.
esim > ~0.2 hurts your standard: 0.15
Some randomness stops rollouts being deterministic and brittle; too much makes them random play.
Your fine grid: (eselect, esim) ∈ {0.05, 0.10, 0.15}² — best 78.3% at 2,500 ms, and only 77.5% at 5,000 ms. Doubling the budget did not help. Hold that thought for the next section.
Bias vs variance — why more search can make you more wrong
Bias is a systematically wrong grade from your rollout policy — more iterations average around the wrong number, ever more precisely.
The search converges onto the rollout policy's own preferred move. In this project we call the failure mode bias concentration: a misgraded position gets picked more unanimously as budget grows.
Lottery time curve · 17 positions · “more time ≠ better when the signal is biased”
Evidence: 54.9% → 54.9% → 58.8% across 5 s / 15 s / 30 s. Seed 1000's pick rate flat from 0.5 s to 28 s. Five lottery positions were 0-for-3 at all three budgets. And in the swap experiments (§9), the one-swap arm went from confused picks at 20K iterations to unanimous wrong takes at 50K on Case 16 — bias concentration, caught in the act.
Diagnostic rule: if more time stops helping, suspect the value signal, not the search.
Three positions that taught us everything
The unification (your framing): all three are decided by the parity of the count of quiet moves before someone must give a box its third side — and whose turn that lands on. 14 is the pure race. 13 is parity with a price. 16 is parity about who opens the remainder.
3×3, E=20. Optimal: GIVE the centre box its 3rd side (value −1); every safe move is −3. The give flips who is forced to open. Rollouts grade gives ≈ −2.5, best safe ≈ −0.6 — inverted — because self-play plays the ~18-move quiet race essentially randomly and never counts the pool. Every variant picks safe.
3 tied optimals (−3) hidden among 18 safe moves (rest −5). Decided purely by whole-game parity — no forced line to look along. All searches fixate on the same wrong move, v,2,2.
*except one stray rep in one mixture — which never recurred.
Unique optimal declines to complete a box: +3 vs −3 for taking. Plain cutoff MCTS passes because the sequel is short and forcing — the position decomposes within a few moves and the exact cutoff prices it. The bare heuristic fails (it takes). Proof the cutoff works exactly where sequels are forcing.
Failed fixes we measured
Theme: rollout-policy perturbations cannot rescue a biased value signal. After any clever flip, the remaining 15+ quiet moves are still played parity-blind — so the flip's consequence is exactly what washes out.
| Fix | Idea | Measured result |
|---|---|---|
| Parity stance (StanceMCTS) | Sample cautious vs tempo heuristic per rollout, 50/50 | 102/129 — exactly the control. Case-survey inversions persisted. |
| Stance mixtures | 25% / 10% tempo instead of 50% | No change on cases 13/14/16 at either ratio. |
| Budgeted swaps (SwapMCTS) | Per rollout: x% no swap, y% exactly one swap, rest swap at every opportunity until decomposed | Small set, 50K iters: control 13/27, mixtures 12/27, swap-always 10/27, one-swap 6/27 — one-swap broke Case 16 (unanimous takes at 50K). |
| Restricted MCTS | Tree restricted to non-giving moves | Best raw score 79.8% but rejected: hard-codes away exactly the moves Cases 12/13 require. |
Does MCTS become minimax? Yes — in a limit you'll never reach.
The game graph below an E=20 root is finite and acyclic (~2²⁰ ≈ 1M states; positions only gain edges). UCB guarantees every state is eventually expanded and visited infinitely often. Then backups flow only from terminals and decomposed leaves — both exact. Rollout bias affects the rate, never the limit. This holds for stance/swap variants too — they only touched rollouts.
Your 50K searches expand ≤50K nodes, frontier ≈ depth 5, while deciding lines stay non-decomposed for 15+ plies. Settling them plausibly takes 10⁷–10⁸ iterations — hundreds to thousands of times your largest runs. At any feasible budget, the search behaves as if its limit were the biased grade.
E=20 benchmark — 129 trials, exact judging
| Method | % optimal | Notes |
|---|---|---|
| Bare heuristic | 65.1% | Mean gap −0.728 boxes |
| Plain cutoff MCTS | 72.9% | Cutoff in tree + rollouts |
| Epsilon control | 79.1% | cp 1.41, eselect 0, esim 0.15, max-visits pick · 102/129 |
| Best epsilon grid cell | 79.1% | 11×11 grid, eselect 0.1 / esim 0.1 |
| Parity stance 50/50 | 79.1% | Identical to control |
| Restricted MCTS | 79.8% | Rejected — structurally unsound |
Files: CutoffMCTS · EpsilonMCTS · StanceMCTS · SwapMCTS (harness variants in mtayter/dots-and-boxes).
Keep this open while you work
Your configuration
cp = 1.41 (√2)
eselect = 0 · esim = 0.15
Root pick = max visits (robust child)
Cutoff: decomposition, in tree AND rollouts
Tree: DAG, keyed by position + player to move
Values: future boxes for root player, normalized by squaresLeft
Glossary
Iteration — one loop trip. Node / edge — position / move. Rollout (playout) — simulated completion used as a value estimate. Leaf — frontier node. Decomposed — all unclaimed boxes in chains/loops. Control value — exact decomposed value (open L-chain → keep L−2; loop L−4). Robust child — most-visited root move.
Design checklist
- State your currency — iterations or wall-clock — in every comparison.
- Tune epsilon on a grid; expect small values (0.05–0.15).
- If more time stops helping, suspect the value signal, not the search.
- Exact evaluation anywhere you can get it — cutoffs, solvers, learned evaluators — beats cleverer sampling.
- Verify zero-sum selection signs. Then verify them again.
Where this leaves the project
The swap/stance family is closed: nine configurations measured, none beat the control. What remains is a different kind of idea — computing parity instead of sampling it: forced-line lookahead rules (generate the flip candidate, play only the forced response, price the remainder exactly), validated offline against solver labels before anything ships. Parked until Monday, Nov 2, by your call.
Broader than Allcock, weaker than exact
MCTS is the first method in this guide that can look ahead from any position: no decomposition requirement, no fresh-component domain. That generality is a genuine improvement on both earlier methods — on the E=20 benchmark (§11), the epsilon control's 79.1% optimal picks beat the bare heuristic's 65.1%, and none of those positions was required to be in the Allcock domain. But “can look anywhere” is not “plays optimally”, and this project measured the gaps precisely.
Where MCTS still plays suboptimally
What the next method changes
Minimax (Part V) keeps the generality and removes the sampling. Instead of grading a root move by simulated continuations, it expands the actual adversarial line tree — every reply priced by the same recursion — and returns a value that is exact when the search completes. There is no rollout policy in the decision, so there is no rollout bias to concentrate; parity is computed, not sampled. The price is the one MCTS was invented to avoid: exhaustive search explodes, so production minimax needs the decomposition cutoff, the GateModel screen, and a 5-second clock — and Part V is explicit about the suboptimal moves those wrappers still let through.
Part V · Minimax
The final step: exhaustive exact search with a decomposition cutoff. It repairs the earlier methods' mistakes in principle — and the production gate and 5-second clock decide where that repair actually reaches.
Minimax: search the lines, stop at the components.
Minimax is the engine's general exact solver. Where Allcock replaces a restricted endgame with a formula, minimax searches the actual lines of the game — both players choosing optimally — until the position either ends or becomes fully decomposed, at which point the component evaluator takes over. It is powerful, expensive, and therefore surrounded by a gate, a clock, and a safety floor.
Price every legal line, from the mover's point of view
At any position, the solver's value is the eventual box differential from that position onward: boxes the player to move will gain minus boxes the other player will gain, assuming optimal play by both. Boxes already banked are not part of the value; they cannot be changed by the search.
The solver tries legal lines at the root, evaluates the resulting positions recursively, and chooses the root line with the highest value. If the whole search completes, the chosen move is not an estimate — it is an exact optimal move for that position.
Negamax: one function, two players
The implementation uses the negamax form of minimax: one recursive function always returns the value for the player to move at that node. Dots and Boxes needs one special rule — taking a box grants another move — so the turn does not simply alternate after every line.
Alpha-beta pruning
Alpha-beta search maintains a window of values that can still matter. Once a branch is shown to be too good or too bad to change an ancestor's decision, the rest of that branch can be skipped. This changes the amount of work, not the answer: a completed alpha-beta search returns the same value as an unpruned search.
Negamax, as pseudocode
function solve(node, alpha, beta, deadline):
if the deadline has passed: throw Abort
if the table holds an exact entry for node: return it
if it holds a bound entry: tighten the window; if closed: return it
if node has no legal lines: return 0
if node is fully decomposed: # the cutoff — §4
return componentGameValue(extractComponents(node))
best = -infinity
for each legal line, captures first:
child, closed = play(line)
if closed > 0:
value = closed + solve(child, -inf, +inf, deadline) # same player again
else:
value = -solve(child, -beta, -alpha, deadline) # turn flips, negate
best = max(best, value); alpha = max(alpha, best)
if alpha >= beta: break # prune: the rest cannot matter
store best in the table with its bound type
return best
Three ways the solver avoids repeating itself
These are exactness-preserving optimisations. They can change how quickly the solver reaches an answer — and, when a time cap interrupts it, which root moves have been fully scored — but a completed search still returns the exact game value.
The decomposition cutoff
A line search does not have to continue all the way to the last box. During recursion the solver tracks how many unclaimed boxes still have 0 or 1 sides. When that count reaches zero, every unclaimed box has at least 2 sides: the position is fully decomposed.
The evaluator has its own internal fast path. If every component is in the Allcock domain, it uses the formula from Part III. Otherwise it runs the micro-game alpha-beta search over component moves, which handles opened ends, short pieces, and singletons that the Allcock formula cannot.
The cutoff, as pseudocode
function valueOf(node): # checked at every recursion node, before expanding
if no unclaimed box has 0 or 1 sides: # fully decomposed
comps = extractComponents(node)
if comps are within the size limits:
return componentGameValue(comps) # exact leaf — no lines expanded
return expand node by lines # §2
function componentGameValue(comps):
if every component is in the Allcock domain: return allcockF(comps)
return microGameValue(comps) # alpha-beta over component moves
This is also where Parts II and IV meet: Allcock can decide a move directly at the top of the cascade, and the same recursion can price a decomposed node deep inside Advanced's minimax search.
The gate: do not start a hopeless search
Even with pruning and the cutoff, some positions would take far longer than a game move can wait. Before Advanced starts the solver, GateModel.js estimates the solve time from the position's structure.
What the “Full” equation looks at
| Feature group | Examples |
|---|---|
| Raw size | Empty lines and unclaimed boxes. |
| Distance to decomposition | D*: the minimum number of added segments that would give every unclaimed box at least 2 sides; the fraction of root moves whose child is already fully decomposed. |
| Freedom and captures | Moves touching no low-sided box, free moves that close a box, and the number of boxes taken by a greedy forced-capture run. |
| Shape statistics | Variance of box side counts and the fraction of empty-line pairs that touch disjoint sets of boxes. |
The equation was refit in 2026 against the current solver: leave-one-out R² of 0.924, with a median prediction error of about 1.31×. Its fitted support is positions with at most 22 empty lines; predictions on larger positions are extrapolations. It is useful as a coarse screen, not as a reliable stopwatch.
The gate, as pseudocode
predicted = GateModel.predict(position) # Full equation, laptop-scale seconds
if predicted >= 1000:
play the heuristic move # hopelessness screen — no search attempted
else:
attempt minimax under the 5-second clock # §6
The 5-second clock, the heuristic floor, and salvage
The bounded search, as pseudocode
heuristicMove = heuristic.chooseFallbackMove(board)
floor = score(heuristicMove) exactly # the floor probe, held aside
best = floor
for each root move, captures first:
if the 5-second clock has expired: break
score the root move fully; best = max(best, scored move)
play best # or heuristicMove, if nothing was scored
What Advanced may actually play
| Outcome | Move played | Status |
|---|---|---|
| Gate screens the position out | Heuristic move | No search was attempted. |
| Search completes | Root move with the highest exact value | Exact optimal |
| Search aborts with a floor or completed root move | Better of the floor and best completed root move | Salvage — value exact, choice unproven |
| Search aborts with nothing completed | Heuristic move | Search produced no usable root score. |
The engine records this distinction internally. A completed minimax move is marked exact; a salvaged minimax move is still labelled 'minimax', but it is not marked as a proven exact choice.
What minimax buys
Intermediate and Advanced are identical until this step: both use Allcock and then the heuristic. Their separation is therefore a direct measure of what Step 2 adds.
| Comparison | Result | Reading |
|---|---|---|
| Intermediate vs Advanced — 76 games | Advanced 68 · Intermediate 6 · ties 2 | The large level gap is the minimax step, not a collection of unrelated changes. |
| 27-case first-move suite (26 scored) | Intermediate 15/26 · Advanced 26/26 | Search rescues positions that are outside the Allcock domain or arise before decomposition. |
Case 20, from the search side
In case 20 the first move is not the separator: every level closes the opened chain's end box. The difference appears later, when the heuristic would sweep part of the chain and use its fixed double cross. Minimax can compare the complete consequences of taking all with giving boxes back, including the exact value of the remaining components, and chooses the line that preserves the +4 result.
The same question as a fixed rule — is sweep-then-double-cross always optimal on such a board? — is answered in Part II §7: no, with the priced rule V(rest) < −2 and three counterexamples.
Game 116, from the gate's side
Advanced used no minimax at all in the first 86 moves of the recorded game 116 — the gate screened every opening attempt. By the time exact play became available, the position's outcome was already fixed. That game is a warning against treating the solver as a general solution to big-board openings: a search that never starts cannot rescue the position.
What minimax does not solve
Minimax in the cascade and in this guide
| Method | Where it appears | What kind of answer? |
|---|---|---|
| Part II — Heuristic | All levels, Step 3; also Advanced's Step 2 floor | Fast local rules; no search and generally no exact value. |
| Part III — Allcock | Intermediate and Advanced, Step 1 | Exact formula for a restricted class of fully decomposed positions. |
| Part IV — MCTS | No current level | Sampling and statistics, not the deterministic exact search described here. |
| Part V — Minimax | Advanced only, Step 2 | Exact line search when it completes; fully scored salvage under the production clock. |
So “Advanced uses search” needs one qualification: it uses two different exact methods in sequence. Allcock is tried first because it is instant when its narrow domain applies. Minimax is tried second because it is general but expensive. The heuristic remains last because it always returns a move.
The whole cascade, as pseudocode
function move(board): # AIEngine.move, checked in order
if level is not beginner:
line = allcockMove(board) # Step 1 — Part III
if line: return line
if level is advanced:
predicted = GateModel.predict(board)
if predicted < 1000: # Step 2 — admitted by the gate
heuristicMove = heuristic.chooseFallbackMove(board)
result = solveRootCutoff(board, 5 seconds, priorityMove = heuristicMove)
if result scored any root move: return the best scored move
return heuristic.chooseFallbackMove(board) # Step 3 — the fallback
Implementation map: AIEngine.js owns the gate threshold, clock, and cascade; SolverCutoff.js owns negamax, alpha-beta, the shared table, macro filtering, the decomposition cutoff, and salvage; GateModel.js owns the prediction; ControlValue.js owns the component evaluator used at cutoff nodes.