cdd
cdd

Reputation: 109

how to get rect attribute with no image

I am creating a class for boxes. When my main sprite collides with will reset its position. The boxes are rectangles drawn on screen and therefore have no image to self.image.get_rect() from. How can i give boxcollisions a rect attribute?

class boxcollisions(pygame.sprite.Sprite):
    def __init__(self, x, y):
        self.y=y
        self.x=x
        self.rect= self.image.get_rect()
        self.rect.left = self.x
        self.rect.top = self.y
        self.rect.width=16
        self.rect.height=16


    def draw(self,x,y):
        pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(x, y, 15, 15))

Upvotes: 1

Views: 1151

Answers (1)

skrx
skrx

Reputation: 20478

You can either give the class a self.image attribute or create an instance of the pygame.Rect class. (I think Box would be a nicer name for the class.)

pygame.sprite.Sprites need an image if you want to use them with sprite groups, so I'd recommend this variant:

class Box(pygame.sprite.Sprite):

    def __init__(self, x, y):
        self.y = y
        self.x = x
        self.image = pygame.Surface((15, 15))
        self.image.fill((0, 128, 255))
        self.rect = self.image.get_rect()
        self.rect.left = self.x
        self.rect.top = self.y

    def draw(self, screen):
        screen.blit(self.image, self.rect)

Here's the rect variant:

class Box(pygame.sprite.Sprite):

    def __init__(self, x, y):
        self.y = y
        self.x = x
        self.rect = pygame.Rect(self.x, self.y, 15, 15)
        self.color = (0, 128, 255)

    def draw(self, screen):
        pygame.draw.rect(screen, self.color, self.rect)

Upvotes: 1

Related Questions