我无法在Pygame中绘制Sprite的图像

时间:2019-11-12 08:05:59

标签: python pygame sprite attributeerror

这是我的代码 在 Class Ball 中,我的get_rect()方法出错了

pygame.init()
pygame.mixer.init()

size = h, w = 500, 500

screen = pygame.display.set_mode(size)
black=0,0,0
gameover=False
image_ball=pygame.image.load('ball.png')
class Ball(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.transform.scale(image_ball, (50, 50))

        self.ball_rect = self.image.get_rect()
        self.ball_rect.x = random.randrange(w-self.ball_rect.width)
        self.ball_rect.y = random.randrange(-100, 100)
        self.x_speed=5
        self.y_speed=5
    def update(self):
        self.ball_rect.x+=self.x_speed
        if self.ball_rect.right<w:
            self.ball_rect.right=w
        if self.ball_rect.left<0:
            self.ball_rect.left=0
all_sprite=pygame.sprite.Group()
ball_sprite = pygame.sprite.Group()
ball = Ball()
all_sprite.add(ball)
for i in range(10):
    b=Ball()
    ball_sprite.add(b)
    all_sprite.add(b)
while not gameover:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameover = True
    all_sprite.update()
    #draw/render
    screen.fill(black)
    ball_sprite.draw(screen)
    pygame.display.flip()
    pygame.time.wait(10)
sys.exit()

我在绘制self.spritedict [spr] = surface_blit(spr.image,spr.rect)时出错

AttributeError:“球”对象没有属性“矩形”

1 个答案:

答案 0 :(得分:3)

  

AttributeError:“球”对象没有属性“矩形”

好吧,这是正确的,您的Ball类没有rect属性。

因此只需更改

   self.ball_rect = self.image.get_rect()
   self.ball_rect.x = random.randrange(w-self.ball_rect.width)
   self.ball_rect.y = random.randrange(-100, 100)

   self.rect = self.image.get_rect()
   self.rect.x = random.randrange(w-self.ball_rect.width)
   self.rect.y = random.randrange(-100, 100)