Text not appearing Pygame with no errors

Viewed 38

I have a game made using pygame, but apparently text isn't working. No error in the console either. This is my code:

font = pygame.font.SysFont("monospace", 55)

def text_screen(text, color, x, y):
    screen_text = font.render(text, True, color)
    gameWindow.blit(screen_text, (x,y))

# rest of code [...]

# then where i need text;
if abs(snake_x - food_x) < 5 and abs(snake_y - food_y) < 5:
        score +=1*10
        print("Score: ", score)
        text_screen("Score: " + str(score * 10), red, 5, 5)
        pygame.display.update()
        food_x = random.randint(20, screen_width / 2)
        food_y = random.randint(20, screen_height / 2)
1 Answers

To make text permanent, you need to draw it every frame, not just once when a collision is detected. Render the text and set a variable (score_surf) when the collision is detected. With the variable set, draw the text in the application loop:

score_surf = None

while True:
    # [...]

    if abs(snake_x - food_x) < 5 and abs(snake_y - food_y) < 5:
        
        score += 10
        print("Score: ", score)
        score_surf = font.render("Score: " + str(score), True, red)

        food_x = random.randint(20, screen_width / 2)
        food_y = random.randint(20, screen_height / 2)

    # [...]

    if score_surf != None: 
       gameWindow.blit(score_surf, (5, 5))
        
    # [...]

    pygame.display.update()
Related