kafka
kafka

Reputation: 129

Variable in for loop could not increment

This is part of a project concerning a shooting game. The variable fail_times is not increasing as it is supposed to. How should I handle this issue?

def check_fail(bullets,stats,screen,fail_times):   
        for bullet in bullets:  
            if bullet.rect.right>=screen.get_rect().right:  
                bullets.remove(bullet)    
                fail_times+=1    
                print(fail_times)    
            elif fail_times>3:
                stats.game_active=False   
                pygame.mouse.set_visible(True)    

Upvotes: 0

Views: 399

Answers (1)

wogsland
wogsland

Reputation: 9518

If you create a class with a class variable it'll have the scope you're looking for:

class game:
    def __init__(self, fail_times=0):
        self.fail_times = fail_times

    def check_fail(self, bullets, stats, screen):
        for bullet in bullets:
            if bullet.rect.right >= screen.get_rect().right:
                bullets.remove(bullet)
                self.fail_times += 1
                print(fail_times)
            elif fail_times > 3:
                stats.game_active = False
                pygame.mouse.set_visible(True)

Then to use it you have to instantiate the class:

my_game = game()
my_game.check_fail(bullets, stats, screen)

Upvotes: 2

Related Questions