Reputation: 1623
I need to make a list of sprites, each of which should have some kind of a timer, so it can perform an action on its own ( like shooting every 10 sec for example). But they will be created and added new ones at a different time, so each of them should has its own timer. I know how to make list of sprites, but I don't know how to attach a timer to each of them or something like that. Can someone help me?
Upvotes: 0
Views: 348
Reputation: 5844
You could add the timer as an attribute of the sprites:
class Sprite:
def __init__(self, ...):
self.timer = pygame.Clock()
# ...
# ...
Or (make sure there is no member already called timer
):
for sprite in sprites:
sprite.timer = pygame.Clock()
Or you could change your list into a list of tuples, containing a sprite and a timer:
sprites = [(sprite, pygame.Clock()) for sprite in sprites]
This will make a list with the format:
[(sprite, timer), (sprite, timer), ...]
You can then access the sprite and timer:
sprite = sprites[0][0] # first sprite
timer = sprites[0][1] # first timer
Or:
sprite, timer = sprites[0] # first pair
You could also have a dictionary of {sprite: timer}
, and then access the timer for a sprite with sprite_to_timer[sprite]
.
Note: Replace pygame.Clock
by what ever timer you want to use
Upvotes: 3