Pygame how to change background colour without erasing anything else

Viewed 223

I'm making this drawing thing in Python with Pygame. I have functions that draw circles and rectangles, but I want to add a function that lets me change the background colour, while not erasing the other circles and rectangles. Here is the code for the rectangles:

def drawRect(surface, colour, x, y, w, h):
     pygame.draw.rect(surface, colour, (x, y, w, h))
if event.type == pygame.KEYDOWN:
     if event.key == pygame.K_s:
        #print("pressed")
        drawRect(screen, RANDOM_COLOUR, RANDOM_X, RANDOM_Y, RANDOM_SIZE_X, RANDOM_SIZE_Y)
        pygame.display.flip()

A function for it would be best, but any solution would work.

1 Answers

You can't. You have to redraw the entire scene in each frame.

Create classes for the shapes. For instance RectShape

class RectShape:
    def __init__(self, colour, x, y, w, h):
        self.colour = colour
        self.rect = pygame.Rect(x, y, w, h)
    def draw(self, surface):
        pygame.draw.rect(surface, self.colour, self.rect)

Add the shapes to a list. Clear the background with the color you want, draw all the shapes in the list, and refresh the display in every frame:

object_list = []

background_color = pygame.Color('gray')

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_s:
                rect = RectShape(RANDOM_COLOUR, RANDOM_X, RANDOM_Y, RANDOM_SIZE_X, RANDOM_SIZE_Y)
                object_list.append(rect)

    screen.fill(background_color)

    for obj in object_list:
        obj.draw(screen)

    pygame.display.flip()
Related