2

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.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
hydraxic
  • 176
  • 7
  • This should help: https://stackoverflow.com/questions/41189928/pygame-how-to-change-background-color – Jakob L Dec 03 '20 at 21:08
  • 2
    I don't think it's possible. – martineau Dec 03 '20 at 21:09
  • 1
    You can't. You have to redraw the entire scene in each frame. – Rabbid76 Dec 03 '20 at 21:14
  • What about using a video mode with a palette & index colour system, like we did in the bad old days? You can then change the palette colour, to change *all* instances of that colour. I just checked the doco, doesn't look like this might be possible anymore. But you could look at https://www.pygame.org/docs/ref/display.html#pygame.display.list_modes - it's probably more trouble than it's worth though. – Kingsley Dec 03 '20 at 22:40
  • Is the issue solved? – Rabbid76 Dec 07 '20 at 12:15

1 Answers1

3

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174