1

These seem to be the relevant portions of a slightly larger program. These are essentially the collision detection functions. bubbles is the original list of circles. I want the circle collided with to disappear on impact. I'm fairly sure my problem lies down there in "if collide ==" conditional.

def getDistance(point1,point2):
    a= point1.getX()
    b= point2.getX()
    c= point1.getY()
    d= point2.getY()
    distance=  math.sqrt((b-a)**2 + ((d-c)**2))
    return distance

def balloonBubbleCollide(balloon,bubble):
    point1 = balloon.getCenter()
    point2= bubble.getCenter()
    distance= getDistance(point1, point2)
    if distance <= 30:
        return True

def check(balloon, bubbles, window):
    for bubble in bubbles:
       collide = balloonBubbleCollide(balloon, bubble)
       if collide == True:
            bubbles.remove(bubble)

Assume main is running them in proper order. Just don't want to bog the post down with code.

aero26
  • 155
  • 1
  • 3
  • 11
  • Don't try to modify a list you're iterating over. – Mark Ransom Oct 25 '14 at 20:21
  • Small comments about your coding style: it is not necessary to compare to True, you can simply say `if collide: ...`. You also seem to like a 'getter' functions a lot, but it is more Pythonic to use attributes for simple parameters (so use `point.x`, `point.y`, `balloon.center`, ...). These can always be upgraded to properties later. – Bas Swinckels Oct 25 '14 at 20:26
  • Interesting @BasSwinckels I've been staying close to what I've been seeing in tutorials. I'll keep that in mind. – aero26 Oct 25 '14 at 20:37
  • @aero26 Using loads of getters and setters seems something you would teach students in a first year course on OO design using Java. It is definitely not common in Python, see e.g. [this question](http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters). I guess the rule of thumb is just use attributes for simple parameters, change them to properties (without any change in syntax for the user) if you later need to add e.g. a simple check for valid before setting, or for getting a value that is easily calculated. For 'expensive' calculations use get/set methods. – Bas Swinckels Oct 25 '14 at 20:55

1 Answers1

1

You should not modify a list using remove while iterating over it.

To filter out the colliding bubbles use instead something like:

def check(balloon, bubbles, window):
    bubbles[:] = [bubble for bubble in bubbles
                  if not baloonBubbleCollide(balloon, bubble)]

the code shown will create a first new list of bubble objects to keep (using a list comprehension) and then replace the current content of the bubbles list with it at once.

6502
  • 112,025
  • 15
  • 165
  • 265