Looking at the latest version, the answer is that your code doesnt move the food to a place that isnt occupied by the snake.
So consider this scenario.
My snake is: (i’m not going to use multiples of 16, but 1, for sake of mental maths.)
[[1,1][1,2],[1,3][1,4],[1,5][1,6],[1,7][1,8]]
8 segments long, and has just eaten the food.
Your code says “Put the food down somewhere.” Let’s say it chooses… 1,6.
Then your code later on says:
for(let i = 0; i < snake.length; i++) {
if(food.x == snake[i].x && food.y == snake[i].y) {
food = {
x : Math.floor(Math.random()*((cvsW/unit)-1)+1)*unit,
y : Math.floor(Math.random()*((cvsH/unit)-1)+1)*unit
}
}
}
so let’s trace that.
i = 0, the snake position is [1,1]… Nothing happens.
i = 1, the snake position is [1,2]… Nothing happens.
i = 2, the snake position is [1,3]… Nothing happens.
i = 3, the snake position is [1,4]… Nothing happens.
i = 4, the snake position is [1,5]… Nothing happens.
i=5: at i = 5, the snake position is [1,6]. Ah! We’ve found a problem! Find a new place for the food. The code rolls a new position and chooses… [1,3] and moves on.
i=6, the snake position is [1,7]… Nothing happens.
i=7, the snake position is [1,8]… Nothing happens.
So we’ve finished our loop. The food is at 1,3. On top of our snake.
Considerations for use:
It’s time to learn Filtering arrays and While loops.
When the food is picked up, choose a place for the new food.
While that location is in the array of the snake, choose a new place.
(NOTE: The game in this state will eventually crash, as it tries to place a piece of food in a completely-snake-filled board.)