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

Let the gems fall

What we are doing

Gravity: in every column the gems above a gap fall down to fill it, and new random gems fill the top. Two counters do it in one pass from the bottom up: r reads, write points to the lowest place still to fill.

```js
// Everything above a gap falls down to fill it, and new gems drop in at the top.
function collapse() {
  for (let c = 0; c < N; c++) {
    let write = N - 1
    for (let r = N - 1; r >= 0; r--) {
      if (board[r][c] < 0) continue
      board[write][c] = board[r][c]
      write--
    }
    for (let r = write; r >= 0; r--) board[r][c] = randomGem()
  }
}

  collapse()
```

What it means

Your turn

  1. Above function cellAt(event) { write the comment and collapse.
  2. In trySwap, call collapse() above return true.

Skills: Arrays and objects, Loops

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