0

I'm making this space invaders type game with pygame and I have this issue where, enemies keep spawning while the time is stopped. I need a fix that removes those enemies from the window ( I use .blit to display my surfaces) right after the time is started again.

E.G:


def draw_on_window(enemy):
   window.blit(enemy)

def main():

    # Command that clears the window of "Enemy surfaces" somehow?? :   
    # window.remove(enemy) ?? 

   run = True
   while run:
     draw_on_window(blue_enemy)
     #game


  • Your code does not provide an option of stopping the game ( or stopping `time` ). Provide a minimal actually working code showing the problem you are facing. – Claudio Aug 20 '22 at 22:08
  • See here: https://stackoverflow.com/questions/2215227/how-to-get-rid-of-pygame-surfaces#2215258 and consider to `draw_on_window(enemy_with_background_color). – Claudio Aug 20 '22 at 22:10
  • Just remove the enemy from the list. – Rabbid76 Aug 21 '22 at 07:31

2 Answers2

0

In pygame you don't remove something from a surface like the window. window.blit(image) draws an image to the window surface.

To clear everything you have to fill the window black.

In pygame you do the following things your main loop normally:

  • fill the screen black window.fill((0, 0, 0))
  • draw everything again
  • handle all events (eg. QUIT, MOUSEBUTTONDOWN...)
  • let the clock tick at a specified frame rate
enemy_coords = [(5, 9), (3, 4)] # just an example
clock = pygame.time.Clock()
max_fps = 60

while run:
    window.fill((0, 0, 0)) # fill the window with black

    for coord in enemy_coords:
        window.blit(enemy_image, coord)

    do_events...

    pygame.display.update()
    clock.tick(max_fps)
Jerry
  • 401
  • 4
  • 11
0

All you need to do is manage the enemies in a list and remove the enemies from the list (see How to remove items from a list while iterating?). Draw only the enemies that are in the list. e.g.: represent the enemies by pygame.Rect objects and remove them when they are out of the window:

def draw_on_window(enemies):
   for enemy_rect in enemies:
       window.blit(enemy_image, enemy_rect)
def main():
    enemies = []
    enemies.append(pygame.Rect(x1, y1, w, h))
    enemies.append(pygame.Rect(x2, y2, w, h))
    
    run = True
    while run:
        
        # [...]

        for enemy in enemies[:]:
            if not enemies.colliderect(window.get_rect())
                enemies.remove(enemy)

        # [...]
       
        draw_on_window(enemies)
        pygame.dispaly.update()

You can remove all items from a list with the clear() method:

enemies.clear()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174