DEV Community

My MP Games
My MP Games

Posted on

Three sides is a gift: how I coded Dots & Boxes in 93 lines for a multiplayer browser game

Dots & Boxes is the game most of us first played on the back of a school notebook. Two players take turns drawing a line between two neighbouring dots. If your line closes the fourth side of a box, you write your initial in it and you must move again. When every box is claimed, whoever owns more boxes wins.

On mympgames, my free arcade of 60+ multiplayer browser games, the whole Dots & Boxes rule engine is one 93-line server module. This post walks through how it is put together: how the grid is stored, how one line can close two boxes at once, the "move again" rule, and the simple bot that plays when you don't have a friend online. I'll also be honest about where the bot is weak, because that weakness is exactly what makes the game interesting.

The contract every game follows

Every game on the site exports the same four things: meta, createState, onAction and publicState. The room server handles sockets, seats and turn timers. The game module only knows the rules. Here is the meta for this one:

const meta = {
  id: 'dots-boxes',
  name: 'Dots & Boxes',
  blurb: 'Claim lines, close boxes, own the grid.',
  players: 2,
  tags: ['turn-based', 'classic'],
};
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

Players are plain indexes, 0 and 1, so "the other player" is always 1 - turn. That little choice shows up again and again and keeps the code short.

Storing lines, not dots

The first design question in any Dots & Boxes implementation is what to store. The dots never change, so they don't need to be in the state at all. What changes is the lines and who owns each box.

The board is a 4x4 grid of boxes, which means 5x5 dots. That gives two kinds of lines:

  • Horizontal lines: 5 rows of them, 4 per row.
  • Vertical lines: 4 rows of them, 5 per row.
const GRID = 4; // 4x4 boxes => 5x5 dots

function createState() {
  const n = GRID;
  return {
    n,
    hLines: Array.from({ length: n + 1 }, () => Array(n).fill(null)),
    vLines: Array.from({ length: n }, () => Array(n + 1).fill(null)),
    boxes: Array.from({ length: n }, () => Array(n).fill(null)),
    scores: [0, 0],
    turn: 0,
    winner: null,
  };
}
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

Keeping horizontal and vertical lines in two separate arrays sounds fussy, but it makes indexing almost free. Box (r, c) is surrounded by exactly four lines:

  • top: hLines[r][c]
  • bottom: hLines[r + 1][c]
  • left: vLines[r][c]
  • right: vLines[r][c + 1]

So checking whether a box is closed is a single expression:

function boxComplete(state, r, c) {
  return (
    state.hLines[r][c] != null &&
    state.hLines[r + 1][c] != null &&
    state.vLines[r][c] != null &&
    state.vLines[r][c + 1] != null
  );
}
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

A line stores the index of the player who drew it, not just true. The rules don't need that, but the client uses it to colour lines by player, which makes the board much easier to read after a long chain of moves.

One line, up to two boxes

Every line borders at most two boxes. A horizontal line sits between the box above it and the box below it. A vertical line sits between the box to its left and the box to its right. Lines on the outer edge only touch one box.

That is the whole trick of onAction: after drawing a line, check the one or two neighbouring boxes and claim any that just closed.

if (orient === 'h') {
  if (r < 0 || r > n || c < 0 || c >= n) return { ok: false, error: 'OOB' };
  if (state.hLines[r][c] != null) return { ok: false, error: 'Taken' };
  state.hLines[r][c] = playerIndex;
  if (r > 0 && boxComplete(state, r - 1, c) && state.boxes[r - 1][c] == null) {
    state.boxes[r - 1][c] = playerIndex;
    claimed++;
  }
  if (r < n && boxComplete(state, r, c) && state.boxes[r][c] == null) {
    state.boxes[r][c] = playerIndex;
    claimed++;
  }
}
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

The vertical branch is the mirror image, with c - 1 and c instead of r - 1 and r. The r > 0 and r < n guards handle the edges, so the top row of lines never looks for a box above the board.

Closing two boxes with one line is a real move in this game, and players love it. Because the code counts claimed instead of using a boolean, a double close simply scores 2.

Validate everything on the server

Before any of that runs, onAction rejects anything that isn't a legal move:

if (state.winner != null) return { ok: false, error: 'Game over' };
if (playerIndex !== state.turn) return { ok: false, error: 'Not your turn' };
if (action.type !== 'line') return { ok: false, error: 'Invalid action' };
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

plus the bounds check and the "line already taken" check you saw above. The browser never decides whether a move is legal. It sends { type: 'line', orient, r, c } and draws whatever state comes back. In a game where two people can tap the same line at nearly the same moment, this matters: whoever's message reaches the server first while it is their turn gets the line, and the other click is simply refused.

The "move again" rule

This is the rule that turns a children's game into a strategy game, and it is two lines of code:

state.scores[playerIndex] += claimed;
const totalBoxes = n * n;
const filled = state.scores[0] + state.scores[1];
if (filled >= totalBoxes) {
  if (state.scores[0] > state.scores[1]) state.winner = 0;
  else if (state.scores[1] > state.scores[0]) state.winner = 1;
  else state.winner = -1;
} else if (claimed === 0) {
  state.turn = 1 - state.turn;
}
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

The turn only passes when you claimed nothing. If you closed a box, turn stays the same and you go again. That is what lets one player sweep a whole chain of boxes in a single turn.

The end check uses the scores rather than scanning the board: every box is owned by somebody, so when the two scores add up to 16 the grid is full. A 4x4 board has an even number of boxes, so a draw is possible, and it is stored as winner = -1. The room layer already knows how to show a draw for other games, so nothing special was needed here.

What the client sees

publicState returns copies of the arrays, never the live state:

function publicState(state) {
  return {
    n: state.n,
    hLines: state.hLines.map((r) => [...r]),
    vLines: state.vLines.map((r) => [...r]),
    boxes: state.boxes.map((r) => [...r]),
    scores: [...state.scores],
    turn: state.turn,
    winner: state.winner,
  };
}
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

There is no hidden information in Dots & Boxes, so both players and any spectators get the same view. Copying is a cheap habit that stops a later bug where something mutates a broadcast object and quietly changes the real game.

The bot, and why "three sides" is a gift

When you play alone, a bot takes the other seat. Its policy is deliberately short:

// Prefer moves that complete a box
for (const line of lines) {
  const trial = JSON.parse(JSON.stringify(state));
  // ...draw the line on the copy, check the neighbouring boxes...
  if (completes) return { type: 'line', ...line };
}
return { type: 'line', ...pick(lines) };
⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026 ⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026

It lists every free line, tries each one on a copy of the state, and takes the first one that closes a box. If nothing closes a box, it plays a random free line.

That makes it greedy, and greedy is beatable. The bot never checks whether its random line draws the third side of a box. A third side is a gift to your opponent: they close the box and move again. On a 4x4 board that often starts a chain, and a human who has noticed this can feed the bot a single box and then take a long chain back.

Real Dots & Boxes strategy goes much deeper. Strong players count long chains and use the "double-cross": deliberately leave the last two boxes of a chain for the opponent so they have to open the next chain. None of that is in the bot today, and that is a tradeoff I'm comfortable with for now. A casual bot that grabs free boxes and otherwise plays loosely gives new players a fair game and lets them discover the chain idea for themselves. A future version could do one cheap thing first: avoid any line that makes a third side while safe lines still exist. That single rule would make it noticeably tougher without any search.

The JSON.parse(JSON.stringify(state)) copy is not elegant, but with at most 40 lines on the board it costs nothing, and it keeps the bot from ever touching the real state.

Tradeoffs in short

  • Two line arrays instead of one: slightly more code, much simpler box lookups.
  • Score-based end check: no board scan, and it can't disagree with the board.
  • Claimed count, not a boolean: double closes score correctly for free.
  • Greedy bot: friendly for beginners, easy to beat once you understand chains.
  • Fixed 4x4 grid: games last a few minutes, which suits playing with a friend on a break. GRID is one constant if I ever add bigger boards.

Try it

If you want to see how long you last against the greedy bot, or test the double-cross on a friend, play Dots & Boxes here: https://mympgames.com/play/dots-boxes . The rest of the 60+ free multiplayer games are at https://mympgames.com .

Top comments (1)

⚡ Match Highlights: mympgames/three sides is a gift how i coded dots boxes in lines for a multiplayer browser game he - Info Live Streaming 2026
 
userxnom profile image
Abdullah Naseer •

The decision I keep coming back to is storing lines, not dots — and storing the player index in each line instead of a boolean. That one choice quietly buys you three things: boxComplete becomes a single expression, the client gets player-coloured lines for free, and a double close scores 2 without any special case. It's a lovely example of the data model doing the work that conditionals would otherwise have to do.

The score-based end check is the same kind of thinking: deriving "game over" from scores that can only ever sum to the total number of boxes means the end condition can never disagree with the board. No board scan, no second source of truth to drift.

And the bot section is honest in the best way — a greedy bot that never checks whether its random line hands over a third side is exactly the kind of weakness that teaches the game. "Three sides is a gift" is a perfect name for it, because the moment a player learns to spot the gift, the game changes from taking lines to setting traps.

Have you tried a next-step bot that at least refuses to give a third side when a safe line exists? I'm curious how much stronger it would feel, and whether you'd then need chain counting and the double-cross to keep it beatable — or whether just avoiding the gift would already be enough to make beginners sweat.