Workshop › Battleship › Step 6 of 35
A fleet has ships of length 5, 4, 3, 3 and 2. Each ship tries random spots until it fits on the sea without overlapping a ship already placed.
```js
const SHIPS = [5, 4, 3, 3, 2]
// A random fleet: each ship tries random spots until it fits on the sea without overlapping another.
function placeFleet() {
const taken = grid(false)
return SHIPS.map((length) => {
for (;;) {
const down = Math.random() < 0.5
const r = Math.floor(Math.random() * (down ? N - length + 1 : N))
const c = Math.floor(Math.random() * (down ? N : N - length + 1))
const cells = shipCells(r, c, length, down)
if (cells.some(([cr, cc]) => taken[cr][cc])) continue
for (const [cr, cc] of cells) taken[cr][cc] = true
return { cells }
}
})
}
```SHIPS.map(...) turns each length into a ship; the result is the list of five ships.for (;;) loops forever; continue tries again, return leaves with a ship that fits.some asks whether any of its squares is already taken; if not, they are marked taken.const N = 10 write SHIPS.function drawSea(, write placeFleet with its comment, followed by an empty line.Skills: Loops, Arrays and objects
← Grids and ships as lists Two fleets →