Pygame 1.9.2

Surface((width, height), flags=0, depth=0, masks=None) -> Surface

Whilst we focus like a shark-lazer on pygame 2, here is a bonus pygame 1.9.6 with a couple of small regression bug fixes. 1.9.2 1.9.2rc1 1.9.2b8 1.9.2b7 1.9.2.dev1 Subscribe to releases. Python Game Development Homepage PyPI. License Other Install pip install Pygame1.9.5.dev0 SourceRank 12. Dependencies 0 Dependent packages 6 Dependent repositories 1.55K Total releases 16.

Surface((width, height), flags=0, Surface) -> Surface

A pygame Surface is used to represent any image. The Surface has a fixed resolution and pixel format. Surfaces with 8-bit pixels use a color palette to map to 24-bit color.

Call to create a new image object. The Surface will be cleared to all black. The only required arguments are the sizes. With no additional arguments, the Surface will be created in a format that best matches the display Surface.

Using cached pygame-1.9.3-cp35-cp35m-manylinux1x8664.whl. Installing collected packages: pygame. The mouse buttons generate pygame.MOUSEBUTTONDOWN and pygame.MOUSEBUTTONUP events when they are pressed and released. These events contain a button attribute representing which button was pressed. The mouse wheel will generate pygame.MOUSEBUTTONDOWN and pygame.MOUSEBUTTONUP events when rolled. The button will be set to 4 when the wheel is. New in Pygame 1.8.1: BLENDRGBA. blitters and blenders to go with the BLENDRGB. blend modes. Documentation updates (mainly for new sprite classes released in 1.8.0).

The pixel format can be controlled by passing the bit depth or an existing Surface. The flags argument is a bitmask of additional features for the surface. You can pass any combination of these flags:

Both flags are only a request, and may not be possible for all displays and formats.

Advance users can combine a set of bitmasks with a depth value. The masks are a set of 4 integers representing which bits in a pixel will represent each color. Normal Surfaces should not require the masks argument.

Surfaces can have many extra attributes like alpha planes, colorkeys, source rectangle clipping. These functions mainly effect how the Surface is blitted to other Surfaces. The blit routines will attempt to use hardware acceleration when possible, otherwise they will use highly optimized software blitting methods.

There are three types of transparency supported in pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. A surface alpha of 255 is opaque, and a value of 0 is completely transparent.

Per pixel alphas are different because they store a transparency value for every pixel. This allows for the most precise transparency effects, but it also the slowest. Per pixel alphas cannot be mixed with surface alpha and colorkeys.

There is support for pixel access for the Surfaces. Pixel access on hardware surfaces is slow and not recommended. Pixels can be accessed using the get_at() and set_at() functions. These methods are fine for simple access, but will be considerably slow when doing of pixel work with them. If you plan on doing a lot of pixel level work, it is recommended to use a , which gives an array like view of the surface. For involved mathematical manipulations try the module (It's quite quick, but requires NumPy.)

Any functions that directly access a surface's pixel data will need that surface to be lock()'ed. These functions can lock() and unlock() the surfaces themselves without assistance. But, if a function will be called many times, there will be a lot of overhead for multiple locking and unlocking of the surface. It is best to lock the surface manually before making the function call many times, and then unlocking when you are finished. All functions that need a locked surface will say so in their docs. Remember to leave the Surface locked only while necessary.

Surface pixels are stored internally as a single number that has all the colors encoded into it. Use the map_rgb() and unmap_rgb() to convert between individual red, green, and blue values into a packed integer for that Surface.

Surfaces can also reference sections of other Surfaces. These are created with the subsurface() method. Any change to either Surface will effect the other.

Each Surface contains a clipping area. By default the clip area covers the entire Surface. If it is changed, all drawing operations will only effect the smaller area.

blit(source, dest, area=None, special_flags=0) -> Rect

Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. Dest can either be pair of coordinates representing the upper left corner of the source. A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit.

An optional area rectangle can be passed as well. This represents a smaller portion of the source Surface to draw.

New in pygame 1.8: Optional special_flags: BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX.

New in pygame 1.8.1: Optional special_flags: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAXBLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX.

The return rectangle is the area of the affected pixels, excluding any pixels outside the destination Surface, or outside the clipping area.

Pixel alphas will be ignored when blitting to an 8 bit Surface.

For a surface with colorkey or blanket alpha, a blit to self may give slightly different colors than a non self-blit.

blits(blit_sequence=(source, dest), ...), doreturn=1) -> [Rect, ...] or None
blits((source, dest, area), ...)) -> [Rect, ...]
blits((source, dest, area, special_flags), ...)) -> [Rect, ...]

Draws many surfaces onto this Surface. It takes a sequence as input, with each of the elements corresponding to the ones of blit(). It needs at minimum a sequence of (source, dest).

Parameters:
  • blit_sequence -- a sequence of surfaces and arguments to blit them, they correspond to the blit() arguments
  • doreturn -- if True, return a list of rects of the areas changed, otherwise return None
Returns:

a list of rects of the areas changed if doreturn is True, otherwise None

Return type:

list or None

New in pygame 1.9.4.

convert(Surface=None) -> Surface
convert(depth, flags=0) -> Surface
convert(masks, flags=0) -> Surface

change the pixel format of an image

Creates a new copy of the Surface with the pixel format changed. The new pixel format can be determined from another existing Surface. Otherwise depth, flags, and masks arguments can be used, similar to the call.

If no arguments are passed the new Surface will have the same pixel format as the display Surface. This is always the fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times.

The converted Surface will have no pixel alphas. They will be stripped if the original had them. See convert_alpha() for preserving or creating per-pixel alphas.

The new copy will have the same class as the copied surface. This lets as Surface subclass inherit this method without the need to override, unless subclass specific instance attributes also need copying.

convert_alpha(Surface) -> Surface
convert_alpha() -> Surface

change the pixel format of an image including per pixel alphas

Creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display.

Unlike the convert() method, the pixel format for the new image will not be exactly the same as the requested source, but it will be optimized for fast alpha blitting to the destination.

As with convert() the returned surface has the same class as the converted surface.

copy() -> Surface

Makes a duplicate copy of a Surface. The new surface will have the same pixel formats, color palettes, transparency settings, and class as the original. If a Surface subclass also needs to copy any instance specific attributes then it should override copy().

fill(color, rect=None, special_flags=0) -> Rect

fill Surface with a solid color

Fill the Surface with a solid color. If no rect argument is given the entire Surface will be filled. The rect argument will limit the fill to a specific area. The fill will also be contained by the Surface clip area.

The color argument can be either a RGB sequence, a RGBA sequence or a mapped color index. If using RGBA, the Alpha (A part of RGBA) is ignored unless the surface uses per pixel alpha (Surface has the SRCALPHA flag).

New in pygame 1.8: Optional special_flags: BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX.

New in pygame 1.8.1: Optional special_flags: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAXBLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX.

This will return the affected Surface area.

scroll(dx=0, dy=0) -> None

Move the image by dx pixels right and dy pixels down. dx and dy may be negative for left and up scrolls respectively. Areas of the surface that are not overwritten retain their original pixel values. Scrolling is contained by the Surface clip area. It is safe to have dx and dy values that exceed the surface size.

New in pygame 1.9.

set_colorkey(Color, flags=0) -> None
set_colorkey(None) -> None

Set the current color key for the Surface. When blitting this Surface onto a destination, any pixels that have the same color as the colorkey will be transparent. The color can be an RGB color or a mapped color integer. If None is passed, the colorkey will be unset.

The colorkey will be ignored if the Surface is formatted to use per pixel alpha values. The colorkey can be mixed with the full Surface alpha value.

The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.

get_colorkey() -> RGB or None

Get the current transparent colorkey

Return the current colorkey value for the Surface. If the colorkey is not set then None is returned.

set_alpha(value, flags=0) -> None
set_alpha(None) -> None

Set the current alpha value for the Surface. When blitting this Surface onto a destination, the pixels will be drawn slightly transparent. The alpha value is an integer from 0 to 255, 0 is fully transparent and 255 is fully opaque. If None is passed for the alpha value, then alpha blending will be disabled, including per-pixel alpha.

This value is different than the per pixel Surface alpha. For a surface with per pixel alpha, blanket alpha is ignored and None is returned.

Changed in pygame 2.0: per-surface alpha can be combined with per-pixel alpha.

The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.

get_alpha() -> int_value

Return the current alpha value for the Surface.

lock() -> None

lock the Surface memory for pixel access

Lock the pixel data of a Surface for access. On accelerated Surfaces, the pixel data may be stored in volatile video memory or nonlinear compressed forms. When a Surface is locked the pixel memory becomes available to access by regular software. Code that reads or writes pixel values will need the Surface to be locked.

Surfaces should not remain locked for more than necessary. A locked Surface can often not be displayed or managed by pygame.

Not all Surfaces require locking. The mustlock() method can determine if it is actually required. There is no performance penalty for locking and unlocking a Surface that does not need it.

All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.

It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.

unlock() -> None

Unlock the Surface pixel data after it has been locked. The unlocked Surface can once again be drawn and managed by pygame. See the lock() documentation for more details.

All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.

It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.

mustlock() -> bool

test if the Surface requires locking

Returns True if the Surface is required to be locked to access pixel data. Usually pure software Surfaces do not require locking. This method is rarely needed, since it is safe and quickest to just lock all Surfaces as needed.

All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.

get_locked() -> bool

Returns True when the Surface is locked. It doesn't matter how many times the Surface is locked.

get_locks() -> tuple

Gets the locks for the Surface

Returns the currently existing locks for the Surface.

get_at((x, y)) -> Color

Return a copy of the RGBA Color value at the given pixel. If the Surface has no per pixel alpha, then the alpha value will always be 255 (opaque). If the pixel position is outside the area of the Surface an IndexError exception will be raised.

Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation. It is better to use methods which operate on many pixels at a time like with the blit, fill and draw methods - or by using /.

This function will temporarily lock and unlock the Surface as needed.

New in pygame 1.9: Returning a Color instead of tuple. Use tuple(surf.get_at((x,y))) if you want a tuple, and not a Color. This should only matter if you want to use the color as a key in a dict.

set_at((x, y), Color) -> None

Set the RGBA or mapped integer color value for a single pixel. If the Surface does not have per pixel alphas, the alpha value is ignored. Setting pixels outside the Surface area or outside the Surface clipping will have no effect.

Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation.

This function will temporarily lock and unlock the Surface as needed.

get_at_mapped((x, y)) -> Color

get the mapped color value at a single pixel

Return the integer value of the given pixel. If the pixel position is outside the area of the Surface an IndexError exception will be raised.

This method is intended for pygame unit testing. It unlikely has any use in an application.

This function will temporarily lock and unlock the Surface as needed.

get_palette() -> [RGB, RGB, RGB, ...]

get the color index palette for an 8-bit Surface

Return a list of up to 256 color elements that represent the indexed colors used in an 8-bit Surface. The returned list is a copy of the palette, and changes will have no effect on the Surface.

Returning a list of Color(withlength3) instances instead of tuples.

get_palette_at(index) -> RGB

get the color for a single entry in a palette
1.9.2

Returns the red, green, and blue color values for a single index in a Surface palette. The index should be a value from 0 to 255.

New in pygame 1.9: Returning Color(withlength3) instance instead of a tuple.

set_palette([RGB, RGB, RGB, ...]) -> None

Set the full palette for an 8-bit Surface. This will replace the colors in the existing palette. A partial palette can be passed and only the first colors in the original palette will be changed.

This function has no effect on a Surface with more than 8-bits per pixel.

set_palette_at(index, RGB) -> None

set the color for a single index in an 8-bit Surface palette

Set the palette value for a single entry in a Surface palette. The index should be a value from 0 to 255.

This function has no effect on a Surface with more than 8-bits per pixel.

map_rgb(Color) -> mapped_int

Convert an RGBA color into the mapped integer value for this Surface. The returned integer will contain no more bits than the bit depth of the Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.

See the Surface object documentation for more information about colors and pixel formats.

unmap_rgb(mapped_int) -> Color

convert a mapped integer color value into a Color

Convert an mapped integer color into the RGB color components for this Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.

See the Surface object documentation for more information about colors and pixel formats.

set_clip(rect) -> None
set_clip(None) -> None

Each Surface has an active clipping area. This is a rectangle that represents the only pixels on the Surface that can be modified. If None is passed for the rectangle the full Surface will be available for changes.

The clipping area is always restricted to the area of the Surface itself. If the clip rectangle is too large it will be shrunk to fit inside the Surface.

get_clip() -> Rect

get the current clipping area of the Surface

Return a rectangle of the current clipping area. The Surface will always return a valid rectangle that will never be outside the bounds of the image. If the Surface has had None set for the clipping area, the Surface will return a rectangle with the full area of the Surface.

subsurface(Rect) -> Surface

Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other. Surface information like clipping area and color keys are unique to each Surface.

The new Surface will inherit the palette, color key, and alpha settings from its parent.

It is possible to have any number of subsurfaces and subsubsurfaces on the parent. It is also possible to subsurface the display Surface if the display mode is not hardware accelerated.

See get_offset() and get_parent() to learn more about the state of a subsurface.

A subsurface will have the same class as the parent surface.

get_parent() -> Surface

find the parent of a subsurface

Returns the parent Surface of a subsurface. If this is not a subsurface then None will be returned.

get_abs_parent() -> Surface

Returns the parent Surface of a subsurface. If this is not a subsurface then this surface will be returned.

get_offset() -> (x, y)

find the position of a child subsurface inside a parent

Get the offset position of a child subsurface inside of a parent. If the Surface is not a subsurface this will return (0, 0).

get_abs_offset() -> (x, y)

find the absolute position of a child subsurface inside its top level parent

Get the offset position of a child subsurface inside of its top level parent Surface. If the Surface is not a subsurface this will return (0, 0).

get_size() -> (width, height)

Return the width and height of the Surface in pixels.

get_width() -> width

get the width of the Surface

Return the width of the Surface in pixels.

get_height() -> height

Return the height of the Surface in pixels.

get_rect(**kwargs) -> Rect

get the rectangular area of the Surface

Returns a new rectangle covering the entire surface. This rectangle will always start at (0, 0) with a width and height the same size as the image.

You can pass keyword argument values to this function. These named values will be applied to the attributes of the Rect before it is returned. An example would be mysurf.get_rect(center=(100,100)) to create a rectangle for the Surface centered at a given position.

get_bitsize() -> int

Returns the number of bits used to represent each pixel. This value may not exactly fill the number of bytes used per pixel. For example a 15 bit Surface still requires a full 2 bytes.

get_bytesize() -> int

get the bytes used per Surface pixel

Return the number of bytes used per pixel.

get_flags() -> int

Returns a set of current Surface features. Each feature is a bit in the flags bitmask. Typical flags are HWSURFACE, RLEACCEL, SRCALPHA, and SRCCOLORKEY.

Here is a more complete list of flags. A full list can be found in SDL_video.h

Available for

Used internally (read-only)

get_pitch() -> int

get the number of bytes used per Surface row

Return the number of bytes separating each row in the Surface. Surfaces in video memory are not always linearly packed. Subsurfaces will also have a larger pitch than their real width.

This value is not needed for normal pygame usage.

get_masks() -> (R, G, B, A)

the bitmasks needed to convert between a color and a mapped integer

Returns the bitmasks used to isolate each color in a mapped integer.

This value is not needed for normal pygame usage.

set_masks((r,g,b,a)) -> None

set the bitmasks needed to convert between a color and a mapped integer

This is not needed for normal pygame usage.

get_shifts() -> (R, G, B, A)

Pygame‑1.9.2a0‑cp35‑none‑win32.whl
the bit shifts needed to convert between a color and a mapped integer

Returns the pixel shifts need to convert between each color and a mapped integer.

This value is not needed for normal pygame usage.

set_shifts((r,g,b,a)) -> None

sets the bit shifts needed to convert between a color and a mapped integer

This is not needed for normal pygame usage.

get_losses() -> (R, G, B, A)

the significant bits used to convert between a color and a mapped integer

Return the least significant number of bits stripped from each color in a mapped integer.

This value is not needed for normal pygame usage.

get_bounding_rect(min_alpha = 1) -> Rect

Returns the smallest rectangular region that contains all the pixels in the surface that have an alpha value greater than or equal to the minimum alpha value.

This function will temporarily lock and unlock the Surface as needed.

New in pygame 1.8.

get_view(<kind>='2') -> BufferProxy

Return an object which exports a surface's internal pixel buffer as a C level array struct, Python level array interface or a C level buffer interface. The pixel buffer is writeable. The new buffer protocol is supported for Python 2.6 and up in CPython. The old buffer protocol is also supported for Python 2.x. The old buffer data is in one segment for kind '0', multi-segment for other buffer view kinds.

The kind argument is the length 1 string '0', '1', '2', '3', 'r', 'g', 'b', or 'a'. The letters are case insensitive; 'A' will work as well. The argument can be either a Unicode or byte (char) string. The default is '2'.

'0' returns a contiguous unstructured bytes view. No surface shape information is given. A ValueError is raised if the surface's pixels are discontinuous.

'1' returns a (surface-width * surface-height) array of continuous pixels. A ValueError is raised if the surface pixels are discontinuous.

'2' returns a (surface-width, surface-height) array of raw pixels. The pixels are surface-bytesize-d unsigned integers. The pixel format is surface specific. The 3 byte unsigned integers of 24 bit surfaces are unlikely accepted by anything other than other pygame functions.

'3' returns a (surface-width, surface-height, 3) array of RGB color components. Each of the red, green, and blue components are unsigned bytes. Only 24-bit and 32-bit surfaces are supported. The color components must be in either RGB or BGR order within the pixel.

Pygame 1.9.2 Download

'r' for red, 'g' for green, 'b' for blue, and 'a' for alpha return a (surface-width, surface-height) view of a single color component within a surface: a color plane. Color components are unsigned bytes. Both 24-bit and 32-bit surfaces support 'r', 'g', and 'b'. Only 32-bit surfaces with SRCALPHA support 'a'.

The surface is locked only when an exposed interface is accessed. For new buffer interface accesses, the surface is unlocked once the last buffer view is released. For array interface and old buffer interface accesses, the surface remains locked until the BufferProxy object is released.

New in pygame 1.9.2.

get_buffer() -> BufferProxy

acquires a buffer object for the pixels of the Surface.

Return a buffer object for the pixels of the Surface. The buffer can be used for direct pixel access and manipulation. Surface pixel data is represented as an unstructured block of memory, with a start address and length in bytes. The data need not be contiguous. Any gaps are included in the length, but otherwise ignored.

This method implicitly locks the Surface. The lock will be released when the returned object is garbage collected.

_pixels_address -> int

pixel buffer address

The starting address of the surface's raw pixel bytes.


Edit on GitHub

© Pygame Developers.
Licensed under the GNU LGPL License version 2.1.
https://www.pygame.org/docs/ref/surface.html

PyGame is a Python wrapper for the SDL library. SDL is a cross-platform library for accessing computer multimedia hardware components (sound, video, input, etc.). SDL is an extremely powerful tool for building all kinds of things, but it’s written in C, and C is hard, so we use PyGame.

In this tutorial we’ll go over the basic PyGame logic and collision detection as well as drawing to the screen and loading outside files into our game.

NOTE: This tutorial assumes you have a basic understanding of the Python syntax, file structure, and OOP.

Setup

Navigate to the PyGame download page, and find the proper binary package for your operating system and version of Python. If you’re using Python 3, make sure you download version 1.9.2.

Create a new .py file and input the following code:

As with all Python programs, we begin by importing the modules we want to use. In this case we will be importing pygame itself and pygame.locals, which we will use later for some of the constants. The last line initializes all the PyGame modules, it must be called before you do anything else with PyGame.

Building Blocks

Screen Objects

First things first: We need something to draw on, so we will create a “screen” which will be our overall canvas. In order to create a screen to display on, we call the set_mode() method of pygame.display and then pass set_mode() a tuple with the width and height of the window we want (800x600 in this case):

If you run this now you’ll see our window pop up briefly and then immediately disappear as the program exits. Not very impressive, is it? In the next section we will introduce our main game loop to ensure that our program only exits when we give it the correct input.

Game Loop

The main game/event loop is where all the action happens. It runs continuously during gameplay, updating the game state, rendering the screen, and collecting input. When we create our loop we need to make sure that we have a way to get out of the loop and exit the application. To that end we will introduce some basic user input at the same time. All user input (and some other events we will get into later) go into the PyGame event queue, which you can access by calling pygame.event.get(). This will return a list of all the events in the queue, which we will loop through and respond to according to the type of event. For now all we care about are KEYDOWN and QUIT events:

Add these lines to the previous code and run it. You should see an empty window. It wont go away until you press the ESC key or trigger a QUIT event by closing the window.

Surfaces and Rects

Surfaces and Rects are basic building blocks in PyGame. Think of surfaces as a blank sheet of paper that you can draw whatever you want onto. Our screen object is also a Surface. They can hold images as well. Rects are a representation of a rectangular area that your Surface encompasses.

Let’s create a basic Surface that’s 50 pixels by 50 pixels, then let’s fill in the Surface with a color. We’ll use white because the default window background is black and we want it to be nice and visible. We’ll then call the get_rect() method on our Surface to get the rectangular area and the x, y coordinates of our surface:

Blit and Flip

Just creating our Surface isn’t actually enough to see it on the screen. To do that we need to Blit the Surface onto another Surface. Blit is just a technical way to say draw. You can only Blit from one Surface object to another – but remember, our screen is just another Surface object. Here’s how we’ll draw our surf to the screen:

blit() takes two arguments: The Surface to draw and the location to draw it at on the source Surface. Here we use the exact center of the screen, but when you run the code you’ll notice our surf does not end up centered on the screen. This is because blit() will draw surf starting at the top left position.

Notice the call to pygame.display.flip() after our Blit. Flip will update the entire screen with everything that has been drawn since the last flip. Without a call to flip(), nothing will show.

Sprites

What are Sprites? In programming terms a Sprite is a 2d representation of something on the screen. Essentially, a Sprite is a picture. Pygame provides a basic class called Sprite, which is meant to be extended and used to hold one or several graphical representations of an object that you want to display on the screen. We will extend the Sprite class so that we can use its built in methods. We’ll call this new object Player. Player will extend Sprite and have only two properties for now: surf and rect. We will also give surf a color (white in this case) just like the previous surface example except that now the Surface belongs to the Player:

Let’s put it all together!

Run this code. You’ll see a white rectangle at roughly the middle of the screen:

What do you think would happen if you changed screen.blit(player.surf,(400,300)) to screen.blit(player.surf, player.rect)? Once changed, try printing player.rect to the console. The first two attributes of the rect() are x, y coordinates of the top left corner of the rect(). When you pass Blit a Rect, it will use those coordinates to draw the surface. We will use this later to make our player move!

User Input

Here’s where the fun starts! Let’s make our player controllable. We discussed earlier that the keydown event pygame.event.get() pulls the latest event off the top of the event stack. Well, Pygame has another event method called pygame.event.get_pressed(). The get_pressed() method returns a dictionary with all the keydown events in the queue. We will put this in our main loop so we get the keys at every frame.

Now we’ll write a method that will take that dictionary and define the behavior of the sprite based off the keys that are pressed. Here’s what it might look like:

K_UP, K_DOWN, K_LEFT, and K_RIGHT correspond to the arrow keys on the keyboard. So we check that key, and if it’s set to True, then we move our rect() in the relevant direction. Rects have two built-in methods for moving; here we use “move in place” – move_ip() – because we want to move the existing Rect without making a copy.

Add the above method to our Player class and put the get_pressed() call in the main loop. Our code should now look like this:

Now you should be able to move your rectangle around the screen with the arrow keys. You may notice though that you can move off the screen, which is something we probably don’t want. So let’s add a bit of logic to the update method that tests if the rectangle’s coordinates have moved beyond our 800 by 600 boundary; and if so, move it back to the edge:

Here instead of using a move method, we just alter the corresponding coordinates for top, bottom, left, or right.

Now let’s add some enemies!

First let’s create a new sprite class called ‘Enemy’. We will follow the same formula we used for the player class:

There are a couple differences here that we should talk about. First off, when we call get_rect() on our surface, we are setting the center property x coordinate to 820, and our y coordinate to a random number generated by random.randint().

Random is a python library that we will import at the beginning of our file in the complete code (import random). Why the random number? Simple: We want our incoming enemies to start past the right side of the screen (820), at a random place (0-600). We also use random to set a speed property for the enemies. This way we will have some enemies that are fast and some that are slow.

Our update() method for the enemies takes no arguments (we don’t care about input for enemies) and simply moves the enemy toward the left side of the screen at a rate of speed. And the last if statement in the update method tests to see if the enemy has gone past the left side of the screen with the right side of its rectangle (so that they don’t just disappear as soon as they touch the side of the screen). When they pass the side of the screen we call Sprites’ built-in kill() method to delete them from their sprite group thereby preventing them from being rendered. Kill does not release the memory taken by the enemy and relies on you no longer having a reference to it so the Python garbage collector will take care of it.

Groups

Another super useful object that PyGame provides are Sprite groups. They are exactly what they sound like – Groups of Sprites. So why do we use Sprite Groups instead of a list? Well, sprite groups have several methods built into them that will help us later with collisions and updating. Let’s make a Group right now that will hold all the Sprites in our game. After we create it, we will add the Player to the Group since that’s our only Sprite so far. We can create another group for enemies as well. When we call a Sprite’s kill() method, the sprite will be removed from all groups that it is a part of.

Now that we have this all_sprites group, let’s change how we are rendering our objects so that we render all objects in this group.

Now anything we put into all_sprites will be rendered.

Custom Events

Now we have a Sprite Group for our enemies but no actual enemies. So how do we get some enemies on the screen? We could just create a bunch of them at the beginning, but then our game wouldn’t last more than a few seconds. So we will create a custom event that will fire off every few seconds and trigger the creation of a new enemy. We listen for this event in the same way that we listened for key presses or quit events. Creating a custom event is as easy as naming it:

That’s it! Now we have an event called ADDENEMY that we can listen for in our main loop. The only gotcha to keep in mind here is that we need our custom event to have a unique value that is greater than the value of USEREVENT. That’s why we set our new event to equal USEREVENT + 1. One small note for anyone curious about about these events: They are at their core just integer constants. USEREVENT has a numeric value and any custom event we create needs to be an integer value that is greater than USEREVENT (because all the values less than USEREVENT are already taken by built-ins).

Now that we’ve defined our event, we need to insert it into the event queue. Since we need to keep creating them over the course of the game, we will set a timer. To do this we use PyGame’s time() object.

This tells PyGame to fire our ADDENEMY event every 250 milliseconds (every quarter second). This goes outside of our game loop, but will still fire throughout the entire game. Now let’s add some code to listen for our event:

Keep in mind that set_timer() is exclusively used for inserting events into the PyGame event queue – it doesn’t do anything else.

Now we are listening for our ADDENEMY event, and when it fires, we create a new instance of the Enemy class. Then we add that instance to the enemies Sprite Group (which we will later use to test for collision) and to the all_sprites Group (so that it gets rendered along with everything else).

Collision

This is why you will love PyGame! Writing collision code is hard, but PyGame has a LOT of collision detection methods, some of which you can find here. For this tutorial we will be using spritecollideany. The spritecollideany() method takes a Sprite object and a Sprite Group and tests if the Sprite object intersects with any of the Sprites in the Sprite group. So we will take our player Sprite and our enemies Sprite Group and test if our player has been hit by an enemy. Here’s what it looks like in code:

We test if our player Sprite object collides with any Sprites in the enemies Sprite Group, and if it does, we call the kill() method on the player Sprite. Because we are only rendering sprites in the all_sprites Group, and the kill() method removes a Sprite from all its Groups, our player will no longer be rendered, thus ‘killing’ it. Let’s put it all together:

Pygame 1.9.2

Test this out!

Images

Now we have a game, but kind of an ugly game. Next we will replace all the boring white rectangles with cool images that will make the game feel like an actual game.

Pygame 1.9.2a0

In the previous code examples we used a Surface object filled with a color to represent everything in our game. While this is a good way to get a handle on what a surface is and how they work, it makes for an ugly game. We’re going to add some pictures for the enemies and the player. I like to draw my own images, so I made a little jet for the player and some missiles for the enemies, which you can download from the repo. You’re welcome to use my art, draw your own, or download some free game art assets to use.

Altering the Object Constructors

Our current player constructor looks like this:

Our new constructor will look like this:

We want to replace our Surface object with an image. We will use pygame.image.load() by passing it a path to a file. The load() method will actually return a Surface object. We then call convert() on that Surface object to create a copy that will draw more quickly on the screen.

Next we call the set_colorkey() method on our image. The set_colorkey method sets the color in the image that PyGame will render as transparent. In this case I chose white, because that’s the background of my jet image. RLEACCEL is a optional parameter that will help PyGame render faster on non-accelerated displays.

Lastly, we get our rect object in the same way as before: By calling get_rect() on our image.

Remember the image is still a surface object; it now just has a picture painted on it.

Let’s do the same thing with the enemy constructor:

Now we have the same game we had before but nicely skinned with some cool images. I think it’s missing something, though. Let’s add a few clouds going past to give the impression of a jet flying through the sky. To do this we are going to use the exact same principles we used before. First, we will create the Cloud object with an image of a cloud and an update() method that continuously moves the cloud toward the left side of the screen. Then we will create a custom event to spawn our clouds at a set interval (we will also add the spawned clouds to the all_sprites group). Here’s what our cloud object will look like:

That should all look familiar, as should this event creation code, which we will put right below our enemy creation event:

And let’s create a new Sprite Group for them:

Now in our main game loop, where we step through our event queue, we need to start listening for our ADDCLOUD event.

This:

Will become this:

We’re going to add the clouds to the all_sprites Group as well as the new clouds Group. We add them to both because we’re using all_sprites to render and clouds to call their update function. You might ask why we don’t add them to the existing enemies Group; after all, we’re calling nearly identical update functions on them. The reason is, we don’t want to test the player for collisions with the clouds. Our jet needs to pass cleanly through all the clouds. Now all that’s left is calling our clouds Group update() method.

Conclusion

Pygame 1.9.2 Download

That’s it! Test it again, and you should see something like:

Pygame 1.9.2 Download

The complete code is available on the GitHub repo. I hope you enjoyed the tutorial and found it helpful.