Workshop › Battleship › Step 24 of 35
To shoot smart, the computer imagines every way the ships still afloat could lie on your sea, skipping any that would cross a miss. Each square counts how many of those ways cover it: a heat map. The hottest square is the best guess.
```js
// How many ways could the ships still afloat lie on the sea, given what the computer knows?
function heatMap() {
const heat = grid(0)
const afloat = myFleet.filter((s) => !sunk(s)).map((s) => s.cells.length)
for (const length of afloat) {
for (let r = 0; r < N; r++) {
for (let c = 0; c < N; c++) {
for (const down of [false, true]) {
const cells = shipCells(r, c, length, down)
if (cells.some(([cr, cc]) => cr >= N || cc >= N)) continue
if (cells.some(([cr, cc]) => theirShots[cr][cc] === 'miss')) continue
for (const [cr, cc] of cells) heat[cr][cc] += 1
}
}
}
}
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (theirShots[r][c]) heat[r][c] = 0
return heat
}
```afloat lists the lengths of your ships still afloat.continue); every other one adds 1 to its squares.Under playerShoots, write the comment and heatMap (above computerShoots).
Skills: Loops, Arrays and objects
← You can lose too Shoot the hottest square →