2

I'm trying to make a snake game. To move the snake I have a 2D array that helps me fill the canvas on the rights places, so to make it move forward my logic is to give to every part of the snake's body (= every index) the position that is in the index of the next one, and the head gets its x position incremented "manually" in the if statement if I am trying to go right for example.

Here I am starting with snake that's length is 3 ([3,3] and [4,3] are the body's parts and [5,3] is the head)

here is my code :

var snake = [[3,3],[4,3],[5,3]];
var dir = "right";
function snakeGo(){
        eraseSnake();

        for(var i = 0; i < snake.length-1; i++){
            snake[i]=snake[i+1];
        }

        if(dir == "right"){
            snake[snake.length-1][0]++;
        }
        drawSnake();
    }

    snakeGo();

but when I am debugging, before the program enters the if, 'snake' is [[4,3],[5,3],[5,3]] and at the end of the if 'snake' is [[4,3],[6,3],[6,3]]

but I think it should be [[4,3],[5,3],[6,3]]..

snake.length-1 = 2 ! why is it incrementing snake1[0] ?

before the if:

enter image description here

after the if:

enter image description here

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
sabak
  • 23
  • 3

1 Answers1

3

The middle array is the same array as the last. It's just a reference to the same exact value. Imagine there are two newscasters, each reporting on the same story. If the story changes, both newscasters will tell you the same update. That's what these arrays are doing. When you say arr1 = arr2, you're just saying that arr1 is now a newscaster for the same story/value- so changing the value associated with one of them changes both of them. To change this, you need to clone the array before assigning it to a new variable.

Replace:

snake[i]=snake[i+1];

with:

snake[i]=snake[i+1].slice(0);

Using .slice(0) on the array is a method to clone a shallow copy of the array (which will be sufficient for your code) so each one is actually its own value.

Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15
  • 1
    wow it's very smart ! thanks you very much ! – sabak Dec 31 '19 at 21:21
  • 1
    No problem! If this is the answer you're looking for, would you mind marking it with an upvote and accepted checkmark? It'll let people know you're happy with the answer and give me some points as well. – Aaron Plocharczyk Dec 31 '19 at 21:22