0

I am creating a game program where I need to run through an array list of circle graphics set at x and y coordinates. I need to make sure that none of the circle graphics overlap each other. This is what i have and seems to work sometimes but I think it is creating an infinite loop. Would love if someone could help me with my code.

for (int i = 0; i < circles.size(); i++) {
        if (circles.isEmpty()) {
            graphic.setX(x);
            graphic.setY(y);
            continue;
        }
        if (this.graphic.isCollidingWith(circles.get(i).graphic)) {
            x = rng.nextInt((int)Engine.getWidth());
            y = rng.nextInt((int)Engine.getHeight());   
            i = -1;
        }
        else {
        graphic.setX(x);
        graphic.setY(y);
        }
    }
molldoll
  • 1
  • 1
  • 1
    why do you do `i = -1;` ? – Scary Wombat Apr 27 '17 at 04:36
  • No I am not criticizing your code, I am asking what your intention is. See having a variable named `i` is great for something like a loop index, but when a variable has *other* use, then a well named variable gives the reader some insight into your logic. I do not know what your are trying to achieve with the code `i = -1` **please inform** – Scary Wombat Apr 27 '17 at 04:46
  • if a circle in the array list is colliding with another circle, i reset the x and y coordinates of the current circle being evaluated and then reset i so that the loop can check that the current circle is not colliding with the previous circles in the list. – molldoll Apr 27 '17 at 04:51
  • a) the loop starts at `0` not -1 - do you mean `i = i - 1;`? b) what would happen if `i` was already `0` - you will need to check. c) rather than resetting this loop, call a method that checks the previous element – Scary Wombat Apr 27 '17 at 04:55
  • Yes, consider a nested loop, that is what my suggested `method` would do. – Scary Wombat Apr 27 '17 at 05:02
  • any tips on how to implement this nested loop? I am very confused. would it be a for loop inside of a for loop? – molldoll Apr 27 '17 at 05:05
  • Yes, that is what a nested loop is – Scary Wombat Apr 27 '17 at 05:08

0 Answers0