user7343338
user7343338

Reputation:

How to freeze a sprite for a certain amount of time in pygame?

Since importing the module "time" and using time.sleep(seconds) freezes the whole screen. How to freeze a sprite for 3, 4 or 5 seconds? I Tried doing this but it freezes the whole pygame for 3 seconds!

elif event.key == pygame.K_q:
time.sleep(3)

Upvotes: 0

Views: 1841

Answers (1)

jsbueno
jsbueno

Reputation: 110746

In Pygame you are responsible for the "main loop", and therefore for all the time management of your game.

This is great for simple drawing examples, and great to "keep in control" of things - but that means that if are the sole responsble for everything that moves and updates on the screen.

When you call pygame.time.delay or time.sleep you pause the whole program - the only way of pausing a certain object and not others, and nt stopping responding events at all, is to build mechanisms in your code that allow for individual object pausing.

For simple code, it can be a simple "pause" attribute and an if verification in your sprite code - for example, given a "frame rate" of 30 updates per second - soemthng along this on your sprite class's update method, if you use that method to actual update the position and "take actions" with your object would be:

class MySprite(BaseSprite):
    def __init__(self, ...):
        self.pause = 0...

    def update(self):
        if self.pause:
            self.pause -= 1
            return 

def main():
   FRAMERATE = 30
   myobject = MySprite(...)

   while True:
       if ...:
           ...

       elif event.key == pygame.K_q:
             myobject.pause = 3 * FRAMERATE
       for obj in all_my_objs:
             obj.update()

Upvotes: 1

Related Questions