Jace
Jace

Reputation: 11

Python Pause a game with a Key

First of all I want to say sorry for my english. Its not my mother tongue. I want to make a 2D Snake Game with python. I also want to press the button "p" to pause the game, and if I press it again, it should go on normaly. My idea was to use the time.sleep command. If p gets pressed it should start to "count" and implementing it into the sleep command. If I would p again it should stop the timer and also the sleep command. Can someone help me with this, because I can't find something in the internet... I use pygames for the key.

Thank you alot.

Jace

Upvotes: 0

Views: 2095

Answers (1)

Agile_Eagle
Agile_Eagle

Reputation: 1839

You can use this function to pause a game:

def paused():

    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("Paused", largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)


    while pause:
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        #gameDisplay.fill(white)


        button("Continue",150,450,100,50,green,bright_green,unpause)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()
        clock.tick(15)  

If you want to bind it to a key, use this:

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_p:
        pause = True
        paused()

Source: https://pythonprogramming.net/pause-game-pygame/

Upvotes: 1

Related Questions