DEV Community

My MP Games
My MP Games

Posted on

Stacked sixes, safe stars and bonus rolls: how I coded Ludo's turn rules for a multiplayer browser game

Ludo is the game everyone thinks they know. Roll a 6 to get out, race round the board, knock people home. Then you sit four people down and find out that everybody grew up with slightly different rules.

Ludo is one of the 60+ games on mympgames, my free multiplayer browser arcade, and it was harder to get right than chess. The board is easy. The turn flow is where it gets tricky: sixes that stack, a third six that cancels everything, bonus rolls that arrive in the middle of spending other dice, and a handful of house rules the host can switch on. This post walks through the server-side rules module, with real code (trimmed a little), and the decisions behind it.

One number per token

The first decision was how to store a token's position. Instead of storing board coordinates, every token is a single integer of progress relative to its own start square:

const TRACK = 52;  // squares on the shared loop
const ENTRY = 50;  // last shared square before the home column
const COL0  = 52;  // first home-column square
const HOME  = 57;
const START = { red: 0, green: 13, yellow: 26, blue: 39 };
const SAFE  = new Set([0, 8, 13, 21, 26, 34, 39, 47]);

// -1 = base, 0..51 = main track, 52..56 = home column, 57 = home
function absSquare(color, p) {
  return (START[color] + p) % TRACK;
}
Enter fullscreen mode Exit fullscreen mode

That makes most questions trivial. "Is this token in base?" is p === -1. "Is it safe forever?" is p > 51. "How far along is it?" is just p, which the computer opponent uses directly. The only time I need the absolute square is when two colours might meet, so absSquare converts on demand, and captures and safe squares are checked in absolute terms.

The drawing code on the client does the reverse mapping to pixels. The rules never know what the board looks like.

Rule one: sixes stack, three sixes forfeit

In the turn flow I implemented (the style most people know from Ludo apps), a 6 doesn't move you straight away. You roll again, and the dice pile up. 6, 6, 4 means three dice to spend. Three 6s in a row and the whole turn is lost.

That rule is mostly a pending array and a counter:

function roll(st, seat) {
  if (seat !== st.turn) return { ok: false, error: 'Not your turn' };
  if (st.phase !== 'roll') return { ok: false, error: 'Use your dice first' };
  const d = rollDie(st);
  if (d === 6) st.sixes += 1;
  if (st.sixes === 3) {
    passTurn(st);            // all pending dice are thrown away
    return { ok: true };
  }
  st.pending.push(d);
  if (d === 6) {
    st.phase = 'roll';       // keep rolling
    return { ok: true };
  }
  st.sixes = 0;
  if (legalByDie(st).every((l) => !l.length)) {
    st.pending = [];         // nothing can move: drop the dice
    endOfDice(st);
    return { ok: true };
  }
  st.phase = 'move';
  return { ok: true };
}
Enter fullscreen mode Exit fullscreen mode

The phase field (roll, move, done) is the backbone. Every action checks it first, so a client that sends "move" while the server expects "roll" just gets an error back. There is no way to move twice or roll in the middle of spending dice.

Dice come from crypto.randomInt(1, 7) on the server. The rules factory also accepts an injected RNG, which is what the tests use to get repeatable games.

Rule two: moving is walking a path

Once the dice are rolled, the player spends them one at a time, in any order, on one token or split across several. The core function answers "where would this token end up with this die, and is that legal?" by literally walking the squares:

function step(st, seat, p) {
  if (p === ENTRY) return canEnterHome(st, seat) ? COL0 : 51;
  if (p === 51) return 0;
  return p + 1;
}

function pathFor(st, seat, token, d) {
  const p0 = st.tokens[seat][token];
  if (p0 === HOME) return null;
  if (p0 === -1) return leavesBase(st, d) ? [0] : null;
  const path = [];
  let p = p0;
  for (let k = 0; k < d; k++) {
    p = step(st, seat, p);
    if (p > HOME) return null;                 // overshot
    path.push(p);
    if (p === HOME && k < d - 1) return null;  // exact roll to finish
  }
  return path;
}
Enter fullscreen mode Exit fullscreen mode

I could have done the arithmetic in one line, but walking square by square pays off three ways:

  1. Exact finish falls out of the loop. You can't overshoot home.
  2. The path is returned. The client animates the token hop by hop along it, and everyone sees the same route.
  3. Walls are easy. With the optional "blocks" rule, two tokens of one colour on a square form a wall that rivals can't land on or pass. That's one extra check inside the loop. A 6 is allowed to jump a wall, so a game can't deadlock with everyone stuck behind one.

step is also where the "kill before you go home" house rule lives. If a player hasn't captured anyone yet, square 50 leads to 51 and then back to 0 instead of into the home column, so the token keeps circling. Without that rule, 51 is never reached.

Legal moves are then just "every token whose pathFor isn't null". The server never keeps a separate rulebook for validation. A move is legal if and only if pathFor returns a path.

Rule three: captures, safe squares and partners

When a token lands on the main track, anything on that absolute square that isn't a friend goes back to base, unless the square is safe:

if (to <= 51) {
  const sq = absSquare(color, to);
  if (!isSafe(st, sq)) {
    for (const v of occupants(st, sq)) {
      if (friends(st, v.seat, seat)) continue;
      st.tokens[v.seat][v.token] = -1;
      (captured ||= []).push(v);
    }
  }
}
if (st.rules.bonusRoll && (captured || to === HOME)) st.bonusRolls += 1;
Enter fullscreen mode Exit fullscreen mode

friends covers both "it's my own token" and team mode, where red and yellow play green and blue and partners can't capture each other. That one helper is reused by the wall check and the computer opponent, so teams only had to be taught once.

The tricky part: a bonus roll while dice are still pending

Here's the case that took me longest. You roll 6, then 3. You use the 3 first and it captures someone. You've earned a bonus roll, but you still owe the 6. What happens?

The answer I settled on: the bonus roll comes now, and its result joins the dice you still hold. So you roll again, get a 2, and now spend the 6 and the 2.

function endOfDice(st) {
  if (st.bonusRolls > 0) {
    st.bonusRolls -= 1;
    st.sixes = 0;
    st.phase = 'roll';      // pending dice are kept
    return;
  }
  if (st.pending.length && legalByDie(st).every((l) => !l.length)) {
    st.pending = [];        // leftover dice nobody can use
  }
  if (st.pending.length) { st.phase = 'move'; return; }
  passTurn(st);
}
Enter fullscreen mode Exit fullscreen mode

Unless the move finishes that player's game, it ends in endOfDice, which decides in a fixed order: bonus roll first, then keep spending, then drop useless dice, then pass. Putting all of the "what happens next" logic in one function meant fixing this ordering once instead of in every branch.

Fewer pointless clicks

Ludo has lots of forced moves: one token out, one die, nothing else legal. Asking a player to tap their only option every time feels slow. The rules module works out the distinct choices, treating two tokens on the same square or two equal dice as the same move:

function choices(st, seat = st.turn) {
  const seen = new Map();
  st.pending.forEach((d, di) => {
    for (const t of legalMoves(st, seat, d)) {
      const k = `${st.tokens[seat][t]}:${d}`;
      if (!seen.has(k)) seen.set(k, { token: t, die: di, value: d });
    }
  });
  return [...seen.values()];
}
Enter fullscreen mode Exit fullscreen mode

If there's exactly one, the view marks it as auto and the client plays it after a short beat. The server still validates it like any other move. The client just saves you a tap.

Keeping everyone in sync

In a multiplayer room, the risk is that a fast player or a bot moves while another screen is still animating the last move. So the server game wrapper puts an animation budget on each action and refuses the next one until it has played out:

if (st.animUntil && Date.now() < st.animUntil - GRACE)
  return { ok: false, error: 'Wait for the move to finish' };
Enter fullscreen mode Exit fullscreen mode

The budget is computed from the move itself: a fixed time per square in the path, plus a pause and a "slide back to base" for any capture. Computer seats use the same number as their delay before acting. The tradeoff is a slightly slower game, but every player and spectator sees the same hop-by-hop move instead of tokens teleporting.

The computer opponent

The bot doesn't search ahead. Dice make deep search expensive and the benefit is small, so it scores each legal (token, die) pair and picks the best. Capturing is worth a lot, more if the victim was far along. Getting home, leaving base and reaching a safe square or the home column all add points. Landing within six squares in front of a rival subtracts points, and moving a token out of danger adds them. A little randomness keeps it from feeling robotic. Because it calls the same legalByDie, it can't make an illegal move, and house rules work for it automatically.

What I'd tell someone building Ludo

  • Store progress, not coordinates. One integer per token makes rules, bots and house rules much simpler.
  • Make the turn a small state machine. phase, pending, sixes and bonusRolls are enough to describe every point in a turn, and each action checks them first.
  • Return paths, not just destinations. Validation, walls, exact finishes and animation all reuse the same walk.
  • Put "what happens next" in one place. Most of my bugs were ordering bugs, and endOfDice is where they got fixed.

You can try all of this at mympgames.com/play/ludo. It's free and runs in the browser, with friends or computer players in empty seats. If Ludo isn't your thing, there are 60+ other games at mympgames.com.

Top comments (0)