https://i.stack.imgur.com/P7Ano.png <- Image ~..~
Hopefully the title is somewhat informative.
I am currently making my first game in Java and i need some help with a certain piece of code.
Here we go:
As the snake moves over a red square (hereafter “blob”), the square is repainted with new, randomly generated coordinates. As these coordinates are randomly generated there is a chance of the blob being painted on top of my snake.
I want to avoid that and i’ve made the method generating the random coordinates check them against the current coordinates of the snake. The snake consists of 5x5px segments, each with their own coordinates stored in a 2D-array.
My logic goes as follows: 1) Generate X and Y coordinates. 2) Get the differential of the coordinates (as in, how far they are away from eachother) 3) if they are within COLLISIONRANGE (5px) of eachother -> do not use those coords.
What im really asking:
Is this an alright solution? Is there any glaring faults with the way i check for this?
As i play the game, i get more triggers of the System.out.println(“Log: No-go spawn #” + i); i have there for logging than i would assume is natural.
It seems that the randomly generated coordinates are within COLLISIONRANGE of the snakesegments too often for everything to be correct.
My method:
private void generateBlobCoordinates() {
Random randomGenerator = new Random();
boolean isClearSpawn = true;
int x = randomGenerator.nextInt(BORDER_X_MAX);
int y = randomGenerator.nextInt(BORDER_Y_MAX);
int xDiff;
int yDiff;
// If generated coords are within COLLISIONRANGE, set isClearSpawn to false
for(int i = 0; i < snakeSegments.length; i++) {
if(snakeSegments[i][0] != -1) {
xDiff = Math.abs(x - snakeSegments[i][0]);
yDiff = Math.abs(y - snakeSegments[i][1]);
if(xDiff <= COLLISIONRANGE || yDiff <= COLLISIONRANGE) {
isClearSpawn = false;
System.out.println("Log: No-go spawn #" + i);
break;
}
}
else
break;
}
if(isClearSpawn == true) {
blobX = x;
blobY = y;
}
else
generateBlobCoordinates();
}
You are right to be concerned. You are testing for the OR condition, but need AND. Otherwise you will get a collision anywhere on a row or column where there is a snake!
Change
To