Workshop › 15 Puzzle › Step 15 of 27

Arrow keys

What we are doing

The arrow keys feel best when they move a tile towards the gap: Left slides the tile on the right of the gap to the left. A small lookup object says where that tile is.

```js
// An arrow moves the tile on the other side of the gap in that direction: Left slides the tile right of the gap to the left.
document.addEventListener('keydown', (event) => {
  const gap = tiles.indexOf(0)
  const from = { ArrowLeft: 1, ArrowRight: -1, ArrowUp: N, ArrowDown: -N }[event.key]
  if (from !== undefined) {
    event.preventDefault()
    if (neighbors(gap).includes(gap + from)) move(gap + from)
  }
})
```

What it means

Your turn

Above function squareX(i), write the comment and the listener, and leave an empty line. Press Run and try the arrows.

Skills: Keyboard and mouse input

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