Joachim
Joachim

Reputation: 375

draw the member of a group in pygame

I want to draw the single images of the group land. but i got only the image gegend[0]

class Landschaft(pygame.sprite.Sprite):
       
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) 
        self.image = gegend[0] 
        self.rect = self.image.get_rect()            
        self.rect.x = random.randrange(40, breite -20)
        self.rect.y = random.randrange(100, hoehe - 200)  

gegend = []
for i in range(10):
    img = pygame.image.load(f"Bilder/ballons/ballon{i}.png")
    img = pygame.transform.scale(img,(175,175))
    gegend.append(img)  

land = pygame.sprite.Group()
while len(land) < 3:
            m = Landschaft()          
            land.add(m)
        
land.draw(screen)

Upvotes: 1

Views: 126

Answers (1)

Rabbid76
Rabbid76

Reputation: 211135

Make the image an argument of the constructor:

class Landschaft(pygame.sprite.Sprite):
       
    def __init__(self, image):
        pygame.sprite.Sprite.__init__(self) 
        self.image = image
        self.rect = self.image.get_rect()            
        self.rect.x = random.randrange(40, breite -20)
        self.rect.y = random.randrange(100, hoehe - 200)  

Pass different images to the constructor when you create the objects. e.g.: choose a random image form the list gegend with random.choice:

land = pygame.sprite.Group()
while len(land) < 3:
    image = random.choice(gegend)
    m = Landschaft(image)          
    land.add(m)

Or show the first 3 images from the list:

for i in range(3):
    m = Landschaft(gegend[i])          
    land.add(m)

Upvotes: 2

Related Questions