I think I have been staring at this code too long and I am not seeing it. I am writing a small game, in which part of it generates a number of objects (currently shapes). As the shapes are created, they are added to an ArrayList as objects defined by a class. I noticed that as the number of shapes increases, the chance of overlapping shapes increases, which I want to fix. I am trying to do so by checking the Y coordinate against the Y coordinates of each of the existing objects in the ArrayList. But for the life of me I cannot remember the way to keep iterating the check function until I generate Y value that is unique.
My initial solution is a do…while loop, but for some reason it keeps returning true.
I simplified my code a bit, just keeping the parts essential to my question. What am I missing? Thanks in advance for any help.
Edit: Also keep in mind that objects are getting added to and removed from the ArrayList constantly as the game progresses. Every time an object (shape) is removed during the game, it is regenerated. This means that for every object being created during the game, it needs to be checked against the existing objects.
int x, y;
int numShapes = 10;
ArrayList<ShapeObject> soArray = new ArrayList<ShapeObject>();
private boolean checkY(int yy) {
for(int i = 0; i < soArray.size(); i++) {
if(soArray.get(i).oY == yy) {
return true;
}
}
return false;
}
public void makeShapes() {
for(int i = 0; i < numShapes; i++) {
if(soArray.size() < numShapes) {
x = rand.nextInt(width - 45) + 45;
do {
y = rand.nextInt(height - 4) + 2;
} while(checkY(y));
soArray.add(new ShapeObject());
}
}
}
class ShapeObject {
int oX = x;
int oY = y;
}
Since I basically figured out the issue on my own, I am posting it as an answer.
It turns out that I forgot I was restricted by the bounds of my canvas. My cell size is 12px on a grid of 600px. I noticed that it would fail after 46 objects in my ArrayList. So basically all of the available Y coordinates were taken. I was testing with 100 objects so it just kept running.
I also modified the checkY() to be checkXY() so that I could completely control the number of rows and columns (x and y coordinates) that are available for objects.