Search code examples
javascriptarrays2048

How to store the numbers for the 2048 game


I have been trying to implement the game 2048.

I can add numbers in random positions of the grid and I can also slide them to a side, as that is what the console.log shows me.

But somehow I am not able to maintain that effect of a slide. Whenever I call key again, the rows are like there was no effect of the previous slides.

function slide(row) {
  arr = row.filter(e => e);
  let missing = 4 - arr.length;
  let zeros = Array(missing).fill(0);
  arr = arr.concat(zeros);
  console.log(arr);
  return arr;
}

function key() {
  for (let i = 0; i < 4; i++) {
    slide(grid[i]);
  }
  addNumber();
}

Solution

  • The problem is that you do not modify the row that the function receives as argument. Instead you create a new array, which you return. But then the caller does not process the return value.

    Instead of:

    for (let i = 0; i < 4; i++) {
        slide(grid[i])
    }
    

    do:

    for (let i = 0; i < 4; i++) {
        grid[i] = slide(grid[i])
    }
    

    Now your grid will actually stay in sync with what the slide function does.