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

Find every match

What we are doing

findMatches finds every cell that is part of three or more of one color in a row or a column. From each cell it looks right and down; it counts a run only from its first gem, and collects the cells in a Set.

```js
// Every cell that is part of three or more of the same color in a row or a column.
function findMatches() {
  const cells = new Set()
  for (let r = 0; r < N; r++) {
    for (let c = 0; c < N; c++) {
      const gem = board[r][c]
      for (const [dr, dc] of [[0, 1], [1, 0]]) {
        // Only start counting at the first gem of a run.
        const pr = r - dr
        const pc = c - dc
        if (pr >= 0 && pc >= 0 && board[pr][pc] === gem) continue
        let length = 1
        while (r + dr * length < N && c + dc * length < N && board[r + dr * length][c + dc * length] === gem) length++
        if (length >= 3) for (let i = 0; i < length; i++) cells.add((r + dr * i) * N + (c + dc * i))
      }
    }
  }
  return cells
}
```

What it means

Your turn

Write the comment and findMatches above function swap(a, b) {.

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