DEV Community

Cover image for Hidden ships, honest server: how I coded Battleship for a multiplayer browser game
My MP Games
My MP Games

Posted on

Hidden ships, honest server: how I coded Battleship for a multiplayer browser game

Most of the games on my site are open-information games. In chess, Connect Four or checkers, both players see the same board, so the server's main job is checking that a move is legal. Battleship is different. The whole game depends on one thing: you must not know where my ships are.

On paper that sounds easy. In a browser it's the thing you can get wrong without noticing. If the server sends the full game state to both clients and lets the UI "hide" the other fleet, anyone who opens DevTools has won. So Battleship on mympgames was really an exercise in deciding who is allowed to see what.

The whole game lives in one file, server/games/battleship.js, at about 200 lines. Here's how it fits together.

The rules I implemented

These are the classic rules, with one house rule that a lot of people grew up with:

  • Each player has a 10×10 grid and the same fleet: carrier (5), battleship (4), cruiser (3), submarine (3), destroyer (2).
  • Ships go in a straight line, horizontal or vertical, and can't overlap or hang off the board.
  • Both players place their fleets at the same time. The battle starts once both are ready.
  • Players take turns firing at one cell. The result is a hit or a miss, and you're told when a ship sinks.
  • A hit fires again. A miss passes the turn.
  • First to sink the whole enemy fleet wins.

The state: one object, two secrets

Every game on the site exports the same small interface: createState, onAction and publicState. For Battleship the state looks like this:

function createState() {
  return {
    phase: 'place',
    grids: [emptyGrid(), emptyGrid()],   // where each player's ships are
    ships: [[], []],                     // ship objects with cells + hits
    placed: [false, false],
    shots: [emptyGrid(), emptyGrid()],   // shots[i] = shots fired BY player i
    turn: 0,
    winner: null,
    lastShot: null,
  };
}
Enter fullscreen mode Exit fullscreen mode

grids and ships are the secrets. shots is public knowledge, because both players saw every shot happen. Writing that comment next to shots saved me from bugs more than once. "Shots fired by me" and "shots fired at me" are easy to mix up when you're tired.

Cells are just numbers. In a ship grid, 1 means a ship. In a shot grid, 0 means not fired, 1 means a miss and 2 means a hit. That's not elegant, but it's cheap to copy and simple to render.

Placement: never trust the client's fleet

The server understands two placement actions. place-fleet takes a start cell and orientation for each ship. auto-place asks the server to place the whole fleet randomly. Right now the browser UI only has an "Auto-place fleet" button, because it gets people into the battle fastest. The manual path is still in the server, though, and it shows the rule I care about most: the server rebuilds the fleet from scratch on a fresh grid and checks every ship itself.

function canPlace(grid, r, c, size, horizontal) {
  if (horizontal) {
    if (c + size > W) return false;
    for (let i = 0; i < size; i++) if (grid[r][c + i]) return false;
  } else {
    if (r + size > H) return false;
    for (let i = 0; i < size; i++) if (grid[r + i][c]) return false;
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

Notice that the client never sends ship sizes. The server walks its own FLEETS list and takes only position and orientation from the player. Otherwise someone could quietly send a fleet of five one-cell destroyers, which would be very hard to find.

auto-place, the one the UI uses today, is plain random placement with retries:

for (const def of FLEETS) {
  let placed = false;
  for (let attempt = 0; attempt < 200 && !placed; attempt++) {
    const horizontal = Math.random() < 0.5;
    const r = Math.floor(Math.random() * H);
    const c = Math.floor(Math.random() * W);
    if (canPlace(grid, r, c, def.size, horizontal)) {
      placeShip(grid, ships, r, c, def.size, horizontal, def.name);
      placed = true;
    }
  }
  if (!placed) return { ok: false, error: 'Auto-place failed' };
}
Enter fullscreen mode Exit fullscreen mode

Rejection sampling like this is the simplest correct approach. With 17 ship cells on a 100-cell board, it practically never needs more than a handful of tries. I kept the 200-attempt cap anyway, so a future bigger fleet fails loudly instead of looping forever.

Because placement is simultaneous, the place phase ignores turn completely. Each player's placed flag flips on its own, and the phase moves to battle only when both are true.

Firing: the whole game in twenty lines

The battle phase accepts exactly one action, fire. Validation comes first: right phase, your turn, on the board, and a cell you haven't fired at already. After that the logic is short:

const opp = 1 - playerIndex;
const hit = state.grids[opp][r][c] === 1;
state.shots[playerIndex][r][c] = hit ? 2 : 1;

let sunk = null;
if (hit) {
  for (const ship of state.ships[opp]) {
    if (ship.cells.some(([rr, cc]) => rr === r && cc === c)) {
      ship.hits += 1;
      if (ship.hits >= ship.size) { ship.sunk = true; sunk = ship.name; }
      break;
    }
  }
}

state.lastShot = { by: playerIndex, r, c, hit, sunk };
if (allSunk(state.ships[opp])) state.winner = playerIndex;
else if (!hit) state.turn = opp;   // a hit keeps the turn
Enter fullscreen mode Exit fullscreen mode

Two things worth pointing out.

First, ship.hits is a counter rather than a set of hit cells. That only works because the "already shot" check makes it impossible to hit the same cell twice. The validation isn't just there for user experience. The scoring depends on it.

Second, the "hit fires again" rule is the last line: the turn only changes on a miss. I like this rule in an online game. It gives a hunting run some momentum, and quick back-and-forth misses keep the game moving. The downside is that a lucky first hit can snowball, but games still feel close more often than you'd expect.

publicState: where hidden information actually lives

This is the function that matters most. After every action, the server calls publicState(state, viewerIndex) separately for each player and sends each one their own view:

function publicState(state, viewerIndex) {
  const opp = 1 - viewerIndex;
  return {
    phase: state.phase,
    myGrid: state.grids[viewerIndex].map((row) => [...row]),
    myShots: state.shots[viewerIndex].map((row) => [...row]),
    oppShotsOnMe: state.shots[opp].map((row) => [...row]),
    myShips: state.ships[viewerIndex].map((s) => ({ name: s.name, size: s.size, sunk: s.sunk, cells: s.cells })),
    oppSunk: state.ships[opp].filter((s) => s.sunk).map((s) => s.name),
    turn: state.turn,
    winner: state.winner,
    lastShot: state.lastShot,
    // ...plus ready flags, grid size and fleet list
  };
}
Enter fullscreen mode Exit fullscreen mode

There's no oppGrid field. You get your own ships, your own shots, the shots fired at you, and the names of enemy ships you've sunk. You don't even get the cells of a sunk enemy ship. The client works out what it can from the pattern of hits, just like a player with a pencil would.

The rows are copied with map((row) => [...row]) before they go out. Nothing on the server's side should hold a reference to an object that's about to be serialised and sent somewhere else. It's a small allocation per update and worth it.

Spectators get their own view

You can watch any room on the site, and that created a new problem. Who is a spectator, as far as publicState is concerned? The generic fallback in the room server takes seat 0's view and removes every field starting with my. That naming convention exists for exactly this reason. For Battleship I wanted to be explicit, so the game exports its own spectatorState:

/** Neutral view for spectators: shots and sunk ships only, never ship positions. */
function spectatorState(state) {
  return {
    phase: state.phase,
    turn: state.turn,
    winner: state.winner,
    lastShot: state.lastShot,
    shots: state.shots.map((g) => g.map((row) => [...row])),
    sunk: state.ships.map((list) => list.filter((s) => s.sunk).map((s) => s.name)),
  };
}
Enter fullscreen mode Exit fullscreen mode

Spectators see both shot boards filling up and nothing else. It's less exciting than a god's-eye view. But it means a friend watching on a second screen can't shout "it's on B7!", and a spectator link can't be used to cheat.

The computer opponent, and an honest tradeoff

You can also play against the computer. Its policy is deliberately simple: if it has an unresolved hit, fire at a neighbouring cell; otherwise fire at a random cell it hasn't tried yet.

const hunts = [];
for (let r = 0; r < 10; r++) for (let c = 0; c < 10; c++) {
  if (shots[r][c] !== 2) continue;
  for (const [dr, dc] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) {
    const rr = r + dr, cc = c + dc;
    if (rr >= 0 && rr < 10 && cc >= 0 && cc < 10 && !shots[rr][cc]) hunts.push({ r: rr, c: cc });
  }
}
const cell = pick(hunts) || pick(cells);
Enter fullscreen mode Exit fullscreen mode

Here's the honest part. The bot runs on the server and is handed the raw room state, so technically it could read your grid. It doesn't. The policy only ever looks at state.shots[bot], its own shot history. That's discipline, though, not enforcement. If I were starting over, I'd pass the bot publicState(state, botIndex) so cheating would be impossible rather than just avoided. It also keeps probing around hits from ships that are already sunk, which wastes a shot now and then. Arguably that makes it more human. A parity-based hunt (only firing on a checkerboard pattern) would make it much stronger, and that's the obvious next difficulty level.

What I'd take from this to other games

  • Write publicState as a whitelist. Start from an empty object and add what the viewer may see. Don't copy the state and delete secrets, because one day you'll forget a field.
  • Use a naming convention for private fields (my* here), so generic code like the spectator fallback can strip them safely.
  • Let the server work out everything it can. A client can suggest positions, but sizes, hits and sinking are the server's business.
  • Remember that validation can be load-bearing. "Already shot" isn't just polite, it's what keeps the hit counter correct.

If you want to see it in action, open a room and send the link to a friend: https://mympgames.com/play/battleship. The rest of the 60+ free multiplayer games are at https://mympgames.com.

Top comments (1)

Collapse
 
wordforge_jp profile image
WordForge •

This was a really clear walkthrough of the part that's easy to get wrong: hidden information. The whitelist approach in publicState stood out to me — starting from an empty object and adding only what the viewer may see, with no oppGrid field at all, makes it much harder to leak a ship position by accident than copying the state and deleting fields. I also liked the explicit spectatorState (shots and sunk ships only) instead of relying on the generic my* stripping fallback, and the honest note about the bot: that it currently gets the raw state and only looks at its own shots, so passing publicState(state, botIndex) would turn discipline into enforcement. One thing I'm curious about: with simultaneous placement, what happens if a player disconnects and reconnects during the place phase — does their placed flag and fleet survive, or do they have to place again?