0
votes

I am making a game that shows game over on screen at the end of the game and if the player presses any key, the game starts again.

Game over screen is displayed but the problem is that when I am pressing any key, the game is not starting. I suspect function gameOverScreen() is not returning out of while loop, I could not understand why.

This function is called when the game is over, and it's continuously running until the player press any key:

def gameOverScreen():
    textFont = pygame.font.Font('freesansbold.ttf',90)
    while True:
        overSurf = textFont.render('GAME OVER',True,RED)
        overRect = overSurf.get_rect()
        overRect.center = (WINDOWWIDTH/2,WINDOWHEIGHT/2)
        DISPLAYSURF.blit(overSurf,overRect)
        drawPressKeyMessage()
        checkForKeyPress()
        if checkForKeyPress():
            pygame.event.get() #clear event queue
            return
        pygame.display.update()
        FPSCLOCK.tick(FPS)

Function to check key press is:

def checkForKeyPress():
    if len(pygame.event.get(QUIT)) > 0:
        terminate()
    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
        return None
    else:
        return keyUpEvents[0].key

Main function which call all functions is:

def main():
    global FPSCLOCK, DISPLAYSURF, BASICFONT

    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
    pygame.display.set_caption('Wormy')

    showStartScreen()
    while True:
        runGame()
        showGameOverScreen()
1
What calls gameOverScreen() and what code comes immediately after? - micsthepick
As soon as a key is pressed, gameOverScreen should finish, how can you tell code does not execute after? - micsthepick
@micsthepick gameOverScreen() function keep running until a return is countered - Tango
I got it now, check for keypress is called twice. You should store the value in a variable in the first call, and then just use that variable in the second instance. - micsthepick

1 Answers

1
votes

Your keypress handler is called twice.

checkForKeyPress()
    if checkForKeyPress():

The first call strips the event queue of kedown events so the second time it is called there is no keypress, so the loop cannot terminate.

There are two solutions:

either: remove the first call - take away the first of these lines:

checkForKeyPress() -- delete this line
if checkForKeyPress():

or: Store the result in a variable and use the variable in the if statement:

keyPress = checkForKeyPress()
if keyPress:
    ...