Workshop › 15 Puzzle › Step 12 of 27

Neighbours

What we are doing

Only a tile next to the gap can move. In the flat list the neighbours of i are i - N (above), i + N (below), i - 1 and i + 1, but only when they are on the board: position 3 ends a row, and 4 starts the next one.

```js
// The squares next to position i (up, down, left, right), staying inside the board.
function neighbors(i) {
  const list = []
  if (rowOf(i) > 0) list.push(i - N)
  if (rowOf(i) < N - 1) list.push(i + N)
  if (colOf(i) > 0) list.push(i - 1)
  if (colOf(i) < N - 1) list.push(i + 1)
  return list
}
```

What it means

Your turn

Under solvedTiles, leave an empty line and write the comment and neighbors. Press Run.

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