Workshop › Battleship › Step 24 of 35

A heat map

What we are doing

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
}
```

What it means

Your turn

Under playerShoots, write the comment and heatMap (above computerShoots).

Skills: Loops, Arrays and objects

All steps

  1. A 10 by 10 sea
  2. A function for any sea
  3. Your own sea
  4. Draw again and again
  5. Grids and ships as lists
  6. A random fleet
  7. Two fleets
  8. Which ship is here?
  9. Fire at a square
  10. Show the shots
  11. Your shot
  12. Tap to fire
  13. A message line
  14. Hit or miss?
  15. See your own fleet
  16. Sinking ships
  17. Darker hits on a sunk ship
  18. Outline sunk ships
  19. Win in as few shots as you can
  20. A record of their shots
  21. Take turns
  22. The computer shoots back
  23. You can lose too
  24. A heat map
  25. Shoot the hottest square
  26. Hunt around a hit
  27. See the heat map
  28. H for heat
  29. Show their ships at the end
  30. A keyboard cursor
  31. Move with the arrows
  32. Fire with Enter, play again
  33. Your best game
  34. A side panel
  35. Build it yourself: ships apart