【问题标题】:I can`t draw an image of a Sprite in Pygame我无法在 Pygame 中绘制 Sprite 的图像
【发布时间】:2020-03-07 21:50:17
【问题描述】:

这是我的代码 在 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: 'Ball' 对象没有属性 'rect'

【问题讨论】:

    标签: python pygame sprite attributeerror


    【解决方案1】:

    AttributeError: 'Ball' 对象没有属性 'rect'

    嗯,这是正确的,你的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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      相关资源
      最近更新 更多