[Tutor] break
Mitya Sirenef
msirenef at lightbird.net
Thu Mar 14 23:56:31 CET 2013
On 03/14/2013 06:38 PM, Matthew Ngaha wrote:
> i cant seem to break out of this loop. let me explain the variables you see:
>
> Enemy.ships = [] #an Enemy class variable that contains enemy ships
> self.missiles = [] an instance variable that appends how many Visible
> missiles my ship has fired
> Enemy.rects = [] an Enemy class variable that represents a rectangle
> for every ship in Enemy.ships
> Explosion() = a class where explosions occur
> QPoint() = is a pyqt function that takes a point x, y position as
arguments
>
> im trying to destroy the ships if they hit a missile, even though i
> use pyqt this is mainly python code
>
> if Enemy.ships:
> for missile in self.missiles:
> for rect in Enemy.rects:
> if QPoint(missile.x + 5, missile.y) in rect:
> explosion = Explosion(rect.x(), rect.y())
> self.explosions.append(explosion)
> break
>
> once the missile has hit 1 Enemy.rect i want to break and go to the
> next missile so the missile is destroyed and doesnt hit another Enemy,
> but for some reason the break i have isnt working and the same missile
> sometimes is hitting 2 different rects on the same iteration. i have
> done the same loop using a simple print statements on strings greater
> than a certain length and it breaks correctly. anyone have any ideas
> why the break isnt breaking out of the nested/inner loop but instead
> continuing to loop through the Enemies?
>
Yes, break statement exits only the current loop, not all loops.
One good approach is to have a separate function or method with
both loops:
def attack(self, Enemy):
for missile in self.missiles:
for rect in Enemy.rects:
if QPoint(missile.x + 5, missile.y) in rect:
explosion = Explosion(rect.x(), rect.y())
self.explosions.append(explosion)
return
You could also set a flag and check it at the end of outer loop
and have a second break statement when the flag is set.
HTH, -m
--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
Fanaticism consists of redoubling your effort when you have forgotten your
aim. George Santayana
More information about the Tutor
mailing list