cd /news/developer-tools/snooker-s-referee-lives-in-one-varia… · home › topics › developer-tools › article
[ARTICLE · art-179219] src=dev.to ↗ pub= topic=developer-tools verified=true sentiment=↑ positive

Snooker's referee lives in one variable: building the rules engine for a browser snooker game

A developer built a snooker rules engine in JavaScript (snooker-core.js, about 825 lines, shared by Node and the browser) for a browser-based snooker game, modeling the game's state machine as a single field, state.on, that tracks which ball is legally on. The engine derives legal first contacts from that field, treats the first colour the cue ball hits as the nominated ball, re-spots potted colours in the standard order, and prices fouls at the maximum of 4, the ball on, the ball hit first, and any illegally potted ball. The game deliberately departs from match rules, using 10 reds instead of 15.

key takeaway

Modeling a snooker referee as a single state.on field (red, colour, individual colours, or any) lets every rule question reduce to what was on when the cue ball moved, with fouls priced at the max of 4, the ball on, the first ball hit, and any illegally potted ball.

by read7 min views5 publishedDec 1, 2026

A quick confession first: the "full frame" of snooker on mympgames.com uses 10 reds, not 15. That's one of a handful of deliberate departures from match rules, and I'll list them all at the end.

The 8-ball and carrom posts already covered the shared setup (deterministic physics, a server-side referee, a bot that tests ideas with the real simulation), so I'll skip it. What's specific to snooker is that the ball you're allowed to hit changes after every pot, a foul costs a different amount depending on what you hit, potted colours come back, and a frame can finish level.

Everything below comes from snooker-core.js (about 825 lines, shared by Node and the browser) and snooker-ai.js (about 190 lines).

state.on The whole state machine is one field, state.on:

'red': a red is on'colour': a red was just potted, so any colour is on'y' 'g' 'n' 'b' 'p' 'k': the reds are gone and the colours go in order'any': the race variants, where every ball is on Almost every rule question becomes "what was on when the cue ball moved?" The legal first contacts follow directly from it:

function onBalls(state) {
  const live = state.balls.filter((b) => b.on && b.c !== 'w');
  if (state.on === 'any') return live;
  if (state.on === 'red') return live.filter((b) => b.c === 'r');
  if (state.on === 'colour') return live.filter((b) => b.c !== 'r');
  return live.filter((b) => b.c === state.on);
}

When a turn ends, on goes back to 'red' if any reds are left, otherwise to the lowest colour still on the table. That covers both the alternation and the colours-in-order phase.

In real snooker you nominate a colour after potting a red. Rather than putting a menu in front of every colour shot, the engine treats the first colour the cue ball hits as the nominated ball:

if (wasOn === 'red') legalFirst = firstC === 'r' || (wasFree && firstC !== 'r');
else if (wasOn === 'colour') legalFirst = firstC !== 'r';
else legalFirst = firstC === wasOn || (wasFree && firstC !== 'r');

const isLegalPot = (b) => {
  if (wasOn === 'red') return b.c === 'r' || b.id === freeId;
  if (wasOn === 'colour') return first && b.id === first.id; // pot what you hit
  return b.c === wasOn || b.id === freeId;
};

Hit the blue and pot the pink, and it's a wrong-pot foul, just as if you'd called blue out loud. The price is that you can't play a called plant (nominate the black, cannon it into the pink). When a red is on, several reds in one shot all count, 1 point each.

While reds remain, a potted colour is re-spotted: on its own spot if it's free, otherwise on the highest-value free spot, otherwise as close as possible behind its own spot. The code follows that order almost word for word:

function respot(balls, ball) {
  const others = balls.filter((b) => b.id !== ball.id);
  const own = SPOTS[ball.c];
  const tryAt = (x, y) => (overlaps(x, y, others, ball.id) ? null : { x, y });
  let p = tryAt(own.x, own.y);
  for (let i = COLOURS.length - 1; i >= 0 && !p; i--)   // black's spot first, then down
    p = tryAt(SPOTS[COLOURS[i]].x, SPOTS[COLOURS[i]].y);
  for (let step = 1; !p && step < 400; step++) {        // then slide along the spot line
    p = tryAt(own.x + step * 2, own.y);
    if (!p) p = tryAt(own.x - step * 2, own.y);
  }
  ball.x = p ? p.x : own.x; ball.y = p ? p.y : own.y; ball.on = true;
}

(The real function also guards the cushion edge.)

Foul points go to the opponent. The value is the highest of 4, the value of the ball on, the ball hit first, and any ball potted illegally. The engine names the foul (miss for no contact at all, then wrong-ball, wrong-pot, in-off) and prices it:

let pen = Math.max(4, onVal);                 // onVal: red = 1, 'colour' = 0
if (first) pen = Math.max(pen, VALUE[firstC]);
for (const b of bad) pen = Math.max(pen, VALUE[b.c]);
if (wasOn !== 'red' && wasOn !== 'colour')
  for (const b of potted) pen = Math.max(pen, VALUE[b.c]);
state.scores[opp] += pen;

So hitting the pink first with a red on costs 6, and an in-off on the black costs 7. Colours potted on a foul are re-spotted, except a final black, which settles the frame.

What's missing: there's no miss rule in the referee's sense (replace the balls, make the offender play again), and no option to send your opponent back to the table after a foul. The turn just passes. It's the biggest gap from match snooker, and the first opt-in rule I'd add.

After a foul, if the incoming player is snookered, they get a free ball: they can nominate any colour as the ball on. The rules define snookered as being unable to hit both extreme edges of any ball on in a straight line, so that's exactly what the code tests:

for (const t of onBalls(state)) {
  const d = Math.hypot(t.x - cue.x, t.y - cue.y) || 1;
  const px = (-(t.y - cue.y) / d) * (2 * R - 1);   // offset to each edge of the target
  const py = ((t.x - cue.x) / d) * (2 * R - 1);
  if (segClear(cue.x, cue.y, t.x + px, t.y + py, state.balls, [cue.id, t.id]) &&
      segClear(cue.x, cue.y, t.x - px, t.y - py, state.balls, [cue.id, t.id])) return false;
}
return true; // snookered

If they are, state.freeBall is set. The legality code then accepts a colour as first contact, and potting it scores the value of the ball on (1 for a red) before the colour is re-spotted. The check is skipped when the cue ball is in hand, since the player is placing it in the D anyway.

A normal frame ends when the table is clear. If the scores are level, the black is re-spotted, on becomes 'k', and the cue ball goes in hand. The first pot or foul after that decides the frame. The official rules toss a coin for who plays first. Here the shot goes to the opponent of the player who cleared the table, which is predictable but simple.

The table is full size in millimetres (3569 × 1778, ball radius 26.25). The middle pockets have slightly smaller capture circles than the corners, and the cushion code knows where each rail stops, so a ball can run into the jaws. Simulation runs at a fixed 400 Hz with sliding/rolling friction. The server sends the shot inputs and a short hash of the final positions, and each browser replays the shot and compares the hash.

The table is about 40% longer than the 8-ball table, so shots are long and frames are too. Ten reds keeps a frame closer to browser-session length, and it costs you the famous 147: the maximum here is 107. There's also a 6-red variant and two races (first to 50 or 100) with one red worth 10 that respots like a colour.

The computer aims a ghost ball at every (ball on, pocket) pair. It drops cuts that are too thin and shallow angles into the middle pockets, runs each candidate through the real simulation, and scores the outcome:

So it will play safe rather than force a low-percentage pot. The top few shots are then re-simulated with a small aim and power wobble, and it prefers shots that still work when slightly off. Easy, Medium and Hard differ in how many shots they simulate, whether they try screw and follow, and how much noise goes into the final strike.

If you play snooker, tell me which of these bothers you most. You can play a frame at https://mympgames.com/play/snooker against the computer, on one device, or with a friend using a room link, and the rest of the 60+ free multiplayer games are at https://mympgames.com.

── more in #developer-tools 4 stories · sorted by recency
── more on @mympgames.com 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/snooker-s-referee-li…] indexed:0 read:7min 2026-12-01 · —