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

Start without matches

What we are doing

We fill the board row by row, left to right, so when a gem is placed only the cells to its left and above it exist. If the two to its left, or the two above it, have its color, it would make three: then we pick again.

```js
// Would this gem make three in a row with the two to its left, or the two above it?
function makesRun(r, c, gem) {
  const left = c >= 2 && board[r][c - 1] === gem && board[r][c - 2] === gem
  const up = r >= 2 && board[r - 1][c] === gem && board[r - 2][c] === gem
  return left || up
}

// A new board with no three in a row: each gem avoids the colors that would make one.

      let gem
      do gem = randomGem()
      while (makesRun(r, c, gem))
      board[r].push(gem)
```

What it means

Your turn

  1. Above function newBoard() { write the comment, makesRun, and the comment for newBoard.
  2. In newBoard, replace board[r].push(randomGem()) with the four lines.

Skills: Loops, 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