doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
pygame.mixer.music.get_endevent() get the event a channel sends when playback stops get_endevent() -> type Returns the event type to be sent every time the music finishes playback. If there is no endevent the function returns pygame.NOEVENT.
pygame.ref.music#pygame.mixer.music.get_endevent
pygame.mixer.music.get_pos() get the music play time get_pos() -> time This gets the number of milliseconds that the music has been playing for. The returned time only represents how long the music has been playing; it does not take into account any starting position offsets.
pygame.ref.music#pygame.mixer.music.get_pos
pygame.mixer.music.get_volume() get the music volume get_volume() -> value Returns the current volume for the mixer. The value will be between 0.0 and 1.0.
pygame.ref.music#pygame.mixer.music.get_volume
pygame.mixer.music.load() Load a music file for playback load(filename) -> None load(object) -> None This will load a music filename/file object and prepare it for playback. If a music stream is already playing it will be stopped. This does not start the music playing.
pygame.ref.music#pygame.mixer.music.load
pygame.mixer.music.pause() temporarily stop music playback pause() -> None Temporarily stop playback of the music stream. It can be resumed with the pygame.mixer.music.unpause() function.
pygame.ref.music#pygame.mixer.music.pause
pygame.mixer.music.play() Start the playback of the music stream play(loops=0, start=0.0, fade_ms = 0) -> None This will play the loaded music stream. If the music is already playing it will be restarted. loops is an optional integer argument, which is 0 by default, it tells how many times to repeat the music. The music repeats indefinately if this argument is set to -1. start is an optional float argument, which is 0.0 by default, which denotes the position in time, the music starts playing from. The starting position depends on the format of the music played. MP3 and OGG use the position as time in seconds. For mp3s the start time position selected may not be accurate as things like variable bit rate encoding and ID3 tags can throw off the timing calculations. For MOD music it is the pattern order number. Passing a start position will raise a NotImplementedError if the start position cannot be set. fade_ms is an optional integer argument, which is 0 by default, makes the music start playing at 0 volume and fade up to full volume over the given time. The sample may end before the fade-in is complete. Changed in pygame 2.0.0: Added optional fade_ms argument
pygame.ref.music#pygame.mixer.music.play
pygame.mixer.music.queue() queue a sound file to follow the current queue(filename) -> None This will load a sound file and queue it. A queued sound file will begin as soon as the current sound naturally ends. Only one sound can be queued at a time. Queuing a new sound while another sound is queued will result in the new sound becoming the queued sound. Also, if the current sound is ever stopped or changed, the queued sound will be lost. The following example will play music by Bach six times, then play music by Mozart once: pygame.mixer.music.load('bach.ogg') pygame.mixer.music.play(5) # Plays six times, not five! pygame.mixer.music.queue('mozart.ogg')
pygame.ref.music#pygame.mixer.music.queue
pygame.mixer.music.rewind() restart music rewind() -> None Resets playback of the current music to the beginning.
pygame.ref.music#pygame.mixer.music.rewind
pygame.mixer.music.set_endevent() have the music send an event when playback stops set_endevent() -> None set_endevent(type) -> None This causes pygame to signal (by means of the event queue) when the music is done playing. The argument determines the type of event that will be queued. The event will be queued every time the music finishes, not just the first time. To stop the event from being queued, call this method with no argument.
pygame.ref.music#pygame.mixer.music.set_endevent
pygame.mixer.music.set_pos() set position to play from set_pos(pos) -> None This sets the position in the music file where playback will start. The meaning of "pos", a float (or a number that can be converted to a float), depends on the music format. For MOD files, pos is the integer pattern number in the module. For OGG it is the absolute position, in seconds, from the beginning of the sound. For MP3 files, it is the relative position, in seconds, from the current position. For absolute positioning in an MP3 file, first call rewind(). Other file formats are unsupported. Newer versions of SDL_mixer have better positioning support than earlier ones. An SDLError is raised if a particular format does not support positioning. Function set_pos() calls underlining SDL_mixer function Mix_SetMusicPosition. New in pygame 1.9.2.
pygame.ref.music#pygame.mixer.music.set_pos
pygame.mixer.music.set_volume() set the music volume set_volume(volume) -> None Set the volume of the music playback. The volume argument is a float between 0.0 and 1.0 that sets volume. When new music is loaded the volume is reset to full volume.
pygame.ref.music#pygame.mixer.music.set_volume
pygame.mixer.music.stop() stop the music playback stop() -> None Stops the music playback if it is currently playing. It Won't Unload the music.
pygame.ref.music#pygame.mixer.music.stop
pygame.mixer.music.unload() Unload the currently loaded music to free up resources unload() -> None This closes resources like files for any music that may be loaded. New in pygame 2.0.0.
pygame.ref.music#pygame.mixer.music.unload
pygame.mixer.music.unpause() resume paused music unpause() -> None This will resume the playback of a music stream after it has been paused.
pygame.ref.music#pygame.mixer.music.unpause
pygame.mixer.pause() temporarily stop playback of all sound channels pause() -> None This will temporarily stop all playback on the active mixer channels. The playback can later be resumed with pygame.mixer.unpause()
pygame.ref.mixer#pygame.mixer.pause
pygame.mixer.pre_init() preset the mixer init arguments pre_init(frequency=44100, size=-16, channels=2, buffer=512, devicename=None) -> None Call pre_init to change the defaults used when the real pygame.mixer.init() is called. Keyword arguments are accepted. The best way to set custom mixer playback values is to call pygame.mixer.pre_init() before calling the top level pygame.init(). For backward compatibility argument values of zero are replaced with the startup defaults. Changed in pygame 1.8: The default buffersize was changed from 1024 to 3072. Changed in pygame 1.9.1: The default buffersize was changed from 3072 to 4096. Changed in pygame 2.0.0: The default buffersize was changed from 4096 to 512. The default frequency changed to 44100 from 22050.
pygame.ref.mixer#pygame.mixer.pre_init
pygame.mixer.quit() uninitialize the mixer quit() -> None This will uninitialize pygame.mixer. All playback will stop and any loaded Sound objects may not be compatible with the mixer if it is reinitialized later.
pygame.ref.mixer#pygame.mixer.quit
pygame.mixer.set_num_channels() set the total number of playback channels set_num_channels(count) -> None Sets the number of available channels for the mixer. The default value is 8. The value can be increased or decreased. If the value is decreased, sounds playing on the truncated channels are stopped.
pygame.ref.mixer#pygame.mixer.set_num_channels
pygame.mixer.set_reserved() reserve channels from being automatically used set_reserved(count) -> None The mixer can reserve any number of channels that will not be automatically selected for playback by Sounds. If sounds are currently playing on the reserved channels they will not be stopped. This allows the application to reserve a specific number of channels for important sounds that must not be dropped or have a guaranteed channel to play on.
pygame.ref.mixer#pygame.mixer.set_reserved
pygame.mixer.Sound Create a new Sound object from a file or buffer object Sound(filename) -> Sound Sound(file=filename) -> Sound Sound(buffer) -> Sound Sound(buffer=buffer) -> Sound Sound(object) -> Sound Sound(file=object) -> Sound Sound(array=object) -> Sound Load a new sound buffer from a filename, a python file object or a readable buffer object. Limited resampling will be performed to help the sample match the initialize arguments for the mixer. A Unicode string can only be a file pathname. A Python 2.x string or a Python 3.x bytes object can be either a pathname or a buffer object. Use the 'file' or 'buffer' keywords to avoid ambiguity; otherwise Sound may guess wrong. If the array keyword is used, the object is expected to export a version 3, C level array interface or, for Python 2.6 or later, a new buffer interface (The object is checked for a buffer interface first.) The Sound object represents actual sound sample data. Methods that change the state of the Sound object will the all instances of the Sound playback. A Sound object also exports an array interface, and, for Python 2.6 or later, a new buffer interface. The Sound can be loaded from an OGG audio file or from an uncompressed WAV. Note: The buffer will be copied internally, no data will be shared between it and the Sound object. For now buffer and array support is consistent with sndarray.make_sound for Numeric arrays, in that sample sign and byte order are ignored. This will change, either by correctly handling sign and byte order, or by raising an exception when different. Also, source samples are truncated to fit the audio sample size. This will not change. New in pygame 1.8: pygame.mixer.Sound(buffer) New in pygame 1.9.2: pygame.mixer.Sound keyword arguments and array interface support play() begin sound playback play(loops=0, maxtime=0, fade_ms=0) -> Channel Begin playback of the Sound (i.e., on the computer's speakers) on an available Channel. This will forcibly select a Channel, so playback may cut off a currently playing sound if necessary. The loops argument controls how many times the sample will be repeated after being played the first time. A value of 5 means that the sound will be played once, then repeated five times, and so is played a total of six times. The default value (zero) means the Sound is not repeated, and so is only played once. If loops is set to -1 the Sound will loop indefinitely (though you can still call stop() to stop it). The maxtime argument can be used to stop playback after a given number of milliseconds. The fade_ms argument will make the sound start playing at 0 volume and fade up to full volume over the time given. The sample may end before the fade-in is complete. This returns the Channel object for the channel that was selected. stop() stop sound playback stop() -> None This will stop the playback of this Sound on any active Channels. fadeout() stop sound playback after fading out fadeout(time) -> None This will stop playback of the sound after fading it out over the time argument in milliseconds. The Sound will fade and stop on all actively playing channels. set_volume() set the playback volume for this Sound set_volume(value) -> None This will set the playback volume (loudness) for this Sound. This will immediately affect the Sound if it is playing. It will also affect any future playback of this Sound. Parameters: value (float) -- volume in the range of 0.0 to 1.0 (inclusive) If value < 0.0, the volume will not be changed If value > 1.0, the volume will be set to 1.0 get_volume() get the playback volume get_volume() -> value Return a value from 0.0 to 1.0 representing the volume for this Sound. get_num_channels() count how many times this Sound is playing get_num_channels() -> count Return the number of active channels this sound is playing on. get_length() get the length of the Sound get_length() -> seconds Return the length of this Sound in seconds. get_raw() return a bytestring copy of the Sound samples. get_raw() -> bytes Return a copy of the Sound object buffer as a bytes (for Python 3.x) or str (for Python 2.x) object. New in pygame 1.9.2.
pygame.ref.mixer#pygame.mixer.Sound
fadeout() stop sound playback after fading out fadeout(time) -> None This will stop playback of the sound after fading it out over the time argument in milliseconds. The Sound will fade and stop on all actively playing channels.
pygame.ref.mixer#pygame.mixer.Sound.fadeout
get_length() get the length of the Sound get_length() -> seconds Return the length of this Sound in seconds.
pygame.ref.mixer#pygame.mixer.Sound.get_length
get_num_channels() count how many times this Sound is playing get_num_channels() -> count Return the number of active channels this sound is playing on.
pygame.ref.mixer#pygame.mixer.Sound.get_num_channels
get_raw() return a bytestring copy of the Sound samples. get_raw() -> bytes Return a copy of the Sound object buffer as a bytes (for Python 3.x) or str (for Python 2.x) object. New in pygame 1.9.2.
pygame.ref.mixer#pygame.mixer.Sound.get_raw
get_volume() get the playback volume get_volume() -> value Return a value from 0.0 to 1.0 representing the volume for this Sound.
pygame.ref.mixer#pygame.mixer.Sound.get_volume
play() begin sound playback play(loops=0, maxtime=0, fade_ms=0) -> Channel Begin playback of the Sound (i.e., on the computer's speakers) on an available Channel. This will forcibly select a Channel, so playback may cut off a currently playing sound if necessary. The loops argument controls how many times the sample will be repeated after being played the first time. A value of 5 means that the sound will be played once, then repeated five times, and so is played a total of six times. The default value (zero) means the Sound is not repeated, and so is only played once. If loops is set to -1 the Sound will loop indefinitely (though you can still call stop() to stop it). The maxtime argument can be used to stop playback after a given number of milliseconds. The fade_ms argument will make the sound start playing at 0 volume and fade up to full volume over the time given. The sample may end before the fade-in is complete. This returns the Channel object for the channel that was selected.
pygame.ref.mixer#pygame.mixer.Sound.play
set_volume() set the playback volume for this Sound set_volume(value) -> None This will set the playback volume (loudness) for this Sound. This will immediately affect the Sound if it is playing. It will also affect any future playback of this Sound. Parameters: value (float) -- volume in the range of 0.0 to 1.0 (inclusive) If value < 0.0, the volume will not be changed If value > 1.0, the volume will be set to 1.0
pygame.ref.mixer#pygame.mixer.Sound.set_volume
stop() stop sound playback stop() -> None This will stop the playback of this Sound on any active Channels.
pygame.ref.mixer#pygame.mixer.Sound.stop
pygame.mixer.stop() stop playback of all sound channels stop() -> None This will stop all playback of all active mixer channels.
pygame.ref.mixer#pygame.mixer.stop
pygame.mixer.unpause() resume paused playback of sound channels unpause() -> None This will resume all active sound channels after they have been paused.
pygame.ref.mixer#pygame.mixer.unpause
pygame.mouse pygame module to work with the mouse The mouse functions can be used to get the current state of the mouse device. These functions can also alter the system cursor for the mouse. When the display mode is set, the event queue will start receiving mouse events. The mouse buttons generate pygame.MOUSEBUTTONDOWN and pygame.MOUSEBUTTONUP events when they are pressed and released. These events contain a button attribute representing which button was pressed. The mouse wheel will generate pygame.MOUSEBUTTONDOWN and pygame.MOUSEBUTTONUP events when rolled. The button will be set to 4 when the wheel is rolled up, and to button 5 when the wheel is rolled down. Whenever the mouse is moved it generates a pygame.MOUSEMOTION event. The mouse movement is broken into small and accurate motion events. As the mouse is moving many motion events will be placed on the queue. Mouse motion events that are not properly cleaned from the event queue are the primary reason the event queue fills up. If the mouse cursor is hidden, and input is grabbed to the current display the mouse will enter a virtual input mode, where the relative movements of the mouse will never be stopped by the borders of the screen. See the functions pygame.mouse.set_visible() and pygame.event.set_grab() to get this configured. Mouse Wheel Behavior in pygame 2 There is proper functionality for mouse wheel behaviour with pygame 2 supporting pygame.MOUSEWHEEL events. The new events support horizontal and vertical scroll movements, with signed integer values representing the amount scrolled (x and y), as well as flipped direction (the set positive and negative values for each axis is flipped). Read more about SDL2 input-related changes here https://wiki.libsdl.org/MigrationGuide#Input In pygame 2, the mouse wheel functionality can be used by listening for the pygame.MOUSEWHEEL type of an event. When this event is triggered, a developer can access the appropriate Event object with pygame.event.get(). The object can be used to access data about the mouse scroll, such as which (it will tell you what exact mouse device trigger the event). Code example of mouse scroll (tested on 2.0.0.dev7) # Taken from husano896's PR thread (slightly modified) import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() def main(): while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return elif event.type == MOUSEWHEEL: print(event) print(event.x, event.y) print(event.flipped) print(event.which) # can access properties with # proper notation(ex: event.y) clock.tick(60) # Execute game: main() 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_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_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.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_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.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.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.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_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.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.ref.mouse
pygame.pixelcopy pygame module for general pixel array copying The pygame.pixelcopy module contains functions for copying between surfaces and objects exporting an array structure interface. It is a backend for pygame.surfarray, adding NumPy support. But pixelcopy is more general, and intended for direct use. The array struct interface exposes an array's data in a standard way. It was introduced in NumPy. In Python 2.7 and above it is replaced by the new buffer protocol, though the buffer protocol is still a work in progress. The array struct interface, on the other hand, is stable and works with earlier Python versions. So for now the array struct interface is the predominate way pygame handles array introspection. New in pygame 1.9.2. 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.pixelcopy.array_to_surface() copy an array object to a surface array_to_surface(<surface>, <array>) -> None See pygame.surfarray.blit_array(). 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.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.ref.pixelcopy
pygame the top level pygame package The pygame package represents the top-level package for others to use. Pygame itself is broken into many submodules, but this does not affect programs that use pygame. As a convenience, most of the top-level variables in pygame have been placed inside a module named pygame.locals. This is meant to be used with from pygame.locals import *, in addition to import pygame. When you import pygame all available pygame submodules are automatically imported. Be aware that some of the pygame modules are considered optional, and may not be available. In that case, pygame will provide a placeholder object instead of the module, which can be used to test for availability. 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.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.get_init() returns True if pygame is currently initialized get_init() -> bool Returns True if pygame is currently initialized. New in pygame 1.9.5. exception pygame.error standard pygame exception raise pygame.error(message) This exception is raised whenever a pygame or SDL operation fails. You can catch any anticipated problems and deal with the error. The exception is always raised with a descriptive message about the problem. Derived from the RuntimeError exception, which can also be used to catch these raised errors. pygame.get_error() get the current error message get_error() -> errorstr 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.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.get_sdl_version() get the version number of SDL get_sdl_version() -> major, minor, patch Returns the three version numbers of the SDL library. This version is built at compile time. It can be used to detect which features may or may not be available through pygame. New in pygame 1.7.0. pygame.get_sdl_byteorder() get the byte order of SDL get_sdl_byteorder() -> int Returns the byte order of the SDL library. It returns 1234 for little endian byte order and 4321 for big endian byte order. New in pygame 1.8. 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.encode_string() Encode a Unicode or bytes object encode_string([obj [, encoding [, errors [, etype]]]]) -> bytes or None obj: If Unicode, encode; if bytes, return unaltered; if anything else, return None; if not given, raise SyntaxError. encoding (string): If present, encoding to use. The default is 'unicode_escape'. errors (string): If given, how to handle unencodable characters. The default is 'backslashreplace'. etype (exception type): If given, the exception type to raise for an encoding error. The default is UnicodeEncodeError, as returned by PyUnicode_AsEncodedString(). For the default encoding and errors values there should be no encoding errors. This function is used in encoding file paths. Keyword arguments are supported. New in pygame 1.9.2: (primarily for use in unit tests) pygame.encode_file_path() Encode a Unicode or bytes object as a file system path encode_file_path([obj [, etype]]) -> bytes or None obj: If Unicode, encode; if bytes, return unaltered; if anything else, return None; if not given, raise SyntaxError. etype (exception type): If given, the exception type to raise for an encoding error. The default is UnicodeEncodeError, as returned by PyUnicode_AsEncodedString(). This function is used to encode file paths in pygame. Encoding is to the codec as returned by sys.getfilesystemencoding(). Keyword arguments are supported. New in pygame 1.9.2: (primarily for use in unit tests) pygame.version small module containing version information This module is automatically imported into the pygame package and can be used to check which version of pygame has been imported. pygame.version.ver version number as a string ver = '1.2' This is the version represented as a string. It can contain a micro release number as well, e.g. '1.5.2' pygame.version.vernum tupled integers of the version vernum = (1, 5, 3) This version information can easily be compared with other version numbers of the same format. An example of checking pygame version numbers would look like this: if pygame.version.vernum < (1, 5): print('Warning, older version of pygame (%s)' % pygame.version.ver) disable_advanced_features = True New in pygame 1.9.6: Attributes major, minor, and patch. vernum.major == vernum[0] vernum.minor == vernum[1] vernum.patch == vernum[2] Changed in pygame 1.9.6: str(pygame.version.vernum) returns a string like "2.0.0" instead of "(2, 0, 0)". Changed in pygame 1.9.6: repr(pygame.version.vernum) returns a string like "PygameVersion(major=2, minor=0, patch=0)" instead of "(2, 0, 0)". pygame.version.rev repository revision of the build rev = 'a6f89747b551+' The Mercurial node identifier of the repository checkout from which this package was built. If the identifier ends with a plus sign '+' then the package contains uncommitted changes. Please include this revision number in bug reports, especially for non-release pygame builds. Important note: pygame development has moved to github, this variable is obsolete now. As soon as development shifted to github, this variable started returning an empty string "". It has always been returning an empty string since v1.9.5. Changed in pygame 1.9.5: Always returns an empty string "". pygame.version.SDL tupled integers of the SDL library version SDL = '(2, 0, 12)' This is the SDL library version represented as an extended tuple. It also has attributes 'major', 'minor' & 'patch' that can be accessed like this: >>> pygame.version.SDL.major 2 printing the whole thing returns a string like this: >>> pygame.version.SDL SDLVersion(major=2, minor=0, patch=12) New in pygame 2.0.0. Setting Environment Variables Some aspects of pygame's behaviour can be controlled by setting environment variables, they cover a wide range of the library's functionality. Some of the variables are from pygame itself, while others come from the underlying C SDL library that pygame uses. In python, environment variables are usually set in code like this: import os os.environ['NAME_OF_ENVIRONMENT_VARIABLE'] = 'value_to_set' Or to preserve users ability to override the variable: import os os.environ['ENV_VAR'] = os.environ.get('ENV_VAR', 'value') If the variable is more useful for users of an app to set than the developer then they can set it like this: Windows: set NAME_OF_ENVIRONMENT_VARIABLE=value_to_set python my_application.py Linux/Mac: ENV_VAR=value python my_application.py For some variables they need to be set before initialising pygame, some must be set before even importing pygame, and others can simply be set right before the area of code they control is run. Below is a list of environment variables, their settable values, and a brief description of what they do. Pygame Environment Variables These variables are defined by pygame itself. PYGAME_DISPLAY - Experimental (subject to change) Set index of the display to use, "0" is the default. This sets the display where pygame will open its window or screen. The value set here will be used if set before calling pygame.display.set_mode(), and as long as no 'display' parameter is passed into pygame.display.set_mode(). PYGAME_FORCE_SCALE - Set to "photo" or "default". This forces set_mode() to use the SCALED display mode and, if "photo" is set, makes the scaling use the slowest, but highest quality anisotropic scaling algorithm, if it is available. Must be set before calling pygame.display.set_mode(). PYGAME_BLEND_ALPHA_SDL2 - New in pygame 2.0.0 Set to "1" to enable the SDL2 blitter. This makes pygame use the SDL2 blitter for all alpha blending. The SDL2 blitter is sometimes faster than the default blitter but uses a different formula so the final colours may differ. Must be set before pygame.init() is called. PYGAME_HIDE_SUPPORT_PROMPT - Set to "1" to hide the prompt. This stops the welcome message popping up in the console that tells you which version of python, pygame & SDL you are using. Must be set before importing pygame. PYGAME_FREETYPE - Set to "1" to enable. This switches the pygame.font module to a pure freetype implementation that bypasses SDL_ttf. See the font module for why you might want to do this. Must be set before importing pygame. PYGAME_CAMERA - Set to "opencv" or "vidcapture" Forces the library backend used in the camera module, overriding the platform defaults. Must be set before calling pygame.camera.init(). SDL Environment Variables These variables are defined by SDL. For documentation on the environment variables available in pygame 1 try here. For Pygame 2, some selected environment variables are listed below. SDL_VIDEO_CENTERED - Set to "1" to enable centering the window. This will make the pygame window open in the centre of the display. Must be set before calling pygame.display.set_mode(). SDL_VIDEO_WINDOW_POS - Set to "x,y" to position the top left corner of the window. This allows control over the placement of the pygame window within the display. Must be set before calling pygame.display.set_mode(). SDL_VIDEODRIVER - Set to "drivername" to change the video driver used. On some platforms there are multiple video drivers available and this allows users to pick between them. More information is available here. Must be set before calling pygame.init() or pygame.display.init(). SDL_AUDIODRIVER - Set to "drivername" to change the audio driver used. On some platforms there are multiple audio drivers available and this allows users to pick between them. More information is available here. Must be set before calling pygame.init() or pygame.mixer.init(). SDL_VIDEO_ALLOW_SCREENSAVER Set to "1" to allow screensavers while pygame apps are running. By default pygame apps disable screensavers while they are running. Setting this environment variable allows users or developers to change that and make screensavers run again. SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR Set to "0" to re-enable the compositor. By default SDL tries to disable the X11 compositor for all pygame apps. This is usually a good thing as it's faster, however if you have an app which doesn't update every frame and are using linux you may want to disable this bypass. The bypass has reported problems on KDE linux. This variable is only used on x11/linux platforms.
pygame.ref.pygame
pygame.scrap pygame module for clipboard support. EXPERIMENTAL!: This API may change or disappear in later pygame releases. If you use this, your code may break with the next pygame release. The scrap module is for transferring data to/from the clipboard. This allows for cutting and pasting data between pygame and other applications. Some basic data (MIME) types are defined and registered: pygame string constant value description -------------------------------------------------- SCRAP_TEXT "text/plain" plain text SCRAP_BMP "image/bmp" BMP encoded image data SCRAP_PBM "image/pbm" PBM encoded image data SCRAP_PPM "image/ppm" PPM encoded image data pygame.SCRAP_PPM, pygame.SCRAP_PBM and pygame.SCRAP_BMP are suitable for surface buffers to be shared with other applications. pygame.SCRAP_TEXT is an alias for the plain text clipboard type. Depending on the platform, additional types are automatically registered when data is placed into the clipboard to guarantee a consistent sharing behaviour with other applications. The following listed types can be used as strings to be passed to the respective pygame.scrap module functions. For Windows platforms, these additional types are supported automatically and resolve to their internal definitions: "text/plain;charset=utf-8" UTF-8 encoded text "audio/wav" WAV encoded audio "image/tiff" TIFF encoded image data For X11 platforms, these additional types are supported automatically and resolve to their internal definitions: "text/plain;charset=utf-8" UTF-8 encoded text "UTF8_STRING" UTF-8 encoded text "COMPOUND_TEXT" COMPOUND text User defined types can be used, but the data might not be accessible by other applications unless they know what data type to look for. Example: Data placed into the clipboard by pygame.scrap.put("my_data_type", byte_data) can only be accessed by applications which query the clipboard for the "my_data_type" data type. For an example of how the scrap module works refer to the examples page (pygame.examples.scrap_clipboard.main()) or the code directly in GitHub (pygame/examples/scrap_clipboard.py). New in pygame 1.8. Note The scrap module is currently only supported for Windows, X11 and Mac OS X. On Mac OS X only text works at the moment - other types may be supported in future releases. 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.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() 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_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.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.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.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.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.ref.scrap
pygame.sndarray pygame module for accessing sound sample data Functions to convert between NumPy arrays and Sound objects. This module will only be available when pygame can use the external NumPy package. Sound data is made of thousands of samples per second, and each sample is the amplitude of the wave at a particular moment in time. For example, in 22-kHz format, element number 5 of the array is the amplitude of the wave after 5/22000 seconds. Each sample is an 8-bit or 16-bit integer, depending on the data format. A stereo sound file has two values per sample, while a mono sound file only has one. 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.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.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.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.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.ref.sndarray
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.ref.sprite
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.ref.surfarray
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.ref.tests
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.ref.time
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.ref.transform
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.ref.mouse#pygame.mouse.get_cursor
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.ref.mouse#pygame.mouse.get_focused
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.ref.mouse#pygame.mouse.get_pos
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.ref.mouse#pygame.mouse.get_pressed
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.ref.mouse#pygame.mouse.get_rel
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.ref.mouse#pygame.mouse.get_visible
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.ref.mouse#pygame.mouse.set_cursor
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.ref.mouse#pygame.mouse.set_pos
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.ref.mouse#pygame.mouse.set_system_cursor
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.ref.mouse#pygame.mouse.set_visible
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.
pygame.ref.overlay
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.
pygame.ref.overlay#pygame.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.
pygame.ref.overlay#pygame.Overlay.get_hardware
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.ref.overlay#pygame.Overlay.set_location
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.
pygame.ref.pixelarray
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.
pygame.ref.pixelarray#pygame.PixelArray.close
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.
pygame.ref.pixelarray#pygame.PixelArray.compare
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.
pygame.ref.pixelarray#pygame.PixelArray.extract
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.
pygame.ref.pixelarray#pygame.PixelArray.itemsize
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.
pygame.ref.pixelarray#pygame.PixelArray.make_surface
ndim Returns the number of dimensions. ndim -> int A pixel array can be 1 or 2 dimensional. New in pygame 1.9.2.
pygame.ref.pixelarray#pygame.PixelArray.ndim
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.
pygame.ref.pixelarray#pygame.PixelArray.replace
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.
pygame.ref.pixelarray#pygame.PixelArray.shape
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.
pygame.ref.pixelarray#pygame.PixelArray.strides
surface Gets the Surface the PixelArray uses. surface -> Surface The Surface the PixelArray was created for.
pygame.ref.pixelarray#pygame.PixelArray.surface
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.ref.pixelarray#pygame.PixelArray.transpose
pygame.pixelcopy.array_to_surface() copy an array object to a surface array_to_surface(<surface>, <array>) -> None See pygame.surfarray.blit_array().
pygame.ref.pixelcopy#pygame.pixelcopy.array_to_surface
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.ref.pixelcopy#pygame.pixelcopy.make_surface
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.ref.pixelcopy#pygame.pixelcopy.map_array
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.ref.pixelcopy#pygame.pixelcopy.surface_to_array
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.ref.pygame#pygame.quit
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})
pygame.ref.rect
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.
pygame.ref.rect#pygame.Rect.clamp
clamp_ip() moves the rectangle inside another, in place clamp_ip(Rect) -> None Same as the Rect.clamp() method, but operates in place.
pygame.ref.rect#pygame.Rect.clamp_ip
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.
pygame.ref.rect#pygame.Rect.clip
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.
pygame.ref.rect#pygame.Rect.clipline
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})
pygame.ref.rect#pygame.Rect.collidedict
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})
pygame.ref.rect#pygame.Rect.collidedictall
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.
pygame.ref.rect#pygame.Rect.collidelist
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.
pygame.ref.rect#pygame.Rect.collidelistall
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.
pygame.ref.rect#pygame.Rect.collidepoint
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.
pygame.ref.rect#pygame.Rect.colliderect
contains() test if one rectangle is inside another contains(Rect) -> bool Returns true when the argument is completely inside the Rect.
pygame.ref.rect#pygame.Rect.contains
copy() copy the rectangle copy() -> Rect Returns a new rectangle having the same position and size as the original. New in pygame 1.9
pygame.ref.rect#pygame.Rect.copy
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.
pygame.ref.rect#pygame.Rect.fit
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.
pygame.ref.rect#pygame.Rect.inflate
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.
pygame.ref.rect#pygame.Rect.inflate_ip
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.
pygame.ref.rect#pygame.Rect.move
move_ip() moves the rectangle, in place move_ip(x, y) -> None Same as the Rect.move() method, but operates in place.
pygame.ref.rect#pygame.Rect.move_ip
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.
pygame.ref.rect#pygame.Rect.normalize
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.
pygame.ref.rect#pygame.Rect.union
union_ip() joins two rectangles into one, in place union_ip(Rect) -> None Same as the Rect.union() method, but operates in place.
pygame.ref.rect#pygame.Rect.union_ip
unionall() the union of many rectangles unionall(Rect_sequence) -> Rect Returns the union of one rectangle with a sequence of many rectangles.
pygame.ref.rect#pygame.Rect.unionall
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.
pygame.ref.rect#pygame.Rect.unionall_ip
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.ref.rect#pygame.Rect.update
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.ref.pygame#pygame.register_quit
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.ref.scrap#pygame.scrap.contains
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.ref.scrap#pygame.scrap.get
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.ref.scrap#pygame.scrap.get_init
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.ref.scrap#pygame.scrap.get_types