0

I'm working on a project in pygame and the text is supposed to display a character's speech. I've got the text displayed, but it runs off the screen. I tried one way to text wrap, but it didn't move to the next line, so it just overlapped on the same line. I don't know if there is some sort of boundary or border I can set or text wrap. I could only find things for python, not pygame.

Here's what I have for the text

white = (255,255,255)
def text_objects(text, font):
    textSurface = font.render(text, True, white)
    return textSurface, textSurface.get_rect()
def words(text):
    largeText = pygame.font.Font('freesansbold.ttf', 18)
    TextSurf, TextRect = text_objects((text), largeText)
    TextRect = ((13), (560))
    screen.blit(TextSurf, TextRect)
`   pygame.display.update()

words("This is just filler. Yup, filler to test if this will run off the screen. And apparently \n doesn't start a new line... Doo duh doo. Bum Dum pssst.")
  • Just look at [the example in the pygame docs](https://www.pygame.org/docs/ref/freetype.html#pygame.freetype.Font.render_to) – sloth Jan 19 '21 at 09:00

1 Answers1

0

The way I did it before was to use textwrap to split the long string into strings that fit on a line. Then I blit them each with a different y value. To split the text you can do this:

import textwrap

sentence = "This is just filler. Yup, filler to test if this will run off the screen. And apparently doesn't start a new line... Doo duh doo. Bum Dum pssst."
characters_in_a_line = 60

lines = textwrap.wrap(sentence, characters_in_a_line , break_long_words=False)

Which gives the output:

['This is just filler. Yup, filler to test if this will run', "off the screen. And apparently doesn't start a new line...", 'Doo duh doo. Bum Dum pssst.']

Then I use a separate function to create text rectangles that are blitted to the main screen:

    def create_text(self, text, font, color, x, y):
        text = font.render(text, True, color)
        rect = text.get_rect()

        rect.topeleft = (x, y)

        self.screen.blit(text, rect)

You would just need to know how tall your text is and send in different y value for each part of text in lines.

eligolf
  • 1,682
  • 1
  • 6
  • 22