1

我正在为即将出版的一本书写一个简单的 Pygame 教程,我在这个问题上有点受阻。我有两个课程,一个球(bola)和一个桨(raquete)。球精灵来自一个图像,它的类非常简单:

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))

然而,球拍是动态绘制的,因为它的高度和宽度作为参数传递。

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)) 

如您所见,我尝试self.image加载

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

然后得到rect使用self.rect = self.image.get_rect()只是不起作用。

当然,由于我无法获得rectfor raquete,因此碰撞也不起作用。

欢迎所有提示!

4

1 回答 1

1

只需创建一个新的Surface并用正确的颜色填充它:

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) 

既然您已经在使用Sprite该类,那么该imprime函数的意义何在?只需使用 apygame.sprite.Group将您的精灵绘制到屏幕上。也就是说,recta 的成员Sprite用于定位,因此您可以将bola类简化为:

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)
于 2013-09-12T13:55:08.190 回答