Search code examples
pythonpygamespritedraw

How to keep a sprite drawn even after the the condition that drew it is no longer valid?


The question I have has to do with a specific portion of my code in Pygame where I m trying to draw a new sprite onto the screen every couple of seconds.

  def spawn(self):
    self.count += 2
    alien1_sprite = Alien1((rand.randrange(38,462),50))
    rem = self.count % 33
    if rem == 0:
      self.alien1 = pygame.sprite.Group()
      self.alien1.add(alien1_sprite)
      self.alien1.draw(screen) 

Whenever I call the spawn function no sprites exist at the same time, how can I resolve this issue?


Solution

  • The problem is, you create a new Group for each alien. You only have to create the Group once and add the Alien Sprites to this one Group:

    • Create the alien1 Group in the constructor (init) of the class.
    • Add the aliens in spawn method.
    • Draw all the aliens in the Group using your "draw" method. (The name of your method may be different - I don't know)
    class ...
    
        def __init__(self):
            # [...]
     
            self.alien1 = pygame.sprite.Group() # creat the group in the constructor
    
        def spawn(self):
            self.count += 2
            rem = self.count % 33
            if rem == 0:
                alien1_sprite = Alien1((rand.randrange(38,462),50))
                self.alien1.add(alien1_sprite)
          
        def draw(self):    # your draw or render method
    
           # [...]
    
           self.alien1.draw(screen)  # draw all the aliens
    

    Read the documentation of pygame.sprite.Group. The Group manages the Sprites it contains. The Group is the "list" that stores the Sprites.