This commit is contained in:
wittmannzl103469 committed 2026-11-05 15:08:42 +01:00
1 parent de41a02749
commit 9af09cebd3
764 files changed
+54218 -78859

No files matched your search

Whitespace-only changes.
@@ -1,148 +0,0 @@
from briefcase.bootstraps.base import BaseGuiBootstrap
class PygameCEGuiBootstrap(BaseGuiBootstrap):
display_name_annotation = "does not support iOS/Android/Web deployment"
def app_source(self):
return """\
import importlib.metadata
import os
import sys
import pygame
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
BGCOLOR = (255, 255, 255)
def main():
# Linux desktop environments use an app's .desktop file to integrate the app
# in to their application menus. The .desktop file of this app will include
# the StartupWMClass key, set to app's formal name. This helps associate the
# app's windows to its menu item.
#
# For association to work, any windows of the app must have WMCLASS property
# set to match the value set in app's desktop file. For pygame_ce, this is
# set using the SDL_VIDEO_X11_WMCLASS environment variable.
# Find the name of the module that was used to start the app
app_module = sys.modules["__main__"].__package__
# Retrieve the app's metadata
metadata = importlib.metadata.metadata(app_module)
os.environ["SDL_VIDEO_X11_WMCLASS"] = metadata["Formal-Name"]
pygame.init()
pygame.display.set_caption(metadata["Formal-Name"])
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
screen.fill(BGCOLOR)
pygame.display.flip()
pygame.quit()
"""
def pyproject_table_briefcase_app_extra_content(self):
return """
requires = [
"pygame-ce",
]
"""
def pyproject_table_macOS(self):
return """\
universal_build = true
requires = [
"std-nslog~=1.0.0",
]
"""
def pyproject_table_linux(self):
return """\
requires = [
]
"""
def pyproject_table_linux_system_debian(self):
return """\
system_requires = [
]
system_runtime_requires = [
]
"""
def pyproject_table_linux_system_rhel(self):
return """\
system_requires = [
]
system_runtime_requires = [
]
"""
def pyproject_table_linux_system_suse(self):
return """\
system_requires = [
]
system_runtime_requires = [
]
"""
def pyproject_table_linux_system_arch(self):
return """\
system_requires = [
]
system_runtime_requires = [
]
"""
def pyproject_table_linux_appimage(self):
return """\
manylinux = "manylinux_2_28"
system_requires = [
]
linuxdeploy_plugins = [
]
"""
def pyproject_table_linux_flatpak(self):
return """\
flatpak_runtime = "org.freedesktop.Platform"
flatpak_runtime_version = "23.08"
flatpak_sdk = "org.freedesktop.Sdk"
"""
def pyproject_table_windows(self):
return """\
requires = [
]
"""
def pyproject_table_iOS(self):
return """\
supported = false
"""
def pyproject_table_android(self):
return """\
supported = false
"""
def pyproject_table_web(self):
return """\
supported = false
"""
@@ -1,4 +1,4 @@
# pygame-ce - Python Game Library
# pygame - Python Game Library
# Copyright (C) 2000-2001 Pete Shinners
#
# This library is free software; you can redistribute it and/or
@@ -21,42 +21,24 @@
It is written on top of the excellent SDL library. This allows you
to create fully featured games and multimedia programs in the python
language. The package is highly portable, with games running on
Windows, macOS, OS X, BeOS, FreeBSD, IRIX, and Linux."""
Windows, MacOS, OS X, BeOS, FreeBSD, IRIX, and Linux."""
import os
import sys
import platform
import os
# Choose Windows display driver
if os.name == "nt":
pygame_dir = os.path.split(__file__)[0]
dll_parents = {pygame_dir}
try:
# For editable support, add some more folders where DLLs are available.
# This block only executes under an editable install. In a "normal"
# install, the json file will not be installed at the supplied path.
with open(
os.path.join(
os.path.dirname(pygame_dir), "buildconfig", "win_dll_dirs.json"
),
encoding="utf-8",
) as f:
import json
dll_parents.update(json.load(f))
del json
except (FileNotFoundError, ValueError):
pass
# pypy does not find the dlls, so we add package folder to PATH.
os.environ["PATH"] = os.environ["PATH"] + ";" + pygame_dir
d = "" # define variable here so that we can consistently delete it
for d in dll_parents:
# adding to PATH is the legacy way, os.add_dll_directory is the new
# and recommended method. For extra safety we do both
os.environ["PATH"] = os.environ["PATH"] + ";" + d
os.add_dll_directory(d)
# windows store python does not find the dlls, so we run this
if sys.version_info > (3, 8):
os.add_dll_directory(pygame_dir) # only available in 3.8+
# cleanup namespace
del pygame_dir, dll_parents, d
del pygame_dir
# when running under X11, always set the SDL window WM_CLASS to make the
# window managers correctly match the pygame window.
@@ -73,13 +55,9 @@ class MissingModule:
def __init__(self, name, urgent=0):
self.name = name
exc_type, exc_msg, _ = sys.exc_info()
if exc_type is not None:
self.info = str(exc_msg)
self.reason = f"{exc_type.__name__}: {self.info}"
else:
self.info = "<no info>"
self.reason = f"<no exception>: {self.info}"
exc_type, exc_msg = sys.exc_info()[:2]
self.info = str(exc_msg)
self.reason = f"{exc_type.__name__}: {self.info}"
self.urgent = urgent
if urgent:
self.warn()
@@ -106,31 +84,6 @@ class MissingModule:
print(message)
# This is a special loader for WebAssembly platform
# where pygame is in fact statically linked
# mixing single phase (C) and multiphase modules (cython)
if sys.platform in ("wasi", "emscripten"):
try:
import pygame.base as pygame_static
except ModuleNotFoundError:
pygame_static = None
if pygame_static:
pygame = sys.modules[__name__]
# cython modules use multiphase initialisation when not in builtin Inittab.
from pygame import _sdl2
import importlib.machinery
loader = importlib.machinery.FrozenImporter
spec = importlib.machinery.ModuleSpec("", loader)
pygame_static.import_cython(spec)
del loader, spec
del pygame_static
# we need to import like this, each at a time. the cleanest way to import
# our modules is with the import command (not the __import__ function)
# isort: skip_file
@@ -139,33 +92,31 @@ if sys.platform in ("wasi", "emscripten"):
from pygame.base import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
from pygame.constants import * # now has __all__ pylint: disable=wildcard-import; lgtm[py/polluting-import]
from pygame.version import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
from pygame.rect import Rect
from pygame.rwobject import encode_string, encode_file_path
import pygame.rect
Rect = pygame.rect.Rect
FRect = pygame.rect.FRect
import pygame.surflock
import pygame.color
Color = pygame.color.Color
import pygame.bufferproxy
BufferProxy = pygame.bufferproxy.BufferProxy
import pygame.math
Vector2 = pygame.math.Vector2
Vector3 = pygame.math.Vector3
from pygame.base import __version__
__version__ = ver
# next, the "standard" modules
# we still allow them to be missing for stripped down pygame distributions
if get_sdl_version() < (2, 0, 0):
# cdrom only available for SDL 1.2.X
try:
import pygame.cdrom
except (ImportError, OSError):
cdrom = MissingModule("cdrom", urgent=1)
try:
import pygame.display
except (ImportError, OSError):
@@ -178,7 +129,6 @@ except (ImportError, OSError):
try:
import pygame.event
from pygame.event import Event
except (ImportError, OSError):
event = MissingModule("event", urgent=1)
@@ -189,7 +139,6 @@ except (ImportError, OSError):
try:
import pygame.joystick
from pygame.joystick import Joystick
except (ImportError, OSError):
joystick = MissingModule("joystick", urgent=1)
@@ -213,6 +162,16 @@ except (ImportError, OSError):
_attribute_undefined("pygame.Cursor")
try:
import pygame.sprite
except (ImportError, OSError):
sprite = MissingModule("sprite", urgent=1)
try:
import pygame.threads
except (ImportError, OSError):
threads = MissingModule("threads", urgent=1)
try:
import pygame.pixelcopy
except (ImportError, OSError):
@@ -220,7 +179,6 @@ except (ImportError, OSError):
try:
import pygame.surflock
from pygame.surface import Surface, SurfaceType
except (ImportError, OSError):
@@ -229,13 +187,6 @@ except (ImportError, OSError):
SurfaceType = Surface
# sprite.py is using pygame.surface.Surface type
try:
import pygame.sprite
except (ImportError, OSError):
sprite = MissingModule("sprite", urgent=1)
try:
import pygame.mask
from pygame.mask import Mask
@@ -254,9 +205,16 @@ except (ImportError, OSError):
_attribute_undefined("pygame.PixelArray")
try:
from pygame.overlay import Overlay
except (ImportError, OSError):
def Overlay(format, size): # pylint: disable=unused-argument
_attribute_undefined("pygame.Overlay")
try:
import pygame.time
from pygame.time import Clock
except (ImportError, OSError):
time = MissingModule("time", urgent=1)
@@ -277,15 +235,13 @@ try:
import pygame.font
import pygame.sysfont
from pygame.font import Font
pygame.font.SysFont = pygame.sysfont.SysFont
pygame.font.get_fonts = pygame.sysfont.get_fonts
pygame.font.match_font = pygame.sysfont.match_font
except (ImportError, OSError):
font = MissingModule("font", urgent=0)
# try to load pygame.mixer_music before mixer, for py2app...
# try and load pygame.mixer_music before mixer, for py2app...
try:
import pygame.mixer_music
@@ -296,8 +252,6 @@ except (ImportError, OSError):
try:
import pygame.mixer
from pygame.mixer import Sound
from pygame.mixer import Channel
except (ImportError, OSError):
mixer = MissingModule("mixer", urgent=0)
@@ -306,86 +260,20 @@ try:
except (ImportError, OSError):
scrap = MissingModule("scrap", urgent=0)
# Two lazily imported modules to avoid loading numpy unnecessarily
from importlib.util import LazyLoader, find_spec, module_from_spec
def lazy_import(name):
"""Lazily import a pygame module.
See https://docs.python.org/3/library/importlib.html#implementing-lazy-imports
Only load the module upon its first attribute access.
Lazily imported modules are directly referenced in packager_imports function.
"""
fullname = "pygame." + name
spec = find_spec(fullname)
if spec is None or spec.loader is None:
return MissingModule(name, urgent=0)
loader = LazyLoader(spec.loader)
spec.loader = loader
module = module_from_spec(spec)
sys.modules[fullname] = module
loader.exec_module(module)
return module
# Check if numpy is available for surfarray and sndarray modules
numpy_missing = find_spec("numpy") is None
try:
if numpy_missing:
# Always fails here. Need the error message for MissingModule.reason
import numpy # pylint: disable=ungrouped-imports
# Check that module dependencies are not missing, or get error message
import pygame.pixelcopy # pylint: disable=ungrouped-imports
import pygame.surfarray
except (ImportError, OSError):
surfarray = MissingModule("surfarray", urgent=0)
else:
surfarray = lazy_import("surfarray")
try:
if numpy_missing:
# Always fails here. Need the error message for MissingModule.reason
import numpy # pylint: disable=ungrouped-imports
# Check that module dependencies are not missing, or get error message
import pygame.mixer # pylint: disable=ungrouped-imports
import pygame.sndarray
except (ImportError, OSError):
sndarray = MissingModule("sndarray", urgent=0)
else:
sndarray = lazy_import("sndarray")
del LazyLoader, find_spec, lazy_import, module_from_spec, numpy_missing
try:
import pygame._debug
from pygame._debug import print_debug_info
import pygame.fastevent
except (ImportError, OSError):
debug = MissingModule("_debug", urgent=0)
try:
import pygame.system
from pygame._data_classes import PowerState as power_state
power_state.__module__ = "pygame.system"
del power_state
except (ImportError, OSError):
system = MissingModule("system", urgent=0)
try:
from pygame.window import Window
except (ImportError, OSError):
def Window(title="pygame window", size=(640, 480), position=None, **kwargs): # pylint: disable=unused-argument
_attribute_undefined("pygame.Window")
try:
import pygame.typing
except (ImportError, OSError):
typing = MissingModule("typing", urgent=0)
fastevent = MissingModule("fastevent", urgent=0)
# there's also a couple "internal" modules not needed
# by users, but putting them here helps "dependency finder"
@@ -407,21 +295,13 @@ except (ImportError, OSError):
def packager_imports():
"""Some additional imports that py2app/py2exe will want to see.
This function is never executed.
Some tools scan the source code for import statements.
"""
"""some additional imports that py2app/py2exe will want to see"""
import atexit
import numpy
import OpenGL.GL
import pygame.macosx
import pygame.colordict
# lazy imports
import pygame.surfarray
import pygame.sndarray
# make Rects pickleable
@@ -452,23 +332,14 @@ def __color_reduce(c):
copyreg.pickle(Color, __color_reduce, __color_constructor)
# Thanks for supporting pygame. Without support now, there won't be pygame later.
if "PYGAME_HIDE_SUPPORT_PROMPT" not in os.environ:
import sysconfig
python_version = platform.python_version()
if (
sys.platform not in ("wasi", "emscripten")
and (sys.version_info >= (3, 13, 0))
and sysconfig.get_config_var("Py_GIL_DISABLED")
):
python_version += f"t, {'' if sys._is_gil_enabled() else 'No '}GIL"
print(
f"pygame-ce {ver} (SDL {'.'.join(map(str, get_sdl_version()))}, "
f"Python {python_version})"
"pygame {} (SDL {}.{}.{}, Python {}.{}.{})".format( # pylint: disable=consider-using-f-string
ver, *get_sdl_version() + sys.version_info[0:3]
)
)
del python_version, sysconfig
print("Hello from the pygame community. https://www.pygame.org/contribute.html")
# cleanup namespace
del pygame, os, sys, platform, MissingModule, copyreg, packager_imports
del pygame, os, sys, MissingModule, copyreg, packager_imports
@@ -1,9 +1,13 @@
# buildconfig/stubs/gen_stubs.py
# A script to auto-generate locals.pyi, constants.pyi and __init__.pyi typestubs
# IMPORTANT NOTE: Do not edit this file by hand!
# ruff: noqa: I001
from . import (
from typing import Tuple, NoReturn
def Overlay(format: int, size: Tuple[int, int]) -> NoReturn: ...
from pygame import (
display as display,
draw as draw,
event as event,
@@ -22,7 +26,9 @@ from . import (
sprite as sprite,
surfarray as surfarray,
transform as transform,
fastevent as fastevent,
scrap as scrap,
threads as threads,
version as version,
base as base,
bufferproxy as bufferproxy,
@@ -35,14 +41,9 @@ from . import (
surface as surface,
surflock as surflock,
sysfont as sysfont,
_debug as _debug,
system as system,
geometry as geometry,
window as window,
typing as typing,
)
from .rect import Rect as Rect, FRect as FRect
from .rect import Rect as Rect
from .surface import Surface as Surface, SurfaceType as SurfaceType
from .color import Color as Color
from .pixelarray import PixelArray as PixelArray
@@ -50,15 +51,7 @@ from .math import Vector2 as Vector2, Vector3 as Vector3
from .cursors import Cursor as Cursor
from .bufferproxy import BufferProxy as BufferProxy
from .mask import Mask as Mask
from ._debug import print_debug_info as print_debug_info
from .event import Event as Event
from .font import Font as Font
from .mixer import Sound as Sound, Channel as Channel
from .time import Clock as Clock
from .joystick import Joystick as Joystick
from .window import Window as Window
from .base import (
__version__ as __version__,
BufferError as BufferError,
HAVE_NEWBUF as HAVE_NEWBUF,
error as error,
@@ -78,7 +71,7 @@ from .rwobject import (
encode_string as encode_string,
)
from .version import SDL as SDL, rev as rev, ver as ver, vernum as vernum
from .version import SDL as SDL, rev as rev, ver as ver, vernum as vernum, ver as __version__
from .constants import (
ACTIVEEVENT as ACTIVEEVENT,
ANYFORMAT as ANYFORMAT,
@@ -109,26 +102,10 @@ from .constants import (
AUDIO_U16SYS as AUDIO_U16SYS,
AUDIO_U8 as AUDIO_U8,
BIG_ENDIAN as BIG_ENDIAN,
BLENDFACTOR_DST_ALPHA as BLENDFACTOR_DST_ALPHA,
BLENDFACTOR_DST_COLOR as BLENDFACTOR_DST_COLOR,
BLENDFACTOR_ONE as BLENDFACTOR_ONE,
BLENDFACTOR_ONE_MINUS_DST_ALPHA as BLENDFACTOR_ONE_MINUS_DST_ALPHA,
BLENDFACTOR_ONE_MINUS_DST_COLOR as BLENDFACTOR_ONE_MINUS_DST_COLOR,
BLENDFACTOR_ONE_MINUS_SRC_ALPHA as BLENDFACTOR_ONE_MINUS_SRC_ALPHA,
BLENDFACTOR_ONE_MINUS_SRC_COLOR as BLENDFACTOR_ONE_MINUS_SRC_COLOR,
BLENDFACTOR_SRC_ALPHA as BLENDFACTOR_SRC_ALPHA,
BLENDFACTOR_SRC_COLOR as BLENDFACTOR_SRC_COLOR,
BLENDFACTOR_ZERO as BLENDFACTOR_ZERO,
BLENDMODE_ADD as BLENDMODE_ADD,
BLENDMODE_BLEND as BLENDMODE_BLEND,
BLENDMODE_MOD as BLENDMODE_MOD,
BLENDMODE_MUL as BLENDMODE_MUL,
BLENDMODE_NONE as BLENDMODE_NONE,
BLENDOPERATION_ADD as BLENDOPERATION_ADD,
BLENDOPERATION_MAXIMUM as BLENDOPERATION_MAXIMUM,
BLENDOPERATION_MINIMUM as BLENDOPERATION_MINIMUM,
BLENDOPERATION_REV_SUBTRACT as BLENDOPERATION_REV_SUBTRACT,
BLENDOPERATION_SUBTRACT as BLENDOPERATION_SUBTRACT,
BLEND_ADD as BLEND_ADD,
BLEND_ALPHA_SDL2 as BLEND_ALPHA_SDL2,
BLEND_MAX as BLEND_MAX,
@@ -189,10 +166,6 @@ from .constants import (
CONTROLLER_BUTTON_START as CONTROLLER_BUTTON_START,
CONTROLLER_BUTTON_X as CONTROLLER_BUTTON_X,
CONTROLLER_BUTTON_Y as CONTROLLER_BUTTON_Y,
DIRECTION_BTT as DIRECTION_BTT,
DIRECTION_LTR as DIRECTION_LTR,
DIRECTION_RTL as DIRECTION_RTL,
DIRECTION_TTB as DIRECTION_TTB,
DOUBLEBUF as DOUBLEBUF,
DROPBEGIN as DROPBEGIN,
DROPCOMPLETE as DROPCOMPLETE,
@@ -201,15 +174,6 @@ from .constants import (
FINGERDOWN as FINGERDOWN,
FINGERMOTION as FINGERMOTION,
FINGERUP as FINGERUP,
FLASH_BRIEFLY as FLASH_BRIEFLY,
FLASH_CANCEL as FLASH_CANCEL,
FLASH_UNTIL_FOCUSED as FLASH_UNTIL_FOCUSED,
FLIP_HORIZONTAL as FLIP_HORIZONTAL,
FLIP_NONE as FLIP_NONE,
FLIP_VERTICAL as FLIP_VERTICAL,
FONT_CENTER as FONT_CENTER,
FONT_LEFT as FONT_LEFT,
FONT_RIGHT as FONT_RIGHT,
FULLSCREEN as FULLSCREEN,
GL_ACCELERATED_VISUAL as GL_ACCELERATED_VISUAL,
GL_ACCUM_ALPHA_SIZE as GL_ACCUM_ALPHA_SIZE,
@@ -257,7 +221,6 @@ from .constants import (
HWACCEL as HWACCEL,
HWPALETTE as HWPALETTE,
HWSURFACE as HWSURFACE,
IS_CE as IS_CE,
JOYAXISMOTION as JOYAXISMOTION,
JOYBALLMOTION as JOYBALLMOTION,
JOYBUTTONDOWN as JOYBUTTONDOWN,
@@ -607,7 +570,6 @@ from .constants import (
MULTIGESTURE as MULTIGESTURE,
NOEVENT as NOEVENT,
NOFRAME as NOFRAME,
NULL_VIDEODRIVER as NULL_VIDEODRIVER,
NUMEVENTS as NUMEVENTS,
OPENGL as OPENGL,
OPENGLBLIT as OPENGLBLIT,
@@ -625,8 +587,6 @@ from .constants import (
SCRAP_PPM as SCRAP_PPM,
SCRAP_SELECTION as SCRAP_SELECTION,
SCRAP_TEXT as SCRAP_TEXT,
SCROLL_ERASE as SCROLL_ERASE,
SCROLL_REPEAT as SCROLL_REPEAT,
SHOWN as SHOWN,
SRCALPHA as SRCALPHA,
SRCCOLORKEY as SRCCOLORKEY,
@@ -646,9 +606,6 @@ from .constants import (
SYSWMEVENT as SYSWMEVENT,
TEXTEDITING as TEXTEDITING,
TEXTINPUT as TEXTINPUT,
TEXTUREACCESS_STATIC as TEXTUREACCESS_STATIC,
TEXTUREACCESS_STREAMING as TEXTUREACCESS_STREAMING,
TEXTUREACCESS_TARGET as TEXTUREACCESS_TARGET,
TIMER_RESOLUTION as TIMER_RESOLUTION,
USEREVENT as USEREVENT,
USEREVENT_DROPFILE as USEREVENT_DROPFILE,
@@ -667,8 +624,6 @@ from .constants import (
WINDOWMAXIMIZED as WINDOWMAXIMIZED,
WINDOWMINIMIZED as WINDOWMINIMIZED,
WINDOWMOVED as WINDOWMOVED,
WINDOWPOS_CENTERED as WINDOWPOS_CENTERED,
WINDOWPOS_UNDEFINED as WINDOWPOS_UNDEFINED,
WINDOWRESIZED as WINDOWRESIZED,
WINDOWRESTORED as WINDOWRESTORED,
WINDOWSHOWN as WINDOWSHOWN,
@@ -1,6 +1,6 @@
"""
binaries hook for pygame seems to be required for pygame 2.0 Windows.
Otherwise, some essential DLLs will not be transferred to the exe.
Otherwise some essential DLLs will not be transferred to the exe.
And also put hooks for datas, resources that pygame uses, to work
correctly with pyinstaller
@@ -1,12 +1,39 @@
"""pygame.camera backend that uses OpenCV.
Uses the cv2 module opencv for python.
See https://pypi.org/project/opencv-python/ for wheels version.
python3 -m pip install opencv-python --user
"""
import sys
import time
import cv2
import numpy
import cv2
import pygame
def list_cameras():
return [0]
""" """
index = 0
device_idx = []
failed = 0
# Sometimes there are gaps between the device index.
# We keep trying max_gaps times.
max_gaps = 3
while failed < max_gaps:
vcap = cv2.VideoCapture(index)
if not vcap.read()[0]:
failed += 1
else:
device_idx.append(index)
vcap.release()
index += 1
return device_idx
def list_cameras_darwin():
@@ -33,12 +60,20 @@ def list_cameras_darwin():
class Camera:
# device should not have a default argument!!
# leaving here for compatibility, but I fixed the stubs.
def __init__(self, device=0, size=(640, 480), mode="RGB"):
def __init__(self, device=0, size=(640, 480), mode="RGB", api_preference=None):
"""
api_preference - cv2.CAP_DSHOW cv2.CAP_V4L2 cv2.CAP_MSMF and others
# See https://docs.opencv.org/3.4/d4/d15/group__videoio__flags__base.html
"""
self._device_index = device
self._size = size
self.api_preference = api_preference
if api_preference is not None and sys.platform == "win32":
# seems more compatible on windows?
self.api_preference = cv2.CAP_DSHOW
if mode == "RGB":
self._fmt = cv2.COLOR_BGR2RGB
elif mode == "YUV":
@@ -51,13 +86,13 @@ class Camera:
self._open = False
# all of this could have been done in the constructor, but creating
# the VideoCapture is very time-consuming, so it makes more sense in the
# the VideoCapture is very time consuming, so it makes more sense in the
# actual start() method
def start(self):
if self._open:
return
self._cam = cv2.VideoCapture(self._device_index)
self._cam = cv2.VideoCapture(self._device_index, self.api_preference)
if not self._cam.isOpened():
raise ValueError("Could not open camera.")
@@ -161,7 +196,7 @@ class Camera:
class CameraMac(Camera):
def __init__(self, device=0, size=(640, 480), mode="RGB"):
def __init__(self, device=0, size=(640, 480), mode="RGB", api_preference=None):
if isinstance(device, int):
_dev = device
elif isinstance(device, str):
@@ -172,4 +207,4 @@ class CameraMac(Camera):
str(type(device)),
)
super().__init__(_dev, size, mode)
super().__init__(_dev, size, mode, api_preference)
@@ -1,13 +0,0 @@
from dataclasses import dataclass
@dataclass(frozen=True)
class PowerState:
battery_percent: int | None
battery_seconds: int | None
on_battery: bool
no_battery: bool
charging: bool
charged: bool
plugged_in: bool
has_battery: bool
@@ -1,186 +0,0 @@
"""Debug functionality that allows for more useful issue reporting"""
import importlib
import platform
import sys
import traceback
from os import environ
from pygame.system import get_cpu_instruction_sets
from pygame.version import ver
def str_from_tuple(version_tuple):
"""Converts a tuple like (2, 0, 20) into a string joined by periods
Args:
version_tuple: tuple(version_major, version_minor, version_patch)
Returns:
str: "major.minor.patch"
"""
if version_tuple is None:
return "None"
strs = map(str, version_tuple)
return ".".join(strs)
def attempt_import(module, function_name, output_str=""):
"""Attempts to import function_name from module
Args:
module: string representing module name
function_name: string representing function name to be imported
output_str: optional string to prepend error messages to if one occurs
Returns:
tuple(str, bool, Any):
[0]: output_str + error_message
[1]: True if successful, False if failed
[2]: if successful, the thing that was imported, else None
"""
try:
mod = importlib.import_module(module)
i = getattr(mod, function_name)
success = True
except (ImportError, AttributeError):
i = None
output_str += f"There was a problem with {module} import\n"
output_str += "A default value will be returned for the version\n"
output_str += traceback.format_exc() + "\n" + "=" * 20 + "\n"
success = False
return (output_str, success, i)
def _get_platform_info():
"""
Internal helper to get platform information
"""
cpu_inst_dict = get_cpu_instruction_sets()
sse2 = "Yes" if cpu_inst_dict["SSE2"] else "No"
avx2 = "Yes" if cpu_inst_dict["AVX2"] else "No"
neon = "Yes" if cpu_inst_dict["NEON"] else "No"
ret = f"Platform:\t\t{platform.platform()}\n"
ret += f"System:\t\t\t{platform.system()}\n"
ret += f"System Version:\t\t{platform.version()}\n"
ret += f"Processor:\t\t{platform.processor()}\tSSE2: {sse2}\tAVX2: {avx2}\tNEON: {neon}\n"
ret += (
f"Architecture:\t\tBits: {platform.architecture()[0]}\t"
f"Linkage: {platform.architecture()[1]}\n\n"
)
ret += f"Python:\t\t\t{platform.python_implementation()} {sys.version}\n"
ret += (
f"GIL Enabled:\t\t{sys._is_gil_enabled()}\n"
if hasattr(sys, "_is_gil_enabled")
else "GIL Enabled:\t\tTrue\n"
)
ret += f"pygame version:\t\t{ver}\n"
return ret
def print_debug_info(filename=None):
"""Gets debug information for reporting bugs. Prints to console
if filename is not specified, otherwise writes to that file
(note: if filename is not an empty file, it will overwrite whatever is
in there)
Args:
filename: string name of the file to save
"""
debug_str = ""
# keyword for compat with getters
def default_return(linked=True):
# pylint: disable=unused-argument
return (-1, -1, -1)
from pygame.base import get_sdl_version
from pygame.display import (
get_driver as get_display_driver,
get_init as display_init,
)
debug_str, *mixer = attempt_import("pygame.mixer", "get_driver", debug_str)
get_mixer_driver = mixer[1] if mixer[0] else lambda: None
debug_str, *mixer = attempt_import("pygame.mixer", "get_init", debug_str)
mixer_init = mixer[1] if mixer[0] else lambda: False
debug_str, *mixer = attempt_import(
"pygame.mixer", "get_sdl_mixer_version", debug_str
)
get_sdl_mixer_version = mixer[1] if mixer[0] else default_return
debug_str, *font = attempt_import("pygame.font", "get_sdl_ttf_version", debug_str)
if not font[0]:
get_sdl_ttf_version = default_return
else:
get_sdl_ttf_version = font[1]
debug_str, *image = attempt_import(
"pygame.image", "get_sdl_image_version", debug_str
)
if not image[0]:
get_sdl_image_version = default_return
else:
get_sdl_image_version = image[1]
debug_str, *freetype = attempt_import("pygame.freetype", "get_version", debug_str)
if not freetype[0]:
ft_version = default_return
else:
ft_version = freetype[1]
debug_str += _get_platform_info()
debug_str += (
f"SDL versions:\t\tLinked: {str_from_tuple(get_sdl_version())}\t"
f"Compiled: {str_from_tuple(get_sdl_version(linked=False))}\n"
)
debug_str += (
f"SDL Mixer versions:\tLinked: {str_from_tuple(get_sdl_mixer_version())}\t"
f"Compiled: {str_from_tuple(get_sdl_mixer_version(linked=False))}\n"
)
debug_str += (
f"SDL Font versions:\tLinked: {str_from_tuple(get_sdl_ttf_version())}\t"
f"Compiled: {str_from_tuple(get_sdl_ttf_version(linked=False))}\n"
)
debug_str += (
f"SDL Image versions:\tLinked: {str_from_tuple(get_sdl_image_version())}\t"
f"Compiled: {str_from_tuple(get_sdl_image_version(linked=False))}\n"
)
debug_str += (
f"Freetype versions:\tLinked: {str_from_tuple(ft_version())}\t"
f"Compiled: {str_from_tuple(ft_version(linked=False))}\n\n"
)
if display_init():
driver = get_display_driver()
if driver.upper() != "X11":
debug_str += f"Display Driver:\t\t{driver}\n"
else:
is_xwayland = (environ.get("XDG_SESSION_TYPE") == "wayland") or (
"WAYLAND_DISPLAY" in environ
)
debug_str += f"Display Driver:\t\t{driver} ( xwayland == {is_xwayland} )\n"
else:
debug_str += "Display Driver:\t\tDisplay Not Initialized\n"
if mixer_init():
debug_str += f"Mixer Driver:\t\t{get_mixer_driver()}"
else:
debug_str += "Mixer Driver:\t\tMixer Not Initialized"
if filename is None:
print(debug_str)
else:
with open(filename, "w", encoding="utf8") as debugfile:
debugfile.write(debug_str)
@@ -1,7 +0,0 @@
from collections.abc import Callable
def str_from_tuple(version_tuple: tuple[int, int, int] | None) -> str: ...
def attempt_import(
module: str, function_name: str, output_str: str = ""
) -> tuple[str, bool, Callable | None]: ...
def print_debug_info(filename: str | None = None) -> None: ...
@@ -1,148 +0,0 @@
from collections.abc import Iterable
from typing import Any, Protocol, final
from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from pygame.typing import ColorLike, IntPoint, Point, RectLike, SequenceLike
from pygame.window import Window
class _DrawableClass(Protocol):
# Object that has the draw method that accepts area and dest arguments
def draw(self, area: RectLike | None = None, dest: RectLike | None = None): ...
@final
class Renderer:
def __init__(
self,
window: Window,
index: int = -1,
accelerated: int = -1,
vsync: bool = False,
target_texture: bool = False,
) -> None: ...
def blit(
self,
source: "Texture" | "Image" | _DrawableClass,
dest: RectLike | None = None,
area: RectLike | None = None,
special_flags: int = 0,
) -> Rect: ...
def clear(self) -> None: ...
def draw_line(self, p1: Point, p2: Point) -> None: ...
def draw_point(self, point: Point) -> None: ...
def draw_quad(self, p1: Point, p2: Point, p3: Point, p4: Point) -> None: ...
def draw_rect(self, rect: RectLike) -> None: ...
def draw_triangle(self, p1: Point, p2: Point, p3: Point) -> None: ...
def fill_quad(self, p1: Point, p2: Point, p3: Point, p4: Point) -> None: ...
def fill_rect(self, rect: RectLike) -> None: ...
def fill_triangle(self, p1: Point, p2: Point, p3: Point) -> None: ...
def get_viewport(self) -> Rect: ...
def coordinates_to_window(self, point: Point) -> tuple[float, float]: ...
def coordinates_from_window(self, point: Point) -> tuple[float, float]: ...
def present(self) -> None: ...
def set_viewport(self, area: RectLike | None) -> None: ...
def to_surface(
self, surface: Surface | None = None, area: RectLike | None = None
) -> Surface: ...
@property
def draw_blend_mode(self) -> int: ...
@draw_blend_mode.setter
def draw_blend_mode(self, value: int) -> None: ...
@property
def draw_color(self) -> Color: ...
@draw_color.setter
def draw_color(self, value: ColorLike) -> None: ...
@property
def logical_size(self) -> tuple[int, int]: ...
@logical_size.setter
def logical_size(self, value: IntPoint) -> None: ...
@property
def scale(self) -> tuple[float, float]: ...
@scale.setter
def scale(self, value: Point) -> None: ...
@property
def target(self) -> "Texture": ...
@target.setter
def target(self, value: "Texture") -> None: ...
@classmethod
def compose_custom_blend_mode(
cls, color_mode: SequenceLike[int], alpha_mode: SequenceLike[int]
) -> int: ...
@classmethod
def from_window(cls, window: Window) -> Renderer: ...
@final
class Texture:
def __init__(
self,
renderer: Renderer,
size: Iterable[int],
depth: int = 0,
static: bool = False,
streaming: bool = False,
target: bool = False,
scale_quality: int | None = None,
) -> None: ...
@property
def alpha(self) -> int: ...
@alpha.setter
def alpha(self, value: int) -> None: ...
@property
def blend_mode(self) -> int: ...
@blend_mode.setter
def blend_mode(self, value: int) -> None: ...
@property
def color(self) -> Color: ...
@color.setter
def color(self, value: ColorLike) -> None: ...
@property
def width(self) -> int: ...
@property
def height(self) -> int: ...
@property
def renderer(self) -> Renderer: ...
@classmethod
def from_surface(cls, renderer: Renderer, surface: Surface) -> Texture: ...
def draw(
self,
srcrect: RectLike | None = None,
dstrect: RectLike | None = None,
angle: float = 0.0,
origin: Iterable[int] | None = None,
flip_x: bool = False,
flip_y: bool = False,
) -> None: ...
def draw_triangle(
self,
p1_xy: Point,
p2_xy: Point,
p3_xy: Point,
p1_uv: Point = (0.0, 0.0),
p2_uv: Point = (1.0, 1.0),
p3_uv: Point = (0.0, 1.0),
p1_mod: ColorLike = (255, 255, 255, 255),
p2_mod: ColorLike = (255, 255, 255, 255),
p3_mod: ColorLike = (255, 255, 255, 255),
) -> None: ...
def draw_quad(
self,
p1_xy: Point,
p2_xy: Point,
p3_xy: Point,
p4_xy: Point,
p1_uv: Point = (0.0, 0.0),
p2_uv: Point = (1.0, 0.0),
p3_uv: Point = (1.0, 1.0),
p4_uv: Point = (0.0, 1.0),
p1_mod: ColorLike = (255, 255, 255, 255),
p2_mod: ColorLike = (255, 255, 255, 255),
p3_mod: ColorLike = (255, 255, 255, 255),
p4_mod: ColorLike = (255, 255, 255, 255),
) -> None: ...
def get_rect(self, **kwargs: Any) -> Rect: ...
def update(self, surface: Surface, area: RectLike | None = None) -> None: ...
@final
class Image:
pass
@@ -1,4 +1,3 @@
if __import__("sys").platform not in ("wasi", "emscripten"):
from .audio import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
from .sdl2 import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
from .video import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
from .sdl2 import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
from .audio import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
from .video import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
@@ -1,5 +1,4 @@
from collections.abc import Callable
from typing import Optional
from typing import Callable, List
AUDIO_U8: int
AUDIO_S8: int
@@ -21,12 +20,12 @@ AUDIO_ALLOW_FORMAT_CHANGE: int
AUDIO_ALLOW_CHANNELS_CHANGE: int
AUDIO_ALLOW_ANY_CHANGE: int
def get_audio_device_names(iscapture: bool = False) -> list[str]: ...
def get_audio_device_names(iscapture: bool = False) -> List[str]: ...
class AudioDevice:
def __init__(
self,
devicename: Optional[str],
devicename: str,
iscapture: bool,
frequency: int,
audioformat: int,
@@ -40,7 +39,7 @@ class AudioDevice:
@property
def deviceid(self) -> int: ...
@property
def devicename(self) -> Optional[str]: ...
def devicename(self) -> str: ...
@property
def callback(self) -> Callable[[AudioDevice, memoryview], None]: ...
@property
@@ -1,34 +1,35 @@
from typing import final
from typing import Dict, Mapping, Optional
from pygame.joystick import JoystickType
from pygame.typing import ColorLike
def init() -> None: ...
def get_init() -> bool: ...
def quit() -> None: ...
def is_controller(device_index: int) -> bool: ...
def set_eventstate(state: bool) -> None: ...
def get_eventstate() -> bool: ...
def update() -> None: ...
def get_count() -> int: ...
@final
def is_controller(index: int) -> bool: ...
def name_forindex(index: int) -> Optional[str]: ...
class Controller:
def __new__(cls, device_index: int) -> Controller: ...
def __init__(self, device_index: int) -> None: ...
@classmethod
def from_joystick(cls, joystick: JoystickType) -> Controller: ...
def get_init(self) -> bool: ...
def init(self) -> None: ...
def quit(self) -> None: ...
@property
def id(self) -> int: ...
def __init__(self, index: int) -> None: ...
@property
def name(self) -> str: ...
@property
def id(self) -> int: ...
def init(self) -> None: ...
def get_init(self) -> bool: ...
def quit(self) -> None: ...
@staticmethod
def from_joystick(joy: JoystickType) -> Controller: ...
def attached(self) -> bool: ...
def as_joystick(self) -> JoystickType: ...
def get_axis(self, axis: int) -> int: ...
def get_button(self, button: int) -> bool: ...
def get_mapping(self) -> dict[str, str]: ...
def set_mapping(self, mapping: dict[str, str]) -> int: ...
def get_mapping(self) -> Dict[str, str]: ...
def set_mapping(self, mapping: Mapping[str, str]) -> int: ...
def rumble(
self, low_frequency: float, high_frequency: float, duration: int
) -> bool: ...
def stop_rumble(self) -> None: ...
def set_led(self, color: ColorLike, /) -> bool: ...
@@ -1,35 +0,0 @@
from collections.abc import Mapping
from pygame.joystick import JoystickType
def init() -> None: ...
def get_init() -> bool: ...
def quit() -> None: ...
def set_eventstate(state: bool) -> None: ...
def get_eventstate() -> bool: ...
def update() -> None: ...
def get_count() -> int: ...
def is_controller(index: int) -> bool: ...
def name_forindex(index: int) -> str | None: ...
class Controller:
def __init__(self, index: int) -> None: ...
@property
def name(self) -> str: ...
@property
def id(self) -> int: ...
def init(self) -> None: ...
def get_init(self) -> bool: ...
def quit(self) -> None: ...
@staticmethod
def from_joystick(joy: JoystickType) -> Controller: ...
def attached(self) -> bool: ...
def as_joystick(self) -> JoystickType: ...
def get_axis(self, axis: int) -> int: ...
def get_button(self, button: int) -> bool: ...
def get_mapping(self) -> dict[str, str]: ...
def set_mapping(self, mapping: Mapping[str, str]) -> int: ...
def rumble(
self, low_frequency: float, high_frequency: float, duration: int
) -> bool: ...
def stop_rumble(self) -> None: ...
@@ -1,3 +1,5 @@
from typing import Optional
INIT_TIMER: int
INIT_AUDIO: int
INIT_VIDEO: int
@@ -9,6 +11,6 @@ INIT_NOPARACHUTE: int
INIT_EVERYTHING: int
class error(RuntimeError):
def __init__(self, message: str | None = None) -> None: ...
def __init__(self, message: Optional[str] = None) -> None: ...
def init_subsystem(flags: int) -> None: ...
@@ -1,12 +1,6 @@
from typing import TypedDict
class _FingerDict(TypedDict):
id: int
x: float
y: float
pressure: float
from typing import Dict, Union
def get_num_devices() -> int: ...
def get_device(index: int, /) -> int: ...
def get_num_fingers(device_id: int, /) -> int: ...
def get_finger(touchid: int, index: int) -> _FingerDict | None: ...
def get_device(index: int) -> int: ...
def get_num_fingers(device_id: int) -> int: ...
def get_finger(touchid: int, index: int) -> Dict[str, Union[int, float]]: ...
@@ -1,18 +1,16 @@
from collections.abc import Generator, Iterable
from typing import Any
from typing import Any, Generator, Iterable, Optional, Tuple, Union
from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from pygame.typing import ColorLike, Point, RectLike
from pygame.window import Window as Window
from .._common import RectValue, Literal, ColorValue
WINDOWPOS_UNDEFINED: int
WINDOWPOS_CENTERED: int
SCALEQUALITY_NEAREST: int
SCALEQUALITY_LINEAR: int
SCALEQUALITY_BEST: int
MESSAGEBOX_ERROR: int
MESSAGEBOX_WARNING: int
MESSAGEBOX_INFORMATION: int
class RendererDriverInfo:
name: str
@@ -22,18 +20,64 @@ class RendererDriverInfo:
max_texture_height: int
def get_drivers() -> Generator[RendererDriverInfo, None, None]: ...
def get_grabbed_window() -> Window | None: ...
def get_grabbed_window() -> Optional[Window]: ...
def messagebox(
title: str,
message: str,
window: Optional[Window] = None,
info: bool = False,
warn: bool = False,
error: bool = False,
buttons: Tuple[str, ...] = ("OK",),
return_button: int = 0,
escape_button: int = 0,
) -> int: ...
class Window:
DEFAULT_SIZE: Tuple[Literal[640], Literal[480]]
def __init__(
self,
title: str = "pygame",
size: Iterable[int] = (640, 480),
position: Optional[Iterable[int]] = None,
fullscreen: bool = False,
fullscreen_desktop: bool = False,
**kwargs: bool
) -> None: ...
@classmethod
def from_display_module(cls) -> Window: ...
@classmethod
def from_window(cls, other: int) -> Window: ...
grab: bool
relative_mouse: bool
def set_windowed(self) -> None: ...
def set_fullscreen(self, desktop: bool = False) -> None: ...
title: str
def destroy(self) -> None: ...
def hide(self) -> None: ...
def show(self) -> None: ...
def focus(self, input_only: bool = False) -> None: ...
def restore(self) -> None: ...
def maximize(self) -> None: ...
def minimize(self) -> None: ...
resizable: bool
borderless: bool
def set_icon(self, surface: Surface) -> None: ...
id: int
size: Iterable[int]
position: Union[int, Iterable[int]]
opacity: float
display_index: int
def set_modal_for(self, parent: Window) -> None: ...
class Texture:
def __init__(
self,
renderer: Renderer,
size: Iterable[int],
depth: int = 0,
static: bool = False,
streaming: bool = False,
target: bool = False,
scale_quality: int | None = None,
) -> None: ...
@staticmethod
def from_surface(renderer: Renderer, surface: Surface) -> Texture: ...
@@ -42,74 +86,39 @@ class Texture:
height: int
alpha: int
blend_mode: int
@property
def color(self) -> Color: ...
@color.setter
def color(self, value: ColorLike) -> None: ...
color: ColorValue
def get_rect(self, **kwargs: Any) -> Rect: ...
def draw(
self,
srcrect: RectLike | None = None,
dstrect: RectLike | None = None,
srcrect: Optional[RectValue] = None,
dstrect: Optional[RectValue] = None,
angle: float = 0.0,
origin: Iterable[int] | None = None,
origin: Optional[Iterable[int]] = None,
flip_x: bool = False,
flip_y: bool = False,
) -> None: ...
def draw_triangle(
self,
p1_xy: Point,
p2_xy: Point,
p3_xy: Point,
p1_uv: Point = (0.0, 0.0),
p2_uv: Point = (1.0, 1.0),
p3_uv: Point = (0.0, 1.0),
p1_mod: Iterable[int] = (255, 255, 255, 255),
p2_mod: Iterable[int] = (255, 255, 255, 255),
p3_mod: Iterable[int] = (255, 255, 255, 255),
) -> None: ...
def draw_quad(
self,
p1_xy: Point,
p2_xy: Point,
p3_xy: Point,
p4_xy: Point,
p1_uv: Point = (0.0, 0.0),
p2_uv: Point = (1.0, 0.0),
p3_uv: Point = (1.0, 1.0),
p4_uv: Point = (0.0, 1.0),
p1_mod: Iterable[int] = (255, 255, 255, 255),
p2_mod: Iterable[int] = (255, 255, 255, 255),
p3_mod: Iterable[int] = (255, 255, 255, 255),
p4_mod: Iterable[int] = (255, 255, 255, 255),
) -> None: ...
def update(self, surface: Surface, area: RectLike | None = None) -> None: ...
def update(self, surface: Surface, area: Optional[RectValue] = None) -> None: ...
class Image:
def __init__(
self,
texture_or_image: Texture | Image,
srcrect: RectLike | None = None,
textureOrImage: Union[Texture, Image],
srcrect: Optional[RectValue] = None,
) -> None: ...
def get_rect(self) -> Rect: ...
def get_rect(self, **kwargs: Any) -> Rect: ...
def draw(
self, srcrect: RectLike | None = None, dstrect: RectLike | None = None
self, srcrect: Optional[RectValue] = None, dstrect: Optional[RectValue] = None
) -> None: ...
angle: float
origin: Iterable[float] | None
origin: Optional[Iterable[float]]
flip_x: bool
flip_y: bool
color: ColorValue
alpha: float
blend_mode: int
texture: Texture
srcrect: Rect
@property
def color(self) -> Color: ...
@color.setter
def color(self, value: ColorLike) -> None: ...
class Renderer:
def __init__(
self,
@@ -122,38 +131,29 @@ class Renderer:
@classmethod
def from_window(cls, window: Window) -> Renderer: ...
draw_blend_mode: int
@property
def draw_color(self) -> Color: ...
@draw_color.setter
def draw_color(self, value: ColorLike) -> None: ...
draw_color: ColorValue
def clear(self) -> None: ...
def present(self) -> None: ...
def get_viewport(self) -> Rect: ...
def set_viewport(self, area: RectLike | None) -> None: ...
def set_viewport(self, area: Optional[RectValue]) -> None: ...
logical_size: Iterable[int]
def coordinates_to_window(self, point: Point) -> tuple[float, float]: ...
def coordinates_from_window(self, point: Point) -> tuple[float, float]: ...
scale: Iterable[float]
target: Texture | None
target: Optional[Texture]
def blit(
self,
source: Texture | Image,
dest: RectLike | None = None,
area: RectLike | None = None,
source: Union[Texture, Image],
dest: Optional[RectValue] = None,
area: Optional[RectValue] = None,
special_flags: int = 0,
) -> Rect: ...
def draw_line(self, p1: Point, p2: Point) -> None: ...
def draw_point(self, point: Point) -> None: ...
def draw_rect(self, rect: RectLike) -> None: ...
def fill_rect(self, rect: RectLike) -> None: ...
def draw_triangle(self, p1: Point, p2: Point, p3: Point) -> None: ...
def fill_triangle(self, p1: Point, p2: Point, p3: Point) -> None: ...
def draw_quad(self, p1: Point, p2: Point, p3: Point, p4: Point) -> None: ...
def fill_quad(self, p1: Point, p2: Point, p3: Point, p4: Point) -> None: ...
def draw_line(self, p1: Iterable[int], p2: Iterable[int]) -> None: ...
def draw_point(self, point: Iterable[int]) -> None: ...
def draw_rect(self, rect: RectValue) -> None: ...
def fill_rect(self, rect: RectValue) -> None: ...
def to_surface(
self, surface: Surface | None = None, area: RectLike | None = None
self, surface: Optional[Surface] = None, area: Optional[RectValue] = None
) -> Surface: ...
@staticmethod
def compose_custom_blend_mode(
color_mode: tuple[int, int, int], alpha_mode: tuple[int, int, int]
color_mode: Tuple[int, int, int], alpha_mode: Tuple[int, int, int]
) -> int: ...
@@ -1 +0,0 @@
from .video import Window # pylint: disable=wildcard-import
@@ -1 +0,0 @@
from pygame._sdl2.video import Window as Window
@@ -1,28 +0,0 @@
import warnings
warnings.warn(
"The ._sprite submodule is deprecated since 2.4.0. Please use pygame.sprite instead.",
category=DeprecationWarning,
stacklevel=2,
)
from pygame.sprite import (
AbstractGroup,
DirtySprite,
Group,
GroupSingle,
LayeredDirty,
LayeredUpdates,
RenderClear,
RenderPlain,
RenderUpdates,
Sprite,
collide_circle,
collide_circle_ratio,
collide_mask,
collide_rect,
collide_rect_ratio,
groupcollide,
spritecollide,
spritecollideany,
)
@@ -1,7 +1,4 @@
from collections.abc import Callable
from typing import Any
__version__: str
from typing import Any, Tuple, Callable
class error(RuntimeError): ...
class BufferError(Exception): ...
@@ -9,14 +6,14 @@ class BufferError(Exception): ...
# Always defined
HAVE_NEWBUF: int = 1
def init() -> tuple[int, int]: ...
def init() -> Tuple[int, int]: ...
def quit() -> None: ...
def get_init() -> bool: ...
def get_error() -> str: ...
def set_error(error_msg: str, /) -> None: ...
def get_sdl_version(linked: bool = True) -> tuple[int, int, int]: ...
def set_error(error_msg: str) -> None: ...
def get_sdl_version(linked: bool = True) -> Tuple[int, int, int]: ...
def get_sdl_byteorder() -> int: ...
def register_quit(callable: Callable[[], Any], /) -> None: ...
def register_quit(callable: Callable[[], Any]) -> None: ...
# undocumented part of pygame API, kept here to make stubtest happy
def get_array_interface(arg: Any, /) -> dict: ...
def get_array_interface(arg: Any) -> dict: ...
@@ -1,27 +1,15 @@
import sys
from typing import Any
from typing import Any, Dict, overload
class BufferProxy:
@property
def parent(self) -> Any: ...
@property
def length(self) -> int: ...
@property
def raw(self) -> bytes: ...
parent: Any
length: int
raw: bytes
# possibly going to be deprecated/removed soon, in which case these
# typestubs must be removed too
@property
def __array_interface__(self) -> dict[str, Any]: ...
@property
def __array_struct__(self) -> Any: ...
if sys.version_info >= (3, 12):
def __buffer__(self, flags: int, /) -> memoryview[int]: ...
def __release_buffer__(self, view: memoryview[int], /) -> None: ...
def __new__(
cls, parent: Any
) -> BufferProxy: ... # TODO: parent: TypedDict | Protocol
def write(
self,
buffer: str | bytes, # Any "read-only bytes-like-object" is valid
offset: int = 0,
) -> None: ...
__array_interface__: Dict[str, Any]
__array_struct__: Any
@overload
def __init__(self) -> None: ...
@overload
def __init__(self, parent: Any) -> None: ...
def write(self, buffer: bytes, offset: int = 0) -> None: ...
@@ -56,9 +56,7 @@ def _pre_init_placeholder_varargs(*_, **__):
class _PreInitPlaceholderCamera(AbstractCamera):
def __init__(self, *args, **kwargs):
_pre_init_placeholder()
__init__ = _pre_init_placeholder_varargs
start = _pre_init_placeholder_varargs
stop = _pre_init_placeholder_varargs
get_controls = _pre_init_placeholder_varargs
@@ -106,6 +104,20 @@ def _setup_backend(backend):
list_cameras = _camera.list_cameras
Camera = _camera.Camera
elif backend == "videocapture":
from pygame import _camera_vidcapture
warnings.warn(
"The VideoCapture backend is not recommended and may be removed."
"For Python3 and Windows 8+, there is now a native Windows "
"backend built into pygame.",
DeprecationWarning,
stacklevel=2,
)
_camera_vidcapture.init()
list_cameras = _camera_vidcapture.list_cameras
Camera = _camera_vidcapture.Camera
else:
raise ValueError("unrecognized backend name")
@@ -113,16 +125,34 @@ def _setup_backend(backend):
def get_backends():
possible_backends = []
if sys.platform == "win32" and int(platform.win32_ver()[0].split(".")[0]) >= 8:
possible_backends.append("_camera (MSMF)")
if sys.platform == "win32":
version_code = platform.win32_ver()[0].split(".")[0]
if "Server" in version_code:
version_code = ''.join(filter(str.isdigit, version_code))[:4]
minimum_satisfied = int(version_code) >= 2012
else:
minimum_satisfied = int(version_code) >= 8
if sys.platform == "linux":
if minimum_satisfied:
try:
# If cv2 is installed, prefer that on windows.
import cv2
possible_backends.append("OpenCV")
except ImportError:
possible_backends.append("_camera (MSMF)")
if "linux" in sys.platform:
possible_backends.append("_camera (V4L2)")
if "darwin" in sys.platform:
possible_backends.append("OpenCV-Mac")
possible_backends.append("OpenCV")
if "OpenCV" not in possible_backends:
possible_backends.append("OpenCV")
if sys.platform == "win32":
possible_backends.append("VideoCapture")
# see if we have any user specified defaults in environments.
camera_env = os.environ.get("PYGAME_CAMERA", "").lower()
@@ -131,6 +161,11 @@ def get_backends():
possible_backends.remove("OpenCV")
possible_backends = ["OpenCV"] + possible_backends
if camera_env in ("vidcapture", "videocapture"): # prioritize vidcapture
if "VideoCapture" in possible_backends:
possible_backends.remove("VideoCapture")
possible_backends = ["VideoCapture"] + possible_backends
return possible_backends
@@ -155,8 +190,8 @@ def init(backend=None):
_setup_backend(backend)
except ImportError:
emsg = f"Backend '{backend}' is not supported on your platform!"
if backend in ("opencv", "opencv-mac"):
dep = "OpenCV"
if backend in ("opencv", "opencv-mac", "videocapture"):
dep = "vidcap" if backend == "videocapture" else "OpenCV"
emsg += (
f" Make sure you have '{dep}' installed to be able to use this backend"
)
@@ -176,7 +211,7 @@ def quit():
if __name__ == "__main__":
# try to use this camera stuff with the pygame camera example.
# try and use this camera stuff with the pygame camera example.
import pygame.examples.camera
# pygame.camera.Camera = Camera
@@ -1,16 +1,12 @@
from abc import ABC, abstractmethod
from typing import Literal
from typing import List, Optional, Sequence, Tuple, Union
from pygame.surface import Surface
from pygame.typing import IntPoint
def get_backends() -> list[str]: ...
def init(backend: str | None = None) -> None: ...
def get_backends() -> List[str]: ...
def init(backend: Optional[str] = None) -> None: ...
def quit() -> None: ...
def list_cameras() -> list[str] | list[int]: ...
def colorspace(
surface: Surface, color: Literal["YUV", "HSV"], dest_surface: Surface = ..., /
) -> Surface: ...
def list_cameras() -> List[str]: ...
class AbstractCamera(ABC):
@abstractmethod
@@ -20,11 +16,11 @@ class AbstractCamera(ABC):
@abstractmethod
def stop(self) -> None: ...
@abstractmethod
def get_size(self) -> tuple[int, int]: ...
def get_size(self) -> Tuple[int, int]: ...
@abstractmethod
def query_image(self) -> bool: ...
@abstractmethod
def get_image(self, dest_surf: Surface | None = None) -> Surface: ...
def get_image(self, dest_surf: Optional[Surface] = None) -> Surface: ...
@abstractmethod
def get_raw(self) -> bytes: ...
# set_controls and get_controls are not a part of the AbstractCamera ABC,
@@ -34,20 +30,20 @@ class AbstractCamera(ABC):
class Camera(AbstractCamera):
def __init__(
self,
device: str | int,
size: IntPoint = (640, 480),
device: Union[str, int] = 0,
size: Union[Tuple[int, int], Sequence[int]] = (640, 480),
format: str = "RGB",
) -> None: ...
def start(self) -> None: ...
def stop(self) -> None: ...
def get_controls(self) -> tuple[bool, bool, int]: ...
def get_controls(self) -> Tuple[bool, bool, int]: ...
def set_controls(
self,
hflip: bool = ...,
vflip: bool = ...,
brightness: int = ...,
) -> tuple[bool, bool, int]: ...
def get_size(self) -> tuple[int, int]: ...
) -> Tuple[bool, bool, int]: ...
def get_size(self) -> Tuple[int, int]: ...
def query_image(self) -> bool: ...
def get_image(self, surface: Surface | None = None) -> Surface: ...
def get_image(self, surface: Optional[Surface] = None) -> Surface: ...
def get_raw(self) -> bytes: ...
@@ -1,228 +1,36 @@
import sys
from collections.abc import Collection, Iterator
from typing import Any, ClassVar, SupportsIndex, overload
from typing import Any, Dict, Iterator, Tuple, overload
from pygame.typing import ColorLike
from typing_extensions import deprecated # added in 3.13
from ._common import ColorValue
THECOLORS: dict[str, tuple[int, int, int, int]]
if sys.version_info >= (3, 9):
from collections.abc import Collection
else:
from typing import Collection
THECOLORS: Dict[str, Tuple[int, int, int, int]]
# Color confirms to the Collection ABC, since it also confirms to
# Sized, Iterable and Container ABCs
class Color(Collection[int]):
"""Pygame object for color representations.
The ``Color`` class represents ``RGBA`` color values using a value range of
0 to 255 inclusive. It allows basic arithmetic operations — binary
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 swizzling for their ``RGBA`` attributes, which allows
the creation of new color objects with the corresponding swizzled attributes
as its ``RGBA`` attributes. For example, ``color.bgra`` provides a shortcut to
doing ``Color(color.b, color.g, color.r, color.a)``. Swizzling with other than
4 attributes will return a tuple consisting of the corresponding elements
instead of a color object.
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.5.6
``bytes(Color(...))`` (assuming `bytes <https://docs.python.org/3/library/stdtypes.html#bytes>`_ is
the built-in type) now returns a ``bytes`` object (of length 4) with the RGBA values of the color,
as opposed to :class:`Color` being interpreted as an integer (think ``int(Color(...))``) causing it
to return a ``bytes`` object filled with 0s the length of said integer.
.. versionchangedold:: 2.0.0
Support for tuples, lists, and :class:`Color` objects when creating
:class:`Color` objects.
.. versionchangedold:: 1.9.2 Color objects export the C level array interface.
.. versionchangedold:: 1.9.0 Color objects support 4-element tuples of integers.
.. versionchangedold:: 1.8.1 New implementation of the class.
"""
r: int
"""Gets or sets the red value of the Color.
The red value of the Color.
"""
g: int
"""Gets or sets the green value of the Color.
The green value of the Color.
"""
b: int
"""Gets or sets the blue value of the Color.
The blue value of the Color.
"""
a: int
"""Gets or sets the alpha value of the Color.
The alpha value of the Color.
"""
cmy: tuple[float, float, float]
"""Gets or sets the CMY representation of the Color.
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.
"""
hsva: tuple[float, float, float, float]
"""Gets or sets the HSVA representation of the Color.
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.
"""
hsla: tuple[float, float, float, float]
"""Gets or sets the HSLA representation of the Color.
The ``HSLA`` representation of the Color. The ``HSLA`` components are in
the ranges ``H`` = [0, 360], ``S`` = [0, 100], ``L`` = [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.
"""
i1i2i3: tuple[float, float, float]
"""Gets or sets the I1I2I3 representation of the Color.
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.
"""
normalized: tuple[float, float, float, float]
"""Gets or sets the normalized representation of the Color.
The ``Normalized`` representation of the Color. The components of the ``Normalized``
representation represent the basic ``RGBA`` values but normalized the
ranges of the values are ``r`` = [0, 1], ``g`` = [0, 1], ``b`` = [0, 1]
and ``a`` = [0, 1] respectively. Note that this will not return the absolutely exact
``Normalized`` values for the set ``RGBA`` values in all cases.
Due to the ``RGB`` mapping from 0-255 and the ``Normalized`` mapping from 0-1
rounding errors may cause the ``Normalized`` values to differ
slightly from what you might expect.
.. versionadded:: 2.5.0
"""
hex: str
"""Gets or sets the stringified hexadecimal representation of the Color.
The stringified hexadecimal representation of the Color. The hexadecimal string
is formatted as ``"#rrggbbaa"`` where rr, gg, bb, and aa are two digit hex numbers
in the range from 0x00 to 0xff.
Setting this property means changing the color channels in place. Both lowercase
and uppercase letters are allowed, the alpha can be omitted (defaults to 0xff) and
the string can start with either ``#`` or ``0x``.
.. versionadded:: 2.5.4
"""
__hash__: ClassVar[None] # type: ignore[assignment]
@property
def __array_struct__(self) -> Any: ...
if sys.version_info >= (3, 12):
def __buffer__(self, flags: int, /) -> memoryview[int]: ...
cmy: Tuple[float, float, float]
hsva: Tuple[float, float, float, float]
hsla: Tuple[float, float, float, float]
i1i2i3: Tuple[float, float, float]
__hash__: None # type: ignore
__array_struct__: Any
@overload
def __init__(self, r: int, g: int, b: int, a: int = 255) -> None: ...
@overload
def __init__(self, rgbvalue: ColorLike) -> None: ...
def __init__(self, rgbvalue: ColorValue) -> None: ...
@overload
def __getitem__(self, i: SupportsIndex) -> int: ...
def __getitem__(self, i: int) -> int: ...
@overload
def __getitem__(self, s: slice) -> tuple[int, ...]: ...
def __getitem__(self, s: slice) -> Tuple[int]: ...
def __setitem__(self, key: int, value: int) -> None: ...
def __iter__(self) -> Iterator[int]: ...
def __add__(self, other: Color) -> Color: ...
@@ -232,180 +40,17 @@ class Color(Collection[int]):
def __mod__(self, other: Color) -> Color: ...
def __int__(self) -> int: ...
def __float__(self) -> float: ...
def __bytes__(self) -> bytes: ...
def __len__(self) -> int: ...
def __index__(self) -> int: ...
def __invert__(self) -> Color: ...
def __contains__(self, other: int) -> bool: ... # type: ignore[override]
def __getattribute__(self, name: str) -> Color | tuple[int, ...]: ...
def __setattr__(self, name: str, value: Color | tuple[int, ...]) -> None: ...
def normalize(self) -> Tuple[float, float, float, float]: ...
def correct_gamma(self, gamma: float) -> Color: ...
def set_length(self, length: int) -> None: ...
def lerp(self, color: ColorValue, amount: float) -> Color: ...
def premul_alpha(self) -> Color: ...
@overload
@classmethod
def from_cmy(cls, object: tuple[float, float, float], /) -> Color: ...
def update(self, r: int, g: int, b: int, a: int = 255) -> None: ...
@overload
@classmethod
def from_cmy(cls, c: float, m: float, y: float, /) -> Color: ...
@classmethod # type: ignore
def from_cmy(cls, *args) -> Color: # type: ignore
"""Returns a Color object from a CMY representation.
Creates a Color object from the given CMY components. Refer to :attr:`Color.cmy`
for more information.
.. versionadded:: 2.3.1
"""
@overload
@classmethod
def from_hsva(cls, object: tuple[float, float, float, float], /) -> Color: ...
@overload
@classmethod
def from_hsva(cls, h: float, s: float, v: float, a: float, /) -> Color: ...
@classmethod # type: ignore
def from_hsva(cls, *args) -> Color: # type: ignore
"""Returns a Color object from an HSVA representation.
Creates a Color object from the given HSVA components. Refer to :attr:`Color.hsva`
for more information.
.. versionadded:: 2.3.1
"""
@overload
@classmethod
def from_hsla(cls, object: tuple[float, float, float, float], /) -> Color: ...
@overload
@classmethod
def from_hsla(cls, h: float, s: float, l: float, a: float, /) -> Color: ...
@classmethod # type: ignore
def from_hsla(cls, *args) -> Color: # type: ignore
"""Returns a Color object from an HSLA representation.
Creates a Color object from the given HSLA components. Refer to :attr:`Color.hsla`
for more information.
.. versionadded:: 2.3.1
"""
@overload
@classmethod
def from_i1i2i3(cls, object: tuple[float, float, float], /) -> Color: ...
@overload
@classmethod
def from_i1i2i3(cls, i1: float, i2: float, i3: float, /) -> Color: ...
@classmethod # type: ignore
def from_i1i2i3(cls, *args) -> Color: # type: ignore
"""Returns a Color object from a I1I2I3 representation.
Creates a Color object from the given I1I2I3 components. Refer to :attr:`Color.i1i2i3`
for more information.
.. versionadded:: 2.3.1
"""
@overload
@classmethod
def from_normalized(cls, object: tuple[float, float, float, float], /) -> Color: ...
@overload
@classmethod
def from_normalized(cls, r: float, g: float, b: float, a: float, /) -> Color: ...
@classmethod # type: ignore
def from_normalized(cls, *args) -> Color: # type: ignore
"""Returns a Color object from a Normalized representation.
Creates a Color object from the given Normalized components. Refer to :attr:`Color.normalized`
for more information.
.. versionadded:: 2.5.0
"""
@classmethod
def from_hex(cls, hex: str, /) -> Color:
"""Returns a Color object from a Hexadecimal representation.
Creates a Color object from the given Hexadecimal components. Refer to :attr:`Color.hex`
for more information.
.. versionadded:: 2.5.6
"""
def normalize(self) -> tuple[float, float, float, float]:
"""Returns the normalized RGBA values of the Color.
Returns the normalized ``RGBA`` values of the Color as floating point
values.
"""
def correct_gamma(self, gamma: float, /) -> Color:
"""Applies a certain gamma value to the Color.
Applies a certain gamma value to the Color and returns a new Color with
the adjusted ``RGBA`` values.
"""
@deprecated("since 2.1.3. Use unpacking instead")
def set_length(self, length: int, /) -> None:
"""Set the number of elements in the Color to 1,2,3, or 4.
DEPRECATED: You may unpack the values you need like so,
``r, g, b, _ = pygame.Color(100, 100, 100)``
If you only want r, g and b
Or
``r, g, *_ = pygame.Color(100, 100, 100)``
if you only want r and g
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)``.
.. deprecated:: 2.1.3
.. versionaddedold:: 1.9.0
"""
def grayscale(self) -> Color:
"""Returns the grayscale of a Color.
Returns a new Color object which represents the grayscaled version of self, using the luminosity formula,
which weights red, green, and blue according to their relative contribution to perceived brightness.
.. versionadded:: 2.1.4
"""
def lerp(self, color: ColorLike, amount: float) -> Color:
"""Returns a linear interpolation to the given 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.
.. versionaddedold:: 2.0.1
"""
def premul_alpha(self) -> Color:
"""Returns a Color where the r,g,b components have been multiplied by the alpha.
Returns a new Color where each of the red, green and blue color
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.
.. versionaddedold:: 2.0.0
"""
@overload
def update(self, r: int, g: int, b: int, a: int = 255, /) -> None: ...
@overload
def update(self, rgbvalue: ColorLike, /) -> None: ...
def update(self, *args) -> None: # type: ignore
"""Sets the elements of the color.
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.
.. versionaddedold:: 2.0.1
"""
def update(self, rgbvalue: ColorValue) -> None: ...
def grayscale(self) -> Color: ...
@@ -1,4 +1,4 @@
# pygame-ce - Python Game Library
# pygame - Python Game Library
# Copyright (C) 2000-2003 Pete Shinners
#
# This library is free software; you can redistribute it and/or
@@ -18,9 +18,9 @@
# Pete Shinners
# pete@shinners.org
"""A dictionary of RGBA tuples indexed by color names.
""" A dictionary of RGBA tuples indexed by color names.
See https://pyga.me/docs/ref/color_list.html for sample swatches.
See https://www.pygame.org/docs/ref/color_list.html for sample swatches.
"""
THECOLORS = {
@@ -31,26 +31,10 @@ AUDIO_U16MSB: int
AUDIO_U16SYS: int
AUDIO_U8: int
BIG_ENDIAN: int
BLENDFACTOR_DST_ALPHA: int
BLENDFACTOR_DST_COLOR: int
BLENDFACTOR_ONE: int
BLENDFACTOR_ONE_MINUS_DST_ALPHA: int
BLENDFACTOR_ONE_MINUS_DST_COLOR: int
BLENDFACTOR_ONE_MINUS_SRC_ALPHA: int
BLENDFACTOR_ONE_MINUS_SRC_COLOR: int
BLENDFACTOR_SRC_ALPHA: int
BLENDFACTOR_SRC_COLOR: int
BLENDFACTOR_ZERO: int
BLENDMODE_ADD: int
BLENDMODE_BLEND: int
BLENDMODE_MOD: int
BLENDMODE_MUL: int
BLENDMODE_NONE: int
BLENDOPERATION_ADD: int
BLENDOPERATION_MAXIMUM: int
BLENDOPERATION_MINIMUM: int
BLENDOPERATION_REV_SUBTRACT: int
BLENDOPERATION_SUBTRACT: int
BLEND_ADD: int
BLEND_ALPHA_SDL2: int
BLEND_MAX: int
@@ -111,10 +95,6 @@ CONTROLLER_BUTTON_RIGHTSTICK: int
CONTROLLER_BUTTON_START: int
CONTROLLER_BUTTON_X: int
CONTROLLER_BUTTON_Y: int
DIRECTION_BTT: int
DIRECTION_LTR: int
DIRECTION_RTL: int
DIRECTION_TTB: int
DOUBLEBUF: int
DROPBEGIN: int
DROPCOMPLETE: int
@@ -123,15 +103,6 @@ DROPTEXT: int
FINGERDOWN: int
FINGERMOTION: int
FINGERUP: int
FLASH_BRIEFLY: int
FLASH_CANCEL: int
FLASH_UNTIL_FOCUSED: int
FLIP_HORIZONTAL: int
FLIP_NONE: int
FLIP_VERTICAL: int
FONT_CENTER: int
FONT_LEFT: int
FONT_RIGHT: int
FULLSCREEN: int
GL_ACCELERATED_VISUAL: int
GL_ACCUM_ALPHA_SIZE: int
@@ -179,7 +150,6 @@ HIDDEN: int
HWACCEL: int
HWPALETTE: int
HWSURFACE: int
IS_CE: int
JOYAXISMOTION: int
JOYBALLMOTION: int
JOYBUTTONDOWN: int
@@ -529,7 +499,6 @@ MOUSEWHEEL: int
MULTIGESTURE: int
NOEVENT: int
NOFRAME: int
NULL_VIDEODRIVER: str
NUMEVENTS: int
OPENGL: int
OPENGLBLIT: int
@@ -547,8 +516,6 @@ SCRAP_PBM: str
SCRAP_PPM: str
SCRAP_SELECTION: int
SCRAP_TEXT: str
SCROLL_ERASE: int
SCROLL_REPEAT: int
SHOWN: int
SRCALPHA: int
SRCCOLORKEY: int
@@ -568,9 +535,6 @@ SYSTEM_CURSOR_WAITARROW: int
SYSWMEVENT: int
TEXTEDITING: int
TEXTINPUT: int
TEXTUREACCESS_STATIC: int
TEXTUREACCESS_STREAMING: int
TEXTUREACCESS_TARGET: int
TIMER_RESOLUTION: int
USEREVENT: int
USEREVENT_DROPFILE: int
@@ -589,606 +553,8 @@ WINDOWLEAVE: int
WINDOWMAXIMIZED: int
WINDOWMINIMIZED: int
WINDOWMOVED: int
WINDOWPOS_CENTERED: int
WINDOWPOS_UNDEFINED: int
WINDOWRESIZED: int
WINDOWRESTORED: int
WINDOWSHOWN: int
WINDOWSIZECHANGED: int
WINDOWTAKEFOCUS: int
__all__ = [
"LIL_ENDIAN",
"BIG_ENDIAN",
"SWSURFACE",
"HWSURFACE",
"RESIZABLE",
"ASYNCBLIT",
"OPENGL",
"OPENGLBLIT",
"ANYFORMAT",
"HWPALETTE",
"DOUBLEBUF",
"FULLSCREEN",
"HWACCEL",
"SRCCOLORKEY",
"RLEACCELOK",
"RLEACCEL",
"SRCALPHA",
"PREALLOC",
"NOFRAME",
"SHOWN",
"HIDDEN",
"SCROLL_ERASE",
"SCROLL_REPEAT",
"SCALED",
"GL_RED_SIZE",
"GL_GREEN_SIZE",
"GL_BLUE_SIZE",
"GL_ALPHA_SIZE",
"GL_BUFFER_SIZE",
"GL_DOUBLEBUFFER",
"GL_DEPTH_SIZE",
"GL_STENCIL_SIZE",
"GL_ACCUM_RED_SIZE",
"GL_ACCUM_GREEN_SIZE",
"GL_ACCUM_BLUE_SIZE",
"GL_ACCUM_ALPHA_SIZE",
"GL_ACCELERATED_VISUAL",
"GL_CONTEXT_MAJOR_VERSION",
"GL_CONTEXT_MINOR_VERSION",
"GL_SHARE_WITH_CURRENT_CONTEXT",
"GL_CONTEXT_FLAGS",
"GL_CONTEXT_DEBUG_FLAG",
"GL_CONTEXT_FORWARD_COMPATIBLE_FLAG",
"GL_CONTEXT_ROBUST_ACCESS_FLAG",
"GL_CONTEXT_RESET_ISOLATION_FLAG",
"GL_CONTEXT_PROFILE_MASK",
"GL_CONTEXT_PROFILE_CORE",
"GL_CONTEXT_PROFILE_COMPATIBILITY",
"GL_CONTEXT_PROFILE_ES",
"GL_FRAMEBUFFER_SRGB_CAPABLE",
"GL_CONTEXT_RELEASE_BEHAVIOR",
"GL_CONTEXT_RELEASE_BEHAVIOR_NONE",
"GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH",
"BLENDMODE_NONE",
"BLENDMODE_BLEND",
"BLENDMODE_ADD",
"BLENDMODE_MOD",
"BLENDMODE_MUL",
"BLENDFACTOR_ZERO",
"BLENDFACTOR_ONE",
"BLENDFACTOR_SRC_COLOR",
"BLENDFACTOR_ONE_MINUS_SRC_COLOR",
"BLENDFACTOR_SRC_ALPHA",
"BLENDFACTOR_ONE_MINUS_SRC_ALPHA",
"BLENDFACTOR_DST_COLOR",
"BLENDFACTOR_ONE_MINUS_DST_COLOR",
"BLENDFACTOR_DST_ALPHA",
"BLENDFACTOR_ONE_MINUS_DST_ALPHA",
"BLENDOPERATION_ADD",
"BLENDOPERATION_SUBTRACT",
"BLENDOPERATION_REV_SUBTRACT",
"BLENDOPERATION_MINIMUM",
"BLENDOPERATION_MAXIMUM",
"GL_STEREO",
"GL_MULTISAMPLEBUFFERS",
"GL_MULTISAMPLESAMPLES",
"GL_SWAP_CONTROL",
"TIMER_RESOLUTION",
"AUDIO_U8",
"AUDIO_S8",
"AUDIO_U16LSB",
"AUDIO_S16LSB",
"AUDIO_U16MSB",
"AUDIO_S16MSB",
"AUDIO_U16",
"AUDIO_S16",
"AUDIO_U16SYS",
"AUDIO_S16SYS",
"SCRAP_TEXT",
"SCRAP_BMP",
"SCRAP_PPM",
"SCRAP_PBM",
"SCRAP_CLIPBOARD",
"SCRAP_SELECTION",
"BLEND_ADD",
"BLEND_SUB",
"BLEND_MULT",
"BLEND_MIN",
"BLEND_MAX",
"BLEND_RGB_ADD",
"BLEND_RGB_SUB",
"BLEND_RGB_MULT",
"BLEND_RGB_MIN",
"BLEND_RGB_MAX",
"BLEND_RGBA_ADD",
"BLEND_RGBA_SUB",
"BLEND_RGBA_MULT",
"BLEND_RGBA_MIN",
"BLEND_RGBA_MAX",
"BLEND_PREMULTIPLIED",
"BLEND_ALPHA_SDL2",
"NOEVENT",
"ACTIVEEVENT",
"KEYDOWN",
"KEYUP",
"MOUSEMOTION",
"MOUSEBUTTONDOWN",
"MOUSEBUTTONUP",
"JOYAXISMOTION",
"JOYBALLMOTION",
"JOYHATMOTION",
"JOYBUTTONDOWN",
"JOYBUTTONUP",
"VIDEORESIZE",
"VIDEOEXPOSE",
"QUIT",
"SYSWMEVENT",
"MIDIIN",
"MIDIOUT",
"USEREVENT",
"NUMEVENTS",
"APP_TERMINATING",
"APP_LOWMEMORY",
"APP_WILLENTERBACKGROUND",
"APP_DIDENTERBACKGROUND",
"APP_WILLENTERFOREGROUND",
"APP_DIDENTERFOREGROUND",
"CLIPBOARDUPDATE",
"KEYMAPCHANGED",
"RENDER_TARGETS_RESET",
"RENDER_DEVICE_RESET",
"HAT_CENTERED",
"HAT_UP",
"HAT_RIGHTUP",
"HAT_RIGHT",
"HAT_RIGHTDOWN",
"HAT_DOWN",
"HAT_LEFTDOWN",
"HAT_LEFT",
"HAT_LEFTUP",
"BUTTON_LEFT",
"BUTTON_MIDDLE",
"BUTTON_RIGHT",
"FINGERMOTION",
"FINGERDOWN",
"FINGERUP",
"MULTIGESTURE",
"AUDIODEVICEADDED",
"AUDIODEVICEREMOVED",
"MOUSEWHEEL",
"TEXTINPUT",
"TEXTEDITING",
"WINDOWSHOWN",
"WINDOWHIDDEN",
"WINDOWEXPOSED",
"WINDOWMOVED",
"WINDOWRESIZED",
"WINDOWSIZECHANGED",
"WINDOWMINIMIZED",
"WINDOWMAXIMIZED",
"WINDOWRESTORED",
"WINDOWENTER",
"WINDOWLEAVE",
"WINDOWFOCUSGAINED",
"WINDOWFOCUSLOST",
"WINDOWCLOSE",
"WINDOWTAKEFOCUS",
"WINDOWHITTEST",
"WINDOWICCPROFCHANGED",
"WINDOWDISPLAYCHANGED",
"TEXTUREACCESS_STATIC",
"TEXTUREACCESS_STREAMING",
"TEXTUREACCESS_TARGET",
"FLIP_NONE",
"FLIP_HORIZONTAL",
"FLIP_VERTICAL",
"CONTROLLERAXISMOTION",
"CONTROLLERBUTTONDOWN",
"CONTROLLERBUTTONUP",
"CONTROLLERDEVICEADDED",
"CONTROLLERDEVICEREMOVED",
"CONTROLLERDEVICEREMAPPED",
"CONTROLLERTOUCHPADDOWN",
"CONTROLLERTOUCHPADMOTION",
"CONTROLLERTOUCHPADUP",
"CONTROLLERSENSORUPDATE",
"LOCALECHANGED",
"JOYDEVICEADDED",
"JOYDEVICEREMOVED",
"BUTTON_X1",
"BUTTON_X2",
"BUTTON_WHEELUP",
"BUTTON_WHEELDOWN",
"AUDIO_ALLOW_FREQUENCY_CHANGE",
"AUDIO_ALLOW_FORMAT_CHANGE",
"AUDIO_ALLOW_CHANNELS_CHANGE",
"AUDIO_ALLOW_ANY_CHANGE",
"DROPFILE",
"DROPTEXT",
"DROPBEGIN",
"DROPCOMPLETE",
"CONTROLLER_AXIS_INVALID",
"CONTROLLER_AXIS_LEFTX",
"CONTROLLER_AXIS_LEFTY",
"CONTROLLER_AXIS_RIGHTX",
"CONTROLLER_AXIS_RIGHTY",
"CONTROLLER_AXIS_TRIGGERLEFT",
"CONTROLLER_AXIS_TRIGGERRIGHT",
"CONTROLLER_AXIS_MAX",
"CONTROLLER_BUTTON_INVALID",
"CONTROLLER_BUTTON_A",
"CONTROLLER_BUTTON_B",
"CONTROLLER_BUTTON_X",
"CONTROLLER_BUTTON_Y",
"CONTROLLER_BUTTON_BACK",
"CONTROLLER_BUTTON_GUIDE",
"CONTROLLER_BUTTON_START",
"CONTROLLER_BUTTON_LEFTSTICK",
"CONTROLLER_BUTTON_RIGHTSTICK",
"CONTROLLER_BUTTON_LEFTSHOULDER",
"CONTROLLER_BUTTON_RIGHTSHOULDER",
"CONTROLLER_BUTTON_DPAD_UP",
"CONTROLLER_BUTTON_DPAD_DOWN",
"CONTROLLER_BUTTON_DPAD_LEFT",
"CONTROLLER_BUTTON_DPAD_RIGHT",
"CONTROLLER_BUTTON_MAX",
"K_AC_BACK",
"KSCAN_AC_BACK",
"K_UNKNOWN",
"KSCAN_UNKNOWN",
"K_BACKSPACE",
"KSCAN_BACKSPACE",
"K_TAB",
"KSCAN_TAB",
"K_CLEAR",
"KSCAN_CLEAR",
"K_RETURN",
"KSCAN_RETURN",
"K_PAUSE",
"KSCAN_PAUSE",
"K_ESCAPE",
"KSCAN_ESCAPE",
"K_SPACE",
"KSCAN_SPACE",
"K_QUOTE",
"KSCAN_APOSTROPHE",
"K_COMMA",
"KSCAN_COMMA",
"K_MINUS",
"KSCAN_MINUS",
"K_PERIOD",
"KSCAN_PERIOD",
"K_SLASH",
"KSCAN_SLASH",
"K_0",
"KSCAN_0",
"K_1",
"KSCAN_1",
"K_2",
"KSCAN_2",
"K_3",
"KSCAN_3",
"K_4",
"KSCAN_4",
"K_5",
"KSCAN_5",
"K_6",
"KSCAN_6",
"K_7",
"KSCAN_7",
"K_8",
"KSCAN_8",
"K_9",
"KSCAN_9",
"K_SEMICOLON",
"KSCAN_SEMICOLON",
"K_EQUALS",
"KSCAN_EQUALS",
"K_LEFTBRACKET",
"KSCAN_LEFTBRACKET",
"K_BACKSLASH",
"KSCAN_BACKSLASH",
"K_RIGHTBRACKET",
"KSCAN_RIGHTBRACKET",
"K_BACKQUOTE",
"KSCAN_GRAVE",
"K_a",
"KSCAN_A",
"K_b",
"KSCAN_B",
"K_c",
"KSCAN_C",
"K_d",
"KSCAN_D",
"K_e",
"KSCAN_E",
"K_f",
"KSCAN_F",
"K_g",
"KSCAN_G",
"K_h",
"KSCAN_H",
"K_i",
"KSCAN_I",
"K_j",
"KSCAN_J",
"K_k",
"KSCAN_K",
"K_l",
"KSCAN_L",
"K_m",
"KSCAN_M",
"K_n",
"KSCAN_N",
"K_o",
"KSCAN_O",
"K_p",
"KSCAN_P",
"K_q",
"KSCAN_Q",
"K_r",
"KSCAN_R",
"K_s",
"KSCAN_S",
"K_t",
"KSCAN_T",
"K_u",
"KSCAN_U",
"K_v",
"KSCAN_V",
"K_w",
"KSCAN_W",
"K_x",
"KSCAN_X",
"K_y",
"KSCAN_Y",
"K_z",
"KSCAN_Z",
"K_DELETE",
"KSCAN_DELETE",
"K_KP_0",
"KSCAN_KP_0",
"K_KP_1",
"KSCAN_KP_1",
"K_KP_2",
"KSCAN_KP_2",
"K_KP_3",
"KSCAN_KP_3",
"K_KP_4",
"KSCAN_KP_4",
"K_KP_5",
"KSCAN_KP_5",
"K_KP_6",
"KSCAN_KP_6",
"K_KP_7",
"KSCAN_KP_7",
"K_KP_8",
"KSCAN_KP_8",
"K_KP_9",
"KSCAN_KP_9",
"K_KP0",
"KSCAN_KP0",
"K_KP1",
"KSCAN_KP1",
"K_KP2",
"KSCAN_KP2",
"K_KP3",
"KSCAN_KP3",
"K_KP4",
"KSCAN_KP4",
"K_KP5",
"KSCAN_KP5",
"K_KP6",
"KSCAN_KP6",
"K_KP7",
"KSCAN_KP7",
"K_KP8",
"KSCAN_KP8",
"K_KP9",
"KSCAN_KP9",
"K_KP_PERIOD",
"KSCAN_KP_PERIOD",
"K_KP_DIVIDE",
"KSCAN_KP_DIVIDE",
"K_KP_MULTIPLY",
"KSCAN_KP_MULTIPLY",
"K_KP_MINUS",
"KSCAN_KP_MINUS",
"K_KP_PLUS",
"KSCAN_KP_PLUS",
"K_KP_ENTER",
"KSCAN_KP_ENTER",
"K_KP_EQUALS",
"KSCAN_KP_EQUALS",
"K_UP",
"KSCAN_UP",
"K_DOWN",
"KSCAN_DOWN",
"K_RIGHT",
"KSCAN_RIGHT",
"K_LEFT",
"KSCAN_LEFT",
"K_INSERT",
"KSCAN_INSERT",
"K_HOME",
"KSCAN_HOME",
"K_END",
"KSCAN_END",
"K_PAGEUP",
"KSCAN_PAGEUP",
"K_PAGEDOWN",
"KSCAN_PAGEDOWN",
"K_F1",
"KSCAN_F1",
"K_F2",
"KSCAN_F2",
"K_F3",
"KSCAN_F3",
"K_F4",
"KSCAN_F4",
"K_F5",
"KSCAN_F5",
"K_F6",
"KSCAN_F6",
"K_F7",
"KSCAN_F7",
"K_F8",
"KSCAN_F8",
"K_F9",
"KSCAN_F9",
"K_F10",
"KSCAN_F10",
"K_F11",
"KSCAN_F11",
"K_F12",
"KSCAN_F12",
"K_F13",
"KSCAN_F13",
"K_F14",
"KSCAN_F14",
"K_F15",
"KSCAN_F15",
"K_NUMLOCKCLEAR",
"KSCAN_NUMLOCKCLEAR",
"K_NUMLOCK",
"KSCAN_NUMLOCK",
"K_CAPSLOCK",
"KSCAN_CAPSLOCK",
"K_SCROLLLOCK",
"KSCAN_SCROLLLOCK",
"K_SCROLLOCK",
"KSCAN_SCROLLOCK",
"K_RSHIFT",
"KSCAN_RSHIFT",
"K_LSHIFT",
"KSCAN_LSHIFT",
"K_RCTRL",
"KSCAN_RCTRL",
"K_LCTRL",
"KSCAN_LCTRL",
"K_RALT",
"KSCAN_RALT",
"K_LALT",
"KSCAN_LALT",
"K_RGUI",
"KSCAN_RGUI",
"K_RMETA",
"KSCAN_RMETA",
"K_LGUI",
"KSCAN_LGUI",
"K_LMETA",
"KSCAN_LMETA",
"K_LSUPER",
"KSCAN_LSUPER",
"K_RSUPER",
"KSCAN_RSUPER",
"K_MODE",
"KSCAN_MODE",
"K_HELP",
"KSCAN_HELP",
"K_PRINTSCREEN",
"KSCAN_PRINTSCREEN",
"K_PRINT",
"KSCAN_PRINT",
"K_SYSREQ",
"KSCAN_SYSREQ",
"K_BREAK",
"KSCAN_BREAK",
"K_MENU",
"KSCAN_MENU",
"K_POWER",
"KSCAN_POWER",
"K_CURRENCYUNIT",
"KSCAN_CURRENCYUNIT",
"K_CURRENCYSUBUNIT",
"KSCAN_CURRENCYSUBUNIT",
"K_EURO",
"KSCAN_EURO",
"KSCAN_INTERNATIONAL1",
"KSCAN_INTERNATIONAL2",
"KSCAN_INTERNATIONAL3",
"KSCAN_INTERNATIONAL4",
"KSCAN_INTERNATIONAL5",
"KSCAN_INTERNATIONAL6",
"KSCAN_INTERNATIONAL7",
"KSCAN_INTERNATIONAL8",
"KSCAN_INTERNATIONAL9",
"KSCAN_LANG1",
"KSCAN_LANG2",
"KSCAN_LANG3",
"KSCAN_LANG4",
"KSCAN_LANG5",
"KSCAN_LANG6",
"KSCAN_LANG7",
"KSCAN_LANG8",
"KSCAN_LANG9",
"KSCAN_NONUSBACKSLASH",
"KSCAN_NONUSHASH",
"K_EXCLAIM",
"K_QUOTEDBL",
"K_HASH",
"K_DOLLAR",
"K_AMPERSAND",
"K_PERCENT",
"K_LEFTPAREN",
"K_RIGHTPAREN",
"K_ASTERISK",
"K_PLUS",
"K_COLON",
"K_LESS",
"K_GREATER",
"K_QUESTION",
"K_AT",
"K_CARET",
"K_UNDERSCORE",
"KMOD_NONE",
"KMOD_LSHIFT",
"KMOD_RSHIFT",
"KMOD_LCTRL",
"KMOD_RCTRL",
"KMOD_LALT",
"KMOD_RALT",
"KMOD_LGUI",
"KMOD_LMETA",
"KMOD_RGUI",
"KMOD_RMETA",
"KMOD_NUM",
"KMOD_CAPS",
"KMOD_MODE",
"KMOD_CTRL",
"KMOD_SHIFT",
"KMOD_ALT",
"KMOD_GUI",
"KMOD_META",
"APPMOUSEFOCUS",
"APPINPUTFOCUS",
"APPACTIVE",
"SYSTEM_CURSOR_ARROW",
"SYSTEM_CURSOR_IBEAM",
"SYSTEM_CURSOR_WAIT",
"SYSTEM_CURSOR_CROSSHAIR",
"SYSTEM_CURSOR_WAITARROW",
"SYSTEM_CURSOR_SIZENWSE",
"SYSTEM_CURSOR_SIZENESW",
"SYSTEM_CURSOR_SIZEWE",
"SYSTEM_CURSOR_SIZENS",
"SYSTEM_CURSOR_SIZEALL",
"SYSTEM_CURSOR_NO",
"SYSTEM_CURSOR_HAND",
"USEREVENT_DROPFILE",
"DIRECTION_LTR",
"DIRECTION_RTL",
"DIRECTION_TTB",
"DIRECTION_BTT",
"FONT_LEFT",
"FONT_CENTER",
"FONT_RIGHT",
"IS_CE",
"NULL_VIDEODRIVER",
"WINDOWPOS_UNDEFINED",
"WINDOWPOS_CENTERED",
"FLASH_CANCEL",
"FLASH_BRIEFLY",
"FLASH_UNTIL_FOCUSED",
]
@@ -1,4 +1,4 @@
# pygame-ce - Python Game Library
# pygame - Python Game Library
# Copyright (C) 2000-2003 Pete Shinners
#
# This library is free software; you can redistribute it and/or
@@ -18,59 +18,21 @@
# Pete Shinners
# pete@shinners.org
"""Pygame module for cursor resources.
"""Set of cursor resources available for use. These cursors come
in a sequence of values that are needed as the arguments for
pygame.mouse.set_cursor(). To dereference the sequence in place
and create the cursor in one step, call like this:
pygame.mouse.set_cursor(*pygame.cursors.arrow).
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`.
Here is a list of available cursors:
arrow, diamond, ball, broken_x, tri_left, tri_right
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.
There is also a sample string cursor named 'thickarrow_strings'.
The compile() function can convert these string cursors into cursor byte data that can be used to
create Cursor objects.
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``
* ``pygame.cursors.ball``
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.cursors.textmarker_strings``
Alternately, you can also create Cursor objects using surfaces or cursors constants,
such as pygame.SYSTEM_CURSOR_ARROW.
"""
import pygame
@@ -92,95 +54,21 @@ _cursor_id_table = {
class Cursor:
"""Pygame object representing a 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`` are (x,y) coordinates that determine 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.
.. versionaddedold:: 2.0.1
"""
def __init__(self, *args):
self.type = "system"
"""Get the cursor type.
"""Cursor(size, hotspot, xormasks, andmasks) -> Cursor
Cursor(hotspot, Surface) -> Cursor
Cursor(constant) -> Cursor
Cursor(Cursor) -> copies the Cursor object passed as an argument
Cursor() -> Cursor
The type will be ``"system"``, ``"bitmap"``, or ``"color"``.
"""
self.data = tuple()
"""Get the cursor data.
pygame object for representing cursors
Returns the data that was used to create this cursor object, wrapped up in a tuple.
"""
You can initialize a cursor from a system cursor or use the
constructor on an existing Cursor object, which will copy it.
Providing a Surface instance will render the cursor displayed
as that Surface when used.
These Surfaces may use other colors than black and white."""
if len(args) == 0:
self.type = "system"
self.data = (pygame.SYSTEM_CURSOR_ARROW,)
@@ -218,14 +106,12 @@ class Cursor:
def __ne__(self, other):
return not self.__eq__(other)
def copy(self):
"""Copy the current cursor.
Returns a new Cursor object with the same data and hotspot as the original.
"""
def __copy__(self):
"""Clone the current Cursor object.
You can do the same thing by doing Cursor(Cursor)."""
return self.__class__(self)
__copy__ = copy
copy = __copy__
def __hash__(self):
return hash(tuple([self.type] + list(self.data)))
@@ -829,51 +715,25 @@ textmarker_strings = (
def compile(strings, black="X", white=".", xor="o"):
"""Create binary cursor data from simple strings.
"""pygame.cursors.compile(strings, black, white, xor) -> data, mask
compile cursor strings into cursor data
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.
This takes a set of strings with equal length and computes
the binary data for that cursor. The string widths must be
divisible by 8.
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
The black and white arguments are single letter strings that
tells which characters will represent black pixels, and which
characters represent white pixels. All other characters are
considered clear.
Some systems 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 ",
" ",
" ",
" ")
This returns a tuple containing the cursor data and cursor mask
data. Both these arguments are used when setting a cursor with
pygame.mouse.set_cursor().
"""
# first check for consistent lengths
size = len(strings[0]), len(strings)
@@ -913,21 +773,12 @@ def compile(strings, black="X", white=".", xor="o"):
def load_xbm(curs, mask):
"""Load cursor data from an XBM file.
"""pygame.cursors.load_xbm(cursorfile, maskfile) -> cursor_args
reads a pair of XBM files into set_cursor arguments
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 curs and mask 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.
Arguments can either be filenames or filelike objects
with the readlines method. Not largely tested, but
should work with typical XBM files.
"""
def bitswap(num):
@@ -1,13 +1,13 @@
from collections.abc import Iterator
from typing import Any, Literal, TypeAlias, overload
from typing import Any, Iterator, Sequence, Tuple, Union, overload
from pygame.surface import Surface
from pygame.typing import FileLike, IntPoint, SequenceLike
_SmallString: TypeAlias = tuple[
from ._common import FileArg, Literal
_Small_string = Tuple[
str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str
]
_BigString: TypeAlias = tuple[
_Big_string = Tuple[
str,
str,
str,
@@ -40,21 +40,21 @@ broken_x: Cursor
tri_left: Cursor
tri_right: Cursor
ball: Cursor
thickarrow_strings: _BigString
sizer_x_strings: _SmallString
sizer_y_strings: _BigString
sizer_xy_strings: _SmallString
textmarker_strings: _SmallString
thickarrow_strings: _Big_string
sizer_x_strings: _Small_string
sizer_y_strings: _Big_string
sizer_xy_strings: _Small_string
textmarker_strings: _Small_string
def compile(
strings: SequenceLike[str],
strings: Sequence[str],
black: str = "X",
white: str = ".",
xor: str = "o",
) -> tuple[tuple[int, ...], tuple[int, ...]]: ...
) -> Tuple[Tuple[int, ...], Tuple[int, ...]]: ...
def load_xbm(
curs: FileLike, mask: FileLike
) -> tuple[tuple[int, int], tuple[int, int], tuple[int, ...], tuple[int, ...]]: ...
curs: FileArg, mask: FileArg
) -> Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, ...], Tuple[int, ...]]: ...
class Cursor:
@overload
@@ -64,26 +64,28 @@ class Cursor:
@overload
def __init__(
self,
size: IntPoint,
hotspot: IntPoint,
xormasks: SequenceLike[int],
andmasks: SequenceLike[int],
size: Union[Tuple[int, int], Sequence[int]],
hotspot: Union[Tuple[int, int], Sequence[int]],
xormasks: Sequence[int],
andmasks: Sequence[int],
) -> None: ...
@overload
def __init__(
self,
hotspot: IntPoint,
hotspot: Union[Tuple[int, int], Sequence[int]],
surface: Surface,
) -> None: ...
def __iter__(self) -> Iterator[Any]: ...
def __len__(self) -> int: ...
def __copy__(self) -> Cursor: ...
def __hash__(self) -> int: ...
def __getitem__(self, index: int) -> int | IntPoint | Surface: ...
def copy(self) -> Cursor: ...
def __getitem__(
self, index: int
) -> Union[int, Tuple[int, int], Sequence[int], Surface]: ...
copy = __copy__
type: Literal["system", "color", "bitmap"]
data: (
tuple[int]
| tuple[tuple[int, int], tuple[int, int], tuple[int, ...], tuple[int, ...]]
| tuple[IntPoint, Surface]
)
data: Union[
Tuple[int],
Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, ...], Tuple[int, ...]],
Tuple[Union[Tuple[int, int], Sequence[int]], Surface],
]
@@ -1,869 +1,77 @@
"""Pygame module to control the display window and screen.
from typing import Union, Tuple, List, Optional, Dict, Sequence, overload
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
graphics 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 to be resizable with the
``pygame.RESIZABLE`` flag, ``pygame.VIDEORESIZE`` event(s) will be sent when the
user adjusts the window dimensions. Depending on your platform, this may be
multiple gradual events or one event at the end (Windows). 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).
"""
from collections.abc import Iterable
from typing import Literal, overload
from pygame._sdl2 import Window
from pygame.constants import FULLSCREEN
from pygame.surface import Surface
from pygame.typing import (
ColorLike,
IntPoint,
Point,
RectLike,
SequenceLike,
)
from typing_extensions import deprecated # added in 3.13
from pygame.constants import FULLSCREEN
from ._common import Coordinate, RectValue, ColorValue, RGBAOutput
class _VidInfo:
@property
def hw(self) -> int: ...
@property
def wm(self) -> int: ...
@property
def video_mem(self) -> int: ...
@property
def bitsize(self) -> int: ...
@property
def bytesize(self) -> int: ...
@property
def masks(self) -> tuple[int, int, int, int]: ...
@property
def shifts(self) -> tuple[int, int, int, int]: ...
@property
def losses(self) -> tuple[int, int, int, int]: ...
@property
def blit_hw(self) -> int: ...
@property
def blit_hw_CC(self) -> int: ...
@property
def blit_hw_A(self) -> int: ...
@property
def blit_sw(self) -> int: ...
@property
def blit_sw_CC(self) -> int: ...
@property
def blit_sw_A(self) -> int: ...
@property
def current_h(self) -> int: ...
@property
def current_w(self) -> int: ...
@property
def pixel_format(self) -> str: ...
def init() -> None:
"""Initialize the display module.
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, wayland
:note: On wayland desktops, pygame-ce may choose to use the X11 video driver to run on Xwayland.
This behaviour is determined by the SDL library and might change in the future, so it's suggested
to account for this and not rely on the default behavior. The Wayland video driver can be forced
by setting the ``SDL_VIDEODRIVER`` environment variable to ``"wayland"``
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.
.. versionchanged:: 2.5.0 the manylinux wheels distributed by us now support the ``wayland`` videodriver
"""
def quit() -> None:
"""Uninitialize the display module.
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.
"""
def get_init() -> bool:
"""Returns True if the display module has been initialized.
Returns True if the :mod:`pygame.display` module is currently initialized.
"""
hw: int
wm: int
video_mem: int
bitsize: int
bytesize: int
masks: RGBAOutput
shifts: RGBAOutput
losses: RGBAOutput
blit_hw: int
blit_hw_CC: int
blit_hw_A: int
blit_sw: int
blit_sw_CC: int
blit_sw_A: int
current_h: int
current_w: int
def init() -> None: ...
def quit() -> None: ...
def get_init() -> bool: ...
def set_mode(
size: Point = (0, 0),
size: Coordinate = (0, 0),
flags: int = 0,
depth: int = 0,
display: int = 0,
vsync: int = 0,
) -> Surface:
"""Initialize a window or screen for display.
This will create a window or display output and return 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)``, 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.
Since pygame 2, the depth argument is ignored, in favour of the best
and fastest one. It also raises a deprecation warning since pygame-ce
2.4.0 if the passed in depth is not 0 or the one pygame selects.
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 only applicable with 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
.. versionaddedold:: 2.0.0 ``SCALED``, ``SHOWN`` and ``HIDDEN``
.. versionaddedold:: 2.0.0 ``vsync`` parameter
By setting the ``vsync`` parameter to ``1``, it is possible to get a display
with vertical sync at a constant frame rate determined by the monitor and
graphics drivers. Subsequent calls to :func:`pygame.display.flip()` or
:func:`pygame.display.update()` will block (i.e. *wait*) until the screen
has refreshed, in order to prevent "screen tearing"
<https://en.wikipedia.org/wiki/Screen_tearing>.
Be careful when using this feature together with ``pygame.time.Clock`` or
:func:`pygame.time.delay()`, as multiple forms of waiting and frame rate
limiting may interact to cause skipped frames.
The request only works when graphics acceleration is available on the
system. The exact behaviour depends on the hardware and driver
configuration. When ``vsync`` is requested, but unavailable,
``set_mode()`` may raise an exception.
Setting the ``vsync`` parameter to ``-1`` in conjunction with ``OPENGL``
will request the OpenGL-specific feature "adaptive vsync" <https://www.khronos.org/opengl/wiki/Swap_Interval#Adaptive_Vsync>.
Here is an example usage of a call
to ``set_mode()`` that may give you a display with vsync:
::
flags = pygame.OPENGL | pygame.FULLSCREEN
try:
window_surface = pygame.display.set_mode((1920, 1080), flags, vsync=1)
vsync_success=True
except pygame.error:
window_surface = pygame.display.set_mode((1920, 1080), flags)
vsync_success=False
.. versionaddedold:: 2.0.0 ``vsync`` parameter
.. versionchanged:: 2.2.0 passing ``vsync`` can raise an exception
.. versionchanged:: 2.2.0 explicit request for "adaptive vsync"
.. versionchanged:: 2.2.0 ``vsync=1`` does not require ``SCALED`` or ``OPENGL``
.. deprecated:: 2.4.0 The depth argument is ignored, and will be set to the optimal value
.. versionchanged:: 2.5.0 No longer emits warning when running on xwayland, see :func:`pygame.display.init` for details on running on wayland directly
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.
.. versionchangedold:: 1.9.5 ``display`` argument added
.. versionchanged:: 2.1.3
pygame now ensures that subsequent calls to this function clears the
window to black. On older versions, this was an implementation detail
on the major platforms this function was tested with.
"""
def get_surface() -> Surface | None:
"""Get a reference to the currently set display surface.
Return a reference to the currently set display Surface. If no display mode
has been set this will return None.
"""
def flip() -> None:
"""Update the full display Surface to the screen.
This will update the contents of the entire display.
When using an ``pygame.OPENGL`` display mode this will perform a gl buffer
swap.
"""
) -> Surface: ...
def get_surface() -> Surface: ...
def flip() -> None: ...
@overload
def update() -> None: ...
def update(
rectangle: Optional[Union[RectValue, Sequence[Optional[RectValue]]]] = None
) -> None: ...
@overload
def update(rectangle: RectLike | None, /) -> None: ...
def update(x: int, y: int, w: int, h: int) -> None: ...
@overload
def update(rectangles: Iterable[RectLike | None], /) -> None: ...
@overload
def update(x: float, y: float, w: float, h: float, /) -> None: ...
@overload
def update(xy: Point, wh: Point, /) -> None: ...
def update(*args): # type: ignore
"""Update all, or a portion, of the display. For non-OpenGL displays.
For non OpenGL display Surfaces, this function is very similar to
``pygame.display.flip()`` with an optional parameter that allows only
portions of the display surface to be updated, instead of the entire area.
If no argument is passed it updates the entire Surface area like
``pygame.display.flip()``.
.. note:: 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 an iterable of rectangles.
Generally you do not want to pass an iterable of rectangles as there is a
performance cost per rectangle passed to the function. On modern hardware,
after a very small number of rectangles passed in, the per-rectangle cost
will exceed the saving of updating less pixels. In most applications it is
simply more efficient to update the entire display surface at once, it also
means you do not need to keep track of a list of rectangles for each call
to update.
If passing an iterable 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.
.. versionchanged:: 2.5.1 Added support for passing an iterable, previously only sequence was allowed
"""
def get_driver() -> str:
"""Get the name of the pygame display backend.
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.init()`` to see some of the common options.
"""
def Info() -> _VidInfo:
"""Create a video display information object.
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:
.. code-block:: text
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. They are -1 on error.
pixel_format: The pixel format of the display Surface as a string.
E.g PIXELFORMAT_RGB888.
.. versionchanged:: 2.4.0 ``pixel_format`` attribute added.
"""
def get_wm_info() -> dict[str, int]:
"""Get information about the current windowing system.
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.
.. versionaddedold:: 1.7.1
"""
def get_desktop_sizes() -> list[tuple[int, int]]:
"""Get sizes of active desktops.
This function returns the sizes of the currently 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.
.. versionaddedold:: 2.0.0
"""
def update(xy: Coordinate, wh: Coordinate) -> None: ...
def get_driver() -> str: ...
def Info() -> _VidInfo: ...
def get_wm_info() -> Dict[str, int]: ...
def list_modes(
depth: int = 0,
flags: int = FULLSCREEN,
display: int = 0,
) -> list[tuple[int, int]]:
"""Get list of available fullscreen modes.
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).
.. versionchangedold:: 1.9.5 ``display`` argument added
"""
) -> List[Tuple[int, int]]: ...
def mode_ok(
size: IntPoint,
size: Union[Sequence[int], Tuple[int, int]],
flags: int = 0,
depth: int = 0,
display: int = 0,
) -> int:
"""Pick the best color depth for a display mode.
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.
.. versionchangedold:: 1.9.5 ``display`` argument added
"""
def gl_get_attribute(flag: int, /) -> int:
"""Get the value for an OpenGL flag for the current display.
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.
"""
def gl_set_attribute(flag: int, value: int, /) -> None:
"""Request an OpenGL display attribute for the display mode.
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.
.. versionaddedold:: 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.
"""
def get_active() -> bool:
"""Returns True when the display is active on the screen.
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.
"""
def iconify() -> bool:
"""Iconify the display surface.
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 receives a
``WINDOWEVENT_MINIMIZED`` event when the window has been iconified on pygame 2.
"""
def toggle_fullscreen() -> int:
"""Switch between fullscreen and windowed displays.
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 #1221 <https://github.com/pygame-community/pygame-ce/issues/1221>`_.
"""
@deprecated("since 2.1.4. Removed in SDL3")
def set_gamma(red: float, green: float = ..., blue: float = ..., /) -> bool:
"""Change the hardware gamma ramps.
DEPRECATED: This functionality will go away in SDL3.
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.
.. deprecated:: 2.1.4
"""
@deprecated("since 2.1.4. Removed in SDL3")
) -> int: ...
def gl_get_attribute(flag: int) -> int: ...
def gl_set_attribute(flag: int, value: int) -> None: ...
def get_active() -> bool: ...
def iconify() -> bool: ...
def toggle_fullscreen() -> int: ...
def set_gamma(red: float, green: float = ..., blue: float = ...) -> int: ...
def set_gamma_ramp(
red: SequenceLike[int], green: SequenceLike[int], blue: SequenceLike[int], /
) -> bool:
"""Change the hardware gamma ramps with a custom lookup.
DEPRECATED: This functionality will go away in SDL3.
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``.
.. deprecated:: 2.1.4
"""
def set_icon(surface: Surface, /) -> None:
"""Change the system image for the display window.
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.
"""
def set_caption(title: str, icontitle: str | None = None, /) -> None:
"""Set the current window caption.
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.
"""
def get_caption() -> tuple[str, str]:
"""Get the current window caption.
Returns the title and icontitle of the display window. In pygame 2.x
these will always be the same value.
"""
def set_palette(palette: SequenceLike[ColorLike], /) -> None:
"""Set the display color palette for indexed displays.
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.
"""
def get_num_displays() -> int:
"""Return the number of displays.
Returns the number of available displays. This is always 1 if
:func:`pygame.get_sdl_version()` returns a major version number below 2.
.. versionaddedold:: 1.9.5
"""
def get_window_size() -> tuple[int, int]:
"""Return the size of the window or screen.
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.
.. versionaddedold:: 2.0.0
"""
def get_window_position() -> tuple[int, int]:
"""Return the position of the window or screen.
Returns the position of the window initialized with :func:`pygame.display.set_mode()`.
The position will change when the user moves the window or when the
position is set manually with :func:`pygame.display.set_window_position()`.
Coordinates could be negative or outside the desktop size bounds. The
position is relative to the topleft of the primary monitor and the y coordinate
ignores the window frame.
.. versionadded:: 2.5.0
"""
def set_window_position(position: Point) -> None:
"""Set the current window position.
Sets the position of the window initialized with :func:`pygame.display.set_mode()`.
This differs from updating environment variables as this function can be
called after the display has been initialised. The position is expected to
be relative to the topleft of the primary monitor. The y coordinate will
ignore the window frame (y = 0 means the frame is hidden). The user will
still be able to move the window after this call. See also
:func:`pygame.display.get_window_position()`.
.. note:: This function is not supported on some video drivers (like wayland)
and a :exc:`pygame.error` exception may be raised in such cases.
.. versionadded:: 2.5.0
"""
def get_allow_screensaver() -> bool:
"""Return whether the screensaver is allowed to run.
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.
.. versionaddedold:: 2.0.0
"""
def set_allow_screensaver(value: bool = True) -> None:
"""Set whether the screensaver may run.
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.
.. versionaddedold:: 2.0.0
"""
def is_fullscreen() -> bool:
"""Returns True if the pygame window created by pygame.display.set_mode() is in full-screen mode.
Edge cases:
If the window is in windowed mode, but maximized, this will return `False`.
If the window is in "borderless fullscreen" mode, this will return `True`.
.. versionadded:: 2.2.0
"""
def is_vsync() -> bool:
"""Returns True if vertical synchronisation for pygame.display.flip() and pygame.display.update() is enabled.
.. versionadded:: 2.2.0
"""
def get_current_refresh_rate() -> int:
"""Returns the screen refresh rate or 0 if unknown.
The screen refresh rate for the current window. In windowed mode, this
should be equal to the refresh rate of the desktop the window is on.
If no window is open, an exception is raised.
When a constant refresh rate cannot be determined, 0 is returned.
.. versionadded:: 2.2.0
"""
def get_desktop_refresh_rates() -> list[int]:
"""Returns the screen refresh rates for all displays (in windowed mode).
If the current window is in full-screen mode, the actual refresh rate for
that window can differ.
This is safe to call when no window is open (i.e. before any calls to
:func:`pygame.display.set_mode()`
When a constant refresh rate cannot be determined, 0 is returned for that
desktop.
.. versionadded:: 2.2.0
"""
def message_box(
title: str,
message: str | None = None,
message_type: Literal["info", "warn", "error"] = "info",
parent_window: Window | None = None,
buttons: SequenceLike[str] = ("OK",),
return_button: int = 0,
escape_button: int | None = None,
) -> int:
"""Create a native GUI message box.
:param str title: A title string.
:param str message: A message string. If this parameter is set to ``None``, the message will be the title.
:param str message_type: Set the type of message_box, could be ``"info"``, ``"warn"`` or ``"error"``.
:param pygame.Window parent_window: The parent window of the message box.
:param tuple buttons: An optional sequence of button name strings to show to the user.
:param int return_button: Button index to use if the return key is hit, ``0`` by default.
:param int escape_button: Button index to use if the escape key is hit, ``None`` for no button linked by default.
:return: The index of the button that was pushed.
This function should be called on the thread that ``set_mode()`` is called.
It will block execution of that thread until the user clicks a button or
closes the message_box.
This function may be called at any time, even before ``pygame.init()``.
Negative values of ``return_button`` and ``escape_button`` are allowed
just like standard Python list indexing.
.. versionadded:: 2.4.0
"""
red: Sequence[int], green: Sequence[int], blue: Sequence[int]
) -> int: ...
def set_icon(surface: Surface) -> None: ...
def set_caption(title: str, icontitle: Optional[str] = None) -> None: ...
def get_caption() -> Tuple[str, str]: ...
def set_palette(palette: Sequence[ColorValue]) -> None: ...
def get_num_displays() -> int: ...
def get_window_size() -> Tuple[int, int]: ...
def get_allow_screensaver() -> bool: ...
def set_allow_screensaver(value: bool = True) -> None: ...
def get_desktop_sizes() -> List[Tuple[int, int]]: ...
def is_fullscreen() -> bool: ...
@@ -1,10 +0,0 @@
# python -m pygame.docs
from pathlib import Path
PKG_DIR = Path(__file__).absolute().parent / "generated"
# for test suite to confirm pygame-ce built with local docs
def has_local_docs():
return PKG_DIR.exists()
@@ -1,17 +1,37 @@
import platform
# python -m pygame.docs
# use relative import here and not absolute, so that `python -m docs` works at
# development time
from .serve import main as serve
from .static import main as static
import os
import webbrowser
from urllib.parse import quote, urlunparse
def main():
if platform.system() == "Linux":
serve()
def _iterpath(path):
path, last = os.path.split(path)
if last:
yield from _iterpath(path)
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 = f"{drive}/{url_path}"
url = urlunparse(("file", "", url_path, "", "", ""))
else:
static()
url = "https://www.pygame.org/docs/"
webbrowser.open(url)
if __name__ == "__main__":
main()
open_docs()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

@@ -12,14 +12,12 @@ pygame C API
c_api/display.rst
c_api/event.rst
c_api/freetype.rst
c_api/joystick.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
c_api/window.rst
src_c/include/ contains header files for applications
@@ -1,5 +1,5 @@
Pygame-ce Front Page
====================
Pygame Front Page
=================
.. toctree::
:maxdepth: 2
@@ -7,8 +7,9 @@ Pygame-ce Front Page
:hidden:
ref/*
tutorials/en/*
tutorials/es/*
tut/*
tut/en/**/*
tut/ko/**/*
c_api
filepaths
logos
@@ -16,10 +17,9 @@ Pygame-ce Front Page
Quick start
-----------
Welcome to pygame-ce! Once you've got pygame-ce installed
(:code:`pip install pygame-ce` or :code:`pip3 install pygame-ce` for most
people), the next question is how to get a game loop running. Pygame-ce,
unlike some other libraries, gives you full control of program
Welcome to pygame! Once you've got pygame installed (:code:`pip install pygame` or
:code:`pip3 install pygame` for most people), the next question is how to get a game
loop running. Pygame, unlike some other libraries, gives you full control of program
execution. That freedom means it is easy to mess up in your initial steps.
Here is a good example of a basic setup (opens the window, updates the screen, and handles events)--
@@ -32,39 +32,9 @@ Here is a slightly more fleshed out example, which shows you how to move somethi
.. literalinclude:: ref/code_examples/base_script_example.py
For more in depth reference, check out the :ref:`tutorials-reference-label`
section below, or reference the API documentation by module.
Experimental modules
--------------------
Experimental modules are work in progress, this is why you should refrain from relying on any features
provided by these modules, as they are subject to change or removal without prior notice.
If you want to test these experimental modules, you might want to understand how you import
them, this is how you can do it:
.. code-block:: python
from pygame import experimental_module
# Or for specific modules like _sdl2.controller
from pygame._sdl2 import controller
# Or
import pygame.experimental_module
Don't forget to report us any problem with the experimental features on `github`_ so we can easily
turn them to stable API in the future ^^.
**Below is currently the list of experimental modules :**
:doc:`ref/geometry`
Pygame module for the Circle, Line, and Polygon objects.
:doc:`ref/sdl2_controller`
Pygame module to work with controllers.
:doc:`ref/sdl2_video`
Pygame module for porting new SDL video systems.
.. _github: https://github.com/pygame-community/pygame-ce
section below, check out a video tutorial (`I'm a fan of this one
<https://www.youtube.com/watch?v=AY9MnQ4x3zk>`_), or reference the API
documentation by module.
Documents
---------
@@ -72,6 +42,10 @@ 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.
:doc:`filepaths`
How pygame handles file system paths.
@@ -89,65 +63,52 @@ Documents
Tutorials
---------
| `Master Python by making 5 games [the new ultimate introduction to pygame] <https://www.youtube.com/watch?v=8OMghdHP-zs>`_
| YouTube video by Clear Code.
: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.
| `Pygame in 18 Minutes <https://www.youtube.com/watch?v=blLLtdv4tvo>`_
| YouTube video by DaFluffyPotato.
| `Introduction to Pygame-ce, 2D game programming <https://github.com/adamsralf/pygame_book/blob/main/00%20pygamece.pdf>`_
| Book by Ralf Adams.
:doc:`Newbie Guide <tutorials/en/newbie-guide>`
A list of thirteen helpful tips for people to get comfortable using pygame.
:doc:`Import and Initialize <tutorials/en/import-init>`
: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? <tutorials/en/move-it>`
: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 <tutorials/en/chimp-explanation>`
: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:`What is Premultiplied Alpha? <tutorials/en/premultiplied-alpha>`
An explanation of alpha compositing and the advantages of using premultiplied alpha.
:doc:`Sprite Module Introduction <tutorials/en/intro-to-sprites>`
: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:`Introduction to Pygame <tutorials/en/intro-to-pygame>`
An introduction to the basics of pygame.
This is written for users of Python and appeared in volume two of the Py magazine.
:doc:`Surfarray Introduction <tutorials/en/intro-to-surfarray>`
: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 <tutorials/en/intro-to-camera>`
: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:`Making Games Tutorial <tutorials/en/make-games>`
: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 <tutorials/en/display-modes>`
:doc:`Display Modes <tut/DisplayModes>`
Getting a display surface for the screen.
:doc:`Tutorial de Pygame - Ejemplo del Chimpancé, Línea Por Línea <tutorials/es/ChimpanceLineaporLinea>`
Los ejemplos de pygame incluyen un sencillo programa con un puño interactivo y un chimpancé.
Está inspirado en el molesto banner de flash de principios de la década de 2000.
Este tutorial examina cada línea de código utilizada en el ejemplo.
:doc:`한국어 튜토리얼 (Korean Tutorial) <tut/ko/빨간블록 검은블록/개요>`
빨간블록 검은블록
Reference
---------
@@ -239,18 +200,14 @@ Reference
:doc:`ref/transform`
Resize and move images.
:doc:`ref/typing`
Provide common typehints
:doc:`ref/window`
Pygame object that handles a window.
:doc:`pygame C API <c_api>`
The C api shared amongst pygame extension modules.
:ref:`search`
Search pygame documents by keyword.
.. _Readme: https://github.com/pygame-community/pygame-ce#readme
.. _Readme: ../wiki/about
.. _Install: ../wiki/GettingStarted#Pygame%20Installation
.. _LGPL License: LGPL.txt
@@ -1,58 +1,47 @@
*************************************************
Pygame CE Logos Page
Pygame Logos Page
*************************************************
Pygame CE Logos
===============
Pygame Logos
============
These logos are available for use in your own game projects.
Please put them up wherever you see fit.
The pygame-ce logo and its variants were created by Mega-JC and kadir014 on June 30, 2024.
.. container:: fullwidth
.. image:: _static/pygame_ce_logo.webp
| `pygame_ce_logo.svg <_static/pygame_ce_logo.svg>`_
| `pygame_ce_logo.webp <_static/pygame_ce_logo.webp>`_ - 1560 x 800
.. image:: _static/pygame_ce_lofi.webp
| `pygame_ce_lofi.svg <_static/pygame_ce_lofi.svg>`_
| `pygame_ce_lofi.webp <_static/pygame_ce_lofi.webp>`_ - 1560 x 800
.. image:: _static/pygame_ce_powered.webp
| `pygame_ce_powered.svg <_static/pygame_ce_powered.svg>`_
| `pygame_ce_powered.webp <_static/pygame_ce_powered.webp>`_ - 1560 x 824
.. image:: _static/pygame_ce_tiny.webp
| `pygame_ce_tiny.webp <_static/pygame_ce_tiny.webp>`_ - 214 x 110
.. image:: _static/pygame_ce_powered_lowres.webp
| `pygame_ce_powered_lowres.webp <_static/pygame_ce_powered_lowres.webp>`_ - 101 x 53
Upstream & legacy logos
-----------------------
The pygame logo was originally created
by TheCorruptor on July 29, 2001.
It was upscaled alongside its "LoFi" and "Powered" variants by Mega-JC on
Please put them up wherever you see fit. The logo was created
by TheCorruptor on July 29, 2001 and upscaled by Mega_JC on
August 29, 2021.
.. container:: fullwidth
| `upstream_logos.zip <_static/upstream_logos.zip>`_ - 314 KB
.. image:: _static/pygame_logo.png
| `pygame_logo.svg <_static/pygame_logo.svg>`_
| `pygame_logo.png <_static/pygame_logo.png>`_ - 1561 x 438
.. image:: _static/pygame_lofi.png
| `pygame_lofi.svg <_static/pygame_lofi.svg>`_
| `pygame_lofi.png <_static/pygame_lofi.png>`_ - 1561 x 438
.. image:: _static/pygame_powered.png
| `pygame_powered.svg <_static/pygame_powered.svg>`_
| `pygame_powered.png <_static/pygame_powered.png>`_ - 1617 x 640
.. image:: _static/pygame_tiny.png
| `pygame_tiny.png <_static/pygame_tiny.png>`_ - 214 x 60
.. image:: _static/pygame_powered_lowres.png
| `pygame_powered_lowres.png <_static/pygame_powered_lowres.png>`_ - 101 x 40
There is a higher resolution layered photoshop image
available `here <https://www.pygame.org/ftp/pygame_ce_logo.psd>`_. *(1.3 MB)*
available `here <https://www.pygame.org/ftp/pygame_logo.psd>`_. *(1.3 MB)*
Legacy logos
------------
.. container:: fullwidth
| `legacy_logos.zip <_static/legacy_logos.zip>`_ - 50.1 KB
`legacy_logos.zip <_static/legacy_logos.zip>`_ - 50.1 KB
@@ -10,7 +10,7 @@
.. class:: BufferProxy
| :sl:`pygame object to export a surface buffer through an array protocol`
| :sg:`BufferProxy(parent) -> BufferProxy`
| :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.
@@ -47,8 +47,8 @@
``"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"``.
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
@@ -57,7 +57,7 @@
``"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``.
``"parent"`` object if given, otherwise ``None``.
The callback is useful for setting a lock on the parent.
``"after"`` : callable : (optional)
@@ -65,18 +65,18 @@
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.
.. versionaddedold:: 1.8.0
.. versionextendedold:: 1.9.2
.. versionadded:: 1.8.0
.. versionextended:: 1.9.2
.. attribute:: parent
| :sl:`Return wrapped exporting object.`
| :sg:`parent -> Surface`
| :sg:`parent -> parent`
| :sg:`parent -> <parent>`
The :class:`Surface` which returned the :class:`BufferProxy` object or
the object passed to a :class:`BufferProxy` call.
@@ -8,12 +8,14 @@
| :sl:`pygame module for camera use`
.. note::
Use import pygame.camera before using this module.
Pygame currently supports Linux (V4L2) and Windows (MSMF) cameras natively,
with wider platform support available via an integrated OpenCV backend.
.. versionaddedold:: 2.0.2 Windows native camera support
.. versionaddedold:: 2.0.3 New OpenCV backends
.. versionchanged:: 2.3.0 Removed deprecated vidcapture 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.
@@ -44,7 +46,7 @@ The Bayer to ``RGB`` function is based on:
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
.. versionaddedold:: 1.9.0
New in pygame 1.9.0.
.. function:: init
@@ -58,7 +60,7 @@ The Bayer to ``RGB`` function is based on:
want into this function. More about backends in
:func:`get_backends()`.
.. versionchangedold:: 2.0.3 Option to explicitly select backend
.. versionchanged:: 2.0.3 Option to explicitly select backend
.. ## pygame.camera.init ##
@@ -79,28 +81,30 @@ The Bayer to ``RGB`` function is based on:
_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 backend,
the module will need to be installed on your system.
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"
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.
.. versionaddedold:: 2.0.3
.. versionadded:: 2.0.3
.. ## pygame.camera.get_backends ##
.. function:: colorspace
| :sl:`Surface colorspace conversion`
| :sg:`colorspace(surface, format, dest_surface = None, /) -> Surface`
| :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
@@ -131,8 +135,8 @@ The Bayer to ``RGB`` function is based on:
| :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.
"/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:
@@ -214,14 +218,14 @@ The Bayer to ``RGB`` function is based on:
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.
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`
| :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
@@ -5,5 +5,279 @@
.. currentmodule:: pygame
.. autopgclass:: Color
:members:
.. 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 operations — binary
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], ``L`` = [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`
DEPRECATED: You may unpack the values you need like so,
``r, g, b, _ = pygame.Color(100, 100, 100)``
If you only want r, g and b
Or
``r, g, *_ = pygame.Color(100, 100, 100)``
if you only want r and g
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)``.
.. deprecated:: 2.1.3
.. versionadded:: 1.9.0
.. ## Color.set_length ##
.. method:: grayscale
| :sl:`returns the grayscale of a Color`
| :sg:`grayscale() -> Color`
Returns a Color which represents the grayscaled version of self using the luminosity formula which weights red, green and blue according to their wavelengths..
.. ## Color.grayscale ##
.. 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 ##
@@ -675,7 +675,7 @@ Named Colors
:doc:`color` lets you specify any of these named colors when creating a new
``pygame.Color`` (taken from the
`colordict module <https://github.com/pygame-community/pygame-ce/blob/main/src_py/colordict.py>`_).
`colordict module <https://github.com/pygame/pygame/blob/main/src_py/colordict.py>`_).
.. role:: aliceblue
.. role:: antiquewhite
@@ -3,8 +3,248 @@
:mod:`pygame.cursors`
=====================
.. autopgmodule:: pygame.cursors
:members:
.. 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)
@@ -3,5 +3,735 @@
:mod:`pygame.display`
=====================
.. autopgmodule:: pygame.display
:members:
.. 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
graphics 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 only applicable with 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 resizeable
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
.. versionchanged:: 2.1.3
pygame now ensures that subsequent calls to this function clears the
window to black. On older versions, this was an implementation detail
on the major platforms this function was tested with.
.. ## 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 be 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 currently 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.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## 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.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. 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 receives 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`
DEPRECATED: This functionality will go away in SDL3.
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.
.. deprecated:: 2.2.0
.. ## 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`
DEPRECATED: This functionality will go away in SDL3.
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``.
.. deprecated:: 2.2.0
.. ## 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.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## 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.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## 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 ##
@@ -3,8 +3,550 @@
:mod:`pygame.draw`
==================
.. autopgmodule:: pygame.draw
:members:
.. 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.
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
|
.. versionchanged:: 2.1.1
Drawing rects with width now draws the width correctly inside the
rect's area, rather than using an internal call to draw.lines(),
which had half the width spill outside the rect area.
: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.
.. 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) (deprecated) 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) (deprecated) 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
@@ -12,3 +554,4 @@
Example code for draw module.
.. literalinclude:: code_examples/draw_module_example.py
@@ -8,179 +8,216 @@
| :sl:`pygame module for interacting with events and queues`
.. rubric:: Event queue
Pygame handles all its event messaging through an event queue. The functions in
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 video system (:mod:`pygame.display` or :class:`pygame.Window`).
If a window has not been created, the event queue may not work properly.
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 :func:`pygame.event.get()`, :func:`pygame.event.pump()`,
:func:`pygame.event.wait()`, :func:`pygame.event.peek()` or
:func:`pygame.event.clear()`).
.. note:: Not handling events may cause the system to decide the program is
frozen (not responding).
.. rubric:: Events of input devices
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`. However,
the event queue still needs to be running internally to enable this; programs
still need to use functions like :func:`pygame.event.get()` or
:func:`pygame.event.pump()` periodically. Note: Joysticks will not send any
events until the device has been initialized.
.. rubric:: Event objects
: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.Event` event objects.
There are a variety of ways to access the queued events, from simply
checking for the existence of events, to popping them off of the event queue.
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.Event` instances contain an event type identifier
and attributes specific to that event type. The event type identifier is
accessible as the :attr:`pygame.event.Event.type` property. An event type's
specific attributes can be accessed directly as an attribute on the event
object.
accessible as the :attr:`pygame.event.Event.type` property. Any of the
event specific attributes can be accessed through the
:attr:`pygame.event.Event.__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.
Users can create their own new events (or emulate system events) by
instantiating :func:`pygame.event.Event()` themselves, usually paired
with :func:`pygame.event.post()`.
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.
.. rubric:: Custom events and debugging
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 should reserve
a custom event number with :func:`pygame.event.custom_type()`.
While debugging and experimenting, you can print an event object for a quick
display of its type and members.
.. rubric:: Event types and attributes
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 are lists of event types with their
specific attributes and notes.
attributes based on the type. The following is a list of 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.
Note that ``ACTIVEEVENT``, ``VIDEORESIZE`` and ``VIDEOEXPOSE`` are considered
as "legacy" events, the use of pygame2 ``WINDOWEVENT`` API is recommended over
the use of this older API.
You can also find a list of constants for keyboard keys
:ref:`here <key-constants-label>`.
::
A keyboard event occurs when a key is pressed (``KEYDOWN``) and when a key is released (``KEYUP``)
The ``key`` attribute of keyboard events contains the value of what key was pressed or released.
The ``mod`` attribute contains information about the state of keyboard modifiers (SHIFT, CTRL, ALT, etc.).
The ``unicode`` attribute stores the 16-bit unicode value of the key that was pressed or released.
The ``scancode`` attribute represents the physical location of a key on the keyboard.
Event type Attributes/Notes
QUIT
USEREVENT (Starting type of the user defined
event types)
KEYDOWN key, mod, unicode, scancode, window(1)
KEYUP key, mod, unicode, scancode, window(1)
MOUSEMOTION pos, rel, buttons, touch(2), window(1)
MOUSEBUTTONUP pos, button, touch(2), clicks(3), window(1)
MOUSEBUTTONDOWN pos, button, touch(2), clicks(3), window(1)
MOUSEWHEEL which, flipped, x, y, touch(2), precise_x,
precise_y, window(1), pos(5)
JOYAXISMOTION instance_id, axis, value (deprecated: joy)
JOYBALLMOTION instance_id, ball, rel (deprecated: joy)
JOYHATMOTION instance_id, hat, value (deprecated: joy)
JOYBUTTONUP instance_id, button (deprecated: joy)
JOYBUTTONDOWN instance_id, button (deprecated: joy)
CONTROLLERDEVICEADDED device_index
JOYDEVICEADDED device_index
CONTROLLERDEVICEREMOVED instance_id
JOYDEVICEREMOVED instance_id
CONTROLLERDEVICEREMAPPED instance_id
(Use the window event API instead of legacy events)
ACTIVEEVENT gain, state (Legacy event)
VIDEORESIZE size, w, h (Legacy event)
VIDEOEXPOSE (Legacy event)
AUDIODEVICEADDED which, iscapture
AUDIODEVICEREMOVED which, iscapture
FINGERMOTION touch_id, finger_id, x, y, dx, dy, window(1)
FINGERDOWN touch_id, finger_id, x, y, dx, dy, window(1)
FINGERUP touch_id, finger_id, x, y, dx, dy, window(1)
MULTIGESTURE touch_id, x, y, pinched, rotated, num_fingers
TEXTEDITING(4) text, start(4), length(4), window(1)
TEXTINPUT(4) text, window(1)
DROPFILE window(1), file (Path of the file dropped
on the window)
DROPBEGIN window(1)
DROPCOMPLETE window(1)
DROPTEXT window(1)
MIDIIN (Reserved for pygame.midi use)
MIDIOUT (Reserved for pygame.midi use)
KEYMAPCHANGED (Keymap change due to language/keyboard
layout change)
CLIPBOARDUPDATE (Partially experimental)
LOCALECHANGED
RENDER_TARGETS_RESET
RENDER_DEVICE_RESET
The ``ACTIVEEVENT`` contains information about the application gaining or losing focus. The ``gain`` attribute
will be 1 if the mouse enters the window, otherwise ``gain`` will be 0. The ``state`` attribute will have a
value of ``SDL_APPMOUSEFOCUS`` if mouse focus was gained/lost, ``SDL_APPINPUTFOCUS`` if the application loses
or gains keyboard focus, or ``SDL_APPACTIVE`` if the application is minimized (``gain`` will be 0) or restored.
|
(``1``): if a :class:`pygame.Window` instance exists for the window that the event
occurred in, the ``window`` attribute of these events will be that instance,
otherwise it will be ``None``.
(``2``): 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.
(``3``): The ``clicks`` attribute of the ``MOUSEBUTTONDOWN`` and ``MOUSEBUTTONUP``
events indicate the number of clicks occurring in rapid succession, e.g. ``1``
for single-click, ``2`` for double-click, etc. Note that double, triple, or
more clicks will still fire mouse events for each individual click, with a
progressively increasing ``clicks`` attribute.
(``4``): The ``start`` attribute of the ``TEXTEDITING`` event is the cursor position,
in UTF-8 characters, where the new typing will be inserted into the editing text,
while the ``length`` attribute is the number of UTF-8 characters that will be
replaced by the new typing.
These ``TEXT*`` events are useful to implement inputs/languages that require composition,
provided by the system's IME (Input Method Editor). The ``TEXTINPUT`` event is only
fired when the text is confirmed.
(``5``): Position information was added to ``MOUSEWHEEL`` events in SDL 2.26.0. If
pygame was built on a version lower than that, the ``pos`` attribute is ``None``.
|
Here is a list of the new window events.
All window events have a ``window`` attribute corresponding to the
:class:`pygame.Window` that generated them.
When compiled with SDL2, pygame has these additional events and their
attributes.
::
Event type Short description and additional attributes
AUDIODEVICEADDED which, iscapture (SDL backend >= 2.0.4)
AUDIODEVICEREMOVED which, iscapture (SDL backend >= 2.0.4)
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, precise_x, precise_y
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.
.. versionadded:: 2.1.3 Added ``precise_x`` and ``precise_y`` to ``MOUSEWHEEL`` events
``MOUSEWHEEL`` event occurs whenever the mouse wheel is moved.
The ``which`` attribute determines if the event was generated from a touch input device vs an actual
mousewheel.
The ``preciseX`` attribute contains a float with the amount scrolled horizontally (positive to the right,
negative to the left).
The ``preciseY`` attribute contains a float with the amount scrolled vertically (positive away from user,
negative towards user).
The ``flipped`` attribute determines if the values in x and y will be opposite or not. If ``SDL_MOUSEWHEEL_FLIPPED``
is defined, the direction of x and y will be opposite.
``TEXTEDITING`` event is triggered when a user activates an input method via hotkey or selecting an
input method in a GUI and starts typing
The ``which`` attribute for ``AUDIODEVICE*`` events is an integer representing the index for new audio
devices that are added. ``AUDIODEVICE*`` events are used to update audio settings or device list.
|
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.
``MIDI*`` events differ from ``AUDIODEVICE*`` events in that AUDIODEVICE
events are triggered when there is a state change related to an audio
input/output device.
pygame 2 also supports controller hot-plugging
::
Event name Attributes and notes
DROPFILE file
DROPBEGIN (SDL backend >= 2.0.5)
DROPCOMPLETE (SDL backend >= 2.0.5)
DROPTEXT text (SDL backend >= 2.0.5)
MIDIIN
MIDIOUT
CONTROLLERDEVICEADDED device_index
JOYDEVICEADDED device_index
CONTROLLERDEVICEREMOVED instance_id
JOYDEVICEREMOVED instance_id
CONTROLLERDEVICEREMAPPED instance_id
KEYMAPCHANGED (SDL backend >= 2.0.4)
CLIPBOARDUPDATE
RENDER_TARGETS_RESET (SDL backend >= 2.0.2)
RENDER_DEVICE_RESET (SDL backend >= 2.0.4)
LOCALECHANGED (SDL backend >= 2.0.14)
Also in this version, ``instance_id`` attributes were added to joystick events,
and the ``joy`` attribute was deprecated.
``KEYMAPCHANGED`` is a type of an event sent when keymap changes due to a
system event such as an input language or keyboard layout change.
``CLIPBOARDUPDATE`` is an event sent when clipboard changes. This can still
be considered as an experimental feature, some kinds of clipboard changes might
not trigger this event.
``LOCALECHANGED`` is an event sent when user locale changes
.. versionadded:: 2.0.0
.. versionadded:: 2.1.3 ``KEYMAPCHANGED``, ``CLIPBOARDUPDATE``,
``RENDER_TARGETS_RESET``, ``RENDER_DEVICE_RESET`` and ``LOCALECHANGED``
|
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 (x, y attributes)
WINDOWSIZECHANGED Window size has changed (x, y attributes)
WINDOWRESIZED Window got resized by the user/window manager
(x, y attributes)
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
@@ -189,44 +226,36 @@ All window events have a ``window`` attribute corresponding to the
WINDOWFOCUSGAINED Window gained focus
WINDOWFOCUSLOST Window lost focus
WINDOWCLOSE Window was closed
WINDOWTAKEFOCUS Window was offered focus
WINDOWHITTEST Window has a special hit test
WINDOWICCPROFCHANGED Window ICC profile changed
(SDL backend >= 2.0.18)
WINDOWDISPLAYCHANGED Window moved on a new display (display_index
attribute. SDL backend >= 2.0.18)
WINDOWTAKEFOCUS Window was offered focus (SDL backend >= 2.0.5)
WINDOWHITTEST Window has a special hit test (SDL backend >= 2.0.5)
WINDOWICCPROFCHANGED Window ICC profile changed (SDL backend >= 2.0.18)
WINDOWDISPLAYCHANGED Window moved on a new display (SDL backend >= 2.0.18)
``WINDOWMOVED``, ``WINDOWRESIZED`` and ``WINDOWSIZECHANGED`` have ``x`` and
``y`` attributes, ``WINDOWDISPLAYCHANGED`` has a ``display_index`` attribute.
All windowevents have a ``window`` attribute.
.. versionadded:: 2.0.1
.. versionadded:: 2.1.3 ``WINDOWICCPROFCHANGED`` and ``WINDOWDISPLAYCHANGED``
|
On Android, the following events can be generated:
On Android, the following events can be generated
::
Event type Short description
Event type Short description
APP_TERMINATING OS is terminating the application
APP_LOWMEMORY OS is low on memory (try to free memory)
APP_LOWMEMORY OS is low on memory, try to free memory if possible
APP_WILLENTERBACKGROUND Application is entering background
APP_DIDENTERBACKGROUND Application entered background
APP_WILLENTERFOREGROUND Application is entering foreground
APP_DIDENTERFOREGROUND Application entered foreground
|
.. versionchangedold:: 2.0.0 The ``joy`` attribute was deprecated, ``instance_id`` was added.
.. versionaddedold:: 2.0.1 Window events and the ``unicode`` attribute for ``KEYUP`` events.
.. versionaddedold:: 2.0.2 The ``touch`` attribute was added to all the ``MOUSE`` events.
.. versionadded:: 2.1.3 Android events, ``precise_x`` and ``precise_y`` to ``MOUSEWHEEL`` events,
``KEYMAPCHANGED``, ``CLIPBOARDUPDATE``, ``LOCALECHANGED``, ``WINDOWICCPROFCHANGED``,
``WINDOWDISPLAYCHANGED``, ``RENDER_TARGETS_RESET``, and ``RENDER_DEVICE_RESET``.
.. versionadded:: 2.5.7 The ``clicks`` attribute was added to ``MOUSEBUTTONDOWN``
and ``MOUSEBUTTONUP`` events.
.. versionadded:: 2.5.8 The ``pos`` attribute was added to ``MOUSEWHEEL`` events.
.. versionadded:: 2.1.3
|
@@ -275,8 +304,8 @@ On Android, the following events can be generated:
If ``pump`` is ``True`` (the default), then :func:`pygame.event.pump()` will be called.
.. versionchangedold:: 1.9.5 Added ``pump`` argument
.. versionchangedold:: 2.0.2 Added ``exclude`` argument
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. versionchanged:: 2.0.2 Added ``exclude`` argument
.. ## pygame.event.get ##
@@ -302,13 +331,13 @@ On Android, the following events can be generated:
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``
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.
.. versionchangedold:: 2.0.0.dev13 Added ``timeout`` argument
.. versionchanged:: 2.0.0.dev13 Added ``timeout`` argument
.. caution::
This function should only be called in the thread that initialized :mod:`pygame.display`.
@@ -325,14 +354,9 @@ On Android, the following events can be generated:
queue. If a sequence of event types is passed, this will return ``True`` if
any of those events are on the queue.
When ``eventtype`` is not passed or ``None``, this function will return ``True`` if
there's any event on the queue, and return ``False`` if the queue is empty.
If ``pump`` is ``True`` (the default), then :func:`pygame.event.pump()` will be called.
.. versionchangedold:: 1.9.5 Added ``pump`` argument
.. versionchanged:: 2.5.3 no longer mistakenly returns an event when ``eventtype`` is None or not passed.
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. ## pygame.event.peek ##
@@ -348,14 +372,14 @@ On Android, the following events can be generated:
If ``pump`` is ``True`` (the default), then :func:`pygame.event.pump()` will be called.
.. versionchangedold:: 1.9.5 Added ``pump`` argument
.. 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`
| :sg:`event_name(type) -> string`
Returns a string representing the name (in CapWords style) of the given
event type.
@@ -363,13 +387,15 @@ On Android, the following events can be generated:
"UserEvent" is returned for all values in the user event id range.
"Unknown" is returned when the event type does not exist.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## pygame.event.event_name ##
.. function:: set_blocked
| :sl:`control which events are blocked on the queue`
| :sg:`set_blocked(type, /) -> None`
| :sg:`set_blocked(typelist, /) -> None`
| :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
@@ -384,8 +410,8 @@ On Android, the following events can be generated:
.. 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(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,
@@ -400,8 +426,8 @@ On Android, the following events can be generated:
.. 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`
| :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
@@ -412,7 +438,7 @@ On Android, the following events can be generated:
.. function:: set_grab
| :sl:`control the sharing of input devices with other applications`
| :sg:`set_grab(bool, /) -> None`
| :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
@@ -433,26 +459,44 @@ On Android, the following events can be generated:
.. ## pygame.event.get_grab ##
.. function:: set_keyboard_grab
| :sl:`grab enables capture of system keyboard shortcuts like Alt+Tab or the Meta/Super key.`
| :sg:`set_keyboard_grab(bool) -> None`
Keyboard grab enables capture of system keyboard shortcuts like Alt+Tab or the Meta/Super key.
Note that not all system keyboard shortcuts can be captured by applications (one example is Ctrl+Alt+Del on Windows).
This is primarily intended for specialized applications such as VNC clients or VM frontends. Normal games should not use keyboard grab.
.. versionadded:: 2.5.0
.. ## pygame.event.set_keyboard_grab ##
.. function:: get_keyboard_grab
| :sl:`get the current keyboard grab state`
| :sg:`get_keyboard_grab() -> bool`
Returns ``True`` when keyboard grab is enabled.
.. versionadded:: 2.5.0
.. ## pygame.event.get_keyboard_grab ##
.. function:: post
| :sl:`place a new event on the queue`
| :sg:`post(event, /) -> bool`
| :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.
When this event is received on the event queue, it will be a shallow copy of
the event object posted by this function; the dict attribute of both events
will be a reference to the same dict object in memory. Modifications on one
dict can affect another, use deepcopy operations on the dict object if you
don't want this behaviour.
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.
.. versionchangedold:: 2.0.1 returns a boolean, previously returned ``None``
.. versionchanged:: 2.0.1 returns a boolean, previously returned ``None``
.. ## pygame.event.post ##
@@ -461,11 +505,11 @@ On Android, the following events can be generated:
| :sl:`make custom user event type`
| :sg:`custom_type() -> int`
Reserves an event slot for use in a custom event ``userevent`` and returns the integer that the event slot is reserved to.
Reserves a ``pygame.USEREVENT`` for a custom use.
If too many events are made a :exc:`pygame.error` is raised.
.. versionaddedold:: 2.0.0.dev3
.. versionadded:: 2.0.0.dev3
.. ## pygame.event.custom_type ##
@@ -481,9 +525,6 @@ On Android, the following events can be generated:
When creating the object, the attributes may come from a dictionary
argument with string keys or from keyword arguments.
.. versionchanged:: 2.1.4 This class is also available through the ``pygame.Event``
alias.
.. note::
From version 2.1.3 ``EventType`` is an alias for ``Event``. Beforehand,
``Event`` was a function that returned ``EventType`` instances. Use of
@@ -497,7 +538,7 @@ On Android, the following events can be generated:
Read-only. The event type identifier. For user created event
objects, this is the ``type`` argument passed to
:class:`pygame.event.Event()`.
:func:`pygame.event.Event()`.
For example, some predefined event identifiers are ``QUIT`` and
``MOUSEMOTION``.
@@ -517,7 +558,7 @@ On Android, the following events can be generated:
.. ## pygame.event.Event.__dict__ ##
.. versionaddedold:: 1.9.2 Mutable attributes.
.. versionadded:: 1.9.2 Mutable attributes.
.. ## pygame.event.Event ##
@@ -26,7 +26,7 @@ eg:
python -m pygame.examples.scaletest someimage.png
Resources such as images and sounds for the examples are found in the
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
@@ -287,8 +287,8 @@ pygame much earlier.
Thumbnail generation with scaling is an example of what you can do with
pygame.
``NOTE``: the pygame scale function uses SIMD acceleration if available,
and can be run in multiple threads.
``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:
@@ -307,7 +307,7 @@ pygame much earlier.
A demo showing full joystick support.
.. versionaddedold:: 2.0.2
.. versionadded:: 2.0.2
.. ## pygame.examples.joystick.main ##
@@ -24,7 +24,7 @@ accessed by passing ``None`` as the font name.
Before pygame 2.0.3, pygame.font accepts any UCS-2 / UTF-16 character
('\\u0001' to '\\uFFFF'). After 2.0.3, pygame.font built with SDL_ttf
2.0.15 accepts any valid UCS-4 / UTF-32 character
2.0.15 accepts any valid UCS-4 / UTF-32 character
(like emojis, if the font has them) ('\\U00000001' to '\\U0010FFFF')).
More about this in :func:`Font.render`.
@@ -36,7 +36,7 @@ solves no longer exists, it will likely be removed in the future.
.. function:: init
| :sl:`Initialize the font module.`
| :sl:`initialize the font module`
| :sg:`init() -> None`
This method is called automatically by ``pygame.init()``. It initializes the
@@ -49,7 +49,7 @@ solves no longer exists, it will likely be removed in the future.
.. function:: quit
| :sl:`Uninitialize the font module.`
| :sl:`uninitialize the font module`
| :sg:`quit() -> None`
Manually uninitialize SDL_ttf's font system. This is called automatically by
@@ -57,30 +57,90 @@ solves no longer exists, it will likely be removed in the future.
It is safe to call this function even if font is currently not initialized.
Previously created font objects will be invalid after the font module is quit.
.. ## pygame.font.quit ##
.. function:: get_init
| :sl:`True if the font module is initialized.`
| :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 ##
.. autopgfunction:: get_default_font
.. function:: get_default_font
.. autopgfunction:: get_sdl_ttf_version
| :sl:`get the filename of the default font`
| :sg:`get_default_font() -> string`
.. autopgfunction:: get_fonts
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.
.. autopgfunction:: match_font
.. ## pygame.font.get_default_font ##
.. function:: get_sdl_ttf_version
| :sl:`gets SDL_ttf version`
| :sg:`get_sdl_ttf_version(linked=True) -> (major, minor, patch)`
**Experimental:** feature still in development available for testing and feedback. It may change.
`Please leave get_sdl_ttf_version feedback with authors <https://github.com/pygame/pygame/pull/3095>`_
Returns a tuple of integers that identify SDL_ttf's version.
SDL_ttf is the underlying font rendering library, written in C,
on which pygame's font module depends. If 'linked' is True (the default),
the function returns the version of the linked TTF library.
Otherwise this function returns the version of TTF pygame was compiled with
.. versionadded:: 2.1.3
.. ## pygame.font.get_sdl_ttf_version ##
.. 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.
.. versionchanged:: 2.1.3 Checks through user fonts instead of just global fonts for Windows.
.. ## 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.
.. versionchanged:: 2.1.3 Checks through user fonts instead of just global fonts for Windows.
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.`
| :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
@@ -93,7 +153,7 @@ solves no longer exists, it will likely be removed in the future.
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
.. versionaddedold:: 2.0.1 Accept an iterable of font names.
.. versionadded:: 2.0.1 Accept an iterable of font names.
.. versionchanged:: 2.1.3 Checks through user fonts instead of just global fonts for Windows.
@@ -101,9 +161,9 @@ solves no longer exists, it will likely be removed in the future.
.. class:: Font
| :sl:`Create a new Font object from a file.`
| :sg:`Font(filename=None, size=20) -> Font`
| :sg:`Font(filename, size) -> Font`
| :sl:`create a new Font object from a file`
| :sg:`Font(file_path=None, size=12) -> Font`
| :sg:`Font(file_path, size) -> Font`
| :sg:`Font(pathlib.Path, size) -> Font`
| :sg:`Font(object, size) -> Font`
@@ -111,18 +171,13 @@ solves no longer exists, it will likely be removed in the future.
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.
be changed. If no arguments are given then the default font will be used and
a font size of 12 is used.
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.
.. versionchanged:: 2.1.4 If no arguments are given then the default font will be used and
a font size of 20 is used.
.. versionchanged:: 2.1.4 This class is also available through the ``pygame.Font``
alias.
.. attribute:: bold
| :sl:`Gets or sets whether the font should be rendered in (faked) bold.`
@@ -137,38 +192,10 @@ solves no longer exists, it will likely be removed in the future.
normal. This can be mixed with the italic, underline and
strikethrough modes.
.. versionaddedold:: 2.0.0
.. versionadded:: 2.0.0
.. ## Font.bold ##
.. attribute:: name
| :sl:`Gets the font's name.`
| :sg:`name -> str`
Read only. Returns the font's name.
.. versionadded:: 2.2
.. ## Font.name ##
.. attribute:: style_name
| :sl:`Gets the font's style_name.`
| :sg:`style_name -> str`
Read only. Returns the font's style name. Style names are arbitrary, can be an empty string.
Here are some examples:
'Black', 'Bold', 'Bold Italic', 'BoldOblique', 'Book', 'BookOblique', 'Condensed', 'Condensed Oblique',
'ExtraLight', 'Italic', 'Light', 'LightOblique', 'Medium', 'MediumOblique', 'Oblique', 'Regular',
'Semibold', 'Semilight', 'Slanted'
.. versionadded:: 2.3.1
.. ## Font.style_name ##
.. attribute:: italic
| :sl:`Gets or sets whether the font should be rendered in (faked) italics.`
@@ -183,7 +210,7 @@ solves no longer exists, it will likely be removed in the future.
than when normal. This can be mixed with the bold, underline and
strikethrough modes.
.. versionaddedold:: 2.0.0
.. versionadded:: 2.0.0
.. ## Font.italic ##
@@ -199,10 +226,10 @@ solves no longer exists, it will likely be removed in the future.
of font size. This can be mixed with the bold, italic and
strikethrough modes.
.. versionaddedold:: 2.0.0
.. versionadded:: 2.0.0
.. ## Font.underline ##
.. attribute:: strikethrough
| :sl:`Gets or sets whether the font should be rendered with a strikethrough.`
@@ -219,82 +246,17 @@ solves no longer exists, it will likely be removed in the future.
.. ## Font.strikethrough ##
.. attribute:: align
| :sl:`Gets or sets how rendered text is aligned when given a wrap length.`
| :sg:`align -> int`
Can be set to `pygame.FONT_LEFT`, `pygame.FONT_RIGHT`, or
`pygame.FONT_CENTER`. This controls the text alignment behavior for the
font. Defaults to `pygame.FONT_LEFT`.
Requires pygame built with SDL_ttf 2.20.0, as all official pygame
distributions are.
.. versionadded:: 2.1.4
.. ## Font.align ##
.. attribute:: point_size
| :sl:`Gets or sets the font's point size.`
| :sg:`point_size -> int`
Returns the point size of the font. Will not be accurate upon initializing
the font object when the font name is initialized as ``None``.
.. versionadded:: 2.3.1
.. ## Font.point_size ##
.. attribute:: outline
| :sl:`Gets or sets the font's outline thickness (pixels).`
| :sg:`outline -> int`
The outline value of the font.
When set to 0, the font will be drawn normally. When positive,
the text will be drawn as a hollow outline. The outline grows in all
directions a number of pixels equal to the value set. Negative values
are not allowed.
This can be drawn underneath unoutlined text to create a text outline
effect. For example: ::
def render_outlined(
font: pygame.Font,
text: str,
text_color: pygame.typing.ColorLike,
outline_color: pygame.typing.ColorLike,
outline_width: int,
) -> pygame.Surface:
old_outline = font.outline
if old_outline != 0:
font.outline = 0
base_text_surf = font.render(text, True, text_color)
font.outline = outline_width
outlined_text_surf = font.render(text, True, outline_color)
outlined_text_surf.blit(base_text_surf, (outline_width, outline_width))
font.outline = old_outline
return outlined_text_surf
.. versionadded:: 2.5.7
.. ## Font.outline ##
.. method:: render
| :sl:`Draw text on a new Surface.`
| :sg:`render(text, antialias, color, bgcolor=None, wraplength=0) -> Surface`
| :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.
This creates a new Surface with the specified text rendered on it.
:mod:`pygame.font` provides no way to directly draw text on an existing
Surface: instead you must use :func:`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
@@ -302,13 +264,9 @@ solves no longer exists, it will likely be removed in the future.
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 bgcolor argument is a color
to use for the text background. If bgcolor is ``None`` the area outside
the text will be transparent.
The `wraplength` argument describes the width (in pixels) a line of text
should be before wrapping to a new line. See
:attr:`pygame.font.Font.align` for line-alignment settings.
[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 :func:`Font.size`). If an empty string is passed
@@ -329,60 +287,212 @@ solves no longer exists, it will likely be removed in the future.
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 newlines yourself.
Font rendering is not thread safe: only a single thread can render text
at any time.
.. versionchangedold:: 2.0.3 Rendering UCS4 unicode works and does not
.. versionchanged:: 2.0.3 Rendering UCS4 unicode works and does not
raise an exception. Use `if hasattr(pygame.font, "UCS4"):` to see if
pygame supports rendering UCS4 unicode including more languages and
emoji.
.. versionchanged:: 2.1.4 newline characters now will break text into
multiple lines.
.. versionadded:: 2.1.4 wraplength parameter
.. versionchanged:: 2.3.0 now supports keyword arguments.
.. ## Font.render ##
.. autopgmethod:: size
.. method:: size
.. autopgmethod:: set_underline
| :sl:`determine the amount of space needed to render text`
| :sg:`size(text) -> (width, height)`
.. autopgmethod:: get_underline
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 word wrapping and other layout effects.
.. autopgmethod:: set_strikethrough
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".
.. autopgmethod:: get_strikethrough
.. ## Font.size ##
.. autopgmethod:: set_bold
.. method:: set_underline
.. autopgmethod:: get_bold
| :sl:`control if text is rendered with an underline`
| :sg:`set_underline(bool) -> None`
.. autopgmethod:: set_italic
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, italic and strikethrough modes.
.. autopgmethod:: metrics
.. note:: This is the same as the :attr:`underline` attribute.
.. autopgmethod:: get_italic
.. ## Font.set_underline ##
.. autopgmethod:: get_linesize
.. method:: get_underline
.. autopgmethod:: set_linesize
| :sl:`check if text will be rendered with an underline`
| :sg:`get_underline() -> bool`
.. autopgmethod:: get_height
Return True when the font underline is enabled.
.. autopgmethod:: set_point_size
.. note:: This is the same as the :attr:`underline` attribute.
.. autopgmethod:: get_point_size
.. ## Font.get_underline ##
.. method:: set_strikethrough
.. autopgmethod:: get_ascent
| :sl:`control if text is rendered with a strikethrough`
| :sg:`set_strikethrough(bool) -> None`
.. autopgmethod:: get_descent
When enabled, all rendered fonts will include a strikethrough. The
strikethrough is always one pixel thick, regardless of font size.
This can be mixed with the bold, italic and underline modes.
.. autopgmethod:: set_script
.. note:: This is the same as the :attr:`strikethrough` attribute.
.. versionadded:: 2.1.3
.. autopgmethod:: set_direction
.. ## Font.set_strikethrough ##
.. method:: get_strikethrough
| :sl:`check if text will be rendered with a strikethrough`
| :sg:`get_strikethrough() -> bool`
Return True when the font strikethrough is enabled.
.. note:: This is the same as the :attr:`strikethrough` attribute.
.. versionadded:: 2.1.3
.. ## Font.get_strikethrough ##
.. 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, underline and
strikethrough 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, underline and
strikethrough 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 ##
.. method:: set_script
| :sl:`set the script code for text shaping`
| :sg:`set_script(str) -> None`
**Experimental:** feature still in development available for testing and feedback. It may change.
`Please leave feedback with authors <https://github.com/pygame/pygame/pull/3330>`_
Sets the script used by harfbuzz text shaping, taking a 4 character
script code as input. For example, Hindi is written in the Devanagari
script, for which the script code is `"Deva"`. See the full list of
script codes in `ISO 15924 <https://www.unicode.org/iso15924/iso15924-codes.html>`_.
This method requires pygame built with SDL_ttf 2.20.0 or above. Otherwise the
method will raise a pygame.error.
.. versionadded:: 2.2.0
.. ## Font.set_script ##
.. ## pygame.font.Font ##
@@ -4,22 +4,18 @@
======================
.. module:: pygame.freetype
:synopsis: pygame module for loading and rendering computer fonts
:synopsis: Enhanced pygame module for loading and rendering computer fonts
| :sl:`pygame module for loading and rendering computer fonts`
| :sl:`Enhanced pygame module for loading and rendering computer fonts`
The ``pygame.freetype`` module is an alternative to :mod:`pygame.font`.
It is implemented directly on the FreeType 2 library, and is not
backward compatible with :mod:`pygame.font`. :mod:`pygame.font`
relies on the SDL_ttf library, and due to the SDL_ttf team's efforts,
``pygame.font`` is now the better supported of our font modules.
In new code, the use of :mod:`pygame.font` is encouraged.
``pygame.font``, unlike ``pygame.freetype``, has support for multiline text,
text shaping for global writing systems, and rendering emoji with color.
The ``pygame.ftfont`` module exists as a limited version of
the :mod:`pygame.font` API, running on top of ``pygame.freetype``.
Many of the recently added font features do not work on it.
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,
@@ -63,7 +59,7 @@ loaded. This module must be imported explicitly to be used. ::
import pygame
import pygame.freetype
.. versionaddedold:: 1.9.2 :mod:`freetype`
.. versionadded:: 1.9.2 :mod:`freetype`
.. function:: get_error
@@ -88,7 +84,7 @@ loaded. This module must be imported explicitly to be used. ::
It will not compile with the original FreeType 1.0. Hence, the first element
of the tuple will always be "2".
.. versionchanged:: 2.1.4 ``linked`` keyword argument added and default behavior changed from returning compiled version to returning linked version
.. versionchanged:: 2.2.0 ``linked`` keyword argument added and default behavior changed from returning compiled version to returning linked version
.. function:: init
@@ -127,7 +123,7 @@ loaded. This module must be imported explicitly to be used. ::
Returns ``True`` if the ``pygame.freetype`` module is currently initialized.
.. versionaddedold:: 1.9.5
.. versionadded:: 1.9.5
.. function:: was_init
@@ -155,7 +151,7 @@ loaded. This module must be imported explicitly to be used. ::
.. function:: set_default_resolution
| :sl:`Set the default pixel size in dots per inch for the module`
| :sg:`set_default_resolution(resolution, /)`
| :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.
@@ -175,7 +171,7 @@ loaded. This module must be imported explicitly to be used. ::
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
.. versionaddedold:: 2.0.1 Accept an iterable of font names.
.. versionadded:: 2.0.1 Accept an iterable of font names.
.. function:: get_default_font
@@ -228,22 +224,6 @@ loaded. This module must be imported explicitly to be used. ::
Read only. Returns the real (long) name of the font, as
recorded in the font file.
.. attribute:: style_name
| :sl:`Gets the font's style_name.`
| :sg:`style_name -> str`
Read only. Returns the font's style name. Style names are arbitrary, can be an empty string.
Here are some examples:
'Black', 'Bold', 'Bold Italic', 'BoldOblique', 'Book', 'BookOblique', 'Condensed', 'Condensed Oblique',
'ExtraLight', 'Italic', 'Light', 'LightOblique', 'Medium', 'MediumOblique', 'Oblique', 'Regular',
'Semibold', 'Semilight', 'Slanted'
.. versionadded:: 2.3.1
.. ## Font.style_name ##
.. attribute:: path
| :sl:`Font file path`
@@ -358,7 +338,7 @@ loaded. This module must be imported explicitly to be used. ::
.. method:: get_sized_ascender
| :sl:`The scaled ascent of the font in pixels`
| :sg:`get_sized_ascender(size=0, /) -> int`
| :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.
@@ -366,15 +346,15 @@ loaded. This module must be imported explicitly to be used. ::
.. method:: get_sized_descender
| :sl:`The scaled descent of the font in pixels`
| :sg:`get_sized_descender(size=0, /) -> int`
| :sg:`get_sized_descender(<size>=0) -> int`
Return the number of pixels from the font's baseline to the bottom of the
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`
| :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.
@@ -382,7 +362,7 @@ loaded. This module must be imported explicitly to be used. ::
.. method:: get_sized_glyph_height
| :sl:`The scaled bounding box height of the font in pixels`
| :sg:`get_sized_glyph_height(size=0, /) -> int`
| :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.
@@ -743,7 +723,7 @@ loaded. This module must be imported explicitly to be used. ::
unset and text will render with a transparent background by default.
Applies to :meth:`render` and :meth:`render_to`.
.. versionaddedold:: 2.0.0
.. versionadded:: 2.0.0
.. attribute:: origin
@@ -1,769 +0,0 @@
.. include:: common.txt
:mod:`pygame.geometry`
======================
.. module:: pygame.geometry
:synopsis: pygame geometry module
.. warning::
**Experimental Module**
**This module is a work in progress. Refrain from relying on any features provided by
this module, as they are subject to change or removal without prior notice.**
.. versionadded:: 2.4.0
| :sl:`pygame module for the Circle, Line, and Polygon objects`
.. currentmodule:: pygame
.. class:: Circle
| :sl:`pygame object for representing a circle`
| :sg:`Circle((x, y), radius) -> Circle`
| :sg:`Circle(x, y, radius) -> Circle`
The `Circle` class provides many useful methods for collision testing, transformation and intersection.
A `Circle` can be created from a combination of a pair of coordinates that represent
the center of the circle and a radius. Circles can also be created from python objects that
are already a `Circle` (effectively copying the circle) or have an attribute named "circle".
Specifically, to construct a circle you can pass the x, y, and radius values as separate
arguments or inside a sequence(list or tuple).
Functions that require a `Circle` argument may also accept these values as Circles:
::
((x, y), radius)
(x, y, radius)
(vector2, radius)
The `Circle` class only stores the x, y and r attributes, everything else is calculated
on the fly based on them.
**Circle Attributes**
----
.. attribute:: x
| :sl:`center x coordinate of the circle`
| :sg:`x -> float`
The horizontal coordinate of the center of the circle. Reassigning it moves the circle.
.. versionadded:: 2.4.0
.. ## Circle.x ##
.. attribute:: y
| :sl:`center y coordinate of the circle`
| :sg:`y -> float`
The vertical coordinate of the center of the circle. Reassigning it moves the circle.
.. versionadded:: 2.4.0
.. ## Circle.y ##
.. attribute:: r
| :sl:`radius of the circle`
| :sg:`r -> float`
Represents the size of the circle. It can't be negative. Reassigning it scales the circle.
.. versionadded:: 2.4.0
.. versionchanged:: 2.5.1 It is now allowed to create degenerate circles with :math:`r = 0`.
.. ## Circle.r ##
.. attribute:: r_sqr
| :sl:`radius of the circle squared`
| :sg:`r_sqr -> float`
It's equivalent to :math:`r^2`. It can't be negative. Reassigning it changes the radius to :math:`r = \sqrt{r_{sqr}}`.
.. versionadded:: 2.4.0
.. ## Circle.r_sqr ##
.. attribute:: center
| :sl:`x and y coordinates of the center of the circle`
| :sg:`center -> (float, float)`
A tuple containing the circle's `x` and `y` coordinates representing its center.
Reassigning it moves the circle to the new position.
.. versionadded:: 2.4.0
.. ## Circle.center ##
.. attribute:: diameter
| :sl:`diameter of the circle`
| :sg:`diameter -> float`
It's equivalent to :math:`2 \cdot r`. It can't be negative. Reassigning it
changes the radius to :math:`r = \frac{d}{2}`.
.. versionadded:: 2.4.0
.. ## Circle.diameter ##
.. attribute:: area
| :sl:`area of the circle`
| :sg:`area -> float`
It's equivalent to :math:`\pi \cdot r^2`. It can't be negative. Reassigning it
changes the radius to :math:`r = \sqrt{\frac{area}{\pi}}` producing a circle with matching area.
.. versionadded:: 2.4.0
.. ## Circle.area ##
.. attribute:: circumference
| :sl:`circumference of the circle`
| :sg:`circumference -> float`
It's equivalent to :math:`2 \cdot \pi \cdot r`. It can't be negative. Reassigning it
changes the radius to :math:`r = \frac{circumference}{2\pi}` producing a circle with
matching circumference.
.. versionadded:: 2.4.0
.. ## Circle.circumference ##
.. attribute:: top
| :sl:`top coordinate of the circle`
| :sg:`top -> (float, float)`
A tuple containing the `x` and `y` coordinates that represent the top
of the circle.
Reassigning it moves the circle to the new position. The radius will not be affected.
.. versionadded:: 2.5.2
.. ## Circle.top ##
.. attribute:: bottom
| :sl:`bottom coordinate of the circle`
| :sg:`bottom -> (float, float)`
A tuple containing the `x` and `y` coordinates that represent the bottom
of the circle.
Reassigning it moves the circle to the new position. The radius will not be affected.
.. versionadded:: 2.5.2
.. ## Circle.bottom ##
.. attribute:: left
| :sl:`left coordinate of the circle`
| :sg:`left -> (float, float)`
A tuple containing the `x` and `y` coordinates that represent the left
of the circle.
Reassigning it moves the circle to the new position. The radius will not be affected.
.. versionadded:: 2.5.2
.. ## Circle.left ##
.. attribute:: right
| :sl:`right coordinate of the circle`
| :sg:`right -> (float, float)`
A tuple containing the `x` and `y` coordinates that represent the right
of the circle.
Reassigning it moves the circle to the new position. The radius will not be affected.
.. versionadded:: 2.5.2
.. ## Circle.right ##
**Circle Methods**
----
.. method:: collidepoint
| :sl:`tests if a point is inside the circle`
| :sg:`collidepoint((x, y), /) -> bool`
| :sg:`collidepoint(x, y, /) -> bool`
| :sg:`collidepoint(vector2, /) -> bool`
Returns `True` if the given point is inside this `Circle` (edge included), `False` otherwise.
It takes a tuple of (x, y) coordinates, two separate x and y coordinates, or a `Vector2`
object as its argument.
.. versionadded:: 2.4.0
.. ## Circle.collidepoint ##
.. method:: collidecircle
| :sl:`tests if a circle collides with this circle`
| :sg:`collidecircle(circle, /) -> bool`
| :sg:`collidecircle(x, y, radius, /) -> bool`
| :sg:`collidecircle((x, y), radius, /) -> bool`
| :sg:`collidecircle(vector2, radius, /) -> bool`
Returns `True` if the given circle intersects with this `Circle`, `False` otherwise.
It takes either a `Circle` object, a tuple of (x, y) coordinates and a radius, or separate x and y
coordinates and a radius as its argument.
.. note::
Calling this method with this circle as the argument will always return `True`.
.. versionadded:: 2.4.0
.. ## Circle.collidecircle ##
.. method:: colliderect
| :sl:`tests if a rectangle collides with this circle`
| :sg:`colliderect(rect, /) -> bool`
| :sg:`colliderect((x, y, width, height), /) -> bool`
| :sg:`colliderect(x, y, width, height, /) -> bool`
| :sg:`colliderect((x, y), (width, height), /) -> bool`
| :sg:`colliderect(vector2, (width, height), /) -> bool`
Returns `True` if the given rectangle intersects with this `Circle`, `False` otherwise.
Takes either a `Rect` object, a tuple of (x, y, width, height) coordinates, or separate
x, y coordinates and width, height as its argument.
.. versionadded:: 2.4.0
.. ## Circle.colliderect ##
.. method:: collideswith
| :sl:`tests if a shape or point collides with this circle`
| :sg:`collideswith(circle, /) -> bool`
| :sg:`collideswith(rect, /) -> bool`
| :sg:`collideswith((x, y), /) -> bool`
| :sg:`collideswith(vector2, /) -> bool`
Returns `True` if the given shape or point intersects with this `Circle`, `False` otherwise.
The shape can be a `Circle`, `Rect`, `FRect`.
.. note::
The shape argument must be an actual shape object (`Circle`, `Rect`, or `FRect`).
You can't pass a tuple or list of coordinates representing the shape (except for a point),
because the shape type can't be determined from the coordinates alone.
.. versionadded:: 2.5.0
.. ## Circle.collideswith ##
.. method:: collidelist
| :sl:`test if a list of objects collide with the circle`
| :sg:`collidelist(colliders) -> int`
The `collidelist` method tests whether a given list of shapes or points collides
(overlaps) with this `Circle` object. The function takes in a single argument, which
must be a list of `Circle`, `Rect`, `FRect`, or a point. The function returns the index
of the first shape or point in the list that collides with the `Circle` object, or
-1 if there is no collision.
.. note::
The shapes must be actual shape objects, such as `Circle`, `Rect` or `FRect`
instances. It is not possible to pass a tuple or list of coordinates representing
the shape as an argument (except for a point), because the shape type can't be
determined from the coordinates alone.
.. versionadded:: 2.5.2
.. ## Circle.collidelist ##
.. method:: collidelistall
| :sl:`test if all objects in a list collide with the circle`
| :sg:`collidelistall(colliders) -> list`
The `collidelistall` method tests whether a given list of shapes or points collides
(overlaps) with this `Circle` object. The function takes in a single argument, which
must be a list of `Circle`, `Rect`, `FRect`, or a point. The function returns a list
containing the indices of all the shapes or points in the list that collide with
the `Circle` object, or an empty list if there is no collision.
.. note::
The shapes must be actual shape objects, such as `Circle`, `Rect` or `FRect`
instances. It is not possible to pass a tuple or list of coordinates representing
the shape as an argument (except for a point), because the shape type can't be
determined from the coordinates alone.
.. versionadded:: 2.5.2
.. ## Circle.collidelistall ##
.. method:: contains
| :sl:`tests if a shape or point is inside the circle`
| :sg:`contains(circle, /) -> bool`
| :sg:`contains(rect, /) -> bool`
| :sg:`contains((x, y), /) -> bool`
| :sg:`contains(vector2, /) -> bool`
Returns `True` if the shape or point is completely contained within this `Circle`, `False` otherwise.
The shape can be a `Circle`, `Rect`, `FRect`.
.. note::
The shape argument must be an actual shape object (`Circle`, `Rect`, or `FRect`).
You can't pass a tuple or list of coordinates representing the shape (except for a point),
because the shape type can't be determined from the coordinates alone.
.. versionadded:: 2.5.0
.. ## Circle.contains ##
.. method:: move
| :sl:`moves the circle by a given amount`
| :sg:`move((x, y), /) -> Circle`
| :sg:`move(x, y, /) -> Circle`
| :sg:`move(vector2, /) -> Circle`
Returns a copy of this `Circle` moved by the given amounts.
Takes either a tuple of (x, y) coordinates, two separate x and y coordinates,
or a `Vector2` object as its argument.
This method is equivalent to the following code:
.. code-block:: python
Circle((circle.x + x, circle.y + y), circle.r)
.. versionadded:: 2.5.0
.. ## Circle.move ##
.. method:: move_ip
| :sl:`moves the circle by a given amount, in place`
| :sg:`move_ip((x, y), /) -> None`
| :sg:`move_ip(x, y, /) -> None`
| :sg:`move_ip(vector2, /) -> None`
Moves this `Circle` in place by the given amounts.
Takes the same types of arguments as :meth:`move` and it always returns `None`.
This method is equivalent to the following code:
.. code-block:: python
circle.x += x
circle.y += y
.. versionadded:: 2.5.0
.. ## Circle.move_ip ##
.. method:: intersect
| :sl:`finds intersections between the circle and a shape`
| :sg:`intersect(circle, /) -> list`
Finds and returns a list of intersection points between the circle and another shape.
The other shape must be a `Circle` object.
If the circle does not intersect or has infinite intersections, an empty list is returned.
.. note::
The shape argument must be an instance of the `Circle` class.
Passing a tuple or list of coordinates representing the shape is not supported,
as the type of shape cannot be determined from coordinates alone.
.. versionadded:: 2.5.2
.. ## Circle.intersect ##
.. method:: update
| :sl:`updates the circle position and radius`
| :sg:`update((x, y), radius, /) -> None`
| :sg:`update(x, y, radius, /) -> None`
| :sg:`update(vector2, radius, /) -> None`
Sets the position and radius of this `Circle` to the provided values.
It always returns `None`.
This method is equivalent to the following code:
.. code-block:: python
circle.x = x
circle.y = y
circle.r = radius
.. versionadded:: 2.4.0
.. ## Circle.update ##
.. method:: rotate
| :sl:`rotates the circle`
| :sg:`rotate(angle, rotation_point=Circle.center, /) -> Circle`
| :sg:`rotate(angle, /) -> Circle`
Returns a copy of this `Circle` rotated by the specified angle (in degrees) around a point.
Positive angles rotate the circle clockwise, counter-clockwise otherwise.
The rotation point is optional and defaults to the circle's center.
.. versionadded:: 2.5.0
.. ## Circle.rotate ##
.. method:: rotate_ip
| :sl:`rotates the circle in place`
| :sg:`rotate_ip(angle, rotation_point=Circle.center, /) -> None`
| :sg:`rotate_ip(angle, /) -> None`
Rotates the circle by a specified angle (in degrees) around a point.
Positive angles rotate the circle clockwise, counter-clockwise otherwise.
The rotation point is optional and defaults to the circle's center.
.. versionadded:: 2.5.0
.. ## Circle.rotate_ip ##
.. method:: as_rect
| :sl:`returns the smallest Rect containing the circle`
| :sg:`as_rect() -> Rect`
Returns the smallest `pygame.Rect` object containing this `Circle`.
This method is equivalent to the following code:
.. code-block:: python
Rect(circle.x - circle.r, circle.y - circle.r, circle.r * 2, circle.r * 2)
.. versionadded:: 2.5.0
.. ## Circle.as_rect ##
.. method:: as_frect
| :sl:`returns the smallest FRect containing the circle`
| :sg:`as_frect() -> FRect`
Returns the smallest `pygame.FRect` object containing this `Circle`.
This method is equivalent to the following code:
.. code-block:: python
FRect(circle.x - circle.r, circle.y - circle.r, circle.r * 2, circle.r * 2)
.. versionadded:: 2.5.0
.. ## Circle.as_frect ##
.. method:: copy
| :sl:`copies the circle`
| :sg:`copy() -> Circle`
Returns a copy of this `Circle`.
.. versionadded:: 2.4.0
.. ## Circle.copy ##
.. ## pygame.Circle ##
.. class:: Line
| :sl:`pygame object for representing a line`
| :sg:`Line((ax, ay), (bx, by)) -> Line`
| :sg:`Line(ax, ay, bx, by) -> Line`
.. versionadded:: 2.5.2
The `Line` class provides many useful methods for collision testing, transformation and intersection.
A `Line` can be created from a combination of two pairs of coordinates that represent the start and end points.
Lines can also be created from python objects that are already a `Line` (effectively copying the line) or have an attribute named "line".
Specifically, to construct a `Line` you can pass the ax, ay, bx, and by values as separate
arguments or inside a sequence(list or tuple).
As a special case you can also pass in `pygame.Rect` / `pygame.FRect`, in which case the
line will be created with (x, y, width, height) as the start and end points.
You can create lines with the same start and end points, but beware that some methods may
not work as expected or error out.
Functions that require a `Line` argument may also accept these values as Lines:
::
((ax, ay), (bx, by))
(ax, ay, bx, by)
(vector2, vector2)
The `Line` class only stores the ax, ay, bx, and by attributes, everything else is calculated
on the fly based on them.
**Line Attributes**
----
.. attribute:: ax
| :sl:`x coordinate of the start point of the line`
| :sg:`ax -> float`
The horizontal coordinate of the start point of the line. Reassigning it moves the line.
.. versionadded:: 2.5.2
.. ## Line.ax ##
.. attribute:: ay
| :sl:`y coordinate of the start point of the line`
| :sg:`ay -> float`
The vertical coordinate of the start point of the line. Reassigning it moves the line.
.. versionadded:: 2.5.2
.. ## Line.ay ##
.. attribute:: bx
| :sl:`x coordinate of the end point of the line`
| :sg:`bx -> float`
The horizontal coordinate of the end point of the line. Reassigning it moves the line.
.. versionadded:: 2.5.2
.. ## Line.bx ##
.. attribute:: by
| :sl:`y coordinate of the end point of the line`
| :sg:`by -> float`
The vertical coordinate of the end point of the line. Reassigning it moves the line.
.. versionadded:: 2.5.2
.. ## Line.by ##
.. attribute:: a
| :sl:`the first point of the line`
| :sg:`a -> (float, float)`
A tuple containing the `ax` and `ay` attributes representing the line's first point.
It can be reassigned to move the `Line`. If reassigned the `ax` and `ay` attributes
will be changed to produce a `Line` with matching first point position.
The `bx` and `by` attributes will not be affected.
.. versionadded:: 2.5.2
.. ## Line.a ##
.. attribute:: b
| :sl:`the second point of the line`
| :sg:`b -> (float, float)`
A tuple containing `bx` and `by` attributes representing the line's second point.
It can be reassigned to move the `Line`. If reassigned the `bx` and `by` attributes
will be changed to produce a `Line` with matching second point position.
The `ax` and `ay` attributes will not be affected.
.. versionadded:: 2.5.2
.. ## Line.b ##
.. attribute:: length
| :sl:`the length of the line`
| :sg:`length -> float`
The length of the line. Calculated using the `sqrt((bx-ax)**2 + (by-ay)**2)` formula.
This attribute is read-only, it cannot be reassigned. To change the line's length
use the `scale` method or change its `a` or `b` attributes.
.. versionadded:: 2.5.3
.. ## Line.length ##
**Line Methods**
----
.. method:: copy
| :sl:`copies the line`
| :sg:`copy() -> Line`
Returns a copy of this `Line`.
.. versionadded:: 2.5.2
.. ## Line.copy ##
.. method:: move
| :sl:`moves the line by a given amount`
| :sg:`move((x, y)) -> Line`
| :sg:`move(x, y) -> Line`
Returns a new `Line` that is moved by the given offset. The original `Line` is
not modified.
This method is equivalent to the following code:
.. code-block:: python
Line(line.ax + x, line.ay + y, line.bx + x, line.by + y)
.. versionadded:: 2.5.3
.. ## Line.move ##
.. method:: move_ip
| :sl:`moves the line by a given amount`
| :sg:`move_ip((x, y)) -> None`
| :sg:`move_ip(x, y) -> None`
Moves the `Line` by the given offset. The original `Line` is modified. Always returns
`None`.
This method is equivalent to the following code:
.. code-block:: python
line.ax += x
line.ay += y
line.bx += x
line.by += y
.. versionadded:: 2.5.3
.. ## Line.move_ip ##
.. method:: update
| :sl:`updates the line's attributes`
| :sg:`update((ax, ay), (bx, by)) -> None`
| :sg:`update(ax, ay, bx, by) -> None`
| :sg:`update(line) -> None`
Updates the `Line`'s attributes. The original `Line` is modified. Always returns `None`.
This method is equivalent to the following code:
.. code-block:: python
line.ax = ax
line.ay = ay
line.bx = bx
line.by = by
.. versionadded:: 2.5.3
.. ## Line.update ##
.. method:: scale
| :sl:`scales the line by the given factor from the given origin`
| :sg:`scale(factor, origin) -> Line`
| :sg:`scale(factor_and_origin) -> Line`
Returns a new `Line` which is scaled by the given factor from the specified origin with 0.0 being
the starting point, 0.5 being the center and 1.0 being the end point.
The original `Line` is not modified.
.. versionadded:: 2.5.3
.. ## Line.scale ##
.. method:: scale_ip
| :sl:`scales the line by the given factor from the given origin in place`
| :sg:`scale_ip(factor, origin) -> None`
| :sg:`scale_ip(factor_and_origin) -> None`
Scales the `Line` by the given factor from the specified origin with 0.0 being
the starting point, 0.5 being the center and 1.0 being the end point.
The original `Line` is modified.
Always returns `None`.
.. versionadded:: 2.5.3
.. ## Line.scale_ip ##
.. method:: flip_ab
| :sl:`flips the line a and b points`
| :sg:`flip_ab() -> Line`
Returns a new `Line` that has the `a` and `b` points flipped.
The original `Line` is not modified.
.. versionadded:: 2.5.3
.. ## Line.flip_ab ##
.. method:: flip_ab_ip
| :sl:`flips the line a and b points, in place`
| :sg:`flip_ab_ip() -> None`
Flips the `Line`'s `a` and `b` points. The original `Line` is modified.
Always returns `None`.
.. versionadded:: 2.5.3
.. ## Line.flip_ab_ip ##
.. method:: project
| :sl:`projects the line onto the given line`
| :sg:`project(point: tuple[float, float], clamp=False) -> tuple[float, float]`
This method takes in a point and one boolean keyword argument clamp. It outputs an orthogonally projected point onto the line.
If clamp is `True` it makes sure that the outputted point will be on the line segment (which might not be orthogonal), and if it is `False` (the default) then any point on the infinitely extended line may be outputted.
This method can be used to find the closest point on a line to the given point. The output is the unique point on the line or line segment that is the smallest distance away from the given point.
.. figure:: code_examples/project.png
:alt: project method image
Example of how it projects the point onto the line. The red point is the point we want to project and the blue point is what you would get as a result.
.. figure:: code_examples/project_clamp.png
:alt: project clamp argument image
Example of what the clamp argument changes. If it is `True`, the point is bounded between the line segment ends.
WARNING: If the line has no length (i.e. the start and end points are the same) then the returned point of this function will be the same point as both ends of the line.
.. versionadded:: 2.5.6
.. ## Line.project ##
@@ -54,13 +54,13 @@ For example:
``pygame.gfxdraw`` wraps the primitives from the library called SDL_gfx,
rather than using modified versions.
.. versionaddedold:: 1.9.0
.. versionadded:: 1.9.0
.. function:: pixel
| :sl:`draw a pixel`
| :sg:`pixel(surface, x, y, color, /) -> None`
| :sg:`pixel(surface, x, y, color) -> None`
Draws a single pixel, at position (x ,y), on the given surface.
@@ -79,7 +79,7 @@ For example:
.. function:: hline
| :sl:`draw a horizontal line`
| :sg:`hline(surface, x1, x2, y, color, /) -> None`
| :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.
@@ -100,7 +100,7 @@ For example:
.. function:: vline
| :sl:`draw a vertical line`
| :sg:`vline(surface, x, y1, y2, color, /) -> None`
| :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.
@@ -121,7 +121,7 @@ For example:
.. function:: line
| :sl:`draw a line`
| :sg:`line(surface, x1, y1, x2, y2, color, /) -> None`
| :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.
@@ -143,7 +143,7 @@ For example:
.. function:: rectangle
| :sl:`draw a rectangle`
| :sg:`rectangle(surface, rect, color, /) -> None`
| :sg:`rectangle(surface, rect, color) -> None`
Draws an unfilled rectangle on the given surface. For a filled rectangle use
:meth:`box`.
@@ -167,7 +167,7 @@ For example:
.. function:: box
| :sl:`draw a filled rectangle`
| :sg:`box(surface, rect, color, /) -> None`
| :sg:`box(surface, rect, color) -> None`
Draws a filled rectangle on the given surface. For an unfilled rectangle use
:meth:`rectangle`.
@@ -197,7 +197,7 @@ For example:
.. function:: circle
| :sl:`draw a circle`
| :sg:`circle(surface, x, y, r, color, /) -> None`
| :sg:`circle(surface, x, y, r, color) -> None`
Draws an unfilled circle on the given surface. For a filled circle use
:meth:`filled_circle`.
@@ -218,7 +218,7 @@ For example:
.. function:: aacircle
| :sl:`draw an antialiased circle`
| :sg:`aacircle(surface, x, y, r, color, /) -> None`
| :sg:`aacircle(surface, x, y, r, color) -> None`
Draws an unfilled antialiased circle on the given surface.
@@ -238,7 +238,7 @@ For example:
.. function:: filled_circle
| :sl:`draw a filled circle`
| :sg:`filled_circle(surface, x, y, r, color, /) -> None`
| :sg:`filled_circle(surface, x, y, r, color) -> None`
Draws a filled circle on the given surface. For an unfilled circle use
:meth:`circle`.
@@ -259,7 +259,7 @@ For example:
.. function:: ellipse
| :sl:`draw an ellipse`
| :sg:`ellipse(surface, x, y, rx, ry, color, /) -> None`
| :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`.
@@ -281,7 +281,7 @@ For example:
.. function:: aaellipse
| :sl:`draw an antialiased ellipse`
| :sg:`aaellipse(surface, x, y, rx, ry, color, /) -> None`
| :sg:`aaellipse(surface, x, y, rx, ry, color) -> None`
Draws an unfilled antialiased ellipse on the given surface.
@@ -302,7 +302,7 @@ For example:
.. function:: filled_ellipse
| :sl:`draw a filled ellipse`
| :sg:`filled_ellipse(surface, x, y, rx, ry, color, /) -> None`
| :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`.
@@ -324,7 +324,7 @@ For example:
.. function:: arc
| :sl:`draw an arc`
| :sg:`arc(surface, x, y, r, start_angle, stop_angle, color, /) -> None`
| :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`.
@@ -356,7 +356,7 @@ For example:
.. function:: pie
| :sl:`draw a pie`
| :sg:`pie(surface, x, y, r, start_angle, stop_angle, color, /) -> None`
| :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.
@@ -385,7 +385,7 @@ For example:
.. function:: trigon
| :sl:`draw a trigon/triangle`
| :sg:`trigon(surface, x1, y1, x2, y2, x3, y3, color, /) -> None`
| :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`.
@@ -412,7 +412,7 @@ For example:
.. function:: aatrigon
| :sl:`draw an antialiased trigon/triangle`
| :sg:`aatrigon(surface, x1, y1, x2, y2, x3, y3, color, /) -> None`
| :sg:`aatrigon(surface, x1, y1, x2, y2, x3, y3, color) -> None`
Draws an unfilled antialiased trigon (triangle) on the given surface.
@@ -438,7 +438,7 @@ For example:
.. function:: filled_trigon
| :sl:`draw a filled trigon/triangle`
| :sg:`filled_trigon(surface, x1, y1, x2, y2, x3, y3, color, /) -> None`
| :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`.
@@ -465,12 +465,12 @@ For example:
.. function:: polygon
| :sl:`draw a polygon`
| :sg:`polygon(surface, points, color, /) -> None`
| :sg:`polygon(surface, points, color) -> None`
Draws an unfilled polygon on the given surface. For a filled polygon use
:meth:`filled_polygon`.
The adjacent points in the ``points`` argument, as well as the first
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
@@ -478,10 +478,10 @@ For example:
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
point in the sequence must be a
*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(point) or list(point)
: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])
@@ -490,7 +490,7 @@ For example:
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(point) < 2`` (each point must have
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.polygon ##
@@ -498,11 +498,11 @@ For example:
.. function:: aapolygon
| :sl:`draw an antialiased polygon`
| :sg:`aapolygon(surface, points, color, /) -> None`
| :sg:`aapolygon(surface, points, color) -> None`
Draws an unfilled antialiased polygon on the given surface.
The adjacent points in the ``points`` argument, as well as the first
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
@@ -510,10 +510,10 @@ For example:
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
point in the sequence must be a
*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(point) or list(point)
: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])
@@ -522,7 +522,7 @@ For example:
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(point) < 2`` (each point must have
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.aapolygon ##
@@ -530,12 +530,12 @@ For example:
.. function:: filled_polygon
| :sl:`draw a filled polygon`
| :sg:`filled_polygon(surface, points, color, /) -> None`
| :sg:`filled_polygon(surface, points, color) -> None`
Draws a filled polygon on the given surface. For an unfilled polygon use
:meth:`polygon`.
The adjacent points in the ``points`` argument, as well as the first
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
@@ -543,10 +543,10 @@ For example:
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
point in the sequence must be a
*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(point) or list(point)
: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])
@@ -555,7 +555,7 @@ For example:
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(point) < 2`` (each point must have
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.filled_polygon ##
@@ -563,7 +563,7 @@ For example:
.. function:: textured_polygon
| :sl:`draw a textured polygon`
| :sg:`textured_polygon(surface, points, texture, tx, ty, /) -> None`
| :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.
@@ -572,7 +572,7 @@ For example:
a :func:`pygame.Surface.blit` blit. Also, a per-pixel alpha texture cannot be
used with an 8-bit per pixel destination.
The adjacent points in the ``points`` argument, as well as the first
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
@@ -580,10 +580,10 @@ For example:
:param Surface surface: surface to draw on
:param points: a sequence of 3 or more (x, y) coordinates, where each
point in the sequence must be a
*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(point) or list(point)
: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
@@ -592,7 +592,7 @@ For example:
:rtype: NoneType
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(point) < 2`` (each point must have
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. ## pygame.gfxdraw.textured_polygon ##
@@ -600,16 +600,16 @@ For example:
.. function:: bezier
| :sl:`draw a Bezier curve`
| :sg:`bezier(surface, points, steps, color, /) -> None`
| :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 point in the sequence must be 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(point) or list(point)
: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])``
@@ -620,12 +620,9 @@ For example:
:raises ValueError: if ``steps < 2``
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises IndexError: if ``len(point) < 2`` (each point must have
:raises IndexError: if ``len(coordinate) < 2`` (each coordinate must have
at least 2 items)
.. note:: This function supports up to around 150-200 points before the algorithm
breaks down.
.. ## pygame.gfxdraw.bezier ##
.. ## pygame.gfxdraw ##
@@ -3,5 +3,373 @@
:mod:`pygame.image`
===================
.. autopgmodule:: pygame.image
:members:
.. module:: pygame.image
:synopsis: pygame module for loading and saving images
| :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.).
In the vast majority of installations, pygame is built to support extended
formats, using the SDL_Image library behind the scenes. However, some
installations may only support uncompressed ``BMP`` images. With full image
support, the :func:`pygame.image.load()` function can load 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
:func:`pygame.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
:func:`pygame.Surface.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 :func:`pygame.image.get_extended()`
returns ``True``, you should be able to load most images (including PNG, JPG
and GIF).
You should use :func:`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(linked=True) -> None`
| :sg:`get_sdl_image_version(linked=True) -> (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``.
``linked=True`` is the default behavior and the function will return the
version of the library that Pygame is linked against, while ``linked=False``
will return the version of the library that Pygame is compiled against.
.. versionadded:: 2.0.0
.. versionchanged:: 2.2.0 ``linked`` keyword argument added and default behavior changed from returning compiled version to returning linked version
.. ## 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 byte buffer`
| :sg:`tostring(Surface, format, flipped=False) -> bytes`
Creates a string of bytes that can be transferred with the ``fromstring``
or ``frombytes`` methods 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 byte 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
* ``BGRA``, 32-bit image with alpha channel, red and blue channels swapped
* ``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
.. note:: it is preferred to use :func:`tobytes` as of pygame 2.1.3
.. versionadded:: 2.1.3 BGRA format
.. ## pygame.image.tostring ##
.. function:: tobytes
| :sl:`transfer image to byte buffer`
| :sg:`tobytes(Surface, format, flipped=False) -> bytes`
Creates a string of bytes that can be transferred with the ``fromstring``
or ``frombytes`` methods 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 byte 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
* ``BGRA``, 32-bit image with alpha channel, red and blue channels swapped
* ``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
.. note:: this function is an alias for :func:`tostring`. The use of this
function is recommended over :func:`tostring` as of pygame 2.1.3.
This function was introduced so it matches nicely with other
libraries (PIL, numpy, etc), and with people's expectations.
.. versionadded:: 2.1.3
.. ## pygame.image.tobytes ##
.. function:: fromstring
| :sl:`create new Surface from a byte buffer`
| :sg:`fromstring(bytes, size, format, flipped=False) -> Surface`
This function takes arguments similar to :func:`pygame.image.tostring()`.
The size argument is a pair of numbers representing the width and height.
Once the new Surface is created it is independent from the memory of the
bytes passed in.
The bytes and format passed must compute to the exact size of image
specified. Otherwise a ``ValueError`` will be raised.
See the :func:`pygame.image.frombuffer()` method for a potentially faster
way to transfer images into pygame.
.. note:: it is preferred to use :func:`frombytes` as of pygame 2.1.3
.. ## pygame.image.fromstring ##
.. function:: frombytes
| :sl:`create new Surface from a byte buffer`
| :sg:`frombytes(bytes, size, format, flipped=False) -> Surface`
This function takes arguments similar to :func:`pygame.image.tobytes()`.
The size argument is a pair of numbers representing the width and height.
Once the new Surface is created it is independent from the memory of the
bytes passed in.
The bytes and format passed must compute to the exact size of image
specified. Otherwise a ``ValueError`` will be raised.
See the :func:`pygame.image.frombuffer()` method for a potentially faster
way to transfer images into pygame.
.. note:: this function is an alias for :func:`fromstring`. The use of this
function is recommended over :func:`fromstring` as of pygame 2.1.3.
This function was introduced so it matches nicely with other
libraries (PIL, numpy, etc), and with people's expectations.
.. versionadded:: 2.1.3
.. ## pygame.image.frombytes ##
.. function:: frombuffer
| :sl:`create a new Surface that shares data inside a bytes buffer`
| :sg:`frombuffer(buffer, size, format) -> Surface`
Create a new Surface that shares pixel data directly from a buffer. This
buffer can be bytes, a bytearray, a memoryview, a
:class:`pygame.BufferProxy`, or any object that supports the buffer protocol.
This method takes similar arguments to :func:`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
* ``BGRA``, 32-bit image with alpha channel, red and blue channels swapped
.. versionadded:: 2.1.3 BGRA format
.. ## 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 :func:`pygame.image.load()`, except that this
function can only be used if pygame was built with extended image format
support.
.. versionchanged:: 2.0.1
This function is always available, but raises an
``NotImplementedError`` 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.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.
In case 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`` in case the namehint was not specified while
saving to a file-like object.
.. versionchanged:: 2.0.1
This function is always available, but raises an
``NotImplementedError`` 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 ##
@@ -85,7 +85,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
| :sl:`Returns the number of joysticks.`
| :sg:`get_count() -> count`
Return the number of joystick devices on the system. The count will be ``0``
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
@@ -96,7 +96,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
.. class:: Joystick
| :sl:`Create a new Joystick object.`
| :sg:`Joystick(id, /) -> Joystick`
| :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``.
@@ -105,10 +105,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
Once the device is initialized the pygame event queue will start receiving
events about its input.
.. versionchangedold:: 2.0.0 Joystick objects are now opened immediately on creation.
.. versionchanged:: 2.1.4 This class is also available through the ``pygame.Joystick``
alias.
.. versionchanged:: 2.0.0 Joystick objects are now opened immediately on creation.
.. method:: init
@@ -118,10 +115,10 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
Initialize the joystick, if it has been closed. It is safe to call this
even if the joystick is already initialized.
.. deprecatedold:: 2.0.0
.. deprecated:: 2.0.0
In future it will not be possible to reinitialise a closed Joystick
object.
object. Will be removed in Pygame 2.1.
.. ## Joystick.init ##
@@ -155,10 +152,10 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
value that was passed to the ``Joystick()`` constructor. This method can
safely be called while the Joystick is not initialized.
.. deprecatedold:: 2.0.0
.. deprecated:: 2.0.0
The original device index is not useful in pygame 2. Use
:meth:`.get_instance_id` instead.
:meth:`.get_instance_id` instead. Will be removed in Pygame 2.1.
.. method:: get_instance_id() -> int
@@ -168,7 +165,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
Get the joystick instance ID. This matches the ``instance_id`` field
that is given in joystick events.
.. versionaddedold:: 2.0.0dev11
.. versionadded:: 2.0.0dev11
.. method:: get_guid() -> str
@@ -178,7 +175,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
Get the GUID string. This identifies the exact hardware of the joystick
device.
.. versionaddedold:: 2.0.0dev11
.. versionadded:: 2.0.0dev11
.. method:: get_power_level() -> str
@@ -190,7 +187,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
One of: ``empty``, ``low``, ``medium``, ``full``, ``wired``, ``max``, or
``unknown``.
.. versionaddedold:: 2.0.0dev11
.. versionadded:: 2.0.0dev11
.. ## Joystick.get_id ##
@@ -215,13 +212,13 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
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
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 ##
@@ -229,12 +226,12 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
.. method:: get_axis
| :sl:`get the current position of an axis`
| :sg:`get_axis(axis_number, /) -> float`
| :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
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``.
@@ -261,7 +258,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
.. method:: get_ball
| :sl:`get the relative position of a trackball`
| :sg:`get_ball(ball_number, /) -> x, y`
| :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.
@@ -286,7 +283,7 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
.. method:: get_button
| :sl:`get the current button state`
| :sg:`get_button(button, /) -> bool`
| :sg:`get_button(button) -> bool`
Returns the current state of a joystick button.
@@ -302,8 +299,8 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
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)``
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 ##
@@ -311,15 +308,15 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
.. method:: get_hat
| :sl:`get the position of a joystick hat`
| :sg:`get_hat(hat_number, /) -> x, y`
| :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
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``
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``.
@@ -338,9 +335,9 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
playing, then it will be overwritten.
Returns True if the rumble was played successfully or False if the
joystick does not support it.
joystick does not support it or :meth:`pygame.version.SDL` is below 2.0.9.
.. versionaddedold:: 2.0.2
.. versionadded:: 2.0.2
.. ## Joystick.rumble ##
@@ -352,26 +349,10 @@ variable. See :ref:`environment variables <environment-variables>` for more deta
Stops any rumble effect playing on the joystick. See
:meth:`Joystick.rumble` for more information.
.. versionaddedold:: 2.0.2
.. versionadded:: 2.0.2
.. ## Joystick.stop_rumble ##
.. method:: set_led
| :sl:`Set the LED color of the joystick`
| :sg:`set_led(color_arg) -> bool`
Set the color of the LED on the joystick. The argument is a
``pygame.Color``-compatible value (alpha being ignored). The
joystick's LED, if it has one, will be set to the input color.
If the joystick does not have an addressable LED, then this
method will do nothing and return False. Returns True if the
LED was set successfully.
.. versionadded:: 2.5.6
.. ## Joystick.set_led ##
.. ## pygame.joystick.Joystick ##
.. ## pygame.joystick ##
@@ -400,75 +381,35 @@ Nintendo Switch Left Joy-Con (pygame 2.x)
*****************************************
The Nintendo Switch Left Joy-Con has 4 axes, 11 buttons, and 0 hats. The values for the 4 axes never change.
The controller is recognized as "Wireless Gamepad".
After SDL 2.24.0, The controller is recognized as "Nintendo Switch Joy-Con (L)".
The controller is recognized as "Wireless Gamepad"
* **Buttons**::
After SDL 2.24.0 Before SDL 2.24.0
D-pad Up Button 2 Button 3
D-pad Down Button 1 Button 0
D-pad Left Button 3 Button 2
D-pad Right Button 0 Button 1
SL Button 9 Button 4
SR Button 10 Button 5
- Button 6 Button 8
Stick In Button 7 Button 10
Capture Button 5 Button 13
L Button 17 Button 14
ZL Button 19 Button 15
Reference : D-pad Up points toward SL and SR buttons.
D-pad Up - Button 0
D-pad Down - Button 1
D-pad Left - Button 2
D-pad Right - Button 3
SL - Button 4
SR - Button 5
- - Button 8
Stick In - Button 10
Capture - Button 13
L - Button 14
ZL - Button 15
* **Hat/JoyStick**::
Down -> Up - Axis 1 Axis Y
Left -> Right - Axis 0 Axis X
Down -> Up - Y Axis
Left -> Right - X Axis
Nintendo Switch Right Joy-Con (pygame 2.x)
******************************************
The Nintendo Switch Right Joy-Con has 4 axes, 11 buttons, and 0 hats. The values for the 4 axes never change.
The controller is recognized as "Wireless Gamepad".
After SDL 2.24.0, The controller is recognized as "Nintendo Switch Joy-Con (R)".
The controller is recognized as "Wireless Gamepad"
* **Buttons**::
After SDL 2.24.0 Before SDL 2.24.0
A Button Button 1 Button 0
B Button Button 3 Button 2
X Button Button 0 Button 1
Y Button Button 2 Button 3
SL Button 9 Button 4
SR Button 10 Button 5
+ Button 6 Button 9
Stick In Button 7 Button 11
Home Button 5 Button 12
R Button 16 Button 14
ZR Button 18 Button 15
* **Hat/JoyStick**::
Down -> Up - Axis 1 Axis Y
Left -> Right - Axis 0 Axis X
Nintendo Switch Left/Right Joy-Con (after SDL **2.24.0**)
*********************************************************
This device is created, if Nintendo Switch Joy-con Left and Nintendo Switch Joy-con Right are connected (these two devices are removed).
The Nintendo Switch Left/Right Joy-Con has 6 axes, 20 buttons, and 0 hats. The values for the 6 axes never change.
The controller is recognized as "Nintendo Switch Joy-Con (L/R)".
* **Left Stick**::
Left -> Right - Axis 0
Up -> Down - Axis 1
* **Right Stick**::
Left -> Right - Axis 2
Up -> Down - Axis 3
* **Buttons**::
@@ -476,22 +417,19 @@ The controller is recognized as "Nintendo Switch Joy-Con (L/R)".
B Button - Button 1
X Button - Button 2
Y Button - Button 3
- Button - Button 4
Home Button - Button 5
+ Button - Button 6
ZL - Button ? Missing
ZR - Button ? Missing
L. Stick In - Button 9
R. Stick In - Button 10
D-pad Up - Button 11
D-pad Down - Button 12
D-pad Left - Button 13
D-pad Right - Button 14
Capture Button - Button 15
Right SR - Button 16
Left SL - Button 17
Right SL - Button 18
Left SR - Button 19
SL - Button 4
SR - Button 5
+ - Button 9
Stick In - Button 11
Home - Button 12
R - Button 14
ZR - Button 15
* **Hat/JoyStick**::
Down -> Up - Y Axis
Left -> Right - X Axis
Nintendo Switch Pro Controller (pygame 2.x)
*******************************************
@@ -625,6 +563,52 @@ The controller is recognized as "PS4 Controller".
D-pad Right - Button 14
Touch Pad Click - Button 15
Playstation 5 Controller (pygame 2.x)
*************************************
The PlayStation 5 controller mapping has 6 axes, 13 buttons, and 1 hat.
The controller is recognized as "Sony Interactive Entertainment Wireless Controller".
* **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**::
Cross Button - Button 0
Circle Button - Button 1
Square Button - Button 2
Triangle Button - Button 3
Left Bumper - Button 4
Right Bumper - Button 5
Left Trigger - Button 6
Right Trigger - Button 7
Share Button - Button 8
Options Button - Button 9
PS Button - Button 10
Left Stick in - Button 11
Right Stick in - Button 12
* **Hat/D-pad**::
Down -> Up - Y Axis
Left -> Right - X Axis
XBox 360 Controller (pygame 1.x)
********************************
@@ -710,3 +694,4 @@ The controller is recognized as "Wireless Controller".
Down -> Up - Y Axis
Left -> Right - X Axis
@@ -3,6 +3,453 @@
:mod:`pygame.key`
=================
.. autopgmodule:: pygame.key
:members:
:exclude-members: ScancodeWrapper
.. 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.
.. versionadded:: 2.2.0
The collection of bools returned by ``get_pressed`` can not be iterated
over because the indexes of the internal tuple does not correspond to the
keycodes.
.. versionadded:: 2.5.0
Iteration over the collection of bools returned by ``get_pressed`` is now
restored. However it still does not make sense to iterate over it. Currently.
.. ## 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, use_compat=True) -> str`
Get the descriptive name of the button from a keyboard button id constant.
Returns an empty string (``""``) if the key is not found.
If ``use_compat`` argument is ``True`` (which is the default), this function
returns the legacy name of a key where applicable. The return value is
expected to be the same across different pygame versions (provided the
corresponding key constant exists and is unique). If the return value is
passed to the ``key_code`` function, the original constant will be returned.
**Experimental:** ``use_compat`` parameter still in development for testing and feedback. It may change.
`Please leave use_compat feedback with authors <https://github.com/pygame/pygame/pull/3312>`_
If this argument is ``False``, the returned name may be prettier to display
and may cover a wider range of keys than with ``use_compat``, but there are
no guarantees that this name will be the same across different pygame
versions. If the name returned is passed to the ``key_code`` function, the
original constant is returned back (this is an implementation detail which
may change later, do not rely on this)
.. versionchanged:: 2.1.3 Added ``use_compat`` argument and guaranteed API stability for it
.. ## 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.
.. 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 ##
@@ -14,7 +14,7 @@ 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-ce documentation. Here are the locations of some of them.
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`.
@@ -3,6 +3,640 @@
:mod:`pygame.mask`
==================
.. autopgmodule:: pygame.mask
:members:
:exclude-members: MaskType
.. 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 ##
File diff suppressed because it is too large. Load diff
@@ -8,7 +8,7 @@
| :sl:`pygame module for interacting with midi input and output.`
.. versionaddedold:: 1.9.0
.. 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.
@@ -23,7 +23,7 @@ future. The pyportmidi bindings are included with pygame.
|
.. versionaddedold:: 2.0.0
.. 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
@@ -71,7 +71,7 @@ midi events to pygame events.
:returns: ``True`` if the :mod:`pygame.midi` module is currently initialized.
:rtype: bool
.. versionaddedold:: 1.9.5
.. versionadded:: 1.9.5
.. ## pygame.midi.get_init ##
@@ -218,7 +218,7 @@ midi events to pygame events.
If no value is given, the pitch bend is returned to "no change".
.. versionaddedold:: 1.9.4
.. versionadded:: 1.9.4
.. method:: write
@@ -439,7 +439,7 @@ midi events to pygame events.
frequency_to_midi(27.5) == 21
.. versionaddedold:: 1.9.5
.. versionadded:: 1.9.5
.. ## pygame.midi.frequency_to_midi ##
@@ -454,7 +454,7 @@ midi events to pygame events.
midi_to_frequency(21) == 27.5
.. versionaddedold:: 1.9.5
.. versionadded:: 1.9.5
.. ## pygame.midi.midi_to_frequency ##
@@ -469,7 +469,7 @@ midi events to pygame events.
midi_to_ansi_note(21) == 'A0'
.. versionaddedold:: 1.9.5
.. versionadded:: 1.9.5
.. ## pygame.midi.midi_to_ansi_note ##
@@ -9,7 +9,9 @@
| :sl:`pygame module for loading and playing sounds`
This module contains classes for loading Sound objects and controlling
playback.
playback. The mixer module is optional and depends on SDL_mixer. Your program
should test that :mod:`pygame.mixer` is available and initialized before using
it.
The mixer module has a limited number of channels for playback of sounds.
Usually programs tell pygame to start playing audio and it selects an available
@@ -28,7 +30,9 @@ streams the music from the files without loading music at once into memory.
The mixer module must be initialized like other pygame modules, but it has some
extra conditions. The ``pygame.mixer.init()`` function takes several optional
arguments to control the playback rate and sample size.
arguments to control the playback rate and sample size. Pygame will default to
reasonable values, but pygame cannot perform Sound resampling, so the mixer
should be initialized to match the values of your audio resources.
``NOTE``: For less laggy sound use a smaller buffer size. The default
is set to reduce the chance of scratchy sounds on some computers. You can
@@ -36,26 +40,6 @@ change the default buffer by calling :func:`pygame.mixer.pre_init` before
:func:`pygame.mixer.init` or :func:`pygame.init` is called. For example:
``pygame.mixer.pre_init(44100,-16,2, 1024)``
The following file formats are supported
* ``WAV``
* ``MP3``
* ``OGG``
* ``FLAC``
* ``OPUS``
* ``WV`` (WavPack)
* ``MOD`` ("Module file" family of music file formats)
* ``MIDI`` (see the :func:`get_soundfont` and :func:`set_soundfont` methods)
.. versionadded:: 2.5.0 Loading WV (Relies on SDL_mixer 2.8.0+)
.. function:: init
@@ -64,7 +48,7 @@ The following file formats are supported
Initialize the mixer module for Sound loading and playback. The default
arguments can be overridden to provide specific audio mixing. Keyword
arguments are accepted. For backwards compatibility, argument values of
arguments are accepted. For backwards compatibility, argument values of
0 are replaced with the startup defaults, except for ``allowedchanges``,
where -1 is used. (startup defaults may be changed by a :func:`pre_init` call).
@@ -75,9 +59,6 @@ The following file formats are supported
The channels argument is used to specify whether to use mono or stereo. 1
for mono and 2 for stereo.
``NOTE``: The channels argument is not related to the number
of channels for playback of sounds, that you can get with the function
"get_num_channels" or set with the function "set_num_channels" (see below).
The buffer argument controls the number of internal samples used in the
sound mixer. The default value should work for most cases. It can be lowered
@@ -86,10 +67,6 @@ The following file formats are supported
playback. The buffer size must be a power of two (if not it is rounded up to
the next nearest power of 2).
The devicename parameter is the name of sound device to open for audio
playback. Allowed device names will vary based on the host system.
If left as ``None`` then a sensible default will be chosen for you.
Some platforms require the :mod:`pygame.mixer` module to be initialized
after the display modules have initialized. The top level ``pygame.init()``
takes care of this automatically, but cannot pass any arguments to the mixer
@@ -100,7 +77,7 @@ The following file formats are supported
what the hardware supports. For example a sound card may not
support 16bit sound samples, so instead it will use 8bit samples internally.
If AUDIO_ALLOW_FORMAT_CHANGE is supplied, then the requested format will
change to the closest that SDL supports.
change to the closest that SDL2 supports.
Apart from 0, allowedchanged accepts the following constants ORed together:
@@ -113,13 +90,13 @@ The following file formats are supported
you cannot change the playback arguments without first calling
``pygame.mixer.quit()``.
.. versionchangedold:: 1.8 The default ``buffersize`` changed from 1024 to 3072.
.. versionchangedold:: 1.9.1 The default ``buffersize`` changed from 3072 to 4096.
.. versionchangedold:: 2.0.0 The default ``buffersize`` changed from 4096 to 512.
.. versionchangedold:: 2.0.0 The default ``frequency`` changed from 22050 to 44100.
.. versionchangedold:: 2.0.0 ``size`` can be 32 (32-bit floats).
.. versionchangedold:: 2.0.0 ``channels`` can also be 4 or 6.
.. versionaddedold:: 2.0.0 ``allowedchanges``, ``devicename`` arguments added
.. versionchanged:: 1.8 The default ``buffersize`` changed from 1024 to 3072.
.. versionchanged:: 1.9.1 The default ``buffersize`` changed from 3072 to 4096.
.. versionchanged:: 2.0.0 The default ``buffersize`` changed from 4096 to 512.
.. versionchanged:: 2.0.0 The default ``frequency`` changed from 22050 to 44100.
.. versionchanged:: 2.0.0 ``size`` can be 32 (32-bit floats).
.. versionchanged:: 2.0.0 ``channels`` can also be 4 or 6.
.. versionadded:: 2.0.0 ``allowedchanges``, ``devicename`` arguments added
.. ## pygame.mixer.init ##
@@ -135,11 +112,11 @@ The following file formats are supported
For backwards compatibility, argument values of 0 are replaced with the
startup defaults, except for ``allowedchanges``, where -1 is used.
.. versionchangedold:: 1.8 The default ``buffersize`` changed from 1024 to 3072.
.. versionchangedold:: 1.9.1 The default ``buffersize`` changed from 3072 to 4096.
.. versionchangedold:: 2.0.0 The default ``buffersize`` changed from 4096 to 512.
.. versionchangedold:: 2.0.0 The default ``frequency`` changed from 22050 to 44100.
.. versionaddedold:: 2.0.0 ``allowedchanges``, ``devicename`` arguments added
.. versionchanged:: 1.8 The default ``buffersize`` changed from 1024 to 3072.
.. versionchanged:: 1.9.1 The default ``buffersize`` changed from 3072 to 4096.
.. versionchanged:: 2.0.0 The default ``buffersize`` changed from 4096 to 512.
.. versionchanged:: 2.0.0 The default ``frequency`` changed from 22050 to 44100.
.. versionadded:: 2.0.0 ``allowedchanges``, ``devicename`` arguments added
.. ## pygame.mixer.pre_init ##
@@ -157,25 +134,13 @@ The following file formats are supported
.. function:: get_init
| :sl:`test if the mixer is initialized`
| :sg:`get_init() -> (frequency, format, channels) | None`
| :sg:`get_init() -> (frequency, format, channels)`
If the mixer is initialized, this returns the playback arguments it is
using. If the mixer has not been initialized this returns ``None``.
.. ## pygame.mixer.get_init ##
.. function:: get_driver
| :sl:`get the name of the current audio backend driver`
| :sg:`get_driver() -> str`
Pygame chooses one of many available audio backend drivers when it is
initialized. This returns the internal name used for the backend. This
function is intended to be used for getting diagnostic/debugging information.
This can be controlled with ``SDL_AUDIODRIVER`` environment variable.
.. versionadded:: 2.5.0
.. function:: stop
| :sl:`stop playback of all sound channels`
@@ -207,7 +172,7 @@ The following file formats are supported
.. function:: fadeout
| :sl:`fade out the volume on all sounds before stopping`
| :sg:`fadeout(time, /) -> None`
| :sg:`fadeout(time) -> None`
This will fade out the volume on all active channels over the time argument
in milliseconds. After the sound is muted the playback will stop.
@@ -217,9 +182,9 @@ The following file formats are supported
.. function:: set_num_channels
| :sl:`set the total number of playback channels`
| :sg:`set_num_channels(count, /) -> None`
| :sg:`set_num_channels(count) -> None`
Sets the number of available playback channels for the mixer. The default value is 8.
Sets the number of available channels for the mixer. The default value is 8.
The value can be increased or decreased. If the value is decreased, sounds
playing on the truncated channels are stopped.
@@ -237,10 +202,10 @@ The following file formats are supported
.. function:: set_reserved
| :sl:`reserve channels from being automatically used`
| :sg:`set_reserved(count, /) -> count`
| :sg:`set_reserved(count) -> count`
The mixer can reserve any number of channels that will not be automatically
selected for playback by Sounds. This means that whenever you play a Sound
selected for playback by Sounds. This means that whenever you play a Sound
without specifying a channel, a reserved channel will never be used. If sounds
are currently playing on the reserved channels they will not be stopped.
@@ -256,7 +221,7 @@ The following file formats are supported
.. function:: find_channel
| :sl:`find an unused channel`
| :sg:`find_channel(force=False) -> Channel | None`
| :sg:`find_channel(force=False) -> Channel`
This will find and return an inactive Channel object. If there are no
inactive Channels this function will return ``None``. If there are no
@@ -265,50 +230,13 @@ The following file formats are supported
.. ## pygame.mixer.find_channel ##
.. function:: set_soundfont
| :sl:`set the soundfont for playing midi music`
| :sg:`set_soundfont(path, /) -> None`
This sets the soundfont file to be used in the playback of midi music.
The soundfont only affects the playback of ``MID``, ``MIDI``, and ``KAR`` file formats.
The optional ``path`` argument, a string (or multiple strings separated by a semi-colon),
must point to the soundfont file(s) to be searched for in order given if some
are missing. If ``path`` is an empty string or the default (``None``), any specified soundfont paths
will be cleared from the mixer.
Note on Windows, the mixer always uses the built-in soundfont instead of the one specified.
Function :func:`set_soundfont` calls underlying SDL_mixer function
``Mix_SetSoundFonts``.
.. versionadded:: 2.3.1
.. ## pygame.mixer.set_soundfont ##
.. function:: get_soundfont
| :sl:`get the soundfont for playing midi music`
| :sg:`get_soundfont() -> paths`
This gets the soundfont filepaths as a string (each path is separated by a semi-colon)
to be used in the playback of ``MID``, ``MIDI``, and ``KAR`` music file formats. If no
soundfont is specified, the return type is ``None``.
Function :func:`get_soundfont` calls underlying SDL_mixer function
``Mix_GetSoundFonts``.
.. versionadded:: 2.3.1
.. ## pygame.mixer.get_soundfont ##
.. function:: get_busy
| :sl:`test if any sound is being mixed`
| :sg:`get_busy() -> bool`
Returns ``True`` if the mixer is busy mixing any channels. If the mixer is
idle or uninitialized then this returns ``False``.
idle then this return ``False``.
.. ## pygame.mixer.get_busy ##
@@ -327,9 +255,9 @@ The following file formats are supported
:rtype: tuple
.. note::
The linked and compiled version numbers should be the same.
The linked and compile version numbers should be the same.
.. versionaddedold:: 2.0.0
.. versionadded:: 2.0.0
.. ## pygame.mixer.get_sdl_mixer_version ##
@@ -350,11 +278,11 @@ The following file formats are supported
the initialize arguments for the mixer. A Unicode string can only be a file
pathname. A bytes object can be either a pathname or a buffer object.
Use the 'file' or 'buffer' keywords to avoid ambiguity; otherwise Sound may
guess wrong. If the array keyword is used, the object is expected to export
guess wrong. If the array keyword is used, the object is expected to export
a new buffer interface (The object is checked for a buffer interface first.)
The Sound object represents actual sound sample data. Methods that change
the state of the Sound object will impact all instances of the Sound playback.
the state of the Sound object will the all instances of the Sound playback.
A Sound object also exports a new buffer interface.
The Sound can be loaded from an ``OGG`` audio file or from an uncompressed
@@ -369,17 +297,10 @@ The following file formats are supported
an exception when different. Also, source samples are truncated to fit the
audio sample size. This will not change.
.. note:: ``bytes(Sound)`` and ``bytearray(Sound)`` make use of the buffer
interface, which is implemented internally by ``pygame.mixer.Sound``.
Because of this, there is no need to directly implement ``__bytes__``.
.. versionaddedold:: 1.8 ``pygame.mixer.Sound(buffer)``
.. versionaddedold:: 1.9.2
.. versionadded:: 1.8 ``pygame.mixer.Sound(buffer)``
.. versionadded:: 1.9.2
:class:`pygame.mixer.Sound` keyword arguments and array interface support
.. versionaddedold:: 2.0.1 pathlib.Path support on Python 3.
.. versionchanged:: 2.5.2 This class is also available through the ``pygame.Sound``
alias.
.. versionadded:: 2.0.1 pathlib.Path support on Python 3.
.. method:: play
@@ -420,7 +341,7 @@ The following file formats are supported
.. method:: fadeout
| :sl:`stop sound playback after fading out`
| :sg:`fadeout(time, /) -> None`
| :sg:`fadeout(time) -> None`
This will stop playback of the sound after fading it out over the time
argument in milliseconds. The Sound will fade and stop on all actively
@@ -431,7 +352,7 @@ The following file formats are supported
.. method:: set_volume
| :sl:`set the playback volume for this Sound`
| :sg:`set_volume(value, /) -> None`
| :sg:`set_volume(value) -> None`
This will set the playback volume (loudness) for this Sound. This will
immediately affect the Sound if it is playing. It will also affect any
@@ -442,25 +363,6 @@ The following file formats are supported
| If value < 0.0, the volume will not be changed
| If value > 1.0, the volume will be set to 1.0
.. note::
The values are internally converted and kept as integer values in range [0, 128], which means
that ``get_volume()`` may return a different volume than it was set to. For example,
>>> sound.set_volume(0.1)
>>> sound.get_volume()
0.09375
This is because when you ``set_volume(0.1)``, the volume is internally calculated like so
>>> int(0.1 * 128)
12
This means that some of the precision is lost, so when you retrieve it again using ``get_volume()``,
it is converted back to a ``float`` using that integer
>>> 12 / 128
0.09375
.. ## Sound.set_volume ##
.. method:: get_volume
@@ -468,10 +370,7 @@ The following file formats are supported
| :sl:`get the playback volume`
| :sg:`get_volume() -> value`
Return a value from 0.0 to 1.0 (inclusive) representing the volume for this Sound.
.. note::
See :func:`Sound.set_volume` for more information regarding the returned value
Return a value from 0.0 to 1.0 representing the volume for this Sound.
.. ## Sound.get_volume ##
@@ -500,30 +399,10 @@ The following file formats are supported
Return a copy of the Sound object buffer as a bytes.
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
.. ## Sound.get_raw ##
.. method:: copy
| :sl:`return a new Sound object that is a deep copy of this Sound`
| :sg:`copy() -> Sound`
| :sg:`copy.copy(original_sound) -> Sound`
Return a new Sound object that is a deep copy of this Sound. The new Sound
will be just as if you loaded it from the same file on disk as you did the
original Sound. If the copy fails, a ``TypeError`` or :meth:`pygame.error`
exception will be raised.
If copying a subclass of ``mixer.Sound``, an instance of the same subclass
will be returned.
Also note that this functions as ``Sound.__copy__``.
.. versionadded:: 2.5.6
.. ## Sound.copy ##
.. ## pygame.mixer.Sound ##
.. class:: Channel
@@ -532,28 +411,12 @@ The following file formats are supported
| :sg:`Channel(id) -> Channel`
Return a Channel object for one of the current channels. The id must be a
value from 0 up to, but not including, ``pygame.mixer.get_num_channels()``.
value from 0 to the value of ``pygame.mixer.get_num_channels()``.
The Channel object can be used to get fine control over the playback of
Sounds. A channel can only playback a single Sound at time. Using channels
is entirely optional since pygame can manage them by default.
.. versionchanged:: 2.1.4 This class is also available through the ``pygame.Channel``
alias.
.. versionchanged:: 2.4.0 It is now possible to create subclasses of ``pygame.mixer.Channel``
.. attribute:: id
| :sl:`get the channel id for the Channel object`
| :sg:`id -> int`
This simply returns the channel id used to create the ``Channel`` instance
as a read-only attribute
.. versionadded:: 2.4.0
.. ## Channel.id ##
.. method:: play
| :sl:`play a Sound on a specific Channel`
@@ -607,59 +470,28 @@ The following file formats are supported
.. method:: fadeout
| :sl:`stop playback after fading channel out`
| :sg:`fadeout(time, /) -> None`
| :sg:`fadeout(time) -> None`
Stop playback of a channel after fading out the sound over the given time
argument in milliseconds.
.. ## Channel.fadeout ##
.. method:: set_source_location
| :sl:`set the position of a playing channel`
| :sg:`set_source_location(angle, distance, /) -> None`
Set the position (angle, distance) of a playing channel.
`angle`: Angle in degrees.
`distance`: Range from 0 to 255.
.. warning:: This function currently fails and raises a
:exc:`pygame.error` when using 7.1 surround sound.
By default, the mixer module will use what the hardware is best
suited for, so this leads to hardware specific exceptions when using
this function.
One way of avoiding this is only using :func:`set_source_location`
with forced stereo. For example:
::
pygame.mixer.pre_init(
channels=2,
allowedchanges=pygame.AUDIO_ALLOW_FREQUENCY_CHANGE,
)
pygame.init()
.. versionadded:: 2.3.0
.. ## Channel.set_source_location ##
.. method:: set_volume
| :sl:`set the volume of a playing channel`
| :sg:`set_volume(value, /) -> None`
| :sg:`set_volume(left, right, /) -> None`
| :sg:`set_volume(value) -> None`
| :sg:`set_volume(left, right) -> None`
Set the volume (loudness) of a playing sound. When a channel starts to
play its volume value is reset. This only affects the current sound. The
value argument is in the range of 0.0 to 1.0 (inclusive).
value argument is between 0.0 and 1.0.
If one argument is passed, it will be the volume of both speakers. If two
arguments are passed and the mixer is in stereo mode, the first argument
will be the volume of the left speaker and the second will be the volume
of the right speaker.
of the right speaker. (If the second argument is ``None``, the first
argument will be the volume of both speakers.)
If the channel is playing a Sound on which ``set_volume()`` has also been
called, both calls are taken into account. For example:
@@ -672,9 +504,6 @@ The following file formats are supported
sound.set_volume(0.6) # Now plays at 60% (previous value replaced).
channel.set_volume(0.5) # Now plays at 30% (0.6 * 0.5).
.. note::
See :func:`Sound.set_volume` for more information regarding how the value is stored internally
.. ## Channel.set_volume ##
.. method:: get_volume
@@ -682,15 +511,11 @@ The following file formats are supported
| :sl:`get the volume of the playing channel`
| :sg:`get_volume() -> value`
Return the volume of the channel for the current playing sound
in the range of 0.0 to 1.0 (inclusive). This does
Return the volume of the channel for the current playing sound. This does
not take into account stereo separation used by
:meth:`Channel.set_volume`. The Sound object also has its own volume
which is mixed with the channel.
.. note::
See :func:`Sound.set_volume` for more information regarding the returned value
.. ## Channel.get_volume ##
.. method:: get_busy
@@ -706,7 +531,7 @@ The following file formats are supported
.. method:: get_sound
| :sl:`get the currently playing Sound`
| :sg:`get_sound() -> Sound | None`
| :sg:`get_sound() -> Sound`
Return the actual Sound object currently playing on this channel. If the
channel is idle ``None`` is returned.
@@ -716,7 +541,7 @@ The following file formats are supported
.. method:: queue
| :sl:`queue a Sound object to follow the current`
| :sg:`queue(sound, /) -> None`
| :sg:`queue(Sound) -> None`
When a Sound is queued on a Channel, it will begin playing immediately
after the current Sound is finished. Each channel can only have a single
@@ -732,7 +557,7 @@ The following file formats are supported
.. method:: get_queue
| :sl:`return any Sound that is queued`
| :sg:`get_queue() -> Sound | None`
| :sg:`get_queue() -> Sound`
If a Sound is already queued on this channel it will be returned. Once
the queued sound begins playback it will no longer be on the queue.
@@ -743,7 +568,7 @@ The following file formats are supported
| :sl:`have the channel send an event when playback stops`
| :sg:`set_endevent() -> None`
| :sg:`set_endevent(type, /) -> None`
| :sg:`set_endevent(type) -> None`
When an endevent is set for a channel, it will send an event to the
pygame queue every time a sound finishes playing on that channel (not
@@ -3,5 +3,217 @@
:mod:`pygame.mouse`
===================
.. autopgmodule:: pygame.mouse
:members:
.. module:: pygame.mouse
:synopsis: pygame module to work with the mouse
| :sl:`pygame module to work with the mouse`
The mouse functions can be used to get the current state of the mouse device.
These functions can also alter the system cursor for the mouse.
When the display mode is set, the event queue will start receiving mouse
events. The mouse buttons generate ``pygame.MOUSEBUTTONDOWN`` and
``pygame.MOUSEBUTTONUP`` events when they are pressed and released. These
events contain a button attribute representing which button was pressed. The
mouse wheel will generate ``pygame.MOUSEBUTTONDOWN`` and
``pygame.MOUSEBUTTONUP`` events when rolled. The button will be set to 4
when the wheel is rolled up, and to button 5 when the wheel is rolled down.
Whenever the mouse is moved it generates a ``pygame.MOUSEMOTION`` event. The
mouse movement is broken into small and accurate motion events. As the mouse
is moving many motion events will be placed on the queue. Mouse motion events
that are not properly cleaned from the event queue are the primary reason the
event queue fills up.
If the mouse cursor is hidden, and input is grabbed to the current display the
mouse will enter a virtual input mode, where the relative movements of the
mouse will never be stopped by the borders of the screen. See the functions
``pygame.mouse.set_visible()`` and ``pygame.event.set_grab()`` to get this
configured.
**Mouse Wheel Behavior in pygame 2**
There is proper functionality for mouse wheel behaviour with pygame 2 supporting
``pygame.MOUSEWHEEL`` events. The new events support horizontal and vertical
scroll movements, with signed integer values representing the amount scrolled
(``x`` and ``y``), as well as ``flipped`` direction (the set positive and
negative values for each axis is flipped). Read more about SDL2
input-related changes here `<https://wiki.libsdl.org/MigrationGuide#input>`_
In pygame 2, the mouse wheel functionality can be used by listening for the
``pygame.MOUSEWHEEL`` type of an event (Bear in mind they still emit
``pygame.MOUSEBUTTONDOWN`` events like in pygame 1.x, as well).
When this event is triggered, a developer can access the appropriate ``Event`` object
with ``pygame.event.get()``. The object can be used to access data about the mouse
scroll, such as ``which`` (it will tell you what exact mouse device trigger the event).
.. code-block:: python
:caption: Code example of mouse scroll (tested on 2.0.0.dev7)
:name: test.py
# Taken from husano896's PR thread (slightly modified)
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
return
elif event.type == MOUSEWHEEL:
print(event)
print(event.x, event.y)
print(event.flipped)
print(event.which)
# can access properties with
# proper notation(ex: event.y)
clock.tick(60)
# Execute game:
main()
.. function:: get_pressed
| :sl:`get the state of the mouse buttons`
| :sg:`get_pressed(num_buttons=3) -> (button1, button2, button3)`
| :sg:`get_pressed(num_buttons=5) -> (button1, button2, button3, button4, button5)`
Returns a sequence of booleans representing the state of all the mouse
buttons. A true value means the mouse is currently being pressed at the time
of the call.
Note, to get all of the mouse events it is better to use either
``pygame.event.wait()`` or ``pygame.event.get()`` and check all of those
events to see if they are ``MOUSEBUTTONDOWN``, ``MOUSEBUTTONUP``, or
``MOUSEMOTION``.
Note, that on ``X11`` some X servers use middle button emulation. When you
click both buttons ``1`` and ``3`` at the same time a ``2`` button event
can be emitted.
Note, remember to call ``pygame.event.get()`` before this function.
Otherwise it will not work as expected.
To support five button mice, an optional parameter ``num_buttons`` has been
added in pygame 2. When this is set to ``5``, ``button4`` and ``button5``
are added to the returned tuple. Only ``3`` and ``5`` are valid values
for this parameter.
.. versionchanged:: 2.0.0 ``num_buttons`` argument added
.. ## pygame.mouse.get_pressed ##
.. function:: get_pos
| :sl:`get the mouse cursor position`
| :sg:`get_pos() -> (x, y)`
Returns the ``x`` and ``y`` position of the mouse cursor. The position is
relative to the top-left corner of the display. The cursor position can be
located outside of the display window, but is always constrained to the
screen.
.. ## pygame.mouse.get_pos ##
.. function:: get_rel
| :sl:`get the amount of mouse movement`
| :sg:`get_rel() -> (x, y)`
Returns the amount of movement in ``x`` and ``y`` since the previous call to
this function. The relative movement of the mouse cursor is constrained to
the edges of the screen, but see the virtual input mouse mode for a way
around this. Virtual input mode is described at the top of the page.
.. ## pygame.mouse.get_rel ##
.. function:: set_pos
| :sl:`set the mouse cursor position`
| :sg:`set_pos([x, y]) -> None`
Set the current mouse position to arguments given. If the mouse cursor is
visible it will jump to the new coordinates. Moving the mouse will generate
a new ``pygame.MOUSEMOTION`` event.
.. ## pygame.mouse.set_pos ##
.. function:: set_visible
| :sl:`hide or show the mouse cursor`
| :sg:`set_visible(bool) -> bool`
If the bool argument is true, the mouse cursor will be visible. This will
return the previous visible state of the cursor.
.. ## pygame.mouse.set_visible ##
.. function:: get_visible
| :sl:`get the current visibility state of the mouse cursor`
| :sg:`get_visible() -> bool`
Get the current visibility state of the mouse cursor. ``True`` if the mouse is
visible, ``False`` otherwise.
.. versionadded:: 2.0.0
.. ## pygame.mouse.get_visible ##
.. function:: get_focused
| :sl:`check if the display is receiving mouse input`
| :sg:`get_focused() -> bool`
Returns true when pygame is receiving mouse input events (or, in windowing
terminology, is "active" or has the "focus").
This method is most useful when working in a window. By contrast, in
full-screen mode, this method always returns true.
Note: under ``MS`` Windows, the window that has the mouse focus also has the
keyboard focus. But under X-Windows, one window can receive mouse events and
another receive keyboard events. ``pygame.mouse.get_focused()`` indicates
whether the pygame window receives mouse events.
.. ## pygame.mouse.get_focused ##
.. function:: set_cursor
| :sl:`set the mouse cursor to a new cursor`
| :sg:`set_cursor(pygame.cursors.Cursor) -> None`
| :sg:`set_cursor(size, hotspot, xormasks, andmasks) -> None`
| :sg:`set_cursor(hotspot, surface) -> None`
| :sg:`set_cursor(constant) -> None`
Set the mouse cursor to something new. This function accepts either an explicit
``Cursor`` object or arguments to create a ``Cursor`` object.
See :class:`pygame.cursors.Cursor` for help creating cursors and for examples.
.. versionchanged:: 2.0.1
.. ## pygame.mouse.set_cursor ##
.. function:: get_cursor
| :sl:`get the current mouse cursor`
| :sg:`get_cursor() -> pygame.cursors.Cursor`
Get the information about the mouse system cursor. The return value contains
the same data as the arguments passed into :func:`pygame.mouse.set_cursor()`.
.. note:: Code that unpacked a get_cursor() call into
``size, hotspot, xormasks, andmasks`` will still work,
assuming the call returns an old school type cursor.
.. versionchanged:: 2.0.1
.. ## pygame.mouse.get_cursor ##
.. ## pygame.mouse ##
@@ -20,8 +20,6 @@ changed in pygame ``v2.0.2`` which got improved MP3 support. Consider using
``OGG`` file format for music as that can give slightly better compression than
MP3 in most cases.
For a complete list of supported file formats, see the :mod:`pygame.mixer` doc page.
.. function:: load
| :sl:`Load a music file for playback`
@@ -35,8 +33,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
If you are loading from a file object, the namehint parameter can be used to specify
the type of music data in the object. For example: :code:`load(fileobj, "ogg")`.
.. versionchangedold:: 2.0.2 Added optional ``namehint`` argument
.. versionchanged:: 2.2.0 Raises ``FileNotFoundError`` instead of :exc:`pygame.error` if file cannot be found
.. versionchanged:: 2.0.2 Added optional ``namehint`` argument
.. ## pygame.mixer.music.load ##
@@ -47,7 +44,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
This closes resources like files for any music that may be loaded.
.. versionaddedold:: 2.0.0
.. versionadded:: 2.0.0
.. ## pygame.mixer.music.load ##
@@ -59,18 +56,18 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
This will play the loaded music stream. If the music is already playing it
will be restarted.
``loops`` is an optional integer argument, which is ``0`` by default, which
indicates how many times to repeat the music. The music repeats indefinitely if
this argument is set to ``-1``.
``start`` is an optional float argument, which is ``0.0`` by default, which
denotes the position in time from which the music starts playing. The starting
position depends on the format of the music played. ``MP3`` and ``OGG`` use
``loops`` is an optional integer argument, which is ``0`` by default, which
indicates how many times to repeat the music. The music repeats indefinitely if
this argument is set to ``-1``.
``start`` is an optional float argument, which is ``0.0`` by default, which
denotes the position in time from which the music starts playing. The starting
position depends on the format of the music played. ``MP3`` and ``OGG`` use
the position as time in seconds. For ``MP3`` files the start time position
selected may not be accurate as things like variable bit rate encoding and ID3
tags can throw off the timing calculations. For ``MOD`` music it is the pattern
order number. Passing a start position will raise a NotImplementedError if
tags can throw off the timing calculations. For ``MOD`` music it is the pattern
order number. Passing a start position will raise a NotImplementedError if
the start position cannot be set.
``fade_ms`` is an optional integer argument, which is ``0`` by default,
@@ -78,8 +75,8 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
will fade up from volume level ``0.0`` to full volume (or the volume level
previously set by :func:`set_volume`). The sample may end before the fade-in
is complete. If the music is already streaming ``fade_ms`` is ignored.
.. versionchangedold:: 2.0.0 Added optional ``fade_ms`` argument
.. versionchanged:: 2.0.0 Added optional ``fade_ms`` argument
.. ## pygame.mixer.music.play ##
@@ -90,7 +87,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
Resets playback of the current music to the beginning. If :func:`pause` has
previously been used to pause the music, the music will remain paused.
.. note:: :func:`rewind` supports a limited number of file types and notably
``WAV`` files are NOT supported. For unsupported file types use :func:`play`
which will restart the music that's already playing (note that this
@@ -131,16 +128,16 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
.. function:: fadeout
| :sl:`stop music playback after fading out`
| :sg:`fadeout(time, /) -> None`
| :sg:`fadeout(time) -> None`
Fade out and stop the currently playing music.
The ``time`` argument denotes the integer milliseconds for which the
The ``time`` argument denotes the integer milliseconds for which the
fading effect is generated.
Note, that this function blocks until the music has faded out. Calls
to :func:`fadeout` and :func:`set_volume` will have no effect during
this time. If an event was set using :func:`set_endevent` it will be
Note, that this function blocks until the music has faded out. Calls
to :func:`fadeout` and :func:`set_volume` will have no effect during
this time. If an event was set using :func:`set_endevent` it will be
called after the music has faded.
.. ## pygame.mixer.music.fadeout ##
@@ -148,19 +145,16 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
.. function:: set_volume
| :sl:`set the music volume`
| :sg:`set_volume(volume, /) -> None`
| :sg:`set_volume(volume) -> None`
Set the volume of the music playback.
The ``volume`` argument is a float between ``0.0`` and ``1.0`` that sets
The ``volume`` argument is a float between ``0.0`` and ``1.0`` that sets
the volume level. When new music is loaded the volume is reset to full
volume. If ``volume`` is a negative value it will be ignored and the
volume will remain set at the current level. If the ``volume`` argument
is greater than ``1.0``, the volume will be set to ``1.0``.
.. note::
See :func:`mixer.Sound.set_volume()<pygame.mixer.Sound.set_volume>` for more information regarding how the value is stored internally
.. ## pygame.mixer.music.set_volume ##
.. function:: get_volume
@@ -168,12 +162,9 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
| :sl:`get the music volume`
| :sg:`get_volume() -> value`
Returns the current volume for the mixer. The value will be between ``0.0``
Returns the current volume for the mixer. The value will be between ``0.0``
and ``1.0``.
.. note::
See :func:`mixer.Sound.set_volume()<pygame.mixer.Sound.set_volume>` for more information regarding the returned value
.. ## pygame.mixer.music.get_volume ##
.. function:: get_busy
@@ -186,19 +177,19 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
False when the music is paused. In pygame 1 it returns True when the music
is paused.
.. versionchangedold:: 2.0.1 Returns False when music paused.
.. versionchanged:: 2.0.1 Returns False when music paused.
.. ## pygame.mixer.music.get_busy ##
.. function:: set_pos
| :sl:`set position to play from`
| :sg:`set_pos(pos, /) -> None`
| :sg:`set_pos(pos) -> None`
This sets the position in the music file where playback will start.
The meaning of "pos", a float (or a number that can be converted to a float),
depends on the music format.
For ``MOD`` files, pos is the integer pattern number in the module.
For ``OGG`` it is the absolute position, in seconds, from
the beginning of the sound. For ``MP3`` files, it is the relative position,
@@ -206,13 +197,13 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
file, first call :func:`rewind`.
Other file formats are unsupported. Newer versions of SDL_mixer have
better positioning support than earlier ones. A :exc:`pygame.error` is
raised if a particular format does not support positioning.
better positioning support than earlier ones. An SDLError is raised if a
particular format does not support positioning.
Function :func:`set_pos` calls underlying SDL_mixer function
Function :func:`set_pos` calls underlining SDL_mixer function
``Mix_SetMusicPosition``.
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
.. ## pygame.mixer.music.set_pos ##
@@ -225,8 +216,6 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
The returned time only represents how long the music has been playing; it
does not take into account any starting position offsets.
Returns -1 if ``get_pos`` failed due to music not playing.
.. ## pygame.mixer.music.get_pos ##
.. function:: queue
@@ -253,8 +242,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
pygame.mixer.music.play(5) # Plays six times, not five!
pygame.mixer.music.queue('mozart.ogg')
.. versionchangedold:: 2.0.2 Added optional ``namehint`` argument
.. versionchanged:: 2.2.0 Raises ``FileNotFoundError`` instead of :exc:`pygame.error` if file cannot be found
.. versionchanged:: 2.0.2 Added optional ``namehint`` argument
.. ## pygame.mixer.music.queue ##
@@ -262,7 +250,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
| :sl:`have the music send an event when playback stops`
| :sg:`set_endevent() -> None`
| :sg:`set_endevent(type, /) -> None`
| :sg:`set_endevent(type) -> None`
This causes pygame to signal (by means of the event queue) when the music is
done playing. The argument determines the type of event that will be queued.
@@ -284,31 +272,3 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p
.. ## pygame.mixer.music.get_endevent ##
.. ## pygame.mixer.music ##
.. function:: get_metadata
| :sl:`get metadata of the specified or currently loaded music stream`
| :sg:`get_metadata() -> dict`
| :sg:`get_metadata(filename) -> dict`
| :sg:`get_metadata(fileobj, namehint="") -> dict`
If no arguments are passed returns a dictionary containing metadata
of the currently loaded music stream, raises an exception if a music stream is not loaded.
Available keys are ``"title"``, ``"album"``, ``"artist"``, ``"copyright"``.
Values are strings containing corresponding retrieved metadata.
If particular metadata was not found the value is an empty string.
Here is an example:
``{'title': 'Small Tone', 'album': 'Tones', 'artist': 'Audacity Generator', 'copyright': ''}``
Refer to the :func:`pygame.mixer.music.load` function for arguments regarding specifying a file or a file-like object
whose metadata you want to retrieve. For this function all arguments are optional,
however, specifying only the ``namehint`` will raise an exception.
Since the underlying functionality was introduced in version 2.6.0 of SDL_mixer,
calling this function with an older version of SDL_mixer will return a dictionary
with all values being set to empty strings. You can find your version of SDL_mixer
by using :func:`pygame.mixer.get_sdl_mixer_version`.
.. versionadded:: 2.1.4
.. ## pygame.mixer.music.get_metadata ##
@@ -42,7 +42,7 @@
if pxarray[0, 0] == surface.map_rgb((0, 0, 255)):
...
When assigning to a range of pixels, a non tuple sequence of colors or
When assigning to a range of of pixels, a non tuple sequence of colors or
a PixelArray can be used as the value. For a sequence, the length must
match the PixelArray width.
@@ -79,7 +79,7 @@
pxarray[::2] = (0, 0, 0) # Same as [::2, :]
During its lifetime, the PixelArray locks the surface, thus you explicitly
have to close() it once it's not used any more and the surface should perform
have to close() it once its not used any more and the surface should perform
operations in the same scope. It is best to use it as a context manager
using the with PixelArray(surf) as pixel_array: style. So it works on pypy too.
@@ -100,19 +100,19 @@
copying is implemented it is suggested PixelArray to PixelArray copies be
only between surfaces of identical format.
.. versionaddedold:: 1.9.4
.. versionadded:: 1.9.4
- close() method was added. For explicitly cleaning up.
- being able to use PixelArray as a context manager for cleanup.
- both of these are useful for when working without reference counting (pypy).
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
- array struct interface
- transpose method
- broadcasting for a length 1 dimension
.. versionchangedold:: 1.9.2
.. versionchanged:: 1.9.2
- A 2D PixelArray can have a length 1 dimension.
Only an integer index on a 2D PixelArray returns a 1D array.
@@ -120,27 +120,23 @@
is a sequence of colors.
.. versionaddedold: 1.8.0
.. versionadded: 1.8.0
Subscript support
.. versionaddedold: 1.8.1
.. versionadded: 1.8.1
Methods :meth:`make_surface`, :meth:`replace`, :meth:`extract`, and
:meth:`compare`
.. versionaddedold: 1.9.2
.. versionadded: 1.9.2
Properties :attr:`itemsize`, :attr:`ndim`, :attr:`shape`,
and :attr:`strides`
.. versionaddedold: 1.9.2
.. versionadded: 1.9.2
Array struct interface
.. versionaddedold: 1.9.4
.. versionadded: 1.9.4
Methods :meth:`close`
.. versionchanged:: 2.5.8
Fixed incorrect color matching and writing on 24-bit surfaces whose
byte layout did not match the platform default.
.. attribute:: surface
| :sl:`Gets the Surface the PixelArray uses.`
@@ -158,7 +154,7 @@
This is the same as :meth:`Surface.get_bytesize` for the
pixel array's surface.
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
.. attribute:: ndim
@@ -167,7 +163,7 @@
A pixel array can be 1 or 2 dimensional.
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
.. attribute:: shape
@@ -177,7 +173,7 @@
A tuple or length :attr:`ndim` giving the length of each
dimension. Analogous to :meth:`Surface.get_size`.
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
.. attribute:: strides
@@ -189,7 +185,7 @@
of that index from the start of the array. A stride is negative
for an array that has is inverted (has a negative step).
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
.. method:: make_surface
@@ -205,7 +201,7 @@
# Create a new surface flipped around the vertical axis.
sf = pxarray[:,::-1].make_surface ()
.. versionaddedold:: 1.8.1
.. versionadded:: 1.8.1
.. ## PixelArray.make_surface ##
@@ -226,11 +222,7 @@
This is an in place operation that directly affects the pixels of the
PixelArray.
.. versionaddedold:: 1.8.1
.. versionchanged:: 2.5.8
Fixed incorrect color matching and writing on 24-bit surfaces whose
byte layout did not match the platform default.
.. versionadded:: 1.8.1
.. ## PixelArray.replace ##
@@ -249,7 +241,7 @@
extraction to take pixels with a similar, but not exactly identical
color, into account as well.
.. versionaddedold:: 1.8.1
.. versionadded:: 1.8.1
.. ## PixelArray.extract ##
@@ -269,7 +261,7 @@
comparison to mark pixels with a similar, but not exactly identical
color, as white.
.. versionaddedold:: 1.8.1
.. versionadded:: 1.8.1
.. ## PixelArray.compare ##
@@ -283,7 +275,7 @@
If an array is one dimensional, then a length 1 x dimension is added,
resulting in a 2D pixel array.
.. versionaddedold:: 1.9.2
.. versionadded:: 1.9.2
.. ## PixelArray.transpose ##
@@ -295,7 +287,7 @@
This method is for explicitly closing the PixelArray, and releasing
a lock on the Surface.
.. versionaddedold:: 1.9.4
.. versionadded:: 1.9.4
.. ## PixelArray.close ##
@@ -3,5 +3,102 @@
:mod:`pygame.pixelcopy`
=======================
.. autopgmodule:: pygame.pixelcopy
:members:
.. module:: pygame.pixelcopy
:synopsis: pygame module for general pixel array copying
| :sl:`pygame module for general pixel array copying`
The ``pygame.pixelcopy`` module contains functions for copying between
surfaces and objects exporting an array structure interface. It is a backend
for :mod:`pygame.surfarray`, adding NumPy support. But pixelcopy is more
general, and intended for direct use.
The array struct interface exposes an array's data in a standard way.
It was introduced in NumPy. In Python 2.7 and above it is replaced by the
new buffer protocol, though the buffer protocol is still a work in progress.
The array struct interface, on the other hand, is stable and works with earlier
Python versions. So for now the array struct interface is the predominate way
pygame handles array introspection.
For 2d arrays of integer pixel values, the values are mapped to the
pixel format of the related surface. To get the actual color of a pixel
value use :meth:`pygame.Surface.unmap_rgb`. 2d arrays can only be used
directly between surfaces having the same pixel layout.
New in pygame 1.9.2.
.. function:: surface_to_array
| :sl:`copy surface pixels to an array object`
| :sg:`surface_to_array(array, surface, kind='P', opaque=255, clear=0) -> None`
The surface_to_array function copies pixels from a Surface object
to a 2D or 3D array. Depending on argument ``kind`` and the target array
dimension, a copy may be raw pixel value, RGB, a color component slice,
or colorkey alpha transparency value. Recognized ``kind`` values are the
single character codes 'P', 'R', 'G', 'B', 'A', and 'C'. Kind codes are case
insensitive, so 'p' is equivalent to 'P'. The first two dimensions
of the target must be the surface size (w, h).
The default 'P' kind code does a direct raw integer pixel (mapped) value
copy to a 2D array and a 'RGB' pixel component (unmapped) copy to a 3D array
having shape (w, h, 3). For an 8 bit colormap surface this means the
table index is copied to a 2D array, not the table value itself. A 2D
array's item size must be at least as large as the surface's pixel
byte size. The item size of a 3D array must be at least one byte.
For the 'R', 'G', 'B', and 'A' copy kinds a single color component
of the unmapped surface pixels are copied to the target 2D array.
For kind 'A' and surfaces with source alpha (the surface was created with
the SRCALPHA flag), has a colorkey
(set with :meth:`Surface.set_colorkey() <pygame.Surface.set_colorkey>`),
or has a blanket alpha
(set with :meth:`Surface.set_alpha() <pygame.Surface.set_alpha>`)
then the alpha values are those expected for a SDL surface.
If a surface has no explicit alpha value, then the target array
is filled with the value of the optional ``opaque`` surface_to_array
argument (default 255: not transparent).
Copy kind 'C' is a special case for alpha copy of a source surface
with colorkey. Unlike the 'A' color component copy, the ``clear``
argument value is used for colorkey matches, ``opaque`` otherwise.
By default, a match has alpha 0 (totally transparent), while everything
else is alpha 255 (totally opaque). It is a more general implementation
of :meth:`pygame.surfarray.array_colorkey`.
Specific to surface_to_array, a ValueError is raised for target arrays
with incorrect shape or item size. A TypeError is raised for an incorrect
kind code. Surface specific problems, such as locking, raise a pygame.error.
.. ## pygame.pixelcopy.surface_to_array ##
.. function:: array_to_surface
| :sl:`copy an array object to a surface`
| :sg:`array_to_surface(<surface>, <array>) -> None`
See :func:`pygame.surfarray.blit_array`.
.. ## pygame.pixelcopy.array_to_surface ##
.. function:: map_array
| :sl:`copy an array to another array, using surface format`
| :sg:`map_array(<array>, <array>, <surface>) -> None`
Map an array of color element values - (w, h, ..., 3) - to an array of
pixels - (w, h) according to the format of <surface>.
.. ## pygame.pixelcopy.map_array ##
.. function:: make_surface
| :sl:`Copy an array to a new surface`
| :sg:`pygame.pixelcopy.make_surface(array) -> Surface`
Create a new Surface that best resembles the data and format of the array.
The array can be 2D or 3D with any sized integer values.
.. ## pygame.pixelcopy.make_surface ##
.. ## pygame.pixelcopy ##
Loaded 100 of 764 files, more files were not shown because too many files have changed in this diff. Show more