We will create a simple game that we will improve on further in the book. As is traditional in books about programming, we will start with a Hello World! example. It's not a game per se. It's important to notice the so-called main game loop where all the action happens and the usage of the Font
module to render text. In this program we will manipulate a Pygame's Surface
object, that is used for drawing and we will handle a quit event.
Imports: First we will import the required Pygame modules. If Pygame is installed properly, we should get no errors, otherwise please return to the Preparing your development environment (Simple) recipe:
import pygame, sys from pygame.locals import *
Initialization: We will initialize Pygame by creating a display of 400 by 300 pixels and setting the window title to
Hello world
:pygame.init() screen = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!')
The main game loop: Games usually have a game loop, which runs forever until, for instance, a quit event occurs. In this example, we will only set a label with the text
Hello world
at coordinates (100, 100). The text has a font size of 19, red color, and falls back to the default font:while True: sys_font = pygame.font.SysFont("None", 19) rendered = sys_font.render('Hello World', 0, (255, 100, 100)) screen.blit(rendered, (100, 100)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
We get the following screenshot as the end result:
The following is the complete code for the Hello World example:
import pygame, sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!') while True: sysFont = pygame.font.SysFont("None", 19) rendered = sysFont.render('Hello World', 0, (255, 100, 100)) screen.blit(rendered, (100, 100)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
It might not seem like much, but we learned a lot in this recipe. The functions that passed the review are summarized in the following table:
Function |
Description |
---|---|
|
This function performs the initialization and needs to be called before any other Pygame functions are called. |
|
This function creates a so-called |
|
This function sets the window title to a specified string value. |
|
This function creates a system font from a comma-separated list of fonts (in this case none) and a font size parameter. |
|
This function draws text on a surface. The second parameter indicates whether anti-aliasing is used. The last parameter is a tuple representing the RGB values of a color. |
|
This function draws on a surface. |
|
This function gets a list of |
|
This function cleans up resources used by Pygame. Call this function before exiting the game. |
|
This function refreshes the surface. |