pythontextfontspygameblit

How to show text when true


I want to show a text on the screen when a variable changes to True. The Text "Game Over" is show for a very short period of time with this code but I disappears after less than one second.

import pygame
import random
import time
import math

# Initialize pygame
pygame.init()

# Create window (width, height)
screen1 = pygame.display.set_mode(((800, 600)))
ScreenHeight = screen1.get_height()
ScreenWidth = screen1.get_width()

#Game Over text
go_font = pygame.font.Font('freesansbold.ttf', 128)
go_text = "GAME OVER"
go_textX = 300
go_textY = 300

def show_gameover(go_textX, go_textY):
    gameover_text = font.render(go_text, True, (105, 105, 105))
    screen1.blit(gameover_text, (go_textY,go_textY))

# Variable to track gameover
gameover = False

while running:

    if gameover:
        show_gameover(go_textX, go_textY)


    # Insert Background
    screen1.blit(background, (0, 0))


    i = 0

    for obs in obstacle_list:
        obs.spawn_obstacle()
        obs.update_y()

        outOfBounds = obs.out_of_bounds(playerX, playerY)
        if outOfBounds:
            obstacle_list.pop(i)

        collision = obs.collision_detection(playerX, playerY)
        if collision:

            gameover = True
            show_gameover(go_textX, go_textY)     #Show Gameover-text

        i += 1


    # Update after each iteration of the while-loop
    pygame.display.update()

Solution

  • You have to draw the text after the background. If you draw the text before drawing the background, it will be hidden from the background. Draw it just before updating the display. So it is drawn over all other objects in the scene.

    while running:
    
        # Insert Background
        screen1.blit(background, (0, 0))
    
        # [...]
    
        if gameover:
            show_gameover(go_textX, go_textY)
    
        # Update after each iteration of the while-loop
        pygame.display.update()