Dots and Boxes — Terminology, Strategy, and the AI Engine

One reference for the Dots and Boxes game and its AI engine. After the vocabulary, the move-choosing methods are presented in order of increasing sophistication: local rules (the heuristic), an exact formula for a narrow endgame (Allcock), general lookahead by sampling (MCTS), and exhaustive exact search (minimax). Each method is explicit about where it still plays suboptimally, and each later method is explicit about which of those mistakes it repairs. Note that this is a reading order, not the engine's execution order: the production cascade runs Allcock, then minimax, then the heuristic — and MCTS, the research record, is not used by any current level.

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

Shape

A 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.
4-chain, horizontal. Top and bottom sides drawn, shared sides between boxes left open.
4-chain, vertical. Same thing turned on its side — left and right sides drawn.
2-chain. The shortest chain that still links two boxes together.

Long chain

Shape

A 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.
6-chain. Long by any count — taking it and giving back 2 still nets 4.
Why length matters. In a 6-chain the 2 give-back boxes (amber) are a small price; in a 2-chain they would be the whole thing.

Loop

Shape

A 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).
4-loop. A 2×2 block: outside sides drawn, the cross in the middle left open.
8-loop. Eight boxes ringing one empty box in the middle. Outer and inner sides drawn, sides between ring boxes open.
10-loop. A wider ring, around two empty boxes. Still no ends anywhere.

Closed chain

State

A 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).
Closed 3-chain. Every box has exactly 2 sides. No box can be taken yet.
Closed 4-chain, vertical. Same state, different orientation — still nothing with 3 sides.
Closed 4-loop. The same untouched state in loop form.

Open chain

State

A 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.
Open 3-chain. The left-hand box (paler green) now has 3 sides — it can be taken, and the rest follow.
Open 4-chain, vertical. The top box has been given a third side, opening the whole column.
Open 4-loop. One side played inside the loop (orange in the opening examples below) leaves two boxes with 3 sides.

Offer

State

A 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.
An offer. One box has 3 sides (paler green), so this chain can be taken now — all of it, not just that box.
Two offers out. Two separate chains, each with a three-sided box. The player to move picks which one to play on.
Not an offer. A closed chain: no box has a third side, so nothing can be taken from it until somebody opens it.

Decomposed position

State of the whole board

An 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.
Schematic map of a decomposed board. Each colour is one separate component — here a 2-chain, a 4-loop and a 3-chain — walled off from the others by drawn lines. Nothing connects them.
Component 1: a closed 3-chain, on its own.
Component 2: a closed 4-loop, on its own. Together with component 1, that is the whole position — there is nothing else left to play.

Quiet play

State of the whole board

Play 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.
A quiet position. Boxes have 0, 1 or 2 sides — none has 3. Nobody can take anything, and several safe moves remain.
A quiet move (orange). It adds a first side to an untouched box: nothing completes, nothing ripens, the turn just passes.

Moves — things a player does

Open a chain

Move

To 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.
Before. A closed 4-chain. Nobody can take anything in it.
The opening move (orange). Playing the left end gives the end box a third side. The mover takes nothing.
Opening a loop. Playing one side inside a closed 4-loop (orange) leaves two boxes with 3 sides — the opponent sweeps all four.

Ripen

Move

To 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.
Ripening one box. The box has top and bottom drawn; the move (orange) adds its left side — its third. It is ripe, but nobody has taken it.
Ripening in a 2-chain. Adding the far end (orange) gives the second box its third side too — now the whole chain is ripe for the opponent.
Unripe vs. ripe. Left box: 2 sides, cannot be taken. Right box: 3 sides, ripe — the next player takes it by drawing the fourth side.

Sweep / take-all

Move

To 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.
Mid-sweep. Two boxes of the 4-chain are taken (dark, ×); closing the second has just ripened the third, which is next.
Sweep complete. All four boxes taken in one turn. Nothing was given back.
Sweeping a loop. All four boxes of the 4-loop taken, working around the ring.

Give-back

Move / amount

The 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.
Leave-2 in a chain. Of a 6-chain, four are taken and the last 2 (amber) are given back.
Leave-4 in a loop. Of an 8-loop, four are taken and the remaining 4 (amber) are given back.
Edge case. A 2-chain is exactly give-back size — giving back means handing over both boxes and taking none.

Double cross

Tactic

The 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.

  1. Sweep most of it — take the component box by box, but stop with 2 left (chain) or 4 left (loop).
  2. 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.
  3. 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.
Step 1 — stop short. Four boxes of the 6-chain taken, two left on the table.
Step 2 — the cross. Instead of taking the last two, play inside them (orange), ripening one for the opponent.
Same move in a loop. With 4 loop boxes left, play one side of the middle cross (orange) — it completes nothing, and gives all four away.

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

Move

The 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.
In a 6-chain. Four boxes taken, two remain and the next one is ripe. Instead of taking it, play the far end edge of the last box (orange) — now both remaining boxes are ripe.
The bare case — a 2-chain. Play an end edge (orange) and both boxes become the opponent's; you take nothing from the chain at all.
The result. Your four boxes are yours (dark, ×). The opponent collects the last two (blue) — and must open whatever comes next.

Double loony

Move

The 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.
The move. In the last four boxes of a loop, play one side of the middle cross (orange). It completes nothing — and gives two boxes their third side at once.
After the move. Two boxes are ripe (paler green). The opponent takes them, which ripens the other two — all four change hands.
The same move in a short chain. With a ripe box at each end, play the side shared by the two middle boxes (orange): both go ripe, nothing completes, and the turn passes.

Control

Strategy

Control 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.
The opener at work. Forced to open the 4-loop (orange): takes nothing, hands all four boxes to the controller.
The controller's reward. The same opponent must then open the big component too, and the controller sweeps it — here an 8-loop.

Loony move

Move

A 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.
Plain loony move. Playing the third side of a lone box (orange) simply hands that box to the opponent.
Loony move in a chain. The same one-line mistake inside a closed 5-chain offers all five boxes, not one.

The four stages of a board

Progression

Four 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.

Stage 1 — Quiet. Every box has 2 sides except the three blue 1-sided boxes, and exactly one safe move remains: the orange edge. Playing it ends quiet play for good.
Stage 2 — No quiet moves, not decomposed. The orange edge is drawn. Every move now gives some box its third side — yet the amber box in the bottom row still has only 1 side, so the board is not decomposed. It is walled in by 2-sided neighbours: this is how a board can have no safe moves and still not decompose.
Stage 3 — Decomposed, not Allcock. The orange edge gives the amber box its second side, and now every box has at least 2 sides. Four components: a fresh 3-chain, a fresh 3-chain, an opened 4-chain (amber — its leftmost box already has 3 sides), and a fresh 5-chain. The opened chain is outside the Allcock domain, so the formula stays silent — though the micro-game evaluator still prices the position exactly.
Stage 4 — Allcock domain. The opened chain has been swept (dark green). What remains — 3-chain, 3-chain, 5-chain, all fresh — is exactly the Allcock domain: the recursion in Part III prices it with no search at all.
  • 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
A classification, not a script. Real games spend most of their length in stage 1, pass through stage 2 quickly — sometimes in a single move — and may bounce between stages 3 and 4 several times in the endgame as components are opened and swept.

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.
Diagrams are simplified examples: green shading picks out the component being discussed, and only the sides that matter to the term are emphasised.

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 production fallback · AIEngineHeuristic.js

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.

Code: AIEngineHeuristic.js — chooseFallbackMoveUsed by all three AI levelsBeginner is this heuristic aloneNo game-tree search
01 · The big idea

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:

Offered positionAt least one box has 3 sides. Somebody has opened a component and boxes can now be taken. The heuristic switches to its controller rules.
→
Controller question“How do I take these boxes without giving the opponent control of what happens next?”
·
Quiet positionNo box has 3 sides. Nothing can be taken yet. The heuristic switches to its opener rules and asks where it can play safely — or, if it must open something, what will cost least.

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.

Two proved exceptions. The heuristic first checks for a component that can be captured completely by one closing move — a ready singleton, an enclosed domino, or an enclosed triplet. Taking it first is always optimal on any board, so these narrow rules are exact even though the heuristic as a whole is not.

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
02 · Perception

How the heuristic reads the board

1
Count sides. For each box, count drawn edges from 0 to 4. Claimed boxes drop out of the decision; 3-sided boxes are immediate takes; 2-sided boxes are the raw material of chains and loops.
2
Build regions. Unclaimed boxes with 2 or 3 sides are grouped into connected regions through their shared, still-undrawn edges. A region may be a chain, a loop, or a less regular blob.
3
Classify the shape. A region is treated as a loop if every undrawn edge of every box in it is shared with another box in the same region — it has no leak to the outside. Otherwise it is treated as a chain.
4
Return exactly one edge. Sweeping a long component is not done by one giant decision. Each heuristic call returns one line; because taking a box grants another move, repeated calls walk through the component until the control rule says to stop and hand boxes back.

Function names in the code: countSquares, buildRegions, isLoop, controllerMove, and openerMove.

03 · Offered positions, step 0

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:

Ready singleton — {single: 1}One isolated 3-sided box. Its last edge takes it and leaves no residue inside that component.
Enclosed domino — {2, 1, 1}Two 3-sided boxes whose shared edge is the last undrawn edge of both. One move closes both.

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.

04 · Offered positions

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:

Sweep a long component, but do not take the last few boxes. Leave 2 boxes from a chain or 4 from a loop, ripen them for the opponent, and force the opponent to take them and open the next component. You surrender a few boxes to keep the profitable job of sweeping what remains.

The actual rules

Offered shapeHeuristic actionWhy
Multiple offered regionsSweep 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 > 2Close 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 boxesChain 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 4Take 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 4Double 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 ≤ 4Try 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 openingsTake one box first.Reduce it until one of the short-shape control rules can apply.
Single offered boxDecline 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
Fixed rule, not a priced choice. Part III's Allcock recursion compares control with take-all and chooses the better reply for each component. The heuristic does not. Once its structural conditions are met, it assumes control is right. That difference is the main reason Intermediate and Advanced exist.
05 · Offered positions, fallback

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:

1
Collect the last undrawn edge of every 3-sided box.
2
Choose one at random and take the box.
3
On the next call, repeat from the new board. If the last component is being swept, this naturally takes it all: with no significant component left to protect, control has nothing left to buy.

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.

06 · Quiet positions

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:

1
Play safe if possible. A safe move is an undrawn edge whose neighbouring boxes both have fewer than 2 sides. Drawing it leaves every neighbouring box with at most 2 sides, so it creates no 3-sided box and offers the opponent nothing. If any safe moves exist, the heuristic picks one at random.
2
Find the smallest area of 2-sided boxes. When no safe move remains, some component must be opened. The opener groups connected 2-sided boxes into areas and selects the smallest area. Size is its proxy for cost.
3
Open a smallest pendant chain inside that area. Junction boxes with three or more chain neighbours are stripped away, leaving path-like chains. The heuristic chooses a smallest surviving chain, then randomly chooses one of its playable edges — an end edge or an interior shared edge.
4
Fallback: open the smallest area directly. If no pendant chain is found — a pure loop is the important example — it picks a random box in the smallest area and a random undrawn edge on that box's border.

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
The case 19 limitation is here. The opener chooses the smallest area before it looks for a chain. In case 19 the areas are a 3-chain, a 4-loop, and a 5-chain, so it opens the 3-chain — even though Allcock prices opening the 4-loop as the optimal move. Replacing “smallest” with “cheapest to open” is not a small patch to the chain finder; priced correctly, it is essentially the Allcock calculation in Part III.
07 · Failure modes

What the rules cannot price

Control is not compared with take-allThe controller assumes the standard give-back is profitable when another significant component remains. Sometimes the rest of the board is worth 0 to its opener, so the donated boxes buy no tempo at all.
Area is not opening costThe opener ranks regions by number of boxes. A larger loop can be cheaper to open than a smaller chain because its give-back is 4 and because of what opening it does to the rest.
Parity is handled indirectlyControl and the safe-move guard encode useful tempo ideas, but the heuristic does not count the exact parity of a decomposed tail or price an unripe singleton as a token.
Multiple offers are swept, not pricedSince 2026-11-23 (case 27) the controller sweeps all but one offered region and controls the last, instead of stepping aside to greedy. The sweep itself is always optimal; the control-vs-take-all call on the last region is still the fixed rule, not a priced choice.

Two test cases make the limits concrete

CaseWhat happensLesson
19Beginner 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.
20All 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:

1
Case 20 — the double cross is the mistake. Opened 4-chain + fresh 4-chain + ring 4, value +4. The control line takes 2 boxes of the opened chain and gives back the last 2, netting 0: the opponent takes the 2, and the remaining {fresh 4-chain, ring} is worth 0 to whoever must open it. Taking all 4 nets +4. The give-back donates exactly 4 points for nothing.
2
Offered 6-chain + fresh 4-chain — the sweep is the mistake. Also decomposed, not Allcock: the opened end puts it outside the domain. Control wins here: take 4, give back 2, and the opponent is left to open a lone fresh 4-chain worth −4 to its opener — net +6. Sweeping all 6 leaves you opening that 4-chain instead, netting only +2.
3
Case 18 — the extreme. {2,1,2} cascade + ring 4 + an unripe singleton {single: 2}. The optimal take is +5; the double cross is −5. The mechanism is the singleton as a tempo token: after the give-back, the opponent takes the 2 boxes and ripens the singleton instead of opening the next component. A search over single-offer control-rule positions found 708 of 2,484 states where sweep-to-2-and-give-back loses to take-all — this is not a rare corner.

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.

What the next step repairs — and what it leaves. Allcock (Part III) removes exactly two of these failure modes, where it applies: it prices which component to open by recursion instead of by area, and it chooses control vs take-all by value instead of by fixed rule. That is enough to fix case 19. It does not fix case 20 — an opened chain is outside the Allcock domain — nor anything on a board that is not yet decomposed, nor the unpriced control call on the last offered region, nor parity in the general position. Those mistakes survive Allcock and are the business of the general search methods in Parts IV and V.
08 · Step by step

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.

StepAlways optimal?Proving case / evidencePseudocode
One-move capture — take a ready singleton {single: 1} or an enclosed domino {2, 1, 1}YesTheorem: 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}YesTheorem: 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 oneYesTheorem: 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 boxYesForcing 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)NoCase 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 boxYesForcing 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-crossNoCases 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 boxNever runsDead 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 crossNever runsDead 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 takesNoCase 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 existsNoCases 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 boxNoCases 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 edgeNoCases 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 edgeNoCases 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.

09 · The cascade by level

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 stepBeginnerIntermediateAdvanced
Step 1 — Allcock
Exact formula on a fully decomposed board with every component in the Allcock domain.
SkippedUsedUsed
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.
SkippedSkippedUsed
Step 3 — Heuristic
One-move captures, controller or greedy play when offered, and safe/smallest-area opener play when quiet.
UsedUsedUsed as fallback
Beginner — heuristic onlyThis page is the whole engine. It captures, controls by rule, and opens the smallest area, but it never checks whether Allcock or search would price the position differently.
Intermediate — Allcock, then heuristicExact play appears precisely when a fully decomposed position lies entirely inside the Allcock domain. Everywhere else, Intermediate makes the same heuristic decisions as Beginner.
Advanced — Allcock, minimax, then heuristicOutside the Allcock domain, Advanced can search before falling back. The heuristic still matters twice: as the fallback if search is screened out or cannot produce a move, and as the first root move evaluated by minimax, so an aborted search's salvage is never supposed to be worse than the heuristic's draw.

Measured separation

ComparisonResultInterpretation
Beginner vs Intermediate — 304 pooled gamesIntermediate 158 · Beginner 140 · ties 6Allcock adds a small, real edge, concentrated where its domain actually occurs.
Intermediate vs Advanced — 76 gamesAdvanced 68 · Intermediate 6 · ties 2Minimax 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 26Case 19 separates Beginner from Intermediate; cases 21–26 separate both from Advanced.
10 · How the guide fits together

Which part describes which level?

Part of this guideBeginnerIntermediateAdvancedRole
Part I — TerminologyLanguageLanguageLanguageDefines 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 HeuristicWhole engineStep 3Step 3 + minimax floorThe 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 1Step 1Exact 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 2Advanced's general exact search: negamax with alpha-beta pruning, a decomposition cutoff, the GateModel screen, and salvage under a 5-second budget.
Reading path. To understand Beginner, read Parts I and II. Add Part III and you understand Intermediate. Add Part V — Minimax — and you understand Advanced. Part IV explains a different, sampled search idea that informed the project's history but is not in the shipped cascade. Remember the guide's order is by sophistication; the cascade's execution order is different: Allcock first, minimax second, heuristic last.

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.

Tutorial · Reference · Your project

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.

Repo: mtayter / dots-and-boxesCode: ControlValue.js — allcockF · allcockMoveg = 2 (chain) · 4 (loop)F(∅) = 0
01 · The big idea

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:

Board positionLines, coordinates, adjacency — hundreds of distinct states that play identically.
Component stateA multiset like { chain 7, loop 5, chain 4 }. Order doesn't matter. Geometry is gone — because in this domain, geometry no longer affects the value.
What remains to decideOnly one real choice: which component to open first. Everything after that is forced optimal replies, which the recursion already knows.
Why this is exact, not a heuristic. The recursion doesn't estimate or sample. For positions inside its domain it returns the true game value — the net box differential under optimal play from both sides — the same number the full search evaluator produces, reached by a shortcut the search itself uses when it can (see §8).

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.

02 · Preconditions

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.

BOARDevery box ≥ 2 sidesno loose boxes → CHAIN · n boxesa path of boxes LOOP · n boxesa ring of boxes { 7-chain,5-loop }

Test 2 — Every component is fresh and long

Loops: ring ≥ 4Written { ring: n } with n ≥ 4. A 3-ring is too short — the give-back of 4 wouldn't leave a sensible control play.
Chains: fresh { n, 2, 2 } with n ≥ 3A path whose both ends still have 2 untaken edges — unopened, nothing offered yet. In extractor terms: not a loop, zero 3-sided boxes (threes == 0).
What falls outside — and why it must. A singleton, a short path (n < 3), a chain with an opened end ({n, 1, 2} or {n, 1, 1}), or a small ring breaks the closed form: once a component is partly played, how it was opened matters again, and the two-reply argument in §3 no longer covers all the lines. Those states are still solved exactly — by the micro-game alpha-beta search over component moves — just not by this formula. See §8.

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
03 · The core choice

Control vs take-all: the sweeper decides

Play in this domain has a fixed script with exactly two decision-makers:

1
The opener — the player to move — must open a component: play the first line that starts it collapsing. The opener's only freedom is which component.
2
The sweeper — the opponent — then sweeps that component, and chooses between exactly two replies. This choice is the heart of the algorithm.
🕹 Control — take size − g, give back gThe sweeper takes most of the component but deliberately hands g boxes back to the opener. In exchange, the opener must open the next component too — the sweeper keeps the profitable role. This is the double-cross, generalised.

g = 2 for a chain g = 4 for a loop
🧹 Take-all — take size, open the rest yourselfThe sweeper takes every box in the component — and pays for it by becoming the opener of whatever remains. Greedy now, burdened next.

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.

The sweeper is adversarial. The sweeper picks whichever reply is worse for the opener. So opening a component is a commitment: you don't get to assume control will be played, or that take-all will be played — you get the minimum of the two. Choosing what to open means choosing the component whose worst case hurts least. That's §4.
04 · The recursion

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.

F(∅) = 0

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:

control  =  2g − s + F(rest)    |    take-all  =  −s − F(rest)
Reading “control”: 2g − s + F(rest)Opener receives g, sweeper receives s − g, so this component nets the opener g − (s − g) = 2g − s. The opener stays the opener of the rest, so add + F(rest).
Reading “take-all”: −s − F(rest)Opener receives 0, sweeper receives s: net −s. Now the sweeper opens the rest, so the rest is worth F(rest) to the sweeper — from the original opener's perspective, − F(rest).
F(S) = max over c in S of   min( control(c), take-all(c) )

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.

Sanity check — a lone component. With rest empty, F(rest) = 0, so control = 2g − s and take-all = −s. The min is always −s: with nothing left to open, the sweeper just takes everything and the “burden” costs nothing. So F({single component of size s}) = −s, whatever it is. Control only becomes valuable when there is a rest to protect — which is precisely the intuition the formula encodes.
05 · Worked example

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:

F({ chain 7 }) = −7   ·   F({ loop 5 }) = −5   ·   F(∅) = 0
A
Open the 7-chain (s = 7, g = 2, rest = { loop 5 }, F(rest) = −5)
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.
B
Open the 5-loop (s = 5, g = 4, rest = { chain 7 }, F(rest) = −7)
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.
✓
Opener takes the max: max(−8, −4) = −4. Open the loop. Final value F = −4: under optimal play the sweeper nets 4 more boxes than you from these 12 — an 8–4 split. Note the counter-intuitive bit: you open the component where the sweeper “only” keeps 1 box under control, because the real cost in line A was never the chain itself — it was being forced to open the loop afterwards.

Every number above is the production recursion evaluated by hand — you can reproduce it, and vary it, in the calculator below.

06 · Hands-on

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.

07 · From value to move

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:

1
Check the board. If the position isn't fully decomposed, return null — not Allcock's problem. Extract the components and convert each to micro form ({ring: n} or {n, a, b}).
2
Check the domain. If any component is outside the Allcock domain (§2), return null.
3
Pick the component. For each component, score it exactly as the recursion does — min(2g − s + F(rest), −s − F(rest)) — and keep the component with the highest score. That component is the optimal opening.
4
Return a canonical line. Inside the chosen component, any first line is value-equal — by symmetry in a ring, and by the fresh-entry equivalence for a fresh chain (the same collapse the evaluator's prunings rely on). So the code simply returns the lowest-id untaken line belonging to that component. The strategic content was entirely in step 3.

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
No size gate. Unlike the old evaluator step, allcockMove has no component-count or box-count cutoff. Its cost is one component scan plus the memoised recursion over the multiset — cheap even on positions far too large for search — so in the cascade (§9) it is attempted on every move and simply returns null when it doesn't apply.
08 · Three solvers, three levels of abstraction

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 searchAllcock recursion
StateThe actual board: lines taken, turn, each box's side countA multiset of micro components: {ring: n}, {n, a, b}, {single: u}A multiset of sizes only: {chain 7, loop 5}
Branches overIndividual legal lines, captures keep the turn; alpha-beta + transposition tableSingle-edge draws inside components (splits, ripens, closes); alpha-beta + bound-typed TTWhich component to open — one branch per distinct component
Applies whenAny position (if the gate admits it and the clock allows)Any fully decomposed positionFully decomposed and every component fresh & long (§2)
ReturnsAn actual line to play, with an exact root value if it finishesThe exact value of the decomposed tailThe exact value F — and via allcockMove, the component to open + a canonical line
CostExponential in open lines; production runs are gated and capped at 5 sSmall state space, but still a search — worst recorded single call ~0.2 s after the PR #80 pruningsMemoised recursion over subsets of the component list; effectively instant

How they nest in practice

→
At the top level, the engine's cascade tries allcockMove first (§9). If the position is in-domain, the move is decided without any search at all.
→
Inside minimax, when the line search reaches a node that has become fully decomposed, it stops expanding lines and asks the component evaluator for that subtree's exact value instead.
→
Inside the evaluator, microGameValue dispatches: in Allcock domain → allcockF directly; otherwise → the micro-game alpha-beta search, which handles opened ends, singletons, and short pieces the formula can't.

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.

09 · Placement

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.

1
Allcock — allcockMove. Fires only on fully decomposed, in-domain positions; returns an exact optimal opening instantly, with no size gate. Phase label: 'allcock', marked exact.
2
Minimax — solveRootCutoff under a flat 5-second cap, admitted only when the GateModel equation doesn't screen the position out as hopeless (predicted ≥ 1000 s is skipped). On a cap abort, the best fully scored root move is salvaged if one exists. Advanced only.
3
Heuristic — AIEngineHeuristic.chooseFallbackMove: controller/greedy play in offered positions (including the heuristic double-cross — a hand-played cousin of control), safe opener play in quiet ones.
LevelStep 1 · AllcockStep 2 · MinimaxStep 3 · HeuristicCharacter
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.
Why the Allcock edge is real but small. The step fires rarely and late — only once a game has fully decomposed with everything still fresh and long. Its exactness is also calibrated against optimal replies, which a heuristic opponent doesn't reliably make. Measured in league play (see §11), that makes Intermediate a close cousin of Beginner — while minimax, which fires across the whole midgame, is the real discontinuity at Advanced.
10 · Trust, but verify

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):

0 differenceson 4,000 random in-domain states vs the micro-game search evaluator.
0 differenceson 250 states vs the unpruned reference evaluator, and on 175 real harvested positions.
Monster states includedThe fresh-monster family (36-chain states) — the cases where a subset recursion should crush a search, and does.
~100× faster in-domain~1000× on the monster states, vs the search evaluator. The win grows with component size, exactly as the state-count argument predicts.

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.

11 · Measured results

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 caseBeginnerIntermediateAdvanced
Case 1PassPassPass
Case 2PassPassPass
Case 3PassPassPass
Case 4PassPassPass
Case 5PassPassPass
Case 6PassPassPass
Case 7PassPassPass
Case 8PassPassPass
Case 9PassPassPass
Case 10MissMissPass
Case 11MissMissPass
Case 12MissMissPass
Case 13MissMissPass
Case 14MissMissPass
Case 15PassPassPass
Case 16MissMissPass
Case 17PassPassPass
Case 18MissMissPass
Case 19 — the separator (decomposed)MissPassPass
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)PassPassPass
Case 21 — ripen beats sweep, safe moves (4×3 · value +2 · unique optimal v,0,2)MissMissPass
Case 22 — ripen beats sweep, loose pair (4×3 · value +2 · unique optimal v,0,2)MissMissPass
Case 23 — free box before chain end (4×3 · value +4 · optimal h,2,1, v,0,3)PassPassPass
Case 24 — loop ripen loses (3×3 · value +7 · optimal h,0,2, h,1,2)MissMissPass
Case 25 — opener picks wrong area (3×3 · value +3 · optimal h,1,2, h,2,2, v,1,2, v,2,2)MissMissPass
Case 26 — opener picks wrong chain edge (3×3 · value +5 · unique optimal h,1,1)MissMissPass
Case 27 — multi-offer sweep (3×3 · value +5 · optimal h,2,2, v,1,1)PassPassPass
Total14 / 2715 / 2727 / 27
Case 20: a first-move pass only. The opened 4-chain {4, 1, 2} is the only component outside the Allcock domain; the fresh 4-chain {4, 2, 2} and the ring 4 are in-domain. Beginner and Intermediate both earn their Pass by playing the optimal first move, v,0,3, but the heuristic then sweeps two boxes and double-crosses the last two of the opened chain (h,5,0), donating them for nothing — the remaining {4-chain, ring} pair is worth 0 to whoever opens it, so the give-back buys no tempo and costs 4 on the differential; in full play the heuristic nets 0 against the exact +4. With fresh companions an opened long chain has no first-move separator: closing the offered end box is never a suboptimal first move, so this failure can only appear at the double-cross, not in the first move.
Why Beginner and Intermediate tie on Cases 1–18 — and how Case 19 breaks the tie. No position among Cases 1–18 is in the Allcock domain at the decision point, so Intermediate's Allcock step never fires there: on all 18, both levels play the identical heuristic move, and the table can't tell them apart. Case 19 (§12) is built to fix exactly that — a position that is in the domain at the decision point, where the heuristic opener and the Allcock opener choose different components. The levels also separate in full-game league play, where positions reach the domain naturally — pooled across 304 league games: Intermediate 158 wins, Beginner 140, ties 6.
12 · New test case

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:

Loop · 4 boxesA ring — at the domain minimum, ring ≥ 4. Give-back g = 4.
Chain · 3 boxesFresh { 3, 2, 2 } — both ends unopened. Give-back g = 2.
Chain · 5 boxesFresh { 5, 2, 2 } — both ends unopened. Give-back g = 2.
S = { loop 4, chain 3, chain 5 }   ·   F(S) = 0

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:

A
Open the loop (s = 4, g = 4, rest = { chain 3, chain 5 }, F(rest) = −4)
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.
B
Open the 3-chain (s = 3, g = 2, rest = { loop 4, chain 5 }, F(rest) = −1)
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.
C
Open the 5-chain (s = 5, g = 2, rest = { loop 4, chain 3 }, F(rest) = −1)
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.
✓
Opener takes the max: max(0, −2, −4) = 0 — open the ring. The optimum is unique: every other opening is strictly worse, so the pass mark is unambiguous. At F = 0 the 12 boxes split 6–6 under optimal play.

What each level plays

Beginner — MissPure heuristic. Its quiet-position opener opens the 3-chain — on every seed — walking into line B: a −2 finish (a 5–7 split) instead of 0. It has no machinery that prices the ring's two replies, so it never sees that the loop is the safe open.
Intermediate — PassallcockMove fires: it scores all three components exactly as above, keeps the max, and opens the ring, returning a canonical first line inside it. Its only exact step is precisely the one this position tests.
Advanced — PassSame Allcock step, first in its cascade — minimax is never consulted. Case 19 separates Beginner from Intermediate; it says nothing about Advanced, which is what Cases 1–18 are for.
Why the design works. Three ingredients, each necessary. (1) In-domain at the decision point — the failure mode of Cases 1–18, removed by construction. (2) A unique optimum — 0 vs −2 vs −4 leaves no tie-break ambiguity about what “pass” means. (3) The heuristic's actual choice is the middle move — the 3-chain isn't a blunder into the worst line, it's the plausible, tidy-looking open that happens to hand the sweeper a take-all worth −2. The case fails Beginner for the honest reason: not carelessness, but the absence of the recursion.

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).

13 · Reference card

Keep this open while you work

F(∅) = 0   |   F(S) = maxc min( 2g − s + F(rest),  −s − F(rest) )   |   g = 2 chain, 4 loop

Domain checklist

  1. Fully decomposed: every box has ≥ 2 sides.
  2. Every loop is a ring of ≥ 4.
  3. Every chain is fresh {n, 2, 2} with n ≥ 3.
  4. 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.

14 · Limits and the next step

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

1
Any component outside the domain switches the whole step off. One opened chain end, one short path, or one unripe singleton anywhere on the board makes allcockMove return null for the entire position — and in production the move falls through to the heuristic, with all of Part II's mistakes intact. Case 20 is the clean example: its opened 4-chain is the only out-of-domain component, so Allcock never fires, and the heuristic's deferred double-cross decides the game later.
2
Boards that are not yet decomposed get nothing. Allcock is an endgame formula. In the long middle of a game — boxes with 0 or 1 sides still on the board — it cannot even state the position, let alone price it. That is why none of cases 1–18 is in-domain at the decision point, and why Intermediate and Beginner play identically on all of them.
3
Parity objects are outside the language. An unripe singleton is a tempo token, not a component the recursion can price (§2). Case 18 turns on exactly that token, and Allcock is silent there too.

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).

Built from your own engine — the recursion, domain test, give-back values, validation counts, and cascade placement are from ControlValue.js and AIEngine.js in mtayter/dots-and-boxes (Allcock fast path, 2026-11-06; three-level split, PR #91, 2026-11-07; Case 19 separator, PR #92, 2026-11-10). The worked example in §5, the calculator in §6, and the Case 19 pricing in §12 evaluate the production recursion exactly. Diagrams are schematic.

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.

Tutorial · Reference · Your project

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.

Repo: mtayter / dots-and-boxesBenchmark: E=20 · 43 positions · 129 trialscp = 1.41 · esim = 0.15Root pick: most-visited
01 · The loop

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.

1 · SELECTIONDescend by tree policy 2 · EXPANSIONAdd one new node 3 · EVALUATIONRollout or exact value 4 · BACKPROPUpdate the path repeat × Nthen play robust child
SelectionWalk from the root through nodes already in the tree, choosing children by UCT (next section).
ExpansionAdd exactly one previously untried move as a new node.
Simulation / evaluationEstimate that new node's value — by playing it out, by an exact solver, by a learned evaluator, or (in your engine) by an exact cutoff.
BackpropagationWalk back up the path: increment visits, add the result to each node's total. Means shift, bonuses shrink, the next iteration chooses differently.

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
02 · Selection

UCT: exploit what looks good, explore what you haven't tried

score(child) = mean value  +  cp · √( ln(parent visits) / child visits )

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.

⚠ The zero-sum sign flip — a bug you actually shipped.
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

03 · Worked example

Why UCT picks the worst-looking move

ROOT1,000 visits Amean 0.60 · 500 visitsbonus 0.166UCT 0.766 Bmean 0.55 · 100 visitsbonus 0.371UCT 0.921 C — SELECTED ✓mean 0.50 · 10 visitsbonus 1.172UCT 1.672

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.

04 · Expansion

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.

play a, then bSAME POSITIONshared statsplay b, then a
05 · Evaluation — where MCTS is won or lost

Selection gets the attention. Evaluation decides the games.

The rollout ladder

(a) Uniform randomFast, unbiased-ish, and very noisy. A baseline, not a strategy.
(b) ε-greedy “dumb” policyTake a box if offered, else prefer safe moves, ε-random otherwise — until the position gains structure.
(c) Full heuristicPlays the rest properly. Better value per iteration, but 10–20× slower than dumb rollouts.
Always state your currency. Heuristic rollouts can win per-iteration and lose per-second. Every comparison in this project should say whether it is fixed-iterations or fixed-wall-clock — your later laptop runs switched to fixed 20K / 50K iterations precisely so machines stopped confounding results.

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.

In the treeDecomposed nodes become exact leaves. No rollout needed.
In rolloutsTruncate the instant a rollout reaches a decomposed position and score the exact tail instead of playing it out.

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.

06 · Epsilon

Two knobs with the same Greek letter. Do not conflate them.

eselect — epsilon in selectionWith probability eselect, ignore UCT and pick a uniformly random edge.

eselect = 1 → 39–49% optimal
Best grid cells: eselect ≈ 0.05–0.15. Pure random selection destroys the search.
esim — epsilon in simulationInside a rollout, with probability esim play a random move instead of the policy's move.

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.

The principle: epsilon changes which moves get sampled. It never changes how continuations are scored. If the scoring is biased, no epsilon setting fixes it.
07 · The central lesson

Bias vs variance — why more search can make you more wrong

Variance is noise in the estimate — more iterations average it away.
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.
5 s15 s30 s% optimal picks 54.9%54.9%58.8% 6× the compute → +2 picks in 51

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.

08 · Case studies

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.

Case 13 — The sacrifice0-for-30 centre box: 2 sides

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.

Case 14 — The lottery0-for-30*

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.

Case 16 — Forego a takePASSES 3/3

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.

09 · Negative results

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.

FixIdeaMeasured result
Parity stance (StanceMCTS)Sample cautious vs tempo heuristic per rollout, 50/50102/129 — exactly the control. Case-survey inversions persisted.
Stance mixtures25% / 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 decomposedSmall 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 MCTSTree restricted to non-giving movesBest raw score 79.8% but rejected: hard-codes away exactly the moves Cases 12/13 require.
10 · Convergence

Does MCTS become minimax? Yes — in a limit you'll never reach.

TRUE limit = minimax
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.
EFFECTIVE limit = rollout policy's favourite
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.
11 · Scoreboard

E=20 benchmark — 129 trials, exact judging

Method% optimalNotes
Bare heuristic65.1%Mean gap −0.728 boxes
Plain cutoff MCTS72.9%Cutoff in tree + rollouts
Epsilon control79.1%cp 1.41, eselect 0, esim 0.15, max-visits pick · 102/129
Best epsilon grid cell79.1%11×11 grid, eselect 0.1 / esim 0.1
Parity stance 50/5079.1%Identical to control
Restricted MCTS79.8%Rejected — structurally unsound

Files: CutoffMCTS · EpsilonMCTS · StanceMCTS · SwapMCTS (harness variants in mtayter/dots-and-boxes).

12 · Reference card

Keep this open while you work

UCT:  mean + cp · √( ln N / n )   |   opponent nodes: mean − bonus

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

  1. State your currency — iterations or wall-clock — in every comparison.
  2. Tune epsilon on a grid; expect small values (0.05–0.15).
  3. If more time stops helping, suspect the value signal, not the search.
  4. Exact evaluation anywhere you can get it — cutoffs, solvers, learned evaluators — beats cleverer sampling.
  5. 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.

13 · Limits and the next step

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

1
Its grades are samples, not values. At any feasible budget the frontier is shallow (§10), so root choices rest on rollout estimates. A move can win the visit count while being worth less than a rival the samples graded badly — cases 13 and 14 went 0-for-30.
2
The rollouts inherit the heuristic's blind spots. The simulation policy plays the quiet parity race essentially blindly, so positions whose whole value is parity are graded wrongly — and more iterations concentrate that bias instead of washing it out (§7). MCTS converges, at practical budgets, to the rollout policy's favourite move, not the position's best move.
3
The improvement over the heuristic is not uniform. In the merged-MCTS region tests on 5×5 midgame positions — positions chosen because the heuristic already played them optimally — MCTS beat the heuristic in 0 of 20 games. Sampled lookahead added value on the E=20 benchmark and subtracted it there. A method that sometimes talks you out of correct moves is not a safe drop-in upgrade.
4
It cannot beat exact play where exact play exists. Inside the Allcock domain the formula is already optimal; MCTS can only tie it, and only once its estimates happen to agree.

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.

Built from your own measured experiments — benchmark numbers, case values, and failure modes are from the dots-and-boxes MCTS work described above, not generic textbook figures. Diagrams are schematic; UCT arithmetic in §3 is exact for the stated inputs.

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.

Advanced only · Step 2 of the cascade

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.

Code: SolverCutoff.jsGate: GateModel.jsAdvanced only5-second solve budgetExact when it completes
01 · The big idea

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.

value(position) = future boxes for player to move − future boxes for opponent

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.

GeneralUnlike Allcock, minimax can start before the board is decomposed and can handle opened chains, singletons, and irregular shapes.
AdversarialIt does not assume the opponent will cooperate or follow the heuristic. Every reply is chosen to minimise the mover's eventual differential.
Potentially enormousThe number of line sequences grows exponentially. The rest of this part is about how production keeps that cost usable without pretending it has disappeared.
What this step repairs, method by method. Against the heuristic (Part II): no fixed control rule and no smallest-area proxy — the actual lines are priced, so the case 19 opening, the case 20 double cross, and the case 18 parity token are all decided by value. Against Allcock (Part III): no domain — minimax plays before decomposition and with opened, short, or token components on the board. Against MCTS (Part IV): no samples and no rollout policy in the decision — a completed search's value is the game's value, not an estimate converging on the rollout policy's favourite.
02 · The search

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.

1
Generate the untaken lines. Capturing moves are considered before non-capturing moves, which usually produces strong bounds early and lets pruning work sooner.
2
If a line closes a box, add the boxes and keep the turn. A line can close one box, or two if it is the shared last edge of two 3-sided boxes. The child position is evaluated for the same player, and the closed boxes are added to its value.
3
If a line closes nothing, flip the turn and negate. The child's value is from the opponent's point of view, so the parent uses its negative.
4
Keep the maximum. At each node the player to move chooses the line with the best eventual differential for themselves.

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.

The value is a differential, not a win probability. A value of +4 means the player to move should gain four more boxes than the opponent from the unclaimed boxes under optimal play. It does not include the current score.

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
03 · Efficiency

Three ways the solver avoids repeating itself

Shared transposition tableThe same board can be reached by playing independent lines in different orders. One table is shared across all root moves in a solve. Entries are bound-typed — exact, lower bound, or upper bound — according to the search window that produced them, so a pruned result is never mistaken for an exact value.
Macro-entry filteringFor a cascade unit of at least 3 ripe boxes, different pure entry lines lead to equivalent subtrees. The solver generates only one canonical entry for such a unit. Units of 1 or 2 boxes keep every entry, because there the equivalence fails.
Captures firstRoot and interior moves that close boxes are searched before quiet lines. Good moves found early tighten the alpha-beta window and prune more of the remaining tree.

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.

04 · The key shortcut

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.

Search by linesWhile the position still contains 0- or 1-sided boxes, expand individual legal lines.
→
Fully decomposed nodeStop expanding. Extract the chains, loops, singletons, and other components.
→
Component evaluatorReturn the exact value of that decomposed tail and plug it directly into the line search.

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
The cutoff is not a heuristic leaf evaluation. The solver does not stop at an arbitrary depth and guess. It stops only when the remaining position belongs to a class that a separate exact method can price completely.

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.

05 · Admission control

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 groupExamples
Raw sizeEmpty lines and unclaimed boxes.
Distance to decompositionD*: 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 capturesMoves touching no low-sided box, free moves that close a box, and the number of boxes taken by a greedy forced-capture run.
Shape statisticsVariance 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.

Production uses only one threshold: 1,000 predicted seconds. If the prediction is at least 1,000 laptop-scale seconds, Advanced skips minimax and plays the heuristic immediately. Below that, it attempts the search. The 1,000 seconds is not the time budget — it is a hopelessness screen chosen because trying and salvaging still has value on many positions the equation expects to be slow.

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
06 · Bounded search

The 5-second clock, the heuristic floor, and salvage

1
Draw the heuristic move first. Before searching, AIEngine asks the heuristic from Part II what it would play.
2
Score that move as a floor probe. The solver evaluates the heuristic's root move first and holds its exact value aside. The probe does not change the standard root order or the move a completed search returns.
3
Search the root moves under a flat 5-second budget. Captures are considered before other lines. Root moves are scored one at a time with the shared transposition table.
4
If time expires, salvage the best fully scored move. The result is the better of the heuristic floor and the best root move completed before the deadline. A salvaged move's own value is exact, but the choice is not proven optimal because other root moves may not have been scored.
5
If nothing was scored, use the heuristic. When neither the floor probe nor any root move completes before the abort, the search contributes no move and the cascade falls through to Step 3.

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
Five seconds is a budget, not an absolute physical guarantee. The deadline is checked as the search moves between nodes. A component-evaluator call at a decomposition cutoff is not itself deadline-checked; the worst recorded call is about 0.2 seconds, so one solve can overshoot by roughly that amount. It is not correct to promise that every Advanced move returns within exactly 5.000 seconds.
07 · Decision outcomes

What Advanced may actually play

OutcomeMove playedStatus
Gate screens the position outHeuristic moveNo search was attempted.
Search completesRoot move with the highest exact valueExact optimal
Search aborts with a floor or completed root moveBetter of the floor and best completed root moveSalvage — value exact, choice unproven
Search aborts with nothing completedHeuristic moveSearch 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.

08 · Measured effect

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.

ComparisonResultReading
Intermediate vs Advanced — 76 gamesAdvanced 68 · Intermediate 6 · ties 2The 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/26Search 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.

09 · Limits

What minimax does not solve

Start with the clean statement: a completed minimax search makes no suboptimal move. Every suboptimal move attributed to Advanced enters through the production wrappers around the search — the gate declining to start it, the clock stopping it, or the fallback playing instead — never through the search's own arithmetic. The four limits below are all of that kind.
Exponential worst cases remainPruning, transpositions, macro filtering, and the decomposition cutoff reduce the work, sometimes dramatically. None changes the fact that hard positions can explode combinatorially.
The gate can be wrong in both directionsIt can screen out a position whose 5-second salvage would have helped, or admit a position that consumes the whole budget without completing a useful root move.
A cap makes the result partialSalvage is principled — it uses only fully scored root moves and never falls below the heuristic floor when that floor was scored — but it is not a proof that the played move was best.
Big-board openings are still the frontierLowering the gate threshold is not the missing lever. The opening positions are too large for exhaustive line search under a normal move budget; progress would need a stronger leaf evaluator, a much longer budget, or a different method.
10 · Placement

Minimax in the cascade and in this guide

MethodWhere it appearsWhat kind of answer?
Part II — HeuristicAll levels, Step 3; also Advanced's Step 2 floorFast local rules; no search and generally no exact value.
Part III — AllcockIntermediate and Advanced, Step 1Exact formula for a restricted class of fully decomposed positions.
Part IV — MCTSNo current levelSampling and statistics, not the deterministic exact search described here.
Part V — MinimaxAdvanced only, Step 2Exact 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.