Search code examples
pythonwaitsleep

Python: Sleep methods


I know this is already technically "asked" on this forums but this question is based around a different concept that I couldn't find.

While using time.sleep(whatever) it obviously sleeps, I get that but while using Pygame it will lock up the program. Is there any real method of using a sleep or a pause in the code other than an input that doesn't lock up pygame? I've tried;

time.sleep
pygame.wait and
pygame.delay

these all do the exact same thing. I'm working on a game for a Computer Science class that involves a small animation of 13 photos I have that are slightly different, but when played 0.12seconds apart, it makes it look good, sadly the whole freezing up of the window from wait statements makes it skip and look very bad.

Thanks to whoever can figure out this mystery.


Solution

  • I think you may want to try using the method that is shown here.

    an example of what I mean is this:

    class Unit():
        def __init__(self):
            self.last = pygame.time.get_ticks()
            self.cooldown = 300    
    
        def fire(self):
            # fire gun, only if cooldown has been 0.3 seconds since last
            now = pygame.time.get_ticks()
            if now - self.last >= self.cooldown:
                self.last = now
                spawn_bullet()
    

    notice he uses pygame.time.get_ticks() to check if a variable is less than that and if it is, he passes in the if statement and spawns the bullet.

    a simpler way to view this concept is the following

    curtime = pygame.time.get_ticks() + 10  # the 10 is what we add to make it sleep
    
    while True:  # Create a loop that checks its value each step
        if curtime < pygame.time.get_ticks():  # check if curtime is less than get_ticks()
            print("Sleep is over now!")
            break  # exit the loop
    

    I hope that helps you in any way, it seems like it might be a viable option since it keeps freezing when you use normal functions.

    ONE MORE THING

    do note that pygame.time.get_ticks() will give you the current time in milliseconds, for full documentation on this go here.