Search code examples
pythonfunctionpygamereturn

One of my pygame screens is running 2 times when I import a function that returns 2 variables from another file


I have a pygame project, which I have divided into 3 different screens: initial screen, game screen and play again screen. On the game screen I want to return the state of the game as well as the highscore so that I can show it on the play again screen. But my game screen is running twice before going do the play again screen.

# Game Loop

state = INIT
while state != DONE:
    if state == INIT:
        state, highscore = init_screen(screen)
    elif state == PLAYING:
        state, highscore = game_screen(screen)
    elif state == PLAYAGAIN:
        state = play_again(screen)
    else:
        state = DONE
# What game screen returns

return state, highscore
#What I'm using in the play again screen to get the highscore from the game screen

highscore = game_screen(screen)[1]
hits = pygame.sprite.spritecollide(player, world_sprites, True, pygame.sprite.collide_mask)

        if len(hits) > 0:
            if score > highscore:
                highscore = score
            state = PLAYAGAIN

This last code should make the game screen go to the play again screen, which was working before I decided to put highscores.

Btw, where should I put the first value for to highscore (highscore = 0)?


Solution

  • You call the game_screen() function during your play_again() function. This runs the game_screen() function, which would explain why you are seeing the game run twice. I would suggest storing your highscore in a global variable then using that in your play_again() function, rather than getting if from your game_screen() function:

    state, highscore = INIT, 0
    while state != DONE:
        ...
    

    Then in your play_again() function, get rid of the line that says:

    highscore = game_screen()[1]
    

    And instead simply say:

    global highscore