Search code examples
pythonpygame

How works sprite. spritecollide?


Want to create a group with 10 images. The images should later on the screen not overlap. I try to check that with sprite.spritecollide. somewhere / somehow images disappear. probably using Spritecollide incorrectly.

ii = -1
while ii < 10:
      ii+=1   
      img = pygame.image.load(f"Bilder/Gegenstaende/geg{ii}.png")    
      img = pygame.transform.scale(img,(100,100))  
      m = Landschaft(img) 
      zzz = 0          
      hits = pygame.sprite.spritecollide(m,land,True)        
      if len(hits) >=1:
        for hit_sprite in hits:
            zzz +=1 
            ii = ii -zzz          
      else: 
        land.add(m)

Solution

  • pygame.sprite.spritecollide() has a doKill argument. If the parameter is True, all pygame.sprite.Sprite objects that collide will be removed from the pygame.sprite.Group.

    You have to pass False to doKill:

    hits = pygame.sprite.spritecollide(m,land,True)

    hits = pygame.sprite.spritecollide(m, land, False)        
    

    Note that if there is no space on the screen, you will get an infinite loop. Use the application loop to add the images one at a time:

    desired_number = 10
    
    while run:
    
        if len(land) < desired_number:
    
            ii = len(land)   
            img = pygame.image.load(f"Bilder/Gegenstaende/geg{ii}.png")    
            img = pygame.transform.scale(img,(100,100))  
            m = Landschaft(img) 
          
            if not pygame.sprite.spritecollide(m, land, False):
                land.add(m)
    
        # [...]