[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Pausing a function



In my game I use iterators for saving animation state. The code winds up something like:

class AnimatedSomething(pygame.sprite.Sprite):

	def __init__(self, images, x, y):
		self.imageiter = iter(images)
		self.rect = pygame.Rect(x, y, 0, 0)

	def update(self):
		try:
			self.image = self.imageiter.next()
			self.rect = self.image.get_rect(center=self.rect.center)
		except StopIteration:
			self.kill() # Done with animating

Create that puppy, shove it in a sprite group (or have it do it itself) and away you go. The above only goes once through the frames, but it would be simple to modify to cycle through (just use itertools.cycle() instead of iter()).

-Casey

On Sep 21, 2007, at 11:58 AM, Michael George wrote:

You might be able to restructure your code a little less if you use generators to simulate coroutines. For example:

def anim1():
   for frame in frames:
      self.image = frame
      yield

def anim2():
   for i in range(10):
      self.rect.move_ip(0, 10)
      yield

anims = [anim1(), anim2()]

while playing:
   # handle events
   for a in anims:
      a.next()
   # update screen

I haven't actually used this technique in pygame so I don't know if it's actually helpful here, but I think it's kind of a cool way of simulating threads without threads. Anyone else have experience with designing code this way?

--Mike

Casey Duncan wrote:
You will need a loop that continuously calls methods to update, draw and refresh the screen. At the top of the loop you could check for events to see if you need to do anything. Basically something like:

clock = pygame.time.Clock()
while playing:
    for event in pygame.event.get():
        handle_event(event)
sprites.update() # update all sprites, including ambient animation
    dirty = sprites.draw(screen)
    pygame.display.update(dirty)
pygame.display.flip() # May not be necessary depending on display config
    clock.tick(40) # Limit to 40 fps (set this to whatever you like)

You can also be kinder to the system by inserting a short time.sleep() in there, but I'll leave that as an exercise for the reader ;)

-Casey

On Sep 21, 2007, at 11:19 AM, Samuel Mankins wrote:

Hi.
Is there a way to pause one function, but to keep all the others going? I'm building a 2D RPG, and my current animation function uses pygame.time.wait(), which is good, but means I can't have "ambient" animations (Things that move around randomly, like plants waving in the wind), and I can only have on going at a time. Does anyone know a way around this?

Thanks!