Game Development Reference
In-Depth Information
37. textobj = font.render(text, 1, TEXTCOLOR)
38. textrect = textobj.get_rect()
39. textrect.topleft = (x, y)
40. surface.blit(textobj, textrect)
Drawing text on the window involves many different steps. First, we must create a
Surface object that has the string rendered in a specific font on it. The render()
method does this. Next, we need to know the size and location of the Surface object we
just made. We can get a Rect object with this information with the get_rect() method
for Surface objects.
This Rect object has no special connection to the Surface object with the text drawn on
it, other than the fact that it has a copy of the width and height information from the
Surface object. We can change the location of the Rect object by setting a new tuple
value for its topleft attribute.
Finally, we blit the Surface object of the rendered text onto the Surface object that
was passed to our drawText() function. Displaying text in Pygame take a few more steps
than simply calling the print() function, but if we put this code into a single function
( drawText() ), then we only need to call the function instead of typing out all the code
every time we want to display text on the screen.
Initializing Pygame and Setting Up the Window
Now that the constant variables and functions are finished, we can start calling the
Pygame functions that will set up Pygame for use in our code. Many of these function calls
are to set up the GUI window and create objects that we will use in the game.
42. # set up pygame, the window, and the mouse cursor
43. pygame.init()
44. mainClock = pygame.time.Clock()
45. windowSurface = pygame.display.set_mode((WINDOWWIDTH,
WINDOWHEIGHT))
46. pygame.display.set_caption('Dodger')
47. pygame.mouse.set_visible(False)
Line 43 sets up the Pygame library. Remember, the pygame.init() function must be
called before we can use any of Pygame's functions or data types. Line 44 creates a
pygame.time.Clock() object and stores it in the mainClock variable. This object
will help us keep the program from running too fast.
Line 45 creates a new Surface object which will be used for the window displayed on
the screen. We will specify the width and height of this Surface object (and the window)
by passing a tuple with the WINDOWWIDTH and WINDOWHEIGHT constant variables. Notice
that there is only one argument passed to pygame.display.set_mode() : a tuple. The
Search WWH ::




Custom Search