0

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()
Harbinger
  • 3
  • 1
  • 2

2 Answers2

1

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()
flakes
  • 21,558
  • 8
  • 41
  • 88
1

Use neither time.sleep() nor time.time() with pygame. Use pygame.time functions instead:

FPS = 30 # number of frames per second
INTRO_DURATION = 4 # how long to play intro in seconds
TICK = USEREVENT + 1 # event type
pygame.time.set_timer(TICK, 1000) # fire the event (tick) every second
clock = pygame.time.Clock()
time_in_seconds = 0
while True: # for each frame
    for event in pygame.event.get():
        if event.type == QUIT:
            Intro.stop()
            TWD.stop()
            pygame.quit()
            sys.exit()
        elif event.type == TICK:
            time_in_seconds += 1

    if time_in_seconds < INTRO_DURATION:
        screen.blit(pygame.image.load(images[time_in_seconds]).convert(),(0,0))
        Intro.play()
    elif time_in_seconds == INTRO_DURATION:
        Intro.stop()
        TWD.play()

    pygame.display.flip()
    clock.tick(FPS)

Use pygame.time.get_ticks() if you need a finer time granularity than one second.

jfs
  • 399,953
  • 195
  • 994
  • 1,670