"""pygame.font: default and system fonts, rendering, measuring text and caching rendered text.""" import pygame pygame.init() screen = pygame.display.set_mode((640, 360)) clock = pygame.time.Clock() default = pygame.font.Font(None, 40) # built-in font, no file needed mono = pygame.font.SysFont("dejavusansmono,consolas,menlo,monospace", 22) # first match wins bold = pygame.font.Font(None, 32) bold.set_bold(True) title = default.render("Pygame fonts", True, "gold") # render once, blit many times w, h = mono.size("Measured text") # size before rendering print("Text size:", w, h, "line height:", mono.get_linesize()) score_cache = {} def score_surface(value): """Re-render only when the value changes: rendering text is slow.""" if value not in score_cache: score_cache.clear() score_cache[value] = bold.render(f"Score: {value}", True, "white") return score_cache[value] score = 0 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: score += 10 screen.fill((20, 26, 46)) screen.blit(title, title.get_rect(midtop=(320, 20))) screen.blit(mono.render("Measured text", True, "lightblue", (40, 60, 100)), (40, 100)) # with background pygame.draw.rect(screen, "white", (40, 100, w, h), 1) screen.blit(score_surface(score), (40, 160)) lines = ["Multi-line text: render each line", "and step down by get_linesize()."] for i, line in enumerate(lines): screen.blit(mono.render(line, True, "white"), (40, 220 + i * mono.get_linesize())) pygame.display.flip() clock.tick(60) pygame.quit()