Winston
Winston

Reputation: 53

Can't find a way to make multiple lines in pygame

I'm aware of the fact that pygame's screen.blit is not meant to support multiple lines, however I can't figure out a work around. All of the other threads that ask this question just don't work with my code. How do I make this work?

I've tried to split response into two by using splitline() on DisplayRoom.prompt and then having the game just load two lines separately, but DisplayRoom.prompt.splitline() does not turn `DisplayRoom.prompt from a tuple to a list and only returns the value for it.

screen.fill(background_colour)
txt_surface = userfont.render(text, True, color)
screen.blit(txt_surface, (100, 800))
response = promptfont.render(DisplayRoom.prompt, True, color)
screen.blit(response, (80, 300))
pygame.display.flip()
clock.tick_busy_loop(60)  # limit FPS

When I defined DisplayRoom.prompt, I expected \n to linebreak it but it doesn't work which is why I'm here.

Upvotes: 1

Views: 1012

Answers (1)

Valentino
Valentino

Reputation: 7361

It is not Surface.blit which doesn't support multiple lines. blit simply draw a Surface on another Surface, it doesn't care what the Surface contains.

It's pygame.Font.render which doesn't support multilines. The docs clearly say:

The text can only be a single line: newline characters are not rendered.

So I don't know what DisplayRoom.prompt is in your code, but if is not a string, is bound to fail: render raises a TypeError: text must be a unicode or bytes.
And if is a string with newlines, newlines are just not rendered.

You have to split the text and render each line separately.

In the following example I create a simple function blitlines which illustrates how you could do.

import sys
import pygame

def blitlines(surf, text, renderer, color, x, y):
    h = renderer.get_height()
    lines = text.split('\n')
    for i, ll in enumerate(lines):
        txt_surface = renderer.render(ll, True, color)
        surf.blit(txt_surface, (x, y+(i*h)))


background_colour = (0, 0, 0)
textcolor = (255, 255, 255)

multitext = "Hello World!\nGoodbye World!\nI'm back World!"

pygame.init()
screen = pygame.display.set_mode((500, 500))
userfont = pygame.font.Font(None, 40)

screen.fill(background_colour)
blitlines(screen, multitext, userfont, textcolor, 100, 100)

pygame.display.flip()

#main loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

This is the result on the screen.

sample image

Upvotes: 4

Related Questions