Workshop › Minesweeper › Step 3 of 26

Draw the field

What we are doing

Every cell is a 40-pixel grey square, below a 40-pixel strip at the top that will hold the counter and the timer. grid.flat() gives all 81 cells in one list, and a for ... of loop draws each.

```js
const CELL = 40
const TOP = 40 // room for the mine counter and the timer

function draw() {
  ctx.fillStyle = '#1e293b'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  for (const cell of grid.flat()) {
    const x = cell.col * CELL
    const y = TOP + cell.row * CELL
    ctx.fillStyle = '#94a3b8'
    ctx.fillRect(x + 1, y + 1, CELL - 2, CELL - 2)
  }
}

newGame()
draw()
```

What it means

Your turn

  1. Under const SIZE = 9, write CELL and TOP.
  2. Above newGame() at the bottom, write draw and leave an empty line. Under newGame() write draw().

Skills: Drawing on a canvas, Loops

All steps

  1. A grid of cell objects
  2. The canvas and the pen
  3. Draw the field
  4. Draw every frame
  5. Neighbours
  6. Mines, but not under the first click
  7. Shuffle the candidates
  8. Count the mines around
  9. Open a cell
  10. Open cells look different
  11. Coloured numbers
  12. Click to open
  13. Stepping on a mine
  14. Show the mines
  15. Flood fill
  16. Flags with the right button
  17. A flag protects its cell
  18. Draw the flags
  19. Mines left
  20. Winning
  21. The end and a new game
  22. What time is it?
  23. The clock
  24. Stop the clock
  25. The best time
  26. Build it yourself: wrong flags