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

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

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)

最新更新