DEV Community

My MP Games
My MP Games

Posted on

Forced captures and multi-jumps: how I coded checkers rules for a multiplayer browser game

Checkers looks like the easy one. Eight by eight board, pieces move diagonally, jump to capture, reach the far side and you get a king. It's one of the classics on mympgames, my free browser arcade.

The board is the simple part. Two rules carry most of the complexity: captures are mandatory, and a capture that can continue must continue with the same piece. Get either wrong and the game quietly stops being checkers. This post walks through the rules module the server uses, with the real code (trimmed a bit), and the decisions behind it.

The board is just an array of nullable objects

Each square is either null or a piece with an owner and a king flag:

function initialBoard() {
  const board = emptyBoard();
  for (let r = 0; r < SIZE; r++) {
    for (let c = 0; c < SIZE; c++) {
      if ((r + c) % 2 === 1) {
        if (r < 3) board[r][c] = { p: 1, k: false };
        else if (r > 4) board[r][c] = { p: 0, k: false };
      }
    }
  }
  return board;
}
Enter fullscreen mode Exit fullscreen mode

(r + c) % 2 === 1 picks the dark squares, the only ones checkers uses. Player 0 fills the bottom three rows and moves up; player 1 fills the top three and moves down. Rows 3 and 4 start empty.

I kept it as plain objects instead of bitboards on purpose. The same file runs on the server (Node) and in the browser, and the computer opponent also calls into it. Readable beat clever here; the board has 32 playable squares, so speed was never the bottleneck.

Direction is the only difference between a man and a king

function dirsFor(piece) {
  if (piece.k) return [[-1, -1], [-1, 1], [1, -1], [1, 1]];
  return piece.p === 0 ? [[-1, -1], [-1, 1]] : [[1, -1], [1, 1]];
}
Enter fullscreen mode Exit fullscreen mode

A man moves forward diagonally, a king moves both ways. Everything else, steps and jumps, is written once on top of this. That kept the king logic from turning into a second copy of the move generator.

A step is "the next diagonal square is empty". A jump is "the next diagonal square holds an opponent and the one after it is empty":

function getCaptures(board, r, c) {
  const piece = board[r][c];
  const moves = [];
  for (const [dr, dc] of dirsFor(piece)) {
    const mr = r + dr, mc = c + dc;          // the jumped square
    const lr = r + dr * 2, lc = c + dc * 2;  // the landing square
    if (inBounds(lr, lc) && board[mr]?.[mc] &&
        board[mr][mc].p !== piece.p && !board[lr][lc]) {
      moves.push({ from: [r, c], to: [lr, lc], capture: [mr, mc] });
    }
  }
  return moves;
}
Enter fullscreen mode Exit fullscreen mode

The move object carries the captured square with it. That turned out to matter later: notation, animation and the "which piece disappeared" check on the client all read move.capture instead of recomputing it.

Rule one: if you can capture, you must

This is the rule casual players forget, and the one that makes checkers a real game. If any of your pieces has a jump, plain steps are not legal at all. The whole rule is a filter in legalMoves:

function legalMoves(board, player, mustContinue = null) {
  const caps = [], steps = [], cells = [];
  if (mustContinue) cells.push(mustContinue);
  else {
    for (let r = 0; r < SIZE; r++)
      for (let c = 0; c < SIZE; c++)
        if (board[r][c]?.p === player) cells.push([r, c]);
  }
  for (const [r, c] of cells) {
    caps.push(...getCaptures(board, r, c));
    if (!mustContinue) steps.push(...getSteps(board, r, c));
  }
  if (mustContinue || caps.length) return caps;
  return steps;
}
Enter fullscreen mode Exit fullscreen mode

Collect both lists, then return captures if there are any and steps otherwise. The server never asks "is this move allowed?" with a separate rulebook. It asks for the legal list and looks the move up in it:

function findMove(board, player, from, to, mustContinue) {
  return legalMoves(board, player, mustContinue).find(
    (m) => m.from[0] === from[0] && m.from[1] === from[1] &&
           m.to[0] === to[0] && m.to[1] === to[1]
  ) || null;
}
Enter fullscreen mode Exit fullscreen mode

One source of truth means the UI highlights, the server check and the bot all agree. If a player sends a step while a jump exists, findMove returns null and the move is rejected. No special case.

Rule two: a multi-jump is several moves with the same turn

One way to model a double or triple jump is as a single move with a list of captures. That pushes work everywhere: the client has to build the whole path, the server has to validate every hop inside it, and a jump that crowns a piece halfway complicates it further.

The rules module instead treats each hop as its own move and simply doesn't hand the turn over. applyMove checks for follow-up jumps from the landing square:

function applyMove(board, move) {
  const piece = { ...board[move.from[0]][move.from[1]] };
  const next = cloneBoard(board);
  next[move.from[0]][move.from[1]] = null;
  if (move.capture) next[move.capture[0]][move.capture[1]] = null;
  const crowned = wouldCrown(piece, move.to[0]);
  if (crowned) piece.k = true;
  next[move.to[0]][move.to[1]] = piece;
  let more = [];
  if (move.capture && !crowned) more = getCaptures(next, move.to[0], move.to[1]);
  return { board: next, piece, crowned, more };
}
Enter fullscreen mode Exit fullscreen mode

Then play uses that to decide whose turn it is:

const continuing = applied.more.length > 0;
const next = {
  board: applied.board,
  turn: continuing ? pos.turn : 1 - pos.turn,
  mustContinue: continuing ? [move.to[0], move.to[1]] : null,
  // ...
};
Enter fullscreen mode Exit fullscreen mode

mustContinue is the trick. When it's set, legalMoves only looks at that one square and only returns captures. So after the first hop, the player can't switch to a different piece and can't stop early. Each hop is validated by exactly the same code as a normal move, and other players and spectators see the chain one hop at a time.

Note the !crowned check. In the rules I implemented, a man that reaches the back row and becomes a king ends the turn there, even if a king could keep jumping. That's the common American/English rule, and it falls out of one condition.

When does the game end?

function outcome(board, playerToMove, idlePlies, mustContinue = null) {
  if (countPieces(board, 0) === 0) return { winner: 1, reason: 'captured' };
  if (countPieces(board, 1) === 0) return { winner: 0, reason: 'captured' };
  if (!hasMoves(board, playerToMove, mustContinue))
    return { winner: 1 - playerToMove, reason: 'nomoves' };
  if (idlePlies >= 80) return { winner: null, draws: true, reason: '40-move' };
  return null;
}
Enter fullscreen mode Exit fullscreen mode

Losing all your pieces loses. So does being completely blocked, which surprises people the first time it happens to them. The draw rule exists because two kings each can chase each other forever. idlePlies counts half-moves with no capture and no man moving; any capture or man move resets it, and 80 idle plies (40 moves each) is a draw.

Small things that paid off

  • A string key for positions. boardKey turns the board into 64 characters (w, W, r, R, .). The computer opponent accepts it as input, and a whole position fits on one readable line.
  • Notation from the move object. c3xe5+ means a capture that crowned. Building it from move.capture and crowned means the move log never disagrees with the board.
  • Pure functions. Nothing in the rules file mutates its input. applyMove clones first. That made the bot's search trivial to write, because it can try a move and throw the result away.

The computer opponent reuses all of it

The bot is a depth-limited search with time limits that grow with difficulty. Its evaluation is simple: men are worth 100, kings 175, plus a bonus for advancing and a little for mobility. The important part is that it calls the same legalMoves, so it can never make an illegal move and it handles forced captures and multi-jumps for free. When it's mid-chain, mustContinue keeps the turn with it exactly as it does for a human.

The takeaway

Model the forced-capture and multi-jump rules as state, not as special move types. One "must continue from this square" field replaced a pile of edge cases, and it kept the server, the browser and the bot honest with each other.

If you want to see the rules in action, you can play checkers with a friend or the computer at mympgames.com/play/checkers. It's free and runs in the browser, and there are 60+ other games at mympgames.com.

Top comments (0)