pygame Drawing on the screen Surfaces


Example

In pygame you usually use Surfaces to represent the appearance of objects, and Rectangles to represent their positions. A Surface is like a blank sheet of paper which contain colors or images. There are two ways to create a Surface: blank from scratch or by loading an image.

Create a Surface

To create a Surface you need at minimum it's size, which is a 2-element integer sequence of width and height, representing the size in pixels.

You can also pass additional arguments when creating a Surface to control bit depth, masks and additional features as per-pixel alpha and/or create the image in video memory. This is outside the scope of this example though.

size = width, height = (32, 32)
empty_surface = pygame.Surface(size)

You can use the pygame.draw module to draw shapes on the Surface, or fill it with a color by calling the Surface method fill(color). The argument color is a 3 or 4-element integer sequence or a pygame.Color object.

Load an image

More often than not you'd like to use your own images in a game (called sprites). Creating a Surface with your image on is as easy as:

my_image = pygame.image.load(path_to_image)

The path to the image can be relative or absolute. To improve performance it's usually wise to convert your image to the same pixel format as the screen. This can be done by calling the Surface method convert(), like so:

my_image = pygame.image.load(path_to_image).convert()

If your image contains transparency (alpha values) you just call the method convert_alpha() instead:

my_image = pygame.image.load(path_to_image).convert_alpha()

Blitting

Surfaces needs to be blit to the screen in order to be able to display them. Blitting essentially means copying pixels from one Surface to another (the screen is a Surface as well). You also need to pass the position of the Surface, which should be a 2-element integer sequence or a Rect object. The topleft of the Surface will be placed at the position.

screen.blit(my_image, (0, 0))
pygame.display.update()  # or pygame.display.flip()

It's possible to blit to other Surfaces than the screen. To display what's been blitted to the screen you need to call pygame.display.update() or pygame.display.flip().