title: Snake movement in snake game
body: <p>Please, I was following a tutorial on how to make a snake game and I understood everything about the code up until the where the snake has to move. I just don't seem to get the logic of how the snake is moving. The code snippet is shown below:</p>
  
  <pre><code>. . . //the code block to setup the canvas and other basic stuff for the game
  //creating the snake
  var snake_array;  //an array of cells to make up the snake
  function create_snake(){
      var length = 5;   //length of the snake
      snake_array = [] //starting with an empty array
      for (var i = 0; i &lt; length; i++) {
          //this will create a horizontal snake starting from top left
          snake_array.push({x:i,y:0});
      }
  }
  
  create_snake() // invoking the method
  
  //painting the snake
  function paint(){
  
      . . . // code block to clear the trail of the snake on the canvas before the snake moves
  
      var nx = snake_array[0].x;
      var ny = snake_array[0].y;
      if(d == "right") nx++;    //d is a variable updated by the keydown event listener code(not shown here) 
      else if(d == "left") nx--;
      if(d == "up") ny--;
      if(d == "down") ny++;
  
      var tail = snake_array.pop(); // pops out the last cell
      tail.x = nx;
      tail.y = ny;
      snake_array.unshift(tail)
  
      . . . // code block to paint the snake cells
  
      }
  }
  
  paint() // invoking the method
  </code></pre>
  
  <p>My problem is: How does portion of code I outlined above do the work of advancing the snake because when I tried following the code with my browser console, after the call to <code>create_snake()</code>, I have an array of five objects(which represent the snake cells) which have the following property and values : <code>{x:0,y:0}</code>,<code>{x:1,y:0}</code>,<code>{x:2,y:0}</code>,<code>{x:3,y:0}</code>,<code>{x:4,y:0}</code>. After invoking the paint method, I still have an array of five objects but with the following property and values : <code>{x:1,y:0}</code>,<code>{x:0,y:0}</code>,<code>{x:1,y:0}</code>,<code>{x:2,y:0}</code>,<code>{x:3,y:0}</code>. Now how does the snake move forward when <code>d = "right"</code>since the x property/co-ordinate of the last cell of the snake after calling <code>paint()</code> is 1 less than its original value before calling the method, and again, two cells now overlap since two objects in the snake_array now have the same co-ordinate(<code>{x:1,y:0}</code>)</p>