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:
after the if: