简体   繁体   中英

Why is the “Game Over” text not displayed?

I have this code, and when I click ESC , I don't see "Game Over". The program waits for two seconds and closes without displaying text. Pygame 1.9.6

What am I doing wrong?

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            pygame.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x_change = -block_size
                lead_y_change = 0
            elif event.key == pygame.K_RIGHT:
                lead_x_change = block_size
                lead_y_change = 0
            elif event.key == pygame.K_UP:
                lead_x_change = 0
                lead_y_change = -block_size
            elif event.key == pygame.K_DOWN:
                lead_x_change = 0
                lead_y_change = block_size
            elif event.key == pygame.K_ESCAPE:
                run = False

    game_display.fill(white)
    lead_x += lead_x_change
    lead_y += lead_y_change
    pygame.draw.rect(game_display, black, [lead_x, lead_y, width, height])
    pygame.display.update()

    clock.tick()

draw_text_middle("Game Over", 40, (0, 0, 0, 255), game_display)
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()

You've to remove the pygame.quit() call from the event loop. pygame.quit() uninitialize all pygame modules. After calling this function, nothing can be drawn any further calls to any pygame instructions will cause an exception.
I recommend to process the pygame events by pygame.event.pump() before .delay the application. This allows pygame to handle internal actions:

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            # pygame.quit() <---------- delete

    # [...]

draw_text_middle("Game Over", 40, (0, 0, 0, 255), game_display)
pygame.display.update()

pygame.event.pump()

pygame.time.delay(2000)
pygame.quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM