critter333
critter333

Reputation: 33

how to blit a function to screen after keydown event (pygame)

i am trying to make my screen switch from the intro screen to an instructions screen by pressing a space bar. However, when you press the space bar, the instructions screen only stays on as you press it

    for event in pygame.event.get():
    intro_screen()
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            instructions()
            pygame.display.flip()

how do i fix this to last on the screen? also, is it possible i can use the same key to display different functions?

I am a pygame newbie :)

Upvotes: 3

Views: 92

Answers (1)

Kingsley
Kingsley

Reputation: 14906

The code needs to maintain the state of the display. Currently the main loop seems to always draw the "Intro Screen", and, as you say, only draw the "Instructions Screen" on spacebar-event. Also this is put into the event handler code, it probably should be outside that part.

for event in pygame.event.get():
    intro_screen()                               # <-- Draw intro
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            instructions()                       # <-- Draw Instructions
        pygame.display.flip()

It's better to store which screen to show in a variable.

current_screen = 'introduction'              # enumerated type would be better
done = False

# main loop
while not done:
    # handle events
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.KEYDOWN ):
            if ( event.key == pygame.K_SPACE ):
                current_screen = 'instructions'    # switch screens
            elif ( event.key == pygame.K_BACKSPACE ):
                current_screen = 'introduction'    # switch screens back

    # paint the screen
    if ( current_screen = 'introduction' ):
        intro_screen()                             # draw the introduction screen
    elif ( current_screen = 'instructions' ):
        instructions()                             # draw the instructions
    else:
        # TODO - more screen types
        pass

    pygame.display.flip()

Upvotes: 2

Related Questions