Python timer on randint
Question: If I have this code:

    
    
    r = randint(0, 255)
    g = randint(0, 255)
    b = randint(0, 255)
    screen.fill((r, g, b))
    

How do I set it so that it chooses a random number every, say, 10 seconds?


Answer: There are **many different** approaches for that problem. :)

A very simple and quick and dirty method is to **pause the game** (i.e. set a
delay) in the main game loop for an amount of time. You could use PyGames
[`pygame.time.delay()`](http://www.pygame.org/docs/ref/time.html#pygame.time.delay)
function:

    
    
    #import pygame and randint function from random module
    import pygame
    from random import randint
    
    pygame.init()
    
    screen = pygame.display.set_mode((800,800)) #create screen
    
    while True:
        #get events from the event queue
        for ev in pygame.event.get():
            if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                    pygame.quit()
                    exit()
    
        #create random variables r, g and b
        r = randint(0, 255)
        g = randint(0, 255)
        b = randint(0, 255)
    
        #fill screen
        screen.fill((r, g, b))
    
        #update whole screen
        pygame.display.flip()
    
        #set timout for 500ms (i.e. pause game for 500ms)
        pygame.time.delay(500)
    

The problem with this approach is, that you **can´t get any events** and do
some stuff **for the amount of time (e.g. 500ms) the game pauses**.

To avoid this problem you could **create** your very **own event which appears
on the event queue every given number of milliseconds**. You could use
[`pygame.time.set_timer()`](http://www.pygame.org/docs/ref/time.html#pygame.time.set_timer)
to create an event:

    
    
    import pygame
    from random import randint
    
    pygame.init()
    
    #create a new event id called event_500ms
    event_500ms = pygame.USEREVENT + 1
    
    #set timer event to appear on the event queue every 500 number of milliseconds
    pygame.time.set_timer(event_500ms, 500)
    
    screen = pygame.display.set_mode((800,800))
    
    while True:
        #get events from the event queue
        for ev in pygame.event.get():
            if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                    pygame.quit()
                    exit()
    
            #check for event_500ms event
            if ev.type == event_500ms:
    
                r = randint(0, 255)
                g = randint(0, 255)
                b = randint(0, 255)
    
                screen.fill((r, g, b))
    
                pygame.display.flip()
    

I hope this helps :)

