doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
set_length()
Set the number of elements in the Color to 1,2,3, or 4. set_length(len) -> None The default Color length is 4. Colors can have lengths 1,2,3 or 4. This is useful if you want to unpack to r,g,b and not r,g,b,a. If you want to get the length of a Color do len(acolor). New in pygame 1.9.0. | pygame.ref.color#pygame.Color.set_length |
update()
Sets the elements of the color update(r, g, b) -> None update(r, g, b, a=255) -> None update(color_value) -> None Sets the elements of the color. See parameters for pygame.Color() for the parameters of this function. If the alpha value was not set it will not change. New in pygame 2.0.1. | pygame.ref.color#pygame.Color.update |
pygame.cursors
pygame module for cursor resources Pygame offers control over the system hardware cursor. Pygame only supports black and white cursors for the system. You control the cursor with functions inside pygame.mouse. This cursors module contains functions for loading and decoding various cursor formats. These allow you to easily store your cursors in external files or directly as encoded python strings. The module includes several standard cursors. The pygame.mouse.set_cursor() function takes several arguments. All those arguments have been stored in a single tuple you can call like this: >>> pygame.mouse.set_cursor(*pygame.cursors.arrow) The following variables can be passed to pygame.mouse.set_cursor function:
pygame.cursors.arrow pygame.cursors.diamond pygame.cursors.broken_x pygame.cursors.tri_left pygame.cursors.tri_right
This module also contains a few cursors as formatted strings. You'll need to pass these to pygame.cursors.compile() function before you can use them. The example call would look like this: >>> cursor = pygame.cursors.compile(pygame.cursors.textmarker_strings)
>>> pygame.mouse.set_cursor((8, 16), (0, 0), *cursor) The following strings can be converted into cursor bitmaps with pygame.cursors.compile() :
pygame.cursors.thickarrow_strings pygame.cursors.sizer_x_strings pygame.cursors.sizer_y_strings pygame.cursors.sizer_xy_strings pygame.cursor.textmarker_strings
pygame.cursors.compile()
create binary cursor data from simple strings compile(strings, black='X', white='.', xor='o') -> data, mask A sequence of strings can be used to create binary cursor data for the system cursor. This returns the binary data in the form of two tuples. Those can be passed as the third and fourth arguments respectively of the pygame.mouse.set_cursor() function. If you are creating your own cursor strings, you can use any value represent the black and white pixels. Some system allow you to set a special toggle color for the system color, this is also called the xor color. If the system does not support xor cursors, that color will simply be black. The height must be divisible by 8. The width of the strings must all be equal and be divisible by 8. If these two conditions are not met, ValueError is raised. An example set of cursor strings looks like this thickarrow_strings = ( #sized 24x24
"XX ",
"XXX ",
"XXXX ",
"XX.XX ",
"XX..XX ",
"XX...XX ",
"XX....XX ",
"XX.....XX ",
"XX......XX ",
"XX.......XX ",
"XX........XX ",
"XX........XXX ",
"XX......XXXXX ",
"XX.XXX..XX ",
"XXXX XX..XX ",
"XX XX..XX ",
" XX..XX ",
" XX..XX ",
" XX..XX ",
" XXXX ",
" XX ",
" ",
" ",
" ")
pygame.cursors.load_xbm()
load cursor data from an XBM file load_xbm(cursorfile) -> cursor_args load_xbm(cursorfile, maskfile) -> cursor_args This loads cursors for a simple subset of XBM files. XBM files are traditionally used to store cursors on UNIX systems, they are an ASCII format used to represent simple images. Sometimes the black and white color values will be split into two separate XBM files. You can pass a second maskfile argument to load the two images into a single cursor. The cursorfile and maskfile arguments can either be filenames or file-like object with the readlines method. The return value cursor_args can be passed directly to the pygame.mouse.set_cursor() function. | pygame.ref.cursors |
pygame.cursors.compile()
create binary cursor data from simple strings compile(strings, black='X', white='.', xor='o') -> data, mask A sequence of strings can be used to create binary cursor data for the system cursor. This returns the binary data in the form of two tuples. Those can be passed as the third and fourth arguments respectively of the pygame.mouse.set_cursor() function. If you are creating your own cursor strings, you can use any value represent the black and white pixels. Some system allow you to set a special toggle color for the system color, this is also called the xor color. If the system does not support xor cursors, that color will simply be black. The height must be divisible by 8. The width of the strings must all be equal and be divisible by 8. If these two conditions are not met, ValueError is raised. An example set of cursor strings looks like this thickarrow_strings = ( #sized 24x24
"XX ",
"XXX ",
"XXXX ",
"XX.XX ",
"XX..XX ",
"XX...XX ",
"XX....XX ",
"XX.....XX ",
"XX......XX ",
"XX.......XX ",
"XX........XX ",
"XX........XXX ",
"XX......XXXXX ",
"XX.XXX..XX ",
"XXXX XX..XX ",
"XX XX..XX ",
" XX..XX ",
" XX..XX ",
" XX..XX ",
" XXXX ",
" XX ",
" ",
" ",
" ") | pygame.ref.cursors#pygame.cursors.compile |
pygame.cursors.load_xbm()
load cursor data from an XBM file load_xbm(cursorfile) -> cursor_args load_xbm(cursorfile, maskfile) -> cursor_args This loads cursors for a simple subset of XBM files. XBM files are traditionally used to store cursors on UNIX systems, they are an ASCII format used to represent simple images. Sometimes the black and white color values will be split into two separate XBM files. You can pass a second maskfile argument to load the two images into a single cursor. The cursorfile and maskfile arguments can either be filenames or file-like object with the readlines method. The return value cursor_args can be passed directly to the pygame.mouse.set_cursor() function. | pygame.ref.cursors#pygame.cursors.load_xbm |
pygame.display
pygame module to control the display window and screen This module offers control over the pygame display. Pygame has a single display Surface that is either contained in a window or runs full screen. Once you create the display you treat it as a regular Surface. Changes are not immediately visible onscreen; you must choose one of the two flipping functions to update the actual display. The origin of the display, where x = 0 and y = 0, is the top left of the screen. Both axes increase positively towards the bottom right of the screen. The pygame display can actually be initialized in one of several modes. By default, the display is a basic software driven framebuffer. You can request special modules like hardware acceleration and OpenGL support. These are controlled by flags passed to pygame.display.set_mode(). Pygame can only have a single display active at any time. Creating a new one with pygame.display.set_mode() will close the previous display. If precise control is needed over the pixel format or display resolutions, use the functions pygame.display.mode_ok(), pygame.display.list_modes(), and pygame.display.Info() to query information about the display. Once the display Surface is created, the functions from this module affect the single existing display. The Surface becomes invalid if the module is uninitialized. If a new display mode is set, the existing Surface will automatically switch to operate on the new display. When the display mode is set, several events are placed on the pygame event queue. pygame.QUIT is sent when the user has requested the program to shut down. The window will receive pygame.ACTIVEEVENT events as the display gains and loses input focus. If the display is set with the pygame.RESIZABLE flag, pygame.VIDEORESIZE events will be sent when the user adjusts the window dimensions. Hardware displays that draw direct to the screen will get pygame.VIDEOEXPOSE events when portions of the window must be redrawn. In pygame 2, there is a new type of event called pygame.WINDOWEVENT that is meant to replace all window related events like pygame.VIDEORESIZE, pygame.VIDEOEXPOSE and pygame.ACTIVEEVENT. Note that the WINDOWEVENT API is considered experimental, and may change in future releases. The new events of type pygame.WINDOWEVENT have an event attribute that can take the following values. Value of event attribute Short description
WINDOWEVENT_SHOWN Window became shown
WINDOWEVENT_HIDDEN Window became hidden
WINDOWEVENT_EXPOSED Window got updated by some external event
WINDOWEVENT_MOVED Window got moved
WINDOWEVENT_RESIZED Window got resized
WINDOWEVENT_SIZE_CHANGED Window changed it's size
WINDOWEVENT_MINIMIZED Window was minimised
WINDOWEVENT_MAXIMIZED Window was maximised
WINDOWEVENT_RESTORED Window was restored
WINDOWEVENT_ENTER Mouse entered the window
WINDOWEVENT_LEAVE Mouse left the window
WINDOWEVENT_FOCUS_GAINED Window gained focus
WINDOWEVENT_FOCUS_LOST Window lost focus
WINDOWEVENT_CLOSE Window was closed
WINDOWEVENT_TAKE_FOCUS Window was offered focus
WINDOWEVENT_HIT_TEST Window has a special hit test If SDL version used is less than 2.0.5, the last two values WINDOWEVENT_TAKE_FOCUS and WINDOWEVENT_HIT_TEST will not work. See the SDL implementation (in C programming) of the same over here. Some display environments have an option for automatically stretching all windows. When this option is enabled, this automatic stretching distorts the appearance of the pygame window. In the pygame examples directory, there is example code (prevent_display_stretching.py) which shows how to disable this automatic stretching of the pygame display on Microsoft Windows (Vista or newer required). pygame.display.init()
Initialize the display module init() -> None Initializes the pygame display module. The display module cannot do anything until it is initialized. This is usually handled for you automatically when you call the higher level pygame.init(). Pygame will select from one of several internal display backends when it is initialized. The display mode will be chosen depending on the platform and permissions of current user. Before the display module is initialized the environment variable SDL_VIDEODRIVER can be set to control which backend is used. The systems with multiple choices are listed here. Windows : windib, directx
Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib On some platforms it is possible to embed the pygame display into an already existing window. To do this, the environment variable SDL_WINDOWID must be set to a string containing the window id or handle. The environment variable is checked when the pygame display is initialized. Be aware that there can be many strange side effects when running in an embedded display. It is harmless to call this more than once, repeated calls have no effect.
pygame.display.quit()
Uninitialize the display module quit() -> None This will shut down the entire display module. This means any active displays will be closed. This will also be handled automatically when the program exits. It is harmless to call this more than once, repeated calls have no effect.
pygame.display.get_init()
Returns True if the display module has been initialized get_init() -> bool Returns True if the pygame.display module is currently initialized.
pygame.display.set_mode()
Initialize a window or screen for display set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface This function will create a display Surface. The arguments passed in are requests for a display type. The actual created display will be the best possible match supported by the system. The size argument is a pair of numbers representing the width and height. The flags argument is a collection of additional options. The depth argument represents the number of bits to use for color. The Surface that gets returned can be drawn to like a regular Surface but changes will eventually be seen on the monitor. If no size is passed or is set to (0, 0) and pygame uses SDL version 1.2.10 or above, the created Surface will have the same size as the current screen resolution. If only the width or height are set to 0, the Surface will have the same width or height as the screen resolution. Using a SDL version prior to 1.2.10 will raise an exception. It is usually best to not pass the depth argument. It will default to the best and fastest color depth for the system. If your game requires a specific color format you can control the depth with this argument. Pygame will emulate an unavailable color depth which can be slow. When requesting fullscreen display modes, sometimes an exact match for the requested size cannot be made. In these situations pygame will select the closest compatible match. The returned surface will still always match the requested size. On high resolution displays(4k, 1080p) and tiny graphics games (640x480) show up very small so that they are unplayable. SCALED scales up the window for you. The game thinks it's a 640x480 window, but really it can be bigger. Mouse events are scaled for you, so your game doesn't need to do it. Note that SCALED is considered an experimental API and may change in future releases. The flags argument controls which type of display you want. There are several to choose from, and you can even combine multiple types using the bitwise or operator, (the pipe "|" character). If you pass 0 or no flags argument it will default to a software driven window. Here are the display flags you will want to choose from: pygame.FULLSCREEN create a fullscreen display
pygame.DOUBLEBUF recommended for HWSURFACE or OPENGL
pygame.HWSURFACE hardware accelerated, only in FULLSCREEN
pygame.OPENGL create an OpenGL-renderable display
pygame.RESIZABLE display window should be sizeable
pygame.NOFRAME display window will have no border or controls Pygame 2 has the following additional flags available. pygame.SCALED resolution depends on desktop size and scale
graphics
pygame.SHOWN window is opened in visible mode (default)
pygame.HIDDEN window is opened in hidden mode New in pygame 2.0.0: SCALED, SHOWN and HIDDEN By setting the vsync parameter to 1, it is possible to get a display with vertical sync, but you are not guaranteed to get one. The request only works at all for calls to set_mode() with the pygame.OPENGL or pygame.SCALED flags set, and is still not guaranteed even with one of those set. What you get depends on the hardware and driver configuration of the system pygame is running on. Here is an example usage of a call to set_mode() that may give you a display with vsync: flags = pygame.OPENGL | pygame.FULLSCREEN
window_surface = pygame.display.set_mode((1920, 1080), flags, vsync=1) Vsync behaviour is considered experimental, and may change in future releases. New in pygame 2.0.0: vsync Basic example: # Open a window on the screen
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width, screen_height]) The display index 0 means the default display is used. Changed in pygame 1.9.5: display argument added
pygame.display.get_surface()
Get a reference to the currently set display surface get_surface() -> Surface Return a reference to the currently set display Surface. If no display mode has been set this will return None.
pygame.display.flip()
Update the full display Surface to the screen flip() -> None This will update the contents of the entire display. If your display mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this will wait for a vertical retrace and swap the surfaces. If you are using a different type of display mode, it will simply update the entire contents of the surface. When using an pygame.OPENGL display mode this will perform a gl buffer swap.
pygame.display.update()
Update portions of the screen for software displays update(rectangle=None) -> None update(rectangle_list) -> None This function is like an optimized version of pygame.display.flip() for software displays. It allows only a portion of the screen to updated, instead of the entire area. If no argument is passed it updates the entire Surface area like pygame.display.flip(). You can pass the function a single rectangle, or a sequence of rectangles. It is more efficient to pass many rectangles at once than to call update multiple times with single or a partial list of rectangles. If passing a sequence of rectangles it is safe to include None values in the list, which will be skipped. This call cannot be used on pygame.OPENGL displays and will generate an exception.
pygame.display.get_driver()
Get the name of the pygame display backend get_driver() -> name Pygame chooses one of many available display backends when it is initialized. This returns the internal name used for the display backend. This can be used to provide limited information about what display capabilities might be accelerated. See the SDL_VIDEODRIVER flags in pygame.display.set_mode() to see some of the common options.
pygame.display.Info()
Create a video display information object Info() -> VideoInfo Creates a simple object containing several attributes to describe the current graphics environment. If this is called before pygame.display.set_mode() some platforms can provide information about the default display mode. This can also be called after setting the display mode to verify specific display options were satisfied. The VidInfo object has several attributes: hw: 1 if the display is hardware accelerated
wm: 1 if windowed display modes can be used
video_mem: The megabytes of video memory on the display. This is 0 if
unknown
bitsize: Number of bits used to store each pixel
bytesize: Number of bytes used to store each pixel
masks: Four values used to pack RGBA values into pixels
shifts: Four values used to pack RGBA values into pixels
losses: Four values used to pack RGBA values into pixels
blit_hw: 1 if hardware Surface blitting is accelerated
blit_hw_CC: 1 if hardware Surface colorkey blitting is accelerated
blit_hw_A: 1 if hardware Surface pixel alpha blitting is accelerated
blit_sw: 1 if software Surface blitting is accelerated
blit_sw_CC: 1 if software Surface colorkey blitting is accelerated
blit_sw_A: 1 if software Surface pixel alpha blitting is accelerated
current_h, current_w: Height and width of the current video mode, or
of the desktop mode if called before the display.set_mode
is called. (current_h, current_w are available since
SDL 1.2.10, and pygame 1.8.0). They are -1 on error, or if
an old SDL is being used.
pygame.display.get_wm_info()
Get information about the current windowing system get_wm_info() -> dict Creates a dictionary filled with string keys. The strings and values are arbitrarily created by the system. Some systems may have no information and an empty dictionary will be returned. Most platforms will return a "window" key with the value set to the system id for the current display. New in pygame 1.7.1.
pygame.display.list_modes()
Get list of available fullscreen modes list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list This function returns a list of possible sizes for a specified color depth. The return value will be an empty list if no display modes are available with the given arguments. A return value of -1 means that any requested size should work (this is likely the case for windowed modes). Mode sizes are sorted from biggest to smallest. If depth is 0, the current/best color depth for the display is used. The flags defaults to pygame.FULLSCREEN, but you may need to add additional flags for specific fullscreen modes. The display index 0 means the default display is used. Changed in pygame 1.9.5: display argument added
pygame.display.mode_ok()
Pick the best color depth for a display mode mode_ok(size, flags=0, depth=0, display=0) -> depth This function uses the same arguments as pygame.display.set_mode(). It is used to determine if a requested display mode is available. It will return 0 if the display mode cannot be set. Otherwise it will return a pixel depth that best matches the display asked for. Usually the depth argument is not passed, but some platforms can support multiple display depths. If passed it will hint to which depth is a better match. The most useful flags to pass will be pygame.HWSURFACE, pygame.DOUBLEBUF, and maybe pygame.FULLSCREEN. The function will return 0 if these display flags cannot be set. The display index 0 means the default display is used. Changed in pygame 1.9.5: display argument added
pygame.display.gl_get_attribute()
Get the value for an OpenGL flag for the current display gl_get_attribute(flag) -> value After calling pygame.display.set_mode() with the pygame.OPENGL flag, it is a good idea to check the value of any requested OpenGL attributes. See pygame.display.gl_set_attribute() for a list of valid flags.
pygame.display.gl_set_attribute()
Request an OpenGL display attribute for the display mode gl_set_attribute(flag, value) -> None When calling pygame.display.set_mode() with the pygame.OPENGL flag, Pygame automatically handles setting the OpenGL attributes like color and double-buffering. OpenGL offers several other attributes you may want control over. Pass one of these attributes as the flag, and its appropriate value. This must be called before pygame.display.set_mode(). Many settings are the requested minimum. Creating a window with an OpenGL context will fail if OpenGL cannot provide the requested attribute, but it may for example give you a stencil buffer even if you request none, or it may give you a larger one than requested. The OPENGL flags are: GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO GL_MULTISAMPLEBUFFERS
Whether to enable multisampling anti-aliasing. Defaults to 0 (disabled). Set GL_MULTISAMPLESAMPLES to a value above 0 to control the amount of anti-aliasing. A typical value is 2 or 3.
GL_STENCIL_SIZE Minimum bit size of the stencil buffer. Defaults to 0.
GL_DEPTH_SIZE Minimum bit size of the depth buffer. Defaults to 16.
GL_STEREO 1 enables stereo 3D. Defaults to 0.
GL_BUFFER_SIZE Minimum bit size of the frame buffer. Defaults to 0.
New in pygame 2.0.0: Additional attributes: GL_ACCELERATED_VISUAL,
GL_CONTEXT_MAJOR_VERSION, GL_CONTEXT_MINOR_VERSION,
GL_CONTEXT_FLAGS, GL_CONTEXT_PROFILE_MASK,
GL_SHARE_WITH_CURRENT_CONTEXT,
GL_CONTEXT_RELEASE_BEHAVIOR,
GL_FRAMEBUFFER_SRGB_CAPABLE GL_CONTEXT_PROFILE_MASK
Sets the OpenGL profile to one of these values: GL_CONTEXT_PROFILE_CORE disable deprecated features
GL_CONTEXT_PROFILE_COMPATIBILITY allow deprecated features
GL_CONTEXT_PROFILE_ES allow only the ES feature
subset of OpenGL
GL_ACCELERATED_VISUAL Set to 1 to require hardware acceleration, or 0 to force software render. By default, both are allowed.
pygame.display.get_active()
Returns True when the display is active on the screen get_active() -> bool Returns True when the display Surface is considered actively renderable on the screen and may be visible to the user. This is the default state immediately after pygame.display.set_mode(). This method may return True even if the application is fully hidden behind another application window. This will return False if the display Surface has been iconified or minimized (either via pygame.display.iconify() or via an OS specific method such as the minimize-icon available on most desktops). The method can also return False for other reasons without the application being explicitly iconified or minimized by the user. A notable example being if the user has multiple virtual desktops and the display Surface is not on the active virtual desktop. Note This function returning True is unrelated to whether the application has input focus. Please see pygame.key.get_focused() and pygame.mouse.get_focused() for APIs related to input focus.
pygame.display.iconify()
Iconify the display surface iconify() -> bool Request the window for the display surface be iconified or hidden. Not all systems and displays support an iconified display. The function will return True if successful. When the display is iconified pygame.display.get_active() will return False. The event queue should receive an ACTIVEEVENT event when the window has been iconified. Additionally, the event queue also recieves a WINDOWEVENT_MINIMIZED event when the window has been iconified on pygame 2.
pygame.display.toggle_fullscreen()
Switch between fullscreen and windowed displays toggle_fullscreen() -> int Switches the display window between windowed and fullscreen modes. Display driver support is not great when using pygame 1, but with pygame 2 it is the most reliable method to switch to and from fullscreen. Supported display drivers in pygame 1:
x11 (Linux/Unix) wayland (Linux/Unix)
Supported display drivers in pygame 2:
windows (Windows) x11 (Linux/Unix) wayland (Linux/Unix) cocoa (OSX/Mac)
pygame.display.set_gamma()
Change the hardware gamma ramps set_gamma(red, green=None, blue=None) -> bool Set the red, green, and blue gamma values on the display hardware. If the green and blue arguments are not passed, they will both be the same as red. Not all systems and hardware support gamma ramps, if the function succeeds it will return True. A gamma value of 1.0 creates a linear color table. Lower values will darken the display and higher values will brighten.
pygame.display.set_gamma_ramp()
Change the hardware gamma ramps with a custom lookup set_gamma_ramp(red, green, blue) -> bool Set the red, green, and blue gamma ramps with an explicit lookup table. Each argument should be sequence of 256 integers. The integers should range between 0 and 0xffff. Not all systems and hardware support gamma ramps, if the function succeeds it will return True.
pygame.display.set_icon()
Change the system image for the display window set_icon(Surface) -> None Sets the runtime icon the system will use to represent the display window. All windows default to a simple pygame logo for the window icon. You can pass any surface, but most systems want a smaller image around 32x32. The image can have colorkey transparency which will be passed to the system. Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode() to create the icon before the display mode is set.
pygame.display.set_caption()
Set the current window caption set_caption(title, icontitle=None) -> None If the display has a window title, this function will change the name on the window. Some systems support an alternate shorter title to be used for minimized displays.
pygame.display.get_caption()
Get the current window caption get_caption() -> (title, icontitle) Returns the title and icontitle for the display Surface. These will often be the same value.
pygame.display.set_palette()
Set the display color palette for indexed displays set_palette(palette=None) -> None This will change the video display color palette for 8-bit displays. This does not change the palette for the actual display Surface, only the palette that is used to display the Surface. If no palette argument is passed, the system default palette will be restored. The palette is a sequence of RGB triplets.
pygame.display.get_num_displays()
Return the number of displays get_num_displays() -> int Returns the number of available displays. This is always 1 if pygame.get_sdl_version() returns a major version number below 2. New in pygame 1.9.5.
pygame.display.get_window_size()
Return the size of the window or screen get_window_size() -> tuple Returns the size of the window initialized with pygame.display.set_mode(). This may differ from the size of the display surface if SCALED is used. New in pygame 2.0.0.
pygame.display.get_allow_screensaver()
Return whether the screensaver is allowed to run. get_allow_screensaver() -> bool Return whether screensaver is allowed to run whilst the app is running. Default is False. By default pygame does not allow the screensaver during game play. Note Some platforms do not have a screensaver or support disabling the screensaver. Please see pygame.display.set_allow_screensaver() for caveats with screensaver support. New in pygame 2.0.0.
pygame.display.set_allow_screensaver()
Set whether the screensaver may run set_allow_screensaver(bool) -> None Change whether screensavers should be allowed whilst the app is running. The default is False. By default pygame does not allow the screensaver during game play. If the screensaver has been disallowed due to this function, it will automatically be allowed to run when pygame.quit() is called. It is possible to influence the default value via the environment variable SDL_HINT_VIDEO_ALLOW_SCREENSAVER, which can be set to either 0 (disable) or 1 (enable). Note Disabling screensaver is subject to platform support. When platform support is absent, this function will silently appear to work even though the screensaver state is unchanged. The lack of feedback is due to SDL not providing any supported method for determining whether it supports changing the screensaver state. SDL_HINT_VIDEO_ALLOW_SCREENSAVER is available in SDL 2.0.2 or later. SDL1.2 does not implement this. New in pygame 2.0.0. | pygame.ref.display |
pygame.display.flip()
Update the full display Surface to the screen flip() -> None This will update the contents of the entire display. If your display mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this will wait for a vertical retrace and swap the surfaces. If you are using a different type of display mode, it will simply update the entire contents of the surface. When using an pygame.OPENGL display mode this will perform a gl buffer swap. | pygame.ref.display#pygame.display.flip |
pygame.display.get_active()
Returns True when the display is active on the screen get_active() -> bool Returns True when the display Surface is considered actively renderable on the screen and may be visible to the user. This is the default state immediately after pygame.display.set_mode(). This method may return True even if the application is fully hidden behind another application window. This will return False if the display Surface has been iconified or minimized (either via pygame.display.iconify() or via an OS specific method such as the minimize-icon available on most desktops). The method can also return False for other reasons without the application being explicitly iconified or minimized by the user. A notable example being if the user has multiple virtual desktops and the display Surface is not on the active virtual desktop. Note This function returning True is unrelated to whether the application has input focus. Please see pygame.key.get_focused() and pygame.mouse.get_focused() for APIs related to input focus. | pygame.ref.display#pygame.display.get_active |
pygame.display.get_allow_screensaver()
Return whether the screensaver is allowed to run. get_allow_screensaver() -> bool Return whether screensaver is allowed to run whilst the app is running. Default is False. By default pygame does not allow the screensaver during game play. Note Some platforms do not have a screensaver or support disabling the screensaver. Please see pygame.display.set_allow_screensaver() for caveats with screensaver support. New in pygame 2.0.0. | pygame.ref.display#pygame.display.get_allow_screensaver |
pygame.display.get_caption()
Get the current window caption get_caption() -> (title, icontitle) Returns the title and icontitle for the display Surface. These will often be the same value. | pygame.ref.display#pygame.display.get_caption |
pygame.display.get_driver()
Get the name of the pygame display backend get_driver() -> name Pygame chooses one of many available display backends when it is initialized. This returns the internal name used for the display backend. This can be used to provide limited information about what display capabilities might be accelerated. See the SDL_VIDEODRIVER flags in pygame.display.set_mode() to see some of the common options. | pygame.ref.display#pygame.display.get_driver |
pygame.display.get_init()
Returns True if the display module has been initialized get_init() -> bool Returns True if the pygame.display module is currently initialized. | pygame.ref.display#pygame.display.get_init |
pygame.display.get_num_displays()
Return the number of displays get_num_displays() -> int Returns the number of available displays. This is always 1 if pygame.get_sdl_version() returns a major version number below 2. New in pygame 1.9.5. | pygame.ref.display#pygame.display.get_num_displays |
pygame.display.get_surface()
Get a reference to the currently set display surface get_surface() -> Surface Return a reference to the currently set display Surface. If no display mode has been set this will return None. | pygame.ref.display#pygame.display.get_surface |
pygame.display.get_window_size()
Return the size of the window or screen get_window_size() -> tuple Returns the size of the window initialized with pygame.display.set_mode(). This may differ from the size of the display surface if SCALED is used. New in pygame 2.0.0. | pygame.ref.display#pygame.display.get_window_size |
pygame.display.get_wm_info()
Get information about the current windowing system get_wm_info() -> dict Creates a dictionary filled with string keys. The strings and values are arbitrarily created by the system. Some systems may have no information and an empty dictionary will be returned. Most platforms will return a "window" key with the value set to the system id for the current display. New in pygame 1.7.1. | pygame.ref.display#pygame.display.get_wm_info |
pygame.display.gl_get_attribute()
Get the value for an OpenGL flag for the current display gl_get_attribute(flag) -> value After calling pygame.display.set_mode() with the pygame.OPENGL flag, it is a good idea to check the value of any requested OpenGL attributes. See pygame.display.gl_set_attribute() for a list of valid flags. | pygame.ref.display#pygame.display.gl_get_attribute |
pygame.display.gl_set_attribute()
Request an OpenGL display attribute for the display mode gl_set_attribute(flag, value) -> None When calling pygame.display.set_mode() with the pygame.OPENGL flag, Pygame automatically handles setting the OpenGL attributes like color and double-buffering. OpenGL offers several other attributes you may want control over. Pass one of these attributes as the flag, and its appropriate value. This must be called before pygame.display.set_mode(). Many settings are the requested minimum. Creating a window with an OpenGL context will fail if OpenGL cannot provide the requested attribute, but it may for example give you a stencil buffer even if you request none, or it may give you a larger one than requested. The OPENGL flags are: GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO GL_MULTISAMPLEBUFFERS
Whether to enable multisampling anti-aliasing. Defaults to 0 (disabled). Set GL_MULTISAMPLESAMPLES to a value above 0 to control the amount of anti-aliasing. A typical value is 2 or 3.
GL_STENCIL_SIZE Minimum bit size of the stencil buffer. Defaults to 0.
GL_DEPTH_SIZE Minimum bit size of the depth buffer. Defaults to 16.
GL_STEREO 1 enables stereo 3D. Defaults to 0.
GL_BUFFER_SIZE Minimum bit size of the frame buffer. Defaults to 0.
New in pygame 2.0.0: Additional attributes: GL_ACCELERATED_VISUAL,
GL_CONTEXT_MAJOR_VERSION, GL_CONTEXT_MINOR_VERSION,
GL_CONTEXT_FLAGS, GL_CONTEXT_PROFILE_MASK,
GL_SHARE_WITH_CURRENT_CONTEXT,
GL_CONTEXT_RELEASE_BEHAVIOR,
GL_FRAMEBUFFER_SRGB_CAPABLE GL_CONTEXT_PROFILE_MASK
Sets the OpenGL profile to one of these values: GL_CONTEXT_PROFILE_CORE disable deprecated features
GL_CONTEXT_PROFILE_COMPATIBILITY allow deprecated features
GL_CONTEXT_PROFILE_ES allow only the ES feature
subset of OpenGL
GL_ACCELERATED_VISUAL Set to 1 to require hardware acceleration, or 0 to force software render. By default, both are allowed. | pygame.ref.display#pygame.display.gl_set_attribute |
pygame.display.iconify()
Iconify the display surface iconify() -> bool Request the window for the display surface be iconified or hidden. Not all systems and displays support an iconified display. The function will return True if successful. When the display is iconified pygame.display.get_active() will return False. The event queue should receive an ACTIVEEVENT event when the window has been iconified. Additionally, the event queue also recieves a WINDOWEVENT_MINIMIZED event when the window has been iconified on pygame 2. | pygame.ref.display#pygame.display.iconify |
pygame.display.Info()
Create a video display information object Info() -> VideoInfo Creates a simple object containing several attributes to describe the current graphics environment. If this is called before pygame.display.set_mode() some platforms can provide information about the default display mode. This can also be called after setting the display mode to verify specific display options were satisfied. The VidInfo object has several attributes: hw: 1 if the display is hardware accelerated
wm: 1 if windowed display modes can be used
video_mem: The megabytes of video memory on the display. This is 0 if
unknown
bitsize: Number of bits used to store each pixel
bytesize: Number of bytes used to store each pixel
masks: Four values used to pack RGBA values into pixels
shifts: Four values used to pack RGBA values into pixels
losses: Four values used to pack RGBA values into pixels
blit_hw: 1 if hardware Surface blitting is accelerated
blit_hw_CC: 1 if hardware Surface colorkey blitting is accelerated
blit_hw_A: 1 if hardware Surface pixel alpha blitting is accelerated
blit_sw: 1 if software Surface blitting is accelerated
blit_sw_CC: 1 if software Surface colorkey blitting is accelerated
blit_sw_A: 1 if software Surface pixel alpha blitting is accelerated
current_h, current_w: Height and width of the current video mode, or
of the desktop mode if called before the display.set_mode
is called. (current_h, current_w are available since
SDL 1.2.10, and pygame 1.8.0). They are -1 on error, or if
an old SDL is being used. | pygame.ref.display#pygame.display.Info |
pygame.display.init()
Initialize the display module init() -> None Initializes the pygame display module. The display module cannot do anything until it is initialized. This is usually handled for you automatically when you call the higher level pygame.init(). Pygame will select from one of several internal display backends when it is initialized. The display mode will be chosen depending on the platform and permissions of current user. Before the display module is initialized the environment variable SDL_VIDEODRIVER can be set to control which backend is used. The systems with multiple choices are listed here. Windows : windib, directx
Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib On some platforms it is possible to embed the pygame display into an already existing window. To do this, the environment variable SDL_WINDOWID must be set to a string containing the window id or handle. The environment variable is checked when the pygame display is initialized. Be aware that there can be many strange side effects when running in an embedded display. It is harmless to call this more than once, repeated calls have no effect. | pygame.ref.display#pygame.display.init |
pygame.display.list_modes()
Get list of available fullscreen modes list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list This function returns a list of possible sizes for a specified color depth. The return value will be an empty list if no display modes are available with the given arguments. A return value of -1 means that any requested size should work (this is likely the case for windowed modes). Mode sizes are sorted from biggest to smallest. If depth is 0, the current/best color depth for the display is used. The flags defaults to pygame.FULLSCREEN, but you may need to add additional flags for specific fullscreen modes. The display index 0 means the default display is used. Changed in pygame 1.9.5: display argument added | pygame.ref.display#pygame.display.list_modes |
pygame.display.mode_ok()
Pick the best color depth for a display mode mode_ok(size, flags=0, depth=0, display=0) -> depth This function uses the same arguments as pygame.display.set_mode(). It is used to determine if a requested display mode is available. It will return 0 if the display mode cannot be set. Otherwise it will return a pixel depth that best matches the display asked for. Usually the depth argument is not passed, but some platforms can support multiple display depths. If passed it will hint to which depth is a better match. The most useful flags to pass will be pygame.HWSURFACE, pygame.DOUBLEBUF, and maybe pygame.FULLSCREEN. The function will return 0 if these display flags cannot be set. The display index 0 means the default display is used. Changed in pygame 1.9.5: display argument added | pygame.ref.display#pygame.display.mode_ok |
pygame.display.quit()
Uninitialize the display module quit() -> None This will shut down the entire display module. This means any active displays will be closed. This will also be handled automatically when the program exits. It is harmless to call this more than once, repeated calls have no effect. | pygame.ref.display#pygame.display.quit |
pygame.display.set_allow_screensaver()
Set whether the screensaver may run set_allow_screensaver(bool) -> None Change whether screensavers should be allowed whilst the app is running. The default is False. By default pygame does not allow the screensaver during game play. If the screensaver has been disallowed due to this function, it will automatically be allowed to run when pygame.quit() is called. It is possible to influence the default value via the environment variable SDL_HINT_VIDEO_ALLOW_SCREENSAVER, which can be set to either 0 (disable) or 1 (enable). Note Disabling screensaver is subject to platform support. When platform support is absent, this function will silently appear to work even though the screensaver state is unchanged. The lack of feedback is due to SDL not providing any supported method for determining whether it supports changing the screensaver state. SDL_HINT_VIDEO_ALLOW_SCREENSAVER is available in SDL 2.0.2 or later. SDL1.2 does not implement this. New in pygame 2.0.0. | pygame.ref.display#pygame.display.set_allow_screensaver |
pygame.display.set_caption()
Set the current window caption set_caption(title, icontitle=None) -> None If the display has a window title, this function will change the name on the window. Some systems support an alternate shorter title to be used for minimized displays. | pygame.ref.display#pygame.display.set_caption |
pygame.display.set_gamma()
Change the hardware gamma ramps set_gamma(red, green=None, blue=None) -> bool Set the red, green, and blue gamma values on the display hardware. If the green and blue arguments are not passed, they will both be the same as red. Not all systems and hardware support gamma ramps, if the function succeeds it will return True. A gamma value of 1.0 creates a linear color table. Lower values will darken the display and higher values will brighten. | pygame.ref.display#pygame.display.set_gamma |
pygame.display.set_gamma_ramp()
Change the hardware gamma ramps with a custom lookup set_gamma_ramp(red, green, blue) -> bool Set the red, green, and blue gamma ramps with an explicit lookup table. Each argument should be sequence of 256 integers. The integers should range between 0 and 0xffff. Not all systems and hardware support gamma ramps, if the function succeeds it will return True. | pygame.ref.display#pygame.display.set_gamma_ramp |
pygame.display.set_icon()
Change the system image for the display window set_icon(Surface) -> None Sets the runtime icon the system will use to represent the display window. All windows default to a simple pygame logo for the window icon. You can pass any surface, but most systems want a smaller image around 32x32. The image can have colorkey transparency which will be passed to the system. Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode() to create the icon before the display mode is set. | pygame.ref.display#pygame.display.set_icon |
pygame.display.set_mode()
Initialize a window or screen for display set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface This function will create a display Surface. The arguments passed in are requests for a display type. The actual created display will be the best possible match supported by the system. The size argument is a pair of numbers representing the width and height. The flags argument is a collection of additional options. The depth argument represents the number of bits to use for color. The Surface that gets returned can be drawn to like a regular Surface but changes will eventually be seen on the monitor. If no size is passed or is set to (0, 0) and pygame uses SDL version 1.2.10 or above, the created Surface will have the same size as the current screen resolution. If only the width or height are set to 0, the Surface will have the same width or height as the screen resolution. Using a SDL version prior to 1.2.10 will raise an exception. It is usually best to not pass the depth argument. It will default to the best and fastest color depth for the system. If your game requires a specific color format you can control the depth with this argument. Pygame will emulate an unavailable color depth which can be slow. When requesting fullscreen display modes, sometimes an exact match for the requested size cannot be made. In these situations pygame will select the closest compatible match. The returned surface will still always match the requested size. On high resolution displays(4k, 1080p) and tiny graphics games (640x480) show up very small so that they are unplayable. SCALED scales up the window for you. The game thinks it's a 640x480 window, but really it can be bigger. Mouse events are scaled for you, so your game doesn't need to do it. Note that SCALED is considered an experimental API and may change in future releases. The flags argument controls which type of display you want. There are several to choose from, and you can even combine multiple types using the bitwise or operator, (the pipe "|" character). If you pass 0 or no flags argument it will default to a software driven window. Here are the display flags you will want to choose from: pygame.FULLSCREEN create a fullscreen display
pygame.DOUBLEBUF recommended for HWSURFACE or OPENGL
pygame.HWSURFACE hardware accelerated, only in FULLSCREEN
pygame.OPENGL create an OpenGL-renderable display
pygame.RESIZABLE display window should be sizeable
pygame.NOFRAME display window will have no border or controls Pygame 2 has the following additional flags available. pygame.SCALED resolution depends on desktop size and scale
graphics
pygame.SHOWN window is opened in visible mode (default)
pygame.HIDDEN window is opened in hidden mode New in pygame 2.0.0: SCALED, SHOWN and HIDDEN By setting the vsync parameter to 1, it is possible to get a display with vertical sync, but you are not guaranteed to get one. The request only works at all for calls to set_mode() with the pygame.OPENGL or pygame.SCALED flags set, and is still not guaranteed even with one of those set. What you get depends on the hardware and driver configuration of the system pygame is running on. Here is an example usage of a call to set_mode() that may give you a display with vsync: flags = pygame.OPENGL | pygame.FULLSCREEN
window_surface = pygame.display.set_mode((1920, 1080), flags, vsync=1) Vsync behaviour is considered experimental, and may change in future releases. New in pygame 2.0.0: vsync Basic example: # Open a window on the screen
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width, screen_height]) The display index 0 means the default display is used. Changed in pygame 1.9.5: display argument added | pygame.ref.display#pygame.display.set_mode |
pygame.display.set_palette()
Set the display color palette for indexed displays set_palette(palette=None) -> None This will change the video display color palette for 8-bit displays. This does not change the palette for the actual display Surface, only the palette that is used to display the Surface. If no palette argument is passed, the system default palette will be restored. The palette is a sequence of RGB triplets. | pygame.ref.display#pygame.display.set_palette |
pygame.display.toggle_fullscreen()
Switch between fullscreen and windowed displays toggle_fullscreen() -> int Switches the display window between windowed and fullscreen modes. Display driver support is not great when using pygame 1, but with pygame 2 it is the most reliable method to switch to and from fullscreen. Supported display drivers in pygame 1:
x11 (Linux/Unix) wayland (Linux/Unix)
Supported display drivers in pygame 2:
windows (Windows) x11 (Linux/Unix) wayland (Linux/Unix) cocoa (OSX/Mac) | pygame.ref.display#pygame.display.toggle_fullscreen |
pygame.display.update()
Update portions of the screen for software displays update(rectangle=None) -> None update(rectangle_list) -> None This function is like an optimized version of pygame.display.flip() for software displays. It allows only a portion of the screen to updated, instead of the entire area. If no argument is passed it updates the entire Surface area like pygame.display.flip(). You can pass the function a single rectangle, or a sequence of rectangles. It is more efficient to pass many rectangles at once than to call update multiple times with single or a partial list of rectangles. If passing a sequence of rectangles it is safe to include None values in the list, which will be skipped. This call cannot be used on pygame.OPENGL displays and will generate an exception. | pygame.ref.display#pygame.display.update |
pygame.draw
pygame module for drawing shapes Draw several simple shapes to a surface. These functions will work for rendering to any format of surface. Rendering to hardware surfaces will be slower than regular software surfaces. Most of the functions take a width argument to represent the size of stroke (thickness) around the edge of the shape. If a width of 0 is passed the shape will be filled (solid). All the drawing functions respect the clip area for the surface and will be constrained to that area. The functions return a rectangle representing the bounding area of changed pixels. This bounding rectangle is the 'minimum' bounding box that encloses the affected area. All the drawing functions accept a color argument that can be one of the following formats:
a pygame.Color object an (RGB) triplet (tuple/list) an (RGBA) quadruplet (tuple/list) an integer value that has been mapped to the surface's pixel format (see pygame.Surface.map_rgb() and pygame.Surface.unmap_rgb())
A color's alpha value will be written directly into the surface (if the surface contains pixel alphas), but the draw function will not draw transparently. These functions temporarily lock the surface they are operating on. Many sequential drawing calls can be sped up by locking and unlocking the surface object around the draw calls (see pygame.Surface.lock() and pygame.Surface.unlock()). Note See the pygame.gfxdraw module for alternative draw methods. pygame.draw.rect()
draw a rectangle rect(surface, color, rect) -> Rect rect(surface, color, rect, width=0, border_radius=0, border_top_left_radius=-1, border_top_right_radius=-1, border_bottom_left_radius=-1, border_bottom_right_radius=-1) -> Rect Draws a rectangle on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
rect (Rect) -- rectangle to draw, position and dimensions
width (int) -- (optional) used for line thickness or to indicate that the rectangle is to be filled (not to be confused with the width value of the rect parameter)
if width == 0, (default) fill the rectangle if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will grow outside the original boundary of the rect. For more details on how the thickness for edge lines grow, refer to the width notes of the pygame.draw.line() function.
border_radius (int) -- (optional) used for drawing rectangle with rounded corners. The supported range is [0, min(height, width) / 2], with 0 representing a rectangle without rounded corners.
border_top_left_radius (int) -- (optional) used for setting the value of top left border. If you don't set this value, it will use the border_radius value.
border_top_right_radius (int) -- (optional) used for setting the value of top right border. If you don't set this value, it will use the border_radius value.
border_bottom_left_radius (int) -- (optional) used for setting the value of bottom left border. If you don't set this value, it will use the border_radius value.
border_bottom_right_radius (int) -- (optional) used for setting the value of bottom right border. If you don't set this value, it will use the border_radius value.
if border_radius < 1 it will draw rectangle without rounded corners if any of border radii has the value < 0 it will use value of the border_radius If sum of radii on the same side of the rectangle is greater than the rect size the radii will get scaled
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the given rect parameter and its width and height will be 0
Return type:
Rect Note The pygame.Surface.fill() method works just as well for drawing filled rectangles and can be hardware accelerated on some platforms with both software and hardware display modes. Changed in pygame 2.0.0: Added support for keyword arguments. Changed in pygame 2.0.0.dev8: Added support for border radius.
pygame.draw.polygon()
draw a polygon polygon(surface, color, points) -> Rect polygon(surface, color, points, width=0) -> Rect Draws a polygon on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
points (tuple(coordinate) or list(coordinate)) -- a sequence of 3 or more (x, y) coordinates that make up the vertices of the polygon, each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats, e.g. [(x1, y1), (x2, y2), (x3, y3)]
width (int) -- (optional) used for line thickness or to indicate that the polygon is to be filled
if width == 0, (default) fill the polygon if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will grow outside the original boundary of the polygon. For more details on how the thickness for edge lines grow, refer to the width notes of the pygame.draw.line() function.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
ValueError -- if len(points) < 3 (must have at least 3 points)
TypeError -- if points is not a sequence or points does not contain number pairs Note For an aapolygon, use aalines() with closed=True. Changed in pygame 2.0.0: Added support for keyword arguments.
pygame.draw.circle()
draw a circle circle(surface, color, center, radius) -> Rect circle(surface, color, center, radius, width=0, draw_top_right=None, draw_top_left=None, draw_bottom_left=None, draw_bottom_right=None) -> Rect Draws a circle on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
center (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- center point of the circle as a sequence of 2 ints/floats, e.g. (x, y)
radius (int or float) -- radius of the circle, measured from the center parameter, nothing will be drawn if the radius is less than 1
width (int) -- (optional) used for line thickness or to indicate that the circle is to be filled
if width == 0, (default) fill the circle if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will only grow inward.
draw_top_right (bool) -- (optional) if this is set to True then the top right corner of the circle will be drawn
draw_top_left (bool) -- (optional) if this is set to True then the top left corner of the circle will be drawn
draw_bottom_left (bool) -- (optional) if this is set to True then the bottom left corner of the circle will be drawn
draw_bottom_right (bool) -- (optional) if this is set to True then the bottom right corner of the circle will be drawn
if any of the draw_circle_part is True then it will draw all circle parts that have the True value, otherwise it will draw the entire circle.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the center parameter value (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
TypeError -- if center is not a sequence of two numbers
TypeError -- if radius is not a number Changed in pygame 2.0.0: Added support for keyword arguments. Nothing is drawn when the radius is 0 (a pixel at the center coordinates used to be drawn when the radius equaled 0). Floats, and Vector2 are accepted for the center param. The drawing algorithm was improved to look more like a circle. Changed in pygame 2.0.0.dev8: Added support for drawing circle quadrants.
pygame.draw.ellipse()
draw an ellipse ellipse(surface, color, rect) -> Rect ellipse(surface, color, rect, width=0) -> Rect Draws an ellipse on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
rect (Rect) -- rectangle to indicate the position and dimensions of the ellipse, the ellipse will be centered inside the rectangle and bounded by it
width (int) -- (optional) used for line thickness or to indicate that the ellipse is to be filled (not to be confused with the width value of the rect parameter)
if width == 0, (default) fill the ellipse if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will only grow inward from the original boundary of the rect parameter.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the given rect parameter and its width and height will be 0
Return type:
Rect Changed in pygame 2.0.0: Added support for keyword arguments.
pygame.draw.arc()
draw an elliptical arc arc(surface, color, rect, start_angle, stop_angle) -> Rect arc(surface, color, rect, start_angle, stop_angle, width=1) -> Rect Draws an elliptical arc on the given surface. The two angle arguments are given in radians and indicate the start and stop positions of the arc. The arc is drawn in a counterclockwise direction from the start_angle to the stop_angle.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
rect (Rect) -- rectangle to indicate the position and dimensions of the ellipse which the arc will be based on, the ellipse will be centered inside the rectangle
start_angle (float) -- start angle of the arc in radians
stop_angle (float) -- stop angle of the arc in radians
if start_angle < stop_angle, the arc is drawn in a counterclockwise direction from the start_angle to the stop_angle
if start_angle > stop_angle, tau (tau == 2 * pi) will be added to the stop_angle, if the resulting stop angle value is greater than the start_angle the above start_angle < stop_angle case applies, otherwise nothing will be drawn if start_angle == stop_angle, nothing will be drawn
width (int) -- (optional) used for line thickness (not to be confused with the width value of the rect parameter)
if width == 0, nothing will be drawn if width > 0, (default is 1) used for line thickness if width < 0, same as width == 0
Note When using width values > 1, the edge lines will only grow inward from the original boundary of the rect parameter.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the given rect parameter and its width and height will be 0
Return type:
Rect Changed in pygame 2.0.0: Added support for keyword arguments.
pygame.draw.line()
draw a straight line line(surface, color, start_pos, end_pos, width) -> Rect line(surface, color, start_pos, end_pos, width=1) -> Rect Draws a straight line on the given surface. There are no endcaps. For thick lines the ends are squared off.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
start_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- start position of the line, (x, y)
end_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- end position of the line, (x, y)
width (int) -- (optional) used for line thickness if width >= 1, used for line thickness (default is 1) if width < 1, nothing will be drawn Note When using width values > 1, lines will grow as follows. For odd width values, the thickness of each line grows with the original line being in the center. For even width values, the thickness of each line grows with the original line being offset from the center (as there is no exact center line drawn). As a result, lines with a slope < 1 (horizontal-ish) will have 1 more pixel of thickness below the original line (in the y direction). Lines with a slope >= 1 (vertical-ish) will have 1 more pixel of thickness to the right of the original line (in the x direction).
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the start_pos parameter value (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
TypeError -- if start_pos or end_pos is not a sequence of two numbers Changed in pygame 2.0.0: Added support for keyword arguments.
pygame.draw.lines()
draw multiple contiguous straight line segments lines(surface, color, closed, points) -> Rect lines(surface, color, closed, points, width=1) -> Rect Draws a sequence of contiguous straight lines on the given surface. There are no endcaps or miter joints. For thick lines the ends are squared off. Drawing thick lines with sharp corners can have undesired looking results.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
closed (bool) -- if True an additional line segment is drawn between the first and last points in the points sequence
points (tuple(coordinate) or list(coordinate)) -- a sequence of 2 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats and adjacent coordinates will be connected by a line segment, e.g. for the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2) and from (x2, y2) to (x3, y3), additionally if the closed parameter is True another line segment will be drawn from (x3, y3) to (x1, y1)
width (int) -- (optional) used for line thickness if width >= 1, used for line thickness (default is 1) if width < 1, nothing will be drawn Note When using width values > 1 refer to the width notes of line() for details on how thick lines grow.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
ValueError -- if len(points) < 2 (must have at least 2 points)
TypeError -- if points is not a sequence or points does not contain number pairs Changed in pygame 2.0.0: Added support for keyword arguments.
pygame.draw.aaline()
draw a straight antialiased line aaline(surface, color, start_pos, end_pos) -> Rect aaline(surface, color, start_pos, end_pos, blend=1) -> Rect Draws a straight antialiased line on the given surface. The line has a thickness of one pixel and the endpoints have a height and width of one pixel each. The way a line and it's endpoints are drawn:
If both endpoints are equal, only a single pixel is drawn (after rounding floats to nearest integer). Otherwise if the line is not steep (i.e. if the length along the x-axis is greater than the height along the y-axis):
For each endpoint:
If x, the endpoint's x-coordinate, is a whole number find which pixels would be covered by it and draw them. Otherwise:
Calculate the position of the nearest point with a whole number for it's x-coordinate, when extending the line past the endpoint. Find which pixels would be covered and how much by that point. If the endpoint is the left one, multiply the coverage by (1 - the decimal part of x). Otherwise multiply the coverage by the decimal part of x. Then draw those pixels. e.g.:
The left endpoint of the line ((1, 1.3), (5, 3)) would cover 70% of the pixel (1, 1) and 30% of the pixel (1, 2) while the right one would cover 100% of the pixel (5, 3). The left endpoint of the line ((1.2, 1.4), (4.6, 3.1)) would cover 56% (i.e. 0.8 * 70%) of the pixel (1, 1) and 24% (i.e. 0.8 * 30%) of the pixel (1, 2) while the right one would cover 42% (i.e. 0.6 * 70%) of the pixel (5, 3) and 18% (i.e. 0.6 * 30%) of the pixel (5, 4) while the right
Then for each point between the endpoints, along the line, whose x-coordinate is a whole number:
Find which pixels would be covered and how much by that point and draw them. e.g.:
The points along the line ((1, 1), (4, 2.5)) would be (2, 1.5) and (3, 2) and would cover 50% of the pixel (2, 1), 50% of the pixel (2, 2) and 100% of the pixel (3, 2). The points along the line ((1.2, 1.4), (4.6, 3.1)) would be (2, 1.8) (covering 20% of the pixel (2, 1) and 80% of the pixel (2, 2)), (3, 2.3) (covering 70% of the pixel (3, 2) and 30% of the pixel (3, 3)) and (4,
2.8) (covering 20% of the pixel (2, 1) and 80% of the pixel (2, 2))
Otherwise do the same for steep lines as for non-steep lines except along the y-axis instead of the x-axis (using y instead of x, top instead of left and bottom instead of right). Note Regarding float values for coordinates, a point with coordinate consisting of two whole numbers is considered being right in the center of said pixel (and having a height and width of 1 pixel would therefore completely cover it), while a point with coordinate where one (or both) of the numbers have non-zero decimal parts would be partially covering two (or four if both numbers have decimal parts) adjacent pixels, e.g. the point (1.4, 2) covers 60% of the pixel (1, 2) and 40% of the pixel (2,2).
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
start_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- start position of the line, (x, y)
end_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- end position of the line, (x, y)
blend (int) -- (optional) if non-zero (default) the line will be blended with the surface's existing pixel shades, otherwise it will overwrite them
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the start_pos parameter value (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
TypeError -- if start_pos or end_pos is not a sequence of two numbers Changed in pygame 2.0.0: Added support for keyword arguments.
pygame.draw.aalines()
draw multiple contiguous straight antialiased line segments aalines(surface, color, closed, points) -> Rect aalines(surface, color, closed, points, blend=1) -> Rect Draws a sequence of contiguous straight antialiased lines on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
closed (bool) -- if True an additional line segment is drawn between the first and last points in the points sequence
points (tuple(coordinate) or list(coordinate)) -- a sequence of 2 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats and adjacent coordinates will be connected by a line segment, e.g. for the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2) and from (x2, y2) to (x3, y3), additionally if the closed parameter is True another line segment will be drawn from (x3, y3) to (x1, y1)
blend (int) -- (optional) if non-zero (default) each line will be blended with the surface's existing pixel shades, otherwise the pixels will be overwritten
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
ValueError -- if len(points) < 2 (must have at least 2 points)
TypeError -- if points is not a sequence or points does not contain number pairs Changed in pygame 2.0.0: Added support for keyword arguments.
Example code for draw module. # Import a library of functions called 'pygame'
import pygame
from math import pi
# Initialize the game engine
pygame.init()
# Define the colors we will use in RGB format
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
# Set the height and width of the screen
size = [400, 300]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Example code for the draw module")
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
while not done:
# This limits the while loop to a max of 10 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(10)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
# All drawing code happens after the for loop and but
# inside the main while done==False loop.
# Clear the screen and set the screen background
screen.fill(WHITE)
# Draw on the screen a GREEN line from (0, 0) to (50, 30)
# 5 pixels wide.
pygame.draw.line(screen, GREEN, [0, 0], [50,30], 5)
# Draw on the screen 3 BLACK lines, each 5 pixels wide.
# The 'False' means the first and last points are not connected.
pygame.draw.lines(screen, BLACK, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)
# Draw on the screen a GREEN line from (0, 50) to (50, 80)
# Because it is an antialiased line, it is 1 pixel wide.
pygame.draw.aaline(screen, GREEN, [0, 50],[50, 80], True)
# Draw a rectangle outline
pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2)
# Draw a solid rectangle
pygame.draw.rect(screen, BLACK, [150, 10, 50, 20])
# Draw a rectangle with rounded corners
pygame.draw.rect(screen, GREEN, [115, 210, 70, 40], 10, border_radius=15)
pygame.draw.rect(screen, RED, [135, 260, 50, 30], 0, border_radius=10, border_top_left_radius=0,
border_bottom_right_radius=15)
# Draw an ellipse outline, using a rectangle as the outside boundaries
pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2)
# Draw an solid ellipse, using a rectangle as the outside boundaries
pygame.draw.ellipse(screen, RED, [300, 10, 50, 20])
# This draws a triangle using the polygon command
pygame.draw.polygon(screen, BLACK, [[100, 100], [0, 200], [200, 200]], 5)
# Draw an arc as part of an ellipse.
# Use radians to determine what angle to draw.
pygame.draw.arc(screen, BLACK,[210, 75, 150, 125], 0, pi/2, 2)
pygame.draw.arc(screen, GREEN,[210, 75, 150, 125], pi/2, pi, 2)
pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi,3*pi/2, 2)
pygame.draw.arc(screen, RED, [210, 75, 150, 125], 3*pi/2, 2*pi, 2)
# Draw a circle
pygame.draw.circle(screen, BLUE, [60, 250], 40)
# Draw only one circle quadrant
pygame.draw.circle(screen, BLUE, [250, 250], 40, 0, draw_top_right=True)
pygame.draw.circle(screen, RED, [250, 250], 40, 30, draw_top_left=True)
pygame.draw.circle(screen, GREEN, [250, 250], 40, 20, draw_bottom_left=True)
pygame.draw.circle(screen, BLACK, [250, 250], 40, 10, draw_bottom_right=True)
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# Be IDLE friendly
pygame.quit() | pygame.ref.draw |
pygame.draw.aaline()
draw a straight antialiased line aaline(surface, color, start_pos, end_pos) -> Rect aaline(surface, color, start_pos, end_pos, blend=1) -> Rect Draws a straight antialiased line on the given surface. The line has a thickness of one pixel and the endpoints have a height and width of one pixel each. The way a line and it's endpoints are drawn:
If both endpoints are equal, only a single pixel is drawn (after rounding floats to nearest integer). Otherwise if the line is not steep (i.e. if the length along the x-axis is greater than the height along the y-axis):
For each endpoint:
If x, the endpoint's x-coordinate, is a whole number find which pixels would be covered by it and draw them. Otherwise:
Calculate the position of the nearest point with a whole number for it's x-coordinate, when extending the line past the endpoint. Find which pixels would be covered and how much by that point. If the endpoint is the left one, multiply the coverage by (1 - the decimal part of x). Otherwise multiply the coverage by the decimal part of x. Then draw those pixels. e.g.:
The left endpoint of the line ((1, 1.3), (5, 3)) would cover 70% of the pixel (1, 1) and 30% of the pixel (1, 2) while the right one would cover 100% of the pixel (5, 3). The left endpoint of the line ((1.2, 1.4), (4.6, 3.1)) would cover 56% (i.e. 0.8 * 70%) of the pixel (1, 1) and 24% (i.e. 0.8 * 30%) of the pixel (1, 2) while the right one would cover 42% (i.e. 0.6 * 70%) of the pixel (5, 3) and 18% (i.e. 0.6 * 30%) of the pixel (5, 4) while the right
Then for each point between the endpoints, along the line, whose x-coordinate is a whole number:
Find which pixels would be covered and how much by that point and draw them. e.g.:
The points along the line ((1, 1), (4, 2.5)) would be (2, 1.5) and (3, 2) and would cover 50% of the pixel (2, 1), 50% of the pixel (2, 2) and 100% of the pixel (3, 2). The points along the line ((1.2, 1.4), (4.6, 3.1)) would be (2, 1.8) (covering 20% of the pixel (2, 1) and 80% of the pixel (2, 2)), (3, 2.3) (covering 70% of the pixel (3, 2) and 30% of the pixel (3, 3)) and (4,
2.8) (covering 20% of the pixel (2, 1) and 80% of the pixel (2, 2))
Otherwise do the same for steep lines as for non-steep lines except along the y-axis instead of the x-axis (using y instead of x, top instead of left and bottom instead of right). Note Regarding float values for coordinates, a point with coordinate consisting of two whole numbers is considered being right in the center of said pixel (and having a height and width of 1 pixel would therefore completely cover it), while a point with coordinate where one (or both) of the numbers have non-zero decimal parts would be partially covering two (or four if both numbers have decimal parts) adjacent pixels, e.g. the point (1.4, 2) covers 60% of the pixel (1, 2) and 40% of the pixel (2,2).
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
start_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- start position of the line, (x, y)
end_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- end position of the line, (x, y)
blend (int) -- (optional) if non-zero (default) the line will be blended with the surface's existing pixel shades, otherwise it will overwrite them
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the start_pos parameter value (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
TypeError -- if start_pos or end_pos is not a sequence of two numbers Changed in pygame 2.0.0: Added support for keyword arguments. | pygame.ref.draw#pygame.draw.aaline |
pygame.draw.aalines()
draw multiple contiguous straight antialiased line segments aalines(surface, color, closed, points) -> Rect aalines(surface, color, closed, points, blend=1) -> Rect Draws a sequence of contiguous straight antialiased lines on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
closed (bool) -- if True an additional line segment is drawn between the first and last points in the points sequence
points (tuple(coordinate) or list(coordinate)) -- a sequence of 2 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats and adjacent coordinates will be connected by a line segment, e.g. for the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2) and from (x2, y2) to (x3, y3), additionally if the closed parameter is True another line segment will be drawn from (x3, y3) to (x1, y1)
blend (int) -- (optional) if non-zero (default) each line will be blended with the surface's existing pixel shades, otherwise the pixels will be overwritten
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
ValueError -- if len(points) < 2 (must have at least 2 points)
TypeError -- if points is not a sequence or points does not contain number pairs Changed in pygame 2.0.0: Added support for keyword arguments. | pygame.ref.draw#pygame.draw.aalines |
pygame.draw.arc()
draw an elliptical arc arc(surface, color, rect, start_angle, stop_angle) -> Rect arc(surface, color, rect, start_angle, stop_angle, width=1) -> Rect Draws an elliptical arc on the given surface. The two angle arguments are given in radians and indicate the start and stop positions of the arc. The arc is drawn in a counterclockwise direction from the start_angle to the stop_angle.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
rect (Rect) -- rectangle to indicate the position and dimensions of the ellipse which the arc will be based on, the ellipse will be centered inside the rectangle
start_angle (float) -- start angle of the arc in radians
stop_angle (float) -- stop angle of the arc in radians
if start_angle < stop_angle, the arc is drawn in a counterclockwise direction from the start_angle to the stop_angle
if start_angle > stop_angle, tau (tau == 2 * pi) will be added to the stop_angle, if the resulting stop angle value is greater than the start_angle the above start_angle < stop_angle case applies, otherwise nothing will be drawn if start_angle == stop_angle, nothing will be drawn
width (int) -- (optional) used for line thickness (not to be confused with the width value of the rect parameter)
if width == 0, nothing will be drawn if width > 0, (default is 1) used for line thickness if width < 0, same as width == 0
Note When using width values > 1, the edge lines will only grow inward from the original boundary of the rect parameter.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the given rect parameter and its width and height will be 0
Return type:
Rect Changed in pygame 2.0.0: Added support for keyword arguments. | pygame.ref.draw#pygame.draw.arc |
pygame.draw.circle()
draw a circle circle(surface, color, center, radius) -> Rect circle(surface, color, center, radius, width=0, draw_top_right=None, draw_top_left=None, draw_bottom_left=None, draw_bottom_right=None) -> Rect Draws a circle on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
center (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- center point of the circle as a sequence of 2 ints/floats, e.g. (x, y)
radius (int or float) -- radius of the circle, measured from the center parameter, nothing will be drawn if the radius is less than 1
width (int) -- (optional) used for line thickness or to indicate that the circle is to be filled
if width == 0, (default) fill the circle if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will only grow inward.
draw_top_right (bool) -- (optional) if this is set to True then the top right corner of the circle will be drawn
draw_top_left (bool) -- (optional) if this is set to True then the top left corner of the circle will be drawn
draw_bottom_left (bool) -- (optional) if this is set to True then the bottom left corner of the circle will be drawn
draw_bottom_right (bool) -- (optional) if this is set to True then the bottom right corner of the circle will be drawn
if any of the draw_circle_part is True then it will draw all circle parts that have the True value, otherwise it will draw the entire circle.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the center parameter value (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
TypeError -- if center is not a sequence of two numbers
TypeError -- if radius is not a number Changed in pygame 2.0.0: Added support for keyword arguments. Nothing is drawn when the radius is 0 (a pixel at the center coordinates used to be drawn when the radius equaled 0). Floats, and Vector2 are accepted for the center param. The drawing algorithm was improved to look more like a circle. Changed in pygame 2.0.0.dev8: Added support for drawing circle quadrants. | pygame.ref.draw#pygame.draw.circle |
pygame.draw.ellipse()
draw an ellipse ellipse(surface, color, rect) -> Rect ellipse(surface, color, rect, width=0) -> Rect Draws an ellipse on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
rect (Rect) -- rectangle to indicate the position and dimensions of the ellipse, the ellipse will be centered inside the rectangle and bounded by it
width (int) -- (optional) used for line thickness or to indicate that the ellipse is to be filled (not to be confused with the width value of the rect parameter)
if width == 0, (default) fill the ellipse if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will only grow inward from the original boundary of the rect parameter.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the given rect parameter and its width and height will be 0
Return type:
Rect Changed in pygame 2.0.0: Added support for keyword arguments. | pygame.ref.draw#pygame.draw.ellipse |
pygame.draw.line()
draw a straight line line(surface, color, start_pos, end_pos, width) -> Rect line(surface, color, start_pos, end_pos, width=1) -> Rect Draws a straight line on the given surface. There are no endcaps. For thick lines the ends are squared off.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
start_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- start position of the line, (x, y)
end_pos (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) -- end position of the line, (x, y)
width (int) -- (optional) used for line thickness if width >= 1, used for line thickness (default is 1) if width < 1, nothing will be drawn Note When using width values > 1, lines will grow as follows. For odd width values, the thickness of each line grows with the original line being in the center. For even width values, the thickness of each line grows with the original line being offset from the center (as there is no exact center line drawn). As a result, lines with a slope < 1 (horizontal-ish) will have 1 more pixel of thickness below the original line (in the y direction). Lines with a slope >= 1 (vertical-ish) will have 1 more pixel of thickness to the right of the original line (in the x direction).
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the start_pos parameter value (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
TypeError -- if start_pos or end_pos is not a sequence of two numbers Changed in pygame 2.0.0: Added support for keyword arguments. | pygame.ref.draw#pygame.draw.line |
pygame.draw.lines()
draw multiple contiguous straight line segments lines(surface, color, closed, points) -> Rect lines(surface, color, closed, points, width=1) -> Rect Draws a sequence of contiguous straight lines on the given surface. There are no endcaps or miter joints. For thick lines the ends are squared off. Drawing thick lines with sharp corners can have undesired looking results.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
closed (bool) -- if True an additional line segment is drawn between the first and last points in the points sequence
points (tuple(coordinate) or list(coordinate)) -- a sequence of 2 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats and adjacent coordinates will be connected by a line segment, e.g. for the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2) and from (x2, y2) to (x3, y3), additionally if the closed parameter is True another line segment will be drawn from (x3, y3) to (x1, y1)
width (int) -- (optional) used for line thickness if width >= 1, used for line thickness (default is 1) if width < 1, nothing will be drawn Note When using width values > 1 refer to the width notes of line() for details on how thick lines grow.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
ValueError -- if len(points) < 2 (must have at least 2 points)
TypeError -- if points is not a sequence or points does not contain number pairs Changed in pygame 2.0.0: Added support for keyword arguments. | pygame.ref.draw#pygame.draw.lines |
pygame.draw.polygon()
draw a polygon polygon(surface, color, points) -> Rect polygon(surface, color, points, width=0) -> Rect Draws a polygon on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
points (tuple(coordinate) or list(coordinate)) -- a sequence of 3 or more (x, y) coordinates that make up the vertices of the polygon, each coordinate in the sequence must be a tuple/list/pygame.math.Vector2 of 2 ints/floats, e.g. [(x1, y1), (x2, y2), (x3, y3)]
width (int) -- (optional) used for line thickness or to indicate that the polygon is to be filled
if width == 0, (default) fill the polygon if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will grow outside the original boundary of the polygon. For more details on how the thickness for edge lines grow, refer to the width notes of the pygame.draw.line() function.
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
Return type:
Rect
Raises:
ValueError -- if len(points) < 3 (must have at least 3 points)
TypeError -- if points is not a sequence or points does not contain number pairs Note For an aapolygon, use aalines() with closed=True. Changed in pygame 2.0.0: Added support for keyword arguments. | pygame.ref.draw#pygame.draw.polygon |
pygame.draw.rect()
draw a rectangle rect(surface, color, rect) -> Rect rect(surface, color, rect, width=0, border_radius=0, border_top_left_radius=-1, border_top_right_radius=-1, border_bottom_left_radius=-1, border_bottom_right_radius=-1) -> Rect Draws a rectangle on the given surface.
Parameters:
surface (Surface) -- surface to draw on
color (Color or int or tuple(int, int, int, [int])) -- color to draw with, the alpha value is optional if using a tuple (RGB[A])
rect (Rect) -- rectangle to draw, position and dimensions
width (int) -- (optional) used for line thickness or to indicate that the rectangle is to be filled (not to be confused with the width value of the rect parameter)
if width == 0, (default) fill the rectangle if width > 0, used for line thickness if width < 0, nothing will be drawn Note When using width values > 1, the edge lines will grow outside the original boundary of the rect. For more details on how the thickness for edge lines grow, refer to the width notes of the pygame.draw.line() function.
border_radius (int) -- (optional) used for drawing rectangle with rounded corners. The supported range is [0, min(height, width) / 2], with 0 representing a rectangle without rounded corners.
border_top_left_radius (int) -- (optional) used for setting the value of top left border. If you don't set this value, it will use the border_radius value.
border_top_right_radius (int) -- (optional) used for setting the value of top right border. If you don't set this value, it will use the border_radius value.
border_bottom_left_radius (int) -- (optional) used for setting the value of bottom left border. If you don't set this value, it will use the border_radius value.
border_bottom_right_radius (int) -- (optional) used for setting the value of bottom right border. If you don't set this value, it will use the border_radius value.
if border_radius < 1 it will draw rectangle without rounded corners if any of border radii has the value < 0 it will use value of the border_radius If sum of radii on the same side of the rectangle is greater than the rect size the radii will get scaled
Returns:
a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the position of the given rect parameter and its width and height will be 0
Return type:
Rect Note The pygame.Surface.fill() method works just as well for drawing filled rectangles and can be hardware accelerated on some platforms with both software and hardware display modes. Changed in pygame 2.0.0: Added support for keyword arguments. Changed in pygame 2.0.0.dev8: Added support for border radius. | pygame.ref.draw#pygame.draw.rect |
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.ref.pygame#pygame.encode_file_path |
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.ref.pygame#pygame.encode_string |
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.ref.pygame#pygame.error |
pygame.event
pygame module for interacting with events and queues Pygame handles all its event messaging through an event queue. The routines in this module help you manage that event queue. The input queue is heavily dependent on the pygame.display module. If the display has not been initialized and a video mode not set, the event queue may not work properly. The event subsystem should be called from the main thread. If you want to post events into the queue from other threads, please use the pygame.fastevent module. The event queue has an upper limit on the number of events it can hold (128 for standard SDL 1.2). When the queue becomes full new events are quietly dropped. To prevent lost events, especially input events which signal a quit command, your program must handle events every frame (with pygame.event.get(), pygame.event.pump(), pygame.event.wait(), pygame.event.peek() or pygame.event.clear()) and process them. Not handling events may cause your system to decide your program has locked up. To speed up queue processing use pygame.event.set_blocked() to limit which events get queued. To get the state of various input devices, you can forego the event queue and access the input devices directly with their appropriate modules: pygame.mouse, pygame.key, and pygame.joystick. If you use this method, remember that pygame requires some form of communication with the system window manager and other parts of the platform. To keep pygame in sync with the system, you will need to call pygame.event.pump() to keep everything current. Usually, this should be called once per game loop. Note: Joysticks will not send any events until the device has been initialized. The event queue contains pygame.event.EventType event objects. There are a variety of ways to access the queued events, from simply checking for the existence of events, to grabbing them directly off the stack. The event queue also offers some simple filtering which can slightly help performance by blocking certain event types from the queue. Use pygame.event.set_allowed() and pygame.event.set_blocked() to change this filtering. By default, all event types can be placed on the queue. All pygame.event.EventType instances contain an event type identifier and attributes specific to that event type. The event type identifier is accessible as the pygame.event.EventType.type property. Any of the event specific attributes can be accessed through the pygame.event.EventType.__dict__ attribute or directly as an attribute of the event object (as member lookups are passed through to the object's dictionary values). The event object has no method functions. Users can create their own new events with the pygame.event.Event() function. The event type identifier is in between the values of NOEVENT and NUMEVENTS. User defined events should have a value in the inclusive range of USEREVENT to NUMEVENTS - 1. It is recommended all user events follow this system. Events support equality and inequality comparisons. Two events are equal if they are the same type and have identical attribute values. While debugging and experimenting, you can print an event object for a quick display of its type and members. The function pygame.event.event_name() can be used to get a string representing the name of the event type. Events that come from the system will have a guaranteed set of member attributes based on the type. The following is a list event types with their specific attributes. QUIT none
ACTIVEEVENT gain, state
KEYDOWN key, mod, unicode, scancode
KEYUP key, mod
MOUSEMOTION pos, rel, buttons
MOUSEBUTTONUP pos, button
MOUSEBUTTONDOWN pos, button
JOYAXISMOTION joy (deprecated), instance_id, axis, value
JOYBALLMOTION joy (deprecated), instance_id, ball, rel
JOYHATMOTION joy (deprecated), instance_id, hat, value
JOYBUTTONUP joy (deprecated), instance_id, button
JOYBUTTONDOWN joy (deprecated), instance_id, button
VIDEORESIZE size, w, h
VIDEOEXPOSE none
USEREVENT code Changed in pygame 2.0.0: The joy attribute was deprecated, instance_id was added. You can also find a list of constants for keyboard keys here. On MacOSX when a file is opened using a pygame application, a USEREVENT with its code attribute set to pygame.USEREVENT_DROPFILE is generated. There is an additional attribute called filename where the name of the file being accessed is stored. USEREVENT code=pygame.USEREVENT_DROPFILE, filename New in pygame 1.9.2. When compiled with SDL2, pygame has these additional events and their attributes. AUDIODEVICEADDED which, iscapture
AUDIODEVICEREMOVED which, iscapture
FINGERMOTION touch_id, finger_id, x, y, dx, dy
FINGERDOWN touch_id, finger_id, x, y, dx, dy
FINGERUP touch_id, finger_id, x, y, dx, dy
MOUSEWHEEL which, flipped, x, y
MULTIGESTURE touch_id, x, y, pinched, rotated, num_fingers
TEXTEDITING text, start, length
TEXTINPUT text
WINDOWEVENT event New in pygame 1.9.5. pygame can recognize text or files dropped in its window. If a file is dropped, file will be its path. The DROPTEXT event is only supported on X11. DROPBEGIN
DROPCOMPLETE
DROPFILE file
DROPTEXT text New in pygame 2.0.0. Events reserved for pygame.midi use. MIDIIN
MIDIOUT New in pygame 2.0.0. SDL2 supports controller hotplugging: CONTROLLERDEVICEADDED device_index
JOYDEVICEADDED device_index
CONTROLLERDEVICEREMOVED instance_id
JOYDEVICEREMOVED instance_id
CONTROLLERDEVICEREMAPPED instance_id Also in this version, instance_id attributes were added to joystick events, and the joy attribute was deprecated. New in pygame 2.0.0. pygame.event.pump()
internally process pygame event handlers pump() -> None For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions. This function is not necessary if your program is consistently processing events on the queue through the other pygame.event functions. There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up. Caution This function should only be called in the thread that initialized pygame.display.
pygame.event.get()
get events from the queue get(eventtype=None) -> Eventlist get(eventtype=None, pump=True) -> Eventlist This will get all the messages and remove them from the queue. If a type or sequence of types is given only those messages will be removed from the queue. If you are only taking specific events from the queue, be aware that the queue could eventually fill up with the events you are not interested. If pump is True (the default), then pygame.event.pump() will be called. Changed in pygame 1.9.5: Added pump argument
pygame.event.poll()
get a single event from the queue poll() -> EventType instance Returns a single event from the queue. If the event queue is empty an event of type pygame.NOEVENT will be returned immediately. The returned event is removed from the queue. Caution This function should only be called in the thread that initialized pygame.display.
pygame.event.wait()
wait for a single event from the queue wait() -> EventType instance wait(timeout) -> EventType instance Returns a single event from the queue. If the queue is empty this function will wait until one is created. From pygame 2.0.0, if a timeout argument is given, the function will return an event of type pygame.NOEVENT if no events enter the queue in timeout milliseconds. The event is removed from the queue once it has been returned. While the program is waiting it will sleep in an idle state. This is important for programs that want to share the system with other applications. Changed in pygame 2.0.0.dev13: Added timeout argument Caution This function should only be called in the thread that initialized pygame.display.
pygame.event.peek()
test if event types are waiting on the queue peek(eventtype=None) -> bool peek(eventtype=None, pump=True) -> bool Returns True if there are any events of the given type waiting on the queue. If a sequence of event types is passed, this will return True if any of those events are on the queue. If pump is True (the default), then pygame.event.pump() will be called. Changed in pygame 1.9.5: Added pump argument
pygame.event.clear()
remove all events from the queue clear(eventtype=None) -> None clear(eventtype=None, pump=True) -> None Removes all events from the queue. If eventtype is given, removes the given event or sequence of events. This has the same effect as pygame.event.get() except None is returned. It can be slightly more efficient when clearing a full event queue. If pump is True (the default), then pygame.event.pump() will be called. Changed in pygame 1.9.5: Added pump argument
pygame.event.event_name()
get the string name from an event id event_name(type) -> string Returns a string representing the name (in CapWords style) of the given event type. "UserEvent" is returned for all values in the user event id range. "Unknown" is returned when the event type does not exist.
pygame.event.set_blocked()
control which events are allowed on the queue set_blocked(type) -> None set_blocked(typelist) -> None set_blocked(None) -> None The given event types are not allowed to appear on the event queue. By default all events can be placed on the queue. It is safe to disable an event type multiple times. If None is passed as the argument, ALL of the event types are blocked from being placed on the queue.
pygame.event.set_allowed()
control which events are allowed on the queue set_allowed(type) -> None set_allowed(typelist) -> None set_allowed(None) -> None The given event types are allowed to appear on the event queue. By default, all event types can be placed on the queue. It is safe to enable an event type multiple times. If None is passed as the argument, ALL of the event types are allowed to be placed on the queue.
pygame.event.get_blocked()
test if a type of event is blocked from the queue get_blocked(type) -> bool get_blocked(typelist) -> bool Returns True if the given event type is blocked from the queue. If a sequence of event types is passed, this will return True if any of those event types are blocked.
pygame.event.set_grab()
control the sharing of input devices with other applications set_grab(bool) -> None When your program runs in a windowed environment, it will share the mouse and keyboard devices with other applications that have focus. If your program sets the event grab to True, it will lock all input into your program. It is best to not always grab the input, since it prevents the user from doing other things on their system.
pygame.event.get_grab()
test if the program is sharing input devices get_grab() -> bool Returns True when the input events are grabbed for this application.
pygame.event.post()
place a new event on the queue post(Event) -> None Places the given event at the end of the event queue. This is usually used for placing pygame.USEREVENT events on the queue. Although any type of event can be placed, if using the system event types your program should be sure to create the standard attributes with appropriate values. If the event queue is full a pygame.error is raised. Caution: In pygame 2.0, calling this function with event types defined by pygame (such as pygame.KEYDOWN) may put events into the SDL2 event queue. In this case, an error may be raised if standard attributes of that event are missing or have incompatible values, and unexpected properties may be silently omitted. In order to avoid this behaviour, custom event properties should be used with custom event types. This behaviour is not guaranteed.
pygame.event.custom_type()
make custom user event type custom_type() -> int Reserves a pygame.USEREVENT for a custom use. If too many events are made a pygame.error is raised. New in pygame 2.0.0.dev3.
pygame.event.Event()
create a new event object Event(type, dict) -> EventType instance Event(type, **attributes) -> EventType instance Creates a new event with the given type and attributes. The attributes can come from a dictionary argument with string keys or from keyword arguments.
pygame.event.EventType
pygame object for representing events A pygame object that represents an event. User event instances are created with an pygame.event.Event() function call. The EventType type is not directly callable. EventType instances support attribute assignment and deletion. type
event type identifier. type -> int Read-only. The event type identifier. For user created event objects, this is the type argument passed to pygame.event.Event(). For example, some predefined event identifiers are QUIT and MOUSEMOTION.
__dict__
event attribute dictionary __dict__ -> dict Read-only. The event type specific attributes of an event. The dict attribute is a synonym for backward compatibility. For example, the attributes of a KEYDOWN event would be unicode, key, and mod
New in pygame 1.9.2: Mutable attributes. | pygame.ref.event |
pygame.event.clear()
remove all events from the queue clear(eventtype=None) -> None clear(eventtype=None, pump=True) -> None Removes all events from the queue. If eventtype is given, removes the given event or sequence of events. This has the same effect as pygame.event.get() except None is returned. It can be slightly more efficient when clearing a full event queue. If pump is True (the default), then pygame.event.pump() will be called. Changed in pygame 1.9.5: Added pump argument | pygame.ref.event#pygame.event.clear |
pygame.event.custom_type()
make custom user event type custom_type() -> int Reserves a pygame.USEREVENT for a custom use. If too many events are made a pygame.error is raised. New in pygame 2.0.0.dev3. | pygame.ref.event#pygame.event.custom_type |
pygame.event.Event()
create a new event object Event(type, dict) -> EventType instance Event(type, **attributes) -> EventType instance Creates a new event with the given type and attributes. The attributes can come from a dictionary argument with string keys or from keyword arguments. | pygame.ref.event#pygame.event.Event |
pygame.event.event_name()
get the string name from an event id event_name(type) -> string Returns a string representing the name (in CapWords style) of the given event type. "UserEvent" is returned for all values in the user event id range. "Unknown" is returned when the event type does not exist. | pygame.ref.event#pygame.event.event_name |
pygame.event.EventType
pygame object for representing events A pygame object that represents an event. User event instances are created with an pygame.event.Event() function call. The EventType type is not directly callable. EventType instances support attribute assignment and deletion. type
event type identifier. type -> int Read-only. The event type identifier. For user created event objects, this is the type argument passed to pygame.event.Event(). For example, some predefined event identifiers are QUIT and MOUSEMOTION.
__dict__
event attribute dictionary __dict__ -> dict Read-only. The event type specific attributes of an event. The dict attribute is a synonym for backward compatibility. For example, the attributes of a KEYDOWN event would be unicode, key, and mod
New in pygame 1.9.2: Mutable attributes. | pygame.ref.event#pygame.event.EventType |
__dict__
event attribute dictionary __dict__ -> dict Read-only. The event type specific attributes of an event. The dict attribute is a synonym for backward compatibility. For example, the attributes of a KEYDOWN event would be unicode, key, and mod | pygame.ref.event#pygame.event.EventType.__dict__ |
type
event type identifier. type -> int Read-only. The event type identifier. For user created event objects, this is the type argument passed to pygame.event.Event(). For example, some predefined event identifiers are QUIT and MOUSEMOTION. | pygame.ref.event#pygame.event.EventType.type |
pygame.event.get()
get events from the queue get(eventtype=None) -> Eventlist get(eventtype=None, pump=True) -> Eventlist This will get all the messages and remove them from the queue. If a type or sequence of types is given only those messages will be removed from the queue. If you are only taking specific events from the queue, be aware that the queue could eventually fill up with the events you are not interested. If pump is True (the default), then pygame.event.pump() will be called. Changed in pygame 1.9.5: Added pump argument | pygame.ref.event#pygame.event.get |
pygame.event.get_blocked()
test if a type of event is blocked from the queue get_blocked(type) -> bool get_blocked(typelist) -> bool Returns True if the given event type is blocked from the queue. If a sequence of event types is passed, this will return True if any of those event types are blocked. | pygame.ref.event#pygame.event.get_blocked |
pygame.event.get_grab()
test if the program is sharing input devices get_grab() -> bool Returns True when the input events are grabbed for this application. | pygame.ref.event#pygame.event.get_grab |
pygame.event.peek()
test if event types are waiting on the queue peek(eventtype=None) -> bool peek(eventtype=None, pump=True) -> bool Returns True if there are any events of the given type waiting on the queue. If a sequence of event types is passed, this will return True if any of those events are on the queue. If pump is True (the default), then pygame.event.pump() will be called. Changed in pygame 1.9.5: Added pump argument | pygame.ref.event#pygame.event.peek |
pygame.event.poll()
get a single event from the queue poll() -> EventType instance Returns a single event from the queue. If the event queue is empty an event of type pygame.NOEVENT will be returned immediately. The returned event is removed from the queue. Caution This function should only be called in the thread that initialized pygame.display. | pygame.ref.event#pygame.event.poll |
pygame.event.post()
place a new event on the queue post(Event) -> None Places the given event at the end of the event queue. This is usually used for placing pygame.USEREVENT events on the queue. Although any type of event can be placed, if using the system event types your program should be sure to create the standard attributes with appropriate values. If the event queue is full a pygame.error is raised. Caution: In pygame 2.0, calling this function with event types defined by pygame (such as pygame.KEYDOWN) may put events into the SDL2 event queue. In this case, an error may be raised if standard attributes of that event are missing or have incompatible values, and unexpected properties may be silently omitted. In order to avoid this behaviour, custom event properties should be used with custom event types. This behaviour is not guaranteed. | pygame.ref.event#pygame.event.post |
pygame.event.pump()
internally process pygame event handlers pump() -> None For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions. This function is not necessary if your program is consistently processing events on the queue through the other pygame.event functions. There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up. Caution This function should only be called in the thread that initialized pygame.display. | pygame.ref.event#pygame.event.pump |
pygame.event.set_allowed()
control which events are allowed on the queue set_allowed(type) -> None set_allowed(typelist) -> None set_allowed(None) -> None The given event types are allowed to appear on the event queue. By default, all event types can be placed on the queue. It is safe to enable an event type multiple times. If None is passed as the argument, ALL of the event types are allowed to be placed on the queue. | pygame.ref.event#pygame.event.set_allowed |
pygame.event.set_blocked()
control which events are allowed on the queue set_blocked(type) -> None set_blocked(typelist) -> None set_blocked(None) -> None The given event types are not allowed to appear on the event queue. By default all events can be placed on the queue. It is safe to disable an event type multiple times. If None is passed as the argument, ALL of the event types are blocked from being placed on the queue. | pygame.ref.event#pygame.event.set_blocked |
pygame.event.set_grab()
control the sharing of input devices with other applications set_grab(bool) -> None When your program runs in a windowed environment, it will share the mouse and keyboard devices with other applications that have focus. If your program sets the event grab to True, it will lock all input into your program. It is best to not always grab the input, since it prevents the user from doing other things on their system. | pygame.ref.event#pygame.event.set_grab |
pygame.event.wait()
wait for a single event from the queue wait() -> EventType instance wait(timeout) -> EventType instance Returns a single event from the queue. If the queue is empty this function will wait until one is created. From pygame 2.0.0, if a timeout argument is given, the function will return an event of type pygame.NOEVENT if no events enter the queue in timeout milliseconds. The event is removed from the queue once it has been returned. While the program is waiting it will sleep in an idle state. This is important for programs that want to share the system with other applications. Changed in pygame 2.0.0.dev13: Added timeout argument Caution This function should only be called in the thread that initialized pygame.display. | pygame.ref.event#pygame.event.wait |
pygame.examples
module of example programs These examples should help get you started with pygame. Here is a brief rundown of what you get. The source code for these examples is in the public domain. Feel free to use for your own projects. There are several ways to run the examples. First they can be run as stand-alone programs. Second they can be imported and their main() methods called (see below). Finally, the easiest way is to use the python -m option: python -m pygame.examples.<example name> <example arguments> eg: python -m pygame.examples.scaletest someimage.png Resources such as images and sounds for the examples are found in the pygame/examples/data subdirectory. You can find where the example files are installed by using the following commands inside the python interpreter. >>> import pygame.examples.scaletest
>>> pygame.examples.scaletest.__file__
'/usr/lib/python2.6/site-packages/pygame/examples/scaletest.py' On each OS and version of Python the location will be slightly different. For example on Windows it might be in 'C:/Python26/Lib/site-packages/pygame/examples/' On Mac OS X it might be in '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pygame/examples/' You can also run the examples in the python interpreter by calling each modules main() function. >>> import pygame.examples.scaletest
>>> pygame.examples.scaletest.main() We're always on the lookout for more examples and/or example requests. Code like this is probably the best way to start getting involved with python gaming. examples as a package is new to pygame 1.9.0. But most of the examples came with pygame much earlier. aliens.main()
play the full aliens example aliens.main() -> None This started off as a port of the SDL demonstration, Aliens. Now it has evolved into something sort of resembling fun. This demonstrates a lot of different uses of sprites and optimized blitting. Also transparency, colorkeys, fonts, sound, music, joystick, and more. (PS, my high score is 117! goodluck)
oldalien.main()
play the original aliens example oldalien.main() -> None This more closely resembles a port of the SDL Aliens demo. The code is a lot simpler, so it makes a better starting point for people looking at code for the first times. These blitting routines are not as optimized as they should/could be, but the code is easier to follow, and it plays quick enough.
stars.main()
run a simple starfield example stars.main() -> None A simple starfield example. You can change the center of perspective by leftclicking the mouse on the screen.
chimp.main()
hit the moving chimp chimp.main() -> None This simple example is derived from the line-by-line tutorial that comes with pygame. It is based on a 'popular' web banner. Note there are comments here, but for the full explanation, follow along in the tutorial.
moveit.main()
display animated objects on the screen moveit.main() -> None This is the full and final example from the Pygame Tutorial, "How Do I Make It Move". It creates 10 objects and animates them on the screen. Note it's a bit scant on error checking, but it's easy to read. :] Fortunately, this is python, and we needn't wrestle with a pile of error codes.
fonty.main()
run a font rendering example fonty.main() -> None Super quick, super simple application demonstrating the different ways to render fonts with the font module
freetype_misc.main()
run a FreeType rendering example freetype_misc.main() -> None A showcase of rendering features the pygame.freetype.Font class provides in addition to those available with pygame.font.Font. It is a demonstration of direct to surface rendering, with vertical text and rotated text, opaque text and semi transparent text, horizontally stretched text and vertically stretched text.
vgrade.main()
display a vertical gradient vgrade.main() -> None Demonstrates creating a vertical gradient with pixelcopy and NumPy python. The app will create a new gradient every half second and report the time needed to create and display the image. If you're not prepared to start working with the NumPy arrays, don't worry about the source for this one :]
eventlist.main()
display pygame events eventlist.main() -> None Eventlist is a sloppy style of pygame, but is a handy tool for learning about pygame events and input. At the top of the screen are the state of several device values, and a scrolling list of events are displayed on the bottom. This is not quality 'ui' code at all, but you can see how to implement very non-interactive status displays, or even a crude text output control.
arraydemo.main()
show various surfarray effects arraydemo.main(arraytype=None) -> None Another example filled with various surfarray effects. It requires the surfarray and image modules to be installed. This little demo can also make a good starting point for any of your own tests with surfarray The arraytype parameter is deprecated; passing any value besides 'numpy' will raise ValueError.
sound.main()
load and play a sound sound.main(file_path=None) -> None Extremely basic testing of the mixer module. Load a sound and play it. All from the command shell, no graphics. If provided, use the audio file 'file_path', otherwise use a default file. sound.py optional command line argument: an audio file
sound_array_demos.main()
play various sndarray effects sound_array_demos.main(arraytype=None) -> None Uses sndarray and NumPy to create offset faded copies of the original sound. Currently it just uses hardcoded values for the number of echoes and the delay. Easy for you to recreate as needed. The arraytype parameter is deprecated; passing any value besides 'numpy' will raise ValueError.
liquid.main()
display an animated liquid effect liquid.main() -> None This example was created in a quick comparison with the BlitzBasic gaming language. Nonetheless, it demonstrates a quick 8-bit setup (with colormap).
glcube.main()
display an animated 3D cube using OpenGL glcube.main() -> None Using PyOpenGL and pygame, this creates a spinning 3D multicolored cube.
scrap_clipboard.main()
access the clipboard scrap_clipboard.main() -> None A simple demonstration example for the clipboard support.
mask.main()
display multiple images bounce off each other using collision detection mask.main(*args) -> None Positional arguments: one or more image file names. This pygame.masks demo will display multiple moving sprites bouncing off each other. More than one sprite image can be provided. If run as a program then mask.py takes one or more image files as command line arguments.
testsprite.main()
show lots of sprites moving around testsprite.main(update_rects = True, use_static = False, use_FastRenderGroup = False, screen_dims = [640, 480], use_alpha = False, flags = 0) -> None Optional keyword arguments: update_rects - use the RenderUpdate sprite group class
use_static - include non-moving images
use_FastRenderGroup - Use the FastRenderGroup sprite group
screen_dims - pygame window dimensions
use_alpha - use alpha blending
flags - additional display mode flags Like the testsprite.c that comes with SDL, this pygame version shows lots of sprites moving around. If run as a stand-alone program then no command line arguments are taken.
headless_no_windows_needed.main()
write an image file that is smoothscaled copy of an input file headless_no_windows_needed.main(fin, fout, w, h) -> None arguments: fin - name of an input image file
fout - name of the output file to create/overwrite
w, h - size of the rescaled image, as integer width and height How to use pygame with no windowing system, like on headless servers. Thumbnail generation with scaling is an example of what you can do with pygame. NOTE: the pygame scale function uses MMX/SSE if available, and can be run in multiple threads. If headless_no_windows_needed.py is run as a program it takes the following command line arguments: -scale inputimage outputimage new_width new_height
eg. -scale in.png outpng 50 50
fastevents.main()
stress test the fastevents module fastevents.main() -> None This is a stress test for the fastevents module.
Fast events does not appear faster!
So far it looks like normal pygame.event is faster by up to two times. So maybe fastevent isn't fast at all. Tested on Windows XP SP2 Athlon, and FreeBSD. However... on my Debian Duron 850 machine fastevents is faster.
overlay.main()
play a .pgm video using overlays overlay.main(fname) -> None Play the .pgm video file given by a path fname. If run as a program overlay.py takes the file name as a command line argument.
blend_fill.main()
demonstrate the various surface.fill method blend options blend_fill.main() -> None A interactive demo that lets one choose which BLEND_xxx option to apply to a surface.
blit_blends.main()
uses alternative additive fill to that of surface.fill blit_blends.main() -> None Fake additive blending. Using NumPy. it doesn't clamp. Press r,g,b Somewhat like blend_fill.
cursors.main()
display two different custom cursors cursors.main() -> None Display an arrow or circle with crossbar cursor.
pixelarray.main()
display various pixelarray generated effects pixelarray.main() -> None Display various pixelarray generated effects.
scaletest.main()
interactively scale an image using smoothscale scaletest.main(imagefile, convert_alpha=False, run_speed_test=True) -> None arguments: imagefile - file name of source image (required)
convert_alpha - use convert_alpha() on the surf (default False)
run_speed_test - (default False) A smoothscale example that resized an image on the screen. Vertical and horizontal arrow keys are used to change the width and height of the displayed image. If the convert_alpha option is True then the source image is forced to have source alpha, whether or not the original images does. If run_speed_test is True then a background timing test is performed instead of the interactive scaler. If scaletest.py is run as a program then the command line options are: ImageFile [-t] [-convert_alpha]
[-t] = Run Speed Test
[-convert_alpha] = Use convert_alpha() on the surf.
midi.main()
run a midi example midi.main(mode='output', device_id=None) -> None Arguments: mode - if 'output' run a midi keyboard output example
'input' run a midi event logger input example
'list' list available midi devices
(default 'output')
device_id - midi device number; if None then use the default midi input or
output device for the system The output example shows how to translate mouse clicks or computer keyboard events into midi notes. It implements a rudimentary button widget and state machine. The input example shows how to translate midi input to pygame events. With the use of a virtual midi patch cord the output and input examples can be run as separate processes and connected so the keyboard output is displayed on a console. new to pygame 1.9.0
scroll.main()
run a Surface.scroll example that shows a magnified image scroll.main(image_file=None) -> None This example shows a scrollable image that has a zoom factor of eight. It uses the Surface.scroll() function to shift the image on the display surface. A clip rectangle protects a margin area. If called as a function, the example accepts an optional image file path. If run as a program it takes an optional file path command line argument. If no file is provided a default image file is used. When running click on a black triangle to move one pixel in the direction the triangle points. Or use the arrow keys. Close the window or press ESC to quit.
camera.main()
display video captured live from an attached camera camera.main() -> None A simple live video player, it uses the first available camera it finds on the system.
playmus.main()
play an audio file playmus.main(file_path) -> None A simple music player with window and keyboard playback control. Playback can be paused and rewound to the beginning. | pygame.ref.examples |
aliens.main()
play the full aliens example aliens.main() -> None This started off as a port of the SDL demonstration, Aliens. Now it has evolved into something sort of resembling fun. This demonstrates a lot of different uses of sprites and optimized blitting. Also transparency, colorkeys, fonts, sound, music, joystick, and more. (PS, my high score is 117! goodluck) | pygame.ref.examples#pygame.examples.aliens.main |
arraydemo.main()
show various surfarray effects arraydemo.main(arraytype=None) -> None Another example filled with various surfarray effects. It requires the surfarray and image modules to be installed. This little demo can also make a good starting point for any of your own tests with surfarray The arraytype parameter is deprecated; passing any value besides 'numpy' will raise ValueError. | pygame.ref.examples#pygame.examples.arraydemo.main |
blend_fill.main()
demonstrate the various surface.fill method blend options blend_fill.main() -> None A interactive demo that lets one choose which BLEND_xxx option to apply to a surface. | pygame.ref.examples#pygame.examples.blend_fill.main |
blit_blends.main()
uses alternative additive fill to that of surface.fill blit_blends.main() -> None Fake additive blending. Using NumPy. it doesn't clamp. Press r,g,b Somewhat like blend_fill. | pygame.ref.examples#pygame.examples.blit_blends.main |
camera.main()
display video captured live from an attached camera camera.main() -> None A simple live video player, it uses the first available camera it finds on the system. | pygame.ref.examples#pygame.examples.camera.main |
chimp.main()
hit the moving chimp chimp.main() -> None This simple example is derived from the line-by-line tutorial that comes with pygame. It is based on a 'popular' web banner. Note there are comments here, but for the full explanation, follow along in the tutorial. | pygame.ref.examples#pygame.examples.chimp.main |
cursors.main()
display two different custom cursors cursors.main() -> None Display an arrow or circle with crossbar cursor. | pygame.ref.examples#pygame.examples.cursors.main |
eventlist.main()
display pygame events eventlist.main() -> None Eventlist is a sloppy style of pygame, but is a handy tool for learning about pygame events and input. At the top of the screen are the state of several device values, and a scrolling list of events are displayed on the bottom. This is not quality 'ui' code at all, but you can see how to implement very non-interactive status displays, or even a crude text output control. | pygame.ref.examples#pygame.examples.eventlist.main |
fastevents.main()
stress test the fastevents module fastevents.main() -> None This is a stress test for the fastevents module.
Fast events does not appear faster!
So far it looks like normal pygame.event is faster by up to two times. So maybe fastevent isn't fast at all. Tested on Windows XP SP2 Athlon, and FreeBSD. However... on my Debian Duron 850 machine fastevents is faster. | pygame.ref.examples#pygame.examples.fastevents.main |
fonty.main()
run a font rendering example fonty.main() -> None Super quick, super simple application demonstrating the different ways to render fonts with the font module | pygame.ref.examples#pygame.examples.fonty.main |
freetype_misc.main()
run a FreeType rendering example freetype_misc.main() -> None A showcase of rendering features the pygame.freetype.Font class provides in addition to those available with pygame.font.Font. It is a demonstration of direct to surface rendering, with vertical text and rotated text, opaque text and semi transparent text, horizontally stretched text and vertically stretched text. | pygame.ref.examples#pygame.examples.freetype_misc.main |
glcube.main()
display an animated 3D cube using OpenGL glcube.main() -> None Using PyOpenGL and pygame, this creates a spinning 3D multicolored cube. | pygame.ref.examples#pygame.examples.glcube.main |
headless_no_windows_needed.main()
write an image file that is smoothscaled copy of an input file headless_no_windows_needed.main(fin, fout, w, h) -> None arguments: fin - name of an input image file
fout - name of the output file to create/overwrite
w, h - size of the rescaled image, as integer width and height How to use pygame with no windowing system, like on headless servers. Thumbnail generation with scaling is an example of what you can do with pygame. NOTE: the pygame scale function uses MMX/SSE if available, and can be run in multiple threads. If headless_no_windows_needed.py is run as a program it takes the following command line arguments: -scale inputimage outputimage new_width new_height
eg. -scale in.png outpng 50 50 | pygame.ref.examples#pygame.examples.headless_no_windows_needed.main |
liquid.main()
display an animated liquid effect liquid.main() -> None This example was created in a quick comparison with the BlitzBasic gaming language. Nonetheless, it demonstrates a quick 8-bit setup (with colormap). | pygame.ref.examples#pygame.examples.liquid.main |
mask.main()
display multiple images bounce off each other using collision detection mask.main(*args) -> None Positional arguments: one or more image file names. This pygame.masks demo will display multiple moving sprites bouncing off each other. More than one sprite image can be provided. If run as a program then mask.py takes one or more image files as command line arguments. | pygame.ref.examples#pygame.examples.mask.main |
midi.main()
run a midi example midi.main(mode='output', device_id=None) -> None Arguments: mode - if 'output' run a midi keyboard output example
'input' run a midi event logger input example
'list' list available midi devices
(default 'output')
device_id - midi device number; if None then use the default midi input or
output device for the system The output example shows how to translate mouse clicks or computer keyboard events into midi notes. It implements a rudimentary button widget and state machine. The input example shows how to translate midi input to pygame events. With the use of a virtual midi patch cord the output and input examples can be run as separate processes and connected so the keyboard output is displayed on a console. new to pygame 1.9.0 | pygame.ref.examples#pygame.examples.midi.main |
moveit.main()
display animated objects on the screen moveit.main() -> None This is the full and final example from the Pygame Tutorial, "How Do I Make It Move". It creates 10 objects and animates them on the screen. Note it's a bit scant on error checking, but it's easy to read. :] Fortunately, this is python, and we needn't wrestle with a pile of error codes. | pygame.ref.examples#pygame.examples.moveit.main |
oldalien.main()
play the original aliens example oldalien.main() -> None This more closely resembles a port of the SDL Aliens demo. The code is a lot simpler, so it makes a better starting point for people looking at code for the first times. These blitting routines are not as optimized as they should/could be, but the code is easier to follow, and it plays quick enough. | pygame.ref.examples#pygame.examples.oldalien.main |
overlay.main()
play a .pgm video using overlays overlay.main(fname) -> None Play the .pgm video file given by a path fname. If run as a program overlay.py takes the file name as a command line argument. | pygame.ref.examples#pygame.examples.overlay.main |
pixelarray.main()
display various pixelarray generated effects pixelarray.main() -> None Display various pixelarray generated effects. | pygame.ref.examples#pygame.examples.pixelarray.main |
playmus.main()
play an audio file playmus.main(file_path) -> None A simple music player with window and keyboard playback control. Playback can be paused and rewound to the beginning. | pygame.ref.examples#pygame.examples.playmus.main |
scaletest.main()
interactively scale an image using smoothscale scaletest.main(imagefile, convert_alpha=False, run_speed_test=True) -> None arguments: imagefile - file name of source image (required)
convert_alpha - use convert_alpha() on the surf (default False)
run_speed_test - (default False) A smoothscale example that resized an image on the screen. Vertical and horizontal arrow keys are used to change the width and height of the displayed image. If the convert_alpha option is True then the source image is forced to have source alpha, whether or not the original images does. If run_speed_test is True then a background timing test is performed instead of the interactive scaler. If scaletest.py is run as a program then the command line options are: ImageFile [-t] [-convert_alpha]
[-t] = Run Speed Test
[-convert_alpha] = Use convert_alpha() on the surf. | pygame.ref.examples#pygame.examples.scaletest.main |
scrap_clipboard.main()
access the clipboard scrap_clipboard.main() -> None A simple demonstration example for the clipboard support. | pygame.ref.examples#pygame.examples.scrap_clipboard.main |
scroll.main()
run a Surface.scroll example that shows a magnified image scroll.main(image_file=None) -> None This example shows a scrollable image that has a zoom factor of eight. It uses the Surface.scroll() function to shift the image on the display surface. A clip rectangle protects a margin area. If called as a function, the example accepts an optional image file path. If run as a program it takes an optional file path command line argument. If no file is provided a default image file is used. When running click on a black triangle to move one pixel in the direction the triangle points. Or use the arrow keys. Close the window or press ESC to quit. | pygame.ref.examples#pygame.examples.scroll.main |
sound.main()
load and play a sound sound.main(file_path=None) -> None Extremely basic testing of the mixer module. Load a sound and play it. All from the command shell, no graphics. If provided, use the audio file 'file_path', otherwise use a default file. sound.py optional command line argument: an audio file | pygame.ref.examples#pygame.examples.sound.main |
sound_array_demos.main()
play various sndarray effects sound_array_demos.main(arraytype=None) -> None Uses sndarray and NumPy to create offset faded copies of the original sound. Currently it just uses hardcoded values for the number of echoes and the delay. Easy for you to recreate as needed. The arraytype parameter is deprecated; passing any value besides 'numpy' will raise ValueError. | pygame.ref.examples#pygame.examples.sound_array_demos.main |
stars.main()
run a simple starfield example stars.main() -> None A simple starfield example. You can change the center of perspective by leftclicking the mouse on the screen. | pygame.ref.examples#pygame.examples.stars.main |
testsprite.main()
show lots of sprites moving around testsprite.main(update_rects = True, use_static = False, use_FastRenderGroup = False, screen_dims = [640, 480], use_alpha = False, flags = 0) -> None Optional keyword arguments: update_rects - use the RenderUpdate sprite group class
use_static - include non-moving images
use_FastRenderGroup - Use the FastRenderGroup sprite group
screen_dims - pygame window dimensions
use_alpha - use alpha blending
flags - additional display mode flags Like the testsprite.c that comes with SDL, this pygame version shows lots of sprites moving around. If run as a stand-alone program then no command line arguments are taken. | pygame.ref.examples#pygame.examples.testsprite.main |
vgrade.main()
display a vertical gradient vgrade.main() -> None Demonstrates creating a vertical gradient with pixelcopy and NumPy python. The app will create a new gradient every half second and report the time needed to create and display the image. If you're not prepared to start working with the NumPy arrays, don't worry about the source for this one :] | pygame.ref.examples#pygame.examples.vgrade.main |
pygame.fastevent
pygame module for interacting with events and queues pygame.fastevent is a wrapper for Bob Pendleton's fastevent library. It provides fast events for use in multithreaded environments. When using pygame.fastevent, you can not use any of the pump, wait, poll, post, get, peek, etc. functions from pygame.event, but you should use the Event objects. pygame.fastevent.init()
initialize pygame.fastevent init() -> None Initialize the pygame.fastevent module.
pygame.fastevent.get_init()
returns True if the fastevent module is currently initialized get_init() -> bool Returns True if the pygame.fastevent module is currently initialized.
pygame.fastevent.pump()
internally process pygame event handlers pump() -> None For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. This function is not necessary if your program is consistently processing events on the queue through the other pygame.fastevent functions. There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.
pygame.fastevent.wait()
wait for an event wait() -> Event Returns the current event on the queue. If there are no messages waiting on the queue, this will not return until one is available. Sometimes it is important to use this wait to get events from the queue, it will allow your application to idle when the user isn't doing anything with it.
pygame.fastevent.poll()
get an available event poll() -> Event Returns next event on queue. If there is no event waiting on the queue, this will return an event with type NOEVENT.
pygame.fastevent.get()
get all events from the queue get() -> list of Events This will get all the messages and remove them from the queue.
pygame.fastevent.post()
place an event on the queue post(Event) -> None This will post your own event objects onto the event queue. You can post any event type you want, but some care must be taken. For example, if you post a MOUSEBUTTONDOWN event to the queue, it is likely any code receiving the event will expect the standard MOUSEBUTTONDOWN attributes to be available, like 'pos' and 'button'. Because pygame.fastevent.post() may have to wait for the queue to empty, you can get into a dead lock if you try to append an event on to a full queue from the thread that processes events. For that reason I do not recommend using this function in the main thread of an SDL program. | pygame.ref.fastevent |
pygame.fastevent.get()
get all events from the queue get() -> list of Events This will get all the messages and remove them from the queue. | pygame.ref.fastevent#pygame.fastevent.get |
pygame.fastevent.get_init()
returns True if the fastevent module is currently initialized get_init() -> bool Returns True if the pygame.fastevent module is currently initialized. | pygame.ref.fastevent#pygame.fastevent.get_init |
pygame.fastevent.init()
initialize pygame.fastevent init() -> None Initialize the pygame.fastevent module. | pygame.ref.fastevent#pygame.fastevent.init |
pygame.fastevent.poll()
get an available event poll() -> Event Returns next event on queue. If there is no event waiting on the queue, this will return an event with type NOEVENT. | pygame.ref.fastevent#pygame.fastevent.poll |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.