forloop while 循环整合

forloop while loop integration

我如何制作一个 for 循环来重复某种循环本身?

这是 class:

class Target(pygame.sprite.Sprite):
    def __init__(self,piture_path,pos_x,pos_y):
        super().__init__()
        self.image = pygame.image.load(piture_path)
        self.rect = self.image.get_rect()
        self.rect.center = [pos_x,pos_y]

这是创建随机目标的方块:

target_group = pygame.sprite.Group()
for target in range(20):
    new_target = Target("target.png",   
    random.randrange(0,screen_width),random.randrange(0,screen_height))
    arget_group.add(new_target)

此代码块创建了一组要射击的目标,我的目标是如果所有目标都已关闭,则创建一组新的目标,如果可能的话创建一​​个循环。

ps。对不起 pygame 和 python.

的新手

一般来说,您可以嵌套任意多个 for-loops。

for target in range(20):
    # some code
    for i in range(10):
        # other code

但我想这不是你的目标。

my goal is to If all the targets are down create a new set of targets creating a loop if possible.

因此,首先您可以使用 target_group.remove(target) 删除目标。调用len(target_group)returns组的大小

要检查是否所有目标都被摧毁,你可以使用if len(target_group) == 0:

target_group = pygame.sprite.Group()
for target in range(20):
    new_target = Target("target.png",   
    random.randrange(0,screen_width),random.randrange(0,screen_height))
    target_group.add(new_target)

# main loop of your game
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
    # check if a target should be removed
    # target_group.remove(target)

    # check if all targets are down
    if len(target_group) == 0:
        for target in range(20):
            new_target = Target("target.png",   
    random.randrange(0,screen_width),random.randrange(0,screen_height))
    target_group.add(new_target)

希望能帮到你

PS:也许您可以从 pygame 上的一些 Youtube 教程中学习。他们真的很有帮助,尤其是作为初学者。我建议 Tech With Tim (https://www.youtube.com/watch?v=Q-__8Xw9KTM) and DaFluffyPotato (https://www.youtube.com/watch?v=xxRhvyZXd8I&list=PLX5fBCkxJmm3nAalPU6gGfRIFLlghRuYy)。 (我没有足够的声誉来发表评论,所以我只是将其添加到 post)