Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0 ๐Ÿ“– 6 min read

Bar, blots and the larger-die rule: how I coded backgammon in JavaScript

A player once told me my backgammon was broken because it wouldn't let them play their 2. They were right that it wouldn't. They were wrong that it was broken. With that roll, the only way to use both dice was 6 first, a

A player once told me my backgammon was broken because it wouldn't let them play their 2. They were right that it wouldn't. They were wrong that it was broken. With that roll, the only way to use both dice was 6 first, and the rules say you have to use both dice if you can.

That rule, and a few like it, made backgammon take longer than games that look far harder. Here's how I coded the rules for the backgammon on mympgames, my free multiplayer browser arcade. Everything lives in one plain file, backgammon-rules.js. The server uses it to judge legality, and the browser loads the same file in a Web Worker for the bot. Excerpts are real code, lightly trimmed.

25 numbers and a sign

A position is a small object:

{ points: [/* 25 ints */], bar: [0, 0], off: [0, 0], turn: 0 }

points[1] through points[24] are the board (index 0 isn't used). Positive numbers are White checkers and negative numbers are Black. The starting position is eight assignments, p[24] = 2, p[13] = 5, p[8] = 3, p[6] = 5, plus the mirrored negatives for Black.

Direction is a lookup table, not an if:

const DIR = [-1, 1];      // White runs 24 รขโ€ โ€™ 1, Black runs 1 รขโ€ โ€™ 24
const BAR_FROM = [25, 0]; // where each side "starts" when entering
const OFF = [0, 25];      // where each side's borne-off checkers go

I copied the bar convention from GNU Backgammon: White's bar is point 25 and Black's is point 0. Entering is then a normal move from just past the end of the board: White entering with a 4 lands on 25 - 4 = 21. One formula, from + DIR[player] * die, covers everything.

One step at a time: tryStep

Every rule about one checker moving one die lives in one function, which returns a new position or null:

Bar first. If you have a checker on the bar, nothing else moves:

if (pos.bar[player] > 0 && from !== barFrom) return null;

No landing on a made point. Two or more enemy checkers block a point:

function blocked(pos, point, player) {
  return nAt(pos, point, player ^ 1) >= 2;
}

If both entry points are blocked, you have no legal play, and the engine passes the turn for you.

Hitting a blot. If exactly one enemy checker sits on the destination, it goes to the bar:

if (nAt(next, to, player ^ 1) === 1) {
  next.points[to] = 0;
  next.bar[player ^ 1] += 1;
  hit = true;
}
next.points[to] += sign;

Because of the sign trick, "clear the point and add my checker" is two lines, whichever colour is moving.

Bearing off has three conditions

The bear-off branch is the one I rewrote the most:

if (goingOff) {
  if (!canBearOff(pos, player)) return null;           // all 15 home, none on the bar
  const dist = player === WHITE ? from : 25 - from;
  if (die < dist) return null;                         // not enough to get off
  if (die > dist && !isHighestHome(pos, player, from)) return null;
  off = true;
}

The last line is the rule people forget. A 6 can bear off a checker from your 4-point, but only if nothing is sitting on your 5 or 6. Otherwise you have to move one of those back checkers instead. isHighestHome scans the higher points of your home board to check.

canBearOff is strict in a simple way. Any checker outside your home board, or on the bar, blocks bearing off completely. If you get hit while bearing off, you have to come all the way around again before taking any more checkers off. Real rule. It hurts.

Doubles, and the "use both dice" rule

Doubles are handled before any search starts:

function expandDice(dice) {
  if (dice.length === 2 && dice[0] === dice[1]) return [dice[0], dice[0], dice[0], dice[0]];
  return dice.slice();
}

After that, a turn is a list of dice to use. genPlays is a small recursive search. It tries every distinct die from every legal starting point, recurses with the remaining dice, and records the sequence when it runs out of dice or gets stuck. For a non-double that means both orders, 6-then-2 and 2-then-6, which is exactly what my confused player needed.

The forced-move rules then become filters on that list:

const maxLen = raw.reduce((m, p) => Math.max(m, p.steps.length), 0);
let best = raw.filter((p) => p.steps.length === maxLen);

if (dice.length === 2 && dice[0] !== dice[1] && maxLen === 1) {
  const hi = Math.max(dice[0], dice[1]);
  const withHi = best.filter((p) => p.steps[0].die === hi);
  if (withHi.length) best = withHi;
}

The first filter says you must use as many dice as you can. That includes doubles, where three playable 5s means you must play three. The second filter is the larger-die rule: if you can only play one die, it has to be the bigger one when that's possible. If only the smaller one fits, withHi is empty and the smaller die is allowed. I don't check rules move by move; I generate every full turn and discard the illegal ones.

The server only accepts whole turns

The client sends its whole sequence of steps, and the server checks it against that list:

const found = B.findPlay(state.pos, state.dice, steps, playerIndex);
if (!found) return { ok: false, error: 'Illegal move' };

findPlay matches a key like 13:7:6|7:5:2 against every legal play. Skipping a turn when a move exists returns Must move. The server also rolls the dice with crypto.randomInt(1, 7). Clients never send dice, so nobody can roll themselves double sixes.

The opening roll follows the real rule: ties are rerolled and the higher roller plays both dice.

Winning: single, gammon, backgammon

if (pos.off[o] > 0) return { winner: w, kind: 'single', mult: 1 };
const inWinnerHome = pos.bar[o] > 0 || rangeHas(pos, o, /* winner's home */);
if (inWinnerHome) return { winner: w, kind: 'backgammon', mult: 3 };
return { winner: w, kind: 'gammon', mult: 2 };

The points scored are cube * mult. The doubling cube is in the game. You can only offer it before you roll and only if you own it (or nobody does yet). Taking doubles the cube and gives the taker ownership. Dropping loses the game at the current cube value. The match variants (to 3 or 5 points) also apply the Crawford rule. The game played right after someone reaches match point minus one has no doubling at all, and the server rejects a double with "Crawford รขโ‚ฌโ€ no doubling".

The bot

backgammon-ai.js runs in a browser Web Worker, so the board stays responsive. Four levels:

  • Beginner plays a random legal move.
  • Easy plays a random move 40% of the time and a heuristic move the rest of the time.
  • Medium picks the legal play with the best static evaluation.
  • Hard looks one roll ahead. For each candidate play it goes through all 21 distinct rolls, weighted by probability (1/36 for doubles, 2/36 otherwise), assumes the opponent answers each one with their best greedy reply, and averages the result.

The evaluation is a hand-tuned mix: pip difference รƒโ€” 10, checkers off, checkers on the bar, a blot penalty based on enemy checkers within six pips, and bonuses for made points and primes. On hard it will offer the cube when its evaluation is high and it leads the race by more than 20 pips. It won't double past 8 and never doubles during the Crawford game.

It's a decent casual opponent. Strong players will beat it; it has no sense of timing or back games.

What I'm not proud of (yet)

  • Brute-force move generation. Doubles can produce a lot of four-step sequences. I dedupe by step sequence, not by final position, so two orders that land in the same place both stay in the list. Hard mode evaluates every one across 21 rolls.
  • Hand-tuned weights. Tuned by feel; a small trained network would beat them.
  • A tiny dice quirk. The browser fallback rollDie uses rejection sampling on crypto.getRandomValues, and writing this post I noticed its cutoff is off by a couple of values. The bias is about one in a billion and multiplayer dice come from the server anyway, but it's on my list.
  • No Jacoby rule, no beavers. Gammons always count, even with the cube in the middle. Correct for match play, a simplification for money games.

What I'd keep is the shape: one pure rules file, a generator for every legal full turn, and a server that only accepts turns from that list. Since then, most bug reports have been about the UI, not the rules.

You can try it at mympgames.com/play/backgammon against a friend or the bot, and find the rest of the arcade at mympgames.com.

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.