Ich habe einen Text und möchte diesen in pygame darstellen. Wie erzeuge ich newlines so…
- User
Ich habe einen Text und möchte diesen in pygame darstellen. Wie erzeuge ich newlines so das der Text in der Darstellung nie aus dem Bildschirm rausreicht?
- Assistant
Am besten den Text in einzelne Wörter zerlegen: text.split(' ') Dann eine kleine Schleife einen Textstring mit erzeugen lassen, jeweils ein Wort zum Teststring hinzufügen, bis dieser > als die gewünschte Breite ist: width, _ = fontsize(Teststring) Das aktuelle Wort ausgeben: font.render(line, True, color) screen.blit(line_surface, (x, y)) Dann den Teststring wieder auf "" setzen und weiter durch die Schleife bis alle Wörter bearbeitet wurden. Viel Spaß beim Programmieren
- User
Kannst Du mir das als komplettes Beispielprogramm coden?
- Assistant
Ja, ich kann Ihnen ein Beispiel-Programmcode geben, der das oben beschriebene Verfahren verwendet, um einen Text in einzelne Wörter zu zerlegen und anschließend jedes Wort in einer Schleife als Teststring hinzuzufügen, bis der Teststring eine gewünschte Breite erreicht hat:
import pygame import pygame.font import pygame.surf Initialize Pygame pygame.init() Set up the window windowwidth = 800 windowheight = 600 screen = pygame.display.setmode((windowwidth, windowheight)) pygame.display.setcaption("Text Splitter") Set the font font = pygame.font.SysFont("Arial", 24) Load the text to be split text = "This is the text to be split" Split the text into words words = text.split(" ") Initialize a variable to store the current width of the text current_width = 0 Iterate through each word in the list for word in words: # Calculate the width of the word wordwidth = font.size(word) # Add the width of the word to the current width currentwidth = currentwidth + wordwidth # Check if the current width is greater than the window width if currentwidth > windowwidth: # If it is, draw the current word on the screen line = font.render(word, True, (255, 255, 255)) screen.blit(line, (x, y)) # Set the current width to 0 and reset the x position currentwidth = 0 x = 0 # Increment the x position x = x + wordwidth # Set the current width to the width of the last word currentwidth = currentwidth + word_width Draw the last word on the screen line = font.render(word, True, (255, 255, 255)) screen.blit(line, (x, y))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →