pythontimepygametimedelay

Time delay in python/pygame without disrupting the game?


I was writing the code for the introduction to a game I was making, here introduction being blitting a series of images with a time delay of 4 seconds in between them. The problem is, using the time.sleep method also messes with the main loop and the program thus "hangs" for that period. Any suggestions please? [Intro and TWD are sound objects]

a=0
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
            Intro.stop()
            TWD.stop()
    if a<=3:
        screen.blit(pygame.image.load(images[a]).convert(),(0,0))
        a=a+1
        if a>1:
                time.sleep(4)
    Intro.play()
    if a==4:
            Intro.stop()
            TWD.play()

    pygame.display.update()

Solution

  • You could add in some logic in that will only advance a if 4 seconds have passed. To do this you can use the time module and get a starting point last_time_ms Every time we loop, we find the new current time and find the difference between this time and last_time_ms. If it is greater than 4000 ms, increment a.

    I used milliseconds because I find its usually more convenient than seconds.

    import time
    
    a=0
    last_time_ms = int(round(time.time() * 1000))
    while True:
        diff_time_ms = int(round(time.time() * 1000)) - last_time_ms
        if(diff_time_ms >= 4000):
            a += 1
            last_time_ms = int(round(time.time() * 1000))
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
                Intro.stop()
                TWD.stop()
        if a <= 3:
            screen.blit(pygame.image.load(images[a]).convert(),(0,0))
            Intro.play()
        if a == 4:
            Intro.stop()
            TWD.play()
    
        pygame.display.update()