pygame.sprite

 pygame module with basic game object classes  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.   pygame.sprite.Sprite
 Simple base class for visible game objects. Sprite(*groups) -> Sprite  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:
class Block(pygame.sprite.Sprite):

    # Constructor. Pass in the color of the block,
    # and its x and y position
    def __init__(self, color, width, height):
       # Call the parent class (Sprite) constructor
       pygame.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.y
       self.rect = self.image.get_rect()
    update()
 method to control sprite behavior update(*args, **kwargs) -> None  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.
   add()
 add the sprite to groups add(*groups) -> None  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.
   remove()
 remove the sprite from groups remove(*groups) -> None  Any number of Group instances can be passed as arguments. The Sprite will be removed from the Groups it is currently a member of.
   kill()
 remove the Sprite from all Groups kill() -> None  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.
   alive()
 does the sprite belong to any groups alive() -> bool  Returns True when the Sprite belongs to one or more Groups.
   groups()
 list of Groups that contain this Sprite groups() -> group_list  Return a list of all the Groups that contain this Sprite.

   pygame.sprite.DirtySprite
 A subclass of Sprite with more attributes and features. DirtySprite(*groups) -> DirtySprite  Extra DirtySprite attributes with their default values: dirty = 1 if set to 1, it is repainted and then set to 0 again
if set to 2 then it is always dirty ( repainted each frame,
flag is not reset)
0 means that it is not dirty and therefore not repainted again blendmode = 0 its the special_flags argument of blit, blendmodes source_rect = None source rect to use, remember that it is relative to
topleft (0,0) of self.image visible = 1 normally 1, if set to 0 it will not be repainted
(you must set it dirty too to be erased from screen) layer = 0 (READONLY value, it is read when adding it to the
LayeredDirty, for details see doc of LayeredDirty)
   pygame.sprite.Group
 A container class to hold and manage multiple Sprite objects. Group(*sprites) -> Group  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: in      test if a Sprite is contained
len     the number of Sprites contained
bool    test if any Sprites are contained
iter    iterate through all the Sprites The Sprites in the Group are not ordered, so drawing and iterating the Sprites is in no particular order.   sprites()
 list of the Sprites this Group contains sprites() -> sprite_list  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.
   copy()
 duplicate the Group copy() -> Group  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()
 add Sprites to this Group add(*sprites) -> None  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()
 remove Sprites from the Group remove(*sprites) -> None  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.
   has()
 test if a Group contains Sprites has(*sprites) -> bool  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.
   update()
 call the update method on contained Sprites update(*args, **kwargs) -> None  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.
   draw()
 blit the Sprite images draw(Surface) -> None  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.
   clear()
 draw a background over the Sprites clear(Surface_dest, background) -> None  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: def clear_callback(surf, rect):
    color = 255, 0, 0
    surf.fill(color, rect)
   empty()
 remove all Sprites empty() -> None  Removes all Sprites from this Group.

   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  This class is derived from pygame.sprite.Group(). It has an extended draw() method that tracks the changed areas of the screen.   draw()
 blit the Sprite images and track changed areas draw(surface) -> Rect_list  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.

   pygame.sprite.OrderedUpdates()
 RenderUpdates sub-class that draws Sprites in order of addition. OrderedUpdates(*spites) -> OrderedUpdates  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.
   pygame.sprite.LayeredUpdates
 LayeredUpdates is a sprite group that handles layers and draws like OrderedUpdates. LayeredUpdates(*spites, **kwargs) -> LayeredUpdates  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.    add()
 add a sprite or sequence of sprites to a group add(*sprites, **kwargs) -> None  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.
   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) -> 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 sprites get_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 sprite change_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 layer get_top_layer() -> layer
   get_bottom_layer()
 returns the bottom layer get_bottom_layer() -> layer
   move_to_front()
 brings the sprite to front layer move_to_front(sprite) -> None  Brings the sprite to front, changing sprite layer to topmost layer (added at the end of that layer).
   move_to_back()
 moves the sprite to the bottom layer move_to_back(sprite) -> None  Moves the sprite to the bottom layer, moving it behind all other layers and adding one additional layer.
   get_top_sprite()
 returns the topmost sprite get_top_sprite() -> Sprite
   get_sprites_from_layer()
 returns all sprites from a layer, ordered by how they where added get_sprites_from_layer(layer) -> sprites  Returns all sprites from a layer, ordered by how they where added. It uses linear search and the sprites are not removed from layer.
   switch_layer()
 switches the sprites from layer1 to layer2 switch_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(*spites, **kwargs) -> LayeredDirty  This group requires pygame.sprite.DirtySprite or any sprite that has the following attributes: image, rect, dirty, visible, blendmode (see doc of DirtySprite). 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: _use_update: True/False   default is False
_default_layer: default layer where sprites without a layer are added.
_time_threshold: threshold time for switching between dirty rect mode
    and fullscreen mode, defaults to 1000./80  == 1000./fps  New in pygame 1.8.    draw()
 draw all sprites in the right order onto the passed surface. draw(surface, bgd=None) -> Rect_list  You can pass the background too. If a background is already set, then the bgd argument has no effect.
   clear()
 used to set background clear(surface, bgd) -> None
   repaint_rect()
 repaints the given area repaint_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 clip set_clip(screen_rect=None) -> None
   get_clip()
 clip the area where to draw. Just pass None (default) to reset the clip get_clip() -> Rect
   change_layer()
 changes the layer of the sprite change_layer(sprite, new_layer) -> None  sprite must have been added to the renderer. It is not checked.
   set_timing_treshold()
 sets the threshold in milliseconds set_timing_treshold(time_ms) -> None  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.
Raises:

TypeError -- if time_ms is 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 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.
   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 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: 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_list
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

# Check the list of colliding sprites, and add one to the score for each one
for block in blocks_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 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.
   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 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.
   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 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.
   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 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.
   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 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).  # Example of mask creation for a sprite.
sprite.mask = pygame.mask.from_surface(sprite.image)
Returns:
first point of collision between the masks or None if no collision
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.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.
   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 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.


pygame.surfarray

 pygame module for accessing surface pixel data using array interfaces  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.   pygame.surfarray.array2d()
 Copy pixels into a 2d array array2d(Surface) -> array  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).
   pygame.surfarray.pixels2d()
 Reference pixels into a 2d array pixels2d(Surface) -> array  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).
   pygame.surfarray.array3d()
 Copy pixels into a 3d array array3d(Surface) -> array  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).
   pygame.surfarray.pixels3d()
 Reference pixels into a 3d array pixels3d(Surface) -> array  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).
   pygame.surfarray.array_alpha()
 Copy pixel alphas into a 2d array array_alpha(Surface) -> array  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).
   pygame.surfarray.pixels_alpha()
 Reference pixel alphas into a 2d array pixels_alpha(Surface) -> array  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.
   pygame.surfarray.pixels_red()
 Reference pixel red into a 2d array. pixels_red (Surface) -> 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.
   pygame.surfarray.pixels_green()
 Reference pixel green into a 2d array. pixels_green (Surface) -> 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.
   pygame.surfarray.pixels_blue()
 Reference pixel blue into a 2d array. pixels_blue (Surface) -> 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.
   pygame.surfarray.array_colorkey()
 Copy the colorkey values into a 2d array array_colorkey(Surface) -> 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.
   pygame.surfarray.make_surface()
 Copy an array to a new surface make_surface(array) -> Surface  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.
   pygame.surfarray.blit_array()
 Blit directly from a array values blit_array(Surface, array) -> None  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.
   pygame.surfarray.map_array()
 Map a 3d array into a 2d array map_array(Surface, array3d) -> array2d  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.
   pygame.surfarray.use_arraytype()
 Sets the array system to be used for surface arrays use_arraytype (arraytype) -> None  DEPRECATED: Uses the requested array type for the module functions. The only supported arraytype is 'numpy'. Other values will raise ValueError.
   pygame.surfarray.get_arraytype()
 Gets the currently active array type. get_arraytype () -> str  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.
   pygame.surfarray.get_arraytypes()
 Gets the array system types currently supported. get_arraytypes () -> tuple  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.


pygame.tests

 Pygame unit test suite package  A quick way to run the test suite package from the command line is to import the go submodule with the Python -m option: python -m pygame.tests [<test options>] 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.   pygame.tests.run()
 Run the pygame unit test suite run(*args, **kwds) -> tuple  Positional arguments (optional): The names of tests to include. If omitted then all tests are run. Test names
need not include the trailing '_test'. Keyword arguments: incomplete - fail incomplete tests (default False)
nosubprocess - run all test suites in the current process
               (default False, use separate subprocesses)
dump - dump failures/errors as dict ready to eval (default False)
file - if provided, the name of a file into which to dump failures/errors
timings - if provided, the number of times to run each individual test to
          get an average run time (default is run each test once)
exclude - A list of TAG names to exclude from the run
show_output - show silenced stderr/stdout on errors (default False)
all - dump all results, not just errors (default False)
randomize - randomize order of tests (default False)
seed - if provided, a seed randomizer integer
multi_thread - if provided, the number of THREADS in which to run
               subprocessed tests
time_out - if subprocess is True then the time limit in seconds before
           killing a test (default 30)
fake - if provided, the name of the fake tests package in the
       run_tests__tests subpackage to run instead of the normal
       pygame tests
python - the path to a python executable to run subprocessed tests
         (default sys.executable) Return value: A tuple of total number of tests run, dictionary of error information.
The dictionary is empty if no errors were recorded. 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.


pygame.time

 pygame module for monitoring time  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.   pygame.time.get_ticks()
 get the time in milliseconds get_ticks() -> milliseconds  Return the number of milliseconds since pygame.init() was called. Before pygame is initialized this will always be 0.
   pygame.time.wait()
 pause the program for an amount of time wait(milliseconds) -> time  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.
   pygame.time.delay()
 pause the program for an amount of time delay(milliseconds) -> time  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.
   pygame.time.set_timer()
 repeatedly create an event on the event queue set_timer(eventid, milliseconds) -> None set_timer(eventid, milliseconds, once) -> None  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.
   pygame.time.Clock
 create an object to help track time Clock() -> Clock  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.   tick()
 update the clock tick(framerate=0) -> milliseconds  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.
   tick_busy_loop()
 update the clock tick_busy_loop(framerate=0) -> milliseconds  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.
   get_time()
 time used in the previous tick get_time() -> milliseconds  The number of milliseconds that passed between the previous two calls to Clock.tick().
   get_rawtime()
 actual time used in the previous tick get_rawtime() -> milliseconds  Similar to Clock.get_time(), but does not include any time used while Clock.tick() was delaying to limit the framerate.
   get_fps()
 compute the clock framerate get_fps() -> float  Compute your game's framerate (in frames per second). It is computed by averaging the last ten calls to Clock.tick().


pygame.transform

 pygame module to transform surfaces  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.)   pygame.transform.flip()
 flip vertically and horizontally flip(Surface, xbool, ybool) -> Surface  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.
   pygame.transform.scale()
 resize to new resolution scale(Surface, (width, height), DestSurface = None) -> Surface  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.
   pygame.transform.rotate()
 rotate an image rotate(Surface, angle) -> Surface  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.
   pygame.transform.rotozoom()
 filtered scale and rotation rotozoom(Surface, angle, scale) -> Surface  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.
   pygame.transform.scale2x()
 specialized image doubler scale2x(Surface, DestSurface = None) -> Surface  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.
   pygame.transform.smoothscale()
 scale a surface to an arbitrary size smoothly smoothscale(Surface, (width, height), DestSurface = None) -> Surface  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.
   pygame.transform.get_smoothscale_backend()
 return smoothscale filter version in use: 'GENERIC', 'MMX', or 'SSE' get_smoothscale_backend() -> String  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.
   pygame.transform.set_smoothscale_backend()
 set smoothscale filter version to one of: 'GENERIC', 'MMX', or 'SSE' set_smoothscale_backend(type) -> None  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.
   pygame.transform.chop()
 gets a copy of an image with an interior area removed chop(Surface, rect) -> Surface  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.
   pygame.transform.laplacian()
 find edges in a surface laplacian(Surface, DestSurface = None) -> Surface  Finds the edges in a surface using the laplacian algorithm.  New in pygame 1.8.
   pygame.transform.average_surfaces()
 find the average surface from many surfaces. average_surfaces(Surfaces, DestSurface = None, palette_colors = 1) -> Surface  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
   pygame.transform.average_color()
 finds the average color of a surface average_color(Surface, Rect = None) -> Color  Finds the average color of a Surface or a region of a surface specified by a Rect, and returns it as a Color.
   pygame.transform.threshold()
 finds which, and how many pixels in a surface are within a threshold of a 'search_color' or a 'search_surf'. threshold(dest_surf, surf, search_color, threshold=(0,0,0,0), set_color=(0,0,0,0), set_behavior=1, search_surf=None, inverse_set=False) -> num_threshold_pixels  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'.
Parameters:

dest_surf (pygame.Surface or None) -- Surface we are changing. See 'set_behavior'. Should be None if counting (set_behavior is 0).
surf (pygame.Surface) -- Surface we are looking at.
search_color (pygame.Color) -- Color we are searching for.
threshold (pygame.Color) -- Within this distance from search_color (or search_surf). You can use a threshold of (r,g,b,a) where the r,g,b can have different thresholds. So you could use an r threshold of 40 and a blue threshold of 2 if you like.
set_color (pygame.Color or None) -- Color we set in dest_surf.
set_behavior (int) --  set_behavior=1 (default). Pixels in dest_surface will be changed to 'set_color'. set_behavior=0 we do not change 'dest_surf', just count. Make dest_surf=None. set_behavior=2 pixels set in 'dest_surf' will be from 'surf'.
search_surf (pygame.Surface or None) --  search_surf=None (default). Search against 'search_color' instead. search_surf=Surface. Look at the color in 'search_surf' rather than using 'search_color'.
inverse_set (bool) --  False, default. Pixels outside of threshold are changed. True, Pixels within threshold are changed.
Return type:

int
Returns:

The number of pixels that are within the 'threshold' in 'surf' compared to either 'search_color' or search_surf.
Examples:
    See the threshold tests for a full of examples: https://github.com/pygame/pygame/blob/master/test/transform_test.py def test_threshold_dest_surf_not_change(self):
        """ the pixels within the threshold.

        All pixels not within threshold are changed to set_color.
        So there should be none changed in this test.
        """
        (w, h) = size = (32, 32)
        threshold = (20, 20, 20, 20)
        original_color = (25, 25, 25, 25)
        original_dest_color = (65, 65, 65, 55)
        threshold_color = (10, 10, 10, 10)
        set_color = (255, 10, 10, 10)

        surf = pygame.Surface(size, pygame.SRCALPHA, 32)
        dest_surf = pygame.Surface(size, pygame.SRCALPHA, 32)
        search_surf = pygame.Surface(size, pygame.SRCALPHA, 32)

        surf.fill(original_color)
        search_surf.fill(threshold_color)
        dest_surf.fill(original_dest_color)

        # set_behavior=1, set dest_surface from set_color.
        # all within threshold of third_surface, so no color is set.

        THRESHOLD_BEHAVIOR_FROM_SEARCH_COLOR = 1
        pixels_within_threshold = pygame.transform.threshold(
            dest_surf=dest_surf,
            surf=surf,
            search_color=None,
            threshold=threshold,
            set_color=set_color,
            set_behavior=THRESHOLD_BEHAVIOR_FROM_SEARCH_COLOR,
            search_surf=search_surf,
        )

        # # Return, of pixels within threshold is correct
        self.assertEqual(w * h, pixels_within_threshold)

        # # Size of dest surface is correct
        dest_rect = dest_surf.get_rect()
        dest_size = dest_rect.size
        self.assertEqual(size, dest_size)

        # The color is not the change_color specified for every pixel As all
        # pixels are within threshold

        for pt in test_utils.rect_area_pts(dest_rect):
            self.assertNotEqual(dest_surf.get_at(pt), set_color)
            self.assertEqual(dest_surf.get_at(pt), original_dest_color)  New in pygame 1.8.   Changed in pygame 1.9.4: Fixed a lot of bugs and added keyword arguments. Test your code.


pygame.mouse.get_cursor()
 get the image of the mouse cursor get_cursor() -> (size, hotspot, xormasks, andmasks)  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.


pygame.mouse.get_focused()
 check if the display is receiving mouse input get_focused() -> bool  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.


pygame.mouse.get_pos()
 get the mouse cursor position get_pos() -> (x, y)  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.


pygame.mouse.get_pressed()
 get the state of the mouse buttons get_pressed(num_buttons=3) -> (button1, button2, button3) get_pressed(num_buttons=5) -> (button1, button2, button3, button4, button5)  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


pygame.mouse.get_rel()
 get the amount of mouse movement get_rel() -> (x, y)  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.


pygame.mouse.get_visible()
 get the current visibility state of the mouse cursor get_visible() -> bool  Get the current visibility state of the mouse cursor. True if the mouse is visible, False otherwise.  New in pygame 2.0.0.


pygame.mouse.set_cursor()
 set the image for the mouse cursor set_cursor(size, hotspot, xormasks, andmasks) -> None  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.


pygame.mouse.set_pos()
 set the mouse cursor position set_pos([x, y]) -> None  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.


pygame.mouse.set_system_cursor()
 set the mouse cursor to a system variant set_system_cursor(constant) -> None  When the mouse cursor is visible, it will displayed as a operating system specific variant of the options below. Pygame Cursor Constant           Description
--------------------------------------------
pygame.SYSTEM_CURSOR_ARROW       arrow
pygame.SYSTEM_CURSOR_IBEAM       i-beam
pygame.SYSTEM_CURSOR_WAIT        wait
pygame.SYSTEM_CURSOR_CROSSHAIR   crosshair
pygame.SYSTEM_CURSOR_WAITARROW   small wait cursor
                                 (or wait if not available)
pygame.SYSTEM_CURSOR_SIZENWSE    double arrow pointing
                                 northwest and southeast
pygame.SYSTEM_CURSOR_SIZENESW    double arrow pointing
                                 northeast and southwest
pygame.SYSTEM_CURSOR_SIZEWE      double arrow pointing
                                 west and east
pygame.SYSTEM_CURSOR_SIZENS      double arrow pointing
                                 north and south
pygame.SYSTEM_CURSOR_SIZEALL     four pointed arrow pointing
                                 north, south, east, and west
pygame.SYSTEM_CURSOR_NO          slashed circle or crossbones
pygame.SYSTEM_CURSOR_HAND        hand  New in pygame 2.0.0.


pygame.mouse.set_visible()
 hide or show the mouse cursor set_visible(bool) -> bool  If the bool argument is true, the mouse cursor will be visible. This will return the previous visible state of the cursor.


pygame.Overlay

 pygame object for video overlay graphics Overlay(format, (width, height)) -> Overlay  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: YV12_OVERLAY, IYUV_OVERLAY, YUY2_OVERLAY, UYVY_OVERLAY, YVYU_OVERLAY 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()
 set the overlay pixel data display((y, u, v)) -> None display() -> None  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_location()
 control where the overlay is displayed set_location(rect) -> None  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().
   get_hardware()
 test if the Overlay is hardware accelerated get_hardware(rect) -> int  Returns a True value when the Overlay is hardware accelerated. If the platform does not support acceleration, software rendering is used.


display()
 set the overlay pixel data display((y, u, v)) -> None display() -> None  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.


get_hardware()
 test if the Overlay is hardware accelerated get_hardware(rect) -> int  Returns a True value when the Overlay is hardware accelerated. If the platform does not support acceleration, software rendering is used.


set_location()
 control where the overlay is displayed set_location(rect) -> None  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().


pygame.PixelArray

 pygame object for direct pixel access of surfaces PixelArray(Surface) -> PixelArray  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. pxarray[x, y] = 0xFF00FF
pxarray[x, y] = pygame.Color(255, 0, 255)
pxarray[x, y] = (255, 0, 255) 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. pxarray = pygame.PixelArray(surface)
# Check, if the first pixel at the topleft corner is blue
if pxarray[0, 0] == surface.map_rgb((0, 0, 255)):
    ... 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. pxarray[a:b] = 0xFF00FF                   # set all pixels to 0xFF00FF
pxarray[a:b] = (0xFF00FF, 0xAACCEE, ... ) # first pixel = 0xFF00FF,
                                          # second pixel  = 0xAACCEE, ...
pxarray[a:b] = [(255, 0, 255), (170, 204, 238), ...] # same as above
pxarray[a:b] = [(255, 0, 255), 0xAACCEE, ...]        # same as above
pxarray[a:b] = otherarray[x:y]            # slice sizes must match 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. # Create some new PixelArray objects providing a different view
# of the original array/surface.
newarray = pxarray[2:4, 3:5]
otherarray = pxarray[::2, ::2] Subscript slices can also be used to do fast rectangular pixel manipulations instead of iterating over the x or y axis. The pxarray[::2, :] = (0, 0, 0)               # Make even columns black.
pxarray[::2] = (0, 0, 0)                  # Same as [::2, :] 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. pxarray[::2, ...] = (0, 0, 0)             # Same as pxarray[::2, :]
pxarray[...] = (255, 0, 0)                # Same as pxarray[:] 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.   New in pygame 1.9.4:
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).      New in pygame 1.9.2:
array struct interface
transpose method
broadcasting for a length 1 dimension      Changed in pygame 1.9.2:
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.      surface
 Gets the Surface the PixelArray uses. surface -> Surface  The Surface the PixelArray was created for.
   itemsize
 Returns the byte size of a pixel array item itemsize -> int  This is the same as Surface.get_bytesize() for the pixel array's surface.  New in pygame 1.9.2.
   ndim
 Returns the number of dimensions. ndim -> int  A pixel array can be 1 or 2 dimensional.  New in pygame 1.9.2.
   shape
 Returns the array size. shape -> tuple of int's  A tuple or length ndim giving the length of each dimension. Analogous to Surface.get_size().  New in pygame 1.9.2.
   strides
 Returns byte offsets for each array dimension. strides -> tuple of int's  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.
   make_surface()
 Creates a new Surface from the current PixelArray. make_surface() -> Surface  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. # Create a new surface flipped around the vertical axis.
sf = pxarray[:,::-1].make_surface ()  New in pygame 1.8.1.
   replace()
 Replaces the passed color in the PixelArray with another one. replace(color, repcolor, distance=0, weights=(0.299, 0.587, 0.114)) -> None  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.
   extract()
 Extracts the passed color from the PixelArray. extract(color, distance=0, weights=(0.299, 0.587, 0.114)) -> PixelArray  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.
   compare()
 Compares the PixelArray with another one. compare(array, distance=0, weights=(0.299, 0.587, 0.114)) -> PixelArray  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.
   transpose()
 Exchanges the x and y axis. transpose() -> PixelArray  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.
   close()
 Closes the PixelArray, and releases Surface lock. transpose() -> PixelArray  This method is for explicitly closing the PixelArray, and releasing a lock on the Suface.  New in pygame 1.9.4.


close()
 Closes the PixelArray, and releases Surface lock. transpose() -> PixelArray  This method is for explicitly closing the PixelArray, and releasing a lock on the Suface.  New in pygame 1.9.4.


compare()
 Compares the PixelArray with another one. compare(array, distance=0, weights=(0.299, 0.587, 0.114)) -> PixelArray  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.


extract()
 Extracts the passed color from the PixelArray. extract(color, distance=0, weights=(0.299, 0.587, 0.114)) -> PixelArray  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.


itemsize
 Returns the byte size of a pixel array item itemsize -> int  This is the same as Surface.get_bytesize() for the pixel array's surface.  New in pygame 1.9.2.


make_surface()
 Creates a new Surface from the current PixelArray. make_surface() -> Surface  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. # Create a new surface flipped around the vertical axis.
sf = pxarray[:,::-1].make_surface ()  New in pygame 1.8.1.


ndim
 Returns the number of dimensions. ndim -> int  A pixel array can be 1 or 2 dimensional.  New in pygame 1.9.2.


replace()
 Replaces the passed color in the PixelArray with another one. replace(color, repcolor, distance=0, weights=(0.299, 0.587, 0.114)) -> None  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.


shape
 Returns the array size. shape -> tuple of int's  A tuple or length ndim giving the length of each dimension. Analogous to Surface.get_size().  New in pygame 1.9.2.


strides
 Returns byte offsets for each array dimension. strides -> tuple of int's  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.


surface
 Gets the Surface the PixelArray uses. surface -> Surface  The Surface the PixelArray was created for.


transpose()
 Exchanges the x and y axis. transpose() -> PixelArray  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.


pygame.pixelcopy.array_to_surface()
 copy an array object to a surface array_to_surface(<surface>, <array>) -> None  See pygame.surfarray.blit_array().


pygame.pixelcopy.make_surface()
 Copy an array to a new surface pygame.pixelcopy.make_surface(array) -> 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.


pygame.pixelcopy.map_array()
 copy an array to another array, using surface format map_array(<array>, <array>, <surface>) -> None  Map an array of color element values - (w, h, ..., 3) - to an array of pixels - (w, h) according to the format of <surface>.


pygame.pixelcopy.surface_to_array()
 copy surface pixels to an array object surface_to_array(array, surface, kind='P', opaque=255, clear=0) -> None  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.


pygame.quit()
 uninitialize all pygame modules quit() -> None  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.Rect

 pygame object for storing rectangular coordinates Rect(left, top, width, height) -> Rect Rect((left, top), (width, height)) -> Rect Rect(object) -> Rect  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: x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h All of these attributes can be assigned to: rect1.right = 10
rect2.center = (20,30) 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.    copy()
 copy the rectangle copy() -> Rect  Returns a new rectangle having the same position and size as the original. New in pygame 1.9
   move()
 moves the rectangle move(x, y) -> Rect  Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative.
   move_ip()
 moves the rectangle, in place move_ip(x, y) -> None  Same as the Rect.move() method, but operates in place.
   inflate()
 grow or shrink the rectangle size inflate(x, y) -> Rect  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.
   inflate_ip()
 grow or shrink the rectangle size, in place inflate_ip(x, y) -> None  Same as the Rect.inflate() method, but operates in place.
   update()
 sets the position and size of the rectangle update(left, top, width, height) -> None update((left, top), (width, height)) -> None update(object) -> None  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.
   clamp()
 moves the rectangle inside another clamp(Rect) -> Rect  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.
   clamp_ip()
 moves the rectangle inside another, in place clamp_ip(Rect) -> None  Same as the Rect.clamp() method, but operates in place.
   clip()
 crops a rectangle inside another clip(Rect) -> Rect  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.
   clipline()
 crops a line inside a rectangle clipline(x1, y1, x2, y2) -> ((cx1, cy1), (cx2, cy2)) clipline(x1, y1, x2, y2) -> () clipline((x1, y1), (x2, y2)) -> ((cx1, cy1), (cx2, cy2)) clipline((x1, y1), (x2, y2)) -> () clipline((x1, y1, x2, y2)) -> ((cx1, cy1), (cx2, cy2)) clipline((x1, y1, x2, y2)) -> () clipline(((x1, y1), (x2, y2))) -> ((cx1, cy1), (cx2, cy2)) clipline(((x1, y1), (x2, y2))) -> ()  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):
 four ints 2 lists/tuples/Vector2s of 2 ints a list/tuple of four ints a list/tuple of 2 lists/tuples/Vector2s of 2 ints

Returns:
a tuple with the coordinates of the given line cropped to be completely inside the rectangle is returned, if the given line does not overlap the rectangle, an empty tuple is returned
Return type:
tuple(tuple(int, int), tuple(int, int)) or ()
Raises:

TypeError -- if the line coordinates are not given as one of the above described line formats     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.  # Example using clipline().
clipped_line = rect.clipline(line)

if clipped_line:
    # If clipped_line is not an empty tuple then the line
    # collides/overlaps with the rect. The returned value contains
    # the endpoints of the clipped line.
    start, end = clipped_line
    x1, y1 = start
    x2, y2 = end
else:
    print("No clipping. The line is fully outside the rect.")  New in pygame 2.0.0.
   union()
 joins two rectangles into one union(Rect) -> Rect  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.
   union_ip()
 joins two rectangles into one, in place union_ip(Rect) -> None  Same as the Rect.union() method, but operates in place.
   unionall()
 the union of many rectangles unionall(Rect_sequence) -> Rect  Returns the union of one rectangle with a sequence of many rectangles.
   unionall_ip()
 the union of many rectangles, in place unionall_ip(Rect_sequence) -> None  The same as the Rect.unionall() method, but operates in place.
   fit()
 resize and move a rectangle with aspect ratio fit(Rect) -> Rect  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.
   normalize()
 correct negative sizes normalize() -> None  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.
   contains()
 test if one rectangle is inside another contains(Rect) -> bool  Returns true when the argument is completely inside the Rect.
   collidepoint()
 test if a point is inside a rectangle collidepoint(x, y) -> bool collidepoint((x,y)) -> bool  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.
   colliderect()
 test if two rectangles overlap colliderect(Rect) -> bool  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.
   collidelist()
 test if one rectangle in a list intersects collidelist(list) -> index  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.
   collidelistall()
 test if all rectangles in a list intersect collidelistall(list) -> indices  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.
   collidedict()
 test if one rectangle in a dictionary intersects collidedict(dict) -> (key, value) collidedict(dict) -> None collidedict(dict, use_values=0) -> (key, value) collidedict(dict, use_values=0) -> None  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})
   collidedictall()
 test if all rectangles in a dictionary intersect collidedictall(dict) -> [(key, value), ...] collidedictall(dict, use_values=0) -> [(key, 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})


clamp()
 moves the rectangle inside another clamp(Rect) -> Rect  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.


clamp_ip()
 moves the rectangle inside another, in place clamp_ip(Rect) -> None  Same as the Rect.clamp() method, but operates in place.


clip()
 crops a rectangle inside another clip(Rect) -> Rect  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.


clipline()
 crops a line inside a rectangle clipline(x1, y1, x2, y2) -> ((cx1, cy1), (cx2, cy2)) clipline(x1, y1, x2, y2) -> () clipline((x1, y1), (x2, y2)) -> ((cx1, cy1), (cx2, cy2)) clipline((x1, y1), (x2, y2)) -> () clipline((x1, y1, x2, y2)) -> ((cx1, cy1), (cx2, cy2)) clipline((x1, y1, x2, y2)) -> () clipline(((x1, y1), (x2, y2))) -> ((cx1, cy1), (cx2, cy2)) clipline(((x1, y1), (x2, y2))) -> ()  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):
 four ints 2 lists/tuples/Vector2s of 2 ints a list/tuple of four ints a list/tuple of 2 lists/tuples/Vector2s of 2 ints

Returns:
a tuple with the coordinates of the given line cropped to be completely inside the rectangle is returned, if the given line does not overlap the rectangle, an empty tuple is returned
Return type:
tuple(tuple(int, int), tuple(int, int)) or ()
Raises:

TypeError -- if the line coordinates are not given as one of the above described line formats     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.  # Example using clipline().
clipped_line = rect.clipline(line)

if clipped_line:
    # If clipped_line is not an empty tuple then the line
    # collides/overlaps with the rect. The returned value contains
    # the endpoints of the clipped line.
    start, end = clipped_line
    x1, y1 = start
    x2, y2 = end
else:
    print("No clipping. The line is fully outside the rect.")  New in pygame 2.0.0.


collidedict()
 test if one rectangle in a dictionary intersects collidedict(dict) -> (key, value) collidedict(dict) -> None collidedict(dict, use_values=0) -> (key, value) collidedict(dict, use_values=0) -> None  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})


collidedictall()
 test if all rectangles in a dictionary intersect collidedictall(dict) -> [(key, value), ...] collidedictall(dict, use_values=0) -> [(key, 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})


collidelist()
 test if one rectangle in a list intersects collidelist(list) -> index  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.


collidelistall()
 test if all rectangles in a list intersect collidelistall(list) -> indices  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.


collidepoint()
 test if a point is inside a rectangle collidepoint(x, y) -> bool collidepoint((x,y)) -> bool  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.


colliderect()
 test if two rectangles overlap colliderect(Rect) -> bool  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.


contains()
 test if one rectangle is inside another contains(Rect) -> bool  Returns true when the argument is completely inside the Rect.


copy()
 copy the rectangle copy() -> Rect  Returns a new rectangle having the same position and size as the original. New in pygame 1.9


fit()
 resize and move a rectangle with aspect ratio fit(Rect) -> Rect  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.


inflate()
 grow or shrink the rectangle size inflate(x, y) -> Rect  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.


inflate_ip()
 grow or shrink the rectangle size, in place inflate_ip(x, y) -> None  Same as the Rect.inflate() method, but operates in place.


move()
 moves the rectangle move(x, y) -> Rect  Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative.


move_ip()
 moves the rectangle, in place move_ip(x, y) -> None  Same as the Rect.move() method, but operates in place.


normalize()
 correct negative sizes normalize() -> None  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.


union()
 joins two rectangles into one union(Rect) -> Rect  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.


union_ip()
 joins two rectangles into one, in place union_ip(Rect) -> None  Same as the Rect.union() method, but operates in place.


unionall()
 the union of many rectangles unionall(Rect_sequence) -> Rect  Returns the union of one rectangle with a sequence of many rectangles.


unionall_ip()
 the union of many rectangles, in place unionall_ip(Rect_sequence) -> None  The same as the Rect.unionall() method, but operates in place.


update()
 sets the position and size of the rectangle update(left, top, width, height) -> None update((left, top), (width, height)) -> None update(object) -> None  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.


pygame.register_quit()
 register a function to be called when pygame quits register_quit(callable) -> None  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.


pygame.scrap.contains()
 Checks whether data for a given type is available in the clipboard. contains(type) -> bool  Checks whether data for the given type is currently available in the clipboard.
Parameters:

type (string) -- data type to check availability of
Returns:

True if data for the passed type is available in the clipboard, False otherwise
Return type:
bool    if pygame.scrap.contains(pygame.SCRAP_TEXT):
    print("There is text in the clipboard.")
if pygame.scrap.contains("own_data_type"):
    print("There is stuff in the clipboard.")


pygame.scrap.get()
 Gets the data for the specified type from the clipboard. get(type) -> bytes or str or None  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).
Parameters:

type (string) -- data type to retrieve from the clipboard
Returns:
data (byte string in python 3 or str in python 2) for the given type identifier or None if no data for the given type is available
Return type:
bytes or str or None    text = pygame.scrap.get(pygame.SCRAP_TEXT)
if text:
    print("There is text in the clipboard.")
else:
    print("There does not seem to be text in the clipboard.")


pygame.scrap.get_init()
 Returns True if the scrap module is currently initialized. get_init() -> bool  Gets the scrap module's initialization state.
Returns:

True if the pygame.scrap module is currently initialized, False otherwise
Return type:
bool     New in pygame 1.9.5.


pygame.scrap.get_types()
 Gets a list of the available clipboard types. get_types() -> list  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.
Returns:
list of strings of the available clipboard data types, if there is no data in the clipboard an empty list is returned
Return type:
list    for t in pygame.scrap.get_types():
    if "text" in t:
        # There is some content with the word "text" in its type string.
        print(pygame.scrap.get(t))


pygame.scrap.init()
 Initializes the scrap module. init() -> None  Initialize the scrap module.
Raises:

pygame.error -- if unable to initialize scrap module        Note The scrap module requires pygame.display.set_mode() be called before being initialized.


pygame.scrap.lost()
 Indicates if the clipboard ownership has been lost by the pygame application. lost() -> bool  Indicates if the clipboard ownership has been lost by the pygame application.
Returns:

True, if the clipboard ownership has been lost by the pygame application, False if the pygame application still owns the clipboard
Return type:
bool    if pygame.scrap.lost():
    print("The clipboard is in use by another application.")


pygame.scrap.put()
 Places data into the clipboard. put(type, data) -> None  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.
Parameters:

type (string) -- type identifier of the data to be placed into the clipboard
data (bytes or str) -- data to be place into the clipboard (in python 3 data is a byte string and in python 2 data is a str)
Raises:

pygame.error -- if unable to put the data into the clipboard     with open("example.bmp", "rb") as fp:
    pygame.scrap.put(pygame.SCRAP_BMP, fp.read())
# The image data is now on the clipboard for other applications to access
# it.
pygame.scrap.put(pygame.SCRAP_TEXT, b"A text to copy")
pygame.scrap.put("Plain text", b"Data for user defined type 'Plain text'")


pygame.scrap.set_mode()
 Sets the clipboard access mode. set_mode(mode) -> None  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.
Parameters:

mode -- access mode, supported values are pygame.SCRAP_CLIPBOARD and pygame.SCRAP_SELECTION (pygame.SCRAP_SELECTION only has an effect when used on X11 platforms)
Raises:

ValueError -- if the mode parameter is not pygame.SCRAP_CLIPBOARD or pygame.SCRAP_SELECTION


pygame.set_error()
 set the current error message set_error(error_msg) -> None  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.


pygame.sndarray.array()
 copy Sound samples into an array array(Sound) -> array  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().


pygame.sndarray.get_arraytype()
 Gets the currently active array type. get_arraytype () -> str  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.


pygame.sndarray.get_arraytypes()
 Gets the array system types currently supported. get_arraytypes () -> tuple  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.


pygame.sndarray.make_sound()
 convert an array into a Sound object make_sound(array) -> Sound  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.


pygame.sndarray.samples()
 reference Sound samples into an array samples(Sound) -> array  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().


pygame.sndarray.use_arraytype()
 Sets the array system to be used for sound arrays use_arraytype (arraytype) -> None  DEPRECATED: Uses the requested array type for the module functions. The only supported arraytype is 'numpy'. Other values will raise ValueError.


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 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.


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 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.