There may be a much better way to manage artillery.

draeath draeath.spamtrap at gmail.com
Sun May 10 22:25:56 EDT 2009


Tobiah wrote:

> 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

This also gives you the means to destroy the oldest bullet when creating a 
new one, once some arbitrary limit was reached. Think back to how old games 
like Raptor worked.

If you had the bullets take care of their lifetime themselves, you would 
have to have more code touching all the bullets to do this. Now, you can add 
a little bit while you are already working through them all, saving yourself 
some cycles I would wager.





More information about the Python-list mailing list