Workshop › Sudoku › Step 1 of 28

Sudoku: Nine by nine

Play Sudoku, then teach the computer to solve it and to invent new puzzles. A grid read from a string, the three rules in one loop, a backtracking solver that picks the most constrained cell, a generator that keeps each puzzle to exactly one solution, and a number pad for phones.

What we are doing

Sudoku is played on 9 × 9 cells. We draw them, centered, as white squares on a light background.

```js
const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

const SIZE = 48
const LEFT = (canvas.width - 9 * SIZE) / 2
const TOP = 56

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

  for (let r = 0; r < 9; r++) {
    for (let c = 0; c < 9; c++) {
      const x = LEFT + c * SIZE
      const y = TOP + r * SIZE
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(x, y, SIZE, SIZE)
    }
  }
}

draw()
```

What it means

Your turn

Write the lines under the comments, then press Run.

Skills: Drawing on a canvas, Loops

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