Workshop › Sudoku › Step 3 of 28

A puzzle from a string

What we are doing

A puzzle is 81 digits, row by row, with 0 for an empty cell. We write it as one text and turn it into a 9 × 9 grid of numbers, then draw the digits.

```js
// The puzzle, row by row; 0 is an empty cell.
const PUZZLE = '530070000600195000098000060800060003400803001700020006060000280000419005000080079'

let grid // grid[r][c]: 1 to 9, or 0 for an empty cell

function reset() {
  grid = Array.from({ length: 9 }, (_, r) => [...PUZZLE.slice(r * 9, r * 9 + 9)].map(Number))
}

      if (grid[r][c] === 0) continue
      ctx.fillStyle = '#0f172a'
      ctx.font = 'bold 26px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillText(String(grid[r][c]), x + SIZE / 2, y + SIZE / 2 + 9)
```

What it means

Your turn

  1. Under TOP, write the comment, PUZZLE, let grid and reset.
  2. In draw, under the white cell, write the digit lines.
  3. Call reset() above draw() at the bottom.

Skills: Arrays and objects

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