Workshop › Candy Crush-style Match 3 › Step 14 of 29
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()
```write starts at the bottom row.r goes up from the bottom (r--). Gaps are skipped; each gem is copied down to write, and write moves up.write up to 0: they get new random gems.trySwap calls collapse() right after clearing.function cellAt(event) { write the comment and collapse.trySwap, call collapse() above return true.Skills: Arrays and objects, Loops
← Clear the match Two halves of a clear →