This commit is contained in:
Waylon Walker 2022-03-31 20:20:07 -05:00
commit 38355d2442
No known key found for this signature in database
GPG key ID: 66E2BF2B4190EFE4
9083 changed files with 1225834 additions and 0 deletions

View file

@ -0,0 +1,38 @@
# python -m pygame.docs
import os
import webbrowser
from urllib.parse import quote, urlunparse
def _iterpath(path):
path, last = os.path.split(path)
if last:
for p in _iterpath(path):
yield p
yield last
# for test suite to confirm pygame built with local docs
def has_local_docs():
pkg_dir = os.path.dirname(os.path.abspath(__file__))
main_page = os.path.join(pkg_dir, "generated", "index.html")
return os.path.exists(main_page)
def open_docs():
pkg_dir = os.path.dirname(os.path.abspath(__file__))
main_page = os.path.join(pkg_dir, "generated", "index.html")
if os.path.exists(main_page):
url_path = quote("/".join(_iterpath(main_page)))
drive, rest = os.path.splitdrive(__file__)
if drive:
url_path = "%s/%s" % (drive, url_path)
url = urlunparse(("file", "", url_path, "", "", ""))
else:
url = "https://www.pygame.org/docs/"
webbrowser.open(url)
if __name__ == "__main__":
open_docs()

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View file

@ -0,0 +1,26 @@
pygame C API
============
.. toctree::
:maxdepth: 1
:glob:
c_api/slots.rst
c_api/base.rst
c_api/bufferproxy.rst
c_api/cdrom.rst
c_api/color.rst
c_api/display.rst
c_api/event.rst
c_api/freetype.rst
c_api/mixer.rst
c_api/rect.rst
c_api/rwobject.rst
c_api/surface.rst
c_api/surflock.rst
c_api/version.rst
src_c/include/ contains header files for applications
that use the pygame C API, while src_c/ contains
headers used by pygame internally.

View file

@ -0,0 +1,17 @@
File Path Function Arguments
============================
A pygame function or method which takes a file path argument will accept
either a Unicode or a byte (8-bit or ASCII character) string.
Unicode strings are translated to Python's default filesystem encoding,
as returned by sys.getfilesystemencoding(). A Unicode code point
above U+FFFF (``\uFFFF``) can be coded directly with a 32-bit escape sequences
(``\Uxxxxxxxx``), even for Python interpreters built with an UCS-2
(16-bit character) Unicode type. Byte strings are passed
to the operating system unchanged.
Null characters (``\x00``) are not permitted in the path, raising an exception.
An exception is also raised if an Unicode file path cannot be encoded.
How UTF-16 surrogate codes are handled is Python-interpreter-dependent.
Use UTF-32 code points and 32-bit escape sequences instead.
The exception types are function-dependent.

View file

@ -0,0 +1,190 @@
.. Pygame documentation master file, created by
sphinx-quickstart on Sat Mar 5 11:56:39 2011.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Pygame Front Page
=================
.. toctree::
:maxdepth: 2
:glob:
:hidden:
ref/*
tut/*
tut/en/**/*
tut/ko/**/*
c_api
filepaths
Documents
---------
`Readme`_
Basic information about pygame: what it is, who is involved, and where to find it.
`Install`_
Steps needed to compile pygame on several platforms.
Also help on finding and installing prebuilt binaries for your system.
`File Path Function Arguments`_
How pygame handles file system paths.
`LGPL License`_
This is the license pygame is distributed under.
It provides for pygame to be distributed with open source and commercial software.
Generally, if pygame is not changed, it can be used with any type of program.
Tutorials
---------
:doc:`Introduction to Pygame <tut/PygameIntro>`
An introduction to the basics of pygame.
This is written for users of Python and appeared in volume two of the Py magazine.
:doc:`Import and Initialize <tut/ImportInit>`
The beginning steps on importing and initializing pygame.
The pygame package is made of several modules.
Some modules are not included on all platforms.
:doc:`How do I move an Image? <tut/MoveIt>`
A basic tutorial that covers the concepts behind 2D computer animation.
Information about drawing and clearing objects to make them appear animated.
:doc:`Chimp Tutorial, Line by Line <tut/ChimpLineByLine>`
The pygame examples include a simple program with an interactive fist and a chimpanzee.
This was inspired by the annoying flash banner of the early 2000s.
This tutorial examines every line of code used in the example.
:doc:`Sprite Module Introduction <tut/SpriteIntro>`
Pygame includes a higher level sprite module to help organize games.
The sprite module includes several classes that help manage details found in almost all games types.
The Sprite classes are a bit more advanced than the regular pygame modules,
and need more understanding to be properly used.
:doc:`Surfarray Introduction <tut/SurfarrayIntro>`
Pygame used the NumPy python module to allow efficient per pixel effects on images.
Using the surface arrays is an advanced feature that allows custom effects and filters.
This also examines some of the simple effects from the pygame example, arraydemo.py.
:doc:`Camera Module Introduction <tut/CameraIntro>`
Pygame, as of 1.9, has a camera module that allows you to capture images,
watch live streams, and do some basic computer vision.
This tutorial covers those use cases.
:doc:`Newbie Guide <tut/newbieguide>`
A list of thirteen helpful tips for people to get comfortable using pygame.
:doc:`Making Games Tutorial <tut/MakeGames>`
A large tutorial that covers the bigger topics needed to create an entire game.
:doc:`Display Modes <tut/DisplayModes>`
Getting a display surface for the screen.
:doc:`한국어 튜토리얼 (Korean Tutorial) <tut/ko/빨간블록 검은블록/overview>`
빨간블록 검은블록
Reference
---------
:ref:`genindex`
A list of all functions, classes, and methods in the pygame package.
:doc:`ref/bufferproxy`
An array protocol view of surface pixels
:doc:`ref/color`
Color representation.
:doc:`ref/cursors`
Loading and compiling cursor images.
:doc:`ref/display`
Configure the display surface.
:doc:`ref/draw`
Drawing simple shapes like lines and ellipses to surfaces.
:doc:`ref/event`
Manage the incoming events from various input devices and the windowing platform.
:doc:`ref/examples`
Various programs demonstrating the use of individual pygame modules.
:doc:`ref/font`
Loading and rendering TrueType fonts.
:doc:`ref/freetype`
Enhanced pygame module for loading and rendering font faces.
:doc:`ref/gfxdraw`
Anti-aliasing draw functions.
:doc:`ref/image`
Loading, saving, and transferring of surfaces.
:doc:`ref/joystick`
Manage the joystick devices.
:doc:`ref/key`
Manage the keyboard device.
:doc:`ref/locals`
Pygame constants.
:doc:`ref/mixer`
Load and play sounds
:doc:`ref/mouse`
Manage the mouse device and display.
:doc:`ref/music`
Play streaming music tracks.
:doc:`ref/pygame`
Top level functions to manage pygame.
:doc:`ref/pixelarray`
Manipulate image pixel data.
:doc:`ref/rect`
Flexible container for a rectangle.
:doc:`ref/scrap`
Native clipboard access.
:doc:`ref/sndarray`
Manipulate sound sample data.
:doc:`ref/sprite`
Higher level objects to represent game images.
:doc:`ref/surface`
Objects for images and the screen.
:doc:`ref/surfarray`
Manipulate image pixel data.
:doc:`ref/tests`
Test pygame.
:doc:`ref/time`
Manage timing and framerate.
:doc:`ref/transform`
Resize and move images.
:doc:`pygame C API <c_api>`
The C api shared amongst pygame extension modules.
:ref:`search`
Search pygame documents by keyword.
.. _Readme: ../wiki/about
.. _Install: ../wiki/GettingStarted#Pygame%20Installation
.. _File Path Function Arguments: filepaths.html
.. _LGPL License: LGPL.txt

View file

@ -0,0 +1,113 @@
.. include:: common.txt
.. default-domain:: py
:class:`pygame.BufferProxy`
===========================
.. currentmodule:: pygame
.. class:: BufferProxy
| :sl:`pygame object to export a surface buffer through an array protocol`
| :sg:`BufferProxy(<parent>) -> BufferProxy`
:class:`BufferProxy` is a pygame support type, designed as the return value
of the :meth:`Surface.get_buffer` and :meth:`Surface.get_view` methods.
For all Python versions a :class:`BufferProxy` object exports a C struct
and Python level array interface on behalf of its parent object's buffer.
A new buffer interface is also exported.
In pygame, :class:`BufferProxy` is key to implementing the
:mod:`pygame.surfarray` module.
:class:`BufferProxy` instances can be created directly from Python code,
either for a parent that exports an interface, or from a Python ``dict``
describing an object's buffer layout. The dict entries are based on the
Python level array interface mapping. The following keys are recognized:
``"shape"`` : tuple
The length of each array dimension as a tuple of integers. The
length of the tuple is the number of dimensions in the array.
``"typestr"`` : string
The array element type as a length 3 string. The first character
gives byteorder, '<' for little-endian, '>' for big-endian, and
'\|' for not applicable. The second character is the element type,
'i' for signed integer, 'u' for unsigned integer, 'f' for floating
point, and 'V' for an chunk of bytes. The third character gives the
bytesize of the element, from '1' to '9' bytes. So, for example,
"<u4" is an unsigned 4 byte little-endian integer, such as a
32 bit pixel on a PC, while "\|V3" would represent a 24 bit pixel,
which has no integer equivalent.
``"data"`` : tuple
The physical buffer start address and a read-only flag as a length
2 tuple. The address is an integer value, while the read-only flag
is a bool—``False`` for writable, ``True`` for read-only.
``"strides"`` : tuple : (optional)
Array stride information as a tuple of integers. It is required
only of non C-contiguous arrays. The tuple length must match
that of ``"shape"``.
``"parent"`` : object : (optional)
The exporting object. It can be used to keep the parent object
alive while its buffer is visible.
``"before"`` : callable : (optional)
Callback invoked when the :class:`BufferProxy` instance
exports the buffer. The callback is given one argument, the
``"parent"`` object if given, otherwise ``None``.
The callback is useful for setting a lock on the parent.
``"after"`` : callable : (optional)
Callback invoked when an exported buffer is released.
The callback is passed on argument, the ``"parent"`` object if given,
otherwise None. The callback is useful for releasing a lock on the
parent.
The BufferProxy class supports subclassing, instance variables, and weak
references.
.. versionadded:: 1.8.0
.. versionextended:: 1.9.2
.. attribute:: parent
| :sl:`Return wrapped exporting object.`
| :sg:`parent -> Surface`
| :sg:`parent -> <parent>`
The :class:`Surface` which returned the :class:`BufferProxy` object or
the object passed to a :class:`BufferProxy` call.
.. attribute:: length
| :sl:`The size, in bytes, of the exported buffer.`
| :sg:`length -> int`
The number of valid bytes of data exported. For discontinuous data,
that is data which is not a single block of memory, the bytes within
the gaps are excluded from the count. This property is equivalent to
the ``Py_buffer`` C struct ``len`` field.
.. attribute:: raw
| :sl:`A copy of the exported buffer as a single block of bytes.`
| :sg:`raw -> bytes`
The buffer data as a ``str``/``bytes`` object.
Any gaps in the exported data are removed.
.. method:: write
| :sl:`Write raw bytes to object buffer.`
| :sg:`write(buffer, offset=0)`
Overwrite bytes in the parent object's data. The data must be C or F
contiguous, otherwise a ValueError is raised. Argument `buffer` is a
``str``/``bytes`` object. An optional offset gives a
start position, in bytes, within the buffer where overwriting begins.
If the offset is negative or greater that or equal to the buffer proxy's
:attr:`length` value, an ``IndexException`` is raised.
If ``len(buffer) > proxy.length + offset``, a ``ValueError`` is raised.

View file

@ -0,0 +1,247 @@
.. include:: common.txt
:mod:`pygame.camera`
====================
.. module:: pygame.camera
:synopsis: pygame module for camera use
| :sl:`pygame module for camera use`
Pygame currently supports Linux (V4L2) and Windows (MSMF) cameras natively,
with wider platform support available via an integrated OpenCV backend.
.. versionadded:: 2.0.2 Windows native camera support
.. versionadded:: 2.0.3 New OpenCV backends
EXPERIMENTAL!: This API may change or disappear in later pygame releases. If
you use this, your code will very likely break with the next pygame release.
The Bayer to ``RGB`` function is based on:
::
Sonix SN9C101 based webcam basic I/F routines
Copyright (C) 2004 Takafumi Mizuno <taka-qce@ls-a.jp>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
New in pygame 1.9.0.
.. function:: init
| :sl:`Module init`
| :sg:`init(backend = None) -> None`
This function starts up the camera module, choosing the best webcam backend
it can find for your system. This is not guaranteed to succeed, and may even
attempt to import third party modules, like `OpenCV`. If you want to
override its backend choice, you can call pass the name of the backend you
want into this function. More about backends in
:func:`get_backends()`.
.. versionchanged:: 2.0.3 Option to explicitly select backend
.. ## pygame.camera.init ##
.. function:: get_backends
| :sl:`Get the backends supported on this system`
| :sg:`get_backends() -> [str]`
This function returns every backend it thinks has a possibility of working
on your system, in order of priority.
pygame.camera Backends:
::
Backend OS Description
---------------------------------------------------------------------------------
_camera (MSMF) Windows Builtin, works on Windows 8+ Python3
_camera (V4L2) Linux Builtin
OpenCV Any Uses `opencv-python` module, can't enumerate cameras
OpenCV-Mac Mac Same as OpenCV, but has camera enumeration
VideoCapture Windows Uses abandoned `VideoCapture` module, can't enumerate
cameras, may be removed in the future
There are two main differences among backends.
The _camera backends are built in to pygame itself, and require no third
party imports. All the other backends do. For the OpenCV and VideoCapture
backends, those modules need to be installed on your system.
The other big difference is "camera enumeration." Some backends don't have
a way to list out camera names, or even the number of cameras on the
system. In these cases, :func:`list_cameras()` will return
something like ``[0]``. If you know you have multiple cameras on the
system, these backend ports will pass through a "camera index number"
through if you use that as the ``device`` parameter.
.. versionadded:: 2.0.3
.. ## pygame.camera.get_backends ##
.. function:: colorspace
| :sl:`Surface colorspace conversion`
| :sg:`colorspace(Surface, format, DestSurface = None) -> Surface`
Allows for conversion from "RGB" to a destination colorspace of "HSV" or
"YUV". The source and destination surfaces must be the same size and pixel
depth. This is useful for computer vision on devices with limited processing
power. Capture as small of an image as possible, ``transform.scale()`` it
even smaller, and then convert the colorspace to ``YUV`` or ``HSV`` before
doing any processing on it.
.. ## pygame.camera.colorspace ##
.. function:: list_cameras
| :sl:`returns a list of available cameras`
| :sg:`list_cameras() -> [cameras]`
Checks the computer for available cameras and returns a list of strings of
camera names, ready to be fed into :class:`pygame.camera.Camera`.
If the camera backend doesn't support webcam enumeration, this will return
something like ``[0]``. See :func:`get_backends()` for much more
information.
.. ## pygame.camera.list_cameras ##
.. class:: Camera
| :sl:`load a camera`
| :sg:`Camera(device, (width, height), format) -> Camera`
Loads a camera. On Linux, the device is typically something like
"/dev/video0". Default width and height are 640 by 480.
Format is the desired colorspace of the output.
This is useful for computer vision purposes. The default is
``RGB``. The following are supported:
* ``RGB`` - Red, Green, Blue
* ``YUV`` - Luma, Blue Chrominance, Red Chrominance
* ``HSV`` - Hue, Saturation, Value
.. method:: start
| :sl:`opens, initializes, and starts capturing`
| :sg:`start() -> None`
Opens the camera device, attempts to initialize it, and begins recording
images to a buffer. The camera must be started before any of the below
functions can be used.
.. ## Camera.start ##
.. method:: stop
| :sl:`stops, uninitializes, and closes the camera`
| :sg:`stop() -> None`
Stops recording, uninitializes the camera, and closes it. Once a camera
is stopped, the below functions cannot be used until it is started again.
.. ## Camera.stop ##
.. method:: get_controls
| :sl:`gets current values of user controls`
| :sg:`get_controls() -> (hflip = bool, vflip = bool, brightness)`
If the camera supports it, get_controls will return the current settings
for horizontal and vertical image flip as bools and brightness as an int.
If unsupported, it will return the default values of (0, 0, 0). Note that
the return values here may be different than those returned by
set_controls, though these are more likely to be correct.
.. ## Camera.get_controls ##
.. method:: set_controls
| :sl:`changes camera settings if supported by the camera`
| :sg:`set_controls(hflip = bool, vflip = bool, brightness) -> (hflip = bool, vflip = bool, brightness)`
Allows you to change camera settings if the camera supports it. The
return values will be the input values if the camera claims it succeeded
or the values previously in use if not. Each argument is optional, and
the desired one can be chosen by supplying the keyword, like hflip. Note
that the actual settings being used by the camera may not be the same as
those returned by set_controls. On Windows, :code:`hflip` and :code:`vflip` are
implemented by pygame, not by the Camera, so they should always work, but
:code:`brightness` is unsupported.
.. ## Camera.set_controls ##
.. method:: get_size
| :sl:`returns the dimensions of the images being recorded`
| :sg:`get_size() -> (width, height)`
Returns the current dimensions of the images being captured by the
camera. This will return the actual size, which may be different than the
one specified during initialization if the camera did not support that
size.
.. ## Camera.get_size ##
.. method:: query_image
| :sl:`checks if a frame is ready`
| :sg:`query_image() -> bool`
If an image is ready to get, it returns true. Otherwise it returns false.
Note that some webcams will always return False and will only queue a
frame when called with a blocking function like :func:`get_image()`.
On Windows (MSMF), and the OpenCV backends, :func:`query_image()`
should be reliable, though. This is useful to separate the framerate of
the game from that of the camera without having to use threading.
.. ## Camera.query_image ##
.. method:: get_image
| :sl:`captures an image as a Surface`
| :sg:`get_image(Surface = None) -> Surface`
Pulls an image off of the buffer as an ``RGB`` Surface. It can optionally
reuse an existing Surface to save time. The bit-depth of the surface is
24 bits on Linux, 32 bits on Windows, or the same as the optionally
supplied Surface.
.. ## Camera.get_image ##
.. method:: get_raw
| :sl:`returns an unmodified image as bytes`
| :sg:`get_raw() -> bytes`
Gets an image from a camera as a string in the native pixelformat of the
camera. Useful for integration with other libraries. This returns a
bytes object
.. ## Camera.get_raw ##
.. ## pygame.camera.Camera ##
.. ## pygame.camera ##

View file

@ -0,0 +1,310 @@
.. include:: common.txt
:mod:`pygame.cdrom`
===================
.. module:: pygame.cdrom
:synopsis: pygame module for audio cdrom control
| :sl:`pygame module for audio cdrom control`
.. warning::
This module is non functional in pygame 2.0 and above, unless you have manually compiled pygame with SDL1.
This module will not be supported in the future.
One alternative for python cdrom functionality is `pycdio <https://pypi.org/project/pycdio/>`_.
The cdrom module manages the ``CD`` and ``DVD`` drives on a computer. It can
also control the playback of audio CDs. This module needs to be initialized
before it can do anything. Each ``CD`` object you create represents a cdrom
drive and must also be initialized individually before it can do most things.
.. function:: init
| :sl:`initialize the cdrom module`
| :sg:`init() -> None`
Initialize the cdrom module. This will scan the system for all ``CD``
devices. The module must be initialized before any other functions will
work. This automatically happens when you call ``pygame.init()``.
It is safe to call this function more than once.
.. ## pygame.cdrom.init ##
.. function:: quit
| :sl:`uninitialize the cdrom module`
| :sg:`quit() -> None`
Uninitialize the cdrom module. After you call this any existing ``CD``
objects will no longer work.
It is safe to call this function more than once.
.. ## pygame.cdrom.quit ##
.. function:: get_init
| :sl:`true if the cdrom module is initialized`
| :sg:`get_init() -> bool`
Test if the cdrom module is initialized or not. This is different than the
``CD.init()`` since each drive must also be initialized individually.
.. ## pygame.cdrom.get_init ##
.. function:: get_count
| :sl:`number of cd drives on the system`
| :sg:`get_count() -> count`
Return the number of cd drives on the system. When you create ``CD`` objects
you need to pass an integer id that must be lower than this count. The count
will be 0 if there are no drives on the system.
.. ## pygame.cdrom.get_count ##
.. class:: CD
| :sl:`class to manage a cdrom drive`
| :sg:`CD(id) -> CD`
You can create a ``CD`` object for each cdrom on the system. Use
``pygame.cdrom.get_count()`` to determine how many drives actually exist.
The id argument is an integer of the drive, starting at zero.
The ``CD`` object is not initialized, you can only call ``CD.get_id()`` and
``CD.get_name()`` on an uninitialized drive.
It is safe to create multiple ``CD`` objects for the same drive, they will
all cooperate normally.
.. method:: init
| :sl:`initialize a cdrom drive for use`
| :sg:`init() -> None`
Initialize the cdrom drive for use. The drive must be initialized for
most ``CD`` methods to work. Even if the rest of pygame has been
initialized.
There may be a brief pause while the drive is initialized. Avoid
``CD.init()`` if the program should not stop for a second or two.
.. ## CD.init ##
.. method:: quit
| :sl:`uninitialize a cdrom drive for use`
| :sg:`quit() -> None`
Uninitialize a drive for use. Call this when your program will not be
accessing the drive for awhile.
.. ## CD.quit ##
.. method:: get_init
| :sl:`true if this cd device initialized`
| :sg:`get_init() -> bool`
Test if this ``CDROM`` device is initialized. This is different than the
``pygame.cdrom.init()`` since each drive must also be initialized
individually.
.. ## CD.get_init ##
.. method:: play
| :sl:`start playing audio`
| :sg:`play(track, start=None, end=None) -> None`
Playback audio from an audio cdrom in the drive. Besides the track number
argument, you can also pass a starting and ending time for playback. The
start and end time are in seconds, and can limit the section of an audio
track played.
If you pass a start time but no end, the audio will play to the end of
the track. If you pass a start time and 'None' for the end time, the
audio will play to the end of the entire disc.
See the ``CD.get_numtracks()`` and ``CD.get_track_audio()`` to find
tracks to playback.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.play ##
.. method:: stop
| :sl:`stop audio playback`
| :sg:`stop() -> None`
Stops playback of audio from the cdrom. This will also lose the current
playback position. This method does nothing if the drive isn't already
playing audio.
.. ## CD.stop ##
.. method:: pause
| :sl:`temporarily stop audio playback`
| :sg:`pause() -> None`
Temporarily stop audio playback on the ``CD``. The playback can be
resumed at the same point with the ``CD.resume()`` method. If the ``CD``
is not playing this method does nothing.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.pause ##
.. method:: resume
| :sl:`unpause audio playback`
| :sg:`resume() -> None`
Unpause a paused ``CD``. If the ``CD`` is not paused or already playing,
this method does nothing.
.. ## CD.resume ##
.. method:: eject
| :sl:`eject or open the cdrom drive`
| :sg:`eject() -> None`
This will open the cdrom drive and eject the cdrom. If the drive is
playing or paused it will be stopped.
.. ## CD.eject ##
.. method:: get_id
| :sl:`the index of the cdrom drive`
| :sg:`get_id() -> id`
Returns the integer id that was used to create the ``CD`` instance. This
method can work on an uninitialized ``CD``.
.. ## CD.get_id ##
.. method:: get_name
| :sl:`the system name of the cdrom drive`
| :sg:`get_name() -> name`
Return the string name of the drive. This is the system name used to
represent the drive. It is often the drive letter or device name. This
method can work on an uninitialized ``CD``.
.. ## CD.get_name ##
.. method:: get_busy
| :sl:`true if the drive is playing audio`
| :sg:`get_busy() -> bool`
Returns True if the drive busy playing back audio.
.. ## CD.get_busy ##
.. method:: get_paused
| :sl:`true if the drive is paused`
| :sg:`get_paused() -> bool`
Returns True if the drive is currently paused.
.. ## CD.get_paused ##
.. method:: get_current
| :sl:`the current audio playback position`
| :sg:`get_current() -> track, seconds`
Returns both the current track and time of that track. This method works
when the drive is either playing or paused.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_current ##
.. method:: get_empty
| :sl:`False if a cdrom is in the drive`
| :sg:`get_empty() -> bool`
Return False if there is a cdrom currently in the drive. If the drive is
empty this will return True.
.. ## CD.get_empty ##
.. method:: get_numtracks
| :sl:`the number of tracks on the cdrom`
| :sg:`get_numtracks() -> count`
Return the number of tracks on the cdrom in the drive. This will return
zero of the drive is empty or has no tracks.
.. ## CD.get_numtracks ##
.. method:: get_track_audio
| :sl:`true if the cdrom track has audio data`
| :sg:`get_track_audio(track) -> bool`
Determine if a track on a cdrom contains audio data. You can also call
``CD.num_tracks()`` and ``CD.get_all()`` to determine more information
about the cdrom.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_track_audio ##
.. method:: get_all
| :sl:`get all track information`
| :sg:`get_all() -> [(audio, start, end, length), ...]`
Return a list with information for every track on the cdrom. The
information consists of a tuple with four values. The audio value is True
if the track contains audio data. The start, end, and length values are
floating point numbers in seconds. Start and end represent absolute times
on the entire disc.
.. ## CD.get_all ##
.. method:: get_track_start
| :sl:`start time of a cdrom track`
| :sg:`get_track_start(track) -> seconds`
Return the absolute time in seconds where at start of the cdrom track.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_track_start ##
.. method:: get_track_length
| :sl:`length of a cdrom track`
| :sg:`get_track_length(track) -> seconds`
Return a floating point value in seconds of the length of the cdrom
track.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_track_length ##
.. ## pygame.cdrom.CD ##
.. ## pygame.cdrom ##

View file

@ -0,0 +1,266 @@
.. include:: common.txt
:mod:`pygame.Color`
===================
.. currentmodule:: pygame
.. class:: Color
| :sl:`pygame object for color representations`
| :sg:`Color(r, g, b) -> Color`
| :sg:`Color(r, g, b, a=255) -> Color`
| :sg:`Color(color_value) -> Color`
The ``Color`` class represents ``RGBA`` color values using a value range of
0 to 255 inclusive. It allows basic arithmetic operationsbinary
operations ``+``, ``-``, ``*``, ``//``, ``%``, and unary operation ``~``to
create new colors, supports conversions to other color spaces such as ``HSV``
or ``HSL`` and lets you adjust single color channels.
Alpha defaults to 255 (fully opaque) when not given.
The arithmetic operations and ``correct_gamma()`` method preserve subclasses.
For the binary operators, the class of the returned color is that of the
left hand color object of the operator.
Color objects support equality comparison with other color objects and 3 or
4 element tuples of integers. There was a bug in pygame 1.8.1
where the default alpha was 0, not 255 like previously.
Color objects export the C level array interface. The interface exports a
read-only one dimensional unsigned byte array of the same assigned length
as the color. The new buffer interface is also exported, with the same
characteristics as the array interface.
The floor division, ``//``, and modulus, ``%``, operators do not raise
an exception for division by zero. Instead, if a color, or alpha, channel
in the right hand color is 0, then the result is 0. For example: ::
# These expressions are True
Color(255, 255, 255, 255) // Color(0, 64, 64, 64) == Color(0, 3, 3, 3)
Color(255, 255, 255, 255) % Color(64, 64, 64, 0) == Color(63, 63, 63, 0)
Use ``int(color)`` to return the immutable integer value of the color,
usable as a ``dict`` key. This integer value differs from the mapped
pixel values of :meth:`pygame.Surface.get_at_mapped`,
:meth:`pygame.Surface.map_rgb` and :meth:`pygame.Surface.unmap_rgb`.
It can be passed as a ``color_value`` argument to :class:`Color`
(useful with sets).
See :doc:`color_list` for samples of the available named colors.
:param int r: red value in the range of 0 to 255 inclusive
:param int g: green value in the range of 0 to 255 inclusive
:param int b: blue value in the range of 0 to 255 inclusive
:param int a: (optional) alpha value in the range of 0 to 255 inclusive,
default is 255
:param color_value: color value (see note below for the supported formats)
.. note::
Supported ``color_value`` formats:
| - **Color object:** clones the given :class:`Color` object
| - **Color name: str:** name of the color to use, e.g. ``'red'``
(all the supported name strings can be found in the
:doc:`color_list`, with sample swatches)
| - **HTML color format str:** ``'#rrggbbaa'`` or ``'#rrggbb'``,
where rr, gg, bb, and aa are 2-digit hex numbers in the range
of 0 to 0xFF inclusive, the aa (alpha) value defaults to 0xFF
if not provided
| - **hex number str:** ``'0xrrggbbaa'`` or ``'0xrrggbb'``, where
rr, gg, bb, and aa are 2-digit hex numbers in the range of 0x00
to 0xFF inclusive, the aa (alpha) value defaults to 0xFF if not
provided
| - **int:** int value of the color to use, using hex numbers can
make this parameter more readable, e.g. ``0xrrggbbaa``, where rr,
gg, bb, and aa are 2-digit hex numbers in the range of 0x00 to
0xFF inclusive, note that the aa (alpha) value is not optional for
the int format and must be provided
| - **tuple/list of int color values:** ``(R, G, B, A)`` or
``(R, G, B)``, where R, G, B, and A are int values in the range of
0 to 255 inclusive, the A (alpha) value defaults to 255 if not
provided
:type color_value: Color or str or int or tuple(int, int, int, [int]) or
list(int, int, int, [int])
:returns: a newly created :class:`Color` object
:rtype: Color
.. versionchanged:: 2.0.0
Support for tuples, lists, and :class:`Color` objects when creating
:class:`Color` objects.
.. versionchanged:: 1.9.2 Color objects export the C level array interface.
.. versionchanged:: 1.9.0 Color objects support 4-element tuples of integers.
.. versionchanged:: 1.8.1 New implementation of the class.
.. attribute:: r
| :sl:`Gets or sets the red value of the Color.`
| :sg:`r -> int`
The red value of the Color.
.. ## Color.r ##
.. attribute:: g
| :sl:`Gets or sets the green value of the Color.`
| :sg:`g -> int`
The green value of the Color.
.. ## Color.g ##
.. attribute:: b
| :sl:`Gets or sets the blue value of the Color.`
| :sg:`b -> int`
The blue value of the Color.
.. ## Color.b ##
.. attribute:: a
| :sl:`Gets or sets the alpha value of the Color.`
| :sg:`a -> int`
The alpha value of the Color.
.. ## Color.a ##
.. attribute:: cmy
| :sl:`Gets or sets the CMY representation of the Color.`
| :sg:`cmy -> tuple`
The ``CMY`` representation of the Color. The ``CMY`` components are in
the ranges ``C`` = [0, 1], ``M`` = [0, 1], ``Y`` = [0, 1]. Note that this
will not return the absolutely exact ``CMY`` values for the set ``RGB``
values in all cases. Due to the ``RGB`` mapping from 0-255 and the
``CMY`` mapping from 0-1 rounding errors may cause the ``CMY`` values to
differ slightly from what you might expect.
.. ## Color.cmy ##
.. attribute:: hsva
| :sl:`Gets or sets the HSVA representation of the Color.`
| :sg:`hsva -> tuple`
The ``HSVA`` representation of the Color. The ``HSVA`` components are in
the ranges ``H`` = [0, 360], ``S`` = [0, 100], ``V`` = [0, 100], A = [0,
100]. Note that this will not return the absolutely exact ``HSV`` values
for the set ``RGB`` values in all cases. Due to the ``RGB`` mapping from
0-255 and the ``HSV`` mapping from 0-100 and 0-360 rounding errors may
cause the ``HSV`` values to differ slightly from what you might expect.
.. ## Color.hsva ##
.. attribute:: hsla
| :sl:`Gets or sets the HSLA representation of the Color.`
| :sg:`hsla -> tuple`
The ``HSLA`` representation of the Color. The ``HSLA`` components are in
the ranges ``H`` = [0, 360], ``S`` = [0, 100], ``V`` = [0, 100], A = [0,
100]. Note that this will not return the absolutely exact ``HSL`` values
for the set ``RGB`` values in all cases. Due to the ``RGB`` mapping from
0-255 and the ``HSL`` mapping from 0-100 and 0-360 rounding errors may
cause the ``HSL`` values to differ slightly from what you might expect.
.. ## Color.hsla ##
.. attribute:: i1i2i3
| :sl:`Gets or sets the I1I2I3 representation of the Color.`
| :sg:`i1i2i3 -> tuple`
The ``I1I2I3`` representation of the Color. The ``I1I2I3`` components are
in the ranges ``I1`` = [0, 1], ``I2`` = [-0.5, 0.5], ``I3`` = [-0.5,
0.5]. Note that this will not return the absolutely exact ``I1I2I3``
values for the set ``RGB`` values in all cases. Due to the ``RGB``
mapping from 0-255 and the ``I1I2I3`` mapping from 0-1 rounding errors
may cause the ``I1I2I3`` values to differ slightly from what you might
expect.
.. ## Color.i1i2i3 ##
.. method:: normalize
| :sl:`Returns the normalized RGBA values of the Color.`
| :sg:`normalize() -> tuple`
Returns the normalized ``RGBA`` values of the Color as floating point
values.
.. ## Color.normalize ##
.. method:: correct_gamma
| :sl:`Applies a certain gamma value to the Color.`
| :sg:`correct_gamma (gamma) -> Color`
Applies a certain gamma value to the Color and returns a new Color with
the adjusted ``RGBA`` values.
.. ## Color.correct_gamma ##
.. method:: set_length
| :sl:`Set the number of elements in the Color to 1,2,3, or 4.`
| :sg:`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)``.
.. versionadded:: 1.9.0
.. ## Color.set_length ##
.. method:: lerp
| :sl:`returns a linear interpolation to the given Color.`
| :sg:`lerp(Color, float) -> Color`
Returns a Color which is a linear interpolation between self and the
given Color in RGBA space. The second parameter determines how far
between self and other the result is going to be.
It must be a value between 0 and 1 where 0 means self and 1 means
other will be returned.
.. versionadded:: 2.0.1
.. ## Color.lerp ##
.. method:: premul_alpha
| :sl:`returns a Color where the r,g,b components have been multiplied by the alpha.`
| :sg:`premul_alpha() -> Color`
Returns a new Color where each of the red, green and blue colour
channels have been multiplied by the alpha channel of the original
color. The alpha channel remains unchanged.
This is useful when working with the ``BLEND_PREMULTIPLIED`` blending mode
flag for :meth:`pygame.Surface.blit()`, which assumes that all surfaces using
it are using pre-multiplied alpha colors.
.. versionadded:: 2.0.0
.. ## Color.premul_alpha ##
.. method:: update
| :sl:`Sets the elements of the color`
| :sg:`update(r, g, b) -> None`
| :sg:`update(r, g, b, a=255) -> None`
| :sg:`update(color_value) -> None`
Sets the elements of the color. See parameters for :meth:`pygame.Color` for the
parameters of this function. If the alpha value was not set it will not change.
.. versionadded:: 2.0.1
.. ## Color.update ##
.. ## pygame.Color ##

View file

@ -0,0 +1,250 @@
.. include:: common.txt
:mod:`pygame.cursors`
=====================
.. module:: pygame.cursors
:synopsis: pygame module for cursor resources
| :sl:`pygame module for cursor resources`
Pygame offers control over the system hardware cursor. Pygame supports
black and white cursors (bitmap cursors), as well as system variant cursors and color cursors.
You control the cursor with functions inside :mod:`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 :func:`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``
.. function:: compile
| :sl:`create binary cursor data from simple strings`
| :sg:`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
:func:`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.compile ##
.. function:: load_xbm
| :sl:`load cursor data from an XBM file`
| :sg:`load_xbm(cursorfile) -> cursor_args`
| :sg:`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.cursors.load_xbm ##
.. class:: Cursor
| :sl:`pygame object representing a cursor`
| :sg:`Cursor(size, hotspot, xormasks, andmasks) -> Cursor`
| :sg:`Cursor(hotspot, surface) -> Cursor`
| :sg:`Cursor(constant) -> Cursor`
| :sg:`Cursor(Cursor) -> Cursor`
| :sg:`Cursor() -> Cursor`
In pygame 2, there are 3 types of cursors you can create to give your
game that little bit of extra polish. There's **bitmap** type cursors,
which existed in pygame 1.x, and are compiled from a string or load from an xbm file.
Then there are **system** type cursors, where you choose a preset that will
convey the same meaning but look native across different operating systems.
Finally you can create a **color** cursor, which displays a pygame surface as the cursor.
**Creating a system cursor**
Choose a constant from this list, pass it into ``pygame.cursors.Cursor(constant)``,
and you're good to go. Be advised that not all systems support every system
cursor, and you may get a substitution instead. For example, on MacOS,
WAIT/WAITARROW should show up as an arrow, and SIZENWSE/SIZENESW/SIZEALL
should show up as a closed hand. And on Wayland, every SIZE cursor should
show up as a hand.
::
Pygame Cursor Constant Description
--------------------------------------------
pygame.SYSTEM_CURSOR_ARROW arrow
pygame.SYSTEM_CURSOR_IBEAM i-beam
pygame.SYSTEM_CURSOR_WAIT wait
pygame.SYSTEM_CURSOR_CROSSHAIR crosshair
pygame.SYSTEM_CURSOR_WAITARROW small wait cursor
(or wait if not available)
pygame.SYSTEM_CURSOR_SIZENWSE double arrow pointing
northwest and southeast
pygame.SYSTEM_CURSOR_SIZENESW double arrow pointing
northeast and southwest
pygame.SYSTEM_CURSOR_SIZEWE double arrow pointing
west and east
pygame.SYSTEM_CURSOR_SIZENS double arrow pointing
north and south
pygame.SYSTEM_CURSOR_SIZEALL four pointed arrow pointing
north, south, east, and west
pygame.SYSTEM_CURSOR_NO slashed circle or crossbones
pygame.SYSTEM_CURSOR_HAND hand
**Creating a cursor without passing arguments**
In addition to the cursor constants available and described above,
you can also call ``pygame.cursors.Cursor()``, and your cursor is ready (doing that is the same as
calling ``pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_ARROW)``.
Doing one of those calls actually creates a system cursor using the default native image.
**Creating a color cursor**
To create a color cursor, create a ``Cursor`` from a ``hotspot`` and a ``surface``.
``hotspot`` is an (x,y) coordinate that determines where in the cursor the exact point is.
The hotspot position must be within the bounds of the ``surface``.
**Creating a bitmap cursor**
When the mouse cursor is visible, it will be displayed as a black and white
bitmap using the given bitmask arrays. The ``size`` is a sequence containing
the cursor width and height. ``hotspot`` is a sequence containing the cursor
hotspot position.
A cursor has a width and height, but a mouse position is represented by a
set of point coordinates. So the value passed into the cursor ``hotspot``
variable helps pygame to actually determine at what exact point the cursor
is at.
``xormasks`` is a sequence of bytes containing the cursor xor data masks.
Lastly ``andmasks``, a sequence of bytes containing the cursor bitmask data.
To create these variables, we can make use of the
:func:`pygame.cursors.compile()` function.
Width and height must be a multiple of 8, and the mask arrays must be the
correct size for the given width and height. Otherwise an exception is raised.
.. method:: copy
| :sl:`copy the current cursor`
| :sg:`copy() -> Cursor`
Returns a new Cursor object with the same data and hotspot as the original.
.. ## pygame.cursors.Cursor.copy ##
.. attribute:: type
| :sl:`Gets the cursor type`
| :sg:`type -> string`
The type will be ``"system"``, ``"bitmap"``, or ``"color"``.
.. ## pygame.cursors.Cursor.type ##
.. attribute:: data
| :sl:`Gets the cursor data`
| :sg:`data -> tuple`
Returns the data that was used to create this cursor object, wrapped up in a tuple.
.. ## pygame.cursors.Cursor.data ##
.. versionadded:: 2.0.1
.. ## pygame.cursors.Cursor ##
.. ## pygame.cursors ##
Example code for creating and settings cursors. (Click the mouse to switch cursor)
.. literalinclude:: code_examples/cursors_module_example.py

View file

@ -0,0 +1,716 @@
.. include:: common.txt
:mod:`pygame.display`
=====================
.. module:: pygame.display
:synopsis: pygame module to control the display window and screen
| :sl:`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 automatic scaling or 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. To detect
the number and size of attached screens, you can use
``pygame.display.get_desktop_sizes`` and then select appropriate window size
and display index to pass to ``pygame.display.set_mode()``.
For backward compatibility ``pygame.display`` allows precise control over
the pixel format or display resolutions. This used to be necessary with old
grahics cards and CRT screens, but is usually not needed any more. Use the
functions ``pygame.display.mode_ok()``, ``pygame.display.list_modes()``, and
``pygame.display.Info()`` to query detailed 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.
A new windowevent API was introduced in pygame 2.0.1. Check event module docs
for more information on that
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).
.. function:: init
| :sl:`Initialize the display module`
| :sg:`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.init ##
.. function:: quit
| :sl:`Uninitialize the display module`
| :sg:`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.quit ##
.. function:: get_init
| :sl:`Returns True if the display module has been initialized`
| :sg:`get_init() -> bool`
Returns True if the :mod:`pygame.display` module is currently initialized.
.. ## pygame.display.get_init ##
.. function:: set_mode
| :sl:`Initialize a window or screen for display`
| :sg:`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.
Note that calling this function implicitly initializes ``pygame.display``, if
it was not initialized before.
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). Here are the display
flags you will want to choose from:
::
pygame.FULLSCREEN create a fullscreen display
pygame.DOUBLEBUF (obsolete in pygame 2) recommended for HWSURFACE or OPENGL
pygame.HWSURFACE (obsolete in pygame 2) 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.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
.. versionadded:: 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.
.. versionadded:: 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. If no display
index argument is provided, the default display can be overridden with an
environment variable.
.. versionchanged:: 1.9.5 ``display`` argument added
.. ## pygame.display.set_mode ##
.. function:: get_surface
| :sl:`Get a reference to the currently set display surface`
| :sg:`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.get_surface ##
.. function:: flip
| :sl:`Update the full display Surface to the screen`
| :sg:`flip() -> None`
This will update the contents of the entire display. If your display mode is
using the flags ``pygame.HWSURFACE`` and ``pygame.DOUBLEBUF`` on pygame 1,
this will wait for a vertical retrace and swap the surfaces.
When using an ``pygame.OPENGL`` display mode this will perform a gl buffer
swap.
.. ## pygame.display.flip ##
.. function:: update
| :sl:`Update portions of the screen for software displays`
| :sg:`update(rectangle=None) -> None`
| :sg:`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()``.
Note that calling ``display.update(None)`` means no part of the window is
updated. Whereas ``display.update()`` means the whole window is updated.
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.update ##
.. function:: get_driver
| :sl:`Get the name of the pygame display backend`
| :sg:`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.get_driver ##
.. function:: Info
| :sl:`Create a video display information object`
| :sg:`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.Info ##
.. function:: get_wm_info
| :sl:`Get information about the current windowing system`
| :sg:`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.
.. versionadded:: 1.7.1
.. ## pygame.display.get_wm_info ##
.. function:: get_desktop_sizes
| :sl:`Get sizes of active desktops`
| :sg:`get_desktop_sizes() -> list`
This function returns the sizes of the currrently configured
virtual desktops as a list of (x, y) tuples of integers.
The length of the list is not the same as the number of attached monitors,
as a desktop can be mirrored across multiple monitors. The desktop sizes
do not indicate the maximum monitor resolutions supported by the hardware,
but the desktop size configured in the operating system.
In order to fit windows into the desktop as it is currently configured, and
to respect the resolution configured by the operating system in fullscreen
mode, this function *should* be used to replace many use cases of
``pygame.display.list_modes()`` whenever applicable.
.. versionadded:: 2.0.0
.. function:: list_modes
| :sl:`Get list of available fullscreen modes`
| :sg:`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.
Since pygame 2.0, ``pygame.display.get_desktop_sizes()`` has taken over
some use cases from ``pygame.display.list_modes()``:
To find a suitable size for non-fullscreen windows, it is preferable to
use ``pygame.display.get_desktop_sizes()`` to get the size of the *current*
desktop, and to then choose a smaller window size. This way, the window is
guaranteed to fit, even when the monitor is configured to a lower resolution
than the maximum supported by the hardware.
To avoid changing the physical monitor resolution, it is also preferable to
use ``pygame.display.get_desktop_sizes()`` to determine the fullscreen
resolution. Developers are strongly advised to default to the current
physical monitor resolution unless the user explicitly requests a different
one (e.g. in an options menu or configuration file).
.. versionchanged:: 1.9.5 ``display`` argument added
.. ## pygame.display.list_modes ##
.. function:: mode_ok
| :sl:`Pick the best color depth for a display mode`
| :sg:`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 function will return ``0`` if the passed display flags cannot be set.
The display index ``0`` means the default display is used.
.. versionchanged:: 1.9.5 ``display`` argument added
.. ## pygame.display.mode_ok ##
.. function:: gl_get_attribute
| :sl:`Get the value for an OpenGL flag for the current display`
| :sg:`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_get_attribute ##
.. function:: gl_set_attribute
| :sl:`Request an OpenGL display attribute for the display mode`
| :sg:`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
:const:`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.
:const:`GL_STENCIL_SIZE`
Minimum bit size of the stencil buffer. Defaults to 0.
:const:`GL_DEPTH_SIZE`
Minimum bit size of the depth buffer. Defaults to 16.
:const:`GL_STEREO`
1 enables stereo 3D. Defaults to 0.
:const:`GL_BUFFER_SIZE`
Minimum bit size of the frame buffer. Defaults to 0.
.. versionadded:: 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
:const:`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
:const:`GL_ACCELERATED_VISUAL`
Set to 1 to require hardware acceleration, or 0 to force software render.
By default, both are allowed.
.. ## pygame.display.gl_set_attribute ##
.. function:: get_active
| :sl:`Returns True when the display is active on the screen`
| :sg:`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.get_active ##
.. function:: iconify
| :sl:`Iconify the display surface`
| :sg:`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.iconify ##
.. function:: toggle_fullscreen
| :sl:`Switch between fullscreen and windowed displays`
| :sg:`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)
.. Note:: :func:`toggle_fullscreen` doesn't work on Windows
unless the window size is in :func:`pygame.display.list_modes()` or
the window is created with the flag ``pygame.SCALED``.
See `issue #2380 <https://github.com/pygame/pygame/issues/2380>`_.
.. ## pygame.display.toggle_fullscreen ##
.. function:: set_gamma
| :sl:`Change the hardware gamma ramps`
| :sg:`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 ##
.. function:: set_gamma_ramp
| :sl:`Change the hardware gamma ramps with a custom lookup`
| :sg:`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_gamma_ramp ##
.. function:: set_icon
| :sl:`Change the system image for the display window`
| :sg:`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.
Note that calling this function implicitly initializes ``pygame.display``, if
it was not initialized before.
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_icon ##
.. function:: set_caption
| :sl:`Set the current window caption`
| :sg:`set_caption(title, icontitle=None) -> None`
If the display has a window title, this function will change the name on the
window. In pygame 1.x, some systems supported an alternate shorter title to
be used for minimized displays, but in pygame 2 ``icontitle`` does nothing.
.. ## pygame.display.set_caption ##
.. function:: get_caption
| :sl:`Get the current window caption`
| :sg:`get_caption() -> (title, icontitle)`
Returns the title and icontitle for the display window. In pygame 2.x
these will always be the same value.
.. ## pygame.display.get_caption ##
.. function:: set_palette
| :sl:`Set the display color palette for indexed displays`
| :sg:`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.set_palette ##
.. function:: get_num_displays
| :sl:`Return the number of displays`
| :sg:`get_num_displays() -> int`
Returns the number of available displays. This is always 1 if
:func:`pygame.get_sdl_version()` returns a major version number below 2.
.. versionadded:: 1.9.5
.. ## pygame.display.get_num_displays ##
.. function:: get_window_size
| :sl:`Return the size of the window or screen`
| :sg:`get_window_size() -> tuple`
Returns the size of the window initialized with :func:`pygame.display.set_mode()`.
This may differ from the size of the display surface if ``SCALED`` is used.
.. versionadded:: 2.0.0
.. ## pygame.display.get_window_size ##
.. function:: get_allow_screensaver
| :sl:`Return whether the screensaver is allowed to run.`
| :sg:`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
:func:`pygame.display.set_allow_screensaver()` for
caveats with screensaver support.
.. versionadded:: 2.0.0
.. ## pygame.display.get_allow_screensaver ##
.. function:: set_allow_screensaver
| :sl:`Set whether the screensaver may run`
| :sg:`set_allow_screensaver(bool) -> None`
Change whether screensavers should be allowed whilst the app is running.
The default value of the argument to the function is True.
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 :func:`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.
.. versionadded:: 2.0.0
.. ## pygame.display.set_allow_screensaver ##
.. ## pygame.display ##

View file

@ -0,0 +1,559 @@
.. include:: common.txt
:mod:`pygame.draw`
==================
.. module:: pygame.draw
:synopsis: pygame module for drawing shapes
| :sl:`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 :mod:`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 :func:`pygame.Surface.map_rgb` and :func:`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 :func:`pygame.Surface.lock` and
:func:`pygame.Surface.unlock`).
.. note ::
See the :mod:`pygame.gfxdraw` module for alternative draw methods.
.. function:: rect
| :sl:`draw a rectangle`
| :sg:`rect(surface, color, rect) -> Rect`
| :sg:`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.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param Rect rect: rectangle to draw, position and dimensions
:param int width: (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 :func:`pygame.draw.line` function.
:param int border_radius: (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.
:param int border_top_left_radius: (optional) used for setting the value of top left
border. If you don't set this value, it will use the border_radius value.
:param int border_top_right_radius: (optional) used for setting the value of top right
border. If you don't set this value, it will use the border_radius value.
:param int border_bottom_left_radius: (optional) used for setting the value of bottom left
border. If you don't set this value, it will use the border_radius value.
:param int border_bottom_right_radius: (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
:rtype: Rect
.. note::
The :func:`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.
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. versionchanged:: 2.0.0.dev8 Added support for border radius.
.. ## pygame.draw.rect ##
.. function:: polygon
| :sl:`draw a polygon`
| :sg:`polygon(surface, color, points) -> Rect`
| :sg:`polygon(surface, color, points, width=0) -> Rect`
Draws a polygon on the given surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param points: 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/:class:`pygame.math.Vector2` of 2 ints/floats,
e.g. ``[(x1, y1), (x2, y2), (x3, y3)]``
:type points: tuple(coordinate) or list(coordinate)
:param int width: (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 :func:`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
:rtype: Rect
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises TypeError: if ``points`` is not a sequence or ``points`` does not
contain number pairs
.. note::
For an aapolygon, use :func:`aalines()` with ``closed=True``.
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.polygon ##
.. function:: circle
| :sl:`draw a circle`
| :sg:`circle(surface, color, center, radius) -> Rect`
| :sg:`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.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param center: center point of the circle as a sequence of 2 ints/floats,
e.g. ``(x, y)``
:type center: tuple(int or float, int or float) or
list(int or float, int or float) or Vector2(int or float, int or float)
:param radius: radius of the circle, measured from the ``center`` parameter,
nothing will be drawn if the ``radius`` is less than 1
:type radius: int or float
:param int width: (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.
:param bool draw_top_right: (optional) if this is set to True then the top right corner
of the circle will be drawn
:param bool draw_top_left: (optional) if this is set to True then the top left corner
of the circle will be drawn
:param bool draw_bottom_left: (optional) if this is set to True then the bottom left corner
of the circle will be drawn
:param bool draw_bottom_right: (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
:rtype: Rect
:raises TypeError: if ``center`` is not a sequence of two numbers
:raises TypeError: if ``radius`` is not a number
.. versionchanged:: 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.
.. versionchanged:: 2.0.0.dev8 Added support for drawing circle quadrants.
.. ## pygame.draw.circle ##
.. function:: ellipse
| :sl:`draw an ellipse`
| :sg:`ellipse(surface, color, rect) -> Rect`
| :sg:`ellipse(surface, color, rect, width=0) -> Rect`
Draws an ellipse on the given surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param Rect rect: rectangle to indicate the position and dimensions of the
ellipse, the ellipse will be centered inside the rectangle and bounded
by it
:param int width: (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
:rtype: Rect
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.ellipse ##
.. function:: arc
| :sl:`draw an elliptical arc`
| :sg:`arc(surface, color, rect, start_angle, stop_angle) -> Rect`
| :sg:`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``.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param 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
:param float start_angle: start angle of the arc in radians
:param float stop_angle: 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
|
:param int width: (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
:rtype: Rect
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.arc ##
.. function:: line
| :sl:`draw a straight line`
| :sg:`line(surface, color, start_pos, end_pos) -> Rect`
| :sg:`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.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param start_pos: start position of the line, (x, y)
:type 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)
:param end_pos: end position of the line, (x, y)
:type 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)
:param int width: (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
:rtype: Rect
:raises TypeError: if ``start_pos`` or ``end_pos`` is not a sequence of
two numbers
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.line ##
.. function:: lines
| :sl:`draw multiple contiguous straight line segments`
| :sg:`lines(surface, color, closed, points) -> Rect`
| :sg:`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.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param bool closed: if ``True`` an additional line segment is drawn between
the first and last points in the ``points`` sequence
:param points: a sequence of 2 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`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)``
:type points: tuple(coordinate) or list(coordinate)
:param int width: (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 :func:`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
:rtype: Rect
:raises ValueError: if ``len(points) < 2`` (must have at least 2 points)
:raises TypeError: if ``points`` is not a sequence or ``points`` does not
contain number pairs
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.lines ##
.. function:: aaline
| :sl:`draw a straight antialiased line`
| :sg:`aaline(surface, color, start_pos, end_pos) -> Rect`
| :sg:`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 its 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 its 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)``.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param start_pos: start position of the line, (x, y)
:type 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)
:param end_pos: end position of the line, (x, y)
:type 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)
:param int blend: (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
:rtype: Rect
:raises TypeError: if ``start_pos`` or ``end_pos`` is not a sequence of
two numbers
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.aaline ##
.. function:: aalines
| :sl:`draw multiple contiguous straight antialiased line segments`
| :sg:`aalines(surface, color, closed, points) -> Rect`
| :sg:`aalines(surface, color, closed, points, blend=1) -> Rect`
Draws a sequence of contiguous straight antialiased lines on the given
surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param bool closed: if ``True`` an additional line segment is drawn between
the first and last points in the ``points`` sequence
:param points: a sequence of 2 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`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)``
:type points: tuple(coordinate) or list(coordinate)
:param int blend: (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
:rtype: Rect
:raises ValueError: if ``len(points) < 2`` (must have at least 2 points)
:raises TypeError: if ``points`` is not a sequence or ``points`` does not
contain number pairs
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.aalines ##
.. ## pygame.draw ##
.. figure:: code_examples/draw_module_example.png
:alt: draw module example
Example code for draw module.
.. literalinclude:: code_examples/draw_module_example.py

View file

@ -0,0 +1,476 @@
.. include:: common.txt
:mod:`pygame.event`
===================
.. module:: pygame.event
:synopsis: pygame module for interacting with events and queues
| :sl:`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 :mod:`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 queue has an upper limit on the number of events it can hold. 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
:func:`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:
:mod:`pygame.mouse`, :mod:`pygame.key`, and :mod:`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 :func:`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 :class:`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
:func:`pygame.event.set_allowed()` and :func:`pygame.event.set_blocked()` to
change this filtering. By default, all event types can be placed on the queue.
All :class:`pygame.event.EventType` instances contain an event type identifier
and attributes specific to that event type. The event type identifier is
accessible as the :attr:`pygame.event.EventType.type` property. Any of the
event specific attributes can be accessed through the
:attr:`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 :func:`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``. User defined events can get a custom
event number with :func:`pygame.event.custom_type()`.
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 :func:`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, unicode, scancode
MOUSEMOTION pos, rel, buttons, touch
MOUSEBUTTONUP pos, button, touch
MOUSEBUTTONDOWN pos, button, touch
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
.. versionchanged:: 2.0.0 The ``joy`` attribute was deprecated, ``instance_id`` was added.
.. versionchanged:: 2.0.1 The ``unicode`` attribute was added to ``KEYUP`` event.
You can also find a list of constants for keyboard keys
:ref:`here <key-constants-label>`.
|
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
.. versionadded:: 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, touch
MULTIGESTURE touch_id, x, y, pinched, rotated, num_fingers
TEXTEDITING text, start, length
TEXTINPUT text
.. versionadded:: 1.9.5
.. versionchanged:: 2.0.2 Fixed amount horizontal scroll (x, positive to the right and negative to the left).
.. versionchanged:: 2.0.2 The ``touch`` attribute was added to all the ``MOUSE`` events.
The ``touch`` attribute of ``MOUSE`` events indicates whether or not the events were generated
by a touch input device, and not a real mouse. You might want to ignore such events, if your application
already handles ``FINGERMOTION``, ``FINGERDOWN`` and ``FINGERUP`` events.
|
Many new events were introduced in pygame 2.
pygame can recognize text or files dropped in its window. If a file
is dropped, ``DROPFILE`` event will be sent, ``file`` will be its path.
The ``DROPTEXT`` event is only supported on X11.
``MIDIIN`` and ``MIDIOUT`` are events reserved for :mod:`pygame.midi` use.
pygame 2 also supports controller hot-plugging
::
DROPBEGIN
DROPCOMPLETE
DROPFILE file
DROPTEXT text
MIDIIN
MIDIOUT
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.
.. versionadded:: 2.0.0
Since pygame 2.0.1, there are a new set of events, called window events.
Here is a list of all window events, along with a short description
::
Event type Short description
WINDOWSHOWN Window became shown
WINDOWHIDDEN Window became hidden
WINDOWEXPOSED Window got updated by some external event
WINDOWMOVED Window got moved
WINDOWRESIZED Window got resized
WINDOWSIZECHANGED Window changed its size
WINDOWMINIMIZED Window was minimized
WINDOWMAXIMIZED Window was maximized
WINDOWRESTORED Window was restored
WINDOWENTER Mouse entered the window
WINDOWLEAVE Mouse left the window
WINDOWFOCUSGAINED Window gained focus
WINDOWFOCUSLOST Window lost focus
WINDOWCLOSE Window was closed
WINDOWTAKEFOCUS Window was offered focus
WINDOWHITTEST Window has a special hit test
If SDL version used is less than 2.0.5, the last two events ``WINDOWTAKEFOCUS``
and ``WINDOWHITTEST`` will not work.
Most these window events do not have any attributes, except ``WINDOWMOVED``,
``WINDOWRESIZED`` and ``WINDOWSIZECHANGED``, these have ``x`` and ``y`` attributes
|
.. function:: pump
| :sl:`internally process pygame event handlers`
| :sg:`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 :mod:`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 :mod:`pygame.display`.
.. ## pygame.event.pump ##
.. function:: get
| :sl:`get events from the queue`
| :sg:`get(eventtype=None) -> Eventlist`
| :sg:`get(eventtype=None, pump=True) -> Eventlist`
| :sg:`get(eventtype=None, pump=True, exclude=None) -> 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 and returned.
If a type or sequence of types is passed in the ``exclude`` argument
instead, then all only *other* messages will be removed from the queue. If
an ``exclude`` parameter is passed, the ``eventtype`` parameter *must* be
None.
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 :func:`pygame.event.pump()` will be called.
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. versionchanged:: 2.0.2 Added ``exclude`` argument
.. ## pygame.event.get ##
.. function:: poll
| :sl:`get a single event from the queue`
| :sg:`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 :mod:`pygame.display`.
.. ## pygame.event.poll ##
.. function:: wait
| :sl:`wait for a single event from the queue`
| :sg:`wait() -> EventType instance`
| :sg:`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.
.. versionchanged:: 2.0.0.dev13 Added ``timeout`` argument
.. caution::
This function should only be called in the thread that initialized :mod:`pygame.display`.
.. ## pygame.event.wait ##
.. function:: peek
| :sl:`test if event types are waiting on the queue`
| :sg:`peek(eventtype=None) -> bool`
| :sg:`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 :func:`pygame.event.pump()` will be called.
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. ## pygame.event.peek ##
.. function:: clear
| :sl:`remove all events from the queue`
| :sg:`clear(eventtype=None) -> None`
| :sg:`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 :func:`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 :func:`pygame.event.pump()` will be called.
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. ## pygame.event.clear ##
.. function:: event_name
| :sl:`get the string name from an event id`
| :sg:`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.event_name ##
.. function:: set_blocked
| :sl:`control which events are allowed on the queue`
| :sg:`set_blocked(type) -> None`
| :sg:`set_blocked(typelist) -> None`
| :sg:`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_blocked ##
.. function:: set_allowed
| :sl:`control which events are allowed on the queue`
| :sg:`set_allowed(type) -> None`
| :sg:`set_allowed(typelist) -> None`
| :sg:`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.set_allowed ##
.. function:: get_blocked
| :sl:`test if a type of event is blocked from the queue`
| :sg:`get_blocked(type) -> bool`
| :sg:`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.get_blocked ##
.. function:: set_grab
| :sl:`control the sharing of input devices with other applications`
| :sg:`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.set_grab ##
.. function:: get_grab
| :sl:`test if the program is sharing input devices`
| :sg:`get_grab() -> bool`
Returns ``True`` when the input events are grabbed for this application.
.. ## pygame.event.get_grab ##
.. function:: post
| :sl:`place a new event on the queue`
| :sg:`post(Event) -> bool`
Places the given event at the end of the event queue.
This is usually used for placing custom events on the event queue.
Any type of event can be posted, and the events posted can have any attributes.
This returns a boolean on whether the event was posted or not. Blocked events
cannot be posted, and this function returns ``False`` if you try to post them.
.. versionchanged:: 2.0.1 returns a boolean, previously returned ``None``
.. ## pygame.event.post ##
.. function:: custom_type
| :sl:`make custom user event type`
| :sg:`custom_type() -> int`
Reserves a ``pygame.USEREVENT`` for a custom use.
If too many events are made a :exc:`pygame.error` is raised.
.. versionadded:: 2.0.0.dev3
.. ## pygame.event.custom_type ##
.. function:: Event
| :sl:`create a new event object`
| :sg:`Event(type, dict) -> EventType instance`
| :sg:`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.Event ##
.. class:: EventType
| :sl:`pygame object for representing events`
A pygame object that represents an event. User event instances are created
with an :func:`pygame.event.Event()` function call. The ``EventType`` type
is not directly callable. ``EventType`` instances support attribute
assignment and deletion.
.. attribute:: type
| :sl:`event type identifier.`
| :sg:`type -> int`
Read-only. The event type identifier. For user created event
objects, this is the ``type`` argument passed to
:func:`pygame.event.Event()`.
For example, some predefined event identifiers are ``QUIT`` and
``MOUSEMOTION``.
.. ## pygame.event.EventType.type ##
.. attribute:: __dict__
| :sl:`event attribute dictionary`
| :sg:`__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.event.EventType.__dict__ ##
.. versionadded:: 1.9.2 Mutable attributes.
.. ## pygame.event.EventType ##
.. ## pygame.event ##

View file

@ -0,0 +1,451 @@
.. include:: common.txt
:mod:`pygame.examples`
======================
.. module:: pygame.examples
:synopsis: module of example programs
| :sl:`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.
.. function:: aliens.main
| :sl:`play the full aliens example`
| :sg:`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.examples.aliens.main ##
.. function:: stars.main
| :sl:`run a simple starfield example`
| :sg:`stars.main() -> None`
A simple starfield example. You can change the center of perspective by
leftclicking the mouse on the screen.
.. ## pygame.examples.stars.main ##
.. function:: chimp.main
| :sl:`hit the moving chimp`
| :sg:`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.examples.chimp.main ##
.. function:: moveit.main
| :sl:`display animated objects on the screen`
| :sg:`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.examples.moveit.main ##
.. function:: fonty.main
| :sl:`run a font rendering example`
| :sg:`fonty.main() -> None`
Super quick, super simple application demonstrating the different ways to
render fonts with the font module
.. ## pygame.examples.fonty.main ##
.. function:: freetype_misc.main
| :sl:`run a FreeType rendering example`
| :sg:`freetype_misc.main() -> None`
A showcase of rendering features the :class:`pygame.freetype.Font`
class provides in addition to those available with :class:`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.examples.fonty.main ##
.. function:: vgrade.main
| :sl:`display a vertical gradient`
| :sg:`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.examples.vgrade.main ##
.. function:: eventlist.main
| :sl:`display pygame events`
| :sg:`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.examples.eventlist.main ##
.. function:: arraydemo.main
| :sl:`show various surfarray effects`
| :sg:`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.examples.arraydemo.main ##
.. function:: sound.main
| :sl:`load and play a sound`
| :sg:`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.examples.sound.main ##
.. function:: sound_array_demos.main
| :sl:`play various sndarray effects`
| :sg:`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.examples.sound_array_demos.main ##
.. function:: liquid.main
| :sl:`display an animated liquid effect`
| :sg:`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.examples.liquid.main ##
.. function:: glcube.main
| :sl:`display an animated 3D cube using OpenGL`
| :sg:`glcube.main() -> None`
Using PyOpenGL and pygame, this creates a spinning 3D multicolored cube.
.. ## pygame.examples.glcube.main ##
.. function:: scrap_clipboard.main
| :sl:`access the clipboard`
| :sg:`scrap_clipboard.main() -> None`
A simple demonstration example for the clipboard support.
.. ## pygame.examples.scrap_clipboard.main ##
.. function:: mask.main
| :sl:`display multiple images bounce off each other using collision detection`
| :sg:`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.examples.mask.main ##
.. function:: testsprite.main
| :sl:`show lots of sprites moving around`
| :sg:`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.examples.testsprite.main ##
.. function:: headless_no_windows_needed.main
| :sl:`write an image file that is smoothscaled copy of an input file`
| :sg:`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.examples.headless_no_windows_needed.main ##
.. function:: joystick.main
| :sl:`demonstrate joystick functionality`
| :sg:`joystick.main() -> None`
A demo showing full joystick support.
.. versionadded:: 2.0.2
.. ## pygame.examples.joystick.main ##
.. function:: blend_fill.main
| :sl:`demonstrate the various surface.fill method blend options`
| :sg:`blend_fill.main() -> None`
A interactive demo that lets one choose which BLEND_xxx option to apply to a
surface.
.. ## pygame.examples.blend_fill.main ##
.. function:: blit_blends.main
| :sl:`uses alternative additive fill to that of surface.fill`
| :sg:`blit_blends.main() -> None`
Fake additive blending. Using NumPy. it doesn't clamp. Press r,g,b Somewhat
like blend_fill.
.. ## pygame.examples.blit_blends.main ##
.. function:: cursors.main
| :sl:`display two different custom cursors`
| :sg:`cursors.main() -> None`
Display an arrow or circle with crossbar cursor.
.. ## pygame.examples.cursors.main ##
.. function:: pixelarray.main
| :sl:`display various pixelarray generated effects`
| :sg:`pixelarray.main() -> None`
Display various pixelarray generated effects.
.. ## pygame.examples.pixelarray.main ##
.. function:: scaletest.main
| :sl:`interactively scale an image using smoothscale`
| :sg:`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.examples.scaletest.main ##
.. function:: midi.main
| :sl:`run a midi example`
| :sg:`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.examples.midi.main ##
.. function:: scroll.main
| :sl:`run a Surface.scroll example that shows a magnified image`
| :sg:`scroll.main(image_file=None) -> None`
This example shows a scrollable image that has a zoom factor of eight. It
uses the :meth:`Surface.scroll() <pygame.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.examples.scroll.main ##
.. function:: camera.main
| :sl:`display video captured live from an attached camera`
| :sg:`camera.main() -> None`
A simple live video player, it uses the first available camera it finds on
the system.
.. ## pygame.examples.camera.main ##
.. function:: playmus.main
| :sl:`play an audio file`
| :sg:`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.examples.playmus.main ##
.. ## pygame.examples ##

View file

@ -0,0 +1,109 @@
.. include:: common.txt
:mod:`pygame.fastevent`
=======================
.. module:: pygame.fastevent
:synopsis: pygame module for interacting with events and queues from multiple
threads.
| :sl:`pygame module for interacting with events and queues`
IMPORTANT NOTE: THIS MODULE IS DEPRECATED IN PYGAME 2.2
In older pygame versions before pygame 2, :mod:`pygame.event` was not well
suited for posting events from different threads. This module served as a
replacement (with less features) for multithreaded use. Now, the usage of this
module is highly discouraged in favour of use of the main :mod:`pygame.event`
module. This module will be removed in a future pygame version.
Below, the legacy docs of the module is provided
.. function:: init
| :sl:`initialize pygame.fastevent`
| :sg:`init() -> None`
Initialize the pygame.fastevent module.
.. ## pygame.fastevent.init ##
.. function:: get_init
| :sl:`returns True if the fastevent module is currently initialized`
| :sg:`get_init() -> bool`
Returns True if the pygame.fastevent module is currently initialized.
.. ## pygame.fastevent.get_init ##
.. function:: pump
| :sl:`internally process pygame event handlers`
| :sg:`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 :mod:`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.pump ##
.. function:: wait
| :sl:`wait for an event`
| :sg:`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.wait ##
.. function:: poll
| :sl:`get an available event`
| :sg:`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.poll ##
.. function:: get
| :sl:`get all events from the queue`
| :sg:`get() -> list of Events`
This will get all the messages and remove them from the queue.
.. ## pygame.fastevent.get ##
.. function:: post
| :sl:`place an event on the queue`
| :sg:`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.fastevent.post ##
.. ## pygame.fastevent ##

View file

@ -0,0 +1,405 @@
.. include:: common.txt
:mod:`pygame.font`
==================
.. module:: pygame.font
:synopsis: pygame module for loading and rendering fonts
| :sl:`pygame module for loading and rendering fonts`
The font module allows for rendering TrueType fonts into a new Surface object.
It accepts any UCS-2 character ('\u0001' to '\uFFFF'). This module is optional
and requires SDL_ttf as a dependency. You should test that :mod:`pygame.font`
is available and initialized before attempting to use the module.
Most of the work done with fonts are done by using the actual Font objects. The
module by itself only has routines to initialize the module and create Font
objects with ``pygame.font.Font()``.
You can load fonts from the system by using the ``pygame.font.SysFont()``
function. There are a few other functions to help lookup the system fonts.
Pygame comes with a builtin default font. This can always be accessed by
passing None as the font name.
To use the :mod:`pygame.freetype` based ``pygame.ftfont`` as
:mod:`pygame.font` define the environment variable PYGAME_FREETYPE before the
first import of :mod:`pygame`. Module ``pygame.ftfont`` is a :mod:`pygame.font`
compatible module that passes all but one of the font module unit tests:
it does not have the UCS-2 limitation of the SDL_ttf based font module, so
fails to raise an exception for a code point greater than '\uFFFF'. If
:mod:`pygame.freetype` is unavailable then the SDL_ttf font module will be
loaded instead.
.. function:: init
| :sl:`initialize the font module`
| :sg:`init() -> None`
This method is called automatically by ``pygame.init()``. It initializes the
font module. The module must be initialized before any other functions will
work.
It is safe to call this function more than once.
.. ## pygame.font.init ##
.. function:: quit
| :sl:`uninitialize the font module`
| :sg:`quit() -> None`
Manually uninitialize SDL_ttf's font system. This is called automatically by
``pygame.quit()``.
It is safe to call this function even if font is currently not initialized.
.. ## pygame.font.quit ##
.. function:: get_init
| :sl:`true if the font module is initialized`
| :sg:`get_init() -> bool`
Test if the font module is initialized or not.
.. ## pygame.font.get_init ##
.. function:: get_default_font
| :sl:`get the filename of the default font`
| :sg:`get_default_font() -> string`
Return the filename of the system font. This is not the full path to the
file. This file can usually be found in the same directory as the font
module, but it can also be bundled in separate archives.
.. ## pygame.font.get_default_font ##
.. function:: get_fonts
| :sl:`get all available fonts`
| :sg:`get_fonts() -> list of strings`
Returns a list of all the fonts available on the system. The names of the
fonts will be set to lowercase with all spaces and punctuation removed. This
works on most systems, but some will return an empty list if they cannot
find fonts.
.. ## pygame.font.get_fonts ##
.. function:: match_font
| :sl:`find a specific font on the system`
| :sg:`match_font(name, bold=False, italic=False) -> path`
Returns the full path to a font file on the system. If bold or italic are
set to true, this will attempt to find the correct family of font.
The font name can also be an iterable of font names, a string of
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
If none of the given names are found, None is returned.
.. versionadded:: 2.0.1 Accept an iterable of font names.
Example:
::
print pygame.font.match_font('bitstreamverasans')
# output is: /usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf
# (but only if you have Vera on your system)
.. ## pygame.font.match_font ##
.. function:: SysFont
| :sl:`create a Font object from the system fonts`
| :sg:`SysFont(name, size, bold=False, italic=False) -> Font`
Return a new Font object that is loaded from the system fonts. The font will
match the requested bold and italic flags. Pygame uses a small set of common
font aliases. If the specific font you ask for is not available, a reasonable
alternative may be used. If a suitable system font is not found this will
fall back on loading the default pygame font.
The font name can also be an iterable of font names, a string of
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
.. versionadded:: 2.0.1 Accept an iterable of font names.
.. ## pygame.font.SysFont ##
.. class:: Font
| :sl:`create a new Font object from a file`
| :sg:`Font(filename, size) -> Font`
| :sg:`Font(pathlib.Path, size) -> Font`
| :sg:`Font(object, size) -> Font`
Load a new font from a given filename or a python file object. The size is
the height of the font in pixels. If the filename is None the pygame default
font will be loaded. If a font cannot be loaded from the arguments given an
exception will be raised. Once the font is created the size cannot be
changed.
Font objects are mainly used to render text into new Surface objects. The
render can emulate bold or italic features, but it is better to load from a
font with actual italic or bold glyphs. The rendered text can be regular
strings or unicode.
.. attribute:: bold
| :sl:`Gets or sets whether the font should be rendered in (faked) bold.`
| :sg:`bold -> bool`
Whether the font should be rendered in bold.
When set to True, this enables the bold rendering of text. This
is a fake stretching of the font that doesn't look good on many
font types. If possible load the font from a real bold font
file. While bold, the font will have a different width than when
normal. This can be mixed with the italic and underline modes.
.. versionadded:: 2.0.0
.. ## Font.bold ##
.. attribute:: italic
| :sl:`Gets or sets whether the font should be rendered in (faked) italics.`
| :sg:`italic -> bool`
Whether the font should be rendered in italic.
When set to True, this enables fake rendering of italic
text. This is a fake skewing of the font that doesn't look good
on many font types. If possible load the font from a real italic
font file. While italic the font will have a different width
than when normal. This can be mixed with the bold and underline
modes.
.. versionadded:: 2.0.0
.. ## Font.italic ##
.. attribute:: underline
| :sl:`Gets or sets whether the font should be rendered with an underline.`
| :sg:`underline -> bool`
Whether the font should be rendered in underline.
When set to True, all rendered fonts will include an
underline. The underline is always one pixel thick, regardless
of font size. This can be mixed with the bold and italic modes.
.. versionadded:: 2.0.0
.. ## Font.underline ##
.. method:: render
| :sl:`draw text on a new Surface`
| :sg:`render(text, antialias, color, background=None) -> Surface`
This creates a new Surface with the specified text rendered on it. pygame
provides no way to directly draw text on an existing Surface: instead you
must use ``Font.render()`` to create an image (Surface) of the text, then
blit this image onto another Surface.
The text can only be a single line: newline characters are not rendered.
Null characters ('\x00') raise a TypeError. Both Unicode and char (byte)
strings are accepted. For Unicode strings only UCS-2 characters
('\u0001' to '\uFFFF') were previously supported and any greater unicode
codepoint would raise a UnicodeError. Now, characters in the UCS-4 range
are supported. For char strings a ``LATIN1`` encoding is assumed. The
antialias argument is a boolean: if true the characters will have smooth
edges. The color argument is the color of the text
[e.g.: (0,0,255) for blue]. The optional background argument is a color
to use for the text background. If no background is passed the area
outside the text will be transparent.
The Surface returned will be of the dimensions required to hold the text.
(the same as those returned by Font.size()). If an empty string is passed
for the text, a blank surface will be returned that is zero pixel wide and
the height of the font.
Depending on the type of background and antialiasing used, this returns
different types of Surfaces. For performance reasons, it is good to know
what type of image will be used. If antialiasing is not used, the return
image will always be an 8-bit image with a two-color palette. If the
background is transparent a colorkey will be set. Antialiased images are
rendered to 24-bit ``RGB`` images. If the background is transparent a
pixel alpha will be included.
Optimization: if you know that the final destination for the text (on the
screen) will always have a solid background, and the text is antialiased,
you can improve performance by specifying the background color. This will
cause the resulting image to maintain transparency information by
colorkey rather than (much less efficient) alpha values.
If you render '\\n' an unknown char will be rendered. Usually a
rectangle. Instead you need to handle new lines yourself.
Font rendering is not thread safe: only a single thread can render text
at any time.
.. versionchanged:: 2.0.3 Rendering UCS_4 unicode works and does not
raise an exception. Use `if hasattr(pygame.font, 'UCS_4'):` to see if
pygame supports rendering UCS_4 unicode including more languages and
emoji.
.. ## Font.render ##
.. method:: size
| :sl:`determine the amount of space needed to render text`
| :sg:`size(text) -> (width, height)`
Returns the dimensions needed to render the text. This can be used to
help determine the positioning needed for text before it is rendered. It
can also be used for wordwrapping and other layout effects.
Be aware that most fonts use kerning which adjusts the widths for
specific letter pairs. For example, the width for "ae" will not always
match the width for "a" + "e".
.. ## Font.size ##
.. method:: set_underline
| :sl:`control if text is rendered with an underline`
| :sg:`set_underline(bool) -> None`
When enabled, all rendered fonts will include an underline. The underline
is always one pixel thick, regardless of font size. This can be mixed
with the bold and italic modes.
.. note:: This is the same as the :attr:`underline` attribute.
.. ## Font.set_underline ##
.. method:: get_underline
| :sl:`check if text will be rendered with an underline`
| :sg:`get_underline() -> bool`
Return True when the font underline is enabled.
.. note:: This is the same as the :attr:`underline` attribute.
.. ## Font.get_underline ##
.. method:: set_bold
| :sl:`enable fake rendering of bold text`
| :sg:`set_bold(bool) -> None`
Enables the bold rendering of text. This is a fake stretching of the font
that doesn't look good on many font types. If possible load the font from
a real bold font file. While bold, the font will have a different width
than when normal. This can be mixed with the italic and underline modes.
.. note:: This is the same as the :attr:`bold` attribute.
.. ## Font.set_bold ##
.. method:: get_bold
| :sl:`check if text will be rendered bold`
| :sg:`get_bold() -> bool`
Return True when the font bold rendering mode is enabled.
.. note:: This is the same as the :attr:`bold` attribute.
.. ## Font.get_bold ##
.. method:: set_italic
| :sl:`enable fake rendering of italic text`
| :sg:`set_italic(bool) -> None`
Enables fake rendering of italic text. This is a fake skewing of the font
that doesn't look good on many font types. If possible load the font from
a real italic font file. While italic the font will have a different
width than when normal. This can be mixed with the bold and underline
modes.
.. note:: This is the same as the :attr:`italic` attribute.
.. ## Font.set_italic ##
.. method:: metrics
| :sl:`gets the metrics for each character in the passed string`
| :sg:`metrics(text) -> list`
The list contains tuples for each character, which contain the minimum
``X`` offset, the maximum ``X`` offset, the minimum ``Y`` offset, the
maximum ``Y`` offset and the advance offset (bearing plus width) of the
character. [(minx, maxx, miny, maxy, advance), (minx, maxx, miny, maxy,
advance), ...]. None is entered in the list for each unrecognized
character.
.. ## Font.metrics ##
.. method:: get_italic
| :sl:`check if the text will be rendered italic`
| :sg:`get_italic() -> bool`
Return True when the font italic rendering mode is enabled.
.. note:: This is the same as the :attr:`italic` attribute.
.. ## Font.get_italic ##
.. method:: get_linesize
| :sl:`get the line space of the font text`
| :sg:`get_linesize() -> int`
Return the height in pixels for a line of text with the font. When
rendering multiple lines of text this is the recommended amount of space
between lines.
.. ## Font.get_linesize ##
.. method:: get_height
| :sl:`get the height of the font`
| :sg:`get_height() -> int`
Return the height in pixels of the actual rendered text. This is the
average size for each glyph in the font.
.. ## Font.get_height ##
.. method:: get_ascent
| :sl:`get the ascent of the font`
| :sg:`get_ascent() -> int`
Return the height in pixels for the font ascent. The ascent is the number
of pixels from the font baseline to the top of the font.
.. ## Font.get_ascent ##
.. method:: get_descent
| :sl:`get the descent of the font`
| :sg:`get_descent() -> int`
Return the height in pixels for the font descent. The descent is the
number of pixels from the font baseline to the bottom of the font.
.. ## Font.get_descent ##
.. ## pygame.font.Font ##
.. ## pygame.font ##

View file

@ -0,0 +1,766 @@
.. include:: common.txt
:mod:`pygame.freetype`
======================
.. module:: pygame.freetype
:synopsis: Enhanced pygame module for loading and rendering computer fonts
| :sl:`Enhanced pygame module for loading and rendering computer fonts`
The ``pygame.freetype`` module is a replacement for :mod:`pygame.font`.
It has all of the functionality of the original, plus many new features.
Yet is has absolutely no dependencies on the SDL_ttf library.
It is implemented directly on the FreeType 2 library.
The ``pygame.freetype`` module is not itself backward compatible with
:mod:`pygame.font`.
Instead, use the ``pygame.ftfont`` module as a drop-in replacement
for :mod:`pygame.font`.
All font file formats supported by FreeType can be rendered by
``pygame.freetype``, namely ``TTF``, Type1, ``CFF``, OpenType,
``SFNT``, ``PCF``, ``FNT``, ``BDF``, ``PFR`` and Type42 fonts.
All glyphs having UTF-32 code points are accessible
(see :attr:`Font.ucs4`).
Most work on fonts is done using :class:`Font` instances.
The module itself only has routines for initialization and creation
of :class:`Font` objects.
You can load fonts from the system using the :func:`SysFont` function.
Extra support of bitmap fonts is available. Available bitmap sizes can
be listed (see :meth:`Font.get_sizes`). For bitmap only fonts :class:`Font`
can set the size for you (see the :attr:`Font.size` property).
For now undefined character codes are replaced with the ``.notdef``
(not defined) character.
How undefined codes are handled may become configurable in a future release.
Pygame comes with a built-in default font. This can always be accessed by
passing None as the font name to the :class:`Font` constructor.
Extra rendering features available to :class:`pygame.freetype.Font`
are direct to surface rendering (see :meth:`Font.render_to`), character kerning
(see :attr:`Font.kerning`), vertical layout (see :attr:`Font.vertical`),
rotation of rendered text (see :attr:`Font.rotation`),
and the strong style (see :attr:`Font.strong`).
Some properties are configurable, such as
strong style strength (see :attr:`Font.strength`) and underline positioning
(see :attr:`Font.underline_adjustment`). Text can be positioned by the upper
right corner of the text box or by the text baseline (see :attr:`Font.origin`).
Finally, a font's vertical and horizontal size can be adjusted separately
(see :attr:`Font.size`).
The :any:`pygame.examples.freetype_misc <pygame.examples.freetype_misc.main>`
example shows these features in use.
The pygame package does not import ``freetype`` automatically when
loaded. This module must be imported explicitly to be used. ::
import pygame
import pygame.freetype
.. versionadded:: 1.9.2 :mod:`freetype`
.. function:: get_error
| :sl:`Return the latest FreeType error`
| :sg:`get_error() -> str`
| :sg:`get_error() -> None`
Return a description of the last error which occurred in the FreeType2
library, or ``None`` if no errors have occurred.
.. function:: get_version
| :sl:`Return the FreeType version`
| :sg:`get_version() -> (int, int, int)`
Returns the version of the FreeType library in use by this module.
Note that the ``freetype`` module depends on the FreeType 2 library.
It will not compile with the original FreeType 1.0. Hence, the first element
of the tuple will always be "2".
.. function:: init
| :sl:`Initialize the underlying FreeType library.`
| :sg:`init(cache_size=64, resolution=72) -> None`
This function initializes the underlying FreeType library and must be
called before trying to use any of the functionality of the ``freetype``
module.
However, :func:`pygame.init()` will automatically call this function
if the ``freetype`` module is already imported. It is safe to call this
function more than once.
Optionally, you may specify a default *cache_size* for the Glyph cache: the
maximum number of glyphs that will be cached at any given time by the
module. Exceedingly small values will be automatically tuned for
performance. Also a default pixel *resolution*, in dots per inch, can
be given to adjust font scaling.
.. function:: quit
| :sl:`Shut down the underlying FreeType library.`
| :sg:`quit() -> None`
This function closes the ``freetype`` module. After calling this
function, you should not invoke any class, method or function related to the
``freetype`` module as they are likely to fail or might give unpredictable
results. It is safe to call this function even if the module hasn't been
initialized yet.
.. function:: get_init
| :sl:`Returns True if the FreeType module is currently initialized.`
| :sg:`get_init() -> bool`
Returns ``True`` if the ``pygame.freetype`` module is currently initialized.
.. versionadded:: 1.9.5
.. function:: was_init
| :sl:`DEPRECATED: Use get_init() instead.`
| :sg:`was_init() -> bool`
DEPRECATED: Returns ``True`` if the ``pygame.freetype`` module is currently
initialized. Use ``get_init()`` instead.
.. function:: get_cache_size
| :sl:`Return the glyph case size`
| :sg:`get_cache_size() -> long`
See :func:`pygame.freetype.init()`.
.. function:: get_default_resolution
| :sl:`Return the default pixel size in dots per inch`
| :sg:`get_default_resolution() -> long`
Returns the default pixel size, in dots per inch, for the module.
The default is 72 DPI.
.. function:: set_default_resolution
| :sl:`Set the default pixel size in dots per inch for the module`
| :sg:`set_default_resolution([resolution])`
Set the default pixel size, in dots per inch, for the module. If the
optional argument is omitted or zero the resolution is reset to 72 DPI.
.. function:: SysFont
| :sl:`create a Font object from the system fonts`
| :sg:`SysFont(name, size, bold=False, italic=False) -> Font`
Return a new Font object that is loaded from the system fonts. The font will
match the requested *bold* and *italic* flags. Pygame uses a small set of
common font aliases. If the specific font you ask for is not available, a
reasonable alternative may be used. If a suitable system font is not found
this will fall back on loading the default pygame font.
The font *name* can also be an iterable of font names, a string of
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
.. versionadded:: 2.0.1 Accept an iterable of font names.
.. function:: get_default_font
| :sl:`Get the filename of the default font`
| :sg:`get_default_font() -> string`
Return the filename of the default pygame font. This is not the full path
to the file. The file is usually in the same directory as the font module,
but can also be bundled in a separate archive.
.. class:: Font
| :sl:`Create a new Font instance from a supported font file.`
| :sg:`Font(file, size=0, font_index=0, resolution=0, ucs4=False) -> Font`
| :sg:`Font(pathlib.Path) -> Font`
Argument *file* can be either a string representing the font's filename, a
file-like object containing the font, or None; if None, a default,
Pygame, font is used.
.. _freetype-font-size-argument:
Optionally, a *size* argument may be specified to set the default size in
points, which determines the size of the rendered characters.
The size can also be passed explicitly to each method call.
Because of the way the caching system works, specifying a default size on
the constructor doesn't imply a performance gain over manually passing
the size on each function call. If the font is bitmap and no *size*
is given, the default size is set to the first available size for the font.
If the font file has more than one font, the font to load can be chosen with
the *index* argument. An exception is raised for an out-of-range font index
value.
The optional *resolution* argument sets the pixel size, in dots per inch,
for use in scaling glyphs for this Font instance. If 0 then the default
module value, set by :func:`init`, is used. The Font object's
resolution can only be changed by re-initializing the Font instance.
The optional *ucs4* argument, an integer, sets the default text translation
mode: 0 (False) recognize UTF-16 surrogate pairs, any other value (True),
to treat Unicode text as UCS-4, with no surrogate pairs. See
:attr:`Font.ucs4`.
.. attribute:: name
| :sl:`Proper font name.`
| :sg:`name -> string`
Read only. Returns the real (long) name of the font, as
recorded in the font file.
.. attribute:: path
| :sl:`Font file path`
| :sg:`path -> unicode`
Read only. Returns the path of the loaded font file
.. attribute:: size
| :sl:`The default point size used in rendering`
| :sg:`size -> float`
| :sg:`size -> (float, float)`
Get or set the default size for text metrics and rendering. It can be
a single point size, given as a Python ``int`` or ``float``, or a
font ppem (width, height) ``tuple``. Size values are non-negative.
A zero size or width represents an undefined size. In this case
the size must be given as a method argument, or an exception is
raised. A zero width but non-zero height is a ValueError.
For a scalable font, a single number value is equivalent to a tuple
with width equal height. A font can be stretched vertically with
height set greater than width, or horizontally with width set
greater than height. For embedded bitmaps, as listed by :meth:`get_sizes`,
use the nominal width and height to select an available size.
Font size differs for a non-scalable, bitmap, font. During a
method call it must match one of the available sizes returned by
method :meth:`get_sizes`. If not, an exception is raised.
If the size is a single number, the size is first matched against the
point size value. If no match, then the available size with the
same nominal width and height is chosen.
.. method:: get_rect
| :sl:`Return the size and offset of rendered text`
| :sg:`get_rect(text, style=STYLE_DEFAULT, rotation=0, size=0) -> rect`
Gets the final dimensions and origin, in pixels, of *text* using the
optional *size* in points, *style*, and *rotation*. For other
relevant render properties, and for any optional argument not given,
the default values set for the :class:`Font` instance are used.
Returns a :class:`Rect <pygame.Rect>` instance containing the
width and height of the text's bounding box and the position of the
text's origin.
The origin is useful in aligning separately rendered pieces of text.
It gives the baseline position and bearing at the start of the text.
See the :meth:`render_to` method for an example.
If *text* is a char (byte) string, its encoding is assumed to be
``LATIN1``.
Optionally, *text* can be ``None``, which will return the bounding
rectangle for the text passed to a previous :meth:`get_rect`,
:meth:`render`, :meth:`render_to`, :meth:`render_raw`, or
:meth:`render_raw_to` call. See :meth:`render_to` for more
details.
.. method:: get_metrics
| :sl:`Return the glyph metrics for the given text`
| :sg:`get_metrics(text, size=0) -> [(...), ...]`
Returns the glyph metrics for each character in *text*.
The glyph metrics are returned as a list of tuples. Each tuple gives
metrics of a single character glyph. The glyph metrics are:
::
(min_x, max_x, min_y, max_y, horizontal_advance_x, horizontal_advance_y)
The bounding box min_x, max_x, min_y, and max_y values are returned as
grid-fitted pixel coordinates of type int. The advance values are
float values.
The calculations are done using the font's default size in points.
Optionally you may specify another point size with the *size* argument.
The metrics are adjusted for the current rotation, strong, and oblique
settings.
If text is a char (byte) string, then its encoding is assumed to be
``LATIN1``.
.. attribute:: height
| :sl:`The unscaled height of the font in font units`
| :sg:`height -> int`
Read only. Gets the height of the font. This is the average value of all
glyphs in the font.
.. attribute:: ascender
| :sl:`The unscaled ascent of the font in font units`
| :sg:`ascender -> int`
Read only. Return the number of units from the font's baseline to
the top of the bounding box.
.. attribute:: descender
| :sl:`The unscaled descent of the font in font units`
| :sg:`descender -> int`
Read only. Return the height in font units for the font descent.
The descent is the number of units from the font's baseline to the
bottom of the bounding box.
.. method:: get_sized_ascender
| :sl:`The scaled ascent of the font in pixels`
| :sg:`get_sized_ascender(<size>=0) -> int`
Return the number of units from the font's baseline to the top of the
bounding box. It is not adjusted for strong or rotation.
.. method:: get_sized_descender
| :sl:`The scaled descent of the font in pixels`
| :sg:`get_sized_descender(<size>=0) -> int`
Return the number of pixels from the font's baseline to the top of the
bounding box. It is not adjusted for strong or rotation.
.. method:: get_sized_height
| :sl:`The scaled height of the font in pixels`
| :sg:`get_sized_height(<size>=0) -> int`
Returns the height of the font. This is the average value of all
glyphs in the font. It is not adjusted for strong or rotation.
.. method:: get_sized_glyph_height
| :sl:`The scaled bounding box height of the font in pixels`
| :sg:`get_sized_glyph_height(<size>=0) -> int`
Return the glyph bounding box height of the font in pixels.
This is the average value of all glyphs in the font.
It is not adjusted for strong or rotation.
.. method:: get_sizes
| :sl:`return the available sizes of embedded bitmaps`
| :sg:`get_sizes() -> [(int, int, int, float, float), ...]`
| :sg:`get_sizes() -> []`
Returns a list of tuple records, one for each point size
supported. Each tuple containing the point size, the height in pixels,
width in pixels, horizontal ppem (nominal width) in fractional pixels,
and vertical ppem (nominal height) in fractional pixels.
.. method:: render
| :sl:`Return rendered text as a surface`
| :sg:`render(text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> (Surface, Rect)`
Returns a new :class:`Surface <pygame.Surface>`,
with the text rendered to it
in the color given by 'fgcolor'. If no foreground color is given,
the default foreground color, :attr:`fgcolor <Font.fgcolor>` is used.
If ``bgcolor`` is given, the surface
will be filled with this color. When no background color is given,
the surface background is transparent, zero alpha. Normally the returned
surface has a 32 bit pixel size. However, if ``bgcolor`` is ``None``
and anti-aliasing is disabled a monochrome 8 bit colorkey surface,
with colorkey set for the background color, is returned.
The return value is a tuple: the new surface and the bounding
rectangle giving the size and origin of the rendered text.
If an empty string is passed for text then the returned Rect is zero
width and the height of the font.
Optional *fgcolor*, *style*, *rotation*, and *size* arguments override
the default values set for the :class:`Font` instance.
If *text* is a char (byte) string, then its encoding is assumed to be
``LATIN1``.
Optionally, *text* can be ``None``, which will render the text
passed to a previous :meth:`get_rect`, :meth:`render`, :meth:`render_to`,
:meth:`render_raw`, or :meth:`render_raw_to` call.
See :meth:`render_to` for details.
.. method:: render_to
| :sl:`Render text onto an existing surface`
| :sg:`render_to(surf, dest, text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> Rect`
Renders the string *text* to the :mod:`pygame.Surface` *surf*,
at position *dest*, a (x, y) surface coordinate pair.
If either x or y is not an integer it is converted to one if possible.
Any sequence where the first two items are x and y positional elements
is accepted, including a :class:`Rect <pygame.Rect>` instance.
As with :meth:`render`,
optional *fgcolor*, *style*, *rotation*, and *size* argument are
available.
If a background color *bgcolor* is given, the text bounding box is
first filled with that color. The text is blitted next.
Both the background fill and text rendering involve full alpha blits.
That is, the alpha values of the foreground, background, and destination
target surface all affect the blit.
The return value is a rectangle giving the size and position of the
rendered text within the surface.
If an empty string is passed for text then the returned
:class:`Rect <pygame.Rect>` is zero width and the height of the font.
The rect will test False.
Optionally, *text* can be set ``None``, which will re-render text
passed to a previous :meth:`render_to`, :meth:`get_rect`, :meth:`render`,
:meth:`render_raw`, or :meth:`render_raw_to` call. Primarily, this
feature is an aid to using :meth:`render_to` in combination with
:meth:`get_rect`. An example: ::
def word_wrap(surf, text, font, color=(0, 0, 0)):
font.origin = True
words = text.split(' ')
width, height = surf.get_size()
line_spacing = font.get_sized_height() + 2
x, y = 0, line_spacing
space = font.get_rect(' ')
for word in words:
bounds = font.get_rect(word)
if x + bounds.width + bounds.x >= width:
x, y = 0, y + line_spacing
if x + bounds.width + bounds.x >= width:
raise ValueError("word too wide for the surface")
if y + bounds.height - bounds.y >= height:
raise ValueError("text to long for the surface")
font.render_to(surf, (x, y), None, color)
x += bounds.width + space.width
return x, y
When :meth:`render_to` is called with the same
font properties:attr:`size`, :attr:`style`, :attr:`strength`,
:attr:`wide`, :attr:`antialiased`, :attr:`vertical`, :attr:`rotation`,
:attr:`kerning`, and :attr:`use_bitmap_strikes`as :meth:`get_rect`,
:meth:`render_to` will use the layout calculated by :meth:`get_rect`.
Otherwise, :meth:`render_to` will recalculate the layout if called
with a text string or one of the above properties has changed
after the :meth:`get_rect` call.
If *text* is a char (byte) string, then its encoding is assumed to be
``LATIN1``.
.. method:: render_raw
| :sl:`Return rendered text as a string of bytes`
| :sg:`render_raw(text, style=STYLE_DEFAULT, rotation=0, size=0, invert=False) -> (bytes, (int, int))`
Like :meth:`render` but with the pixels returned as a byte string
of 8-bit gray-scale values. The foreground color is 255, the
background 0, useful as an alpha mask for a foreground pattern.
.. method:: render_raw_to
| :sl:`Render text into an array of ints`
| :sg:`render_raw_to(array, text, dest=None, style=STYLE_DEFAULT, rotation=0, size=0, invert=False) -> Rect`
Render to an array object exposing an array struct interface. The array
must be two dimensional with integer items. The default *dest* value,
``None``, is equivalent to position (0, 0). See :meth:`render_to`.
As with the other render methods, *text* can be ``None`` to
render a text string passed previously to another method.
The return value is a :func:`pygame.Rect` giving the size and position of
the rendered text.
.. attribute:: style
| :sl:`The font's style flags`
| :sg:`style -> int`
Gets or sets the default style of the Font. This default style will be
used for all text rendering and size calculations unless overridden
specifically a render or :meth:`get_rect` call.
The style value may be a bit-wise OR of one or more of the following
constants:
::
STYLE_NORMAL
STYLE_UNDERLINE
STYLE_OBLIQUE
STYLE_STRONG
STYLE_WIDE
STYLE_DEFAULT
These constants may be found on the FreeType constants module.
Optionally, the default style can be modified or obtained accessing the
individual style attributes (underline, oblique, strong).
The ``STYLE_OBLIQUE`` and ``STYLE_STRONG`` styles are for
scalable fonts only. An attempt to set either for a bitmap font raises
an AttributeError. An attempt to set either for an inactive font,
as returned by ``Font.__new__()``, raises a RuntimeError.
Assigning ``STYLE_DEFAULT`` to the :attr:`style` property leaves
the property unchanged, as this property defines the default.
The :attr:`style` property will never return ``STYLE_DEFAULT``.
.. attribute:: underline
| :sl:`The state of the font's underline style flag`
| :sg:`underline -> bool`
Gets or sets whether the font will be underlined when drawing text. This
default style value will be used for all text rendering and size
calculations unless overridden specifically in a render or
:meth:`get_rect` call, via the 'style' parameter.
.. attribute:: strong
| :sl:`The state of the font's strong style flag`
| :sg:`strong -> bool`
Gets or sets whether the font will be bold when drawing text. This
default style value will be used for all text rendering and size
calculations unless overridden specifically in a render or
:meth:`get_rect` call, via the 'style' parameter.
.. attribute:: oblique
| :sl:`The state of the font's oblique style flag`
| :sg:`oblique -> bool`
Gets or sets whether the font will be rendered as oblique. This
default style value will be used for all text rendering and size
calculations unless overridden specifically in a render or
:meth:`get_rect` call, via the *style* parameter.
The oblique style is only supported for scalable (outline) fonts.
An attempt to set this style on a bitmap font will raise an
AttributeError. If the font object is inactive, as returned by
``Font.__new__()``, setting this property raises a RuntimeError.
.. attribute:: wide
| :sl:`The state of the font's wide style flag`
| :sg:`wide -> bool`
Gets or sets whether the font will be stretched horizontally
when drawing text. It produces a result similar to
:class:`pygame.font.Font`'s bold. This style not available for
rotated text.
.. attribute:: strength
| :sl:`The strength associated with the strong or wide font styles`
| :sg:`strength -> float`
The amount by which a font glyph's size is enlarged for the
strong or wide transformations, as a fraction of the untransformed
size. For the wide style only the horizontal dimension is
increased. For strong text both the horizontal and vertical
dimensions are enlarged. A wide style of strength 0.08333 ( 1/12 ) is
equivalent to the :class:`pygame.font.Font` bold style.
The default is 0.02778 ( 1/36 ).
The strength style is only supported for scalable (outline) fonts.
An attempt to set this property on a bitmap font will raise an
AttributeError. If the font object is inactive, as returned by
``Font.__new__()``, assignment to this property raises a RuntimeError.
.. attribute:: underline_adjustment
| :sl:`Adjustment factor for the underline position`
| :sg:`underline_adjustment -> float`
Gets or sets a factor which, when positive, is multiplied with the
font's underline offset to adjust the underline position. A negative
value turns an underline into a strike-through or overline. It is
multiplied with the ascender. Accepted values range between -2.0 and 2.0
inclusive. A value of 0.5 closely matches Tango underlining. A value of
1.0 mimics :class:`pygame.font.Font` underlining.
.. attribute:: fixed_width
| :sl:`Gets whether the font is fixed-width`
| :sg:`fixed_width -> bool`
Read only. Returns ``True`` if the font contains fixed-width
characters (for example Courier, Bitstream Vera Sans Mono, Andale Mono).
.. attribute:: fixed_sizes
| :sl:`the number of available bitmap sizes for the font`
| :sg:`fixed_sizes -> int`
Read only. Returns the number of point sizes for which the font contains
bitmap character images. If zero then the font is not a bitmap font.
A scalable font may contain pre-rendered point sizes as strikes.
.. attribute:: scalable
| :sl:`Gets whether the font is scalable`
| :sg:`scalable -> bool`
Read only. Returns ``True`` if the font contains outline glyphs.
If so, the point size is not limited to available bitmap sizes.
.. attribute:: use_bitmap_strikes
| :sl:`allow the use of embedded bitmaps in an outline font file`
| :sg:`use_bitmap_strikes -> bool`
Some scalable fonts include embedded bitmaps for particular point
sizes. This property controls whether or not those bitmap strikes
are used. Set it ``False`` to disable the loading of any bitmap
strike. Set it ``True``, the default, to permit bitmap strikes
for a non-rotated render with no style other than :attr:`wide` or
:attr:`underline`. This property is ignored for bitmap fonts.
See also :attr:`fixed_sizes` and :meth:`get_sizes`.
.. attribute:: antialiased
| :sl:`Font anti-aliasing mode`
| :sg:`antialiased -> bool`
Gets or sets the font's anti-aliasing mode. This defaults to
``True`` on all fonts, which are rendered with full 8 bit blending.
Set to ``False`` to do monochrome rendering. This should
provide a small speed gain and reduce cache memory size.
.. attribute:: kerning
| :sl:`Character kerning mode`
| :sg:`kerning -> bool`
Gets or sets the font's kerning mode. This defaults to ``False``
on all fonts, which will be rendered without kerning.
Set to ``True`` to add kerning between character pairs, if supported
by the font, when positioning glyphs.
.. attribute:: vertical
| :sl:`Font vertical mode`
| :sg:`vertical -> bool`
Gets or sets whether the characters are laid out vertically rather
than horizontally. May be useful when rendering Kanji or some other
vertical script.
Set to ``True`` to switch to a vertical text layout. The default
is ``False``, place horizontally.
Note that the :class:`Font` class does not automatically determine
script orientation. Vertical layout must be selected explicitly.
Also note that several font formats (especially bitmap based ones) don't
contain the necessary metrics to draw glyphs vertically, so drawing in
those cases will give unspecified results.
.. attribute:: rotation
| :sl:`text rotation in degrees counterclockwise`
| :sg:`rotation -> int`
Gets or sets the baseline angle of the rendered text. The angle is
represented as integer degrees. The default angle is 0, with horizontal
text rendered along the X-axis, and vertical text along the Y-axis.
A positive value rotates these axes counterclockwise that many degrees.
A negative angle corresponds to a clockwise rotation. The rotation
value is normalized to a value within the range 0 to 359 inclusive
(eg. 390 -> 390 - 360 -> 30, -45 -> 360 + -45 -> 315,
720 -> 720 - (2 * 360) -> 0).
Only scalable (outline) fonts can be rotated. An attempt to change
the rotation of a bitmap font raises an AttributeError.
An attempt to change the rotation of an inactive font instance, as
returned by ``Font.__new__()``, raises a RuntimeError.
.. attribute:: fgcolor
| :sl:`default foreground color`
| :sg:`fgcolor -> Color`
Gets or sets the default glyph rendering color. It is initially opaque
black(0, 0, 0, 255). Applies to :meth:`render` and :meth:`render_to`.
.. attribute:: bgcolor
| :sl:`default background color`
| :sg:`bgcolor -> Color`
Gets or sets the default background rendering color. Initially it is
unset and text will render with a transparent background by default.
Applies to :meth:`render` and :meth:`render_to`.
.. versionadded:: 2.0.0
.. attribute:: origin
| :sl:`Font render to text origin mode`
| :sg:`origin -> bool`
If set ``True``, :meth:`render_to` and :meth:`render_raw_to` will
take the *dest* position to be that of the text origin, as opposed to
the top-left corner of the bounding box. See :meth:`get_rect` for
details.
.. attribute:: pad
| :sl:`padded boundary mode`
| :sg:`pad -> bool`
If set ``True``, then the text boundary rectangle will be inflated
to match that of :class:`font.Font <pygame.font.Font>`.
Otherwise, the boundary rectangle is just large enough for the text.
.. attribute:: ucs4
| :sl:`Enable UCS-4 mode`
| :sg:`ucs4 -> bool`
Gets or sets the decoding of Unicode text. By default, the
freetype module performs UTF-16 surrogate pair decoding on Unicode text.
This allows 32-bit escape sequences ('\Uxxxxxxxx') between 0x10000 and
0x10FFFF to represent their corresponding UTF-32 code points on Python
interpreters built with a UCS-2 Unicode type (on Windows, for instance).
It also means character values within the UTF-16 surrogate area (0xD800
to 0xDFFF) are considered part of a surrogate pair. A malformed surrogate
pair will raise a UnicodeEncodeError. Setting ucs4 ``True`` turns
surrogate pair decoding off, allowing access the full UCS-4 character
range to a Python interpreter built with four-byte Unicode character
support.
.. attribute:: resolution
| :sl:`Pixel resolution in dots per inch`
| :sg:`resolution -> int`
Read only. Gets pixel size used in scaling font glyphs for this
:class:`Font` instance.

View file

@ -0,0 +1,628 @@
.. include:: common.txt
:mod:`pygame.gfxdraw`
=====================
.. module:: pygame.gfxdraw
:synopsis: pygame module for drawing shapes
| :sl:`pygame module for drawing shapes`
**EXPERIMENTAL!**: This API may change or disappear in later pygame releases. If
you use this, your code may break with the next pygame release.
The pygame package does not import gfxdraw automatically when loaded, so it
must imported explicitly to be used.
::
import pygame
import pygame.gfxdraw
For all functions the arguments are strictly positional and integers are
accepted for coordinates and radii. The ``color`` argument can be one of the
following formats:
- a :mod:`pygame.Color` object
- an ``(RGB)`` triplet (tuple/list)
- an ``(RGBA)`` quadruplet (tuple/list)
The functions :meth:`rectangle` and :meth:`box` will accept any ``(x, y, w, h)``
sequence for their ``rect`` argument, though :mod:`pygame.Rect` instances are
preferred.
To draw a filled antialiased shape, first use the antialiased (aa*) version
of the function, and then use the filled (filled_*) version.
For example:
::
col = (255, 0, 0)
surf.fill((255, 255, 255))
pygame.gfxdraw.aacircle(surf, x, y, 30, col)
pygame.gfxdraw.filled_circle(surf, x, y, 30, col)
.. note::
For threading, each of the functions releases the GIL during the C part of
the call.
.. note::
See the :mod:`pygame.draw` module for alternative draw methods.
The ``pygame.gfxdraw`` module differs from the :mod:`pygame.draw` module in
the API it uses and the different draw functions available.
``pygame.gfxdraw`` wraps the primitives from the library called SDL_gfx,
rather than using modified versions.
.. versionadded:: 1.9.0
.. function:: pixel
| :sl:`draw a pixel`
| :sg:`pixel(surface, x, y, color) -> None`
Draws a single pixel, at position (x ,y), on the given surface.
:param Surface surface: surface to draw on
:param int x: x coordinate of the pixel
:param int y: y coordinate of the pixel
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.pixel ##
.. function:: hline
| :sl:`draw a horizontal line`
| :sg:`hline(surface, x1, x2, y, color) -> None`
Draws a straight horizontal line (``(x1, y)`` to ``(x2, y)``) on the given
surface. There are no endcaps.
:param Surface surface: surface to draw on
:param int x1: x coordinate of one end of the line
:param int x2: x coordinate of the other end of the line
:param int y: y coordinate of the line
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.hline ##
.. function:: vline
| :sl:`draw a vertical line`
| :sg:`vline(surface, x, y1, y2, color) -> None`
Draws a straight vertical line (``(x, y1)`` to ``(x, y2)``) on the given
surface. There are no endcaps.
:param Surface surface: surface to draw on
:param int x: x coordinate of the line
:param int y1: y coordinate of one end of the line
:param int y2: y coordinate of the other end of the line
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.vline ##
.. function:: line
| :sl:`draw a line`
| :sg:`line(surface, x1, y1, x2, y2, color) -> None`
Draws a straight line (``(x1, y1)`` to ``(x2, y2)``) on the given surface.
There are no endcaps.
:param Surface surface: surface to draw on
:param int x1: x coordinate of one end of the line
:param int y1: y coordinate of one end of the line
:param int x2: x coordinate of the other end of the line
:param int y2: y coordinate of the other end of the line
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.line ##
.. function:: rectangle
| :sl:`draw a rectangle`
| :sg:`rectangle(surface, rect, color) -> None`
Draws an unfilled rectangle on the given surface. For a filled rectangle use
:meth:`box`.
:param Surface surface: surface to draw on
:param Rect rect: rectangle to draw, position and dimensions
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. note::
The ``rect.bottom`` and ``rect.right`` attributes of a :mod:`pygame.Rect`
always lie one pixel outside of its actual border. Therefore, these
values will not be included as part of the drawing.
.. ## pygame.gfxdraw.rectangle ##
.. function:: box
| :sl:`draw a filled rectangle`
| :sg:`box(surface, rect, color) -> None`
Draws a filled rectangle on the given surface. For an unfilled rectangle use
:meth:`rectangle`.
:param Surface surface: surface to draw on
:param Rect rect: rectangle to draw, position and dimensions
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. note::
The ``rect.bottom`` and ``rect.right`` attributes of a :mod:`pygame.Rect`
always lie one pixel outside of its actual border. Therefore, these
values will not be included as part of the drawing.
.. note::
The :func:`pygame.Surface.fill` method works just as well for drawing
filled rectangles. In fact :func:`pygame.Surface.fill` can be hardware
accelerated on some platforms with both software and hardware display
modes.
.. ## pygame.gfxdraw.box ##
.. function:: circle
| :sl:`draw a circle`
| :sg:`circle(surface, x, y, r, color) -> None`
Draws an unfilled circle on the given surface. For a filled circle use
:meth:`filled_circle`.
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the circle
:param int y: y coordinate of the center of the circle
:param int r: radius of the circle
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.circle ##
.. function:: aacircle
| :sl:`draw an antialiased circle`
| :sg:`aacircle(surface, x, y, r, color) -> None`
Draws an unfilled antialiased circle on the given surface.
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the circle
:param int y: y coordinate of the center of the circle
:param int r: radius of the circle
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.aacircle ##
.. function:: filled_circle
| :sl:`draw a filled circle`
| :sg:`filled_circle(surface, x, y, r, color) -> None`
Draws a filled circle on the given surface. For an unfilled circle use
:meth:`circle`.
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the circle
:param int y: y coordinate of the center of the circle
:param int r: radius of the circle
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.filled_circle ##
.. function:: ellipse
| :sl:`draw an ellipse`
| :sg:`ellipse(surface, x, y, rx, ry, color) -> None`
Draws an unfilled ellipse on the given surface. For a filled ellipse use
:meth:`filled_ellipse`.
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the ellipse
:param int y: y coordinate of the center of the ellipse
:param int rx: horizontal radius of the ellipse
:param int ry: vertical radius of the ellipse
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.ellipse ##
.. function:: aaellipse
| :sl:`draw an antialiased ellipse`
| :sg:`aaellipse(surface, x, y, rx, ry, color) -> None`
Draws an unfilled antialiased ellipse on the given surface.
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the ellipse
:param int y: y coordinate of the center of the ellipse
:param int rx: horizontal radius of the ellipse
:param int ry: vertical radius of the ellipse
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.aaellipse ##
.. function:: filled_ellipse
| :sl:`draw a filled ellipse`
| :sg:`filled_ellipse(surface, x, y, rx, ry, color) -> None`
Draws a filled ellipse on the given surface. For an unfilled ellipse use
:meth:`ellipse`.
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the ellipse
:param int y: y coordinate of the center of the ellipse
:param int rx: horizontal radius of the ellipse
:param int ry: vertical radius of the ellipse
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.filled_ellipse ##
.. function:: arc
| :sl:`draw an arc`
| :sg:`arc(surface, x, y, r, start_angle, stop_angle, color) -> None`
Draws an arc on the given surface. For an arc with its endpoints connected
to its center use :meth:`pie`.
The two angle arguments are given in degrees and indicate the start and stop
positions of the arc. The arc is drawn in a clockwise direction from the
``start_angle`` to the ``stop_angle``. If ``start_angle == stop_angle``,
nothing will be drawn
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the arc
:param int y: y coordinate of the center of the arc
:param int r: radius of the arc
:param int start_angle: start angle in degrees
:param int stop_angle: stop angle in degrees
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. note::
This function uses *degrees* while the :func:`pygame.draw.arc` function
uses *radians*.
.. ## pygame.gfxdraw.arc ##
.. function:: pie
| :sl:`draw a pie`
| :sg:`pie(surface, x, y, r, start_angle, stop_angle, color) -> None`
Draws an unfilled pie on the given surface. A pie is an :meth:`arc` with its
endpoints connected to its center.
The two angle arguments are given in degrees and indicate the start and stop
positions of the pie. The pie is drawn in a clockwise direction from the
``start_angle`` to the ``stop_angle``. If ``start_angle == stop_angle``,
a straight line will be drawn from the center position at the given angle,
to a length of the radius.
:param Surface surface: surface to draw on
:param int x: x coordinate of the center of the pie
:param int y: y coordinate of the center of the pie
:param int r: radius of the pie
:param int start_angle: start angle in degrees
:param int stop_angle: stop angle in degrees
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.pie ##
.. function:: trigon
| :sl:`draw a trigon/triangle`
| :sg:`trigon(surface, x1, y1, x2, y2, x3, y3, color) -> None`
Draws an unfilled trigon (triangle) on the given surface. For a filled
trigon use :meth:`filled_trigon`.
A trigon can also be drawn using :meth:`polygon` e.g.
``polygon(surface, ((x1, y1), (x2, y2), (x3, y3)), color)``
:param Surface surface: surface to draw on
:param int x1: x coordinate of the first corner of the trigon
:param int y1: y coordinate of the first corner of the trigon
:param int x2: x coordinate of the second corner of the trigon
:param int y2: y coordinate of the second corner of the trigon
:param int x3: x coordinate of the third corner of the trigon
:param int y3: y coordinate of the third corner of the trigon
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.trigon ##
.. function:: aatrigon
| :sl:`draw an antialiased trigon/triangle`
| :sg:`aatrigon(surface, x1, y1, x2, y2, x3, y3, color) -> None`
Draws an unfilled antialiased trigon (triangle) on the given surface.
An aatrigon can also be drawn using :meth:`aapolygon` e.g.
``aapolygon(surface, ((x1, y1), (x2, y2), (x3, y3)), color)``
:param Surface surface: surface to draw on
:param int x1: x coordinate of the first corner of the trigon
:param int y1: y coordinate of the first corner of the trigon
:param int x2: x coordinate of the second corner of the trigon
:param int y2: y coordinate of the second corner of the trigon
:param int x3: x coordinate of the third corner of the trigon
:param int y3: y coordinate of the third corner of the trigon
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.aatrigon ##
.. function:: filled_trigon
| :sl:`draw a filled trigon/triangle`
| :sg:`filled_trigon(surface, x1, y1, x2, y2, x3, y3, color) -> None`
Draws a filled trigon (triangle) on the given surface. For an unfilled
trigon use :meth:`trigon`.
A filled_trigon can also be drawn using :meth:`filled_polygon` e.g.
``filled_polygon(surface, ((x1, y1), (x2, y2), (x3, y3)), color)``
:param Surface surface: surface to draw on
:param int x1: x coordinate of the first corner of the trigon
:param int y1: y coordinate of the first corner of the trigon
:param int x2: x coordinate of the second corner of the trigon
:param int y2: y coordinate of the second corner of the trigon
:param int x3: x coordinate of the third corner of the trigon
:param int y3: y coordinate of the third corner of the trigon
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
.. ## pygame.gfxdraw.filled_trigon ##
.. function:: polygon
| :sl:`draw a polygon`
| :sg:`polygon(surface, points, color) -> None`
Draws an unfilled polygon on the given surface. For a filled polygon use
:meth:`filled_polygon`.
The adjacent coordinates in the ``points`` argument, as well as the first
and last points, will be connected by line segments.
e.g. For the points ``[(x1, y1), (x2, y2), (x3, y3)]`` a line segment will
be drawn from ``(x1, y1)`` to ``(x2, y2)``, from ``(x2, y2)`` to
``(x3, y3)``, and from ``(x3, y3)`` to ``(x1, y1)``.
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats (float values
will be truncated)
:type points: tuple(coordinate) or list(coordinate)
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.polygon ##
.. function:: aapolygon
| :sl:`draw an antialiased polygon`
| :sg:`aapolygon(surface, points, color) -> None`
Draws an unfilled antialiased polygon on the given surface.
The adjacent coordinates in the ``points`` argument, as well as the first
and last points, will be connected by line segments.
e.g. For the points ``[(x1, y1), (x2, y2), (x3, y3)]`` a line segment will
be drawn from ``(x1, y1)`` to ``(x2, y2)``, from ``(x2, y2)`` to
``(x3, y3)``, and from ``(x3, y3)`` to ``(x1, y1)``.
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats (float values
will be truncated)
:type points: tuple(coordinate) or list(coordinate)
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.aapolygon ##
.. function:: filled_polygon
| :sl:`draw a filled polygon`
| :sg:`filled_polygon(surface, points, color) -> None`
Draws a filled polygon on the given surface. For an unfilled polygon use
:meth:`polygon`.
The adjacent coordinates in the ``points`` argument, as well as the first
and last points, will be connected by line segments.
e.g. For the points ``[(x1, y1), (x2, y2), (x3, y3)]`` a line segment will
be drawn from ``(x1, y1)`` to ``(x2, y2)``, from ``(x2, y2)`` to
``(x3, y3)``, and from ``(x3, y3)`` to ``(x1, y1)``.
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats (float values
will be truncated)`
:type points: tuple(coordinate) or list(coordinate)
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.filled_polygon ##
.. function:: textured_polygon
| :sl:`draw a textured polygon`
| :sg:`textured_polygon(surface, points, texture, tx, ty) -> None`
Draws a textured polygon on the given surface. For better performance, the
surface and the texture should have the same format.
A per-pixel alpha texture blit to a per-pixel alpha surface will differ from
a :func:`pygame.Surface.blit` blit. Also, a per-pixel alpha texture cannot be
used with an 8-bit per pixel destination.
The adjacent coordinates in the ``points`` argument, as well as the first
and last points, will be connected by line segments.
e.g. For the points ``[(x1, y1), (x2, y2), (x3, y3)]`` a line segment will
be drawn from ``(x1, y1)`` to ``(x2, y2)``, from ``(x2, y2)`` to
``(x3, y3)``, and from ``(x3, y3)`` to ``(x1, y1)``.
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats (float values
will be truncated)
:type points: tuple(coordinate) or list(coordinate)
:param Surface texture: texture to draw on the polygon
:param int tx: x offset of the texture
:param int ty: y offset of the texture
:returns: ``None``
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.textured_polygon ##
.. function:: bezier
| :sl:`draw a Bezier curve`
| :sg:`bezier(surface, points, steps, color) -> None`
Draws a Bézier curve on the given surface.
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates used to form a
curve, where each *coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats (float values
will be truncated)
:type points: tuple(coordinate) or list(coordinate)
:param int steps: number of steps for the interpolation, the minimum is 2
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or tuple(int, int, int, [int])
:returns: ``None``
:rtype: NoneType
:raises ValueError: if ``steps < 2``
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.bezier ##
.. ## pygame.gfxdraw ##

View file

@ -0,0 +1,284 @@
.. include:: common.txt
:mod:`pygame.image`
===================
.. module:: pygame.image
:synopsis: pygame module for image transfer
| :sl:`pygame module for image transfer`
The image module contains functions for loading and saving pictures, as well as
transferring Surfaces to formats usable by other packages.
Note that there is no Image class; an image is loaded as a Surface object. The
Surface class allows manipulation (drawing lines, setting pixels, capturing
regions, etc.).
The image module is a required dependency of pygame, but it only optionally
supports any extended file formats. By default it can only load uncompressed
``BMP`` images. When built with full image support, the ``pygame.image.load()``
function can support the following formats.
* ``BMP``
* ``GIF`` (non-animated)
* ``JPEG``
* ``LBM`` (and ``PBM``, ``PGM``, ``PPM``)
* ``PCX``
* ``PNG``
* ``PNM``
* ``SVG`` (limited support, using Nano SVG)
* ``TGA`` (uncompressed)
* ``TIFF``
* ``WEBP``
* ``XPM``
.. versionadded:: 2.0 Loading SVG, WebP, PNM
Saving images only supports a limited set of formats. You can save to the
following formats.
* ``BMP``
* ``JPEG``
* ``PNG``
* ``TGA``
``JPEG`` and ``JPG``, as well as ``TIF`` and ``TIFF`` refer to the same file format
.. versionadded:: 1.8 Saving PNG and JPEG files.
.. function:: load
| :sl:`load new image from a file (or file-like object)`
| :sg:`load(filename) -> Surface`
| :sg:`load(fileobj, namehint="") -> Surface`
Load an image from a file source. You can pass either a filename, a Python
file-like object, or a pathlib.Path.
Pygame will automatically determine the image type (e.g., ``GIF`` or bitmap)
and create a new Surface object from the data. In some cases it will need to
know the file extension (e.g., ``GIF`` images should end in ".gif"). If you
pass a raw file-like object, you may also want to pass the original filename
as the namehint argument.
The returned Surface will contain the same color format, colorkey and alpha
transparency as the file it came from. You will often want to call
``Surface.convert()`` with no arguments, to create a copy that will draw
more quickly on the screen.
For alpha transparency, like in .png images, use the ``convert_alpha()``
method after loading so that the image has per pixel transparency.
pygame may not always be built to support all image formats. At minimum it
will support uncompressed ``BMP``. If ``pygame.image.get_extended()``
returns 'True', you should be able to load most images (including PNG, JPG
and GIF).
You should use ``os.path.join()`` for compatibility.
::
eg. asurf = pygame.image.load(os.path.join('data', 'bla.png'))
.. ## pygame.image.load ##
.. function:: save
| :sl:`save an image to file (or file-like object)`
| :sg:`save(Surface, filename) -> None`
| :sg:`save(Surface, fileobj, namehint="") -> None`
This will save your Surface as either a ``BMP``, ``TGA``, ``PNG``, or
``JPEG`` image. If the filename extension is unrecognized it will default to
``TGA``. Both ``TGA``, and ``BMP`` file formats create uncompressed files.
You can pass a filename, a pathlib.Path or a Python file-like object.
For file-like object, the image is saved to ``TGA`` format unless
a namehint with a recognizable extension is passed in.
.. note:: When saving to a file-like object, it seems that for most formats,
the object needs to be flushed after saving to it to make loading
from it possible.
.. versionchanged:: 1.8 Saving PNG and JPEG files.
.. versionchanged:: 2.0.0
The ``namehint`` parameter was added to make it possible
to save other formats than ``TGA`` to a file-like object.
Saving to a file-like object with JPEG is possible.
.. ## pygame.image.save ##
.. function:: get_sdl_image_version
| :sl:`get version number of the SDL_Image library being used`
| :sg:`get_sdl_image_version() -> None`
| :sg:`get_sdl_image_version() -> (major, minor, patch)`
If pygame is built with extended image formats, then this function will
return the SDL_Image library's version number as a tuple of 3 integers
``(major, minor, patch)``. If not, then it will return ``None``.
.. versionadded:: 2.0.0
.. ## pygame.image.get_sdl_image_version ##
.. function:: get_extended
| :sl:`test if extended image formats can be loaded`
| :sg:`get_extended() -> bool`
If pygame is built with extended image formats this function will return
True. It is still not possible to determine which formats will be available,
but generally you will be able to load them all.
.. ## pygame.image.get_extended ##
.. function:: tostring
| :sl:`transfer image to string buffer`
| :sg:`tostring(Surface, format, flipped=False) -> string`
Creates a string that can be transferred with the 'fromstring' method in
other Python imaging packages. Some Python image packages prefer their
images in bottom-to-top format (PyOpenGL for example). If you pass True for
the flipped argument, the string buffer will be vertically flipped.
The format argument is a string of one of the following values. Note that
only 8-bit Surfaces can use the "P" format. The other formats will work for
any Surface. Also note that other Python image packages support more formats
than pygame.
* ``P``, 8-bit palettized Surfaces
* ``RGB``, 24-bit image
* ``RGBX``, 32-bit image with unused space
* ``RGBA``, 32-bit image with an alpha channel
* ``ARGB``, 32-bit image with alpha channel first
* ``RGBA_PREMULT``, 32-bit image with colors scaled by alpha channel
* ``ARGB_PREMULT``, 32-bit image with colors scaled by alpha channel, alpha channel first
.. ## pygame.image.tostring ##
.. function:: fromstring
| :sl:`create new Surface from a string buffer`
| :sg:`fromstring(string, size, format, flipped=False) -> Surface`
This function takes arguments similar to ``pygame.image.tostring()``. The
size argument is a pair of numbers representing the width and height. Once
the new Surface is created you can destroy the string buffer.
The size and format image must compute the exact same size as the passed
string buffer. Otherwise an exception will be raised.
See the ``pygame.image.frombuffer()`` method for a potentially faster way to
transfer images into pygame.
.. ## pygame.image.fromstring ##
.. function:: frombuffer
| :sl:`create a new Surface that shares data inside a bytes buffer`
| :sg:`frombuffer(bytes, size, format) -> Surface`
Create a new Surface that shares pixel data directly from a bytes buffer.
This method takes similar arguments to ``pygame.image.fromstring()``, but
is unable to vertically flip the source data.
This will run much faster than :func:`pygame.image.fromstring`, since no
pixel data must be allocated and copied.
It accepts the following 'format' arguments:
* ``P``, 8-bit palettized Surfaces
* ``RGB``, 24-bit image
* ``BGR``, 24-bit image, red and blue channels swapped.
* ``RGBX``, 32-bit image with unused space
* ``RGBA``, 32-bit image with an alpha channel
* ``ARGB``, 32-bit image with alpha channel first
.. ## pygame.image.frombuffer ##
.. function:: load_basic
| :sl:`load new BMP image from a file (or file-like object)`
| :sg:`load_basic(file) -> Surface`
Load an image from a file source. You can pass either a filename or a Python
file-like object, or a pathlib.Path.
This function only supports loading "basic" image format, ie ``BMP``
format.
This function is always available, no matter how pygame was built.
.. ## pygame.image.load_basic ##
.. function:: load_extended
| :sl:`load an image from a file (or file-like object)`
| :sg:`load_extended(filename) -> Surface`
| :sg:`load_extended(fileobj, namehint="") -> Surface`
This function is similar to ``pygame.image.load()``, except that this
function can only be used if pygame was built with extended image format
support.
From version 2.0.1, this function is always available, but raises an
error if extended image formats are not supported. Previously, this
function may or may not be available, depending on the state of
extended image format support.
.. versionchanged:: 2.0.1
.. ## pygame.image.load_extended ##
.. function:: save_extended
| :sl:`save a png/jpg image to file (or file-like object)`
| :sg:`save_extended(Surface, filename) -> None`
| :sg:`save_extended(Surface, fileobj, namehint="") -> None`
This will save your Surface as either a ``PNG`` or ``JPEG`` image.
Incase the image is being saved to a file-like object, this function
uses the namehint argument to determine the format of the file being
saved. Saves to ``JPEG`` incase the namehint was not specified while
saving to file-like object.
.. versionchanged:: 2.0.1
This function is always available, but raises an
error if extended image formats are not supported.
Previously, this function may or may not be
available, depending on the state of extended image
format support.
.. ## pygame.image.save_extended ##
.. ## pygame.image ##

View file

@ -0,0 +1,545 @@
.. include:: common.txt
:mod:`pygame.joystick`
======================
.. module:: pygame.joystick
:synopsis: Pygame module for interacting with joysticks, gamepads, and trackballs.
| :sl:`Pygame module for interacting with joysticks, gamepads, and trackballs.`
The joystick module manages the joystick devices on a computer.
Joystick devices include trackballs and video-game-style
gamepads, and the module allows the use of multiple buttons and "hats".
Computers may manage multiple joysticks at a time.
Each instance of the Joystick class represents one gaming device plugged
into the computer. If a gaming pad has multiple joysticks on it, then the
joystick object can actually represent multiple joysticks on that single
game device.
For a quick way to initialise the joystick module and get a list of Joystick instances
use the following code::
pygame.joystick.init()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
The following event types will be generated by the joysticks ::
JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION
And in pygame 2, which supports hotplugging::
JOYDEVICEADDED JOYDEVICEREMOVED
Note that in pygame 2, joysticks events use a unique "instance ID". The device index
passed in the constructor to a Joystick object is not unique after devices have
been added and removed. You must call :meth:`Joystick.get_instance_id()` to find
the instance ID that was assigned to a Joystick on opening.
The event queue needs to be pumped frequently for some of the methods to work.
So call one of pygame.event.get, pygame.event.wait, or pygame.event.pump regularly.
.. function:: init
| :sl:`Initialize the joystick module.`
| :sg:`init() -> None`
This function is called automatically by ``pygame.init()``.
It initializes the joystick module. The module must be initialized before any
other functions will work.
It is safe to call this function more than once.
.. ## pygame.joystick.init ##
.. function:: quit
| :sl:`Uninitialize the joystick module.`
| :sg:`quit() -> None`
Uninitialize the joystick module. After you call this any existing joystick
objects will no longer work.
It is safe to call this function more than once.
.. ## pygame.joystick.quit ##
.. function:: get_init
| :sl:`Returns True if the joystick module is initialized.`
| :sg:`get_init() -> bool`
Test if the ``pygame.joystick.init()`` function has been called.
.. ## pygame.joystick.get_init ##
.. function:: get_count
| :sl:`Returns the number of joysticks.`
| :sg:`get_count() -> count`
Return the number of joystick devices on the system. The count will be ``0``
if there are no joysticks on the system.
When you create Joystick objects using ``Joystick(id)``, you pass an integer
that must be lower than this count.
.. ## pygame.joystick.get_count ##
.. class:: Joystick
| :sl:`Create a new Joystick object.`
| :sg:`Joystick(id) -> Joystick`
Create a new joystick to access a physical device. The id argument must be a
value from ``0`` to ``pygame.joystick.get_count() - 1``.
Joysticks are initialised on creation and are shut down when deallocated.
Once the device is initialized the pygame event queue will start receiving
events about its input.
.. versionchanged:: 2.0.0 Joystick objects are now opened immediately on creation.
.. method:: init
| :sl:`initialize the Joystick`
| :sg:`init() -> None`
Initialize the joystick, if it has been closed. It is safe to call this
even if the joystick is already initialized.
.. deprecated:: 2.0.0
In future it will not be possible to reinitialise a closed Joystick
object. Will be removed in Pygame 2.1.
.. ## Joystick.init ##
.. method:: quit
| :sl:`uninitialize the Joystick`
| :sg:`quit() -> None`
Close a Joystick object. After this the pygame event queue will no longer
receive events from the device.
It is safe to call this more than once.
.. ## Joystick.quit ##
.. method:: get_init
| :sl:`check if the Joystick is initialized`
| :sg:`get_init() -> bool`
Return True if the Joystick object is currently initialised.
.. ## Joystick.get_init ##
.. method:: get_id
| :sl:`get the device index (deprecated)`
| :sg:`get_id() -> int`
Returns the original device index for this device. This is the same
value that was passed to the ``Joystick()`` constructor. This method can
safely be called while the Joystick is not initialized.
.. deprecated:: 2.0.0
The original device index is not useful in pygame 2. Use
:meth:`.get_instance_id` instead. Will be removed in Pygame 2.1.
.. method:: get_instance_id() -> int
| :sl:`get the joystick instance id`
| :sg:`get_instance_id() -> int`
Get the joystick instance ID. This matches the ``instance_id`` field
that is given in joystick events.
.. versionadded:: 2.0.0dev11
.. method:: get_guid() -> str
| :sl:`get the joystick GUID`
| :sg:`get_guid() -> str`
Get the GUID string. This identifies the exact hardware of the joystick
device.
.. versionadded:: 2.0.0dev11
.. method:: get_power_level() -> str
| :sl:`get the approximate power status of the device`
| :sg:`get_power_level() -> str`
Get a string giving the power status of the device.
One of: ``empty``, ``low``, ``medium``, ``full``, ``wired``, ``max``, or
``unknown``.
.. versionadded:: 2.0.0dev11
.. ## Joystick.get_id ##
.. method:: get_name
| :sl:`get the Joystick system name`
| :sg:`get_name() -> string`
Returns the system name for this joystick device. It is unknown what name
the system will give to the Joystick, but it should be a unique name that
identifies the device. This method can safely be called while the
Joystick is not initialized.
.. ## Joystick.get_name ##
.. method:: get_numaxes
| :sl:`get the number of axes on a Joystick`
| :sg:`get_numaxes() -> int`
Returns the number of input axes are on a Joystick. There will usually be
two for the position. Controls like rudders and throttles are treated as
additional axes.
The ``pygame.JOYAXISMOTION`` events will be in the range from ``-1.0``
to ``1.0``. A value of ``0.0`` means the axis is centered. Gamepad devices
will usually be ``-1``, ``0``, or ``1`` with no values in between. Older
analog joystick axes will not always use the full ``-1`` to ``1`` range,
and the centered value will be some area around ``0``.
Analog joysticks usually have a bit of noise in their axis, which will
generate a lot of rapid small motion events.
.. ## Joystick.get_numaxes ##
.. method:: get_axis
| :sl:`get the current position of an axis`
| :sg:`get_axis(axis_number) -> float`
Returns the current position of a joystick axis. The value will range
from ``-1`` to ``1`` with a value of ``0`` being centered. You may want
to take into account some tolerance to handle jitter, and joystick drift
may keep the joystick from centering at ``0`` or using the full range of
position values.
The axis number must be an integer from ``0`` to ``get_numaxes() - 1``.
When using gamepads both the control sticks and the analog triggers are
usually reported as axes.
.. ## Joystick.get_axis ##
.. method:: get_numballs
| :sl:`get the number of trackballs on a Joystick`
| :sg:`get_numballs() -> int`
Returns the number of trackball devices on a Joystick. These devices work
similar to a mouse but they have no absolute position; they only have
relative amounts of movement.
The ``pygame.JOYBALLMOTION`` event will be sent when the trackball is
rolled. It will report the amount of movement on the trackball.
.. ## Joystick.get_numballs ##
.. method:: get_ball
| :sl:`get the relative position of a trackball`
| :sg:`get_ball(ball_number) -> x, y`
Returns the relative movement of a joystick button. The value is a ``x, y``
pair holding the relative movement since the last call to get_ball.
The ball number must be an integer from ``0`` to ``get_numballs() - 1``.
.. ## Joystick.get_ball ##
.. method:: get_numbuttons
| :sl:`get the number of buttons on a Joystick`
| :sg:`get_numbuttons() -> int`
Returns the number of pushable buttons on the joystick. These buttons
have a boolean (on or off) state.
Buttons generate a ``pygame.JOYBUTTONDOWN`` and ``pygame.JOYBUTTONUP``
event when they are pressed and released.
.. ## Joystick.get_numbuttons ##
.. method:: get_button
| :sl:`get the current button state`
| :sg:`get_button(button) -> bool`
Returns the current state of a joystick button.
.. ## Joystick.get_button ##
.. method:: get_numhats
| :sl:`get the number of hat controls on a Joystick`
| :sg:`get_numhats() -> int`
Returns the number of joystick hats on a Joystick. Hat devices are like
miniature digital joysticks on a joystick. Each hat has two axes of
input.
The ``pygame.JOYHATMOTION`` event is generated when the hat changes
position. The ``position`` attribute for the event contains a pair of
values that are either ``-1``, ``0``, or ``1``. A position of ``(0, 0)``
means the hat is centered.
.. ## Joystick.get_numhats ##
.. method:: get_hat
| :sl:`get the position of a joystick hat`
| :sg:`get_hat(hat_number) -> x, y`
Returns the current position of a position hat. The position is given as
two values representing the ``x`` and ``y`` position for the hat. ``(0, 0)``
means centered. A value of ``-1`` means left/down and a value of ``1`` means
right/up: so ``(-1, 0)`` means left; ``(1, 0)`` means right; ``(0, 1)`` means
up; ``(1, 1)`` means upper-right; etc.
This value is digital, ``i.e.``, each coordinate can be ``-1``, ``0`` or ``1``
but never in-between.
The hat number must be between ``0`` and ``get_numhats() - 1``.
.. ## Joystick.get_hat ##
.. method:: rumble
| :sl:`Start a rumbling effect`
| :sg:`rumble(low_frequency, high_frequency, duration) -> bool`
Start a rumble effect on the joystick, with the specified strength ranging
from 0 to 1. Duration is length of the effect, in ms. Setting the duration
to 0 will play the effect until another one overwrites it or
:meth:`Joystick.stop_rumble` is called. If an effect is already
playing, then it will be overwritten.
Returns True if the rumble was played successfully or False if the
joystick does not support it or :meth:`pygame.version.SDL` is below 2.0.9.
.. versionadded:: 2.0.2
.. ## Joystick.rumble ##
.. method:: stop_rumble
| :sl:`Stop any rumble effect playing`
| :sg:`stop_rumble() -> None`
Stops any rumble effect playing on the joystick. See
:meth:`Joystick.rumble` for more information.
.. versionadded:: 2.0.2
.. ## Joystick.stop_rumble ##
.. ## pygame.joystick.Joystick ##
.. ## pygame.joystick ##
.. figure:: code_examples/joystick_calls.png
:scale: 100 %
:alt: joystick module example
Example code for joystick module.
.. literalinclude:: code_examples/joystick_calls.py
.. _controller-mappings:
**Common Controller Axis Mappings**
Controller mappings are drawn from the underlying SDL library which pygame uses and they differ
between pygame 1 and pygame 2. Below are a couple of mappings for two popular game pads.
**Pygame 2**
Axis and hat mappings are listed from -1 to +1.
**X-Box 360 Controller (name: "Xbox 360 Controller")**
In pygame 2 the X360 controller mapping has 6 Axes, 11 buttons and 1 hat.
* **Left Stick**::
Left -> Right - Axis 0
Up -> Down - Axis 1
* **Right Stick**::
Left -> Right - Axis 3
Up -> Down - Axis 4
* **Left Trigger**::
Out -> In - Axis 2
* **Right Trigger**::
Out -> In - Axis 5
* **Buttons**::
A Button - Button 0
B Button - Button 1
X Button - Button 2
Y Button - Button 3
Left Bumper - Button 4
Right Bumper - Button 5
Back Button - Button 6
Start Button - Button 7
L. Stick In - Button 8
R. Stick In - Button 9
Guide Button - Button 10
* **Hat/D-pad**::
Down -> Up - Y Axis
Left -> Right - X Axis
**Playstation 4 Controller (name: "PS4 Controller")**
In pygame 2 the PS4 controller mapping has 6 Axes and 16 buttons.
* **Left Stick**::
Left -> Right - Axis 0
Up -> Down - Axis 1
* **Right Stick**::
Left -> Right - Axis 2
Up -> Down - Axis 3
* **Left Trigger**::
Out -> In - Axis 4
* **Right Trigger**::
Out -> In - Axis 5
* **Buttons**::
Cross Button - Button 0
Circle Button - Button 1
Square Button - Button 2
Triangle Button - Button 3
Share Button - Button 4
PS Button - Button 5
Options Button - Button 6
L. Stick In - Button 7
R. Stick In - Button 8
Left Bumper - Button 9
Right Bumper - Button 10
D-pad Up - Button 11
D-pad Down - Button 12
D-pad Left - Button 13
D-pad Right - Button 14
Touch Pad Click - Button 15
**Pygame 1**
Axis and hat mappings are listed from -1 to +1.
**X-Box 360 Controller (name: "Controller (XBOX 360 For Windows)")**
In pygame 1 the X360 controller mapping has 5 Axes, 10 buttons and 1 hat.
* **Left Stick**::
Left -> Right - Axis 0
Up -> Down - Axis 1
* **Right Stick**::
Left -> Right - Axis 4
Up -> Down - Axis 3
* **Left Trigger & Right Trigger**::
RT -> LT - Axis 2
* **Buttons**::
A Button - Button 0
B Button - Button 1
X Button - Button 2
Y Button - Button 3
Left Bumper - Button 4
Right Bumper - Button 5
Back Button - Button 6
Start Button - Button 7
L. Stick In - Button 8
R. Stick In - Button 9
* **Hat/D-pad**::
Down -> Up - Y Axis
Left -> Right - X Axis
**Playstation 4 Controller (name: "Wireless Controller")**
In pygame 1 the PS4 controller mapping has 6 Axes and 14 buttons and 1 hat.
* **Left Stick**::
Left -> Right - Axis 0
Up -> Down - Axis 1
* **Right Stick**::
Left -> Right - Axis 2
Up -> Down - Axis 3
* **Left Trigger**::
Out -> In - Axis 5
* **Right Trigger**::
Out -> In - Axis 4
* **Buttons**::
Cross Button - Button 0
Circle Button - Button 1
Square Button - Button 2
Triangle Button - Button 3
Left Bumper - Button 4
Right Bumper - Button 5
L. Trigger(Full)- Button 6
R. Trigger(Full)- Button 7
Share Button - Button 8
Options Button - Button 9
L. Stick In - Button 10
R. Stick In - Button 11
PS Button - Button 12
Touch Pad Click - Button 13
* **Hat/D-pad**::
Down -> Up - Y Axis
Left -> Right - X Axis

View file

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

View file

@ -0,0 +1,27 @@
.. include:: common.txt
:mod:`pygame.locals`
====================
.. module:: pygame.locals
:synopsis: pygame constants
| :sl:`pygame constants`
This module contains various constants used by pygame. Its contents are
automatically placed in the pygame module namespace. However, an application
can use ``pygame.locals`` to include only the pygame constants with a ``from
pygame.locals import *``.
Detailed descriptions of the various constants can be found throughout the
pygame documentation. Here are the locations of some of them.
- The :mod:`pygame.display` module contains flags like ``FULLSCREEN`` used
by :func:`pygame.display.set_mode`.
- The :mod:`pygame.event` module contains the various event types.
- The :mod:`pygame.key` module lists the keyboard constants and modifiers
(``K_``\* and ``MOD_``\*) relating to the ``key`` and ``mod`` attributes of
the ``KEYDOWN`` and ``KEYUP`` events.
- The :mod:`pygame.time` module defines ``TIMER_RESOLUTION``.
.. ## pygame.locals ##

View file

@ -0,0 +1,642 @@
.. include:: common.txt
:mod:`pygame.mask`
==================
.. module:: pygame.mask
:synopsis: pygame module for image masks.
| :sl:`pygame module for image masks.`
Useful for fast pixel perfect collision detection. A mask uses 1 bit per-pixel
to store which parts collide.
.. versionadded:: 1.8
.. versionchanged:: 2.0.2 Mask functions now support keyword arguments.
.. versionchanged:: 2.0.2 Mask functions that take positions or offsets now
support :class:`pygame.math.Vector2` arguments.
.. function:: from_surface
| :sl:`Creates a Mask from the given surface`
| :sg:`from_surface(surface) -> Mask`
| :sg:`from_surface(surface, threshold=127) -> Mask`
Creates a :class:`Mask` object from the given surface by setting all the
opaque pixels and not setting the transparent pixels.
If the surface uses a color-key, then it is used to decide which bits in
the resulting mask are set. All the pixels that are **not** equal to the
color-key are **set** and the pixels equal to the color-key are not set.
If a color-key is not used, then the alpha value of each pixel is used to
decide which bits in the resulting mask are set. All the pixels that have an
alpha value **greater than** the ``threshold`` parameter are **set** and the
pixels with an alpha value less than or equal to the ``threshold`` are
not set.
:param Surface surface: the surface to create the mask from
:param int threshold: (optional) the alpha threshold (default is 127) to
compare with each surface pixel's alpha value, if the ``surface`` is
color-keyed this parameter is ignored
:returns: a newly created :class:`Mask` object from the given surface
:rtype: Mask
.. note::
This function is used to create the masks for
:func:`pygame.sprite.collide_mask`.
.. ## pygame.mask.from_surface ##
.. function:: from_threshold
| :sl:`Creates a mask by thresholding Surfaces`
| :sg:`from_threshold(surface, color) -> Mask`
| :sg:`from_threshold(surface, color, threshold=(0, 0, 0, 255), othersurface=None, palette_colors=1) -> Mask`
This is a more featureful method of getting a :class:`Mask` from a surface.
If the optional ``othersurface`` is not used, all the pixels **within** the
``threshold`` of the ``color`` parameter are **set** in the resulting mask.
If the optional ``othersurface`` is used, every pixel in the first surface
that is **within** the ``threshold`` of the corresponding pixel in
``othersurface`` is **set** in the resulting mask.
:param Surface surface: the surface to create the mask from
:param color: color used to check if the surface's pixels are within the
given ``threshold`` range, this parameter is ignored if the optional
``othersurface`` parameter is supplied
:type color: Color or int or tuple(int, int, int, [int]) or list[int, int, int, [int]]
:param threshold: (optional) the threshold range used to check the difference
between two colors (default is ``(0, 0, 0, 255)``)
:type threshold: Color or int or tuple(int, int, int, [int]) or list[int, int, int, [int]]
:param Surface othersurface: (optional) used to check whether the pixels of
the first surface are within the given ``threshold`` range of the pixels
from this surface (default is ``None``)
:param int palette_colors: (optional) indicates whether to use the palette
colors or not, a nonzero value causes the palette colors to be used and a
0 causes them not to be used (default is 1)
:returns: a newly created :class:`Mask` object from the given surface
:rtype: Mask
.. ## pygame.mask.from_threshold ##
.. class:: Mask
| :sl:`pygame object for representing 2D bitmasks`
| :sg:`Mask(size=(width, height)) -> Mask`
| :sg:`Mask(size=(width, height), fill=False) -> Mask`
A ``Mask`` object is used to represent a 2D bitmask. Each bit in
the mask represents a pixel. 1 is used to indicate a set bit and 0 is used
to indicate an unset bit. Set bits in a mask can be used to detect collisions
with other masks and their set bits.
A filled mask has all of its bits set to 1, conversely an
unfilled/cleared/empty mask has all of its bits set to 0. Masks can be
created unfilled (default) or filled by using the ``fill`` parameter. Masks
can also be cleared or filled using the :func:`pygame.mask.Mask.clear()` and
:func:`pygame.mask.Mask.fill()` methods respectively.
A mask's coordinates start in the top left corner at ``(0, 0)`` just like
:mod:`pygame.Surface`. Individual bits can be accessed using the
:func:`pygame.mask.Mask.get_at()` and :func:`pygame.mask.Mask.set_at()`
methods.
.. _mask-offset-label:
The methods :meth:`overlap`, :meth:`overlap_area`, :meth:`overlap_mask`,
:meth:`draw`, :meth:`erase`, and :meth:`convolve` use an offset parameter
to indicate the offset of another mask's top left corner from the calling
mask's top left corner. The calling mask's top left corner is considered to
be the origin ``(0, 0)``. Offsets are a sequence of two values
``(x_offset, y_offset)``. Positive and negative offset values are supported.
::
0 to x (x_offset)
: :
0 ..... +----:---------+
to | : |
y .......... +-----------+
(y_offset) | | othermask |
| +-----------+
| calling_mask |
+--------------+
:param size: the dimensions of the mask (width and height)
:param bool fill: (optional) create an unfilled mask (default: ``False``) or
filled mask (``True``)
:returns: a newly created :class:`Mask` object
:rtype: Mask
.. versionchanged:: 2.0.0
Shallow copy support added. The :class:`Mask` class supports the special
method ``__copy__()`` and shallow copying via ``copy.copy(mask)``.
.. versionchanged:: 2.0.0 Subclassing support added. The :class:`Mask` class
can be used as a base class.
.. versionchanged:: 1.9.5 Added support for keyword arguments.
.. versionchanged:: 1.9.5 Added the optional keyword parameter ``fill``.
.. versionchanged:: 1.9.5 Added support for masks with a width and/or a
height of 0.
.. method:: copy
| :sl:`Returns a new copy of the mask`
| :sg:`copy() -> Mask`
:returns: a new copy of this mask, the new mask will have the same width,
height, and set/unset bits as the original
:rtype: Mask
.. note::
If a mask subclass needs to copy any instance specific attributes
then it should override the ``__copy__()`` method. The overridden
``__copy__()`` method needs to call ``super().__copy__()`` and then
copy the required data as in the following example code.
::
class SubMask(pygame.mask.Mask):
def __copy__(self):
new_mask = super().__copy__()
# Do any SubMask attribute copying here.
return new_mask
.. versionadded:: 2.0.0
.. ## Mask.copy ##
.. method:: get_size
| :sl:`Returns the size of the mask`
| :sg:`get_size() -> (width, height)`
:returns: the size of the mask, (width, height)
:rtype: tuple(int, int)
.. ## Mask.get_size ##
.. method:: get_rect
| :sl:`Returns a Rect based on the size of the mask`
| :sg:`get_rect(\**kwargs) -> Rect`
Returns a new :func:`pygame.Rect` object based on the size of this mask.
The rect's default position will be ``(0, 0)`` and its default width and
height will be the same as this mask's. The rect's attributes can be
altered via :func:`pygame.Rect` attribute keyword arguments/values passed
into this method. As an example, ``a_mask.get_rect(center=(10, 5))`` would
create a :func:`pygame.Rect` based on the mask's size centered at the
given position.
:param dict kwargs: :func:`pygame.Rect` attribute keyword arguments/values
that will be applied to the rect
:returns: a new :func:`pygame.Rect` object based on the size of this mask
with any :func:`pygame.Rect` attribute keyword arguments/values applied
to it
:rtype: Rect
.. versionadded:: 2.0.0
.. ## Mask.get_rect ##
.. method:: get_at
| :sl:`Gets the bit at the given position`
| :sg:`get_at(pos) -> int`
:param pos: the position of the bit to get (x, y)
:returns: 1 if the bit is set, 0 if the bit is not set
:rtype: int
:raises IndexError: if the position is outside of the mask's bounds
.. ## Mask.get_at ##
.. method:: set_at
| :sl:`Sets the bit at the given position`
| :sg:`set_at(pos) -> None`
| :sg:`set_at(pos, value=1) -> None`
:param pos: the position of the bit to set (x, y)
:param int value: any nonzero int will set the bit to 1, 0 will set the
bit to 0 (default is 1)
:returns: ``None``
:rtype: NoneType
:raises IndexError: if the position is outside of the mask's bounds
.. ## Mask.set_at ##
.. method:: overlap
| :sl:`Returns the point of intersection`
| :sg:`overlap(other, offset) -> (x, y)`
| :sg:`overlap(other, offset) -> None`
Returns the first point of intersection encountered between this mask and
``other``. A point of intersection is 2 overlapping set bits.
The current algorithm searches the overlapping area in
``sizeof(unsigned long int) * CHAR_BIT`` bit wide column blocks (the value
of ``sizeof(unsigned long int) * CHAR_BIT`` is platform dependent, for
clarity it will be referred to as ``W``). Starting at the top left corner
it checks bits 0 to ``W - 1`` of the first row (``(0, 0)`` to
``(W - 1, 0)``) then continues to the next row (``(0, 1)`` to
``(W - 1, 1)``). Once this entire column block is checked, it continues to
the next one (``W`` to ``2 * W - 1``). This is repeated until it finds a
point of intersection or the entire overlapping area is checked.
:param Mask other: the other mask to overlap with this mask
:param offset: the offset of ``other`` from this mask, for more
details refer to the :ref:`Mask offset notes <mask-offset-label>`
:returns: point of intersection or ``None`` if no intersection
:rtype: tuple(int, int) or NoneType
.. ## Mask.overlap ##
.. method:: overlap_area
| :sl:`Returns the number of overlapping set bits`
| :sg:`overlap_area(other, offset) -> numbits`
Returns the number of overlapping set bits between between this mask and
``other``.
This can be useful for collision detection. An approximate collision
normal can be found by calculating the gradient of the overlapping area
through the finite difference.
::
dx = mask.overlap_area(other, (x + 1, y)) - mask.overlap_area(other, (x - 1, y))
dy = mask.overlap_area(other, (x, y + 1)) - mask.overlap_area(other, (x, y - 1))
:param Mask other: the other mask to overlap with this mask
:param offset: the offset of ``other`` from this mask, for more
details refer to the :ref:`Mask offset notes <mask-offset-label>`
:returns: the number of overlapping set bits
:rtype: int
.. ## Mask.overlap_area ##
.. method:: overlap_mask
| :sl:`Returns a mask of the overlapping set bits`
| :sg:`overlap_mask(other, offset) -> Mask`
Returns a :class:`Mask`, the same size as this mask, containing the
overlapping set bits between this mask and ``other``.
:param Mask other: the other mask to overlap with this mask
:param offset: the offset of ``other`` from this mask, for more
details refer to the :ref:`Mask offset notes <mask-offset-label>`
:returns: a newly created :class:`Mask` with the overlapping bits set
:rtype: Mask
.. ## Mask.overlap_mask ##
.. method:: fill
| :sl:`Sets all bits to 1`
| :sg:`fill() -> None`
Sets all bits in the mask to 1.
:returns: ``None``
:rtype: NoneType
.. ## Mask.fill ##
.. method:: clear
| :sl:`Sets all bits to 0`
| :sg:`clear() -> None`
Sets all bits in the mask to 0.
:returns: ``None``
:rtype: NoneType
.. ## Mask.clear ##
.. method:: invert
| :sl:`Flips all the bits`
| :sg:`invert() -> None`
Flips all of the bits in the mask. All the set bits are cleared to 0 and
all the unset bits are set to 1.
:returns: ``None``
:rtype: NoneType
.. ## Mask.invert ##
.. method:: scale
| :sl:`Resizes a mask`
| :sg:`scale((width, height)) -> Mask`
Creates a new :class:`Mask` of the requested size with its bits scaled
from this mask.
:param size: the width and height (size) of the mask to create
:returns: a new :class:`Mask` object with its bits scaled from this mask
:rtype: Mask
:raises ValueError: if ``width < 0`` or ``height < 0``
.. ## Mask.scale ##
.. method:: draw
| :sl:`Draws a mask onto another`
| :sg:`draw(other, offset) -> None`
Performs a bitwise OR, drawing ``othermask`` onto this mask.
:param Mask other: the mask to draw onto this mask
:param offset: the offset of ``other`` from this mask, for more
details refer to the :ref:`Mask offset notes <mask-offset-label>`
:returns: ``None``
:rtype: NoneType
.. ## Mask.draw ##
.. method:: erase
| :sl:`Erases a mask from another`
| :sg:`erase(other, offset) -> None`
Erases (clears) all bits set in ``other`` from this mask.
:param Mask other: the mask to erase from this mask
:param offset: the offset of ``other`` from this mask, for more
details refer to the :ref:`Mask offset notes <mask-offset-label>`
:returns: ``None``
:rtype: NoneType
.. ## Mask.erase ##
.. method:: count
| :sl:`Returns the number of set bits`
| :sg:`count() -> bits`
:returns: the number of set bits in the mask
:rtype: int
.. ## Mask.count ##
.. method:: centroid
| :sl:`Returns the centroid of the set bits`
| :sg:`centroid() -> (x, y)`
Finds the centroid (the center mass of the set bits) for this mask.
:returns: a coordinate tuple indicating the centroid of the mask, it will
return ``(0, 0)`` if the mask has no bits set
:rtype: tuple(int, int)
.. ## Mask.centroid ##
.. method:: angle
| :sl:`Returns the orientation of the set bits`
| :sg:`angle() -> theta`
Finds the approximate orientation (from -90 to 90 degrees) of the set bits
in the mask. This works best if performed on a mask with only one
connected component.
:returns: the orientation of the set bits in the mask, it will return
``0.0`` if the mask has no bits set
:rtype: float
.. note::
See :meth:`connected_component` for details on how a connected
component is calculated.
.. ## Mask.angle ##
.. method:: outline
| :sl:`Returns a list of points outlining an object`
| :sg:`outline() -> [(x, y), ...]`
| :sg:`outline(every=1) -> [(x, y), ...]`
Returns a list of points of the outline of the first connected component
encountered in the mask. To find a connected component, the mask is
searched per row (left to right) starting in the top left corner.
The ``every`` optional parameter skips set bits in the outline. For
example, setting it to 10 would return a list of every 10th set bit in the
outline.
:param int every: (optional) indicates the number of bits to skip over in
the outline (default is 1)
:returns: a list of points outlining the first connected component
encountered, an empty list is returned if the mask has no bits set
:rtype: list[tuple(int, int)]
.. note::
See :meth:`connected_component` for details on how a connected
component is calculated.
.. ## Mask.outline ##
.. method:: convolve
| :sl:`Returns the convolution of this mask with another mask`
| :sg:`convolve(other) -> Mask`
| :sg:`convolve(other, output=None, offset=(0, 0)) -> Mask`
Convolve this mask with the given ``other`` Mask.
:param Mask other: mask to convolve this mask with
:param output: (optional) mask for output (default is ``None``)
:type output: Mask or NoneType
:param offset: the offset of ``other`` from this mask, (default is
``(0, 0)``)
:returns: a :class:`Mask` with the ``(i - offset[0], j - offset[1])`` bit
set, if shifting ``other`` (such that its bottom right corner is at
``(i, j)``) causes it to overlap with this mask
If an ``output`` Mask is specified, the output is drawn onto it and
it is returned. Otherwise a mask of size ``(MAX(0, width + other mask's
width - 1), MAX(0, height + other mask's height - 1))`` is created and
returned.
:rtype: Mask
.. ## Mask.convolve ##
.. method:: connected_component
| :sl:`Returns a mask containing a connected component`
| :sg:`connected_component() -> Mask`
| :sg:`connected_component(pos) -> Mask`
A connected component is a group (1 or more) of connected set bits
(orthogonally and diagonally). The SAUF algorithm, which checks 8 point
connectivity, is used to find a connected component in the mask.
By default this method will return a :class:`Mask` containing the largest
connected component in the mask. Optionally, a bit coordinate can be
specified and the connected component containing it will be returned. If
the bit at the given location is not set, the returned :class:`Mask` will
be empty (no bits set).
:param pos: (optional) selects the connected component that contains the
bit at this position
:returns: a :class:`Mask` object (same size as this mask) with the largest
connected component from this mask, if this mask has no bits set then
an empty mask will be returned
If the ``pos`` parameter is provided then the mask returned will have
the connected component that contains this position. An empty mask will
be returned if the ``pos`` parameter selects an unset bit.
:rtype: Mask
:raises IndexError: if the optional ``pos`` parameter is outside of the
mask's bounds
.. ## Mask.connected_component ##
.. method:: connected_components
| :sl:`Returns a list of masks of connected components`
| :sg:`connected_components() -> [Mask, ...]`
| :sg:`connected_components(minimum=0) -> [Mask, ...]`
Provides a list containing a :class:`Mask` object for each connected
component.
:param int minimum: (optional) indicates the minimum number of bits (to
filter out noise) per connected component (default is 0, which equates
to no minimum and is equivalent to setting it to 1, as a connected
component must have at least 1 bit set)
:returns: a list containing a :class:`Mask` object for each connected
component, an empty list is returned if the mask has no bits set
:rtype: list[Mask]
.. note::
See :meth:`connected_component` for details on how a connected
component is calculated.
.. ## Mask.connected_components ##
.. method:: get_bounding_rects
| :sl:`Returns a list of bounding rects of connected components`
| :sg:`get_bounding_rects() -> [Rect, ...]`
Provides a list containing a bounding rect for each connected component.
:returns: a list containing a bounding rect for each connected component,
an empty list is returned if the mask has no bits set
:rtype: list[Rect]
.. note::
See :meth:`connected_component` for details on how a connected
component is calculated.
.. ## Mask.get_bounding_rects ##
.. method:: to_surface
| :sl:`Returns a surface with the mask drawn on it`
| :sg:`to_surface() -> Surface`
| :sg:`to_surface(surface=None, setsurface=None, unsetsurface=None, setcolor=(255, 255, 255, 255), unsetcolor=(0, 0, 0, 255), dest=(0, 0)) -> Surface`
Draws this mask on the given surface. Set bits (bits set to 1) and unset
bits (bits set to 0) can be drawn onto a surface.
:param surface: (optional) Surface to draw mask onto, if no surface is
provided one will be created (default is ``None``, which will cause a
surface with the parameters
``Surface(size=mask.get_size(), flags=SRCALPHA, depth=32)`` to be
created, drawn on, and returned)
:type surface: Surface or None
:param setsurface: (optional) use this surface's color values to draw
set bits (default is ``None``), if this surface is smaller than the
mask any bits outside its bounds will use the ``setcolor`` value
:type setsurface: Surface or None
:param unsetsurface: (optional) use this surface's color values to draw
unset bits (default is ``None``), if this surface is smaller than the
mask any bits outside its bounds will use the ``unsetcolor`` value
:type unsetsurface: Surface or None
:param setcolor: (optional) color to draw set bits (default is
``(255, 255, 255, 255)``, white), use ``None`` to skip drawing the set
bits, the ``setsurface`` parameter (if set) will takes precedence over
this parameter
:type setcolor: Color or str or int or tuple(int, int, int, [int]) or
list(int, int, int, [int]) or None
:param unsetcolor: (optional) color to draw unset bits (default is
``(0, 0, 0, 255)``, black), use ``None`` to skip drawing the unset
bits, the ``unsetsurface`` parameter (if set) will takes precedence
over this parameter
:type unsetcolor: Color or str or int or tuple(int, int, int, [int]) or
list(int, int, int, [int]) or None
:param dest: (optional) surface destination of where to position the
topleft corner of the mask being drawn (default is ``(0, 0)``), if a
Rect is used as the ``dest`` parameter, its ``x`` and ``y`` attributes
will be used as the destination, **NOTE1:** rects with a negative width
or height value will not be normalized before using their ``x`` and
``y`` values, **NOTE2:** this destination value is only used to
position the mask on the surface, it does not offset the ``setsurface``
and ``unsetsurface`` from the mask, they are always aligned with the
mask (i.e. position ``(0, 0)`` on the mask always corresponds to
position ``(0, 0)`` on the ``setsurface`` and ``unsetsurface``)
:type dest: Rect or tuple(int, int) or list(int, int) or Vector2(int, int)
:returns: the ``surface`` parameter (or a newly created surface if no
``surface`` parameter was provided) with this mask drawn on it
:rtype: Surface
:raises ValueError: if the ``setsurface`` parameter or ``unsetsurface``
parameter does not have the same format (bytesize/bitsize/alpha) as
the ``surface`` parameter
.. note ::
To skip drawing the set bits, both ``setsurface`` and ``setcolor`` must
be ``None``. The ``setsurface`` parameter defaults to ``None``, but
``setcolor`` defaults to a color value and therefore must be set to
``None``.
.. note ::
To skip drawing the unset bits, both ``unsetsurface`` and
``unsetcolor`` must be ``None``. The ``unsetsurface`` parameter
defaults to ``None``, but ``unsetcolor`` defaults to a color value and
therefore must be set to ``None``.
.. versionadded:: 2.0.0
.. ## Mask.to_surface ##
.. ## pygame.mask.Mask ##
.. ## pygame.mask ##

View file

@ -0,0 +1,880 @@
.. include:: common.txt
:mod:`pygame.math`
==================
.. module:: pygame.math
:synopsis: pygame module for vector classes
| :sl:`pygame module for vector classes`
The pygame math module currently provides Vector classes in two and three
dimensions, ``Vector2`` and ``Vector3`` respectively.
They support the following numerical operations: ``vec+vec``, ``vec-vec``,
``vec*number``, ``number*vec``, ``vec/number``, ``vec//number``, ``vec+=vec``,
``vec-=vec``, ``vec*=number``, ``vec/=number``, ``vec//=number``.
All these operations will be performed elementwise.
In addition ``vec*vec`` will perform a scalar-product (a.k.a. dot-product).
If you want to multiply every element from vector v with every element from
vector w you can use the elementwise method: ``v.elementwise() * w``
The coordinates of a vector can be retrieved or set using attributes or
subscripts
::
v = pygame.Vector3()
v.x = 5
v[1] = 2 * v.x
print(v[1]) # 10
v.x == v[0]
v.y == v[1]
v.z == v[2]
Multiple coordinates can be set using slices or swizzling
::
v = pygame.Vector2()
v.xy = 1, 2
v[:] = 1, 2
.. versionadded:: 1.9.2pre
.. versionchanged:: 1.9.4 Removed experimental notice.
.. versionchanged:: 1.9.4 Allow scalar construction like GLSL Vector2(2) == Vector2(2.0, 2.0)
.. versionchanged:: 1.9.4 :mod:`pygame.math` required import. More convenient ``pygame.Vector2`` and ``pygame.Vector3``.
.. class:: Vector2
| :sl:`a 2-Dimensional Vector`
| :sg:`Vector2() -> Vector2`
| :sg:`Vector2(int) -> Vector2`
| :sg:`Vector2(float) -> Vector2`
| :sg:`Vector2(Vector2) -> Vector2`
| :sg:`Vector2(x, y) -> Vector2`
| :sg:`Vector2((x, y)) -> Vector2`
Some general information about the ``Vector2`` class.
.. method:: dot
| :sl:`calculates the dot- or scalar-product with the other vector`
| :sg:`dot(Vector2) -> float`
.. ## Vector2.dot ##
.. method:: cross
| :sl:`calculates the cross- or vector-product`
| :sg:`cross(Vector2) -> Vector2`
calculates the third component of the cross-product.
.. ## Vector2.cross ##
.. method:: magnitude
| :sl:`returns the Euclidean magnitude of the vector.`
| :sg:`magnitude() -> float`
calculates the magnitude of the vector which follows from the
theorem: ``vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2)``
.. ## Vector2.magnitude ##
.. method:: magnitude_squared
| :sl:`returns the squared magnitude of the vector.`
| :sg:`magnitude_squared() -> float`
calculates the magnitude of the vector which follows from the
theorem: ``vec.magnitude_squared() == vec.x**2 + vec.y**2``. This
is faster than ``vec.magnitude()`` because it avoids the square root.
.. ## Vector2.magnitude_squared ##
.. method:: length
| :sl:`returns the Euclidean length of the vector.`
| :sg:`length() -> float`
calculates the Euclidean length of the vector which follows from the
Pythagorean theorem: ``vec.length() == math.sqrt(vec.x**2 + vec.y**2)``
.. ## Vector2.length ##
.. method:: length_squared
| :sl:`returns the squared Euclidean length of the vector.`
| :sg:`length_squared() -> float`
calculates the Euclidean length of the vector which follows from the
Pythagorean theorem: ``vec.length_squared() == vec.x**2 + vec.y**2``.
This is faster than ``vec.length()`` because it avoids the square root.
.. ## Vector2.length_squared ##
.. method:: normalize
| :sl:`returns a vector with the same direction but length 1.`
| :sg:`normalize() -> Vector2`
Returns a new vector that has ``length`` equal to ``1`` and the same
direction as self.
.. ## Vector2.normalize ##
.. method:: normalize_ip
| :sl:`normalizes the vector in place so that its length is 1.`
| :sg:`normalize_ip() -> None`
Normalizes the vector so that it has ``length`` equal to ``1``.
The direction of the vector is not changed.
.. ## Vector2.normalize_ip ##
.. method:: is_normalized
| :sl:`tests if the vector is normalized i.e. has length == 1.`
| :sg:`is_normalized() -> Bool`
Returns True if the vector has ``length`` equal to ``1``. Otherwise
it returns ``False``.
.. ## Vector2.is_normalized ##
.. method:: scale_to_length
| :sl:`scales the vector to a given length.`
| :sg:`scale_to_length(float) -> None`
Scales the vector so that it has the given length. The direction of the
vector is not changed. You can also scale to length ``0``. If the vector
is the zero vector (i.e. has length ``0`` thus no direction) a
``ValueError`` is raised.
.. ## Vector2.scale_to_length ##
.. method:: reflect
| :sl:`returns a vector reflected of a given normal.`
| :sg:`reflect(Vector2) -> Vector2`
Returns a new vector that points in the direction as if self would bounce
of a surface characterized by the given surface normal. The length of the
new vector is the same as self's.
.. ## Vector2.reflect ##
.. method:: reflect_ip
| :sl:`reflect the vector of a given normal in place.`
| :sg:`reflect_ip(Vector2) -> None`
Changes the direction of self as if it would have been reflected of a
surface with the given surface normal.
.. ## Vector2.reflect_ip ##
.. method:: distance_to
| :sl:`calculates the Euclidean distance to a given vector.`
| :sg:`distance_to(Vector2) -> float`
.. ## Vector2.distance_to ##
.. method:: distance_squared_to
| :sl:`calculates the squared Euclidean distance to a given vector.`
| :sg:`distance_squared_to(Vector2) -> float`
.. ## Vector2.distance_squared_to ##
.. method:: lerp
| :sl:`returns a linear interpolation to the given vector.`
| :sg:`lerp(Vector2, float) -> Vector2`
Returns a Vector which is a linear interpolation between self and the
given Vector. The second parameter determines how far between self and
other the result is going to be. It must be a value between ``0`` and ``1``
where ``0`` means self and ``1`` means other will be returned.
.. ## Vector2.lerp ##
.. method:: slerp
| :sl:`returns a spherical interpolation to the given vector.`
| :sg:`slerp(Vector2, float) -> Vector2`
Calculates the spherical interpolation from self to the given Vector. The
second argument - often called t - must be in the range ``[-1, 1]``. It
parametrizes where - in between the two vectors - the result should be.
If a negative value is given the interpolation will not take the
complement of the shortest path.
.. ## Vector2.slerp ##
.. method:: elementwise
| :sl:`The next operation will be performed elementwise.`
| :sg:`elementwise() -> VectorElementwiseProxy`
Applies the following operation to each element of the vector.
.. ## Vector2.elementwise ##
.. method:: rotate
| :sl:`rotates a vector by a given angle in degrees.`
| :sg:`rotate(angle) -> Vector2`
Returns a vector which has the same length as self but is rotated
counterclockwise by the given angle in degrees.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector2.rotate ##
.. method:: rotate_rad
| :sl:`rotates a vector by a given angle in radians.`
| :sg:`rotate_rad(angle) -> Vector2`
Returns a vector which has the same length as self but is rotated
counterclockwise by the given angle in radians.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.0.0
.. ## Vector2.rotate_rad ##
.. method:: rotate_ip
| :sl:`rotates the vector by a given angle in degrees in place.`
| :sg:`rotate_ip(angle) -> None`
Rotates the vector counterclockwise by the given angle in degrees. The
length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector2.rotate_ip ##
.. method:: rotate_ip_rad
| :sl:`rotates the vector by a given angle in radians in place.`
| :sg:`rotate_ip_rad(angle) -> None`
DEPRECATED: Use rotate_rad_ip() instead.
.. versionadded:: 2.0.0
.. deprecated:: 2.1.1
.. ## Vector2.rotate_rad_ip ##
.. method:: rotate_rad_ip
| :sl:`rotates the vector by a given angle in radians in place.`
| :sg:`rotate_rad_ip(angle) -> None`
Rotates the vector counterclockwise by the given angle in radians. The
length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.1.1
.. ## Vector2.rotate_rad_ip ##
.. method:: angle_to
| :sl:`calculates the angle to a given vector in degrees.`
| :sg:`angle_to(Vector2) -> float`
Returns the angle between self and the given vector.
.. ## Vector2.angle_to ##
.. method:: as_polar
| :sl:`returns a tuple with radial distance and azimuthal angle.`
| :sg:`as_polar() -> (r, phi)`
Returns a tuple ``(r, phi)`` where r is the radial distance, and phi
is the azimuthal angle.
.. ## Vector2.as_polar ##
.. method:: from_polar
| :sl:`Sets x and y from a polar coordinates tuple.`
| :sg:`from_polar((r, phi)) -> None`
Sets x and y from a tuple (r, phi) where r is the radial distance, and
phi is the azimuthal angle.
.. ## Vector2.from_polar ##
.. method:: project
| :sl:`projects a vector onto another.`
| :sg:`project(Vector2) -> Vector2`
Returns the projected vector. This is useful for collision detection in finding the components in a certain direction (e.g. in direction of the wall).
For a more detailed explanation see `Wikipedia <https://en.wikipedia.org/wiki/Vector_projection>`_.
.. versionadded:: 2.0.2
.. ## Vector2.project ##
.. method :: copy
| :sl:`Returns a copy of itself.`
| :sg:`copy() -> Vector2`
Returns a new Vector2 having the same dimensions.
.. versionadded:: 2.1.1
.. ## Vector2.copy ##
.. method:: update
| :sl:`Sets the coordinates of the vector.`
| :sg:`update() -> None`
| :sg:`update(int) -> None`
| :sg:`update(float) -> None`
| :sg:`update(Vector2) -> None`
| :sg:`update(x, y) -> None`
| :sg:`update((x, y)) -> None`
Sets coordinates x and y in place.
.. versionadded:: 1.9.5
.. ## Vector2.update ##
.. ## pygame.math.Vector2 ##
.. class:: Vector3
| :sl:`a 3-Dimensional Vector`
| :sg:`Vector3() -> Vector3`
| :sg:`Vector3(int) -> Vector3`
| :sg:`Vector3(float) -> Vector3`
| :sg:`Vector3(Vector3) -> Vector3`
| :sg:`Vector3(x, y, z) -> Vector3`
| :sg:`Vector3((x, y, z)) -> Vector3`
Some general information about the Vector3 class.
.. method:: dot
| :sl:`calculates the dot- or scalar-product with the other vector`
| :sg:`dot(Vector3) -> float`
.. ## Vector3.dot ##
.. method:: cross
| :sl:`calculates the cross- or vector-product`
| :sg:`cross(Vector3) -> Vector3`
calculates the cross-product.
.. ## Vector3.cross ##
.. method:: magnitude
| :sl:`returns the Euclidean magnitude of the vector.`
| :sg:`magnitude() -> float`
calculates the magnitude of the vector which follows from the
theorem: ``vec.magnitude() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)``
.. ## Vector3.magnitude ##
.. method:: magnitude_squared
| :sl:`returns the squared Euclidean magnitude of the vector.`
| :sg:`magnitude_squared() -> float`
calculates the magnitude of the vector which follows from the
theorem:
``vec.magnitude_squared() == vec.x**2 + vec.y**2 + vec.z**2``.
This is faster than ``vec.magnitude()`` because it avoids the
square root.
.. ## Vector3.magnitude_squared ##
.. method:: length
| :sl:`returns the Euclidean length of the vector.`
| :sg:`length() -> float`
calculates the Euclidean length of the vector which follows from the
Pythagorean theorem:
``vec.length() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)``
.. ## Vector3.length ##
.. method:: length_squared
| :sl:`returns the squared Euclidean length of the vector.`
| :sg:`length_squared() -> float`
calculates the Euclidean length of the vector which follows from the
Pythagorean theorem:
``vec.length_squared() == vec.x**2 + vec.y**2 + vec.z**2``.
This is faster than ``vec.length()`` because it avoids the square root.
.. ## Vector3.length_squared ##
.. method:: normalize
| :sl:`returns a vector with the same direction but length 1.`
| :sg:`normalize() -> Vector3`
Returns a new vector that has ``length`` equal to ``1`` and the same
direction as self.
.. ## Vector3.normalize ##
.. method:: normalize_ip
| :sl:`normalizes the vector in place so that its length is 1.`
| :sg:`normalize_ip() -> None`
Normalizes the vector so that it has ``length`` equal to ``1``. The
direction of the vector is not changed.
.. ## Vector3.normalize_ip ##
.. method:: is_normalized
| :sl:`tests if the vector is normalized i.e. has length == 1.`
| :sg:`is_normalized() -> Bool`
Returns True if the vector has ``length`` equal to ``1``. Otherwise it
returns ``False``.
.. ## Vector3.is_normalized ##
.. method:: scale_to_length
| :sl:`scales the vector to a given length.`
| :sg:`scale_to_length(float) -> None`
Scales the vector so that it has the given length. The direction of the
vector is not changed. You can also scale to length ``0``. If the vector
is the zero vector (i.e. has length ``0`` thus no direction) a
``ValueError`` is raised.
.. ## Vector3.scale_to_length ##
.. method:: reflect
| :sl:`returns a vector reflected of a given normal.`
| :sg:`reflect(Vector3) -> Vector3`
Returns a new vector that points in the direction as if self would bounce
of a surface characterized by the given surface normal. The length of the
new vector is the same as self's.
.. ## Vector3.reflect ##
.. method:: reflect_ip
| :sl:`reflect the vector of a given normal in place.`
| :sg:`reflect_ip(Vector3) -> None`
Changes the direction of self as if it would have been reflected of a
surface with the given surface normal.
.. ## Vector3.reflect_ip ##
.. method:: distance_to
| :sl:`calculates the Euclidean distance to a given vector.`
| :sg:`distance_to(Vector3) -> float`
.. ## Vector3.distance_to ##
.. method:: distance_squared_to
| :sl:`calculates the squared Euclidean distance to a given vector.`
| :sg:`distance_squared_to(Vector3) -> float`
.. ## Vector3.distance_squared_to ##
.. method:: lerp
| :sl:`returns a linear interpolation to the given vector.`
| :sg:`lerp(Vector3, float) -> Vector3`
Returns a Vector which is a linear interpolation between self and the
given Vector. The second parameter determines how far between self an
other the result is going to be. It must be a value between ``0`` and
``1``, where ``0`` means self and ``1`` means other will be returned.
.. ## Vector3.lerp ##
.. method:: slerp
| :sl:`returns a spherical interpolation to the given vector.`
| :sg:`slerp(Vector3, float) -> Vector3`
Calculates the spherical interpolation from self to the given Vector. The
second argument - often called t - must be in the range ``[-1, 1]``. It
parametrizes where - in between the two vectors - the result should be.
If a negative value is given the interpolation will not take the
complement of the shortest path.
.. ## Vector3.slerp ##
.. method:: elementwise
| :sl:`The next operation will be performed elementwise.`
| :sg:`elementwise() -> VectorElementwiseProxy`
Applies the following operation to each element of the vector.
.. ## Vector3.elementwise ##
.. method:: rotate
| :sl:`rotates a vector by a given angle in degrees.`
| :sg:`rotate(angle, Vector3) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise by the given angle in degrees around the given axis.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate ##
.. method:: rotate_rad
| :sl:`rotates a vector by a given angle in radians.`
| :sg:`rotate_rad(angle, Vector3) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise by the given angle in radians around the given axis.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.0.0
.. ## Vector3.rotate_rad ##
.. method:: rotate_ip
| :sl:`rotates the vector by a given angle in degrees in place.`
| :sg:`rotate_ip(angle, Vector3) -> None`
Rotates the vector counterclockwise around the given axis by the given
angle in degrees. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate_ip ##
.. method:: rotate_ip_rad
| :sl:`rotates the vector by a given angle in radians in place.`
| :sg:`rotate_ip_rad(angle, Vector3) -> None`
DEPRECATED: Use rotate_rad_ip() instead.
.. versionadded:: 2.0.0
.. deprecated:: 2.1.1
.. ## Vector3.rotate_ip_rad ##
.. method:: rotate_rad_ip
| :sl:`rotates the vector by a given angle in radians in place.`
| :sg:`rotate_rad_ip(angle, Vector3) -> None`
Rotates the vector counterclockwise around the given axis by the given
angle in radians. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.1.1
.. ## Vector3.rotate_rad_ip ##
.. method:: rotate_x
| :sl:`rotates a vector around the x-axis by the angle in degrees.`
| :sg:`rotate_x(angle) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise around the x-axis by the given angle in degrees.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate_x ##
.. method:: rotate_x_rad
| :sl:`rotates a vector around the x-axis by the angle in radians.`
| :sg:`rotate_x_rad(angle) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise around the x-axis by the given angle in radians.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.0.0
.. ## Vector3.rotate_x_rad ##
.. method:: rotate_x_ip
| :sl:`rotates the vector around the x-axis by the angle in degrees in place.`
| :sg:`rotate_x_ip(angle) -> None`
Rotates the vector counterclockwise around the x-axis by the given angle
in degrees. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate_x_ip ##
.. method:: rotate_x_ip_rad
| :sl:`rotates the vector around the x-axis by the angle in radians in place.`
| :sg:`rotate_x_ip_rad(angle) -> None`
DEPRECATED: Use rotate_x_rad_ip() instead.
.. versionadded:: 2.0.0
.. deprecated:: 2.1.1
.. ## Vector3.rotate_x_ip_rad ##
.. method:: rotate_x_rad_ip
| :sl:`rotates the vector around the x-axis by the angle in radians in place.`
| :sg:`rotate_x_rad_ip(angle) -> None`
Rotates the vector counterclockwise around the x-axis by the given angle
in radians. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.1.1
.. ## Vector3.rotate_x_rad_ip ##
.. method:: rotate_y
| :sl:`rotates a vector around the y-axis by the angle in degrees.`
| :sg:`rotate_y(angle) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise around the y-axis by the given angle in degrees.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate_y ##
.. method:: rotate_y_rad
| :sl:`rotates a vector around the y-axis by the angle in radians.`
| :sg:`rotate_y_rad(angle) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise around the y-axis by the given angle in radians.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.0.0
.. ## Vector3.rotate_y_rad ##
.. method:: rotate_y_ip
| :sl:`rotates the vector around the y-axis by the angle in degrees in place.`
| :sg:`rotate_y_ip(angle) -> None`
Rotates the vector counterclockwise around the y-axis by the given angle
in degrees. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate_y_ip ##
.. method:: rotate_y_ip_rad
| :sl:`rotates the vector around the y-axis by the angle in radians in place.`
| :sg:`rotate_y_ip_rad(angle) -> None`
DEPRECATED: Use rotate_y_rad_ip() instead.
.. versionadded:: 2.0.0
.. deprecated:: 2.1.1
.. ## Vector3.rotate_y_ip_rad ##
.. method:: rotate_y_rad_ip
| :sl:`rotates the vector around the y-axis by the angle in radians in place.`
| :sg:`rotate_y_rad_ip(angle) -> None`
Rotates the vector counterclockwise around the y-axis by the given angle
in radians. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.1.1
.. ## Vector3.rotate_y_rad_ip ##
.. method:: rotate_z
| :sl:`rotates a vector around the z-axis by the angle in degrees.`
| :sg:`rotate_z(angle) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise around the z-axis by the given angle in degrees.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate_z ##
.. method:: rotate_z_rad
| :sl:`rotates a vector around the z-axis by the angle in radians.`
| :sg:`rotate_z_rad(angle) -> Vector3`
Returns a vector which has the same length as self but is rotated
counterclockwise around the z-axis by the given angle in radians.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.0.0
.. ## Vector3.rotate_z_rad ##
.. method:: rotate_z_ip
| :sl:`rotates the vector around the z-axis by the angle in degrees in place.`
| :sg:`rotate_z_ip(angle) -> None`
Rotates the vector counterclockwise around the z-axis by the given angle
in degrees. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. ## Vector3.rotate_z_ip ##
.. method:: rotate_z_ip_rad
| :sl:`rotates the vector around the z-axis by the angle in radians in place.`
| :sg:`rotate_z_ip_rad(angle) -> None`
DEPRECATED: Use rotate_z_rad_ip() instead.
.. deprecated:: 2.1.1
.. ## Vector3.rotate_z_ip_rad ##
.. method:: rotate_z_rad_ip
| :sl:`rotates the vector around the z-axis by the angle in radians in place.`
| :sg:`rotate_z_rad_ip(angle) -> None`
Rotates the vector counterclockwise around the z-axis by the given angle
in radians. The length of the vector is not changed.
(Note that due to pygame's inverted y coordinate system, the rotation
will look clockwise if displayed).
.. versionadded:: 2.1.1
.. ## Vector3.rotate_z_rad_ip ##
.. method:: angle_to
| :sl:`calculates the angle to a given vector in degrees.`
| :sg:`angle_to(Vector3) -> float`
Returns the angle between self and the given vector.
.. ## Vector3.angle_to ##
.. method:: as_spherical
| :sl:`returns a tuple with radial distance, inclination and azimuthal angle.`
| :sg:`as_spherical() -> (r, theta, phi)`
Returns a tuple ``(r, theta, phi)`` where r is the radial distance, theta is
the inclination angle and phi is the azimuthal angle.
.. ## Vector3.as_spherical ##
.. method:: from_spherical
| :sl:`Sets x, y and z from a spherical coordinates 3-tuple.`
| :sg:`from_spherical((r, theta, phi)) -> None`
Sets x, y and z from a tuple ``(r, theta, phi)`` where r is the radial
distance, theta is the inclination angle and phi is the azimuthal angle.
.. ## Vector3.from_spherical ##
.. method:: project
| :sl:`projects a vector onto another.`
| :sg:`project(Vector3) -> Vector3`
Returns the projected vector. This is useful for collision detection in finding the components in a certain direction (e.g. in direction of the wall).
For a more detailed explanation see `Wikipedia <https://en.wikipedia.org/wiki/Vector_projection>`_.
.. versionadded:: 2.0.2
.. ## Vector3.project ##
.. method :: copy
| :sl:`Returns a copy of itself.`
| :sg:`copy() -> Vector3`
Returns a new Vector3 having the same dimensions.
.. versionadded:: 2.1.1
.. ## Vector3.copy ##
.. method:: update
| :sl:`Sets the coordinates of the vector.`
| :sg:`update() -> None`
| :sg:`update(int) -> None`
| :sg:`update(float) -> None`
| :sg:`update(Vector3) -> None`
| :sg:`update(x, y, z) -> None`
| :sg:`update((x, y, z)) -> None`
Sets coordinates x, y, and z in place.
.. versionadded:: 1.9.5
.. ## Vector3.update ##
.. ## ##
.. ## pygame.math.Vector3 ##
.. ## pygame.math ##

View file

@ -0,0 +1,484 @@
.. include:: common.txt
:mod:`pygame.midi`
==================
.. module:: pygame.midi
:synopsis: pygame module for interacting with midi input and output.
| :sl:`pygame module for interacting with midi input and output.`
.. versionadded:: 1.9.0
The midi module can send output to midi devices and get input from midi
devices. It can also list midi devices on the system.
The midi module supports real and virtual midi devices.
It uses the portmidi library. Is portable to which ever platforms portmidi
supports (currently Windows, Mac OS X, and Linux).
This uses pyportmidi for now, but may use its own bindings at some point in the
future. The pyportmidi bindings are included with pygame.
|
.. versionadded:: 2.0.0
These are pygame events (:mod:`pygame.event`) reserved for midi use. The
``MIDIIN`` event is used by :func:`pygame.midi.midis2events` when converting
midi events to pygame events.
::
MIDIIN
MIDIOUT
|
.. function:: init
| :sl:`initialize the midi module`
| :sg:`init() -> None`
Initializes the :mod:`pygame.midi` module. Must be called before using the
:mod:`pygame.midi` module.
It is safe to call this more than once.
.. ## pygame.midi.init ##
.. function:: quit
| :sl:`uninitialize the midi module`
| :sg:`quit() -> None`
Uninitializes the :mod:`pygame.midi` module. If :func:`pygame.midi.init` was
called to initialize the :mod:`pygame.midi` module, then this function will
be called automatically when your program exits.
It is safe to call this function more than once.
.. ## pygame.midi.quit ##
.. function:: get_init
| :sl:`returns True if the midi module is currently initialized`
| :sg:`get_init() -> bool`
Gets the initialization state of the :mod:`pygame.midi` module.
:returns: ``True`` if the :mod:`pygame.midi` module is currently initialized.
:rtype: bool
.. versionadded:: 1.9.5
.. ## pygame.midi.get_init ##
.. class:: Input
| :sl:`Input is used to get midi input from midi devices.`
| :sg:`Input(device_id) -> None`
| :sg:`Input(device_id, buffer_size) -> None`
:param int device_id: midi device id
:param int buffer_size: (optional) the number of input events to be buffered
.. method:: close
| :sl:`closes a midi stream, flushing any pending buffers.`
| :sg:`close() -> None`
PortMidi attempts to close open streams when the application exits.
.. note:: This is particularly difficult under Windows.
.. ## Input.close ##
.. method:: poll
| :sl:`returns True if there's data, or False if not.`
| :sg:`poll() -> bool`
Used to indicate if any data exists.
:returns: ``True`` if there is data, ``False`` otherwise
:rtype: bool
:raises MidiException: on error
.. ## Input.poll ##
.. method:: read
| :sl:`reads num_events midi events from the buffer.`
| :sg:`read(num_events) -> midi_event_list`
Reads from the input buffer and gives back midi events.
:param int num_events: number of input events to read
:returns: the format for midi_event_list is
``[[[status, data1, data2, data3], timestamp], ...]``
:rtype: list
.. ## Input.read ##
.. ## pygame.midi.Input ##
.. class:: Output
| :sl:`Output is used to send midi to an output device`
| :sg:`Output(device_id) -> None`
| :sg:`Output(device_id, latency=0) -> None`
| :sg:`Output(device_id, buffer_size=256) -> None`
| :sg:`Output(device_id, latency, buffer_size) -> None`
The ``buffer_size`` specifies the number of output events to be buffered
waiting for output. In some cases (see below) PortMidi does not buffer
output at all and merely passes data to a lower-level API, in which case
buffersize is ignored.
``latency`` is the delay in milliseconds applied to timestamps to determine
when the output should actually occur. If ``latency`` is <<0, 0 is assumed.
If ``latency`` is zero, timestamps are ignored and all output is delivered
immediately. If ``latency`` is greater than zero, output is delayed until the
message timestamp plus the ``latency``. In some cases, PortMidi can obtain
better timing than your application by passing timestamps along to the
device driver or hardware. Latency may also help you to synchronize midi
data to audio data by matching midi latency to the audio buffer latency.
.. note::
Time is measured relative to the time source indicated by time_proc.
Timestamps are absolute, not relative delays or offsets.
.. method:: abort
| :sl:`terminates outgoing messages immediately`
| :sg:`abort() -> None`
The caller should immediately close the output port; this call may result
in transmission of a partial midi message. There is no abort for Midi
input because the user can simply ignore messages in the buffer and close
an input device at any time.
.. ## Output.abort ##
.. method:: close
| :sl:`closes a midi stream, flushing any pending buffers.`
| :sg:`close() -> None`
PortMidi attempts to close open streams when the application exits.
.. note:: This is particularly difficult under Windows.
.. ## Output.close ##
.. method:: note_off
| :sl:`turns a midi note off (note must be on)`
| :sg:`note_off(note, velocity=None, channel=0) -> None`
Turn a note off in the output stream. The note must already be on for
this to work correctly.
.. ## Output.note_off ##
.. method:: note_on
| :sl:`turns a midi note on (note must be off)`
| :sg:`note_on(note, velocity=None, channel=0) -> None`
Turn a note on in the output stream. The note must already be off for
this to work correctly.
.. ## Output.note_on ##
.. method:: set_instrument
| :sl:`select an instrument, with a value between 0 and 127`
| :sg:`set_instrument(instrument_id, channel=0) -> None`
Select an instrument.
.. ## Output.set_instrument ##
.. method:: pitch_bend
| :sl:`modify the pitch of a channel.`
| :sg:`set_instrument(value=0, channel=0) -> None`
Adjust the pitch of a channel. The value is a signed integer
from -8192 to +8191. For example, 0 means "no change", +4096 is
typically a semitone higher, and -8192 is 1 whole tone lower (though
the musical range corresponding to the pitch bend range can also be
changed in some synthesizers).
If no value is given, the pitch bend is returned to "no change".
.. versionadded:: 1.9.4
.. method:: write
| :sl:`writes a list of midi data to the Output`
| :sg:`write(data) -> None`
Writes series of MIDI information in the form of a list.
:param list data: data to write, the expected format is
``[[[status, data1=0, data2=0, ...], timestamp], ...]``
with the ``data#`` fields being optional
:raises IndexError: if more than 1024 elements in the data list
Example:
::
# Program change at time 20000 and 500ms later send note 65 with
# velocity 100.
write([[[0xc0, 0, 0], 20000], [[0x90, 60, 100], 20500]])
.. note::
- Timestamps will be ignored if latency = 0
- To get a note to play immediately, send MIDI info with timestamp
read from function Time
- Optional data fields: ``write([[[0xc0, 0, 0], 20000]])`` is
equivalent to ``write([[[0xc0], 20000]])``
.. ## Output.write ##
.. method:: write_short
| :sl:`writes up to 3 bytes of midi data to the Output`
| :sg:`write_short(status) -> None`
| :sg:`write_short(status, data1=0, data2=0) -> None`
Output MIDI information of 3 bytes or less. The ``data`` fields are
optional and assumed to be 0 if omitted.
Examples of status byte values:
::
0xc0 # program change
0x90 # note on
# etc.
Example:
::
# note 65 on with velocity 100
write_short(0x90, 65, 100)
.. ## Output.write_short ##
.. method:: write_sys_ex
| :sl:`writes a timestamped system-exclusive midi message.`
| :sg:`write_sys_ex(when, msg) -> None`
Writes a timestamped system-exclusive midi message.
:param msg: midi message
:type msg: list[int] or str
:param when: timestamp in milliseconds
Example:
::
midi_output.write_sys_ex(0, '\xF0\x7D\x10\x11\x12\x13\xF7')
# is equivalent to
midi_output.write_sys_ex(pygame.midi.time(),
[0xF0, 0x7D, 0x10, 0x11, 0x12, 0x13, 0xF7])
.. ## Output.write_sys_ex ##
.. ## pygame.midi.Output ##
.. function:: get_count
| :sl:`gets the number of devices.`
| :sg:`get_count() -> num_devices`
Device ids range from 0 to ``get_count() - 1``
.. ## pygame.midi.get_count ##
.. function:: get_default_input_id
| :sl:`gets default input device number`
| :sg:`get_default_input_id() -> default_id`
The following describes the usage details for this function and the
:func:`get_default_output_id` function.
Return the default device ID or ``-1`` if there are no devices. The result
can be passed to the :class:`Input`/:class:`Output` class.
On a PC the user can specify a default device by setting an environment
variable. To use device #1, for example:
::
set PM_RECOMMENDED_INPUT_DEVICE=1
or
set PM_RECOMMENDED_OUTPUT_DEVICE=1
The user should first determine the available device ID by using the
supplied application "testin" or "testout".
In general, the registry is a better place for this kind of info. With
USB devices that can come and go, using integers is not very reliable
for device identification. Under Windows, if ``PM_RECOMMENDED_INPUT_DEVICE``
(or ``PM_RECOMMENDED_OUTPUT_DEVICE``) is NOT found in the environment,
then the default device is obtained by looking for a string in the registry
under:
::
HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
or
HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
The number of the first device with a substring that matches the
string exactly is returned. For example, if the string in the registry is
"USB" and device 1 is named "In USB MidiSport 1x1", then that will be
the default input because it contains the string "USB".
In addition to the name, :func:`get_device_info()` returns "interf", which is
the interface name. The "interface" is the underlying software system or
API used by PortMidi to access devices. Supported interfaces:
::
MMSystem # the only Win32 interface currently supported
ALSA # the only Linux interface currently supported
CoreMIDI # the only Mac OS X interface currently supported
# DirectX - not implemented
# OSS - not implemented
To specify both the interface and the device name in the registry, separate
the two with a comma and a space. The string before the comma must be a
substring of the "interf" string and the string after the space must be a
substring of the "name" name string in order to match the device. e.g.:
::
MMSystem, In USB MidiSport 1x1
.. note::
In the current release, the default is simply the first device (the
input or output device with the lowest PmDeviceID).
.. ## pygame.midi.get_default_input_id ##
.. function:: get_default_output_id
| :sl:`gets default output device number`
| :sg:`get_default_output_id() -> default_id`
See :func:`get_default_input_id` for usage details.
.. ## pygame.midi.get_default_output_id ##
.. function:: get_device_info
| :sl:`returns information about a midi device`
| :sg:`get_device_info(an_id) -> (interf, name, input, output, opened)`
| :sg:`get_device_info(an_id) -> None`
Gets the device info for a given id.
:param int an_id: id of the midi device being queried
:returns: if the id is out of range ``None`` is returned, otherwise
a tuple of (interf, name, input, output, opened) is returned.
- interf: string describing the device interface (e.g. 'ALSA')
- name: string name of the device (e.g. 'Midi Through Port-0')
- input: 1 if the device is an input device, otherwise 0
- output: 1 if the device is an output device, otherwise 0
- opened: 1 if the device is opened, otherwise 0
:rtype: tuple or None
.. ## pygame.midi.get_device_info ##
.. function:: midis2events
| :sl:`converts midi events to pygame events`
| :sg:`midis2events(midi_events, device_id) -> [Event, ...]`
Takes a sequence of midi events and returns list of pygame events.
The ``midi_events`` data is expected to be a sequence of
``((status, data1, data2, data3), timestamp)`` midi events (all values
required).
:returns: a list of pygame events of event type ``MIDIIN``
:rtype: list
.. ## pygame.midi.midis2events ##
.. function:: time
| :sl:`returns the current time in ms of the PortMidi timer`
| :sg:`time() -> time`
The time is reset to 0 when the :mod:`pygame.midi` module is initialized.
.. ## pygame.midi.time ##
.. function:: frequency_to_midi
| :sl:`Converts a frequency into a MIDI note. Rounds to the closest midi note.`
| :sg:`frequency_to_midi(midi_note) -> midi_note`
example:
::
frequency_to_midi(27.5) == 21
.. versionadded:: 1.9.5
.. ## pygame.midi.frequency_to_midi ##
.. function:: midi_to_frequency
| :sl:`Converts a midi note to a frequency.`
| :sg:`midi_to_frequency(midi_note) -> frequency`
example:
::
midi_to_frequency(21) == 27.5
.. versionadded:: 1.9.5
.. ## pygame.midi.midi_to_frequency ##
.. function:: midi_to_ansi_note
| :sl:`Returns the Ansi Note name for a midi number.`
| :sg:`midi_to_ansi_note(midi_note) -> ansi_note`
example:
::
midi_to_ansi_note(21) == 'A0'
.. versionadded:: 1.9.5
.. ## pygame.midi.midi_to_ansi_note ##
.. exception:: MidiException
| :sl:`exception that pygame.midi functions and classes can raise`
| :sg:`MidiException(errno) -> None`
.. ## pygame.midi.MidiException ##
.. ## pygame.midi ##

Some files were not shown because too many files have changed in this diff Show more