Question

I am writing a simple Pygame tutorial for an upcoming book and I am sort of blocked in this issue here. I have two classes, a ball (bola) and a paddle (raquete). The ball sprite comes from an image and its class is quite straightforward:

class bola(pygame.sprite.Sprite):

    def __init__(self, x, y, imagem_bola):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.image = pygame.image.load(imagem_bola)
        self.rect = self.image.get_rect()

    def imprime(self):
        cenario.blit(self.image, (self.x, self.y))

The racket, however, gets drawn dynamically as its height and width are passed as parameters.

class raquete(pygame.sprite.Sprite):

    def __init__(self, x, y, l_raquete, a_raquete):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.l_raquete = l_raquete
        self.a_raquete = a_raquete
        self.image = pygame.draw.rect(cenario, branco, (self.x, self.y, self.l_raquete, self.a_raquete))
        self.rect = self.image.get_rect()  # this doesn't work!

    def imprime(self):
        pygame.draw.rect(cenario, branco, (self.x, self.y, self.l_raquete, self.a_raquete)) 

As you can see, my attempt to load self.image with

pygame.draw.rect(cenario, branco, self.x, self.y, self.l_raquete, self.a_raquete))

and then get the rect using self.rect = self.image.get_rect() just doesn't work.

Of course, as I cannot get the rect for raquete, collisions also don't work.

All hints are welcome!

Was it helpful?

Solution

Just create a new Surface and fill it with the right color:

class raquete(pygame.sprite.Sprite):

    def __init__(self, x, y, l_raquete, a_raquete):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((l_raquete, a_raquete))
        # I guess branco means color
        self.image.fill(branco) 
        # no need for the x and y members, 
        # since we store the position in self.rect already
        self.rect = self.image.get_rect(x=x, y=y) 

Since you're already using the Sprite class, what's the point of the imprime function anyway? Just use a pygame.sprite.Group to draw your sprites to the screen. That said, the rect member of a Sprite is used for positioning, so you can simplify your bola class to:

class bola(pygame.sprite.Sprite):

    def __init__(self, x, y, imagem_bola):
        pygame.sprite.Sprite.__init__(self)
        # always call convert() on loaded images
        # so the surface will have the right pixel format
        self.image = pygame.image.load(imagem_bola).convert()
        self.rect = self.image.get_rect(x=x, y=y)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top