[pygame] Sprite class

Sprite class

pygame.sprite.Sprite is the base class for objects in visual games

Attribute: Sprite(*groups) -> Sprite

Deriving a new class using the Sprite class requires assigning the Sprite.image and Sprite.rect properties and adding the Sprite.update() method. The initializer can add any number of Group instances. When subclassing the Sprite class, make sure the base initializer is called before adding the Sprite class to Groups. For example:

class Block(pygame. sprite. Sprite):
 
    # Constructor. Pass in the color and x,y position of the tile.
    def __init__(self, color, width, height):
       # Call parent class (Sprite) constructor
       pygame.sprite.Sprite.__init__(self)
 
       # Create a tile and fill it in, or load an image
       self. image = pygame. Surface([width, height])
       self. image. fill(color)
 
       # Get a Rect object with image dimensions
       # Update the position of the object by setting rect.x and rect.y
       self.rect = self.image.get_rect()

pygame.sprite.Sprite.update() method to control sprite behavior

update(*args, **kwargs) -> None

The default execution action of this method is nothing, which is a “hook” that is easy to rewrite. This method is called by Group.update(). [Group.update() parameters can be set freely]
There is no need to use this method if you are not using the method of the same name in the group class.

pygame.sprite.Sprite.add() adds sprites to the group

add(*groups) -> None

Any number of group instances can be passed as arguments. The sprite will be added to groups it is not already a member of.

pygame.sprite.Sprite.remove() removes the sprite from the group

remove(*groups) -> None
Any number of group instances can be passed as arguments. The sprite will be removed from the group it currently belongs to.

pygame.sprite.Sprite.kill() removes sprites from all groups

kill() -> None
The sprite will be removed from all groups containing it. This does not change the state of the sprite. After calling this method, you can continue working with the sprite, including adding it to a group.

pygame.sprite.Sprite.alive() determines whether the sprite belongs to any group

alive() -> bool
Returns True when the sprite belongs to one or more groups.

pygame.sprite.Sprite.groups() Get a list of groups containing this sprite

groups() -> group_list

Returns a list of all groups that contain this sprite.

A subclass of the pygame.sprite.DirtySprite sprite class, with more properties and features.

DirtySprite(*groups) -> DirtySprite

Additional DirtySprite properties and their default values:

dirty = 1
If set to 1, repaint, then set to 0 again

If set to 2, it is always dirty (redraws every frame, flag is not reset)

0 means it’s not dirty, so it won’t be repainted

blendmode = 0 blit, special flags parameter for blendmodes
source_rect = None
The source rect to use, relative to self.imaged’s topleft(0,0)

visible = 1
Usually 1, if set to 0, no repainting (must be set to dirty to remove from screen)

layer = 0
Read-only value, readable when adding it to LayeredDirty (see LayeredDirty documentation for details)

pygame.sprite.Group is a container class for storing and managing multiple sprite objects.

Group(*sprites) -> Group

A container for simple sprite objects. This class can be inherited to create containers with more specific behavior. The constructor accepts any number of sprite parameters to add to the group class. This set of classes supports the following standard Python operations:

in tests whether a sprite is contained

The number of sprites contained in len

bool test if contains any sprites

iter traverses all sprites

The sprites in the group class are not ordered, so there is no particular order in which sprites are drawn and iterated.

pygame.sprite.Group.sprites() The list of sprites contained in this group

sprites() -> sprite_list

Returns a list of all sprites contained in this set of classes. Iterators can also be obtained from the group class, but iterator operations cannot be performed on the group class when it is modified.

pygame.sprite.Group.copy() copy group class

copy() -> Group

Create a new group class with the same sprites as the original group class. If there is a subclass group class, the new object will have the same (sub)class as the original object. This only works if the constructor of the derived class takes the same parameters as the group class.

pygame.sprite.Group.add() adds sprites to this group class

add(*sprites) -> None

Add any number of sprites to this group. This method will only add sprites to group classes that are not already members.
Each sprite parameter can also be an iterator containing sprites.

pygame.sprite.Group.remove() removes the sprite from the group class

remove(*sprites) -> None

Removing any number of sprites from the group will only remove sprites that are already members of the group class.
Each sprite parameter can also be an iterator containing sprites.

pygame.sprite.Group.has() Test whether the group class contains sprites

has(*sprites) -> bool

Returns True if the group class contains all the given sprites. This is similar to using the “in” operator (“if sprite in Group:…”) on a group class to test whether a single sprite belongs to a group.
Each sprite parameter can also be an iterator containing sprites.

pygame.sprite.Group.update() calls the update method on the contained sprite

update(*args, **kwargs) -> None

Call the update() method on all sprites in the group class. The base Sprite class has an update() method that takes any number of arguments but does nothing. The arguments passed to Group.update() will be passed to each sprite.
Unable to get return value from Sprite.update() method.

pygame.sprite.Group.draw() blit sprite images

draw(Surface) -> None

Draw the contained sprite to the Surface parameter. Use the Sprite.image property and the Sprite.rect property as the source surface properties.
The group class doesn’t hold the sprites in any order, so the drawing order is arbitrary.

pygame.sprite.Group.clear() draws the background on top of the sprite (overlay)

clear(Surface_dest, background) -> None

Deletes the last sprite drawn with Group.draw(). Clears the target Surface by filling the drawn sprite’s position with the background.
The background is usually a Surface image of the same size as the target Surface. However, it can also be a callback function with two parameters [the target Surface and the area to be cleared]. The background callback function will be called multiple times per clear. Here’s an example callback that clears the solid red sprite:

def clear_callback(surf, rect):
    color = 255, 0, 0
    surf. fill(color, rect)

pygame.sprite.Group.empty() removes all sprites

empty() -> None
Removes all sprites from this group.

pygame.sprite.RenderPlain

Function: Equivalent to pygame.sprite.Group. This class is an alias for pygame.sprite.Group(). It has no extra functionality.

pygame.sprite.RenderClear

Function: Equivalent to pygame.sprite.Group. This class is an alias for pygame.sprite.Group(). It has no extra functionality.

pygame.sprite.RenderUpdates Group class subclass that tracks dirty updates.

Attribute: RenderUpdates(*sprites) -> RenderUpdates

This class is derived from pygame.sprite.Group(). It has an extended draw() method for keeping track of changing regions of the screen.

pygame.sprite.RenderUpdates.draw() blits sprite images and tracks changed regions

draw(surface) -> Rect_list

Draw all sprites to Surface, equivalent to Group.draw(). This method also returns a list of changed rectangular regions on the screen. The returned changes include the screen area affected by a previous Group.clear() call.
The returned Rect list will be passed to pygame.display.update(). This will help improve performance in software-driven display modes. This type of update is usually only useful for targets with non-animated backgrounds.

pygame.sprite.OrderedUpdates() RenderUpdates subclass, draw sprites in the order they were added.

Attribute: OrderedUpdates(*spites) -> OrderedUpdates

This class is derived from pygame.sprite.RenderUpdates(). It maintains the order in which sprites are added to the group class for rendering. This makes adding and removing sprites in group classes slightly slower than regular group classes.

pygame.sprite.LayeredUpdates layer class

LayeredUpdates is a sprite group that handles layers and drawing [like OrderedUpdates].

Attribute: LayeredUpdates(*spites, **kwargs) -> LayeredUpdates

This group is fully compatible with pygame.sprite.Sprite.
The default layer can be set via kwargs using ‘default_layer’ or an integer. The default layer is 0.

If the added sprite has an attribute layer, that layer will be used. If the kwarg contains “layer”, the passed sprite will be added to that layer (overriding the sprite.layer property). If the sprite has neither an attribute layer nor a kwarg, the sprite is added with the default layer.

New in pygame 1.8.

pygame.sprite.LayeredUpdates.add() adds a sprite or sequence of sprites to a group

Attributes: add(*sprites, **kwargs) -> None

If the sprite(s) have a property layer, that property layer is used for that layer. If **kwargs contains “layer”, the sprite(s) will be added to that argument (overriding sprite layer properties). If neither is passed, the sprite(s) will be added to the default layer.

pygame.sprite.LayeredUpdates.sprites() returns an ordered list of sprites (first down, last up)

Attribute: sprites() -> sprites

pygame.sprite.LayeredUpdates.draw()

Function: Draws all sprites to the passed Surface in the correct order.

Attribute: draw(surface) -> Rect_list

pygame.sprite.LayeredUpdates.get_sprites_at()

Function: Returns a list containing all sprites at this position (the first one is below, the last one is above)

Attribute: get_sprites_at(pos) -> colliding_sprites

pygame.sprite.LayeredUpdates.get_sprite()

Function: Returns the sprite at index idx from the group sprites

Attribute: get_sprite(idx) -> sprite

Raises IndexOutOfBounds if idx is not in range.

pygame.sprite.LayeredUpdates.remove_sprites_of_layer()

Function: Removes all sprites from the layer and returns them as a list.

Attribute: remove_sprites_of_layer(layer_nr) -> sprites

pygame.sprite.LayeredUpdates.layers()

Function: Returns the defined (unique) layer list, sorted from bottom to top.

Attribute: layers() -> layers

pygame.sprite.LayeredUpdates.change_layer()

Function: Change the layer of the sprite

Attribute: change_layer(sprite, new_layer) -> None

The sprite must have been added to the renderer beforehand. Pay attention to check.

pygame.sprite.LayeredUpdates.get_layer_of_sprite()

Function: Return the current layer of the sprite.

Attribute: get_layer_of_sprite(sprite) -> layer

If the sprite is not found, it will fall back to the default layer.

pygame.sprite.LayeredUpdates.get_top_layer()

Function: return to the top

Attribute: get_top_layer() -> layer

pygame.sprite.LayeredUpdates.get_bottom_layer()

Function: return to the bottom layer

Attribute: get_bottom_layer() -> layer

pygame.sprite.LayeredUpdates.move_to_front()

Function: bring the sprite to the top

Attribute: move_to_front(sprite) -> None

To bring the sprite to the front, change the sprite layer to be topmost (add at the end of the layer).

pygame.sprite.LayeredUpdates.move_to_back()

Function: Move the sprite to the bottom layer

Attribute: move_to_back(sprite) -> None

Move the sprite to the bottom layer, move it behind all other layers and add an additional layer.

pygame.sprite.LayeredUpdates.get_top_sprite()

Function: Return to the top sprite

Attribute: get_top_sprite() -> Sprite

pygame.sprite.LayeredUpdates.get_sprites_from_layer()

Returns all sprites in a layer, sorted by where they were added: function

Attribute: get_sprites_from_layer(layer) -> sprites

Returns all sprites in the layer, sorted by where they were added. It uses a linear search and the sprites are not removed from the layer.

pygame.sprite.LayeredUpdates.switch_layer()

Function: switch the sprite from layer 1 to layer 2

Attribute: switch_layer(layer1_nr, layer2_nr) -> None

The layer number must exist, pay attention to check.

pygame.sprite.LayeredDirty

Function: The LayeredDirty group class is used for DirtySprite objects. Subclass LayeredUpdates.

Attribute: LayeredDirty(*spites, **kwargs) -> LayeredDirty

This set of classes requires pygame.sprite.DirtySprite or any sprite with the following properties: image, rect, dirty, visible, blendmode (see doc of DirtySprite).
This set of classes uses a dirty flag technique and is therefore faster than pygame.sprite.RenderUpdates. It can also automatically switch between dirty rect updates and full-screen drawing if the program has a lot of static sprites.
As with pygame.sprite.Group , some additional properties can be specified via kwargs:
_use_update True/False default is False
_default_layer The default layer for sprites with no layers added
_time_threshold
Threshold time for switching between dirty rect modes. Full screen mode, the default is 1000./80==1000./fps

New in pygame 1.8.

pygame.sprite.LayeredDirty.draw()

Function: Draw all sprites to the passed surface in the correct order.

Attribute: draw(surface, bgd=None) -> Rect_list

A background can also be passed. The bgd parameter has no effect if the background is already set.

pygame.sprite.LayeredDirty.clear()

Function: used to set the background

Attribute: clear(surface, bgd) -> None

pygame.sprite.LayeredDirty.repaint_rect()

Function: Redraw the given area, screen_rect is in screen coordinates.

Attribute: repaint_rect(screen_rect) -> None

pygame.sprite.LayeredDirty.set_clip()

Function: Clip the area to be drawn. By passing None (the default) to reset the clip

Attribute: set_clip(screen_rect=None) -> None

pygame.sprite.LayeredDirty.get_clip()

Function: Clip the area to be drawn. By passing None (the default) to reset the clip

Attribute: get_clip() -> Rect

pygame.sprite.LayeredDirty.change_layer()

Function: Change the layer of the sprite

Attribute: change_layer(sprite, new_layer) -> None

The sprite must be added to the renderer beforehand, pay attention to check.

pygame.sprite.LayeredDirty.set_timing_treshold()

Function: set the threshold in milliseconds

Attribute: set_timing_treshold(time_ms) -> None

The default is 1000/80, where 80 is the fps to switch to full screen mode. There is a small mistake in the name of this method.

Raises: TypeError — if time_ms is not int or float
pygame.sprite.GroupSingle()
Function: A group class container that holds a single sprite.

Attribute: GroupSingle(sprite=None) -> GroupSingle

A GroupSingle container holds only one sprite. When new sprites are added, old sprites are removed.
There is a special attribute [GroupSingle.sprite] used to access the sprites contained in this group class. Displays None when the group class is empty. You can also specify properties to add sprites to GroupSingle containers.
pygame.sprite.spritecollide()
Function: Find a sprite in a group class that intersects another sprite.

Attribute: spritecollide(sprite, group, dokill, collided = None) -> Sprite_list

Returns a list containing all sprites in a group that intersect another sprite. Intersecting is comparing the Sprite.rect properties of each sprite.
The dokill parameter is a boolean. If set to True, all colliding sprites will be removed from the group.
The collision parameter is a callback function used to calculate whether two sprites collide. It should take two sprites as values and return a bool indicating if they collided. All sprites must have a “rect” value [the rectangle of the sprite’s area, used to calculate collisions) if not collided. collided Callable with parameters: collide_rect, collide_rect_ratio, collide_circle, collide_circle_ratio, collide_mask. For example:

Check if the sprite block conflicts with anything in the group block_list

True flag will delete sprites in block_list

blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

Check the collision sprite list and count

for block in blocks_hit_list:
score + =1
?pygame.sprite.collide_rect()
Function: Detect the collision between two sprites, represented by rects.

Attribute: collide_rect(left, right) -> bool

Tests for collision between two sprites. Collisions are calculated using the pygame rect colliderect function. And passed to the *collide function as a collision callback function.
Sprites must have a “rect” property.
New in pygame 1.8.

pygame.sprite.collide_rect_ratio()
Function: Collision detection between two sprites, represented by rects with a given scale.

Attribute: collide_rect_ratio(ratio) -> collided_callable

A callable class that checks for collisions between two sprites, represented using scaled versions of sprite rects.
Created with a ratio, then pass the instance to the *collide function as a collision callback.
Ratio is a float – 1.0 is the same size, 2.0 is twice as big, 0.5 is half as big
New in pygame 1.8.1.

pygame.sprite.collide_circle()
Function: Detect the collision between two sprites, represented by a circle.

Attribute: collide_circle(left, right) -> bool

Test for collision between two sprites by testing whether two circles centered on the sprite overlap. If the sprite has a “radius” property, that property is used to create the circle, otherwise a circle large enough to completely enclose the sprite’s “rect” property is created. And passed to the *collide function as a conflict callback function.
Sprites must have a “rect” and an optional “radius” property.
New in pygame 1.8.1.

pygame.sprite.collide_circle_ratio()
Function: Collision detection between two sprites, represented by a circle scaled by a given scale.

Attribute: collide_circle_ratio(ratio) -> collided_callable

A class callable that checks for collisions between two sprites, represented by a scaled version of the sprite’s radius.
Create with a floating point ratio, then pass the instance to the collide function as a collision callback.
The ratio is a float – 1.0 is the same size, 2.0 is twice as big, 0.5 is half as big.
A callable that tests for collision between two created sprites by testing whether two circles centered on the sprite overlap after scaling the circle radius by the stored ratio. If the sprite has a “radius” property, that property is used to create the circle, otherwise a circle large enough to completely enclose the sprite’s “rect” property is created and passed to the collide function as the collision callback.
Sprites must have a “rect” and an optional “radius” property.
New in pygame 1.8.1.

pygame.sprite.collide_mask()
Function: Collision detection between two sprites, represented by a mask.

Attributes:

collide_mask(sprite1, sprite2) -> (int, int)
collide_mask(sprite1, sprite2) -> None
Collisions are detected by testing whether the bitmasks of two sprites overlap (using pygame.mask.Mask.overlap()). If the sprite has a mask property it will be used as the mask, otherwise the mask will be created from the sprite’s image property (using pygame.mask.from_surface()). Sprites must have a rect property; a mask property is optional.
Returns the first collision point between masks. The coordinate origin of the collision point is the upper left corner of the mask of sprite 1 [always regarded as (0, 0)]. The collision point is a position within the mask, independent of sprite 1’s actual screen position.
This function will be passed as the collision callback function to the group class collision functions (see spritecollide(), group collide(), spritecollideany()).
Notice:

To improve performance, create and set a mask property for all sprites that will use this function to check for collisions. Otherwise, each time this function is called, it will create a new mask.
Every time you change the sprite’s image (for example, if you use a new image or rotate an existing one), you need to recreate a new mask.

Example of creating a mask for a sprite.

sprite.mask = pygame.mask.from_surface(sprite.image)
Returns: the first collision point between masks, or None if there is no collision
Return type: tuple(int, int) or NoneType
New in pygame 1.8.0.

pygame.sprite.groupcollide()
Function: Find all sprites that collide between two groups

Attribute: groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict

This method will find collisions between all sprites in the two groups. Collision is done by comparing the Sprite.rect property of each sprite, if, or using the collided function [when its parameter is not None].
Each sprite in group1 will be added to the returned dictionary. The value of each item is the list of intersected sprites in group2.
If the dokill parameter is true, colliding sprites will be removed from their respective group classes.
The collision parameter is a callback function used to calculate whether two sprites collide. It should take two sprites as values and return a bool indicating if they collided. All sprites must have a “rect” value [the rectangle of the sprite’s area, used to calculate collisions) if no collisions occurred.
pygame.sprite.spritecollideany()
Functionality: Simple test if a sprite intersects with anything in a set.

Attributes:

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 individual sprites in the group, the individual sprites in the group are returned. Returns None if there is no collision.
If you don’t need all the features of the pygame.sprite.spritecollide() function, this function will be a bit faster.
The collision parameter is a callback function used to calculate whether two sprites collide. It should take two sprites as values and return a bool indicating if they collided. All sprites must have a “rect” value [the rectangle of the sprite’s area, used to calculate collisions) if no collisions occurred.

syntaxbug.com © 2021 All Rights Reserved.