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.
import pygame, sys from pygame.locals import *
Hello world
:pygame.init() screen = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!')
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. |