I'm writing a video game with armed space ships.
I decided to make a class to manage all of the bullets
that may be on the screen at a given time:

class Bullets():

        def __init__(self):
                self.bullets = []

        def update(self):
                temp = []
                for bullet in self.bullets:
                        bullet.update()
                        bullet.time_to_live -= 1
                        if bullet.time_to_live:
                                temp.append(bullet)
                self.bullets = temp

        def add(self, new_bullet):
                self.bullets.append(new_bullet)

When the main loop calls .update() on the bullets
object, I want it to decrement a counter on each
bullet, and destroy the bullets who's time has come.

I wanted the bullets to be responsible for destroying
themselves, but a little Googling brought me to points
about dangling references and how an object is not allowed
(nor does it seem to have the means) to destroy itself. 
That's why I made this wrapper class for all of the bullets.

The idea is to copy bullets with time left into a temp list
and then overwrite the man bullets array with the good bullets.
I believe that the other bullets will be garbage collected.
I could not delete the items in place within the loop, of course.
Was there a better container than a list for my purposes?

Above is what I settled on, but I wonder
whether my approach is a good one.

Thanks very much,

Toby
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to