Workshop › 15 Puzzle › Step 17 of 27

Shuffle with real slides

What we are doing

A puzzle must start mixed. We start from the solved board and make 200 random slides, never undoing the one just made. Every board reached like this can be solved by playing the slides backwards.

```js
// Mix the tiles by making random slides, so the puzzle can always be solved.
function shuffle(count) {
  let gap = tiles.indexOf(0)
  let previous = -1
  for (let n = 0; n < count; n++) {
    const options = neighbors(gap).filter((i) => i !== previous) // do not undo the last slide
    const i = options[Math.floor(Math.random() * options.length)]
    tiles[gap] = tiles[i]
    tiles[i] = 0
    previous = gap
    gap = i
  }
}

  tiles = solvedTiles()
  shuffle(200)
```

What it means

Your turn

  1. Above function reset(), write the comment and shuffle, and leave an empty line.
  2. In reset, under tiles = solvedTiles(), write shuffle(200). Press Run a few times.

Skills: Loops, Arrays and objects

All steps

  1. A board in one list
  2. The canvas and the pen
  3. Paint the table
  4. A function that draws
  5. Row and column
  6. Where each square is
  7. Draw one tile
  8. The number on the tile
  9. All the tiles
  10. Draw again and again
  11. The solved board from N
  12. Neighbours
  13. Slide a tile
  14. Click a tile
  15. Arrow keys
  16. Count the moves
  17. Shuffle with real slides
  18. Which boards can be solved?
  19. Is it solved?
  20. Remember the slide
  21. Count the frames
  22. Smooth sliding
  23. Solved!
  24. Show the win
  25. Play again
  26. A record to beat
  27. Build it yourself: a timer