I am trying to make a game and I am trying to render a lot of text. When the text renders, the rest of the text goes off the screen. Is there any easy way to make the text g
There is no easy way to render text on multiple lines in pygame, but this helper function could provide some use to you. Just pass in your text (with newlines), x, y, and font size.
def render_multi_line(text, x, y, fsize)
lines = text.splitlines()
for i, l in enumerate(lines):
screen.blit(sys_font.render(l, 0, hecolor), (x, y + fsize*i))
One thing you could do is use a monospaced font. They have the same size for all characters and so are beloved by programmers. That's going to be my solution for handling the height/width problem.
Building on previous answers I made a somewhat comprehensive blit text function I can use with a single short command:
def blittext(text, **kwargs):
#blit text into screen, uses defaults and works for multiline strings
fontface = kwargs.get('font', 'PressStart2P-Regular.ttf')
b = kwargs.get('bold', False)
fontsize = kwargs.get('size', 30)
color = kwargs.get('color', (255, 255, 255))
topleft = kwargs.get('topleft',(w/2,h/2))
center = kwargs.get('center')
textsurf = kwargs.get('surface',surface)
maxwidth = kwargs.get('width',w)
try:
myfont = pygame.font.Font('/storage/emulated/0/games/' + fontface, fontsize)
except:
myfont = pygame.font.SysFont(fontface, fontsize, bold=b)
x,y = topleft
charwidth = myfont.size(' ')[0]
charheight = fontsize + 3
if center:
for l in text.splitlines():
mytext = myfont.render(l, False, color)
textrect = mytext.get_rect(center=center)
center = (center[0],center[1]+charheight)
textsurf.blit(mytext,textrect)
else:
for line in text.splitlines():
for word in line.split(' '):
mytext = myfont.render(word, False, color)
textrect = mytext.get_rect(topleft=(x,y))
wordwidth = textrect.width
if x + wordwidth >= maxwidth:
x,y = (topleft[0], y + charheight)
textsurf.blit(mytext,(x,y))
x += charwidth + wordwidth
x,y = (topleft[0], y + charheight)