I know what the problem is!
In Snake, you can't turn around over yourself. In other words, if you are moving left, you can't move right, you have to move up first. However, your code is ordering the snake to move incorrectly without regard to it's previous direction. It shouldn't be able to go up then down etc.
Fix that problem and you will probably fix the whole thing. Make sure the A* algorithm factors in that turning around is an illegal direction.
Here's the correct pseudocode:
- see if we are going in the correct direction
- if yes, continue
- if no, figure out if A* wants us to turn left or right
- move one square
- repeat step 1
The logic should be something like this:
switch (snakeAI.getDirection()) {
case Snake.DIR_LEFT:
if (s.x >= px) { // don't go left anymore
if (s.y > py) {
snakeAI.setDirection(Snake.DIR_UP);
} else if (s.y < py) {
snakeAI.setDirection(Snake.DIR_DOWN);
} else {
// You should probably change this
snakeAI.setDircetion(Snake.DIR_DOWN);
}
}
break;
case Snake.DIR_RIGHT: