-3

First, have a look at this Snake-Game.

My problem is, the method locateApple() generate the apple on a random position.

Sometimes it spawns directly on the snake. How do I prevent this?

A way could be to check the Array of Snake's body. But I dont know how to do this.

Thank you.

2 Answers2

0

you can discard the apple and try a new location if it is no proper location...

Point position = null;
do{
    Point candidate = createRandomLocation();
    double distance = measureDistance(head, candidate);    
    if (distance > 20) { //maybe you check other things as well...
        position = new Poisition(candidate)
    }
}while(position ==null);
Martin Frank
  • 3,445
  • 1
  • 27
  • 47
0

Lets say you have a Coordinate class that holds 2 values for x and y. This class has methods like:

  • int getX(); to get the value of the x coordinate
  • int getY(); to get the value of the y coordinate

Now you also need a CoordinateContainer class that holds a number of Coordinates.

The Coordinate container class can have (among others..) methods like :

  • void add(Coordinate x); to add a Coordinate.
  • Coordinate getCoordinate(Coordinate x); to get a Coordinate
  • `boolean contains(Coordinate x); to check if the container contains a specific coordinate.

and so on.

Now you can represent a snake as a CoordinateContainer.

The implementation of the contains method can look like this:

public boolean contains(Coordinate x){
    for(int i = 0; i < numOfCoordinates; i++) //numOfCoordinates is an int holding how many Coordinates you have passed in the array.
        if(array[i].getX() == x.getX() && array[i].getY() == x.getY()) return true;
    return false; // Compare value of X,Y of each Coordinate with the respective X,Y of the parameter Coordinate.
}

Now that you have a way to check if a Coordinate is contained in a CoordinateContainer you are good to go. The method to place apples can look like this:

private void placeNewApple(){
    Coordinate newApple = apples.getRandom(); //<-- getRandom() returns a random Coordinate within the board        
    while(snake.contains(newApple)){
        newApple = apples.getNew();
    }
    placeApple(newApple);// method to place an apple at newApple.getX() , newApple.getY();
}

Hope this makes sense

NOTE: If you don't have to/want to do it this way, i.e with seperate classes, and you only have an Array in a main programm please add some code to your questions and i will update my answer.

gkrls
  • 2,618
  • 2
  • 15
  • 29