We already know how to display a caption text on a pygame window. Now let's see how to display text on your game screen.
Here comes the font module of pygame. It is written to load and render different fonts. Basically all the text we display in pygame is a surface (image). It accepts any UCS-2 character ('u0001' to 'uFFFF'). This module is optional and requires SDL_ttf as a dependency. You should test that
pygame.font
pygame module for loading and rendering fonts
is available and initialized before attempting to use the module.There are methods to
init
and quit
the font module. Most of the time we don't need to call pygame.font.init()
because pygame.init()
automatically does that.This module comes with a default font. You can also use any .ttf font to render text.
Just like images, to render any text, you first need to load the font.let's say I am loading a font and naming it as font1. The syntax for loading a font is
font1=pygame.font.Font(font_name_to_load, font_size_in_int)
example:
font1 = pygame.font.SysFont(None, 32)
Here we used
pygame.font.SysFont
because we wanted to use a font from system font. and specified None as font name this tells the module we want to use default font pf pygame and we provided 32 as font size. this is going to display the style for very first text in above image. But now we just loaded the font we still have to display some text using this font. To do so, first we need to define a surface with the text we want to display. The following code creates the text surface
text1=font1.render("Hello I am simple text", True,(255,0,0))#text color specified to red
now we created the text surface which we have to display on the screen. for this we just need to
blit
it on the screen as usually we blit other images on the screen.
Game_Window.blit(text1,(20,20))
To load external font other than system fonts, use
pygame.font.Font()
method instead of pygame.font.SysFont()
To define bold,italics,underlined styles we have methods in the module named
set_bold(bool), set_italic(bool), set_underline(bool)
.While rendering the text, you can also have background color to text. You need to add an extra color argument in
font1.render()
as follows
text4 =font1.render("Hello I am simple text with yellow background", True,(255,0,0),(255,255,0))#text color specified to red
You can get full source code below to create all the styles shown in above image.
The external font used tin above script is taken from the following website.
https://cooltext.com/Download-Font-Kongtext
No comments:
Post a Comment
Your comments and suggestions are valuable and are always welcome and will be helpful to me to create a good quality content. Please leave your thoughts