Question

So, I create my own Snake game with AI, but now I have very-very weird snake actions.

Video

So, my algorithm is:

  1. Get map with: 1 - path is clear, 0 - no path(walls, snake)
  2. Get fruit position
  3. Get SnakeAI head position
  4. Send it to A* algorithm(work correctly)
  5. Get path (Array of Points; end is fruit position, start is snakeAi head)
  6. Set direction of snakeAI

Code on Pastebin

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.

Was it helpful?

Solution

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:

  1. 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
  2. move one square
  3. 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:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top