Search code examples
pythontimepygame

pygame.time.delay() doesn't display the text message for required time


I am trying to create a 5 second long display message for every time the user presses "Return". But the program just pauses for 5 seconds and displays the message for 1 millisecond. This is just a rough representation of the type of code i tried to use.

while running:
    pygame.time.delay(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    keys=pygame.key.get_pressed()
    win.fill((255,255,255))
    if keys[pygame.K_RETURN]:
        text = font.render("You pressed Return", True,(0,0,0))
        win.blit(text, (350,350))
    pygame.display.update()
    if keys[pygame.K_RETURN]:    
        pygame.time.delay(5000)

Solution

  • You to handle the events by either pygame.event.pump() or pygame.event.get() after pygame.display.update(). On some systems the update of the display is finished during the internal event handling. e.g:

    while running:
        pygame.time.delay(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        keys=pygame.key.get_pressed()
        win.fill((255,255,255))
        if keys[pygame.K_RETURN]:
            text = font.render("You pressed Return", True,(0,0,0))
            win.blit(text, (350,350))
        pygame.display.update()
        if keys[pygame.K_RETURN]:
            pygame.event.pump() # <----
            pygame.time.delay(5000)
    

    Anyway I won't do it like that, because the system is not responding, when the application is delayed.
    Use pygame.time.get_ticks() to draw the text for a time span.

    Get the current time in milliseconds:

    current_time = pygame.time.get_ticks()
    

    When RETURN is pressed, then compute the time when the text has to disapear:

    if keys[pygame.K_RETURN]:
        pause_time = current_time + 5000 
    

    Draw the text as long text_time is grater than current_time:

    e.g.:

    running = True
    text_time = 0
    while running:
        pygame.time.delay(10)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        current_time = pygame.time.get_ticks()
        keys = pygame.key.get_pressed()
        if keys[pygame.K_RETURN]:
            text_time = current_time + 5000
    
        win.fill((255,255,255))
        if text_time > current_time:
            text = font.render("You pressed Return", True,(0,0,0))
            win.blit(text, (350,350))
        pygame.display.update()