Workshop › Battleship › Step 1 of 35

Battleship: A 10 by 10 sea

Sink the enemy fleet before it sinks yours, and teach the computer to hunt. Random fleets that never overlap, one fire function for both sides, turns, and three computer players you can measure: random (about 95 shots), hunt and target (about 56) and a heat map of every possible ship position (about 44).

What we are doing

Battleship is played on a sea of 10 by 10 squares. We draw the enemy's sea, where you will shoot: 100 blue squares with thin gaps between them.

```js
const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

const N = 10
const BIG = 36 // cell size of the enemy's sea, where you shoot
const SEA = { x: 30, y: 50 }

ctx.fillStyle = '#0f172a'
ctx.fillRect(0, 0, canvas.width, canvas.height)

ctx.fillStyle = '#1e3a8a'
for (let r = 0; r < N; r++) {
  for (let c = 0; c < N; c++) {
    ctx.fillRect(SEA.x + c * BIG + 1, SEA.y + r * BIG + 1, BIG - 2, BIG - 2)
  }
}
```

What it means

Your turn

Write the code under the three comment lines, then press Run.

Skills: Drawing on a canvas, Loops

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