Natürlich! Um einen Text mit Zeilenumbrüchen in Pygame darzustellen, können Sie den Text zunächst in Absätze aufteilen und dann jeden Absatz separat mit der render-Methode rendern. Der Abstand zwischen den Absätzen kann durch die Verwendung einer Konstanten oder einer Variablen definiert werden.
Hier ist ein Beispielcode, der einen Text mit Zeilenumbrüchen und begrenzter Breite auf dem Bildschirm darstellt:
import pygame
# Initialize Pygame
pygame.init()
# Set the width and height of the screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# Set the font and font size
font = pygame.font.Font(None, 24)
# Set the text to be displayed
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam euismod felis ac sapien bibendum, vel euismod urna varius. Vestibulum vel magna eget ante feugiat euismod non non nulla. Sed sed nibh quis dolor consequat consequat. Integer aliquet eleifend dui, quis tempus felis fermentum quis. Sed vitae dolor elit. Suspendisse euismod neque id semper tristique."
# Split the text into paragraphs
paragraphs = text.split('\n')
# Set the maximum width of each line
max_width = screen_width - 20
# Set the line height
line_height = font.get_linesize()
# Calculate the total height of the text
total_height = len(paragraphs) * line_height
# Set the initial position to render the text
x = 10
y = 10
# Render each paragraph separately
for paragraph in paragraphs:
# Split the paragraph into words
words = paragraph.split()
# Set the initial line
line = ""
# Render each word separately and check if the line length exceeds the maximum width
for word in words:
if font.size(line + " " + word)[0] < max_width:
line += " " + word
else:
# Render the line
text_surface = font.render(line, True, (255, 255, 255))
screen.blit(text_surface, (x, y))
# Move to the next line
y += line_height
line = word
# Render the last line of the paragraph
text_surface = font.render(line, True, (255, 255, 255))
screen.blit(text_surface, (x, y))
# Move to the next paragraph
y += line_height
# Update the screen
pygame.display.flip()
# Loop until the user clicks the close button
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Quit Pygame
pygame.quit()
Dieser Code teilt den Text in Absätze auf und rendert jeden Absatz separat. Jeder Absatz wird dann in Zeilen aufgeteilt, die die maximale Breite des Bildschirms nicht überschreiten. Wenn eine Zeile zu lang wird, wird sie gerendert, und die nächste Zeile beginnt auf einer neuen Zeile. Der Abstand zwischen den Zeilen wird durch die line_height-Variable definiert, und der Abstand zwischen den Absätzen kann durch die Änderung der y-Koordinate gesteuert werden. Der Text wird schließlich auf dem Bildschirm angezeigt, indem die blit-Methode aufgerufen wird. Schließlich wird das PyGame-Display aktualisiert und die Spielschleife wird ausgeführt, bis der Nutzer den Schließen-Button drückt.