Created
February 23, 2023 14:08
-
-
Save galatolofederico/aa43e0d3bfce5fd6173fb25c8b48e8f3 to your computer and use it in GitHub Desktop.
pygame function to display multiline texts and auto scroll to the bottom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pygame | |
| import math | |
| pygame.init() | |
| SIZE = WIDTH, HEIGHT = (1024, 720) | |
| FPS = 30 | |
| screen = pygame.display.set_mode(SIZE, pygame.RESIZABLE) | |
| clock = pygame.time.Clock() | |
| def blit_text(surface, text, pos, font, color=pygame.Color('black')): | |
| words = [word.split(' ') for word in text.splitlines()] | |
| space = font.size(' ')[0] | |
| max_width, max_height = surface.get_size() | |
| x, y = pos | |
| rects = [] | |
| row_rects = [] | |
| for line in words: | |
| for word in line: | |
| word_surface = font.render(word, 0, color) | |
| word_width, word_height = word_surface.get_size() | |
| if x + word_width >= max_width: | |
| x = pos[0] | |
| rects.append(row_rects) | |
| row_rects = [] | |
| row_rects.append(word) | |
| x += word_width + space | |
| x = pos[0] | |
| rects.append(row_rects) | |
| row_rects = [] | |
| max_vertical_rects = math.floor(max_height / font.size(' ')[1]) | |
| printable_rects = rects[-max_vertical_rects:] | |
| for line in printable_rects: | |
| for word in line: | |
| word_surface = font.render(word, 0, color) | |
| word_width, word_height = word_surface.get_size() | |
| surface.blit(word_surface, (x, y)) | |
| x += word_width + space | |
| x = pos[0] | |
| y += word_height | |
| text = "This is a really long sentence with a couple of breaks.\nSometimes it will break even if there isn't a break " \ | |
| "in the sentence, but that's because the text is too long to fit the screen.\nIt can look strange sometimes.\n" \ | |
| "This function doesn't check if the text is too high to fit on the height of the surface though, so sometimes " \ | |
| "text will disappear underneath the surface" | |
| font = pygame.font.SysFont('Arial', 64) | |
| while True: | |
| dt = clock.tick(FPS) / 1000 | |
| for event in pygame.event.get(): | |
| if event.type == pygame.QUIT: | |
| quit() | |
| screen.fill(pygame.Color('white')) | |
| blit_text(screen, text, (20, 20), font) | |
| pygame.display.update() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment