1

So, i have this code:

import pygame
pygame.init() 
surface = pygame.display.set_mode((400,1000)) 
surface.fill((0,0,0))
color = (255,0,255)

pygame.draw.rect(surface, color, pygame.Rect(100, 100, 50, 50)) 

pygame.draw.rect(surface, color, pygame.Rect(200, 200, 50, 50)) 

pygame.draw.rect(surface, color, pygame.Rect(100, 200, 50, 50)) 

pygame.draw.rect(surface, color, pygame.Rect(200, 100, 50, 50)) 
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    pygame.display.update()

And i was wondering how to change the rectangle's colors live (like in real time i guess), i have tried using the time module but im new to it so i don't understand it all that well.

1 Answers1

0

You have to redraw the entire scene in each frame. he typical PyGame application loop has to:

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.
For a timer event you need to define a unique user events id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). See also Is there a way to have different tick rates for differents parts of my code in pygame?.

Define a list of colors and use random.shuffle to change the colors when the timer event occurs.

import pygame, random

pygame.init() 
surface = pygame.display.set_mode((400,1000)) 
clock = pygame.time.Clock()

timer_interval = 500 # 0.5 seconds
timer_event_id = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event_id, timer_interval)

colors = [(255,0,0), (255,255,0), (0,255,0), (0,0,255)]

running = True
while running:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == timer_event_id:
            random.shuffle(colors)

    surface.fill((0,0,0))
    pygame.draw.rect(surface, colors[0], pygame.Rect(100, 100, 50, 50)) 
    pygame.draw.rect(surface, colors[1], pygame.Rect(200, 200, 50, 50)) 
    pygame.draw.rect(surface, colors[2], pygame.Rect(100, 200, 50, 50)) 
    pygame.draw.rect(surface, colors[3], pygame.Rect(200, 100, 50, 50)) 
    pygame.display.update()

pygame.quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174