how to make text change lines pygame

Solutions on MaxInterview for how to make text change lines pygame by the best coders in the world

showing results for - "how to make text change lines pygame"
Helena
23 May 2020
1import pygame
2pygame.init()
3
4
5SIZE = WIDTH, HEIGHT = (1024, 720)
6FPS = 30
7screen = pygame.display.set_mode(SIZE, pygame.RESIZABLE)
8clock = pygame.time.Clock()
9
10
11def blit_text(surface, text, pos, font, color=pygame.Color('black')):
12    words = [word.split(' ') for word in text.splitlines()]  # 2D array where each row is a list of words.
13    space = font.size(' ')[0]  # The width of a space.
14    max_width, max_height = surface.get_size()
15    x, y = pos
16    for line in words:
17        for word in line:
18            word_surface = font.render(word, 0, color)
19            word_width, word_height = word_surface.get_size()
20            if x + word_width >= max_width:
21                x = pos[0]  # Reset the x.
22                y += word_height  # Start on new row.
23            surface.blit(word_surface, (x, y))
24            x += word_width + space
25        x = pos[0]  # Reset the x.
26        y += word_height  # Start on new row.
27
28
29text = "This is a really long sentence with a couple of breaks.\nSometimes it will break even if there isn't a break " \
30       "in the sentence, but that's because the text is too long to fit the screen.\nIt can look strange sometimes.\n" \
31       "This function doesn't check if the text is too high to fit on the height of the surface though, so sometimes " \
32       "text will disappear underneath the surface"
33font = pygame.font.SysFont('Arial', 64)
34
35while True:
36
37    dt = clock.tick(FPS) / 1000
38
39    for event in pygame.event.get():
40        if event.type == pygame.QUIT:
41            quit()
42
43    screen.fill(pygame.Color('white'))
44    blit_text(screen, text, (20, 20), font)
45    pygame.display.update()