So, I create my own Snake game with AI, but now I have very-very weird snake actions.
So, my algorithm is:
- Get map with: 1 - path is clear, 0 - no path(walls, snake)
- Get fruit position
- Get SnakeAI head position
- Send it to A* algorithm(work correctly)
- Get path (Array of Points; end is fruit position, start is snakeAi head)
- Set direction of snakeAI
private void AI() {
Point s = new Point();
//SnakeAI head
Point n = new Point();
//Food
n.x = food.x / 13;
n.y = food.y / 13;
s.x = snakeAI.getBody().get(0).x / 13;
s.y = snakeAI.getBody().get(0).y / 13;
int px;
int py;
//Path
g = f.findPath(map, n, s);
if (g.size() > 0) {
//Next snake positin
px = g.get(g.size() - 1).x;
py = g.get(g.size() - 1).y;
} else {
return;
}
if (s.x == px) {
//Move UP
if (s.y > py) {
snakeAI.setDirection(Snake.DIR_UP);
}
//Move DOWN
if (s.y < py) {
snakeAI.setDirection(Snake.DIR_DOWN);
}
}
if (s.y == py) {
//Move LEFT
if (s.x > px) {
snakeAI.setDirection(Snake.DIR_LEFT);
}
//Move RIGHT
if (s.x < px) {
snakeAI.setDirection(Snake.DIR_RIGHT);
}
}
}
So, I fight with that wrong moves about week, and I really don't know where error is. Yoda Master, help me.