pygame.sprite- pygame module with basic game object classes
— Simple base class for visible game objects. — A subclass of Sprite that references its Groups weakly. This means that any group this belongs to that is not referenced anywhere else is garbage collected automatically. — A subclass of Sprite with more attributes and features. — A container class to hold and manage multiple Sprite objects. — A subclass of WeakSprite and DirtySprite that combines the benefits of both classes. — Same as pygame.sprite.Group — Same as pygame.sprite.Group — Group sub-class that tracks dirty updates. — RenderUpdates sub-class that draws Sprites in order of addition. — LayeredUpdates is a sprite group that handles layers and draws like OrderedUpdates. — LayeredDirty group is for DirtySprite objects. Subclasses LayeredUpdates. — Group container that holds a single sprite. — Find sprites in a group that intersect another sprite. — Collision detection between two sprites, using rects. — Collision detection between two sprites, using rects scaled to a ratio. — Collision detection between two sprites, using circles. — Collision detection between two sprites, using circles scaled to a ratio. — Collision detection between two sprites, using masks. — Find all sprites that collide between two groups. — Simple test if a sprite intersects anything in a group. This module contains several simple classes to be used within games. There isthe main Sprite class and several Group classes that contain Sprites. The useof these classes is entirely optional when using pygame. The classes are fairlylightweight and only provide a starting place for the code that is common tomost games.
The Sprite class is intended to be used as a base class for the different typesof objects in the game. There is also a base Group class that simply storessprites. A game could create new types of Group classes that operate onspecially customized Sprite instances they contain.
The basic Group class can draw the Sprites it contains to a Surface. The
Group.draw()method requires that each Sprite have aSurface.imageattribute and aSurface.rect. TheGroup.clear()method requires thesesame attributes, and can be used to erase all the Sprites with background.There are also more advanced Groups:pygame.sprite.RenderUpdates()andpygame.sprite.OrderedUpdates().Lastly, this module contains several collision functions. These help findsprites inside multiple groups that have intersecting bounding rectangles. Tofind the collisions, the Sprites are required to have a
Surface.rectattribute assigned.The groups are designed for high efficiency in removing and adding Sprites tothem. They also allow cheap testing to see if a Sprite already exists in aGroup. A given Sprite can exist in any number of groups. A game could use somegroups to control object rendering, and a completely separate set of groups tocontrol interaction or player movement. Instead of adding type attributes orbools to a derived Sprite class, consider keeping the Sprites inside organizedGroups. This will allow for easier lookup later in the game.
Sprites and Groups manage their relationships with the
add()andremove()methods. These methods can accept a single or multiple targets formembership. The default initializers for these classes also takes a single orlist of targets for initial membership. It is safe to repeatedly add and removethe same Sprite from a Group.While it is possible to design sprite and group classes that don't derive fromthe Sprite and AbstractGroup classes below, it is strongly recommended that youextend those when you add a Sprite or Group class.
Sprites are not thread safe. So lock them yourself if using threads.
- pygame.sprite.Sprite¶
- Simple base class for visible game objects.Sprite(*groups) -> Sprite
— method to control sprite behavior — add the sprite to groups — remove the sprite from groups — remove the Sprite from all Groups — does the sprite belong to any groups — list of Groups that contain this Sprite The base class for visible game objects. Derived classes will want tooverride the
Sprite.update()and assign aSprite.imageandSprite.rectattributes. The initializer can accept any number of Groupinstances to be added to.When subclassing the Sprite, be sure to call the base initializer beforeadding the Sprite to Groups. For example:
classBlock(pygame.sprite.Sprite):# Constructor. Pass in the color of the block,# and its x and y positiondef__init__(self,color,width,height):# Call the parent class (Sprite) constructorpygame.sprite.Sprite.__init__(self)# Create an image of the block, and fill it with a color.# This could also be an image loaded from the disk.self.image=pygame.Surface([width,height])self.image.fill(color)# Fetch the rectangle object that has the dimensions of the image# Update the position of this object by setting the values of rect.x and rect.yself.rect=self.image.get_rect()
- update()¶
- method to control sprite behaviorupdate(*args, **kwargs) -> None
The default implementation of this method does nothing; it's just aconvenient "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 methodby the same name in the Group class.
- add()¶
- add the sprite to groupsadd(*groups) -> None
Any number of Group instances can be passed as arguments. The Sprite willbe added to the Groups it is not already a member of.
- remove()¶
- remove the sprite from groupsremove(*groups) -> None
Any number of Group instances can be passed as arguments. The Sprite willbe removed from the Groups it is currently a member of.
- kill()¶
- remove the Sprite from all Groupskill() -> None
The Sprite is removed from all the Groups that contain it. This won'tchange anything about the state of the Sprite. It is possible to continueto use the Sprite after this method has been called, including adding itto Groups.
- alive()¶
- does the sprite belong to any groupsalive() -> bool
Returns True when the Sprite belongs to one or more Groups.
- groups()¶
- list of Groups that contain this Spritegroups() -> group_list
Return a list of all the Groups that contain this Sprite.
- pygame.sprite.WeakSprite¶
- A subclass of Sprite that references its Groups weakly. This means that any group this belongs to that is not referenced anywhere else is garbage collected automatically.WeakSprite(*groups) -> WeakSprite
- pygame.sprite.DirtySprite¶
- A subclass of Sprite with more attributes and features.DirtySprite(*groups) -> DirtySprite
Extra DirtySprite attributes with their default values:
dirty = 1
ifsetto1,itisrepaintedandthensetto0againifsetto2thenitisalwaysdirty(repaintedeachframe,flagisnotreset)0meansthatitisnotdirtyandthereforenotrepaintedagain
blendmode = 0
itsthespecial_flagsargumentofblit,blendmodes
source_rect = None
sourcerecttouse,rememberthatitisrelativetotopleft(0,0)ofself.image
visible = 1
normally1,ifsetto0itwillnotberepainted(youmustsetitdirtytootobeerasedfromscreen)
layer = 0
(READONLYvalue,itisreadwhenaddingittotheLayeredDirty,fordetailsseedocofLayeredDirty)
- pygame.sprite.Group¶
- A container class to hold and manage multiple Sprite objects.Group(*sprites) -> Group
— list of the Sprites this Group contains — duplicate the Group — add Sprites to this Group — remove Sprites from the Group — test if a Group contains Sprites — call the update method on contained Sprites — blit the Sprite images — draw a background over the Sprites — remove all Sprites A simple container for Sprite objects. This class can be inherited to createcontainers with more specific behaviors. The constructor takes any number ofSprite arguments to add to the Group. The group supports the followingstandard Python operations:
intestifaSpriteiscontainedlenthenumberofSpritescontainedbooltestifanySpritesarecontainediteriteratethroughalltheSprites
The Sprites in the Group are ordered only on python 3.6 and higher.Below python 3.6 drawing and iterating over the Sprites is in no particular order.
- sprites()¶
- list of the Sprites this Group containssprites() -> sprite_list
Return a list of all the Sprites this group contains. You can also get aniterator from the group, but you cannot iterate over a Group whilemodifying it.
- copy()¶
- duplicate the Groupcopy() -> Group
Creates a new Group with all the same Sprites as the original. If youhave subclassed Group, the new object will have the same (sub-)class asthe original. This only works if the derived class's constructor takesthe same arguments as the Group class's.
- add()¶
- add Sprites to this Groupadd(*sprites) -> None
Add any number of Sprites to this Group. This will only add Sprites thatare not already members of the Group.
Each sprite argument can also be a iterator containing Sprites.
- remove()¶
- remove Sprites from the Groupremove(*sprites) -> None
Remove any number of Sprites from the Group. This will only removeSprites that are already members of the Group.
Each sprite argument can also be a iterator containing Sprites.
- has()¶
- test if a Group contains Spriteshas(*sprites) -> bool
Return True if the Group contains all of the given sprites. This issimilar 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.
- update()¶
- call the update method on contained Spritesupdate(*args, **kwargs) -> None
Calls the
update()method on all Sprites in the Group. The baseSprite class has an update method that takes any number of arguments anddoes nothing. The arguments passed toGroup.update()will be passedto each Sprite.There is no way to get the return value from the
Sprite.update()methods.
- draw()¶
- blit the Sprite imagesdraw(Surface, bgsurf=None, special_flags=0) -> List[Rect]
Draws the contained Sprites to the Surface argument. This uses the
Sprite.imageattribute for the source surface, andSprite.rectfor the position.special_flagsis passed toSurface.blit().bgsurfis unused in this method butLayeredDirty.draw()usesit.The Group does not keep sprites in any order, so the draw order isarbitrary.
- clear()¶
- draw a background over the Spritesclear(Surface_dest, background) -> None
Erases the Sprites used in the last
Group.draw()call. Thedestination Surface is cleared by filling the drawn Sprite positions withthe background.The background is usually a Surface image the same dimensions as thedestination Surface. However, it can also be a callback function thattakes two arguments; the destination Surface and an area to clear. Thebackground callback function will be called several times each clear.
Here is an example callback that will clear the Sprites with solid red:
defclear_callback(surf,rect):color=255,0,0surf.fill(color,rect)
- empty()¶
- remove all Spritesempty() -> None
Removes all Sprites from this Group.
- pygame.sprite.WeakDirtySprite¶
- A subclass of WeakSprite and DirtySprite that combines the benefits of both classes.WeakDirtySprite(*groups) -> WeakDirtySprite
- pygame.sprite.RenderPlain¶
- Same as pygame.sprite.Group
This class is an alias to
pygame.sprite.Group(). It has no additional functionality.
- pygame.sprite.RenderClear¶
- Same as pygame.sprite.Group
This class is an alias to
pygame.sprite.Group(). It has no additional functionality.
- pygame.sprite.RenderUpdates¶
- Group sub-class that tracks dirty updates.RenderUpdates(*sprites) -> RenderUpdates
— blit the Sprite images and track changed areas This class is derived from
pygame.sprite.Group(). It has an extendeddraw()method that tracks the changed areas of the screen.- draw()¶
- blit the Sprite images and track changed areasdraw(surface, bgsurf=None, special_flags=0) -> Rect_list
Draws all the Sprites to the surface, the same as
Group.draw(). Thismethod also returns a list of Rectangular areas on the screen that havebeen changed. The returned changes include areas of the screen that havebeen affected by previousGroup.clear()calls.special_flagsispassed toSurface.blit().The returned Rect list should be passed to
pygame.display.update().This will help performance on software driven display modes. This type ofupdating is usually only helpful on destinations with non-animatingbackgrounds.
- pygame.sprite.OrderedUpdates()¶
- RenderUpdates sub-class that draws Sprites in order of addition.OrderedUpdates(*sprites) -> OrderedUpdates
This class derives from
pygame.sprite.RenderUpdates(). It maintains theorder in which the Sprites were added to the Group for rendering. This makesadding and removing Sprites from the Group a little slower than regularGroups.
- pygame.sprite.LayeredUpdates¶
- LayeredUpdates is a sprite group that handles layers and draws like OrderedUpdates.LayeredUpdates(*sprites, **kwargs) -> LayeredUpdates
— add a sprite or sequence of sprites to a group — returns a ordered list of sprites (first back, last top). — draw all sprites in the right order onto the passed surface. — returns a list with all sprites at that position. — returns the sprite at the index idx from the groups sprites — removes all sprites from a layer and returns them as a list. — returns a list of layers defined (unique), sorted from bottom up. — changes the layer of the sprite — returns the layer that sprite is currently in. — returns the top layer — returns the bottom layer — brings the sprite to front layer — moves the sprite to the bottom layer — returns the topmost sprite — returns all sprites from a layer, ordered by how they where added — switches the sprites from layer1 to layer2 This group is fully compatible with
pygame.sprite.SpriteSimple base class for visible game objects..You can set the default layer through kwargs using 'default_layer' and aninteger 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 tothat layer (overriding the
sprite.layerattribute). If neither spritehas attribute layer nor **kwarg then the default layer is used to add thesprites.New in pygame 1.8.
- add()¶
- add a sprite or sequence of sprites to a groupadd(*sprites, **kwargs) -> None
If the
sprite(s)have an attribute layer then that is used for thelayer. If **kwargs contains 'layer' then thesprite(s)will be addedto that argument (overriding the sprite layer attribute). If neither ispassed then thesprite(s)will be added to the default layer.
- sprites()¶
- returns a ordered list of sprites (first back, last top).sprites() -> sprites
- draw()¶
- draw all sprites in the right order onto the passed surface.draw(surface, bgsurf=None, special_flags=0) -> Rect_list
- get_sprites_at()¶
- returns a list with all sprites at that position.get_sprites_at(pos) -> colliding_sprites
Bottom sprites first, top last.
- get_sprite()¶
- returns the sprite at the index idx from the groups spritesget_sprite(idx) -> sprite
Raises IndexOutOfBounds if the idx is not within range.
- remove_sprites_of_layer()¶
- removes all sprites from a layer and returns them as a list.remove_sprites_of_layer(layer_nr) -> sprites
- layers()¶
- returns a list of layers defined (unique), sorted from bottom up.layers() -> layers
- change_layer()¶
- changes the layer of the spritechange_layer(sprite, new_layer) -> None
sprite must have been added to the renderer. It is not checked.
- get_layer_of_sprite()¶
- returns the layer that sprite is currently in.get_layer_of_sprite(sprite) -> layer
If the sprite is not found then it will return the default layer.
- get_top_layer()¶
- returns the top layerget_top_layer() -> layer
- get_bottom_layer()¶
- returns the bottom layerget_bottom_layer() -> layer
- move_to_front()¶
- brings the sprite to front layermove_to_front(sprite) -> None
Brings the sprite to front, changing sprite layer to topmost layer (addedat the end of that layer).
- move_to_back()¶
- moves the sprite to the bottom layermove_to_back(sprite) -> None
Moves the sprite to the bottom layer, moving it behind all other layersand adding one additional layer.
- get_top_sprite()¶
- returns the topmost spriteget_top_sprite() -> Sprite
- get_sprites_from_layer()¶
- returns all sprites from a layer, ordered by how they where addedget_sprites_from_layer(layer) -> sprites
Returns all sprites from a layer, ordered by how they where added. Ituses linear search and the sprites are not removed from layer.
- switch_layer()¶
- switches the sprites from layer1 to layer2switch_layer(layer1_nr, layer2_nr) -> None
The layers number must exist, it is not checked.
- pygame.sprite.LayeredDirty¶
- LayeredDirty group is for DirtySprite objects. Subclasses LayeredUpdates.LayeredDirty(*sprites, **kwargs) -> LayeredDirty
— draw all sprites in the right order onto the passed surface. — used to set background — repaints the given area — clip the area where to draw. Just pass None (default) to reset the clip — clip the area where to draw. Just pass None (default) to reset the clip — changes the layer of the sprite — sets the threshold in milliseconds — sets the threshold in milliseconds This group requires
pygame.sprite.DirtySpriteA subclass of Sprite with more attributes and features. or any sprite thathas the following attributes:image,rect,dirty,visible,blendmode(seedocofDirtySprite).
It uses the dirty flag technique and is therefore faster than the
pygame.sprite.RenderUpdatesGroup sub-class that tracks dirty updates. if you have many static sprites. Italso switches automatically between dirty rect update and full screendrawing, so you do not have to worry what would be faster.Same as for the
pygame.sprite.GroupA container class to hold and manage multiple Sprite objects.. You can specify someadditional attributes through kwargs:_use_update:True/FalsedefaultisFalse_default_layer:defaultlayerwherespriteswithoutalayerareadded._time_threshold:thresholdtimeforswitchingbetweendirtyrectmodeandfullscreenmode,defaultsto1000./80==1000./fps
New in pygame 1.8.
- draw()¶
- draw all sprites in the right order onto the passed surface.draw(surface, bgsurf=None, special_flags=None) -> Rect_list
You can pass the background too. If a background is already set, then thebgsurf argument has no effect. If present, the
special_flagsargument isalways passed toSurface.blit(), overridingDirtySprite.blendmode.Ifspecial_flagsis not present,DirtySprite.blendmodeis passedto theSurface.blit()instead.
- clear()¶
- used to set backgroundclear(surface, bgd) -> None
- repaint_rect()¶
- repaints the given arearepaint_rect(screen_rect) -> None
screen_rect is in screen coordinates.
- set_clip()¶
- clip the area where to draw. Just pass None (default) to reset the clipset_clip(screen_rect=None) -> None
- get_clip()¶
- clip the area where to draw. Just pass None (default) to reset the clipget_clip() -> Rect
- change_layer()¶
- changes the layer of the spritechange_layer(sprite, new_layer) -> None
sprite must have been added to the renderer. It is not checked.
- set_timing_treshold()¶
- sets the threshold in millisecondsset_timing_treshold(time_ms) -> None
DEPRECATED: Use set_timing_threshold() instead.
Deprecated since pygame 2.1.1.
- set_timing_threshold()¶
- sets the threshold in millisecondsset_timing_threshold(time_ms) -> None
Defaults to 1000.0 / 80.0. This means that the screen will be paintedusing the flip method rather than the update method if the updatemethod is taking so long to update the screen that the frame rate fallsbelow 80 frames per second.
New in pygame 2.1.1.
- Raises
TypeError -- if
time_msis not int or float
- pygame.sprite.GroupSingle()¶
- Group container that holds a single sprite.GroupSingle(sprite=None) -> GroupSingle
The GroupSingle container only holds a single Sprite. When a new Sprite isadded, the old one is removed.
There is a special property,
GroupSingle.sprite, that accesses theSprite that this Group contains. It can be None when the Group is empty. Theproperty can also be assigned to add a Sprite into the GroupSinglecontainer.
- pygame.sprite.spritecollide()¶
- Find sprites in a group that intersect another sprite.spritecollide(sprite, group, dokill, collided = None) -> Sprite_list
Return a list containing all Sprites in a Group that intersect with anotherSprite. Intersection is determined by comparing the
Sprite.rectattribute of each Sprite.The dokill argument is a bool. If set to True, all Sprites that collide willbe removed from the Group.
The collided argument is a callback function used to calculate if twosprites are colliding. it should take two sprites as values, and return abool value indicating if they are colliding. If collided is not passed, allsprites must have a "rect" value, which is a rectangle of the sprite area,which will be used to calculate the collision.
collided callables:
collide_rect,collide_rect_ratio,collide_circle,collide_circle_ratio,collide_mask
Example:
# See if the Sprite block has collided with anything in the Group block_list# The True flag will remove the sprite in block_listblocks_hit_list=pygame.sprite.spritecollide(player,block_list,True)# Check the list of colliding sprites, and add one to the score for each oneforblockinblocks_hit_list:score+=1
- pygame.sprite.collide_rect()¶
- Collision detection between two sprites, using rects.collide_rect(left, right) -> bool
Tests for collision between two sprites. Uses the pygame rect colliderectfunction to calculate the collision. Intended to be passed as a collidedcallback function to the *collide functions. Sprites must have a "rect"attributes.
New in pygame 1.8.
- pygame.sprite.collide_rect_ratio()¶
- Collision detection between two sprites, using rects scaled to a ratio.collide_rect_ratio(ratio) -> collided_callable
A callable class that checks for collisions between two sprites, using ascaled version of the sprites rects.
Is created with a ratio, the instance is then intended to be passed as acollided callback function to the *collide functions.
A ratio is a floating point number - 1.0 is the same size, 2.0 is twice asbig, and 0.5 is half the size.
New in pygame 1.8.1.
- pygame.sprite.collide_circle()¶
- Collision detection between two sprites, using circles.collide_circle(left, right) -> bool
Tests for collision between two sprites, by testing to see if two circlescentered 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 bigenough 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.
- pygame.sprite.collide_circle_ratio()¶
- Collision detection between two sprites, using circles scaled to a ratio.collide_circle_ratio(ratio) -> collided_callable
A callable class that checks for collisions between two sprites, using ascaled version of the sprites radius.
Is created with a floating point ratio, the instance is then intended to bepassed 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 asbig, and 0.5 is half the size.
The created callable tests for collision between two sprites, by testing tosee if two circles centered on the sprites overlap, after scaling thecircles radius by the stored ratio. If the sprites have a "radius"attribute, that is used to create the circle, otherwise a circle is createdthat is big enough to completely enclose the sprites rect as given by the"rect" attribute. Intended to be passed as a collided callback function tothe *collide functions. Sprites must have a "rect" and an optional "radius"attribute.
New in pygame 1.8.1.
- pygame.sprite.collide_mask()¶
- Collision detection between two sprites, using masks.collide_mask(sprite1, sprite2) -> (int, int)collide_mask(sprite1, sprite2) -> None
Tests for collision between two sprites, by testing if their bitmasksoverlap (uses
pygame.mask.Mask.overlap()Returns the point of intersection). If the sprites have amaskattribute, it is used as the mask, otherwise a mask is created fromthe sprite'simage(usespygame.mask.from_surface()Creates a Mask from the given surface). Sprites musthave arectattribute; themaskattribute is optional.The first point of collision between the masks is returned. The collisionpoint 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 notrelated to the actual screen position ofsprite1.This function is intended to be passed as a
collidedcallback functionto the group collide functions (seespritecollide(),groupcollide(),spritecollideany()).Note
To increase performance, create and set a
maskattribute for allsprites 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).
# Example of mask creation for a sprite.sprite.mask=pygame.mask.from_surface(sprite.image)
- Returns
first point of collision between the masks or
Noneif nocollision- Return type
tuple(int, int) or NoneType
New in pygame 1.8.0.
- pygame.sprite.groupcollide()¶
- Find all sprites that collide between two groups.groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict
This will find collisions between all the Sprites in two groups.Collision is determined by comparing the
Sprite.rectattribute ofeach Sprite or by using the collided function if it is not None.Every Sprite inside group1 is added to the return dictionary. The value foreach item is the list of Sprites in group2 that intersect.
If either dokill argument is True, the colliding Sprites will be removedfrom their respective Group.
The collided argument is a callback function used to calculate if two sprites arecolliding. It should take two sprites as values and return a bool valueindicating if they are colliding. If collided is not passed, then allsprites must have a "rect" value, which is a rectangle of the sprite area,which will be used to calculate the collision.
- pygame.sprite.spritecollideany()¶
- Simple test if a sprite intersects anything in a group.spritecollideany(sprite, group, collided = None) -> Sprite Collision with the returned sprite.spritecollideany(sprite, group, collided = None) -> None No collision
If the sprite collides with any single sprite in the group, a singlesprite 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, thisfunction will be a bit quicker.The collided argument is a callback function used to calculate if two sprites arecolliding. It should take two sprites as values and return a bool valueindicating if they are colliding. If collided is not passed, then allsprites must have a "rect" value, which is a rectangle of the sprite area,which will be used to calculate the collision.
Edit on GitHub
