简体   繁体   English

如何解决:“ UnboundLocalError:分配前已引用局部变量'all_sprites'”

[英]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” . 错误显然是local variable 'all_sprites' referenced before assignment” Yes, think what happens when game_over is None from the if statement ? 是的,想想if statement game_overNone时会发生什么? Then your code try to execute all_sprites.update() , so in that time you didn't create all_sprites variable. 然后,您的代码尝试执行all_sprites.update() ,因此在那时您没有创建all_sprites变量。 Which mean you didn't execute the all_sprites = pygame.sprite.Group() in the if statement , because game_over is None . 这意味着您没有在if statement执行all_sprites = pygame.sprite.Group() ,因为game_overNone Got it? 得到它了? I think all the below code lines after this example should in your if statement . 我认为此示例之后的所有以下代码行都应在if statement Otherwise you'll get same error again in all_sprites.add(expl) . 否则,您将在all_sprites.add(expl)再次遇到相同的错误。 Please check it and let me know! 请检查并让我知道!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 UnboundLocalError:赋值前引用的局部变量“o1” - How to fix UnboundLocalError: local variable 'o1' referenced before assignment 如何修复“UnboundLocalError:赋值前引用的局部变量‘books’”? - How to fix "UnboundLocalError: local variable 'books' referenced before assignment"? 如何修复 UnboundLocalError:在 Python 中分配之前引用的局部变量“df” - How to fix UnboundLocalError: local variable 'df' referenced before assignment in Python 如何修复 UnboundLocalError:分配前引用的局部变量“命令” - How do i fix UnboundLocalError: local variable 'command' referenced before assignment 如何修复我的代码中的“UnboundLocalError:分配前引用的局部变量“dc”? - How do I fix 'UnboundLocalError: local variable 'dc' referenced before assignment' in my code? 如何解决此错误“UnboundLocalError:分配前引用的局部变量'a'” - How can I fix this error “UnboundLocalError: local variable 'a' referenced before assignment” UnboundLocalError:分配前已引用局部变量“ totalp” - UnboundLocalError: local variable 'totalp' referenced before assignment unboundLocalError:分配前已引用局部变量“ arm”? - unboundLocalError: local variable 'arm' referenced before assignment? UnboundLocalError:赋值前引用了局部变量“n” - UnboundLocalError: local variable 'n' referenced before assignment UnboundLocalError:赋值前引用的局部变量&#39;html&#39; - UnboundLocalError: local variable 'html' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM