Workshop › Candy Crush-style Match 3 › Step 3 of 29

The game loop

What we are doing

Gems will flash and fall, so the picture must be redrawn about 60 times a second. The drawing goes into draw, and loop calls it before every screen refresh.

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

  for (let r = 0; r < N; r++) {
    for (let c = 0; c < N; c++) {
      const x = LEFT + c * SIZE
      const y = TOP + r * SIZE
      ctx.fillStyle = (r + c) % 2 === 0 ? '#312e81' : '#3730a3'
      ctx.fillRect(x, y, SIZE, SIZE)
    }
  }
}

function loop() {
  draw()
  requestAnimationFrame(loop)
}

requestAnimationFrame(loop)
```

What it means

Your turn

  1. Wrap all the drawing lines in function draw() { ... }, indented by two spaces.
  2. Under it write loop and the line that starts it.

Skills: The game loop, Functions

All steps

  1. A place for the board
  2. A checkered grid
  3. The game loop
  4. A board of random gems
  5. Draw the gems
  6. Start without matches
  7. Click a gem
  8. Show the selection
  9. Swap two neighbours
  10. Find every match
  11. No match, no swap
  12. A score and a fresh start
  13. Clear the match
  14. Let the gems fall
  15. Two halves of a clear
  16. Wait before clearing
  17. Flash, and hands off
  18. Cascades
  19. Where a gem came from
  20. Slide down
  21. Out from under the top
  22. Is there any move?
  23. Never stuck
  24. A hint after five seconds
  25. Show the hint
  26. Twenty moves
  27. The end of a game
  28. Remember the best score
  29. Build it yourself: swipe to swap