forloop while loop integration

Viewed 69

how can I make a for loop to repeat some sort of loop in itself?

this is the 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]

this is the block to create the random targets:

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)

this block of code creates a set of targets to shoot, my goal is to If all the targets are down create a new set of targets creating a loop if possible.

ps. sorry new to pygame and python.

1 Answers

In general you can nest as many for-loops as you want.

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

But I guess that's not what your aiming for.

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

So first of all you can remove a target with target_group.remove(target). Calling len(target_group) returns the size of the group.

To check if all targets are destroyed you can use 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)

I hope I could help you.

PS: maybe you could learn form some Youtube tutorials on pygame. They can be really helpful especially as a begeinner. I'd suggest Tech With Tim (https://www.youtube.com/watch?v=Q-__8Xw9KTM) and DaFluffyPotato (https://www.youtube.com/watch?v=xxRhvyZXd8I&list=PLX5fBCkxJmm3nAalPU6gGfRIFLlghRuYy). (I don't have enought reputation to comment, so I just added that to the post)

Related