在 pygame 中绘制组成员

draw the member of a group in pygame

我想画群地的单图。但我只有图片 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)

将图像作为构造函数的参数:

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)  

创建对象时将不同的图像传递给构造函数。例如:从列表 gegend 中选择一个随机图像 random.choice:

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

或显示列表中的前 3 张图片:

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