Reputation: 350
Hey i'm making this space shooter game in pygame and want to spawn 10 enemies at a time. Here is the code i used:
blocks.append([random.randrange(0, display_width),0])
for block in blocks:
pygame.draw.rect(game_display, green, (block[0],block[1], 30, 40))
for leng in range(len(blocks)):
blocks[leng][1]+=10
for block in blocks:
if block[1]<0:
blocks.remove(block)
Using this code, my screen gets filled with enemies(green rects). Is there any way i can spawn a certain number of enemies at a time and keep spawning more if the enemy goes off the screen or dies?
Upvotes: 0
Views: 484
Reputation: 101052
Instead of a List that represent your enemies, start using the Rect
class (in fact, you should use the Sprite
class, but one step at a time).
So instead of
blocks.append([random.randrange(0, display_width),0])
for block in blocks:
pygame.draw.rect(game_display, green, (block[0],block[1], 30, 40))
we can write
blocks.append(pygame.Rect(random.randrange(0, display_width), 0, 30, 40))
for block in blocks:
pygame.draw.rect(game_display, green, block)
and instead of
for leng in range(len(blocks)):
blocks[leng][1]+=10
for block in blocks:
if block[1]<0:
blocks.remove(block)
we can use (see how much clearer the code becomes):
for block in blocks[:]:
block.move_ip(0, 10)
if not game_display.get_rect().contains(block):
blocks.remove(block)
blocks.append(pygame.Rect(random.randrange(0, display_width), 0, 30, 40))
which will also add a new enemy whenever one leaves the screen. We could also just reset its position, like this:
for block in blocks:
block.move_ip(0, 10)
if not game_display.get_rect().contains(block):
block.x = random.randrange(0, display_width)
So, whenever you want a new rect to appear, just call
blocks.append(pygame.Rect(random.randrange(0, display_width), 0, 30, 40))
which you may want to put into a function, or better use the Sprite class instead
Upvotes: 4