pygame.gfxdraw.rectangle()
 draw a rectangle rectangle(surface, rect, color) -> None  Draws an unfilled rectangle on the given surface. For a filled rectangle use box().
Parameters:

surface (Surface) -- surface to draw on
rect (Rect) -- rectangle to draw, position and dimensions
color (Color or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])

Returns:

None
Return type:

NoneType      Note The rect.bottom and rect.right attributes of a pygame.Rect always lie one pixel outside of its actual border. Therefore, these values will not be included as part of the drawing.


pygame.gfxdraw.textured_polygon()
 draw a textured polygon textured_polygon(surface, points, texture, tx, ty) -> None  Draws a textured polygon on the given surface. For better performance, the surface and the texture should have the same format. A per-pixel alpha texture blit to a per-pixel alpha surface will differ from a pygame.Surface.blit() blit. Also, a per-pixel alpha texture cannot be used with an 8-bit per pixel destination. The adjacent coordinates in the points argument, as well as the first and last points, will be connected by line segments. e.g. For the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2), from (x2, y2) to (x3, y3), and from (x3, y3) to (x1, y1).
Parameters:

surface (Surface) -- surface to draw on
points (tuple(coordinate) or list(coordinate)) -- a sequence of 3 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats (float values will be truncated)
texture (Surface) -- texture to draw on the polygon
tx (int) -- x offset of the texture
ty (int) -- y offset of the texture
Returns:

None
Return type:

NoneType
Raises:

ValueError -- if len(points) < 3 (must have at least 3 points)
IndexError -- if len(coordinate) < 2 (each coordinate must have at least 2 items)


pygame.gfxdraw.trigon()
 draw a trigon/triangle trigon(surface, x1, y1, x2, y2, x3, y3, color) -> None  Draws an unfilled trigon (triangle) on the given surface. For a filled trigon use filled_trigon(). A trigon can also be drawn using polygon() e.g. polygon(surface, ((x1, y1), (x2, y2), (x3, y3)), color)
Parameters:

surface (Surface) -- surface to draw on
x1 (int) -- x coordinate of the first corner of the trigon
y1 (int) -- y coordinate of the first corner of the trigon
x2 (int) -- x coordinate of the second corner of the trigon
y2 (int) -- y coordinate of the second corner of the trigon
x3 (int) -- x coordinate of the third corner of the trigon
y3 (int) -- y coordinate of the third corner of the trigon
color (Color or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])

Returns:

None
Return type:

NoneType


pygame.gfxdraw.vline()
 draw a vertical line vline(surface, x, y1, y2, color) -> None  Draws a straight vertical line ((x, y1) to (x, y2)) on the given surface. There are no endcaps.
Parameters:

surface (Surface) -- surface to draw on
x (int) -- x coordinate of the line
y1 (int) -- y coordinate of one end of the line
y2 (int) -- y coordinate of the other end of the line
color (Color or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])

Returns:

None
Return type:

NoneType


pygame.image

 pygame module for image transfer  The image module contains functions for loading and saving pictures, as well as transferring Surfaces to formats usable by other packages. Note that there is no Image class; an image is loaded as a Surface object. The Surface class allows manipulation (drawing lines, setting pixels, capturing regions, etc.). The image module is a required dependency of pygame, but it only optionally supports any extended file formats. By default it can only load uncompressed BMP images. When built with full image support, the pygame.image.load() function can support the following formats.
 JPG PNG
GIF (non-animated) BMP PCX
TGA (uncompressed) TIF
LBM (and PBM)
PBM (and PGM, PPM) XPM
 Saving images only supports a limited set of formats. You can save to the following formats.
 BMP TGA PNG JPEG
 JPEG and JPG refer to the same file format  New in pygame 1.8: Saving PNG and JPEG files.    pygame.image.load_basic()
 load new BMP image from a file (or file-like object) load_basic(file) -> Surface  Load an image from a file source. You can pass either a filename or a Python file-like object. This function only supports loading "basic" image format, ie BMP format. This function is always available, no matter how pygame was built.
   pygame.image.load()
 load new image from a file (or file-like object) load(filename) -> Surface load(fileobj, namehint="") -> Surface  Load an image from a file source. You can pass either a filename or a Python file-like object. Pygame will automatically determine the image type (e.g., GIF or bitmap) and create a new Surface object from the data. In some cases it will need to know the file extension (e.g., GIF images should end in ".gif"). If you pass a raw file-like object, you may also want to pass the original filename as the namehint argument. The returned Surface will contain the same color format, colorkey and alpha transparency as the file it came from. You will often want to call Surface.convert() with no arguments, to create a copy that will draw more quickly on the screen. For alpha transparency, like in .png images, use the convert_alpha() method after loading so that the image has per pixel transparency. pygame may not always be built to support all image formats. At minimum it will support uncompressed BMP. If pygame.image.get_extended() returns 'True', you should be able to load most images (including PNG, JPG and GIF). You should use os.path.join() for compatibility. eg. asurf = pygame.image.load(os.path.join('data', 'bla.png'))
   pygame.image.load_extended()
 load an image from a file (or file-like object) load_extended(filename) -> Surface load_extended(fileobj, namehint="") -> Surface  This function is similar to pygame.image.load(), except that this function can only be used if pygame was built with extended image format support. From version 2.0.1, this function is always available, but raises an error if extended image formats are not supported. Previously, this function may or may not be available, depending on the state of extended image format support.  Changed in pygame 2.0.1.
   pygame.image.save()
 save an image to file (or file-like object) save(Surface, filename) -> None save(Surface, fileobj, namehint="") -> None  This will save your Surface as either a BMP, TGA, PNG, or JPEG image. If the filename extension is unrecognized it will default to TGA. Both TGA, and BMP file formats create uncompressed files. You can pass a filename or a Python file-like object. For file-like object, the image is saved to TGA format unless a namehint with a recognizable extension is passed in.  Note To be able to save the JPEG file format to a file-like object, SDL2_Image version 2.0.2 or newer is needed.   Note When saving to a file-like object, it seems that for most formats, the object needs to be flushed after saving to it to make loading from it possible.   Changed in pygame 1.8: Saving PNG and JPEG files.   Changed in pygame 2.0.0.dev11: The namehint parameter was added to make it possible to save other formats than TGA to a file-like object.
   pygame.image.save_extended()
 save a png/jpg image to file (or file-like object) save_extended(Surface, filename) -> None save_extended(Surface, fileobj, namehint="") -> None  This will save your Surface as either a PNG or JPEG image. Incase the image is being saved to a file-like object, this function uses the namehint argument to determine the format of the file being saved. Saves to JPEG incase the namehint was not specified while saving to file-like object. From version 2.0.1, this function is always available, but raises an error if extended image formats are not supported. Previously, this function may or may not be available, depending on the state of extended image format support.  Changed in pygame 2.0.1.
   pygame.image.get_sdl_image_version()
 get version number of the SDL_Image library being used get_sdl_image_version() -> None get_sdl_image_version() -> (major, minor, patch)  If pygame is built with extended image formats, then this function will return the SDL_Image library's version number as a tuple of 3 integers (major, minor, patch). If not, then it will return None.  New in pygame 2.0.0.dev11.
   pygame.image.get_extended()
 test if extended image formats can be loaded get_extended() -> bool  If pygame is built with extended image formats this function will return True. It is still not possible to determine which formats will be available, but generally you will be able to load them all.
   pygame.image.tostring()
 transfer image to string buffer tostring(Surface, format, flipped=False) -> string  Creates a string that can be transferred with the 'fromstring' method in other Python imaging packages. Some Python image packages prefer their images in bottom-to-top format (PyOpenGL for example). If you pass True for the flipped argument, the string buffer will be vertically flipped. The format argument is a string of one of the following values. Note that only 8-bit Surfaces can use the "P" format. The other formats will work for any Surface. Also note that other Python image packages support more formats than pygame.

P, 8-bit palettized Surfaces
RGB, 24-bit image
RGBX, 32-bit image with unused space
RGBA, 32-bit image with an alpha channel
ARGB, 32-bit image with alpha channel first
RGBA_PREMULT, 32-bit image with colors scaled by alpha channel
ARGB_PREMULT, 32-bit image with colors scaled by alpha channel, alpha channel first

   pygame.image.fromstring()
 create new Surface from a string buffer fromstring(string, size, format, flipped=False) -> Surface  This function takes arguments similar to pygame.image.tostring(). The size argument is a pair of numbers representing the width and height. Once the new Surface is created you can destroy the string buffer. The size and format image must compute the exact same size as the passed string buffer. Otherwise an exception will be raised. See the pygame.image.frombuffer() method for a potentially faster way to transfer images into pygame.
   pygame.image.frombuffer()
 create a new Surface that shares data inside a bytes buffer frombuffer(bytes, size, format) -> Surface  Create a new Surface that shares pixel data directly from a bytes buffer. This method takes similar arguments to pygame.image.fromstring(), but is unable to vertically flip the source data. This will run much faster than pygame.image.fromstring(), since no pixel data must be allocated and copied. It accepts the following 'format' arguments:

P, 8-bit palettized Surfaces
RGB, 24-bit image
BGR, 24-bit image, red and blue channels swapped.
RGBX, 32-bit image with unused space
RGBA, 32-bit image with an alpha channel
ARGB, 32-bit image with alpha channel first


pygame.image.frombuffer()
 create a new Surface that shares data inside a bytes buffer frombuffer(bytes, size, format) -> Surface  Create a new Surface that shares pixel data directly from a bytes buffer. This method takes similar arguments to pygame.image.fromstring(), but is unable to vertically flip the source data. This will run much faster than pygame.image.fromstring(), since no pixel data must be allocated and copied. It accepts the following 'format' arguments:

P, 8-bit palettized Surfaces
RGB, 24-bit image
BGR, 24-bit image, red and blue channels swapped.
RGBX, 32-bit image with unused space
RGBA, 32-bit image with an alpha channel
ARGB, 32-bit image with alpha channel first


pygame.image.fromstring()
 create new Surface from a string buffer fromstring(string, size, format, flipped=False) -> Surface  This function takes arguments similar to pygame.image.tostring(). The size argument is a pair of numbers representing the width and height. Once the new Surface is created you can destroy the string buffer. The size and format image must compute the exact same size as the passed string buffer. Otherwise an exception will be raised. See the pygame.image.frombuffer() method for a potentially faster way to transfer images into pygame.


pygame.image.get_extended()
 test if extended image formats can be loaded get_extended() -> bool  If pygame is built with extended image formats this function will return True. It is still not possible to determine which formats will be available, but generally you will be able to load them all.


pygame.image.get_sdl_image_version()
 get version number of the SDL_Image library being used get_sdl_image_version() -> None get_sdl_image_version() -> (major, minor, patch)  If pygame is built with extended image formats, then this function will return the SDL_Image library's version number as a tuple of 3 integers (major, minor, patch). If not, then it will return None.  New in pygame 2.0.0.dev11.


pygame.image.load()
 load new image from a file (or file-like object) load(filename) -> Surface load(fileobj, namehint="") -> Surface  Load an image from a file source. You can pass either a filename or a Python file-like object. Pygame will automatically determine the image type (e.g., GIF or bitmap) and create a new Surface object from the data. In some cases it will need to know the file extension (e.g., GIF images should end in ".gif"). If you pass a raw file-like object, you may also want to pass the original filename as the namehint argument. The returned Surface will contain the same color format, colorkey and alpha transparency as the file it came from. You will often want to call Surface.convert() with no arguments, to create a copy that will draw more quickly on the screen. For alpha transparency, like in .png images, use the convert_alpha() method after loading so that the image has per pixel transparency. pygame may not always be built to support all image formats. At minimum it will support uncompressed BMP. If pygame.image.get_extended() returns 'True', you should be able to load most images (including PNG, JPG and GIF). You should use os.path.join() for compatibility. eg. asurf = pygame.image.load(os.path.join('data', 'bla.png'))


pygame.image.load_basic()
 load new BMP image from a file (or file-like object) load_basic(file) -> Surface  Load an image from a file source. You can pass either a filename or a Python file-like object. This function only supports loading "basic" image format, ie BMP format. This function is always available, no matter how pygame was built.


pygame.image.load_extended()
 load an image from a file (or file-like object) load_extended(filename) -> Surface load_extended(fileobj, namehint="") -> Surface  This function is similar to pygame.image.load(), except that this function can only be used if pygame was built with extended image format support. From version 2.0.1, this function is always available, but raises an error if extended image formats are not supported. Previously, this function may or may not be available, depending on the state of extended image format support.  Changed in pygame 2.0.1.


pygame.image.save()
 save an image to file (or file-like object) save(Surface, filename) -> None save(Surface, fileobj, namehint="") -> None  This will save your Surface as either a BMP, TGA, PNG, or JPEG image. If the filename extension is unrecognized it will default to TGA. Both TGA, and BMP file formats create uncompressed files. You can pass a filename or a Python file-like object. For file-like object, the image is saved to TGA format unless a namehint with a recognizable extension is passed in.  Note To be able to save the JPEG file format to a file-like object, SDL2_Image version 2.0.2 or newer is needed.   Note When saving to a file-like object, it seems that for most formats, the object needs to be flushed after saving to it to make loading from it possible.   Changed in pygame 1.8: Saving PNG and JPEG files.   Changed in pygame 2.0.0.dev11: The namehint parameter was added to make it possible to save other formats than TGA to a file-like object.


pygame.image.save_extended()
 save a png/jpg image to file (or file-like object) save_extended(Surface, filename) -> None save_extended(Surface, fileobj, namehint="") -> None  This will save your Surface as either a PNG or JPEG image. Incase the image is being saved to a file-like object, this function uses the namehint argument to determine the format of the file being saved. Saves to JPEG incase the namehint was not specified while saving to file-like object. From version 2.0.1, this function is always available, but raises an error if extended image formats are not supported. Previously, this function may or may not be available, depending on the state of extended image format support.  Changed in pygame 2.0.1.


pygame.image.tostring()
 transfer image to string buffer tostring(Surface, format, flipped=False) -> string  Creates a string that can be transferred with the 'fromstring' method in other Python imaging packages. Some Python image packages prefer their images in bottom-to-top format (PyOpenGL for example). If you pass True for the flipped argument, the string buffer will be vertically flipped. The format argument is a string of one of the following values. Note that only 8-bit Surfaces can use the "P" format. The other formats will work for any Surface. Also note that other Python image packages support more formats than pygame.

P, 8-bit palettized Surfaces
RGB, 24-bit image
RGBX, 32-bit image with unused space
RGBA, 32-bit image with an alpha channel
ARGB, 32-bit image with alpha channel first
RGBA_PREMULT, 32-bit image with colors scaled by alpha channel
ARGB_PREMULT, 32-bit image with colors scaled by alpha channel, alpha channel first


pygame.init()
 initialize all imported pygame modules init() -> (numpass, numfail)  Initialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but pygame.init() is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail. You may want to initialize the different modules separately to speed up your program or to not use modules your game does not require. It is safe to call this init() more than once as repeated calls will have no effect. This is true even if you have pygame.quit() all the modules.


pygame.joystick

 Pygame module for interacting with joysticks, gamepads, and trackballs.  The joystick module manages the joystick devices on a computer. Joystick devices include trackballs and video-game-style gamepads, and the module allows the use of multiple buttons and "hats". Computers may manage multiple joysticks at a time. Each instance of the Joystick class represents one gaming device plugged into the computer. If a gaming pad has multiple joysticks on it, than the joystick object can actually represent multiple joysticks on that single game device. For a quick way to initialise the joystick module and get a list of Joystick instances use the following code: pygame.joystick.init()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())] The following event types will be generated by the joysticks JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION And in pygame 2, which supports hotplugging: JOYDEVICEADDED JOYDEVICEREMOVED Note that in pygame 2, joysticks events use a unique "instance ID". The device index passed in the constructor to a Joystick object is not unique after devices have been added and removed. You must call Joystick.get_instance_id() to find the instance ID that was assigned to a Joystick on opening. The event queue needs to be pumped frequently for some of the methods to work. So call one of pygame.event.get, pygame.event.wait, or pygame.event.pump regularly.   pygame.joystick.init()
 Initialize the joystick module. init() -> None  This function is called automatically by pygame.init(). It initializes the joystick module. The module must be initialized before any other functions will work. It is safe to call this function more than once.
   pygame.joystick.quit()
 Uninitialize the joystick module. quit() -> None  Uninitialize the joystick module. After you call this any existing joystick objects will no longer work. It is safe to call this function more than once.
   pygame.joystick.get_init()
 Returns True if the joystick module is initialized. get_init() -> bool  Test if the pygame.joystick.init() function has been called.
   pygame.joystick.get_count()
 Returns the number of joysticks. get_count() -> count  Return the number of joystick devices on the system. The count will be 0 if there are no joysticks on the system. When you create Joystick objects using Joystick(id), you pass an integer that must be lower than this count.
   pygame.joystick.Joystick
 Create a new Joystick object. Joystick(id) -> Joystick  Create a new joystick to access a physical device. The id argument must be a value from 0 to pygame.joystick.get_count() - 1. Joysticks are initialised on creation and are shut down when deallocated. Once the device is initialized the pygame event queue will start receiving events about its input.  Changed in pygame 2.0.0: Joystick objects are now opened immediately on creation.    init()
 initialize the Joystick init() -> None  Initialize the joystick, if it has been closed. It is safe to call this even if the joystick is already initialized.  Deprecated since pygame 2.0.0: In future it will not be possible to reinitialise a closed Joystick object. Will be removed in Pygame 2.1.
   quit()
 uninitialize the Joystick quit() -> None  Close a Joystick object. After this the pygame event queue will no longer receive events from the device. It is safe to call this more than once.
   get_init()
 check if the Joystick is initialized get_init() -> bool  Return True if the Joystick object is currently initialised.
   get_id()
 get the device index (deprecated) get_id() -> int  Returns the original device index for this device. This is the same value that was passed to the Joystick() constructor. This method can safely be called while the Joystick is not initialized.  Deprecated since pygame 2.0.0: The original device index is not useful in pygame 2. Use get_instance_id() instead. Will be removed in Pygame 2.1.
   get_instance_id() → int
 get the joystick instance id get_instance_id() -> int  Get the joystick instance ID. This matches the instance_id field that is given in joystick events.  New in pygame 2.0.0dev11.
   get_guid() → str
 get the joystick GUID get_guid() -> str  Get the GUID string. This identifies the exact hardware of the joystick device.  New in pygame 2.0.0dev11.
   get_power_level() → str
 get the approximate power status of the device get_power_level() -> str  Get a string giving the power status of the device. One of: empty, low, medium, full, wired, max, or unknown.  New in pygame 2.0.0dev11.
   get_name()
 get the Joystick system name get_name() -> string  Returns the system name for this joystick device. It is unknown what name the system will give to the Joystick, but it should be a unique name that identifies the device. This method can safely be called while the Joystick is not initialized.
   get_numaxes()
 get the number of axes on a Joystick get_numaxes() -> int  Returns the number of input axes are on a Joystick. There will usually be two for the position. Controls like rudders and throttles are treated as additional axes. The pygame.JOYAXISMOTION events will be in the range from -1.0 to 1.0. A value of 0.0 means the axis is centered. Gamepad devices will usually be -1, 0, or 1 with no values in between. Older analog joystick axes will not always use the full -1 to 1 range, and the centered value will be some area around 0. Analog joysticks usually have a bit of noise in their axis, which will generate a lot of rapid small motion events.
   get_axis()
 get the current position of an axis get_axis(axis_number) -> float  Returns the current position of a joystick axis. The value will range from -1 to 1 with a value of 0 being centered. You may want to take into account some tolerance to handle jitter, and joystick drift may keep the joystick from centering at 0 or using the full range of position values. The axis number must be an integer from 0 to get_numaxes() - 1. When using gamepads both the control sticks and the analog triggers are usually reported as axes.
   get_numballs()
 get the number of trackballs on a Joystick get_numballs() -> int  Returns the number of trackball devices on a Joystick. These devices work similar to a mouse but they have no absolute position; they only have relative amounts of movement. The pygame.JOYBALLMOTION event will be sent when the trackball is rolled. It will report the amount of movement on the trackball.
   get_ball()
 get the relative position of a trackball get_ball(ball_number) -> x, y  Returns the relative movement of a joystick button. The value is a x, y pair holding the relative movement since the last call to get_ball. The ball number must be an integer from 0 to get_numballs() - 1.
   get_numbuttons()
 get the number of buttons on a Joystick get_numbuttons() -> int  Returns the number of pushable buttons on the joystick. These buttons have a boolean (on or off) state. Buttons generate a pygame.JOYBUTTONDOWN and pygame.JOYBUTTONUP event when they are pressed and released.
   get_button()
 get the current button state get_button(button) -> bool  Returns the current state of a joystick button.
   get_numhats()
 get the number of hat controls on a Joystick get_numhats() -> int  Returns the number of joystick hats on a Joystick. Hat devices are like miniature digital joysticks on a joystick. Each hat has two axes of input. The pygame.JOYHATMOTION event is generated when the hat changes position. The position attribute for the event contains a pair of values that are either -1, 0, or 1. A position of (0, 0) means the hat is centered.
   get_hat()
 get the position of a joystick hat get_hat(hat_number) -> x, y  Returns the current position of a position hat. The position is given as two values representing the x and y position for the hat. (0, 0) means centered. A value of -1 means left/down and a value of 1 means right/up: so (-1, 0) means left; (1, 0) means right; (0, 1) means up; (1, 1) means upper-right; etc. This value is digital, i.e., each coordinate can be -1, 0 or 1 but never in-between. The hat number must be between 0 and get_numhats() - 1.

   Example code for joystick module.  import pygame

# Define some colors.
BLACK = pygame.Color('black')
WHITE = pygame.Color('white')

# This is a simple class that will help us print to the screen.
# It has nothing to do with the joysticks, just outputting the
# information.
class TextPrint(object):
    def __init__(self):
        self.reset()
        self.font = pygame.font.Font(None, 20)

    def tprint(self, screen, textString):
        textBitmap = self.font.render(textString, True, BLACK)
        screen.blit(textBitmap, (self.x, self.y))
        self.y += self.line_height

    def reset(self):
        self.x = 10
        self.y = 10
        self.line_height = 15

    def indent(self):
        self.x += 10

    def unindent(self):
        self.x -= 10

pygame.init()

# Set the width and height of the screen (width, height).
screen = pygame.display.set_mode((500, 700))

pygame.display.set_caption("My Game")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates.
clock = pygame.time.Clock()

# Initialize the joysticks.
pygame.joystick.init()

# Get ready to print.
textPrint = TextPrint()

# -------- Main Program Loop -----------
while not done:
    #
    # EVENT PROCESSING STEP
    #
    # Possible joystick actions: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN,
    # JOYBUTTONUP, JOYHATMOTION
    for event in pygame.event.get(): # User did something.
        if event.type == pygame.QUIT: # If user clicked close.
            done = True # Flag that we are done so we exit this loop.
        elif event.type == pygame.JOYBUTTONDOWN:
            print("Joystick button pressed.")
        elif event.type == pygame.JOYBUTTONUP:
            print("Joystick button released.")

    #
    # DRAWING STEP
    #
    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(WHITE)
    textPrint.reset()

    # Get count of joysticks.
    joystick_count = pygame.joystick.get_count()

    textPrint.tprint(screen, "Number of joysticks: {}".format(joystick_count))
    textPrint.indent()

    # For each joystick:
    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()

        try:
            jid = joystick.get_instance_id()
        except AttributeError:
            # get_instance_id() is an SDL2 method
            jid = joystick.get_id()
        textPrint.tprint(screen, "Joystick {}".format(jid))
        textPrint.indent()

        # Get the name from the OS for the controller/joystick.
        name = joystick.get_name()
        textPrint.tprint(screen, "Joystick name: {}".format(name))

        try:
            guid = joystick.get_guid()
        except AttributeError:
            # get_guid() is an SDL2 method
            pass
        else:
            textPrint.tprint(screen, "GUID: {}".format(guid))

        # Usually axis run in pairs, up/down for one, and left/right for
        # the other.
        axes = joystick.get_numaxes()
        textPrint.tprint(screen, "Number of axes: {}".format(axes))
        textPrint.indent()

        for i in range(axes):
            axis = joystick.get_axis(i)
            textPrint.tprint(screen, "Axis {} value: {:>6.3f}".format(i, axis))
        textPrint.unindent()

        buttons = joystick.get_numbuttons()
        textPrint.tprint(screen, "Number of buttons: {}".format(buttons))
        textPrint.indent()

        for i in range(buttons):
            button = joystick.get_button(i)
            textPrint.tprint(screen,
                             "Button {:>2} value: {}".format(i, button))
        textPrint.unindent()

        hats = joystick.get_numhats()
        textPrint.tprint(screen, "Number of hats: {}".format(hats))
        textPrint.indent()

        # Hat position. All or nothing for direction, not a float like
        # get_axis(). Position is a tuple of int values (x, y).
        for i in range(hats):
            hat = joystick.get_hat(i)
            textPrint.tprint(screen, "Hat {} value: {}".format(i, str(hat)))
        textPrint.unindent()

        textPrint.unindent()

    #
    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
    #

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 20 frames per second.
    clock.tick(20)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit() Common Controller Axis Mappings Controller mappings are drawn from the underlying SDL library which pygame uses and they differ between pygame 1 and pygame 2. Below are a couple of mappings for two popular game pads. Pygame 2 Axis and hat mappings are listed from -1 to +1. X-Box 360 Controller (name: "Xbox 360 Controller") In pygame 2 the X360 controller mapping has 6 Axes, 11 buttons and 1 hat.
Left Stick: Left -> Right   - Axis 0
Up   -> Down    - Axis 1
Right Stick: Left -> Right   - Axis 3
Up   -> Down    - Axis 4
Left Trigger: Out -> In       - Axis 2
Right Trigger: Out -> In       - Axis 5
Buttons: A Button        - Button 0
B Button        - Button 1
X Button        - Button 2
Y Button        - Button 3
Left Bumper     - Button 4
Right Bumper    - Button 5
Back Button     - Button 6
Start Button    - Button 7
L. Stick In     - Button 8
R. Stick In     - Button 9
Guide Button    - Button 10
Hat/D-pad: Down -> Up      - Y Axis
Left -> Right   - X Axis   Playstation 4 Controller (name: "PS4 Controller") In pygame 2 the PS4 controller mapping has 6 Axes and 16 buttons.
Left Stick: Left -> Right   - Axis 0
Up   -> Down    - Axis 1
Right Stick: Left -> Right   - Axis 2
Up   -> Down    - Axis 3
Left Trigger: Out -> In       - Axis 4
Right Trigger: Out -> In       - Axis 5
Buttons: Cross Button    - Button 0
Circle Button   - Button 1
Square Button   - Button 2
Triangle Button - Button 3
Share Button    - Button 4
PS Button       - Button 5
Options Button  - Button 6
L. Stick In     - Button 7
R. Stick In     - Button 8
Left Bumper     - Button 9
Right Bumper    - Button 10
D-pad Up        - Button 11
D-pad Down      - Button 12
D-pad Left      - Button 13
D-pad Right     - Button 14
Touch Pad Click - Button 15   Pygame 1 Axis and hat mappings are listed from -1 to +1. X-Box 360 Controller (name: "Controller (XBOX 360 For Windows)") In pygame 1 the X360 controller mapping has 5 Axes, 10 buttons and 1 hat.
Left Stick: Left -> Right   - Axis 0
Up   -> Down    - Axis 1
Right Stick: Left -> Right   - Axis 4
Up   -> Down    - Axis 3
Left Trigger & Right Trigger: RT -> LT        - Axis 2
Buttons: A Button        - Button 0
B Button        - Button 1
X Button        - Button 2
Y Button        - Button 3
Left Bumper     - Button 4
Right Bumper    - Button 5
Back Button     - Button 6
Start Button    - Button 7
L. Stick In     - Button 8
R. Stick In     - Button 9
Hat/D-pad: Down -> Up      - Y Axis
Left -> Right   - X Axis   Playstation 4 Controller (name: "Wireless Controller") In pygame 1 the PS4 controller mapping has 6 Axes and 14 buttons and 1 hat.
Left Stick: Left -> Right   - Axis 0
Up   -> Down    - Axis 1
Right Stick: Left -> Right   - Axis 2
Up   -> Down    - Axis 3
Left Trigger: Out -> In       - Axis 5
Right Trigger: Out -> In       - Axis 4
Buttons: Cross Button    - Button 0
Circle Button   - Button 1
Square Button   - Button 2
Triangle Button - Button 3
Left Bumper     - Button 4
Right Bumper    - Button 5
L. Trigger(Full)- Button 6
R. Trigger(Full)- Button 7
Share Button    - Button 8
Options Button  - Button 9
L. Stick In     - Button 10
R. Stick In     - Button 11
PS Button       - Button 12
Touch Pad Click - Button 13
Hat/D-pad: Down -> Up      - Y Axis
Left -> Right   - X Axis


pygame.joystick.get_count()
 Returns the number of joysticks. get_count() -> count  Return the number of joystick devices on the system. The count will be 0 if there are no joysticks on the system. When you create Joystick objects using Joystick(id), you pass an integer that must be lower than this count.


pygame.joystick.get_init()
 Returns True if the joystick module is initialized. get_init() -> bool  Test if the pygame.joystick.init() function has been called.


pygame.joystick.init()
 Initialize the joystick module. init() -> None  This function is called automatically by pygame.init(). It initializes the joystick module. The module must be initialized before any other functions will work. It is safe to call this function more than once.


pygame.joystick.Joystick
 Create a new Joystick object. Joystick(id) -> Joystick  Create a new joystick to access a physical device. The id argument must be a value from 0 to pygame.joystick.get_count() - 1. Joysticks are initialised on creation and are shut down when deallocated. Once the device is initialized the pygame event queue will start receiving events about its input.  Changed in pygame 2.0.0: Joystick objects are now opened immediately on creation.    init()
 initialize the Joystick init() -> None  Initialize the joystick, if it has been closed. It is safe to call this even if the joystick is already initialized.  Deprecated since pygame 2.0.0: In future it will not be possible to reinitialise a closed Joystick object. Will be removed in Pygame 2.1.
   quit()
 uninitialize the Joystick quit() -> None  Close a Joystick object. After this the pygame event queue will no longer receive events from the device. It is safe to call this more than once.
   get_init()
 check if the Joystick is initialized get_init() -> bool  Return True if the Joystick object is currently initialised.
   get_id()
 get the device index (deprecated) get_id() -> int  Returns the original device index for this device. This is the same value that was passed to the Joystick() constructor. This method can safely be called while the Joystick is not initialized.  Deprecated since pygame 2.0.0: The original device index is not useful in pygame 2. Use get_instance_id() instead. Will be removed in Pygame 2.1.
   get_instance_id() → int
 get the joystick instance id get_instance_id() -> int  Get the joystick instance ID. This matches the instance_id field that is given in joystick events.  New in pygame 2.0.0dev11.
   get_guid() → str
 get the joystick GUID get_guid() -> str  Get the GUID string. This identifies the exact hardware of the joystick device.  New in pygame 2.0.0dev11.
   get_power_level() → str
 get the approximate power status of the device get_power_level() -> str  Get a string giving the power status of the device. One of: empty, low, medium, full, wired, max, or unknown.  New in pygame 2.0.0dev11.
   get_name()
 get the Joystick system name get_name() -> string  Returns the system name for this joystick device. It is unknown what name the system will give to the Joystick, but it should be a unique name that identifies the device. This method can safely be called while the Joystick is not initialized.
   get_numaxes()
 get the number of axes on a Joystick get_numaxes() -> int  Returns the number of input axes are on a Joystick. There will usually be two for the position. Controls like rudders and throttles are treated as additional axes. The pygame.JOYAXISMOTION events will be in the range from -1.0 to 1.0. A value of 0.0 means the axis is centered. Gamepad devices will usually be -1, 0, or 1 with no values in between. Older analog joystick axes will not always use the full -1 to 1 range, and the centered value will be some area around 0. Analog joysticks usually have a bit of noise in their axis, which will generate a lot of rapid small motion events.
   get_axis()
 get the current position of an axis get_axis(axis_number) -> float  Returns the current position of a joystick axis. The value will range from -1 to 1 with a value of 0 being centered. You may want to take into account some tolerance to handle jitter, and joystick drift may keep the joystick from centering at 0 or using the full range of position values. The axis number must be an integer from 0 to get_numaxes() - 1. When using gamepads both the control sticks and the analog triggers are usually reported as axes.
   get_numballs()
 get the number of trackballs on a Joystick get_numballs() -> int  Returns the number of trackball devices on a Joystick. These devices work similar to a mouse but they have no absolute position; they only have relative amounts of movement. The pygame.JOYBALLMOTION event will be sent when the trackball is rolled. It will report the amount of movement on the trackball.
   get_ball()
 get the relative position of a trackball get_ball(ball_number) -> x, y  Returns the relative movement of a joystick button. The value is a x, y pair holding the relative movement since the last call to get_ball. The ball number must be an integer from 0 to get_numballs() - 1.
   get_numbuttons()
 get the number of buttons on a Joystick get_numbuttons() -> int  Returns the number of pushable buttons on the joystick. These buttons have a boolean (on or off) state. Buttons generate a pygame.JOYBUTTONDOWN and pygame.JOYBUTTONUP event when they are pressed and released.
   get_button()
 get the current button state get_button(button) -> bool  Returns the current state of a joystick button.
   get_numhats()
 get the number of hat controls on a Joystick get_numhats() -> int  Returns the number of joystick hats on a Joystick. Hat devices are like miniature digital joysticks on a joystick. Each hat has two axes of input. The pygame.JOYHATMOTION event is generated when the hat changes position. The position attribute for the event contains a pair of values that are either -1, 0, or 1. A position of (0, 0) means the hat is centered.
   get_hat()
 get the position of a joystick hat get_hat(hat_number) -> x, y  Returns the current position of a position hat. The position is given as two values representing the x and y position for the hat. (0, 0) means centered. A value of -1 means left/down and a value of 1 means right/up: so (-1, 0) means left; (1, 0) means right; (0, 1) means up; (1, 1) means upper-right; etc. This value is digital, i.e., each coordinate can be -1, 0 or 1 but never in-between. The hat number must be between 0 and get_numhats() - 1.


get_axis()
 get the current position of an axis get_axis(axis_number) -> float  Returns the current position of a joystick axis. The value will range from -1 to 1 with a value of 0 being centered. You may want to take into account some tolerance to handle jitter, and joystick drift may keep the joystick from centering at 0 or using the full range of position values. The axis number must be an integer from 0 to get_numaxes() - 1. When using gamepads both the control sticks and the analog triggers are usually reported as axes.


get_ball()
 get the relative position of a trackball get_ball(ball_number) -> x, y  Returns the relative movement of a joystick button. The value is a x, y pair holding the relative movement since the last call to get_ball. The ball number must be an integer from 0 to get_numballs() - 1.


get_button()
 get the current button state get_button(button) -> bool  Returns the current state of a joystick button.


get_guid() → str
 get the joystick GUID get_guid() -> str  Get the GUID string. This identifies the exact hardware of the joystick device.  New in pygame 2.0.0dev11.


get_hat()
 get the position of a joystick hat get_hat(hat_number) -> x, y  Returns the current position of a position hat. The position is given as two values representing the x and y position for the hat. (0, 0) means centered. A value of -1 means left/down and a value of 1 means right/up: so (-1, 0) means left; (1, 0) means right; (0, 1) means up; (1, 1) means upper-right; etc. This value is digital, i.e., each coordinate can be -1, 0 or 1 but never in-between. The hat number must be between 0 and get_numhats() - 1.


get_id()
 get the device index (deprecated) get_id() -> int  Returns the original device index for this device. This is the same value that was passed to the Joystick() constructor. This method can safely be called while the Joystick is not initialized.  Deprecated since pygame 2.0.0: The original device index is not useful in pygame 2. Use get_instance_id() instead. Will be removed in Pygame 2.1.


get_init()
 check if the Joystick is initialized get_init() -> bool  Return True if the Joystick object is currently initialised.


get_instance_id() → int
 get the joystick instance id get_instance_id() -> int  Get the joystick instance ID. This matches the instance_id field that is given in joystick events.  New in pygame 2.0.0dev11.


get_name()
 get the Joystick system name get_name() -> string  Returns the system name for this joystick device. It is unknown what name the system will give to the Joystick, but it should be a unique name that identifies the device. This method can safely be called while the Joystick is not initialized.


get_numaxes()
 get the number of axes on a Joystick get_numaxes() -> int  Returns the number of input axes are on a Joystick. There will usually be two for the position. Controls like rudders and throttles are treated as additional axes. The pygame.JOYAXISMOTION events will be in the range from -1.0 to 1.0. A value of 0.0 means the axis is centered. Gamepad devices will usually be -1, 0, or 1 with no values in between. Older analog joystick axes will not always use the full -1 to 1 range, and the centered value will be some area around 0. Analog joysticks usually have a bit of noise in their axis, which will generate a lot of rapid small motion events.


get_numballs()
 get the number of trackballs on a Joystick get_numballs() -> int  Returns the number of trackball devices on a Joystick. These devices work similar to a mouse but they have no absolute position; they only have relative amounts of movement. The pygame.JOYBALLMOTION event will be sent when the trackball is rolled. It will report the amount of movement on the trackball.


get_numbuttons()
 get the number of buttons on a Joystick get_numbuttons() -> int  Returns the number of pushable buttons on the joystick. These buttons have a boolean (on or off) state. Buttons generate a pygame.JOYBUTTONDOWN and pygame.JOYBUTTONUP event when they are pressed and released.


get_numhats()
 get the number of hat controls on a Joystick get_numhats() -> int  Returns the number of joystick hats on a Joystick. Hat devices are like miniature digital joysticks on a joystick. Each hat has two axes of input. The pygame.JOYHATMOTION event is generated when the hat changes position. The position attribute for the event contains a pair of values that are either -1, 0, or 1. A position of (0, 0) means the hat is centered.


get_power_level() → str
 get the approximate power status of the device get_power_level() -> str  Get a string giving the power status of the device. One of: empty, low, medium, full, wired, max, or unknown.  New in pygame 2.0.0dev11.


init()
 initialize the Joystick init() -> None  Initialize the joystick, if it has been closed. It is safe to call this even if the joystick is already initialized.  Deprecated since pygame 2.0.0: In future it will not be possible to reinitialise a closed Joystick object. Will be removed in Pygame 2.1.


quit()
 uninitialize the Joystick quit() -> None  Close a Joystick object. After this the pygame event queue will no longer receive events from the device. It is safe to call this more than once.


pygame.joystick.quit()
 Uninitialize the joystick module. quit() -> None  Uninitialize the joystick module. After you call this any existing joystick objects will no longer work. It is safe to call this function more than once.


pygame.key

 pygame module to work with the keyboard  This module contains functions for dealing with the keyboard. The pygame.event queue gets pygame.KEYDOWN and pygame.KEYUP events when the keyboard buttons are pressed and released. Both events have key and mod attributes.

key: an integer ID representing every key on the keyboard
mod: a bitmask of all the modifier keys that were in a pressed state when the event occurred
 The pygame.KEYDOWN event has the additional attributes unicode and scancode.

unicode: a single character string that is the fully translated character entered, this takes into account the shift and composition keys
scancode: the platform-specific key code, which could be different from keyboard to keyboard, but is useful for key selection of weird keys like the multimedia keys
  New in pygame 2.0.0: The pygame.TEXTINPUT event is preferred to the unicode attribute of pygame.KEYDOWN. The attribute text contains the input.  The following is a list of all the constants (from pygame.locals) used to represent keyboard keys. Portability note: The integers for key constants differ between pygame 1 and 2. Always use key constants (K_a) rather than integers directly (97) so that your key handling code works well on both pygame 1 and pygame 2. pygame
Constant      ASCII   Description
---------------------------------
K_BACKSPACE   \b      backspace
K_TAB         \t      tab
K_CLEAR               clear
K_RETURN      \r      return
K_PAUSE               pause
K_ESCAPE      ^[      escape
K_SPACE               space
K_EXCLAIM     !       exclaim
K_QUOTEDBL    "       quotedbl
K_HASH        #       hash
K_DOLLAR      $       dollar
K_AMPERSAND   &       ampersand
K_QUOTE               quote
K_LEFTPAREN   (       left parenthesis
K_RIGHTPAREN  )       right parenthesis
K_ASTERISK    *       asterisk
K_PLUS        +       plus sign
K_COMMA       ,       comma
K_MINUS       -       minus sign
K_PERIOD      .       period
K_SLASH       /       forward slash
K_0           0       0
K_1           1       1
K_2           2       2
K_3           3       3
K_4           4       4
K_5           5       5
K_6           6       6
K_7           7       7
K_8           8       8
K_9           9       9
K_COLON       :       colon
K_SEMICOLON   ;       semicolon
K_LESS        <       less-than sign
K_EQUALS      =       equals sign
K_GREATER     >       greater-than sign
K_QUESTION    ?       question mark
K_AT          @       at
K_LEFTBRACKET [       left bracket
K_BACKSLASH   \       backslash
K_RIGHTBRACKET ]      right bracket
K_CARET       ^       caret
K_UNDERSCORE  _       underscore
K_BACKQUOTE   `       grave
K_a           a       a
K_b           b       b
K_c           c       c
K_d           d       d
K_e           e       e
K_f           f       f
K_g           g       g
K_h           h       h
K_i           i       i
K_j           j       j
K_k           k       k
K_l           l       l
K_m           m       m
K_n           n       n
K_o           o       o
K_p           p       p
K_q           q       q
K_r           r       r
K_s           s       s
K_t           t       t
K_u           u       u
K_v           v       v
K_w           w       w
K_x           x       x
K_y           y       y
K_z           z       z
K_DELETE              delete
K_KP0                 keypad 0
K_KP1                 keypad 1
K_KP2                 keypad 2
K_KP3                 keypad 3
K_KP4                 keypad 4
K_KP5                 keypad 5
K_KP6                 keypad 6
K_KP7                 keypad 7
K_KP8                 keypad 8
K_KP9                 keypad 9
K_KP_PERIOD   .       keypad period
K_KP_DIVIDE   /       keypad divide
K_KP_MULTIPLY *       keypad multiply
K_KP_MINUS    -       keypad minus
K_KP_PLUS     +       keypad plus
K_KP_ENTER    \r      keypad enter
K_KP_EQUALS   =       keypad equals
K_UP                  up arrow
K_DOWN                down arrow
K_RIGHT               right arrow
K_LEFT                left arrow
K_INSERT              insert
K_HOME                home
K_END                 end
K_PAGEUP              page up
K_PAGEDOWN            page down
K_F1                  F1
K_F2                  F2
K_F3                  F3
K_F4                  F4
K_F5                  F5
K_F6                  F6
K_F7                  F7
K_F8                  F8
K_F9                  F9
K_F10                 F10
K_F11                 F11
K_F12                 F12
K_F13                 F13
K_F14                 F14
K_F15                 F15
K_NUMLOCK             numlock
K_CAPSLOCK            capslock
K_SCROLLOCK           scrollock
K_RSHIFT              right shift
K_LSHIFT              left shift
K_RCTRL               right control
K_LCTRL               left control
K_RALT                right alt
K_LALT                left alt
K_RMETA               right meta
K_LMETA               left meta
K_LSUPER              left Windows key
K_RSUPER              right Windows key
K_MODE                mode shift
K_HELP                help
K_PRINT               print screen
K_SYSREQ              sysrq
K_BREAK               break
K_MENU                menu
K_POWER               power
K_EURO                Euro The keyboard also has a list of modifier states (from pygame.locals) that can be assembled by bitwise-ORing them together. pygame
Constant      Description
-------------------------
KMOD_NONE     no modifier keys pressed
KMOD_LSHIFT   left shift
KMOD_RSHIFT   right shift
KMOD_SHIFT    left shift or right shift or both
KMOD_LCTRL    left control
KMOD_RCTRL    right control
KMOD_CTRL     left control or right control or both
KMOD_LALT     left alt
KMOD_RALT     right alt
KMOD_ALT      left alt or right alt or both
KMOD_LMETA    left meta
KMOD_RMETA    right meta
KMOD_META     left meta or right meta or both
KMOD_CAPS     caps lock
KMOD_NUM      num lock
KMOD_MODE     AltGr The modifier information is contained in the mod attribute of the pygame.KEYDOWN and pygame.KEYUP events. The mod attribute is a bitmask of all the modifier keys that were in a pressed state when the event occurred. The modifier information can be decoded using a bitwise AND (except for KMOD_NONE, which should be compared using equals ==). For example: for event in pygame.event.get():
    if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
        if event.mod == pygame.KMOD_NONE:
            print('No modifier keys were in a pressed state when this '
                  'event occurred.')
        else:
            if event.mod & pygame.KMOD_LSHIFT:
                print('Left shift was in a pressed state when this event '
                      'occurred.')
            if event.mod & pygame.KMOD_RSHIFT:
                print('Right shift was in a pressed state when this event '
                      'occurred.')
            if event.mod & pygame.KMOD_SHIFT:
                print('Left shift or right shift or both were in a '
                      'pressed state when this event occurred.')   pygame.key.get_focused()
 true if the display is receiving keyboard input from the system get_focused() -> bool  Returns True when the display window has keyboard focus from the system. If the display needs to ensure it does not lose keyboard focus, it can use pygame.event.set_grab() to grab all input.
   pygame.key.get_pressed()
 get the state of all keyboard buttons get_pressed() -> bools  Returns a sequence of boolean values representing the state of every key on the keyboard. Use the key constant values to index the array. A True value means the that button is pressed.  Note Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. There is no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the pygame.event queue for this functionality.
   pygame.key.get_mods()
 determine which modifier keys are being held get_mods() -> int  Returns a single integer representing a bitmask of all the modifier keys being held. Using bitwise operators you can test if specific modifier keys are pressed.
   pygame.key.set_mods()
 temporarily set which modifier keys are pressed set_mods(int) -> None  Create a bitmask of the modifier key constants you want to impose on your program.
   pygame.key.set_repeat()
 control how held keys are repeated set_repeat() -> None set_repeat(delay) -> None set_repeat(delay, interval) -> None  When the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. The delay parameter is the number of milliseconds before the first repeated pygame.KEYDOWN event will be sent. After that, another pygame.KEYDOWN event will be sent every interval milliseconds. If a delay value is provided and an interval value is not provided or is 0, then the interval will be set to the same value as delay. To disable key repeat call this function with no arguments or with delay set to 0. When pygame is initialized the key repeat is disabled.
Raises:

ValueError -- if delay or interval is < 0     Changed in pygame 2.0.0: A ValueError is now raised (instead of a pygame.error) if delay or interval is < 0.
   pygame.key.get_repeat()
 see how held keys are repeated get_repeat() -> (delay, interval)  Get the delay and interval keyboard repeat values. Refer to pygame.key.set_repeat() for a description of these values.  New in pygame 1.8.
   pygame.key.name()
 get the name of a key identifier name(key) -> string  Get the descriptive name of the button from a keyboard button id constant.
   pygame.key.key_code()
 get the key identifier from a key name key_code(name=string) -> int  Get the key identifier code from the descriptive name of the key. This returns an integer matching one of the K_* keycodes. For example: >>> pygame.key.key_code("return") == pygame.K_RETURN
True
>>> pygame.key.key_code("0") == pygame.K_0
True
>>> pygame.key.key_code("space") == pygame.K_SPACE
True
Raises:

ValueError -- if the key name is not known.
NotImplementedError -- if used with SDL 1.       New in pygame 2.0.0.
   pygame.key.start_text_input()
 start handling Unicode text input events start_text_input() -> None  Start receiving pygame.TEXTEDITING and pygame.TEXTINPUT events. A pygame.TEXTEDITING event is received when an IME composition is started or changed. It contains the composition text, length, and editing start position within the composition (attributes text, length, and start, respectively). When the composition is committed (or non-IME input is received), a pygame.TEXTINPUT event is generated. Text input events handling is on by default.  New in pygame 2.0.0.
   pygame.key.stop_text_input()
 stop handling Unicode text input events stop_text_input() -> None  Stop receiving pygame.TEXTEDITING and pygame.TEXTINPUT events. Text input events handling is on by default  New in pygame 2.0.0.
   pygame.key.set_text_input_rect()
 controls the position of the candidate list set_text_input_rect(Rect) -> None  This sets the rectangle used for typing with an IME. It controls where the candidate list will open, if supported.  New in pygame 2.0.0.


pygame.key.get_focused()
 true if the display is receiving keyboard input from the system get_focused() -> bool  Returns True when the display window has keyboard focus from the system. If the display needs to ensure it does not lose keyboard focus, it can use pygame.event.set_grab() to grab all input.


pygame.key.get_mods()
 determine which modifier keys are being held get_mods() -> int  Returns a single integer representing a bitmask of all the modifier keys being held. Using bitwise operators you can test if specific modifier keys are pressed.


pygame.key.get_pressed()
 get the state of all keyboard buttons get_pressed() -> bools  Returns a sequence of boolean values representing the state of every key on the keyboard. Use the key constant values to index the array. A True value means the that button is pressed.  Note Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. There is no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the pygame.event queue for this functionality.


pygame.key.get_repeat()
 see how held keys are repeated get_repeat() -> (delay, interval)  Get the delay and interval keyboard repeat values. Refer to pygame.key.set_repeat() for a description of these values.  New in pygame 1.8.


pygame.key.key_code()
 get the key identifier from a key name key_code(name=string) -> int  Get the key identifier code from the descriptive name of the key. This returns an integer matching one of the K_* keycodes. For example: >>> pygame.key.key_code("return") == pygame.K_RETURN
True
>>> pygame.key.key_code("0") == pygame.K_0
True
>>> pygame.key.key_code("space") == pygame.K_SPACE
True
Raises:

ValueError -- if the key name is not known.
NotImplementedError -- if used with SDL 1.       New in pygame 2.0.0.


pygame.key.name()
 get the name of a key identifier name(key) -> string  Get the descriptive name of the button from a keyboard button id constant.


pygame.key.set_mods()
 temporarily set which modifier keys are pressed set_mods(int) -> None  Create a bitmask of the modifier key constants you want to impose on your program.


pygame.key.set_repeat()
 control how held keys are repeated set_repeat() -> None set_repeat(delay) -> None set_repeat(delay, interval) -> None  When the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. The delay parameter is the number of milliseconds before the first repeated pygame.KEYDOWN event will be sent. After that, another pygame.KEYDOWN event will be sent every interval milliseconds. If a delay value is provided and an interval value is not provided or is 0, then the interval will be set to the same value as delay. To disable key repeat call this function with no arguments or with delay set to 0. When pygame is initialized the key repeat is disabled.
Raises:

ValueError -- if delay or interval is < 0     Changed in pygame 2.0.0: A ValueError is now raised (instead of a pygame.error) if delay or interval is < 0.


pygame.key.set_text_input_rect()
 controls the position of the candidate list set_text_input_rect(Rect) -> None  This sets the rectangle used for typing with an IME. It controls where the candidate list will open, if supported.  New in pygame 2.0.0.


pygame.key.start_text_input()
 start handling Unicode text input events start_text_input() -> None  Start receiving pygame.TEXTEDITING and pygame.TEXTINPUT events. A pygame.TEXTEDITING event is received when an IME composition is started or changed. It contains the composition text, length, and editing start position within the composition (attributes text, length, and start, respectively). When the composition is committed (or non-IME input is received), a pygame.TEXTINPUT event is generated. Text input events handling is on by default.  New in pygame 2.0.0.


pygame.key.stop_text_input()
 stop handling Unicode text input events stop_text_input() -> None  Stop receiving pygame.TEXTEDITING and pygame.TEXTINPUT events. Text input events handling is on by default  New in pygame 2.0.0.


pygame.locals

 pygame constants  This module contains various constants used by pygame. Its contents are automatically placed in the pygame module namespace. However, an application can use pygame.locals to include only the pygame constants with a from
pygame.locals import *. Detailed descriptions of the various constants can be found throughout the pygame documentation. Here are the locations of some of them.
 The pygame.display module contains flags like HWSURFACE used by pygame.display.set_mode(). The pygame.event module contains the various event types. The pygame.key module lists the keyboard constants and modifiers (K_* and MOD_*) relating to the key and mod attributes of the KEYDOWN and KEYUP events. The pygame.time module defines TIMER_RESOLUTION.


pygame.mask

 pygame module for image masks.  Useful for fast pixel perfect collision detection. A mask uses 1 bit per-pixel to store which parts collide.  New in pygame 1.8.    pygame.mask.from_surface()
 Creates a Mask from the given surface from_surface(Surface) -> Mask from_surface(Surface, threshold=127) -> Mask  Creates a Mask object from the given surface by setting all the opaque pixels and not setting the transparent pixels. If the surface uses a color-key, then it is used to decide which bits in the resulting mask are set. All the pixels that are not equal to the color-key are set and the pixels equal to the color-key are not set. If a color-key is not used, then the alpha value of each pixel is used to decide which bits in the resulting mask are set. All the pixels that have an alpha value greater than the threshold parameter are set and the pixels with an alpha value less than or equal to the threshold are not set.
Parameters:

surface (Surface) -- the surface to create the mask from
threshold (int) -- (optional) the alpha threshold (default is 127) to compare with each surface pixel's alpha value, if the surface is color-keyed this parameter is ignored
Returns:

a newly created Mask object from the given surface
Return type:

Mask      Note This function is used to create the masks for pygame.sprite.collide_mask().
   pygame.mask.from_threshold()
 Creates a mask by thresholding Surfaces from_threshold(Surface, color) -> Mask from_threshold(Surface, color, threshold=(0, 0, 0, 255), othersurface=None, palette_colors=1) -> Mask  This is a more featureful method of getting a Mask from a surface. If the optional othersurface is not used, all the pixels within the threshold of the color parameter are set in the resulting mask. If the optional othersurface is used, every pixel in the first surface that is within the threshold of the corresponding pixel in othersurface is set in the resulting mask.
Parameters:

surface (Surface) -- the surface to create the mask from
color (Color or int or tuple(int, int, int, [int]) or list[int, int, int, [int]]) -- color used to check if the surface's pixels are within the given threshold range, this parameter is ignored if the optional othersurface parameter is supplied
threshold (Color or int or tuple(int, int, int, [int]) or list[int, int, int, [int]]) -- (optional) the threshold range used to check the difference between two colors (default is (0, 0, 0, 255))
othersurface (Surface) -- (optional) used to check whether the pixels of the first surface are within the given threshold range of the pixels from this surface (default is None)
palette_colors (int) -- (optional) indicates whether to use the palette colors or not, a nonzero value causes the palette colors to be used and a 0 causes them not to be used (default is 1)
Returns:

a newly created Mask object from the given surface
Return type:

Mask
   pygame.mask.Mask
 pygame object for representing 2D bitmasks Mask(size=(width, height)) -> Mask Mask(size=(width, height), fill=False) -> Mask  A Mask object is used to represent a 2D bitmask. Each bit in the mask represents a pixel. 1 is used to indicate a set bit and 0 is used to indicate an unset bit. Set bits in a mask can be used to detect collisions with other masks and their set bits. A filled mask has all of its bits set to 1, conversely an unfilled/cleared/empty mask has all of its bits set to 0. Masks can be created unfilled (default) or filled by using the fill parameter. Masks can also be cleared or filled using the pygame.mask.Mask.clear() and pygame.mask.Mask.fill() methods respectively. A mask's coordinates start in the top left corner at (0, 0) just like pygame.Surface. Individual bits can be accessed using the pygame.mask.Mask.get_at() and pygame.mask.Mask.set_at() methods. The methods overlap(), overlap_area(), overlap_mask(), draw(), erase(), and convolve() use an offset parameter to indicate the offset of another mask's top left corner from the calling mask's top left corner. The calling mask's top left corner is considered to be the origin (0, 0). Offsets are a tuple or list of 2 integer values (x_offset, y_offset). Positive and negative offset values are supported. 0 to x (x_offset)
           :    :
   0 ..... +----:---------+
   to      |    :         |
   y .......... +-----------+
(y_offset) |    | othermask |
           |    +-----------+
           | calling_mask |
           +--------------+
Parameters:

size (tuple(int, int) or list[int, int]) -- the dimensions of the mask (width and height)
fill (bool) -- (optional) create an unfilled mask (default: False) or filled mask (True)
Returns:

a newly created Mask object
Return type:

Mask      Changed in pygame 2.0.0: Shallow copy support added. The Mask class supports the special method __copy__() and shallow copying via copy.copy(mask).   Changed in pygame 2.0.0: Subclassing support added. The Mask class can be used as a base class.   Changed in pygame 1.9.5: Added support for keyword arguments.   Changed in pygame 1.9.5: Added the optional keyword parameter fill.   Changed in pygame 1.9.5: Added support for masks with a width and/or a height of 0.    copy()
 Returns a new copy of the mask copy() -> Mask
Returns:
a new copy of this mask, the new mask will have the same width, height, and set/unset bits as the original
Return type:
Mask     Note If a mask subclass needs to copy any instance specific attributes then it should override the __copy__() method. The overridden __copy__() method needs to call super().__copy__() and then copy the required data as in the following example code. class SubMask(pygame.mask.Mask):
    def __copy__(self):
        new_mask = super().__copy__()
        # Do any SubMask attribute copying here.
        return new_mask   New in pygame 2.0.0.
   get_size()
 Returns the size of the mask get_size() -> (width, height)
Returns:
the size of the mask, (width, height)
Return type:
tuple(int, int)
   get_rect()
 Returns a Rect based on the size of the mask get_rect(**kwargs) -> Rect  Returns a new pygame.Rect() object based on the size of this mask. The rect's default position will be (0, 0) and its default width and height will be the same as this mask's. The rect's attributes can be altered via pygame.Rect() attribute keyword arguments/values passed into this method. As an example, a_mask.get_rect(center=(10, 5)) would create a pygame.Rect() based on the mask's size centered at the given position.
Parameters:

kwargs (dict) -- pygame.Rect() attribute keyword arguments/values that will be applied to the rect
Returns:
a new pygame.Rect() object based on the size of this mask with any pygame.Rect() attribute keyword arguments/values applied to it
Return type:
Rect     New in pygame 2.0.0.
   get_at()
 Gets the bit at the given position get_at((x, y)) -> int
Parameters:

pos (tuple(int, int) or list[int, int]) -- the position of the bit to get
Returns:
1 if the bit is set, 0 if the bit is not set
Return type:
int
Raises:

IndexError -- if the position is outside of the mask's bounds
   set_at()
 Sets the bit at the given position set_at((x, y)) -> None set_at((x, y), value=1) -> None
Parameters:

pos (tuple(int, int) or list[int, int]) -- the position of the bit to set
value (int) -- any nonzero int will set the bit to 1, 0 will set the bit to 0 (default is 1)
Returns:

None
Return type:

NoneType
Raises:

IndexError -- if the position is outside of the mask's bounds
   overlap()
 Returns the point of intersection overlap(othermask, offset) -> (x, y) overlap(othermask, offset) -> None  Returns the first point of intersection encountered between this mask and othermask. A point of intersection is 2 overlapping set bits. The current algorithm searches the overlapping area in sizeof(unsigned long int) * CHAR_BIT bit wide column blocks (the value of sizeof(unsigned long int) * CHAR_BIT is platform dependent, for clarity it will be referred to as W). Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (W - 1, 0)) then continues to the next row ((0, 1) to (W - 1, 1)). Once this entire column block is checked, it continues to the next one (W to 2 * W - 1). This is repeated until it finds a point of intersection or the entire overlapping area is checked.
Parameters:

othermask (Mask) -- the other mask to overlap with this mask
offset (tuple(int, int) or list[int, int]) -- the offset of othermask from this mask, for more details refer to the Mask offset notes

Returns:

point of intersection or None if no intersection
Return type:

tuple(int, int) or NoneType
   overlap_area()
 Returns the number of overlapping set bits overlap_area(othermask, offset) -> numbits  Returns the number of overlapping set bits between between this mask and othermask. This can be useful for collision detection. An approximate collision normal can be found by calculating the gradient of the overlapping area through the finite difference. dx = mask.overlap_area(othermask, (x + 1, y)) - mask.overlap_area(othermask, (x - 1, y))
dy = mask.overlap_area(othermask, (x, y + 1)) - mask.overlap_area(othermask, (x, y - 1))
Parameters:

othermask (Mask) -- the other mask to overlap with this mask
offset (tuple(int, int) or list[int, int]) -- the offset of othermask from this mask, for more details refer to the Mask offset notes

Returns:

the number of overlapping set bits
Return type:

int
   overlap_mask()
 Returns a mask of the overlapping set bits overlap_mask(othermask, offset) -> Mask  Returns a Mask, the same size as this mask, containing the overlapping set bits between this mask and othermask.
Parameters:

othermask (Mask) -- the other mask to overlap with this mask
offset (tuple(int, int) or list[int, int]) -- the offset of othermask from this mask, for more details refer to the Mask offset notes

Returns:

a newly created Mask with the overlapping bits set
Return type:

Mask
   fill()
 Sets all bits to 1 fill() -> None  Sets all bits in the mask to 1.
Returns:
None
Return type:
NoneType
   clear()
 Sets all bits to 0 clear() -> None  Sets all bits in the mask to 0.
Returns:
None
Return type:
NoneType
   invert()
 Flips all the bits invert() -> None  Flips all of the bits in the mask. All the set bits are cleared to 0 and all the unset bits are set to 1.
Returns:
None
Return type:
NoneType
   scale()
 Resizes a mask scale((width, height)) -> Mask  Creates a new Mask of the requested size with its bits scaled from this mask.
Parameters:

size (tuple(int, int) or list[int, int]) -- the width and height (size) of the mask to create
Returns:
a new Mask object with its bits scaled from this mask
Return type:
Mask
Raises:

ValueError -- if width < 0 or height < 0

   draw()
 Draws a mask onto another draw(othermask, offset) -> None  Performs a bitwise OR, drawing othermask onto this mask.
Parameters:

othermask (Mask) -- the mask to draw onto this mask
offset (tuple(int, int) or list[int, int]) -- the offset of othermask from this mask, for more details refer to the Mask offset notes

Returns:

None
Return type:

NoneType
   erase()
 Erases a mask from another erase(othermask, offset) -> None  Erases (clears) all bits set in othermask from this mask.
Parameters:

othermask (Mask) -- the mask to erase from this mask
offset (tuple(int, int) or list[int, int]) -- the offset of othermask from this mask, for more details refer to the Mask offset notes

Returns:

None
Return type:

NoneType
   count()
 Returns the number of set bits count() -> bits
Returns:
the number of set bits in the mask
Return type:
int
   centroid()
 Returns the centroid of the set bits centroid() -> (x, y)  Finds the centroid (the center mass of the set bits) for this mask.
Returns:
a coordinate tuple indicating the centroid of the mask, it will return (0, 0) if the mask has no bits set
Return type:
tuple(int, int)
   angle()
 Returns the orientation of the set bits angle() -> theta  Finds the approximate orientation (from -90 to 90 degrees) of the set bits in the mask. This works best if performed on a mask with only one connected component.
Returns:
the orientation of the set bits in the mask, it will return 0.0 if the mask has no bits set
Return type:
float     Note See connected_component() for details on how a connected component is calculated.
   outline()
 Returns a list of points outlining an object outline() -> [(x, y), ...] outline(every=1) -> [(x, y), ...]  Returns a list of points of the outline of the first connected component encountered in the mask. To find a connected component, the mask is searched per row (left to right) starting in the top left corner. The every optional parameter skips set bits in the outline. For example, setting it to 10 would return a list of every 10th set bit in the outline.
Parameters:

every (int) -- (optional) indicates the number of bits to skip over in the outline (default is 1)
Returns:
a list of points outlining the first connected component encountered, an empty list is returned if the mask has no bits set
Return type:
list[tuple(int, int)]     Note See connected_component() for details on how a connected component is calculated.
   convolve()
 Returns the convolution of this mask with another mask convolve(othermask) -> Mask convolve(othermask, outputmask=None, offset=(0, 0)) -> Mask  Convolve this mask with the given othermask.
Parameters:

othermask (Mask) -- mask to convolve this mask with
outputmask (Mask or NoneType) -- (optional) mask for output (default is None)
offset (tuple(int, int) or list[int, int]) -- the offset of othermask from this mask, (default is (0, 0))
Returns:

a Mask with the (i - offset[0], j - offset[1]) bit set, if shifting othermask (such that its bottom right corner is at (i, j)) causes it to overlap with this mask If an outputmask is specified, the output is drawn onto it and it is returned. Otherwise a mask of size (MAX(0, width + othermask's
width - 1), MAX(0, height + othermask's height - 1)) is created and returned.
Return type:

Mask
   connected_component()
 Returns a mask containing a connected component connected_component() -> Mask connected_component((x, y)) -> Mask  A connected component is a group (1 or more) of connected set bits (orthogonally and diagonally). The SAUF algorithm, which checks 8 point connectivity, is used to find a connected component in the mask. By default this method will return a Mask containing the largest connected component in the mask. Optionally, a bit coordinate can be specified and the connected component containing it will be returned. If the bit at the given location is not set, the returned Mask will be empty (no bits set).
Parameters:

pos (tuple(int, int) or list[int, int]) -- (optional) selects the connected component that contains the bit at this position
Returns:
a Mask object (same size as this mask) with the largest connected component from this mask, if this mask has no bits set then an empty mask will be returnedIf the pos parameter is provided then the mask returned will have the connected component that contains this position. An empty mask will be returned if the pos parameter selects an unset bit.
Return type:
Mask
Raises:

IndexError -- if the optional pos parameter is outside of the mask's bounds
   connected_components()
 Returns a list of masks of connected components connected_components() -> [Mask, ...] connected_components(min=0) -> [Mask, ...]  Provides a list containing a Mask object for each connected component.
Parameters:

min (int) -- (optional) indicates the minimum number of bits (to filter out noise) per connected component (default is 0, which equates to no minimum and is equivalent to setting it to 1, as a connected component must have at least 1 bit set)
Returns:
a list containing a Mask object for each connected component, an empty list is returned if the mask has no bits set
Return type:
list[Mask]     Note See connected_component() for details on how a connected component is calculated.
   get_bounding_rects()
 Returns a list of bounding rects of connected components get_bounding_rects() -> [Rect, ...]  Provides a list containing a bounding rect for each connected component.
Returns:
a list containing a bounding rect for each connected component, an empty list is returned if the mask has no bits set
Return type:
list[Rect]     Note See connected_component() for details on how a connected component is calculated.
   to_surface()
 Returns a surface with the mask drawn on it to_surface() -> Surface to_surface(surface=None, setsurface=None, unsetsurface=None, setcolor=(255, 255, 255, 255), unsetcolor=(0, 0, 0, 255), dest=(0, 0)) -> Surface  Draws this mask on the given surface. Set bits (bits set to 1) and unset bits (bits set to 0) can be drawn onto a surface.
Parameters:

surface (Surface or None) -- (optional) Surface to draw mask onto, if no surface is provided one will be created (default is None, which will cause a surface with the parameters Surface(size=mask.get_size(), flags=SRCALPHA, depth=32) to be created, drawn on, and returned)
setsurface (Surface or None) -- (optional) use this surface's color values to draw set bits (default is None), if this surface is smaller than the mask any bits outside its bounds will use the setcolor value
unsetsurface (Surface or None) -- (optional) use this surface's color values to draw unset bits (default is None), if this surface is smaller than the mask any bits outside its bounds will use the unsetcolor value
setcolor (Color or str or int or tuple(int, int, int, [int]) or list(int, int, int, [int]) or None) -- (optional) color to draw set bits (default is (255, 255, 255, 255), white), use None to skip drawing the set bits, the setsurface parameter (if set) will takes precedence over this parameter
unsetcolor (Color or str or int or tuple(int, int, int, [int]) or list(int, int, int, [int]) or None) -- (optional) color to draw unset bits (default is (0, 0, 0, 255), black), use None to skip drawing the unset bits, the unsetsurface parameter (if set) will takes precedence over this parameter
dest (Rect or tuple(int, int) or list(int, int) or Vector2(int, int)) -- (optional) surface destination of where to position the topleft corner of the mask being drawn (default is (0, 0)), if a Rect is used as the dest parameter, its x and y attributes will be used as the destination, NOTE1: rects with a negative width or height value will not be normalized before using their x and y values, NOTE2: this destination value is only used to position the mask on the surface, it does not offset the setsurface and unsetsurface from the mask, they are always aligned with the mask (i.e. position (0, 0) on the mask always corresponds to position (0, 0) on the setsurface and unsetsurface)
Returns:

the surface parameter (or a newly created surface if no surface parameter was provided) with this mask drawn on it
Return type:

Surface
Raises:

ValueError -- if the setsurface parameter or unsetsurface parameter does not have the same format (bytesize/bitsize/alpha) as the surface parameter      Note To skip drawing the set bits, both setsurface and setcolor must be None. The setsurface parameter defaults to None, but setcolor defaults to a color value and therefore must be set to None.   Note To skip drawing the unset bits, both unsetsurface and unsetcolor must be None. The unsetsurface parameter defaults to None, but unsetcolor defaults to a color value and therefore must be set to None.   New in pygame 2.0.0.


pygame.mask.from_surface()
 Creates a Mask from the given surface from_surface(Surface) -> Mask from_surface(Surface, threshold=127) -> Mask  Creates a Mask object from the given surface by setting all the opaque pixels and not setting the transparent pixels. If the surface uses a color-key, then it is used to decide which bits in the resulting mask are set. All the pixels that are not equal to the color-key are set and the pixels equal to the color-key are not set. If a color-key is not used, then the alpha value of each pixel is used to decide which bits in the resulting mask are set. All the pixels that have an alpha value greater than the threshold parameter are set and the pixels with an alpha value less than or equal to the threshold are not set.
Parameters:

surface (Surface) -- the surface to create the mask from
threshold (int) -- (optional) the alpha threshold (default is 127) to compare with each surface pixel's alpha value, if the surface is color-keyed this parameter is ignored
Returns:

a newly created Mask object from the given surface
Return type:

Mask      Note This function is used to create the masks for pygame.sprite.collide_mask().


pygame.mask.from_threshold()
 Creates a mask by thresholding Surfaces from_threshold(Surface, color) -> Mask from_threshold(Surface, color, threshold=(0, 0, 0, 255), othersurface=None, palette_colors=1) -> Mask  This is a more featureful method of getting a Mask from a surface. If the optional othersurface is not used, all the pixels within the threshold of the color parameter are set in the resulting mask. If the optional othersurface is used, every pixel in the first surface that is within the threshold of the corresponding pixel in othersurface is set in the resulting mask.
Parameters:

surface (Surface) -- the surface to create the mask from
color (Color or int or tuple(int, int, int, [int]) or list[int, int, int, [int]]) -- color used to check if the surface's pixels are within the given threshold range, this parameter is ignored if the optional othersurface parameter is supplied
threshold (Color or int or tuple(int, int, int, [int]) or list[int, int, int, [int]]) -- (optional) the threshold range used to check the difference between two colors (default is (0, 0, 0, 255))
othersurface (Surface) -- (optional) used to check whether the pixels of the first surface are within the given threshold range of the pixels from this surface (default is None)
palette_colors (int) -- (optional) indicates whether to use the palette colors or not, a nonzero value causes the palette colors to be used and a 0 causes them not to be used (default is 1)
Returns:

a newly created Mask object from the given surface
Return type:

Mask