webdevpuneet.com

Dots and Boxes Game: Play vs CPU or a Friend (Free)

Dots and Boxes Game · Games · Plain HTML, CSS & JS · Live preview

CategoryGames

About this UI Snippet

Dots and Boxes: A Line-Based Grid, an Extra-Turn Rule and a CPU That Solves the Endgame

Screenshot of the Dots and Boxes Game snippet rendered live

Dots and Boxes is a pencil-and-paper classic: two players take turns drawing one line between two neighbouring dots, and whoever draws the fourth side of a box claims it, marks it and goes again. This snippet is a complete version in plain HTML, CSS and JavaScript on an inline SVG board, with three board sizes (3×3, 4×4 and 5×5 boxes), a computer opponent on three levels, a two-player mode on one screen, undo, hints and a win record that is kept in the browser.

The game state is the lines, not the cells

Most grid games store a value for every cell. Here the lines between dots are what players take, so the state is one array of lines (horizontals numbered first, then verticals) plus a counter of how many sides each box has. buildGeometry() creates the line list and, for each box, its four lines (top, bottom, left, right); each line also remembers the one or two boxes it touches. Taking a line adds one to those boxes' counters, and a counter that reaches four means the box is closed and belongs to the player who took the last side. A line shared by two boxes can close both at once.

The extra-turn rule

Closing a box gives the same player another move, and the turn only passes after a move that closes nothing. That single rule creates the whole strategy of the game: drawing a box's third side hands the opponent a box and another turn. doMove() returns the list of boxes the move closed, and the turn switches only when that list is empty.

A computer player in three levels

Easy takes a box some of the time and otherwise plays a random line, so it makes mistakes you can punish. Medium always takes a box when one is available, otherwise plays a line that gives nothing away (no box reaches three sides), and when every line gives something away it picks the line that gives away the fewest boxes. Hard plays like Medium until 18 or fewer lines are left, then switches to an exact solver. The solver treats the remaining lines as the bits of a number, scores every position once with a memo table (my boxes minus yours, with the extra-turn rule), and picks the best line. Because it searches the real rules, it finds the "double-cross" sacrifice (leaving the opponent two boxes to keep control of the rest of a chain) without that strategy being coded in. On the 3×3 board that means Hard plays almost perfectly from about the middle of the game.

Built to feel good

The board is built once and moves only change classes, so lines draw themselves with a stroke animation, boxes pop in with the owner's letter, the last line played is thickened, and the hover colour matches whose turn it is. Each line has a wide invisible hit line on top of the thin visible one, so it is easy to tap on a phone, and every line is also reachable with the keyboard (Tab, then Enter or Space). Undo restores a saved copy of the state, and Hint asks the Hard solver for a good move and flashes it. Sound effects are made with the Web Audio API and can be muted.

What's included

Features

Full Dots and Boxes rules on an SVG board, with 3×3, 4×4 and 5×5 box sizes
Line-based state (lines plus a side counter per box) that handles a line closing two boxes at once
Extra turn for every box closed, shown by a "Go again" message
Three CPU levels, with Hard switching to an exact endgame solver (bitmask search with a memo table)
Two-player mode on one screen, with Player 1 and Player 2 labels
Undo and a Hint button that flashes a strong move
Animated lines and boxes, last-move highlight and a hover colour that follows the turn
Keyboard-playable lines (Tab, Enter or Space) and wide hit targets for touch
Won, lost and drawn record per difficulty and size, and the settings, saved in localStorage
Synthesised sound effects (Web Audio) with a mute button, no audio files

Step by step

How to Use

  1. 1
    Choose how to playPick vs CPU or 2 players, a difficulty (Easy, Medium or Hard for the CPU) and a board size (3×3, 4×4 or 5×5 boxes). Changing a setting starts a new game.
  2. 2
    Draw a lineClick or tap the gap between two neighbouring dots. The line is drawn in your colour, and the last line played is highlighted so you can follow the game.
  3. 3
    Close a box and go againThe player who draws the fourth side of a box claims it, marks it with their letter and plays again. Avoid drawing a box’s third side, because that gives the opponent a free box.
  4. 4
    Use Undo and HintUndo takes back your last move (or the last move in 2-player mode). Hint flashes a strong line, picked by the Hard solver.
  5. 5
    Win the boardThe game ends when every box is claimed, and whoever has more boxes wins. Against the CPU your won, lost and drawn games are kept for each difficulty and size.
  6. 6
    Customise itThe sizes, the EXACT_MAX number (how late Hard starts solving exactly) and the colours are plain constants and CSS values, and the three CPU levels live in one function, chooseMove().

Real-world uses

Common Use Cases

A classic paper game for a games section
A faithful version of a game normally played on graph paper, which fits next to other turn-based games like the Tic-Tac-Toe Game and the Connect Four Game.
Teaching edge-based game state
A clear example of a game whose state lives on the edges between cells rather than in the cells, which is also how many graph and tiling problems are modelled.
A small game-AI ladder to study
Random moves, a greedy-and-safe heuristic and an exact solver with memoisation sit in one function, so you can compare how each level plays.
A pass-and-play game for two on one phone
The 2-player mode and large touch targets make it work as a quick game for two people sharing a screen.
SVG game UI patterns
Building the SVG once and animating by class, wide invisible hit lines over thin strokes, and a stroke-dashoffset draw animation are reusable in any SVG-based game or diagram.

Got questions?

Frequently Asked Questions

That is the real rule of Dots and Boxes. doMove() collects the boxes the move closed, and the turn only passes to the other player when that list is empty. It is also why drawing a box’s third side is a mistake: it lets the opponent close that box and keep playing.

Easy takes an available box 60% of the time and otherwise plays a random line. Medium always takes a box, otherwise plays a line that does not give a box its third side, and when it has to give something away it picks the line that gives away the fewest boxes. Hard plays like Medium until 18 or fewer lines are left and then solves the rest of the game exactly.

It looks at every way the remaining lines can be played, with the extra-turn rule, and scores each position as (my boxes minus your boxes). The remaining lines are the bits of a number, so each position is stored once in a typed-array memo table. This is why Hard finds the double-cross sacrifice, where it leaves you two boxes on purpose to keep control of the rest of a chain.

Yes. A line between two boxes adds a side to both, and if both reach four sides the move closes both. applyMove() returns every box it closed, and each one is scored and animated.

The size buttons set cfg.n, and buildGeometry(n) builds the lines and boxes for any n. To offer 6×6, add a button with data-v="6" and add 6 to the allowed sizes. Hard still solves exactly at 18 or fewer lines left, which is a fast search; with larger boards it plays like Medium for longer.

Each line is drawn twice: a thin visible line and a 22px-wide invisible hit line on top. The hit line takes the clicks, the Enter and Space keys and the focus ring, so a line is easy to tap and reachable with the keyboard.

Copy & paste

Source Code

<div class="db-app">
  <div class="db-header">
    <h2>Dots and Boxes</h2>
    <button class="icon-btn" id="db-mute" type="button" aria-label="Sound on" aria-pressed="false">🔊</button>
  </div>

  <div class="db-stats">
    <div class="stat p1" id="db-card1"><span class="stat-label" id="db-name1">You</span><span class="stat-val" id="db-p1">0</span></div>
    <div class="stat p2" id="db-card2"><span class="stat-label" id="db-name2">CPU</span><span class="stat-val" id="db-p2">0</span></div>
  </div>

  <div class="db-opts">
    <div class="seg" id="db-mode" role="group" aria-label="Opponent">
      <button type="button" data-v="cpu">vs CPU</button>
      <button type="button" data-v="2p">2 players</button>
    </div>
    <div class="seg" id="db-diff" role="group" aria-label="Difficulty">
      <button type="button" data-v="easy">Easy</button>
      <button type="button" data-v="medium">Medium</button>
      <button type="button" data-v="hard">Hard</button>
    </div>
    <div class="seg" id="db-size" role="group" aria-label="Board size">
      <button type="button" data-v="3">3×3</button>
      <button type="button" data-v="4">4×4</button>
      <button type="button" data-v="5">5×5</button>
    </div>
  </div>

  <p class="db-turn" id="db-turn" aria-live="polite">Your turn — pick a line.</p>

  <div class="db-board-wrap">
    <svg id="db-board" class="db-board" viewBox="0 0 320 320" xmlns="http://www.w3.org/2000/svg"></svg>
  </div>

  <div class="db-actions">
    <button class="ghost-btn" id="db-undo" type="button">↶ Undo</button>
    <button class="ghost-btn" id="db-hint" type="button">💡 Hint</button>
    <button class="primary-btn" id="db-reset" type="button">New Game</button>
  </div>
  <p class="db-record" id="db-record"></p>
</div>

Extend with AI

Take This Snippet Further With AI

Paste this snippet's HTML, CSS and JS into an AI assistant like Claude and ask it to explain how the line arrays map to each box's four sides, why the turn passes only when a move closes nothing, and how the exact solver uses a bitmask and a memo table. It is a good base to extend: ask for an online or shared-link two-player mode, a smarter Hard level for 4×4 and 5×5 using chain and loop counting, an animated replay of the finished game, a tournament mode that tracks several rounds, themes or avatars for the players, or a port to a React component with the state in useReducer. Treat it as a working prototype to question and rebuild.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a complete Dots and Boxes game in plain HTML, CSS and JavaScript on an inline SVG board, with no libraries.

Requirements:
- Board sizes of 3x3, 4x4 and 5x5 boxes, chosen with buttons. The board is built once with SVG and moves only change classes.
- Model the game as lines, not cells: one list of lines (horizontals then verticals), a counter of how many sides each box has, and an owner per box. Each line knows which one or two boxes it touches, so a single line can close two boxes at once.
- Two players alternate drawing a line between neighbouring dots. A player who closes a box claims it, shows their letter in it, and plays again; the turn passes only after a move that closes no box. Show a "go again" message.
- Modes: vs CPU and 2 players on one screen. Show a score card for each player with the active player highlighted.
- Three CPU levels. Easy: takes a box 60% of the time, otherwise a random line. Medium: always takes a box if one exists, else a line that does not give a box its third side, else the line that gives away the fewest boxes. Hard: like Medium until 18 or fewer lines remain, then an exact solver using a bitmask of the remaining lines, a typed-array memo table and the extra-turn rule (value = my boxes minus the opponent's), which finds the double-cross sacrifice.
- Undo (restores a saved copy of the state), a Hint button that flashes a strong line, and a New Game button. A line should draw itself with a stroke-dashoffset animation, boxes should pop in, the last line played should be highlighted, and the hover colour should follow whose turn it is.
- Give every line a wide invisible hit line on top of the thin visible one for easy tapping, and make lines reachable with Tab and Enter or Space.
- Save the settings and a won, lost and drawn record for each difficulty and size in localStorage (with try/catch). Add Web Audio sound effects with a mute button.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.