Workshop › Battleship › Step 1 of 35
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).
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)
}
}
```N is the size of the sea, BIG the size of one square, SEA the top-left corner of the sea.r from 0 to 9; for each row the inner loop counts the columns c.Write the code under the three comment lines, then press Run.
Skills: Drawing on a canvas, Loops