Python pygame - Deleting offscreen sprites
<p>I created a simple 2D game with python 2 and pygame where you have to avoid squares that are moving down. I created this class for the 'enemy':</p>

<pre><code>class Enemy(pygame.sprite.Sprite):

  def __init__(self, game):
      self.groups = game.all_sprites
      pygame.sprite.Sprite.__init__(self, self.groups)
      self.game = game
      self.image = pygame.Surface((TILESIZE + 10, TILESIZE + 10))
      self.image.fill(ENEMY_COLOR)
      self.rect = self.image.get_rect()
      self.x = random.uniform(0, WIDTH - TILESIZE)
      self.rect.x = self.x
      self.y = 0

  def update(self):
      if self.rect.colliderect(self.game.player.rect):
          self.game.deaths += 1
          self.game.score = 0
          self.game.run()
      self.rect.y += (self.game.score + 500) / 50
</code></pre>

<p>Then, I have a thread that creates an instance of the enemy:</p>

<pre><code>class Create_Enemy(Thread):

  def __init__(self):
      Thread.__init__(self)

  def run(self):
      while True:
          while not game.game_paused:
              time.sleep((game.score + 1) / game.speed)
              Enemy(game)
</code></pre>

<p>Then in the draw method i just write <code>self.all_sprites.draw()</code>
The game is an infinite runner, and every frame the enemies move a few pixels down. The problem is that after a bit the game gets laggy since, when the blocks go offscreen, the sprites don't get deleted.
Is there a way to automatically delete the offscreen instances?</p>

<p>I tried the following but it just deletes all the enemies onscreen.</p>

<pre><code>if self.rect.y &gt;= WIDTH:
    self.rect.kill()
</code></pre>

<p>I was thinking I could do something like <code>game.all_sprites.pop(1)</code> (the position 0 is the player) but I couldn't find a way to archive something similar ...</p>