1

I have a function like this:

  def valami() :
        pygame.draw.rect(screen, (0, 255, 0), (0, 0, 20, 20)) 
        pygame.draw.rect(screen, (0, 255, 0), (100, 100, 120, 120)) 
        pygame.draw.rect(screen, (0, 255, 0), (200, 200, 220, 220)) 

And this is my main while loop:

  while True:
        valami() 

I want to draw these 3 rectangles one by one every 5 seconds.

1 Answers1

1

Define an array of rectangles and a counter:

rects = [(0, 0, 20, 20), (100, 100, 120, 120), (200, 200, 220, 220)]
counter = 0

Draw the rectangle dependent on counter in valami:

def valami() :
    pygame.draw.rect(screen, (0, 255, 0), rects[counter % len(rects)]) 

Define a user event see (pygame.event) and start a timer with an interval of 5000 milliseconds (5 seconds) before the main loop, See pygame.time.set_timer():

mytimerevent = pygame.USEREVENT + 1
pygame.time.set_timer(mytimerevent, 5000) # 5000 milliseconds  

Increment counter when the timer elapse. A timer can be stopped by calling pygame.time.set_timer() with an interval of 0:

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

        if event.type == mytimerevent: # timer event
            counter += 1
            if counter == 2:
                pygame.time.set_timer(mytimerevent, 0) # stop timer

    screen.fill(0)
    valami()
    pygame.display.flip()

Note, the modulom (%) operator calculates the rest (remainder) of an integral division.
Because of rects[counter % len(rects)] the rectangles will be drawn on by one in a loop, if you don't stop the timer.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174