Workshop › Minesweeper › Step 12 of 26

Click to open

What we are doing

A click opens the cell under the pointer. cellAt(event) scales the click into canvas pixels and divides by CELL to find the column and row; clicks on the top strip give undefined.

```js
function cellAt(event) {
  // The canvas may be displayed at a different size than its own pixels, so scale the pointer.
  const rect = canvas.getBoundingClientRect()
  const x = (event.clientX - rect.left) * (canvas.width / rect.width)
  const y = (event.clientY - rect.top) * (canvas.height / rect.height)
  const col = Math.floor(x / CELL)
  const row = Math.floor((y - TOP) / CELL)
  if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) return undefined
  return grid[row][col]
}

canvas.addEventListener('click', (event) => {
  const cell = cellAt(event)
  if (cell) reveal(cell)
})
```

What it means

Your turn

Above function draw() {, write cellAt and the click listener, with an empty line after each. Press Run and click.

Skills: Keyboard and mouse input

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