You are basing your new direction on the tail rather than the head. d
is set on every iteration of the loop, which means the only one that matters is the last. So since your tail is facing down in the example, d
is set to down.
You either need to examine the tail before the reverse, and then reverse d
or examine the head instead of the tail.
Assuming the snake is at least length 2, do the following, outside of the loop:
if(snake_array[0].x<snake_array[1].x){
d="left"; // left or right depending on how your coordinate system works
} ...
This will just look at the facing of the head. You would probably want a check to see if the snake is only length 1, and then just reverse your current direction.