When I added 8-ball pool to mympgames.com, I expected the physics to be the hard part. The balls were moving within a weekend. The rules took much longer: when a foul counts as a foul, who owns which group, and what happens when the 8 drops at the wrong moment.
So I'm going to follow one shot from the moment the cue is released until the next player can aim. Every rule shows up somewhere along the way. All of it lives in pool8-core.js, a UMD module that Node and the browser load unchanged. That turns out to matter.
0. The table, in millimetres
const L = 2540, WT = 1270, R = 28.575; // 9 ft table, 2¼ in balls
const HEAD_X = L / 4; // break from behind this line ("the kitchen")
const VMAX = 5600; // mm/s at full power
const DT = 1 / 400; // fixed 400 Hz step
Because everything is in real units, I could look up friction coefficients and pocket mouth widths and use them as they are.
1. The request: the client only sends intent
The client sends a direction, power (0–1), a spin offset and, when the player has ball in hand, where to put the cue ball. prepareShot normalises and clamps all of it, then validates the placement:
if (state.inHand) {
const p = placeCue(state.balls, shot.x, shot.y, state.kitchen);
if (!p) return { ok: false, error: 'Place the cue ball' };
}
state.kitchen is true only for the break, because you break from behind the head string. After a foul, ball in hand is anywhere on the table. If the requested spot is more than 2 mm from a legal one, the shot is rejected with a clear message instead of the ball being quietly moved.
The computer opponent goes through this same path and produces an ordinary shoot action, so it can't cheat by accident.
2. The strike: velocity plus "slip"
A struck cue ball slides before it rolls, and the spin decides what it does next. Each ball carries a velocity v and a contact-point slip u. When the slip reaches zero, the ball is rolling.
const slip = 1 - 1.25 * sy; // centre = 1, top = -0.25, draw = 2.25
return { vx: ux*v, vy: uy*v, ux: ux*v*slip, uy: uy*v*slip, s: sx*v*0.4 };
Topspin starts with backwards slip, so friction speeds the ball up after contact. Draw starts with a large forward slip, so friction pulls it back. Side spin (s) is a separate value that decays over time and only matters at the cushions.
3. Up to 8,800 fixed steps
simulate steps at 1/400 s and stops after at most 22 seconds of table time. Each step runs four phases, always in this order.
Friction. A sliding solid sphere loses slip 7/2 times faster than it loses velocity:
if (us > STOP_V) { // sliding
const du = 3.5 * SLIDE_A * DT; // SLIDE_A ≈ μ·g = 1962 mm/s²
b.vx -= ex * k; b.ux -= ex * du; // k = SLIDE_A * DT
} else { // rolling
const ns = sp * (1 - ROLL_DAMP * DT) - ROLL_A * DT;
}
Rolling resistance combines a constant deceleration with a small proportional damping. With only the constant term, slow balls stopped abruptly. With only the damping, they crept along for ages.
Pockets, then cushions. My first version did cushions first, so balls bounced off an invisible wall across the pocket jaws. Now pockets are checked first, and the cushion code skips the part of each rail that spans a pocket mouth (130 mm at the corners, 128 mm at the sides).
Cushions reflect the ball with a restitution of 0.8 and apply a side-spin kick along the rail. That's what makes running and check side work.
Ball-to-ball pairs are resolved in a fixed i < j order. The code pushes overlapping balls apart, applies a normal impulse (restitution 0.95), and then a small, capped tangential "throw" impulse that includes side spin. Without throw, slow cut shots felt wrong to anyone who plays real pool.
Along the way the simulator records firstHit, railAfter (rail contacts after first contact) and railBalls (how many distinct object balls touched a rail). The referee needs all three.
4. The referee: applyShot
Once every ball has stopped, fouls are checked in a fixed order, and a scratch overrides everything else:
if (!first) foul = 'miss';
else if (!wasBreak && !legalFirstSet.has(first.id)) foul = 'wrong-ball';
if (!foul && wasBreak && !potted.length && sim.railBalls < 4) foul = 'break';
if (!foul && !wasBreak && !potted.length && !(sim.railAfter > 0)) foul = 'no-rail';
if (cueIn) foul = 'scratch';
legalFirstSet comes from onBalls. On an open table you can hit anything except the 8. Once groups are assigned you have to hit your own group first. Once your group is cleared, the 8 is the only legal first contact.
- Break: to be legal, the break has to pot a ball or send at least four object balls to a rail. If the 8 goes down on the break it is re-spotted, not counted as a loss, and the table stays open.
- Open table: the first legal pot assigns groups. If a solid and a stripe both drop, I sort the pocket events by simulation step and the earlier one decides. A pot on a foul shot assigns nothing.
- Turn: you keep shooting if you legally pot at least one of your own balls. Potting only an opponent's ball passes the turn.
- Fouls: the turn passes and the opponent gets ball in hand anywhere.
-
The 8:
wasOnEightis computed before the shot. Potting the 8 when you were already on it, without a foul, wins. Potting it early loses, and so does scratching on it. Potting your last group ball and the 8 in the same stroke also loses, simply because of the order things are evaluated in. A unit test covers that case.
One rule I skipped on purpose is calling the pocket. On a phone, an extra "tap a pocket" step before every 8-ball shot was more annoying than the slop it prevents.
5. The broadcast: inputs and a hash, not frames
The server doesn't stream ball positions. It stores the starting position, the cue parameters and a fingerprint of the result:
state.lastShot = { id, seat, start, cue: prep.cue, durMs: sim.durMs,
check: C.endCheck(sim), summary };
state.phase = 'moving';
state.turn = -1; // nobody shoots while balls roll
Each browser re-runs simulate with frames: true and animates the result. endCheck is an FNV-1a hash of every final position, so if a client's replay drifts, it counts a desync and logs it. The server's result stands either way. The real turn and winner wait in pending until the animation should have finished, so the UI never announces a winner while the balls are still rolling.
The determinism comes from a fixed timestep, a fixed iteration order, plain arithmetic plus Math.sqrt (which IEEE 754 requires to be correctly rounded), and inputs rounded to three decimals before they reach the simulation.
6. The computer: geometry proposes, physics decides
For every legal ball and pocket, pool8-ai.js works out the ghost-ball aim point, throws out thin cuts and blocked lines, and estimates power from distance. Spin variants and a few gentle safeties are added so there's always a legal option. Each candidate then goes through the real simulate and applyShot (scoring simplified here):
if (tmp.winner === seat) return 1000;
if (g) sc += potsOfMine * 4;
if (sum.foul) sc -= 12;
if (sum.keep) sc += 6 + positionBonus; // is there a next pot from here?
else sc -= opponentsBestNextPot; // don't leave an easy one
The leading candidates are simulated again with small aim and power errors, and their scores are averaged, which filters out shots that only go in at one exact angle. Difficulty sets how many shots get simulated (22/45/80) and how much aim noise is added at the end. Easy loses because its hands shake, not because it chooses badly.
Tradeoffs
- One shared core is the only reason the hash check can exist.
- 400 Hz with discrete collisions: at full power a ball moves 14 mm per step, which is under half a radius, so it can't tunnel. A higher speed cap would need swept collisions.
- Pockets are circles plus "no cushion" zones. They play well, but real jaws rattle and mine don't. That's next on my list.
8-ball is one of 60+ games on the site. You can play 8-ball pool here against a friend or the computer, or browse the rest at mympgames.com.
Top comments (0)