CallMeAdmiral
CallMeAdmiral

Reputation: 33

How can I display a text a certain amount of duration?

Thank you for your help on my last question, i managed to fix my error.

So i am continuing my small game and i would like the player to see how many points they get (briefly) when they defeat an enemy.

 if bullet_rect.colliderect(enemy1_rect):
#enemy respawn
     enemy1_rect.x = 1350
     enemy1_rect.y = random.randint(0, 500)
#points won display
     points += 100
     points_rect = points_text.render('+ 100$', None, 'Green')
     screen.blit(points_rect, bullet_rect)

This kind of works, but it only displays for just 1 frame! I tried pygame.time.wait,delay,sleep, and i have come nowhere. I would like for it to display for half a second, so maybe since i run the game at 60 FPS capped, display it for 30 frames. Any suggestions? Thank you!

Upvotes: 1

Views: 278

Answers (1)

Rabbid76
Rabbid76

Reputation: 210997

You need to draw the text in the application loop. Use pygame.time.get_ticks to measure time in milliseconds. Calculate the time when the text must vanish and display the text until the time is reached:

text_end_time = 0
text_rect = None

run = True
while run:
    # [...]

    current_time = pygame.time.get_ticks() 

    if bullet_rect.colliderect(enemy1_rect):
        enemy1_rect.x = 1350
        enemy1_rect.y = random.randint(0, 500)
        points += 100
        points_surf = points_text.render('+ 100$', None, 'Green')
        text_end_time = current_time + 2000 # 2 seconds
        text_rect = bullet_rect.copy()

    if text_end_time > current_time
        screen.blit(points_surf, text_rect)

See also Pygame "pop up" text and Adding a particle effect to my clicker game.

Upvotes: 2

Related Questions