How to make a text blink in PyGame?

Viewed 240

Like this, but it doesn't have to fade out or any other advanced way.

font_fade = pygame.USEREVENT + 1
pygame.time.set_timer(font_fade, 1)
if event.type == pygame.KEYDOWN:
    click_to_start()
    
if event.type == font_fade:
    text('press  any  button  to  start', (0, 0, 0), screen, screen.get_width() / 2, screen.get_height() - 70, 20)

i have tried with USEREVENT, but it blinks so fast and does not works sometimes

1 Answers

The unit of time of pygame.time.set_timer is milliseconds. IF you want to define an interval of 1 second you have specify a time of 1000 milliseconds:

pygame.time.set_timer(font_fade, 1)

pygame.time.set_timer(font_fade, 1000)

You need to draw the text in the application loop. If you want the a blinking text you have to draw it once and not draw it once.
Add a Boolean variable show_text. Toggle the variable when the event occurse. Draw the text depending on the variable:

while True:
    for event in pygame.event.get():
        # [...]

        if event.type == font_fade:
            show_text = not show_text     

    # [...]

    if show_text:
        text('press  any  button  to  start', (0, 0, 0), screen, screen.get_width() / 2, screen.get_height() - 70, 20)

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((500, 100))
clock = pygame.time.Clock()

font_fade = pygame.USEREVENT + 1
pygame.time.set_timer(font_fade, 200)

font = pygame.font.SysFont(None, 40)
text_surf = font.render('press  any  button  to  start', True, (255, 255, 0))    
show_text = True

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False     
        if event.type == font_fade:
            show_text = not show_text     

    window.fill(0)
    if show_text:
        window.blit(text_surf, text_surf.get_rect(center = window.get_rect().center))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()
Related