简体   繁体   中英

How to fix: “UnboundLocalError: local variable 'all_sprites' referenced before assignment”

I am making a game and updating the sprites in a game loop, but it says this:

"File "/Users//PycharmProjects/Pygame3/Shoot 'em Up.py", line 505, in game_loop
    all_sprites.update()
UnboundLocalError: local variable 'all_sprites' referenced before assignment"

I assumed this meant making it a global variable, but that didn't work. Maybe I just declared it incorrectly? I gave variables for all the sprites above the game loop, but that didn't work either. Does anyone know how to fix this problem? Thank you!

all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
powerups = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
    newmob()
score = 0

def game_loop():  # Game loop

    game_over = False

    running = True

    while running:

        # keeps loop running at the right speed
        clock.tick(FPS)
        # Process input (events)
        for event in pygame.event.get():
            # print(event)  # prints all events (mouse motions, keys pressed, etc.)
            # checks for closing window
            if event.type == pygame.QUIT:
                running = False

        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_p]:
            pause()

        # shows game over screen and resets stats and graphics
        if game_over:
            game_over_screen()
            game_over = False
            all_sprites = pygame.sprite.Group()
            mobs = pygame.sprite.Group()
            bullets = pygame.sprite.Group()
            powerups = pygame.sprite.Group()
            player = Player()
            all_sprites.add(player)
            for i in range(8):
                newmob()
            score = 0

        # Update
        all_sprites.update()

        # checks to see if a bullet hits a mob and spawns powerups
        hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
        for hit in hits:
            score += 51 - hit.radius
            expl_sound.play()
            expl = Explosion(hit.rect.center, 'lg')
            all_sprites.add(expl)
            if random.random() > 0.95:
                pow = Pow(hit.rect.center)
                all_sprites.add(pow)
                powerups.add(pow)
            newmob()

        # checks to see if a mob hits a player
        hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle)
        for hit in hits:
            player.shield -= hit.radius * 2
            expl = Explosion(hit.rect.center, 'sm')
            all_sprites.add(expl)
            newmob()
            if player.shield <= 0:
                player_die_sound.play()
                death_explosion = Explosion(player.rect.center, 'player')
                all_sprites.add(death_explosion)
                player.hide()
                player.lives -= 1
                player.shield = 100

        # if the player has died and the explosion has finished playing
        if player.lives == 0 and not death_explosion.alive():
            game_over = True

        # checks to see if the player hit a powerup
        hits = pygame.sprite.spritecollide(player, powerups, True)
        for hit in hits:
            if hit.type == 'shield':
                player.shield += random.randrange(10, 30)
                shield_sound.play()
                if player.shield >= 100:
                    player.shield = 100
            if hit.type == 'gun':
                player.powerup()
                power_sound.play()

        # Draw / render
        screen.fill(BLACK)
        screen.blit(background, background_rect)
        all_sprites.draw(screen)
        draw_text(screen, str(score), 18, WIDTH / 2, 10, WHITE)
        draw_shield_bar(screen, 5, 5, player.shield)
        draw_lives(screen, WIDTH - 100, 5, player.lives, player_mini_img)

        # *after* drawing everything, flip the display
        pygame.display.flip()

Below code changes will be solved your problem.

# shows game over screen and resets stats and graphics
if game_over:
    game_over_screen()
    game_over = False
    all_sprites = pygame.sprite.Group()
    mobs = pygame.sprite.Group()
    bullets = pygame.sprite.Group()
    powerups = pygame.sprite.Group()
    player = Player()
    all_sprites.add(player)
    for i in range(8):
        newmob()
    score = 0

    # Update
    all_sprites.update()  # <-- this line should be in this if statement.

The error is clearly mention local variable 'all_sprites' referenced before assignment” . Yes, think what happens when game_over is None from the if statement ? Then your code try to execute all_sprites.update() , so in that time you didn't create all_sprites variable. Which mean you didn't execute the all_sprites = pygame.sprite.Group() in the if statement , because game_over is None . Got it? I think all the below code lines after this example should in your if statement . Otherwise you'll get same error again in all_sprites.add(expl) . Please check it and let me know!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM