Call pre_init to change the defaults used when the real pygame.mixer.init() is called. Keyword arguments are accepted. The best way to set custom mixer playback values is to call pygame.mixer.pre_init() before calling the top level pygame.init(). For backward compatibility argument values of zero are replaced with the startup defaults.
Changed in pygame 1.8: The default buffersize was changed from 1024 to 3072.
Changed in pygame 1.9.1: The default buffersize was changed from 3072 to 4096.
Changed in pygame 2.0.0: The default buffersize was changed from 4096 to 512. The default frequency changed to 44100 from 22050.


This will uninitialize pygame.mixer. All playback will stop and any loaded Sound objects may not be compatible with the mixer if it is reinitialized later.


Sets the number of available channels for the mixer. The default value is 8. The value can be increased or decreased. If the value is decreased, sounds playing on the truncated channels are stopped.


The mixer can reserve any number of channels that will not be automatically selected for playback by Sounds. If sounds are currently playing on the reserved channels they will not be stopped.
This allows the application to reserve a specific number of channels for important sounds that must not be dropped or have a guaranteed channel to play on.


Load a new sound buffer from a filename, a python file object or a readable buffer object. Limited resampling will be performed to help the sample match the initialize arguments for the mixer. A Unicode string can only be a file pathname. A Python 2.x string or a Python 3.x bytes object can be either a pathname or a buffer object. Use the 'file' or 'buffer' keywords to avoid ambiguity; otherwise Sound may guess wrong. If the array keyword is used, the object is expected to export a version 3, C level array interface or, for Python 2.6 or later, a new buffer interface (The object is checked for a buffer interface first.)
The Sound object represents actual sound sample data. Methods that change the state of the Sound object will the all instances of the Sound playback. A Sound object also exports an array interface, and, for Python 2.6 or later, a new buffer interface.
The Sound can be loaded from an OGG audio file or from an uncompressed WAV.
Note: The buffer will be copied internally, no data will be shared between it and the Sound object.
For now buffer and array support is consistent with sndarray.make_sound for Numeric arrays, in that sample sign and byte order are ignored. This will change, either by correctly handling sign and byte order, or by raising an exception when different. Also, source samples are truncated to fit the audio sample size. This will not change.
New in pygame 1.8: pygame.mixer.Sound(buffer)
New in pygame 1.9.2: pygame.mixer.Sound keyword arguments and array interface support
Begin playback of the Sound (i.e., on the computer's speakers) on an available Channel. This will forcibly select a Channel, so playback may cut off a currently playing sound if necessary.
The loops argument controls how many times the sample will be repeated after being played the first time. A value of 5 means that the sound will be played once, then repeated five times, and so is played a total of six times. The default value (zero) means the Sound is not repeated, and so is only played once. If loops is set to -1 the Sound will loop indefinitely (though you can still call stop() to stop it).
The maxtime argument can be used to stop playback after a given number of milliseconds.
The fade_ms argument will make the sound start playing at 0 volume and fade up to full volume over the time given. The sample may end before the fade-in is complete.
This returns the Channel object for the channel that was selected.
This will stop the playback of this Sound on any active Channels.
This will stop playback of the sound after fading it out over the time argument in milliseconds. The Sound will fade and stop on all actively playing channels.
This will set the playback volume (loudness) for this Sound. This will immediately affect the Sound if it is playing. It will also affect any future playback of this Sound.
volume in the range of 0.0 to 1.0 (inclusive)
Return a value from 0.0 to 1.0 representing the volume for this Sound.
Return the number of active channels this sound is playing on.
Return the length of this Sound in seconds.
Return a copy of the Sound object buffer as a bytes (for Python 3.x) or str (for Python 2.x) object.
New in pygame 1.9.2.


This will stop playback of the sound after fading it out over the time argument in milliseconds. The Sound will fade and stop on all actively playing channels.


Return the length of this Sound in seconds.


Return the number of active channels this sound is playing on.


Return a copy of the Sound object buffer as a bytes (for Python 3.x) or str (for Python 2.x) object.
New in pygame 1.9.2.


Return a value from 0.0 to 1.0 representing the volume for this Sound.


Begin playback of the Sound (i.e., on the computer's speakers) on an available Channel. This will forcibly select a Channel, so playback may cut off a currently playing sound if necessary.
The loops argument controls how many times the sample will be repeated after being played the first time. A value of 5 means that the sound will be played once, then repeated five times, and so is played a total of six times. The default value (zero) means the Sound is not repeated, and so is only played once. If loops is set to -1 the Sound will loop indefinitely (though you can still call stop() to stop it).
The maxtime argument can be used to stop playback after a given number of milliseconds.
The fade_ms argument will make the sound start playing at 0 volume and fade up to full volume over the time given. The sample may end before the fade-in is complete.
This returns the Channel object for the channel that was selected.


This will set the playback volume (loudness) for this Sound. This will immediately affect the Sound if it is playing. It will also affect any future playback of this Sound.
volume in the range of 0.0 to 1.0 (inclusive)


This will stop the playback of this Sound on any active Channels.


This will stop all playback of all active mixer channels.


This will resume all active sound channels after they have been paused.


The mouse functions can be used to get the current state of the mouse device. These functions can also alter the system cursor for the mouse.
When the display mode is set, the event queue will start receiving mouse events. 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 rolled up, and to button 5 when the wheel is rolled down. Whenever the mouse is moved it generates a pygame.MOUSEMOTION event. The mouse movement is broken into small and accurate motion events. As the mouse is moving many motion events will be placed on the queue. Mouse motion events that are not properly cleaned from the event queue are the primary reason the event queue fills up.
If the mouse cursor is hidden, and input is grabbed to the current display the mouse will enter a virtual input mode, where the relative movements of the mouse will never be stopped by the borders of the screen. See the functions pygame.mouse.set_visible() and pygame.event.set_grab() to get this configured.
Mouse Wheel Behavior in pygame 2
There is proper functionality for mouse wheel behaviour with pygame 2 supporting pygame.MOUSEWHEEL events. The new events support horizontal and vertical scroll movements, with signed integer values representing the amount scrolled (x and y), as well as flipped direction (the set positive and negative values for each axis is flipped). Read more about SDL2 input-related changes here https://wiki.libsdl.org/MigrationGuide#Input
In pygame 2, the mouse wheel functionality can be used by listening for the pygame.MOUSEWHEEL type of an event. When this event is triggered, a developer can access the appropriate Event object with pygame.event.get(). The object can be used to access data about the mouse scroll, such as which (it will tell you what exact mouse device trigger the event).
Returns a sequence of booleans representing the state of all the mouse buttons. A true value means the mouse is currently being pressed at the time of the call.
Note, to get all of the mouse events it is better to use either pygame.event.wait() or pygame.event.get() and check all of those events to see if they are MOUSEBUTTONDOWN, MOUSEBUTTONUP, or MOUSEMOTION.
Note, that on X11 some X servers use middle button emulation. When you click both buttons 1 and 3 at the same time a 2 button event can be emitted.
Note, remember to call pygame.event.get() before this function. Otherwise it will not work as expected.
To support five button mice, an optional parameter num_buttons has been added in pygame 2. When this is set to 5, button4 and button5 are added to the returned tuple. Only 3 and 5 are valid values for this parameter.
Changed in pygame 2.0.0: num_buttons argument added
Returns the x and y position of the mouse cursor. The position is relative to the top-left corner of the display. The cursor position can be located outside of the display window, but is always constrained to the screen.
Returns the amount of movement in x and y since the previous call to this function. The relative movement of the mouse cursor is constrained to the edges of the screen, but see the virtual input mouse mode for a way around this. Virtual input mode is described at the top of the page.
Set the current mouse position to arguments given. If the mouse cursor is visible it will jump to the new coordinates. Moving the mouse will generate a new pygame.MOUSEMOTION event.
If the bool argument is true, the mouse cursor will be visible. This will return the previous visible state of the cursor.
Get the current visibility state of the mouse cursor. True if the mouse is visible, False otherwise.
New in pygame 2.0.0.
Returns true when pygame is receiving mouse input events (or, in windowing terminology, is "active" or has the "focus").
This method is most useful when working in a window. By contrast, in full-screen mode, this method always returns true.
Note: under MS Windows, the window that has the mouse focus also has the keyboard focus. But under X-Windows, one window can receive mouse events and another receive keyboard events. pygame.mouse.get_focused() indicates whether the pygame window receives mouse events.
When the mouse cursor is visible, it will be displayed as a black and white bitmap using the given bitmask arrays. The size is a sequence containing the cursor width and height. hotspot is a sequence containing the cursor hotspot position.
A cursor has a width and height, but a mouse position is represented by a set of point coordinates. So the value passed into the cursor hotspot variable helps pygame to actually determine at what exact point the cursor is at.
xormasks is a sequence of bytes containing the cursor xor data masks. Lastly andmasks, a sequence of bytes containing the cursor bitmask data. To create these variables, we can make use of the pygame.cursors.compile() function.
Width and height must be a multiple of 8, and the mask arrays must be the correct size for the given width and height. Otherwise an exception is raised.
See the pygame.cursor module for help creating default and custom masks for the mouse cursor and also for more examples related to cursors.
When the mouse cursor is visible, it will displayed as a operating system specific variant of the options below.
New in pygame 2.0.0.
Get the information about the mouse system cursor. The return value is the same data as the arguments passed into pygame.mouse.set_cursor().
Note
This method is unavailable with pygame 2, as SDL2 does not provide the underlying code to implement this method.


The pygame.pixelcopy module contains functions for copying between surfaces and objects exporting an array structure interface. It is a backend for pygame.surfarray, adding NumPy support. But pixelcopy is more general, and intended for direct use.
The array struct interface exposes an array's data in a standard way. It was introduced in NumPy. In Python 2.7 and above it is replaced by the new buffer protocol, though the buffer protocol is still a work in progress. The array struct interface, on the other hand, is stable and works with earlier Python versions. So for now the array struct interface is the predominate way pygame handles array introspection.
New in pygame 1.9.2.
The surface_to_array function copies pixels from a Surface object to a 2D or 3D array. Depending on argument kind and the target array dimension, a copy may be raw pixel value, RGB, a color component slice, or colorkey alpha transparency value. Recognized kind values are the single character codes 'P', 'R', 'G', 'B', 'A', and 'C'. Kind codes are case insensitive, so 'p' is equivalent to 'P'. The first two dimensions of the target must be the surface size (w, h).
The default 'P' kind code does a direct raw integer pixel (mapped) value copy to a 2D array and a 'RGB' pixel component (unmapped) copy to a 3D array having shape (w, h, 3). For an 8 bit colormap surface this means the table index is copied to a 2D array, not the table value itself. A 2D array's item size must be at least as large as the surface's pixel byte size. The item size of a 3D array must be at least one byte.
For the 'R', 'G', 'B', and 'A' copy kinds a single color component of the unmapped surface pixels are copied to the target 2D array. For kind 'A' and surfaces with source alpha (the surface was created with the SRCALPHA flag), has a colorkey (set with Surface.set_colorkey()), or has a blanket alpha (set with Surface.set_alpha()) then the alpha values are those expected for a SDL surface. If a surface has no explicit alpha value, then the target array is filled with the value of the optional opaque surface_to_array argument (default 255: not transparent).
Copy kind 'C' is a special case for alpha copy of a source surface with colorkey. Unlike the 'A' color component copy, the clear argument value is used for colorkey matches, opaque otherwise. By default, a match has alpha 0 (totally transparent), while everything else is alpha 255 (totally opaque). It is a more general implementation of pygame.surfarray.array_colorkey().
Specific to surface_to_array, a ValueError is raised for target arrays with incorrect shape or item size. A TypeError is raised for an incorrect kind code. Surface specific problems, such as locking, raise a pygame.error.
See pygame.surfarray.blit_array().
Map an array of color element values - (w, h, ..., 3) - to an array of pixels - (w, h) according to the format of <surface>.
Create a new Surface that best resembles the data and format of the array. The array can be 2D or 3D with any sized integer values.


The pygame package represents the top-level package for others to use. Pygame itself is broken into many submodules, but this does not affect programs that use pygame.
As a convenience, most of the top-level variables in pygame have been placed inside a module named pygame.locals. This is meant to be used with from pygame.locals import *, in addition to import pygame.
When you import pygame all available pygame submodules are automatically imported. Be aware that some of the pygame modules are considered optional, and may not be available. In that case, pygame will provide a placeholder object instead of the module, which can be used to test for availability.
Initialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but pygame.init() is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.
You may want to initialize the different modules separately to speed up your program or to not use modules your game does not require.
It is safe to call this init() more than once as repeated calls will have no effect. This is true even if you have pygame.quit() all the modules.
Uninitialize all pygame modules that have previously been initialized. When the Python interpreter shuts down, this method is called regardless, so your program should not need it, except when it wants to terminate its pygame resources and continue. It is safe to call this function more than once as repeated calls have no effect.
Note
Calling pygame.quit() will not exit your program. Consider letting your program end in the same way a normal Python program will end.
Returns True if pygame is currently initialized.
New in pygame 1.9.5.
This exception is raised whenever a pygame or SDL operation fails. You can catch any anticipated problems and deal with the error. The exception is always raised with a descriptive message about the problem.
Derived from the RuntimeError exception, which can also be used to catch these raised errors.
SDL maintains an internal error message. This message will usually be given to you when pygame.error() is raised, so this function will rarely be needed.
SDL maintains an internal error message. This message will usually be given to you when pygame.error() is raised, so this function will rarely be needed.
Returns the three version numbers of the SDL library. This version is built at compile time. It can be used to detect which features may or may not be available through pygame.
New in pygame 1.7.0.
Returns the byte order of the SDL library. It returns 1234 for little endian byte order and 4321 for big endian byte order.
New in pygame 1.8.
When pygame.quit() is called, all registered quit functions are called. Pygame modules do this automatically when they are initializing, so this function will rarely be needed.
obj: If Unicode, encode; if bytes, return unaltered; if anything else, return None; if not given, raise SyntaxError.
encoding (string): If present, encoding to use. The default is 'unicode_escape'.
errors (string): If given, how to handle unencodable characters. The default is 'backslashreplace'.
etype (exception type): If given, the exception type to raise for an encoding error. The default is UnicodeEncodeError, as returned by PyUnicode_AsEncodedString(). For the default encoding and errors values there should be no encoding errors.
This function is used in encoding file paths. Keyword arguments are supported.
New in pygame 1.9.2: (primarily for use in unit tests)
obj: If Unicode, encode; if bytes, return unaltered; if anything else, return None; if not given, raise SyntaxError.
etype (exception type): If given, the exception type to raise for an encoding error. The default is UnicodeEncodeError, as returned by PyUnicode_AsEncodedString().
This function is used to encode file paths in pygame. Encoding is to the codec as returned by sys.getfilesystemencoding(). Keyword arguments are supported.
New in pygame 1.9.2: (primarily for use in unit tests)
This module is automatically imported into the pygame package and can be used to check which version of pygame has been imported.
This is the version represented as a string. It can contain a micro release number as well, e.g. '1.5.2'
This version information can easily be compared with other version numbers of the same format. An example of checking pygame version numbers would look like this:
New in pygame 1.9.6: Attributes major, minor, and patch.
Changed in pygame 1.9.6: str(pygame.version.vernum) returns a string like "2.0.0" instead of "(2, 0, 0)".
Changed in pygame 1.9.6: repr(pygame.version.vernum) returns a string like "PygameVersion(major=2, minor=0, patch=0)" instead of "(2, 0, 0)".
The Mercurial node identifier of the repository checkout from which this package was built. If the identifier ends with a plus sign '+' then the package contains uncommitted changes. Please include this revision number in bug reports, especially for non-release pygame builds.
Important note: pygame development has moved to github, this variable is obsolete now. As soon as development shifted to github, this variable started returning an empty string "". It has always been returning an empty string since v1.9.5.
Changed in pygame 1.9.5: Always returns an empty string "".
This is the SDL library version represented as an extended tuple. It also has attributes 'major', 'minor' & 'patch' that can be accessed like this:
printing the whole thing returns a string like this:
New in pygame 2.0.0.
Setting Environment Variables
Some aspects of pygame's behaviour can be controlled by setting environment variables, they cover a wide range of the library's functionality. Some of the variables are from pygame itself, while others come from the underlying C SDL library that pygame uses.
In python, environment variables are usually set in code like this:
Or to preserve users ability to override the variable:
If the variable is more useful for users of an app to set than the developer then they can set it like this:
Windows:
Linux/Mac:
For some variables they need to be set before initialising pygame, some must be set before even importing pygame, and others can simply be set right before the area of code they control is run.
Below is a list of environment variables, their settable values, and a brief description of what they do.
Pygame Environment Variables
These variables are defined by pygame itself.
This sets the display where pygame will open its window or screen. The value set here will be used if set before calling pygame.display.set_mode(), and as long as no 'display' parameter is passed into pygame.display.set_mode().
This forces set_mode() to use the SCALED display mode and, if "photo" is set, makes the scaling use the slowest, but highest quality anisotropic scaling algorithm, if it is available. Must be set before calling pygame.display.set_mode().
This makes pygame use the SDL2 blitter for all alpha blending. The SDL2 blitter is sometimes faster than the default blitter but uses a different formula so the final colours may differ. Must be set before pygame.init() is called.
This stops the welcome message popping up in the console that tells you which version of python, pygame & SDL you are using. Must be set before importing pygame.
This switches the pygame.font module to a pure freetype implementation that bypasses SDL_ttf. See the font module for why you might want to do this. Must be set before importing pygame.
Forces the library backend used in the camera module, overriding the platform defaults. Must be set before calling pygame.camera.init().
SDL Environment Variables
These variables are defined by SDL.
For documentation on the environment variables available in pygame 1 try here. For Pygame 2, some selected environment variables are listed below.
This will make the pygame window open in the centre of the display. Must be set before calling pygame.display.set_mode().
This allows control over the placement of the pygame window within the display. Must be set before calling pygame.display.set_mode().
On some platforms there are multiple video drivers available and this allows users to pick between them. More information is available here. Must be set before calling pygame.init() or pygame.display.init().
On some platforms there are multiple audio drivers available and this allows users to pick between them. More information is available here. Must be set before calling pygame.init() or pygame.mixer.init().
By default pygame apps disable screensavers while they are running. Setting this environment variable allows users or developers to change that and make screensavers run again.
By default SDL tries to disable the X11 compositor for all pygame apps. This is usually a good thing as it's faster, however if you have an app which doesn't update every frame and are using linux you may want to disable this bypass. The bypass has reported problems on KDE linux. This variable is only used on x11/linux platforms.


EXPERIMENTAL!: This API may change or disappear in later pygame releases. If you use this, your code may break with the next pygame release.
The scrap module is for transferring data to/from the clipboard. This allows for cutting and pasting data between pygame and other applications. Some basic data (MIME) types are defined and registered:
pygame.SCRAP_PPM, pygame.SCRAP_PBM and pygame.SCRAP_BMP are suitable for surface buffers to be shared with other applications. pygame.SCRAP_TEXT is an alias for the plain text clipboard type.
Depending on the platform, additional types are automatically registered when data is placed into the clipboard to guarantee a consistent sharing behaviour with other applications. The following listed types can be used as strings to be passed to the respective pygame.scrap module functions.
For Windows platforms, these additional types are supported automatically and resolve to their internal definitions:
For X11 platforms, these additional types are supported automatically and resolve to their internal definitions:
User defined types can be used, but the data might not be accessible by other applications unless they know what data type to look for. Example: Data placed into the clipboard by pygame.scrap.put("my_data_type", byte_data) can only be accessed by applications which query the clipboard for the "my_data_type" data type.
For an example of how the scrap module works refer to the examples page (pygame.examples.scrap_clipboard.main()) or the code directly in GitHub (pygame/examples/scrap_clipboard.py).
New in pygame 1.8.
Note
The scrap module is currently only supported for Windows, X11 and Mac OS X. On Mac OS X only text works at the moment - other types may be supported in future releases.
Initialize the scrap module.
Note
The scrap module requires pygame.display.set_mode() be called before being initialized.
Gets the scrap module's initialization state.
New in pygame 1.9.5.
Retrieves the data for the specified type from the clipboard. In python 3 the data is returned as a byte string and might need further processing (such as decoding to Unicode).
Gets a list of data type string identifiers for the data currently available on the clipboard. Each identifier can be used in the pygame.scrap.get() method to get the clipboard content of the specific type.
Places data for a given clipboard type into the clipboard. The data must be a string buffer. The type is a string identifying the type of data to be placed into the clipboard. This can be one of the predefined pygame.SCRAP_PBM, pygame.SCRAP_PPM, pygame.SCRAP_BMP or pygame.SCRAP_TEXT values or a user defined string identifier.
pygame.error -- if unable to put the data into the clipboard
Checks whether data for the given type is currently available in the clipboard.
Indicates if the clipboard ownership has been lost by the pygame application.
Sets the access mode for the clipboard. This is only of interest for X11 environments where clipboard modes pygame.SCRAP_SELECTION (for mouse selections) and pygame.SCRAP_CLIPBOARD (for the clipboard) are available. Setting the mode to pygame.SCRAP_SELECTION in other environments will not change the mode from pygame.SCRAP_CLIPBOARD.


Functions to convert between NumPy arrays and Sound objects. This module will only be available when pygame can use the external NumPy package.
Sound data is made of thousands of samples per second, and each sample is the amplitude of the wave at a particular moment in time. For example, in 22-kHz format, element number 5 of the array is the amplitude of the wave after 5/22000 seconds.
Each sample is an 8-bit or 16-bit integer, depending on the data format. A stereo sound file has two values per sample, while a mono sound file only has one.
Creates a new array for the sound data and copies the samples. The array will always be in the format returned from pygame.mixer.get_init().
Creates a new array that directly references the samples in a Sound object. Modifying the array will change the Sound. The array will always be in the format returned from pygame.mixer.get_init().
Create a new playable Sound object from an array. The mixer module must be initialized and the array format must be similar to the mixer audio format.
DEPRECATED: Uses the requested array type for the module functions. The only supported arraytype is 'numpy'. Other values will raise ValueError.
DEPRECATED: Returns the currently active array type. This will be a value of the get_arraytypes() tuple and indicates which type of array module is used for the array creation.
New in pygame 1.8.
DEPRECATED: Checks, which array systems are available and returns them as a tuple of strings. The values of the tuple can be used directly in the pygame.sndarray.use_arraytype() () method. If no supported array system could be found, None will be returned.
New in pygame 1.8.


This module contains several simple classes to be used within games. There is the main Sprite class and several Group classes that contain Sprites. The use of these classes is entirely optional when using pygame. The classes are fairly lightweight and only provide a starting place for the code that is common to most games.
The Sprite class is intended to be used as a base class for the different types of objects in the game. There is also a base Group class that simply stores sprites. A game could create new types of Group classes that operate on specially customized Sprite instances they contain.
The basic Sprite class can draw the Sprites it contains to a Surface. The Group.draw() method requires that each Sprite have a Surface.image attribute and a Surface.rect. The Group.clear() method requires these same attributes, and can be used to erase all the Sprites with background. There are also more advanced Groups: pygame.sprite.RenderUpdates() and pygame.sprite.OrderedUpdates().
Lastly, this module contains several collision functions. These help find sprites inside multiple groups that have intersecting bounding rectangles. To find the collisions, the Sprites are required to have a Surface.rect attribute assigned.
The groups are designed for high efficiency in removing and adding Sprites to them. They also allow cheap testing to see if a Sprite already exists in a Group. A given Sprite can exist in any number of groups. A game could use some groups to control object rendering, and a completely separate set of groups to control interaction or player movement. Instead of adding type attributes or bools to a derived Sprite class, consider keeping the Sprites inside organized Groups. This will allow for easier lookup later in the game.
Sprites and Groups manage their relationships with the add() and remove() methods. These methods can accept a single or multiple targets for membership. The default initializers for these classes also takes a single or list of targets for initial membership. It is safe to repeatedly add and remove the same Sprite from a Group.
While it is possible to design sprite and group classes that don't derive from the Sprite and AbstractGroup classes below, it is strongly recommended that you extend those when you add a Sprite or Group class.
Sprites are not thread safe. So lock them yourself if using threads.
The base class for visible game objects. Derived classes will want to override the Sprite.update() and assign a Sprite.image and Sprite.rect attributes. The initializer can accept any number of Group instances to be added to.
When subclassing the Sprite, be sure to call the base initializer before adding the Sprite to Groups. For example:
The default implementation of this method does nothing; it's just a convenient "hook" that you can override. This method is called by Group.update() with whatever arguments you give it.
There is no need to use this method if not using the convenience method by the same name in the Group class.
Any number of Group instances can be passed as arguments. The Sprite will be added to the Groups it is not already a member of.
Any number of Group instances can be passed as arguments. The Sprite will be removed from the Groups it is currently a member of.
The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups.
Returns True when the Sprite belongs to one or more Groups.
Return a list of all the Groups that contain this Sprite.
Extra DirtySprite attributes with their default values:
dirty = 1
blendmode = 0
source_rect = None
visible = 1
layer = 0
A simple container for Sprite objects. This class can be inherited to create containers with more specific behaviors. The constructor takes any number of Sprite arguments to add to the Group. The group supports the following standard Python operations:
The Sprites in the Group are not ordered, so drawing and iterating the Sprites is in no particular order.
Return a list of all the Sprites this group contains. You can also get an iterator from the group, but you cannot iterate over a Group while modifying it.
Creates a new Group with all the same Sprites as the original. If you have subclassed Group, the new object will have the same (sub-)class as the original. This only works if the derived class's constructor takes the same arguments as the Group class's.
Add any number of Sprites to this Group. This will only add Sprites that are not already members of the Group.
Each sprite argument can also be a iterator containing Sprites.
Remove any number of Sprites from the Group. This will only remove Sprites that are already members of the Group.
Each sprite argument can also be a iterator containing Sprites.
Return True if the Group contains all of the given sprites. This is similar to using the "in" operator on the Group ("if sprite in group: ..."), which tests if a single Sprite belongs to a Group.
Each sprite argument can also be a iterator containing Sprites.
Calls the update() method on all Sprites in the Group. The base Sprite class has an update method that takes any number of arguments and does nothing. The arguments passed to Group.update() will be passed to each Sprite.
There is no way to get the return value from the Sprite.update() methods.
Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.
The Group does not keep sprites in any order, so the draw order is arbitrary.
Erases the Sprites used in the last Group.draw() call. The destination Surface is cleared by filling the drawn Sprite positions with the background.
The background is usually a Surface image the same dimensions as the destination Surface. However, it can also be a callback function that takes two arguments; the destination Surface and an area to clear. The background callback function will be called several times each clear.
Here is an example callback that will clear the Sprites with solid red:
Removes all Sprites from this Group.
This class is an alias to pygame.sprite.Group(). It has no additional functionality.
This class is an alias to pygame.sprite.Group(). It has no additional functionality.
This class is derived from pygame.sprite.Group(). It has an extended draw() method that tracks the changed areas of the screen.
Draws all the Sprites to the surface, the same as Group.draw(). This method also returns a list of Rectangular areas on the screen that have been changed. The returned changes include areas of the screen that have been affected by previous Group.clear() calls.
The returned Rect list should be passed to pygame.display.update(). This will help performance on software driven display modes. This type of updating is usually only helpful on destinations with non-animating backgrounds.
This class derives from pygame.sprite.RenderUpdates(). It maintains the order in which the Sprites were added to the Group for rendering. This makes adding and removing Sprites from the Group a little slower than regular Groups.
This group is fully compatible with pygame.sprite.Sprite.
You can set the default layer through kwargs using 'default_layer' and an integer for the layer. The default layer is 0.
If the sprite you add has an attribute _layer then that layer will be used. If the **kwarg contains 'layer' then the sprites passed will be added to that layer (overriding the sprite.layer attribute). If neither sprite has attribute layer nor **kwarg then the default layer is used to add the sprites.
New in pygame 1.8.
If the sprite(s) have an attribute layer then that is used for the layer. If **kwargs contains 'layer' then the sprite(s) will be added to that argument (overriding the sprite layer attribute). If neither is passed then the sprite(s) will be added to the default layer.
Bottom sprites first, top last.
Raises IndexOutOfBounds if the idx is not within range.
sprite must have been added to the renderer. It is not checked.
If the sprite is not found then it will return the default layer.
Brings the sprite to front, changing sprite layer to topmost layer (added at the end of that layer).
Moves the sprite to the bottom layer, moving it behind all other layers and adding one additional layer.
Returns all sprites from a layer, ordered by how they where added. It uses linear search and the sprites are not removed from layer.
The layers number must exist, it is not checked.
This group requires pygame.sprite.DirtySprite or any sprite that has the following attributes:
It uses the dirty flag technique and is therefore faster than the pygame.sprite.RenderUpdates if you have many static sprites. It also switches automatically between dirty rect update and full screen drawing, so you do no have to worry what would be faster.
Same as for the pygame.sprite.Group. You can specify some additional attributes through kwargs:
New in pygame 1.8.
You can pass the background too. If a background is already set, then the bgd argument has no effect.
screen_rect is in screen coordinates.
sprite must have been added to the renderer. It is not checked.
Default is 1000./80 where 80 is the fps I want to switch to full screen mode. This method's name is a typo and should be fixed.
The GroupSingle container only holds a single Sprite. When a new Sprite is added, the old one is removed.
There is a special property, GroupSingle.sprite, that accesses the Sprite that this Group contains. It can be None when the Group is empty. The property can also be assigned to add a Sprite into the GroupSingle container.
Return a list containing all Sprites in a Group that intersect with another Sprite. Intersection is determined by comparing the Sprite.rect attribute of each Sprite.
The dokill argument is a bool. If set to True, all Sprites that collide will be removed from the Group.
The collided argument is a callback function used to calculate if two sprites are colliding. it should take two sprites as values, and return a bool value indicating if they are colliding. If collided is not passed, all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.
collided callables:
Example:
Tests for collision between two sprites. Uses the pygame rect colliderect function to calculate the collision. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" attributes.
New in pygame 1.8.
A callable class that checks for collisions between two sprites, using a scaled version of the sprites rects.
Is created with a ratio, the instance is then intended to be passed as a collided callback function to the *collide functions.
A ratio is a floating point number - 1.0 is the same size, 2.0 is twice as big, and 0.5 is half the size.
New in pygame 1.8.1.
Tests for collision between two sprites, by testing to see if two circles centered on the sprites overlap. If the sprites have a "radius" attribute, that is used to create the circle, otherwise a circle is created that is big enough to completely enclose the sprites rect as given by the "rect" attribute. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute.
New in pygame 1.8.1.
A callable class that checks for collisions between two sprites, using a scaled version of the sprites radius.
Is created with a floating point ratio, the instance is then intended to be passed as a collided callback function to the *collide functions.
A ratio is a floating point number - 1.0 is the same size, 2.0 is twice as big, and 0.5 is half the size.
The created callable tests for collision between two sprites, by testing to see if two circles centered on the sprites overlap, after scaling the circles radius by the stored ratio. If the sprites have a "radius" attribute, that is used to create the circle, otherwise a circle is created that is big enough to completely enclose the sprites rect as given by the "rect" attribute. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute.
New in pygame 1.8.1.
Tests for collision between two sprites, by testing if their bitmasks overlap (uses pygame.mask.Mask.overlap()). If the sprites have a mask attribute, it is used as the mask, otherwise a mask is created from the sprite's image (uses pygame.mask.from_surface()). Sprites must have a rect attribute; the mask attribute is optional.
The first point of collision between the masks is returned. The collision point is offset from sprite1's mask's topleft corner (which is always (0, 0)). The collision point is a position within the mask and is not related to the actual screen position of sprite1.
This function is intended to be passed as a collided callback function to the group collide functions (see spritecollide(), groupcollide(), spritecollideany()).
Note
To increase performance, create and set a mask attibute for all sprites that will use this function to check for collisions. Otherwise, each time this function is called it will create new masks.
Note
A new mask needs to be recreated each time a sprite's image is changed (e.g. if a new image is used or the existing image is rotated).
New in pygame 1.8.0.
This will find collisions between all the Sprites in two groups. Collision is determined by comparing the Sprite.rect attribute of each Sprite or by using the collided function if it is not None.
Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.
If either dokill argument is True, the colliding Sprites will be removed from their respective Group.
The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.
If the sprite collides with any single sprite in the group, a single sprite from the group is returned. On no collision None is returned.
If you don't need all the features of the pygame.sprite.spritecollide() function, this function will be a bit quicker.
The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.


Functions to convert pixel data between pygame Surfaces and arrays. This module will only be functional when pygame can use the external NumPy package.
Every pixel is stored as a single integer value to represent the red, green, and blue colors. The 8-bit images use a value that looks into a colormap. Pixels with higher depth use a bit packing process to place three or four values into a single number.
The arrays are indexed by the X axis first, followed by the Y axis. Arrays that treat the pixels as a single integer are referred to as 2D arrays. This module can also separate the red, green, and blue color values into separate indices. These types of arrays are referred to as 3D arrays, and the last index is 0 for red, 1 for green, and 2 for blue.
Copy the mapped (raw) pixels from a Surface into a 2D array. The bit depth of the surface will control the size of the integer values, and will work for any type of pixel format.
This function will temporarily lock the Surface as pixels are copied (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).
Create a new 2D array that directly references the pixel values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
Pixels from a 24-bit Surface cannot be referenced, but all other Surface bit depths can.
The Surface this references will remain locked for the lifetime of the array (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).
Copy the pixels from a Surface into a 3D array. The bit depth of the surface will control the size of the integer values, and will work for any type of pixel format.
This function will temporarily lock the Surface as pixels are copied (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).
Create a new 3D array that directly references the pixel values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This will only work on Surfaces that have 24-bit or 32-bit formats. Lower pixel formats cannot be referenced.
The Surface this references will remain locked for the lifetime of the array (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).
Copy the pixel alpha values (degree of transparency) from a Surface into a 2D array. This will work for any type of Surface format. Surfaces without a pixel alpha will return an array with all opaque values.
This function will temporarily lock the Surface as pixels are copied (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).
Create a new 2D array that directly references the alpha values (degree of transparency) in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 32-bit Surfaces with a per-pixel alpha value.
The Surface this array references will remain locked for the lifetime of the array.
Create a new 2D array that directly references the red values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 24-bit or 32-bit Surfaces.
The Surface this array references will remain locked for the lifetime of the array.
Create a new 2D array that directly references the green values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 24-bit or 32-bit Surfaces.
The Surface this array references will remain locked for the lifetime of the array.
Create a new 2D array that directly references the blue values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 24-bit or 32-bit Surfaces.
The Surface this array references will remain locked for the lifetime of the array.
Create a new array with the colorkey transparency value from each pixel. If the pixel matches the colorkey it will be fully transparent; otherwise it will be fully opaque.
This will work on any type of Surface format. If the image has no colorkey a solid opaque array will be returned.
This function will temporarily lock the Surface as pixels are copied.
Create a new Surface that best resembles the data and format on the array. The array can be 2D or 3D with any sized integer values. Function make_surface uses the array struct interface to acquire array properties, so is not limited to just NumPy arrays. See pygame.pixelcopy.
New in pygame 1.9.2: array struct interface support.
Directly copy values from an array into a Surface. This is faster than converting the array into a Surface and blitting. The array must be the same dimensions as the Surface and will completely replace all pixel values. Only integer, ASCII character and record arrays are accepted.
This function will temporarily lock the Surface as the new values are copied.
Convert a 3D array into a 2D array. This will use the given Surface format to control the conversion. Palette surface formats are supported for NumPy arrays.
DEPRECATED: Uses the requested array type for the module functions. The only supported arraytype is 'numpy'. Other values will raise ValueError.
DEPRECATED: Returns the currently active array type. This will be a value of the get_arraytypes() tuple and indicates which type of array module is used for the array creation.
New in pygame 1.8.
DEPRECATED: Checks, which array systems are available and returns them as a tuple of strings. The values of the tuple can be used directly in the pygame.surfarray.use_arraytype() () method. If no supported array system could be found, None will be returned.
New in pygame 1.8.


A quick way to run the test suite package from the command line is to import the go submodule with the Python -m option:
Command line option --help displays a usage message. Available options correspond to the pygame.tests.run() arguments.
The xxxx_test submodules of the tests package are unit test suites for individual parts of pygame. Each can also be run as a main program. This is useful if the test, such as cdrom_test, is interactive.
For pygame development the test suite can be run from a pygame distribution root directory. Program run_tests.py is provided for convenience, though test/go.py can be run directly.
Module level tags control which modules are included in a unit test run. Tags are assigned to a unit test module with a corresponding <name>_tags.py module. The tags module has the global __tags__, a list of tag names. For example, cdrom_test.py has a tag file cdrom_tags.py containing a tags list that has the 'interactive' string. The 'interactive' tag indicates cdrom_test.py expects user input. It is excluded from a run_tests.py or pygame.tests.go run. Two other tags that are excluded are 'ignore' and 'subprocess_ignore'. These two tags indicate unit tests that will not run on a particular platform, or for which no corresponding pygame module is available. The test runner will list each excluded module along with the tag responsible.
Positional arguments (optional):
Keyword arguments:
Return value:
By default individual test modules are run in separate subprocesses. This recreates normal pygame usage where pygame.init() and pygame.quit() are called only once per program execution, and avoids unfortunate interactions between test modules. Also, a time limit is placed on test execution, so frozen tests are killed when there time allotment expired. Use the single process option if threading is not working properly or if tests are taking too long. It is not guaranteed that all tests will pass in single process mode.
Tests are run in a randomized order if the randomize argument is True or a seed argument is provided. If no seed integer is provided then the system time is used.
Individual test modules may have a __tags__ attribute, a list of tag strings used to selectively omit modules from a run. By default only 'interactive' modules such as cdrom_test are ignored. An interactive module must be run from the console as a Python program.
This function can only be called once per Python session. It is not reentrant.


Times in pygame are represented in milliseconds (1/1000 seconds). Most platforms have a limited time resolution of around 10 milliseconds. This resolution, in milliseconds, is given in the TIMER_RESOLUTION constant.
Return the number of milliseconds since pygame.init() was called. Before pygame is initialized this will always be 0.
Will pause for a given number of milliseconds. This function sleeps the process to share the processor with other programs. A program that waits for even a few milliseconds will consume very little processor time. It is slightly less accurate than the pygame.time.delay() function.
This returns the actual number of milliseconds used.
Will pause for a given number of milliseconds. This function will use the processor (rather than sleeping) in order to make the delay more accurate than pygame.time.wait().
This returns the actual number of milliseconds used.
Set an event type to appear on the event queue every given number of milliseconds. The first event will not appear until the amount of time has passed.
Every event type can have a separate timer attached to it. It is best to use the value between pygame.USEREVENT and pygame.NUMEVENTS.
To disable the timer for an event, set the milliseconds argument to 0.
If the once argument is True, then only send the timer once.
New in pygame 2.0.0.dev3: once argument added.
Creates a new Clock object that can be used to track an amount of time. The clock also provides several functions to help control a game's framerate.
This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.
Note that this function uses SDL_Delay function which is not accurate on every platform, but does not use much CPU. Use tick_busy_loop if you want an accurate timer, and don't mind chewing CPU.
This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick_busy_loop(40) once per frame, the program will never run at more than 40 frames per second.
Note that this function uses pygame.time.delay(), which uses lots of CPU in a busy loop to make sure that timing is more accurate.
New in pygame 1.8.
The number of milliseconds that passed between the previous two calls to Clock.tick().
Similar to Clock.get_time(), but does not include any time used while Clock.tick() was delaying to limit the framerate.
Compute your game's framerate (in frames per second). It is computed by averaging the last ten calls to Clock.tick().


A Surface transform is an operation that moves or resizes the pixels. All these functions take a Surface to operate on and return a new Surface with the results.
Some of the transforms are considered destructive. These means every time they are performed they lose pixel data. Common examples of this are resizing and rotating. For this reason, it is better to re-transform the original surface than to keep transforming an image multiple times. (For example, suppose you are animating a bouncing spring which expands and contracts. If you applied the size changes incrementally to the previous images, you would lose detail. Instead, always begin with the original image and scale to the desired size.)
This can flip a Surface either vertically, horizontally, or both. Flipping a Surface is non-destructive and returns a new Surface with the same dimensions.
Resizes the Surface to a new resolution. This is a fast scale operation that does not sample the results.
An optional destination surface can be used, rather than have it create a new one. This is quicker if you want to repeatedly scale something. However the destination must be the same size as the (width, height) passed in. Also the destination surface must be the same format.
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Unless rotating by 90 degree increments, the image will be padded larger to hold the new size. If the image has pixel alphas, the padded area will be transparent. Otherwise pygame will pick a color that matches the Surface colorkey or the topleft pixel value.
This is a combined scale and rotation transform. The resulting Surface will be a filtered 32-bit Surface. The scale argument is a floating point value that will be multiplied by the current resolution. The angle argument is a floating point value that represents the counterclockwise degrees to rotate. A negative rotation angle will rotate clockwise.
This will return a new image that is double the size of the original. It uses the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics.
This really only has an effect on simple images with solid colors. On photographic and antialiased images it will look like a regular unfiltered scale.
An optional destination surface can be used, rather than have it create a new one. This is quicker if you want to repeatedly scale something. However the destination must be twice the size of the source surface passed in. Also the destination surface must be the same format.
Uses one of two different algorithms for scaling each dimension of the input surface as required. For shrinkage, the output pixels are area averages of the colors they cover. For expansion, a bilinear filter is used. For the x86-64 and i686 architectures, optimized MMX routines are included and will run much faster than other machine types. The size is a 2 number sequence for (width, height). This function only works for 24-bit or 32-bit surfaces. An exception will be thrown if the input surface bit depth is less than 24.
New in pygame 1.8.
Shows whether or not smoothscale is using MMX or SSE acceleration. If no acceleration is available then "GENERIC" is returned. For a x86 processor the level of acceleration to use is determined at runtime.
This function is provided for pygame testing and debugging.
Sets smoothscale acceleration. Takes a string argument. A value of 'GENERIC' turns off acceleration. 'MMX' uses MMX instructions only. 'SSE' allows SSE extensions as well. A value error is raised if type is not recognized or not supported by the current processor.
This function is provided for pygame testing and debugging. If smoothscale causes an invalid instruction error then it is a pygame/SDL bug that should be reported. Use this function as a temporary fix only.
Extracts a portion of an image. All vertical and horizontal pixels surrounding the given rectangle area are removed. The corner areas (diagonal to the rect) are then brought together. (The original image is not altered by this operation.)
NOTE: If you want a "crop" that returns the part of an image within a rect, you can blit with a rect to a new surface or copy a subsurface.
Finds the edges in a surface using the laplacian algorithm.
New in pygame 1.8.
Takes a sequence of surfaces and returns a surface with average colors from each of the surfaces.
palette_colors - if true we average the colors in palette, otherwise we average the pixel values. This is useful if the surface is actually greyscale colors, and not palette colors.
Note, this function currently does not handle palette using surfaces correctly.
New in pygame 1.8.
New in pygame 1.9: palette_colors argument
Finds the average color of a Surface or a region of a surface specified by a Rect, and returns it as a Color.
This versatile function can be used for find colors in a 'surf' close to a 'search_color' or close to colors in a separate 'search_surf'.
It can also be used to transfer pixels into a 'dest_surf' that match or don't match.
By default it sets pixels in the 'dest_surf' where all of the pixels NOT within the threshold are changed to set_color. If inverse_set is optionally set to True, the pixels that ARE within the threshold are changed to set_color.
If the optional 'search_surf' surface is given, it is used to threshold against rather than the specified 'set_color'. That is, it will find each pixel in the 'surf' that is within the 'threshold' of the pixel at the same coordinates of the 'search_surf'.
int
The number of pixels that are within the 'threshold' in 'surf' compared to either 'search_color' or search_surf.
See the threshold tests for a full of examples: https://github.com/pygame/pygame/blob/master/test/transform_test.py
New in pygame 1.8.
Changed in pygame 1.9.4: Fixed a lot of bugs and added keyword arguments. Test your code.


Get the information about the mouse system cursor. The return value is the same data as the arguments passed into pygame.mouse.set_cursor().
Note
This method is unavailable with pygame 2, as SDL2 does not provide the underlying code to implement this method.


Returns true when pygame is receiving mouse input events (or, in windowing terminology, is "active" or has the "focus").
This method is most useful when working in a window. By contrast, in full-screen mode, this method always returns true.
Note: under MS Windows, the window that has the mouse focus also has the keyboard focus. But under X-Windows, one window can receive mouse events and another receive keyboard events. pygame.mouse.get_focused() indicates whether the pygame window receives mouse events.


Returns the x and y position of the mouse cursor. The position is relative to the top-left corner of the display. The cursor position can be located outside of the display window, but is always constrained to the screen.


Returns a sequence of booleans representing the state of all the mouse buttons. A true value means the mouse is currently being pressed at the time of the call.
Note, to get all of the mouse events it is better to use either pygame.event.wait() or pygame.event.get() and check all of those events to see if they are MOUSEBUTTONDOWN, MOUSEBUTTONUP, or MOUSEMOTION.
Note, that on X11 some X servers use middle button emulation. When you click both buttons 1 and 3 at the same time a 2 button event can be emitted.
Note, remember to call pygame.event.get() before this function. Otherwise it will not work as expected.
To support five button mice, an optional parameter num_buttons has been added in pygame 2. When this is set to 5, button4 and button5 are added to the returned tuple. Only 3 and 5 are valid values for this parameter.
Changed in pygame 2.0.0: num_buttons argument added


Returns the amount of movement in x and y since the previous call to this function. The relative movement of the mouse cursor is constrained to the edges of the screen, but see the virtual input mouse mode for a way around this. Virtual input mode is described at the top of the page.


Get the current visibility state of the mouse cursor. True if the mouse is visible, False otherwise.
New in pygame 2.0.0.


When the mouse cursor is visible, it will be displayed as a black and white bitmap using the given bitmask arrays. The size is a sequence containing the cursor width and height. hotspot is a sequence containing the cursor hotspot position.
A cursor has a width and height, but a mouse position is represented by a set of point coordinates. So the value passed into the cursor hotspot variable helps pygame to actually determine at what exact point the cursor is at.
xormasks is a sequence of bytes containing the cursor xor data masks. Lastly andmasks, a sequence of bytes containing the cursor bitmask data. To create these variables, we can make use of the pygame.cursors.compile() function.
Width and height must be a multiple of 8, and the mask arrays must be the correct size for the given width and height. Otherwise an exception is raised.
See the pygame.cursor module for help creating default and custom masks for the mouse cursor and also for more examples related to cursors.


Set the current mouse position to arguments given. If the mouse cursor is visible it will jump to the new coordinates. Moving the mouse will generate a new pygame.MOUSEMOTION event.


When the mouse cursor is visible, it will displayed as a operating system specific variant of the options below.
New in pygame 2.0.0.


If the bool argument is true, the mouse cursor will be visible. This will return the previous visible state of the cursor.


The Overlay objects provide support for accessing hardware video overlays. Video overlays do not use standard RGB pixel formats, and can use multiple resolutions of data to create a single image.
The Overlay objects represent lower level access to the display hardware. To use the object you must understand the technical details of video overlays.
The Overlay format determines the type of pixel data used. Not all hardware will support all types of overlay formats. Here is a list of available format types:
The width and height arguments control the size for the overlay image data. The overlay image can be displayed at any size, not just the resolution of the overlay.
The overlay objects are always visible, and always show above the regular display contents.
Display the YUV data in SDL's overlay planes. The y, u, and v arguments are strings of binary data. The data must be in the correct format used to create the Overlay.
If no argument is passed in, the Overlay will simply be redrawn with the current data. This can be useful when the Overlay is not really hardware accelerated.
The strings are not validated, and improperly sized strings could crash the program.
Set the location for the overlay. The overlay will always be shown relative to the main display Surface. This does not actually redraw the overlay, it will be updated on the next call to Overlay.display().
Returns a True value when the Overlay is hardware accelerated. If the platform does not support acceleration, software rendering is used.


Display the YUV data in SDL's overlay planes. The y, u, and v arguments are strings of binary data. The data must be in the correct format used to create the Overlay.
If no argument is passed in, the Overlay will simply be redrawn with the current data. This can be useful when the Overlay is not really hardware accelerated.
The strings are not validated, and improperly sized strings could crash the program.


Returns a True value when the Overlay is hardware accelerated. If the platform does not support acceleration, software rendering is used.


Set the location for the overlay. The overlay will always be shown relative to the main display Surface. This does not actually redraw the overlay, it will be updated on the next call to Overlay.display().


The PixelArray wraps a Surface and provides direct access to the surface's pixels. A pixel array can be one or two dimensional. A two dimensional array, like its surface, is indexed [column, row]. Pixel arrays support slicing, both for returning a subarray or for assignment. A pixel array sliced on a single column or row returns a one dimensional pixel array. Arithmetic and other operations are not supported. A pixel array can be safely assigned to itself. Finally, pixel arrays export an array struct interface, allowing them to interact with pygame.pixelcopy methods and NumPy arrays.
A PixelArray pixel item can be assigned a raw integer values, a pygame.Color instance, or a (r, g, b[, a]) tuple.
However, only a pixel's integer value is returned. So, to compare a pixel to a particular color the color needs to be first mapped using the Surface.map_rgb() method of the Surface object for which the PixelArray was created.
When assigning to a range of of pixels, a non tuple sequence of colors or a PixelArray can be used as the value. For a sequence, the length must match the PixelArray width.
For PixelArray assignment, if the right hand side array has a row length of 1, then the column is broadcast over the target array's rows. An array of height 1 is broadcast over the target's columns, and is equivalent to assigning a 1D PixelArray.
Subscript slices can also be used to assign to a rectangular subview of the target PixelArray.
Subscript slices can also be used to do fast rectangular pixel manipulations instead of iterating over the x or y axis. The
During its lifetime, the PixelArray locks the surface, thus you explicitly have to close() it once its not used any more and the surface should perform operations in the same scope. It is best to use it as a context manager using the with PixelArray(surf) as pixel_array: style. So it works on pypy too.
A simple : slice index for the column can be omitted.
A note about PixelArray to PixelArray assignment, for arrays with an item size of 3 (created from 24 bit surfaces) pixel values are translated from the source to the destinations format. The red, green, and blue color elements of each pixel are shifted to match the format of the target surface. For all other pixel sizes no such remapping occurs. This should change in later pygame releases, where format conversions are performed for all pixel sizes. To avoid code breakage when full mapped copying is implemented it is suggested PixelArray to PixelArray copies be only between surfaces of identical format.
close() method was added. For explicitly cleaning up.
being able to use PixelArray as a context manager for cleanup.
both of these are useful for when working without reference counting (pypy).
array struct interface
transpose method
broadcasting for a length 1 dimension
A 2D PixelArray can have a length 1 dimension. Only an integer index on a 2D PixelArray returns a 1D array.
For assignment, a tuple can only be a color. Any other sequence type is a sequence of colors.
The Surface the PixelArray was created for.
This is the same as Surface.get_bytesize() for the pixel array's surface.
New in pygame 1.9.2.
A pixel array can be 1 or 2 dimensional.
New in pygame 1.9.2.
A tuple or length ndim giving the length of each dimension. Analogous to Surface.get_size().
New in pygame 1.9.2.
A tuple or length ndim byte counts. When a stride is multiplied by the corresponding index it gives the offset of that index from the start of the array. A stride is negative for an array that has is inverted (has a negative step).
New in pygame 1.9.2.
Creates a new Surface from the current PixelArray. Depending on the current PixelArray the size, pixel order etc. will be different from the original Surface.
New in pygame 1.8.1.
Replaces the pixels with the passed color in the PixelArray by changing them them to the passed replacement color.
It uses a simple weighted Euclidean distance formula to calculate the distance between the colors. The distance space ranges from 0.0 to 1.0 and is used as threshold for the color detection. This causes the replacement to take pixels with a similar, but not exactly identical color, into account as well.
This is an in place operation that directly affects the pixels of the PixelArray.
New in pygame 1.8.1.
Extracts the passed color by changing all matching pixels to white, while non-matching pixels are changed to black. This returns a new PixelArray with the black/white color mask.
It uses a simple weighted Euclidean distance formula to calculate the distance between the colors. The distance space ranges from 0.0 to 1.0 and is used as threshold for the color detection. This causes the extraction to take pixels with a similar, but not exactly identical color, into account as well.
New in pygame 1.8.1.
Compares the contents of the PixelArray with those from the passed in PixelArray. It returns a new PixelArray with a black/white color mask that indicates the differences (black) of both arrays. Both PixelArray objects must have identical bit depths and dimensions.
It uses a simple weighted Euclidean distance formula to calculate the distance between the colors. The distance space ranges from 0.0 to 1.0 and is used as a threshold for the color detection. This causes the comparison to mark pixels with a similar, but not exactly identical color, as white.
New in pygame 1.8.1.
This method returns a new view of the pixel array with the rows and columns swapped. So for a (w, h) sized array a (h, w) slice is returned. If an array is one dimensional, then a length 1 x dimension is added, resulting in a 2D pixel array.
New in pygame 1.9.2.
This method is for explicitly closing the PixelArray, and releasing a lock on the Suface.
New in pygame 1.9.4.


This method is for explicitly closing the PixelArray, and releasing a lock on the Suface.
New in pygame 1.9.4.


Compares the contents of the PixelArray with those from the passed in PixelArray. It returns a new PixelArray with a black/white color mask that indicates the differences (black) of both arrays. Both PixelArray objects must have identical bit depths and dimensions.
It uses a simple weighted Euclidean distance formula to calculate the distance between the colors. The distance space ranges from 0.0 to 1.0 and is used as a threshold for the color detection. This causes the comparison to mark pixels with a similar, but not exactly identical color, as white.
New in pygame 1.8.1.


Extracts the passed color by changing all matching pixels to white, while non-matching pixels are changed to black. This returns a new PixelArray with the black/white color mask.
It uses a simple weighted Euclidean distance formula to calculate the distance between the colors. The distance space ranges from 0.0 to 1.0 and is used as threshold for the color detection. This causes the extraction to take pixels with a similar, but not exactly identical color, into account as well.
New in pygame 1.8.1.


This is the same as Surface.get_bytesize() for the pixel array's surface.
New in pygame 1.9.2.


Creates a new Surface from the current PixelArray. Depending on the current PixelArray the size, pixel order etc. will be different from the original Surface.
New in pygame 1.8.1.


A pixel array can be 1 or 2 dimensional.
New in pygame 1.9.2.


Replaces the pixels with the passed color in the PixelArray by changing them them to the passed replacement color.
It uses a simple weighted Euclidean distance formula to calculate the distance between the colors. The distance space ranges from 0.0 to 1.0 and is used as threshold for the color detection. This causes the replacement to take pixels with a similar, but not exactly identical color, into account as well.
This is an in place operation that directly affects the pixels of the PixelArray.
New in pygame 1.8.1.


A tuple or length ndim giving the length of each dimension. Analogous to Surface.get_size().
New in pygame 1.9.2.


A tuple or length ndim byte counts. When a stride is multiplied by the corresponding index it gives the offset of that index from the start of the array. A stride is negative for an array that has is inverted (has a negative step).
New in pygame 1.9.2.


The Surface the PixelArray was created for.


This method returns a new view of the pixel array with the rows and columns swapped. So for a (w, h) sized array a (h, w) slice is returned. If an array is one dimensional, then a length 1 x dimension is added, resulting in a 2D pixel array.
New in pygame 1.9.2.


Create a new Surface that best resembles the data and format of the array. The array can be 2D or 3D with any sized integer values.


Map an array of color element values - (w, h, ..., 3) - to an array of pixels - (w, h) according to the format of <surface>.


The surface_to_array function copies pixels from a Surface object to a 2D or 3D array. Depending on argument kind and the target array dimension, a copy may be raw pixel value, RGB, a color component slice, or colorkey alpha transparency value. Recognized kind values are the single character codes 'P', 'R', 'G', 'B', 'A', and 'C'. Kind codes are case insensitive, so 'p' is equivalent to 'P'. The first two dimensions of the target must be the surface size (w, h).
The default 'P' kind code does a direct raw integer pixel (mapped) value copy to a 2D array and a 'RGB' pixel component (unmapped) copy to a 3D array having shape (w, h, 3). For an 8 bit colormap surface this means the table index is copied to a 2D array, not the table value itself. A 2D array's item size must be at least as large as the surface's pixel byte size. The item size of a 3D array must be at least one byte.
For the 'R', 'G', 'B', and 'A' copy kinds a single color component of the unmapped surface pixels are copied to the target 2D array. For kind 'A' and surfaces with source alpha (the surface was created with the SRCALPHA flag), has a colorkey (set with Surface.set_colorkey()), or has a blanket alpha (set with Surface.set_alpha()) then the alpha values are those expected for a SDL surface. If a surface has no explicit alpha value, then the target array is filled with the value of the optional opaque surface_to_array argument (default 255: not transparent).
Copy kind 'C' is a special case for alpha copy of a source surface with colorkey. Unlike the 'A' color component copy, the clear argument value is used for colorkey matches, opaque otherwise. By default, a match has alpha 0 (totally transparent), while everything else is alpha 255 (totally opaque). It is a more general implementation of pygame.surfarray.array_colorkey().
Specific to surface_to_array, a ValueError is raised for target arrays with incorrect shape or item size. A TypeError is raised for an incorrect kind code. Surface specific problems, such as locking, raise a pygame.error.


Uninitialize all pygame modules that have previously been initialized. When the Python interpreter shuts down, this method is called regardless, so your program should not need it, except when it wants to terminate its pygame resources and continue. It is safe to call this function more than once as repeated calls have no effect.
Note
Calling pygame.quit() will not exit your program. Consider letting your program end in the same way a normal Python program will end.


Pygame uses Rect objects to store and manipulate rectangular areas. A Rect can be created from a combination of left, top, width, and height values. Rects can also be created from python objects that are already a Rect or have an attribute named "rect".
Any pygame function that requires a Rect argument also accepts any of these values to construct a Rect. This makes it easier to create Rects on the fly as arguments to functions.
The Rect functions that change the position or size of a Rect return a new copy of the Rect with the affected changes. The original Rect is not modified. Some methods have an alternate "in-place" version that returns None but affects the original Rect. These "in-place" methods are denoted with the "ip" suffix.
The Rect object has several virtual attributes which can be used to move and align the Rect:
All of these attributes can be assigned to:
Assigning to size, width or height changes the dimensions of the rectangle; all other assignments move the rectangle without resizing it. Notice that some attributes are integers and others are pairs of integers.
If a Rect has a nonzero width or height, it will return True for a nonzero test. Some methods return a Rect with 0 size to represent an invalid rectangle. A Rect with a 0 size will not collide when using collision detection methods (e.g. collidepoint(), colliderect(), etc.).
The coordinates for Rect objects are all integers. The size values can be programmed to have negative values, but these are considered illegal Rects for most operations.
There are several collision tests between other rectangles. Most python containers can be searched for collisions against a single Rect.
The area covered by a Rect does not include the right- and bottom-most edge of pixels. If one Rect's bottom border is another Rect's top border (i.e., rect1.bottom=rect2.top), the two meet exactly on the screen but do not overlap, and rect1.colliderect(rect2) returns false.
New in pygame 1.9.2: The Rect class can be subclassed. Methods such as copy() and move() will recognize this and return instances of the subclass. However, the subclass's __init__() method is not called, and __new__() is assumed to take no arguments. So these methods should be overridden if any extra attributes need to be copied.
Returns a new rectangle having the same position and size as the original.
New in pygame 1.9
Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative.
Same as the Rect.move() method, but operates in place.
Returns a new rectangle with the size changed by the given offset. The rectangle remains centered around its current center. Negative values will shrink the rectangle. Note, uses integers, if the offset given is too small(< 2 > -2), center will be off.
Same as the Rect.inflate() method, but operates in place.
Sets the position and size of the rectangle, in place. See parameters for pygame.Rect() for the parameters of this function.
New in pygame 2.0.1.
Returns a new rectangle that is moved to be completely inside the argument Rect. If the rectangle is too large to fit inside, it is centered inside the argument Rect, but its size is not changed.
Same as the Rect.clamp() method, but operates in place.
Returns a new rectangle that is cropped to be completely inside the argument Rect. If the two rectangles do not overlap to begin with, a Rect with 0 size is returned.
Returns the coordinates of a line that is cropped to be completely inside the rectangle. If the line does not overlap the rectangle, then an empty tuple is returned.
The line to crop can be any of the following formats (floats can be used in place of ints, but they will be truncated):
Note
This method can be used for collision detection between a rect and a line. See example code below.
Note
The rect.bottom and rect.right attributes of a pygame.Rect always lie one pixel outside of its actual border.
New in pygame 2.0.0.
Returns a new rectangle that completely covers the area of the two provided rectangles. There may be area inside the new Rect that is not covered by the originals.
Same as the Rect.union() method, but operates in place.
Returns the union of one rectangle with a sequence of many rectangles.
The same as the Rect.unionall() method, but operates in place.
Returns a new rectangle that is moved and resized to fit another. The aspect ratio of the original Rect is preserved, so the new rectangle may be smaller than the target in either width or height.
This will flip the width or height of a rectangle if it has a negative size. The rectangle will remain in the same place, with only the sides swapped.
Returns true when the argument is completely inside the Rect.
Returns true if the given point is inside the rectangle. A point along the right or bottom edge is not considered to be inside the rectangle.
Note
For collision detection between a rect and a line the clipline() method can be used.
Returns true if any portion of either rectangle overlap (except the top+bottom or left+right edges).
Note
For collision detection between a rect and a line the clipline() method can be used.
Test whether the rectangle collides with any in a sequence of rectangles. The index of the first collision found is returned. If no collisions are found an index of -1 is returned.
Returns a list of all the indices that contain rectangles that collide with the Rect. If no intersecting rectangles are found, an empty list is returned.
Returns the first key and value pair that intersects with the calling Rect object. If no collisions are found, None is returned. If use_values is 0 (default) then the dict's keys will be used in the collision detection, otherwise the dict's values will be used.
Note
Rect objects cannot be used as keys in a dictionary (they are not hashable), so they must be converted to a tuple/list. e.g. rect.collidedict({tuple(key_rect) : value})
Returns a list of all the key and value pairs that intersect with the calling Rect object. If no collisions are found an empty list is returned. If use_values is 0 (default) then the dict's keys will be used in the collision detection, otherwise the dict's values will be used.
Note
Rect objects cannot be used as keys in a dictionary (they are not hashable), so they must be converted to a tuple/list. e.g. rect.collidedictall({tuple(key_rect) : value})


Returns a new rectangle that is moved to be completely inside the argument Rect. If the rectangle is too large to fit inside, it is centered inside the argument Rect, but its size is not changed.


Same as the Rect.clamp() method, but operates in place.


Returns a new rectangle that is cropped to be completely inside the argument Rect. If the two rectangles do not overlap to begin with, a Rect with 0 size is returned.


Returns the coordinates of a line that is cropped to be completely inside the rectangle. If the line does not overlap the rectangle, then an empty tuple is returned.
The line to crop can be any of the following formats (floats can be used in place of ints, but they will be truncated):
Note
This method can be used for collision detection between a rect and a line. See example code below.
Note
The rect.bottom and rect.right attributes of a pygame.Rect always lie one pixel outside of its actual border.
New in pygame 2.0.0.


Returns the first key and value pair that intersects with the calling Rect object. If no collisions are found, None is returned. If use_values is 0 (default) then the dict's keys will be used in the collision detection, otherwise the dict's values will be used.
Note
Rect objects cannot be used as keys in a dictionary (they are not hashable), so they must be converted to a tuple/list. e.g. rect.collidedict({tuple(key_rect) : value})


Returns a list of all the key and value pairs that intersect with the calling Rect object. If no collisions are found an empty list is returned. If use_values is 0 (default) then the dict's keys will be used in the collision detection, otherwise the dict's values will be used.
Note
Rect objects cannot be used as keys in a dictionary (they are not hashable), so they must be converted to a tuple/list. e.g. rect.collidedictall({tuple(key_rect) : value})


Test whether the rectangle collides with any in a sequence of rectangles. The index of the first collision found is returned. If no collisions are found an index of -1 is returned.


Returns a list of all the indices that contain rectangles that collide with the Rect. If no intersecting rectangles are found, an empty list is returned.


Returns true if the given point is inside the rectangle. A point along the right or bottom edge is not considered to be inside the rectangle.
Note
For collision detection between a rect and a line the clipline() method can be used.


Returns true if any portion of either rectangle overlap (except the top+bottom or left+right edges).
Note
For collision detection between a rect and a line the clipline() method can be used.


Returns true when the argument is completely inside the Rect.


Returns a new rectangle having the same position and size as the original.
New in pygame 1.9


Returns a new rectangle that is moved and resized to fit another. The aspect ratio of the original Rect is preserved, so the new rectangle may be smaller than the target in either width or height.


Returns a new rectangle with the size changed by the given offset. The rectangle remains centered around its current center. Negative values will shrink the rectangle. Note, uses integers, if the offset given is too small(< 2 > -2), center will be off.


Same as the Rect.inflate() method, but operates in place.


Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative.


Same as the Rect.move() method, but operates in place.


This will flip the width or height of a rectangle if it has a negative size. The rectangle will remain in the same place, with only the sides swapped.


Returns a new rectangle that completely covers the area of the two provided rectangles. There may be area inside the new Rect that is not covered by the originals.


Same as the Rect.union() method, but operates in place.


Returns the union of one rectangle with a sequence of many rectangles.


The same as the Rect.unionall() method, but operates in place.


Sets the position and size of the rectangle, in place. See parameters for pygame.Rect() for the parameters of this function.
New in pygame 2.0.1.


When pygame.quit() is called, all registered quit functions are called. Pygame modules do this automatically when they are initializing, so this function will rarely be needed.


Checks whether data for the given type is currently available in the clipboard.


Retrieves the data for the specified type from the clipboard. In python 3 the data is returned as a byte string and might need further processing (such as decoding to Unicode).


Gets the scrap module's initialization state.
New in pygame 1.9.5.


Gets a list of data type string identifiers for the data currently available on the clipboard. Each identifier can be used in the pygame.scrap.get() method to get the clipboard content of the specific type.


Initialize the scrap module.
Note
The scrap module requires pygame.display.set_mode() be called before being initialized.


Indicates if the clipboard ownership has been lost by the pygame application.


Places data for a given clipboard type into the clipboard. The data must be a string buffer. The type is a string identifying the type of data to be placed into the clipboard. This can be one of the predefined pygame.SCRAP_PBM, pygame.SCRAP_PPM, pygame.SCRAP_BMP or pygame.SCRAP_TEXT values or a user defined string identifier.
pygame.error -- if unable to put the data into the clipboard


Sets the access mode for the clipboard. This is only of interest for X11 environments where clipboard modes pygame.SCRAP_SELECTION (for mouse selections) and pygame.SCRAP_CLIPBOARD (for the clipboard) are available. Setting the mode to pygame.SCRAP_SELECTION in other environments will not change the mode from pygame.SCRAP_CLIPBOARD.


SDL maintains an internal error message. This message will usually be given to you when pygame.error() is raised, so this function will rarely be needed.


Creates a new array for the sound data and copies the samples. The array will always be in the format returned from pygame.mixer.get_init().


DEPRECATED: Returns the currently active array type. This will be a value of the get_arraytypes() tuple and indicates which type of array module is used for the array creation.
New in pygame 1.8.


DEPRECATED: Checks, which array systems are available and returns them as a tuple of strings. The values of the tuple can be used directly in the pygame.sndarray.use_arraytype() () method. If no supported array system could be found, None will be returned.
New in pygame 1.8.


Create a new playable Sound object from an array. The mixer module must be initialized and the array format must be similar to the mixer audio format.


Creates a new array that directly references the samples in a Sound object. Modifying the array will change the Sound. The array will always be in the format returned from pygame.mixer.get_init().


DEPRECATED: Uses the requested array type for the module functions. The only supported arraytype is 'numpy'. Other values will raise ValueError.


Tests for collision between two sprites, by testing to see if two circles centered on the sprites overlap. If the sprites have a "radius" attribute, that is used to create the circle, otherwise a circle is created that is big enough to completely enclose the sprites rect as given by the "rect" attribute. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute.
New in pygame 1.8.1.


A callable class that checks for collisions between two sprites, using a scaled version of the sprites radius.
Is created with a floating point ratio, the instance is then intended to be passed as a collided callback function to the *collide functions.
A ratio is a floating point number - 1.0 is the same size, 2.0 is twice as big, and 0.5 is half the size.
The created callable tests for collision between two sprites, by testing to see if two circles centered on the sprites overlap, after scaling the circles radius by the stored ratio. If the sprites have a "radius" attribute, that is used to create the circle, otherwise a circle is created that is big enough to completely enclose the sprites rect as given by the "rect" attribute. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute.
New in pygame 1.8.1.


Tests for collision between two sprites, by testing if their bitmasks overlap (uses pygame.mask.Mask.overlap()). If the sprites have a mask attribute, it is used as the mask, otherwise a mask is created from the sprite's image (uses pygame.mask.from_surface()). Sprites must have a rect attribute; the mask attribute is optional.
The first point of collision between the masks is returned. The collision point is offset from sprite1's mask's topleft corner (which is always (0, 0)). The collision point is a position within the mask and is not related to the actual screen position of sprite1.
This function is intended to be passed as a collided callback function to the group collide functions (see spritecollide(), groupcollide(), spritecollideany()).
Note
To increase performance, create and set a mask attibute for all sprites that will use this function to check for collisions. Otherwise, each time this function is called it will create new masks.
Note
A new mask needs to be recreated each time a sprite's image is changed (e.g. if a new image is used or the existing image is rotated).
New in pygame 1.8.0.


Tests for collision between two sprites. Uses the pygame rect colliderect function to calculate the collision. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" attributes.
New in pygame 1.8.


A callable class that checks for collisions between two sprites, using a scaled version of the sprites rects.
Is created with a ratio, the instance is then intended to be passed as a collided callback function to the *collide functions.
A ratio is a floating point number - 1.0 is the same size, 2.0 is twice as big, and 0.5 is half the size.
New in pygame 1.8.1.


Extra DirtySprite attributes with their default values:
dirty = 1
blendmode = 0
source_rect = None
visible = 1
layer = 0


A simple container for Sprite objects. This class can be inherited to create containers with more specific behaviors. The constructor takes any number of Sprite arguments to add to the Group. The group supports the following standard Python operations:
The Sprites in the Group are not ordered, so drawing and iterating the Sprites is in no particular order.
Return a list of all the Sprites this group contains. You can also get an iterator from the group, but you cannot iterate over a Group while modifying it.
Creates a new Group with all the same Sprites as the original. If you have subclassed Group, the new object will have the same (sub-)class as the original. This only works if the derived class's constructor takes the same arguments as the Group class's.
Add any number of Sprites to this Group. This will only add Sprites that are not already members of the Group.
Each sprite argument can also be a iterator containing Sprites.
Remove any number of Sprites from the Group. This will only remove Sprites that are already members of the Group.
Each sprite argument can also be a iterator containing Sprites.
Return True if the Group contains all of the given sprites. This is similar to using the "in" operator on the Group ("if sprite in group: ..."), which tests if a single Sprite belongs to a Group.
Each sprite argument can also be a iterator containing Sprites.
Calls the update() method on all Sprites in the Group. The base Sprite class has an update method that takes any number of arguments and does nothing. The arguments passed to Group.update() will be passed to each Sprite.
There is no way to get the return value from the Sprite.update() methods.
Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.
The Group does not keep sprites in any order, so the draw order is arbitrary.
Erases the Sprites used in the last Group.draw() call. The destination Surface is cleared by filling the drawn Sprite positions with the background.
The background is usually a Surface image the same dimensions as the destination Surface. However, it can also be a callback function that takes two arguments; the destination Surface and an area to clear. The background callback function will be called several times each clear.
Here is an example callback that will clear the Sprites with solid red:
Removes all Sprites from this Group.


Add any number of Sprites to this Group. This will only add Sprites that are not already members of the Group.
Each sprite argument can also be a iterator containing Sprites.


Erases the Sprites used in the last Group.draw() call. The destination Surface is cleared by filling the drawn Sprite positions with the background.
The background is usually a Surface image the same dimensions as the destination Surface. However, it can also be a callback function that takes two arguments; the destination Surface and an area to clear. The background callback function will be called several times each clear.
Here is an example callback that will clear the Sprites with solid red:


Creates a new Group with all the same Sprites as the original. If you have subclassed Group, the new object will have the same (sub-)class as the original. This only works if the derived class's constructor takes the same arguments as the Group class's.


Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.
The Group does not keep sprites in any order, so the draw order is arbitrary.


Return True if the Group contains all of the given sprites. This is similar to using the "in" operator on the Group ("if sprite in group: ..."), which tests if a single Sprite belongs to a Group.
Each sprite argument can also be a iterator containing Sprites.


Remove any number of Sprites from the Group. This will only remove Sprites that are already members of the Group.
Each sprite argument can also be a iterator containing Sprites.


Return a list of all the Sprites this group contains. You can also get an iterator from the group, but you cannot iterate over a Group while modifying it.


Calls the update() method on all Sprites in the Group. The base Sprite class has an update method that takes any number of arguments and does nothing. The arguments passed to Group.update() will be passed to each Sprite.
There is no way to get the return value from the Sprite.update() methods.