Workshop › Sudoku › Step 23 of 28

Hints

What we are doing

Stuck? H fills in a cell from the solution: the selected one if it is wrong or empty, otherwise the first cell that is. Hints are counted.

```js
let hints
  hints = 0

// A hint fills the selected cell (or the first empty one) from the solution.
function hint() {
  if (won) return
  let cell = grid[selected.r][selected.c] === solution[selected.r][selected.c] ? null : selected
  for (let i = 0; i < 81 && !cell; i++) {
    const r = Math.floor(i / 9)
    const c = i % 9
    if (grid[r][c] !== solution[r][c]) cell = { r, c }
  }
  if (!cell) return
  selected = cell
  grid[cell.r][cell.c] = solution[cell.r][cell.c]
  hints += 1
  checkWin()
}

  else if (event.key === 'h' || event.key === 'H') hint()
```

What it means

Your turn

  1. Under let won, write let hints; in reset, set it to 0.
  2. Under enter, write the comment and hint.
  3. In keydown, add the H line at the end of the chain.

Skills: Game states, Keyboard and mouse input

All steps

  1. Nine by nine
  2. Lines and boxes
  3. A puzzle from a string
  4. The puzzle's own digits
  5. Keep drawing
  6. The selected cell
  7. Light up row, column and box
  8. The same digit everywhere
  9. Click to select
  10. Move with the arrows
  11. Write digits
  12. The three rules in one loop
  13. Show mistakes
  14. Solved!
  15. A clock
  16. The solved message
  17. Play again
  18. The easiest cell
  19. The solver
  20. Random order
  21. Invent a puzzle
  22. A new puzzle every game
  23. Hints
  24. Best time
  25. N for a new puzzle
  26. A number pad
  27. Tap the pad
  28. Build it yourself: undo