Reputation: 161
Trying to write a pygame program, but I can't seem to figure out how to let pygame format text as a paragraph without third party modules. For example, I want:
"Hello World, how are you doing today? I'm fine actually, thank you."
to be more along the lines of:
"Hello World, how are
you doing today? I'm
fine actually, thank you."
Here is my code:
def instructions(text):
pressKey, pressRect = makeText('Last Block is a survival game. Every ten lines that you clear will shorten the screen, clear as many lines as possible before you run out of space!', smallFont, bgColor)
pressRect.center = (int(windowWidth/ 2), int(windowHeight / 2) + 100)
displaySurf.blit(pressKey, pressRect)
while press() == None:
pygame.display.update()
and the makeText
function:
def makeText(text, font, color):
surf = font.render(text, True, color)
return surf, surf.get_rect()
So that pygame can divide the long line of text up into sections of x words each and format it to look somewhat like a paragraph. Right now, I'm using numerous surface objects and blits to make it look like this which seems tedious. Any other ways to achieve the effect?
Upvotes: 2
Views: 3608
Reputation: 1318
If I understand you correctly, you want some code to display text in a multiline paragraph. If so, I used the code here: http://www.pygame.org/pcr/text_rect/index.php
Doesn't need any additional modules.The method takes the following parameters:
def render_textrect(string, font, rect, text_color, background_color, justification=0):
"""Returns a surface containing the passed text string, reformatted
to fit within the given rect, word-wrapping as necessary. The text
will be anti-aliased.
Takes the following arguments:
string - the text you wish to render. \n begins a new line.
font - a Font object
rect - a rectstyle giving the size of the surface requested.
text_color - a three-byte tuple of the rgb value of the
text color. ex (0, 0, 0) = BLACK
background_color - a three-byte tuple of the rgb value of the surface.
justification - 0 (default) left-justified
1 horizontally centered
2 right-justified
Returns the following values:
Success - a surface object with the text rendered onto it.
Failure - raises a TextRectException if the text won't fit onto the surface.
"""
Sorry for posting again - clicked community wiki by mistake.
Upvotes: 3
Reputation:
It sounds like you are looking for the functionality offered by textwrap.fill
:
from textwrap import fill
mystr = "Hello World, how are you doing today? I'm fine actually, thank you."
print(fill(mystr, 20))
print()
print(fill(mystr, 40))
print()
print(fill(mystr, 10))
Output:
Hello World, how are you doing today? I'm fine actually, thank you. Hello World, how are you doing today? I'm fine actually, thank you. Hello World, how are you doing today? I'm fine actually, thank you.
The first argument to textwrap.fill
is the string that you want to break up. The second is the maximum length of the lines (in characters).
Upvotes: 1