Search code examples
pythonpygamespritegame-loop

Removing a sprite from Pygame.Group which is declared in a loop


I have found a solution to this problem by moving the sprite off the screen but I was wondering if there was a more ethical way of solving it like removing it from the sprite.group. I have attempted this but because the coin is declared in an if statement it just adds itself back to the screen.

The code is a quick summary of the part of my program that controls the coin. The 'player' is controlled by the user. In my updated code I moved the coin off the screen in the coin.rect.collide if statement.

Class Coin (pygame.sprite.Sprite):
      def __init__(self, x, y):
      super().__init__()

      self.image = image

      self.rect = get rect 
      self.rect.x = y
      self.rect.y = y

class room1(Room):
     def __init__(self):
         Room.__init__(self)

class player (pygame.sprite.Sprite):
     def __init__(self,x,y):
         super().__init__()

         self.image = pygame.image.load ('playerimg.png')
         self.rect = self.image.get_rect()
         self.rect.x = x
         self.rect.y = y

def mainLoop():
    global coin
    coin= Coin(10,10)
    spritegroup = pygame.sprite.group

    gameLoop = 1
    while gameLoop ==1:
         #keyboard controls
         #room changing code

         if room1 == 2:

             if coin.rect.coliderect(player.rect):
                  spritegroup.remove(coin)

             spritegroup.add(coin)


         spritegroup.draw(screen)
         spritegroup.update()

Solution

  • As you have written it, a coin is added to the sprite group on every iteration so long as room1 == 2. What if you placed all the objects in the room just once?

    room1IsLoaded = False
    
    while gameLoop == 1:
      if not room1IsLoaded:
        spritegroup.add(coin)
        room1IsLoaded = True