Search code examples
pythonpygame

Display list items one after another after 2 sec in Pygame


This is the list

places = ["London", "India", "America", "Australia", "Cambodia", "China", 
          "Dubai", "Egypt",  "France", "Germany", "Japan", "Jordan", 
          "Korea", "Myanmar", "Peru", "Russia", "Singapore", "Spain"]

I randomised the list:

random_place = random.choice(places)

Here I have tried to display random items from the list. I have tried using for loop and time.sleep function but it didn't work.

def text():
    game_font = pygame.freetype.SysFont("monospace", 35)
    text_surface, rect = game_font.render(random_place, (0, 0, 0))
    screen.blit(text_surface, (680, 420))
   
# Game loop
running = True
while running:
    screen.fill((255, 194, 102))  # RGB
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
   
    card()
    text()
    pygame.display.update()

It would be great if anyone could solve this issue.


Solution

  • Use a timer event. In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds.

    Choose a new random card, when the timer event occurs:

    random_place = random.choice(places)
    
    timer_interval = 2000 # 2000 milliseconds = 2 seconds
    timer_event = pygame.USEREVENT + 1
    pygame.time.set_timer(timer_event, timer_interval)
    
    running = True
    while running:
        screen.fill((255, 194, 102))  # RGB
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
            if event.type == timer_event:
                random_place = random.choice(places)
    
        card()
        text()
        pygame.display.update()
    

    Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.