Pygame application doesn't close out the first time

Viewed 54

I am building a small game in pygame and I wanted a function to exit out. However it takes multiple clicks to exit and it is not consistent either. Also the windows exit function is restarting the program, too Here is the part of the code that deals with exiting

    if isKill:
        pygame.mixer.music.stop()
        gameover = myfont.render("Press R to Respawn", False, (255, 255, 255))
        rect = gameover.get_rect()
        rect.center = screen.get_rect().center
        screen.blit(gameover, rect)
        if event.type == KEYDOWN:
            if event.key == K_r:
                gameloop()

and

    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False

*gameloop() is the whole script

3 Answers

Instead of event.type, you can use the pygame builtin event QUIT

Refer the following code

running = True
while running:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
        #Can use pygame.quit() in place of running=False if the above line doesn't work.

This while loop is the starting of gameloop. The contents of the gameloop should be inside it.
Don't call the gameloop() function inside the while loop

Perhaps use sys.exit to stop the program. Try:

import sys
import pygame

while 1:

    #code

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

In your game loop, you should always keep the loop running at one level. In your code, the respawn actually freezes the current level and reruns the game at a lower level. This is why several quit commands are required to exit the game.

When the player respawns, reset the game variables, then continue the game loop.

Update your code similar to this:

if isKill:  # game is over
    pygame.mixer.music.stop()
    gameover = myfont.render("Press R to Respawn", False, (255, 255, 255))
    rect = gameover.get_rect()
    rect.center = screen.get_rect().center
    screen.blit(gameover, rect)
    if event.type == KEYDOWN:
        if event.key == K_r:
            #gameloop() # remove this
            dospawn()  # initialize\reset game variables here (can use same function at game start)
            isKill = False  # start new game
    continue  # skip rest of game process
Related