How to draw rectangles from a list in pygame

Viewed 99

It says rect argument is invalid but when I give the same rect without a variable it works, here is the part of a code responsible for it

class Background:
    def __init__(self, background):
        self.background = background
        self.endpoint = 5590
        self.bx = 0
        self.scrolling_right = False
        self.scrolling_right = True
        self.obstacleses = []
    
    def obstacles(self):
        self.obstacleses = pygame.Rect(300, 300, 20, 60)
        print(self.obstacleses)

    def surface(self):
        screen.blit(self.background, (self.bx, 0))
        screen.blit(templar1.image, templar1.pos)
        screen.blit(Rogue.image, Rogue.pos)  
        pygame.draw.rect(screen, (255, 0, 0), self.obstacleses)
        pygame.display.update()

I also tried self.obstacleses(0) in pygame.draw.rect but then i get list object is not callable.

2 Answers

You have to draw the rectangles in a loop:

for obstacle in self.obstacleses:
    pygame.draw.rect(screen, (255, 0, 0), obstacle)
import pygame
...
screen = pygame.display.set_mode((WIDTH, HEIGHT))
RECTS = []
RECTS.append(  pygame.Rect(10, 10, 60, 60) )

# Use this in mainloop
for rect in RECTS:
    pygame.draw.rect(screen, GREEN, rect)

Related