Workshop › 2048 › Step 16 of 26

Up and down are columns

What we are doing

Up and down work on columns: read a column from top to bottom as if it were a row, slide it "left" (towards the top), and write it back. Down is the same, reversed. One tested function, reused four ways.

```js
// Every direction is "slide left" on a row or a column, possibly reversed.
function move(direction) {
  const before = JSON.stringify(board)
  const horizontal = direction === 'left' || direction === 'right'
  const reversed = direction === 'right' || direction === 'down'
  for (let i = 0; i < SIZE; i++) {
    const line = horizontal ? [...board[i]] : board.map((row) => row[i])

    if (horizontal) board[i] = row
    else row.forEach((value, r) => (board[r][i] = value))

const directions = { ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down' }
```

What it means

Your turn

  1. Above function move, write the comment.
  2. Replace the reversed line with the horizontal and reversed lines shown.
  3. In the loop, change the line line, and replace board[i] = row with the two lines.
  4. Add ArrowUp and ArrowDown to the table.

Skills: Arrays and objects, Functions

All steps

  1. The board
  2. Sixteen cells
  3. A grid of numbers
  4. A color for every number
  5. Numbers on the tiles
  6. Big numbers, smaller text
  7. Find the empty cells
  8. A new tile
  9. Two tiles to start
  10. Slide a row
  11. Merge equal tiles
  12. Move left
  13. The arrow key
  14. Only real moves count
  15. Right is left, reversed
  16. Up and down are columns
  17. Score
  18. Is there a move left?
  19. Game over
  20. Making 2048
  21. Win and lose screens
  22. Space to go on
  23. Best score
  24. Swipes
  25. A tap is not a swipe
  26. Build it yourself: undo