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.