Cross-platform library for developing multimedia applications and video games in Python built on top of SDL
npx @tessl/cli install tessl/pypi-pygame@2.6.0A comprehensive cross-platform library for developing multimedia applications and video games in Python. Built on top of the Simple DirectMedia Layer (SDL), pygame provides a high-level interface for graphics rendering, sound playback, input handling, and game development utilities, abstracting complex low-level operations into intuitive Python APIs.
pip install pygameimport pygameFor specific modules:
import pygame.display
import pygame.image
import pygame.mixer
from pygame.locals import * # Import all constantsimport pygame
import sys
# Initialize pygame
pygame.init()
# Set up display
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My Game")
# Game loop
clock = pygame.time.Clock()
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill screen with color
screen.fill((0, 0, 0)) # Black
# Draw something
pygame.draw.circle(screen, (255, 0, 0), (400, 300), 50)
# Update display
pygame.display.flip()
clock.tick(60) # 60 FPS
pygame.quit()
sys.exit()Pygame is organized into three categories of modules:
The library follows a graceful degradation pattern where missing optional modules are replaced with helpful error messages rather than crashes.
Essential pygame initialization, configuration, and core utilities including the main init/quit cycle, error handling, and version information.
def init() -> tuple[int, int]:
"""Initialize all pygame modules, returns (numpass, numfail)"""
def quit() -> None:
"""Uninitialize all pygame modules"""
def get_init() -> bool:
"""Returns True if pygame is initialized"""Display window management, screen surface creation, and display configuration including fullscreen mode, window properties, and OpenGL integration.
def set_mode(size: tuple[int, int], flags: int = 0, depth: int = 0, display: int = 0, vsync: int = 0) -> pygame.Surface:
"""Create a display surface"""
def flip() -> None:
"""Update the full display surface"""
def update(rectangle: pygame.Rect = None) -> None:
"""Update portions of the display"""Primitive shape drawing functions for creating graphics including lines, circles, rectangles, polygons, and advanced drawing with antialiasing.
def rect(surface: pygame.Surface, color, rect: pygame.Rect, width: int = 0, border_radius: int = 0) -> pygame.Rect:
"""Draw a rectangle on a surface"""
def circle(surface: pygame.Surface, color, center: tuple[int, int], radius: int, width: int = 0) -> pygame.Rect:
"""Draw a circle on a surface"""
def line(surface: pygame.Surface, color, start_pos: tuple[int, int], end_pos: tuple[int, int], width: int = 1) -> pygame.Rect:
"""Draw a line on a surface"""High-precision graphics primitives with antialiasing, filled shapes, and complex drawing operations for professional-quality rendering including bezier curves, pie charts, and textured polygons.
def aacircle(surface: pygame.Surface, x: int, y: int, r: int, color) -> None:
"""Draw an antialiased circle"""
def filled_polygon(surface: pygame.Surface, points: list[tuple[int, int]], color) -> None:
"""Draw a filled polygon"""
def bezier(surface: pygame.Surface, points: list[tuple[int, int]], steps: int, color) -> None:
"""Draw a bezier curve"""Surface creation, manipulation, and image loading/saving including pixel access, transformations, color operations, and format conversions.
class Surface:
def __init__(self, size: tuple[int, int], flags: int = 0, depth: int = 0, masks = None): ...
def blit(self, source: 'Surface', dest: tuple[int, int], area: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect: ...
def fill(self, color, rect: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect: ...
def get_rect(self, **kwargs) -> pygame.Rect: ...Event queue management and input handling including keyboard, mouse, and joystick events with filtering and custom event creation.
def get(eventtype = None, pump: bool = True, exclude = None) -> list[pygame.event.Event]:
"""Get events from the queue"""
def poll() -> pygame.event.Event:
"""Get a single event from the queue"""
def wait(timeout: int = 0) -> pygame.event.Event:
"""Wait for a single event"""Keyboard and mouse input handling including state checking, position tracking, text input, and cursor management with comprehensive support for all input methods.
def get_pressed() -> ScancodeWrapper:
"""Get the state of all keyboard keys"""
def get_pos() -> tuple[int, int]:
"""Get the mouse cursor position"""
def set_cursor(*args) -> None:
"""Set mouse cursor appearance (system, bitmap, or color cursors)"""Complete gamepad, joystick, and game controller support including analog sticks, triggers, buttons, d-pads, and haptic feedback for comprehensive game input handling.
def get_count() -> int:
"""Get number of connected joysticks"""
class Joystick:
def __init__(self, id: int): ...
def get_axis(self, axis_number: int) -> float: ...
def get_button(self, button: int) -> bool: ...
def rumble(self, low_frequency: float, high_frequency: float, duration: int) -> bool: ...Audio system including sound effects, music streaming, mixing channels, and volume control with support for multiple audio formats.
class Sound:
def __init__(self, file_or_buffer): ...
def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> pygame.mixer.Channel: ...
def stop(self) -> None: ...
def get_volume(self) -> float: ...
def set_volume(self, value: float) -> None: ...Font loading and text rendering including system fonts, TrueType fonts, text metrics, and styling options.
class Font:
def __init__(self, filename, size: int): ...
def render(self, text: str, antialias: bool, color, background = None) -> pygame.Surface: ...
def size(self, text: str) -> tuple[int, int]: ...
def get_height(self) -> int: ...Sprite and collision system for managing game objects including sprite groups, collision detection algorithms, and update/rendering workflows.
class Sprite:
def __init__(self): ...
def update(self, *args): ...
def kill(self) -> None: ...
class Group:
def __init__(self, *sprites): ...
def update(self, *args): ...
def draw(self, surface: pygame.Surface) -> None: ...Mathematical functions and vector operations including 2D/3D vectors, collision detection math, and utility functions for game calculations.
class Vector2:
def __init__(self, x: float = 0, y: float = 0): ...
def dot(self, vector: 'Vector2') -> float: ...
def cross(self, vector: 'Vector2') -> float: ...
def normalize(self) -> 'Vector2': ...
def rotate(self, angle: float) -> 'Vector2': ...
class Vector3:
def __init__(self, x: float = 0, y: float = 0, z: float = 0): ...Timing control, frame rate management, and animation support including clock objects, delays, and timer events for smooth gameplay.
class Clock:
def __init__(self): ...
def tick(self, framerate: int = 0) -> int: ...
def get_fps(self) -> float: ...
def get_time(self) -> int: ...
def get_ticks() -> int:
"""Get milliseconds since pygame.init() was called"""
def wait(milliseconds: int) -> int:
"""Pause the program for an amount of time"""Image transformation operations including scaling, rotation, flipping, and advanced image processing filters.
def scale(surface: pygame.Surface, size: tuple[int, int]) -> pygame.Surface:
"""Resize a surface to new resolution"""
def rotate(surface: pygame.Surface, angle: float) -> pygame.Surface:
"""Rotate an image"""
def flip(surface: pygame.Surface, xbool: bool, ybool: bool) -> pygame.Surface:
"""Flip an image vertically and horizontally"""Transform and Image Processing
class Rect:
def __init__(self, left: int, top: int, width: int, height: int): ...
# Position properties
x: int
y: int
top: int
left: int
bottom: int
right: int
center: tuple[int, int]
# Size properties
width: int
height: int
size: tuple[int, int]
# Methods
def move(self, x: int, y: int) -> 'Rect': ...
def inflate(self, x: int, y: int) -> 'Rect': ...
def colliderect(self, rect: 'Rect') -> bool: ...
def contains(self, rect: 'Rect') -> bool: ...
def union(self, rect: 'Rect') -> 'Rect': ...
def clip(self, rect: 'Rect') -> 'Rect': ...class Color:
def __init__(self, r: int, g: int = None, b: int = None, a: int = 255): ...
# Color components
r: int # Red (0-255)
g: int # Green (0-255)
b: int # Blue (0-255)
a: int # Alpha (0-255)
# Color space properties
cmy: tuple[float, float, float]
hsva: tuple[float, float, float, float]
hsla: tuple[float, float, float, float]
# Methods
def normalize(self) -> tuple[float, float, float, float]: ...
def lerp(self, color: 'Color', t: float) -> 'Color': ...
def grayscale(self) -> 'Color': ...class Event:
def __init__(self, type: int, **attributes): ...
type: int # Event type constant
# Dynamic attributes based on event type# Common key constants
K_ESCAPE: int
K_SPACE: int
K_RETURN: int
K_UP: int
K_DOWN: int
K_LEFT: int
K_RIGHT: int
K_a: int # through K_z
K_0: int # through K_9
# Event type constants
QUIT: int
KEYDOWN: int
KEYUP: int
MOUSEBUTTONDOWN: int
MOUSEBUTTONUP: int
MOUSEMOTION: int
# Display flag constants
FULLSCREEN: int
DOUBLEBUF: int
HWSURFACE: int
OPENGL: int
RESIZABLE: int