DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

Building Battleship from scratch: hidden fleets and a hunt-and-target AI

Battleship looks like pure luck. It isn't — not for the computer. The whole game is a 10×10 grid of unknowns, and a good AI turns "random guessing" into something close to a search algorithm. I built a playable Battleship in vanilla JavaScript, and the interesting part was never the UI — it was making the opponent smart.

The board

Two 10×10 grids: yours and the enemy's. Five ships (lengths 5,4,3,3,2) are placed so none overlap and none run off the board — that validation is the first real bit of logic. Each turn you fire at a cell on the enemy grid; the result is hit, miss, or "sunk" once every cell of a ship is hit. First to sink the whole enemy fleet wins.

The dumb AI

The naive computer fires at random empty cells. It works, eventually — but it wastes shots spraying the board. On average it takes ~95 shots to clear the 100-cell grid. That's barely better than filling in every square.

The hunt-and-target AI

Real Battleship AIs run in two modes:

Hunt mode — before any hit, don't fire randomly. Ships are at least 2 cells long, so every ship must touch at least one cell of a checkerboard pattern. Firing only on "parity" cells (like the black squares of a chessboard) halves the search space and still guarantees you can't miss a ship entirely.

Target mode — the moment you land a hit, stop hunting. Push the four neighbouring cells onto a queue and fire those next. Once you get a second hit in line with the first, you've found the ship's axis — now fire only along that line, forwards then backwards, until the ship sinks. Then drop back to hunt mode.

That single behaviour change is huge: my hunt-and-target AI averages ~59 shots versus the random AI's ~95. Same game, same luck of ship placement — the difference is entirely in how it chooses the next cell.

Going further: probability density

The strongest Battleship AIs don't even use a fixed parity pattern. Each turn they compute, for every empty cell, how many ways the remaining ships could still fit through it — and fire at the cell with the highest count. It naturally hunts the middle early (more ships fit there) and adapts as cells are eliminated. I kept the demo at hunt-and-target because it's the clearest teaching version, but the page explains where density search takes over.

What it teaches

Battleship is a tiny, friendly introduction to searching under uncertainty: constrain the space (parity), exploit information the moment you get it (target mode), and — if you want to go pro — score every option by how much it narrows what's left. The board never changes; only the strategy does.

Play it, watch the AI switch from hunting to targeting the instant it lands a hit, and check how many fewer shots it needs than random:
https://dev48v.infy.uk/game/day32-battleship.html

Top comments (0)