[英]Enemies in pygame
Hey i'm making this space shooter game in pygame and want to spawn 10 enemies at a time. 嘿,我正在pygame中制作这个太空射击游戏,想一次生成10个敌人。 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? 如果敌人离开屏幕或死亡,我有什么办法可以一次产生一定数量的敌人,并继续产生更多的敌人?
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). 开始使用Rect
类而不是代表敌人的列表(实际上,您应该使用Sprite
类,但一次只能使用一个步骤)。
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 您可能希望将其放入函数中,或者更好地使用Sprite类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.