Search code examples
pythonlistpygamerect

how to display a rect inside a list


What i am trying to do is create a list in which i would append a number of rects and then draw them latter using their index. However this appears to not be working for some reason the shape(rect) is not displayed in the app window so i would appreciate it if someone would point me in the right direction or give me another method of doing this.

thanks in advance.

def buffer(self):

    self.blocks = [] # rect container


    """
    ---- creating and appending rects ----

    """

    for x in range(5):
        self.blocks.append(

            pygame.draw.rect(
                self.screen,
                (255,255,0),
                [0,0,50,50]
                )

            )

    while 1:

        self.key = pygame.key.get_pressed()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return 0


        self.screen.fill((0,0,0))

        self.blocks[0] # draw rect

        pygame.display.update()
        self.clock.tick(self.fps)


    pygame.quit()
    sys.exit()
    quit()

Solution

  • Create at least tuples with color, x, y, width, height

    self.blocks = [] # rect container
    
    # creating and appending rects
    
    for x in range(5):
        self.blocks.append( ((255,255,0),[0,0,50,50]) )
    

    Then you can use it to draw rect

    # draw rect
    color, (x, y, w, h) = self.blocks[0] 
    pygame.draw.rect(self.screen, color, pygame.Rect(x, y, w, h)) 
    

    pygame.draw.rect creates rect on the screen but doesn't create object which you can keep on list.