Python Game Development library providing comprehensive multimedia functionality for creating games and interactive applications.
npx @tessl/cli install tessl/pypi-pygame-ce@2.5.0pygame-ce (pygame Community Edition) is a free and open-source cross-platform multimedia library designed for developing video games and multimedia applications using Python. Built on top of the Simple DirectMedia Layer (SDL), it provides comprehensive functionality for graphics rendering, sound playback, input handling, and game development with high-level abstractions for common multimedia tasks.
pip install pygame-ceimport pygameCommon initialization pattern:
import pygame
import sys
# Initialize pygame
pygame.init()
# Your game loop here
# ...
# Quit pygame
pygame.quit()
sys.exit()Access to specific modules:
import pygame
from pygame import Surface, Rect, Color
from pygame.sprite import Sprite, Group
from pygame.cursors import Cursor
from pygame.midi import Input, Output
import pygame.typing # Type support
import pygame.freetype # Advanced fonts
import pygame.surfarray # NumPy integrationComplete minimal game example:
import pygame
import sys
# Initialize pygame
pygame.init()
# Set up the display
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My Game")
# Game objects
clock = pygame.time.Clock()
player_rect = pygame.Rect(375, 275, 50, 50)
player_color = pygame.Color('blue')
# Game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle input
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.x -= 5
if keys[pygame.K_RIGHT]:
player_rect.x += 5
if keys[pygame.K_UP]:
player_rect.y -= 5
if keys[pygame.K_DOWN]:
player_rect.y += 5
# Clear screen
screen.fill(pygame.Color('black'))
# Draw game objects
pygame.draw.rect(screen, player_color, player_rect)
# Update display
pygame.display.flip()
clock.tick(60) # 60 FPS
# Quit
pygame.quit()
sys.exit()pygame-ce follows a modular architecture with distinct subsystems:
Essential system functions for initializing pygame, managing modules, and handling errors. These functions form the foundation that must be called before using other pygame functionality.
def init() -> tuple[int, int]: ...
def quit() -> None: ...
def get_init() -> bool: ...
def get_error() -> str: ...
def set_error(msg: str) -> None: ...Comprehensive display management including window creation, surface operations, and drawing primitives. Handles everything from basic window setup to advanced graphics rendering and transformations.
def set_mode(size: tuple[int, int], flags: int = 0, depth: int = 0, display: int = 0, vsync: int = 0) -> Surface: ...
def flip() -> None: ...
def update(rectangle_list: list[Rect] | None = None) -> None: ...
class Surface:
def __init__(self, size: tuple[int, int], flags: int = 0, depth: int = 0, masks: tuple[int, int, int, int] | None = None): ...
def blit(self, source: Surface, dest: tuple[int, int] | Rect, area: Rect | None = None, special_flags: int = 0) -> Rect: ...Event system for processing user input and system events. Provides queued event handling with filtering capabilities and custom event creation for game logic.
class Event:
def __init__(self, type: int, dict: dict | None = None): ...
def get(eventtype: int | None = None, pump: bool = True) -> list[Event]: ...
def poll() -> Event: ...
def wait(timeout: int = 0) -> Event: ...
def post(event: Event) -> None: ...Comprehensive input handling for keyboard, mouse, and game controllers. Provides both real-time state checking and event-based input processing.
# Keyboard
def get_pressed() -> dict[int, bool]: ...
def get_focused() -> bool: ...
# Mouse
def get_pos() -> tuple[int, int]: ...
def get_pressed(num_buttons: int = 3) -> tuple[bool, ...]: ...
class Joystick:
def __init__(self, id: int): ...Complete audio subsystem supporting sound effects, music playback, and multi-channel mixing. Handles various audio formats with volume control and channel management.
class Sound:
def __init__(self, file: str | bytes): ...
def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> Channel: ...
def init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 512) -> None: ...
def load(filename: str) -> Sound: ...High-level game object management with sprite classes, collision detection, and group operations. Provides organized structure for managing game entities and their interactions.
class Sprite:
def __init__(self): ...
def update(self, *args, **kwargs) -> None: ...
def kill(self) -> None: ...
class Group:
def add(self, *sprites: Sprite) -> None: ...
def remove(self, *sprites: Sprite) -> None: ...
def update(self, *args, **kwargs) -> None: ...Vector mathematics and geometric utilities for game development. Provides 2D and 3D vector operations, rectangle manipulation, and collision detection.
class Vector2:
def __init__(self, x: float = 0, y: float = 0): ...
def normalize(self) -> Vector2: ...
def distance_to(self, other: Vector2) -> float: ...
class Rect:
def __init__(self, left: int, top: int, width: int, height: int): ...
def colliderect(self, rect: Rect) -> bool: ...Musical Instrument Digital Interface support for real-time musical input/output, device management, and musical utility functions for music applications.
class Input:
def __init__(self, device_id: int, buffer_size: int = 4096): ...
def read(self, num_events: int) -> list[list]: ...
def poll(self) -> bool: ...
class Output:
def __init__(self, device_id: int, latency: int = 0, buffer_size: int = 256): ...
def note_on(self, note: int, velocity: int = 127, channel: int = 0) -> None: ...
def note_off(self, note: int, velocity: int = 0, channel: int = 0) -> None: ...
def get_device_info(device_id: int) -> tuple[str, str, int, int, int] | None: ...
def frequency_to_midi(frequency: float) -> int: ...
def midi_to_frequency(midi_note: int) -> float: ...Type hints and protocols for enhanced development experience with pygame-ce, providing comprehensive type aliases and protocol classes for better IDE support.
# Type aliases
RectLike = Union[Rect, FRect, SequenceLike[float], SequenceLike[Point], _HasRectAttribute]
ColorLike = Union[Color, SequenceLike[int], str, int]
FileLike = Union[str, bytes, PathLike[str], PathLike[bytes], IO[bytes], IO[str]]
# Protocol classes
class SequenceLike(Protocol[T_co]):
def __getitem__(self, index: int) -> T_co: ...
def __len__(self) -> int: ...Comprehensive mouse cursor control including system cursors, custom bitmap cursors, and color cursors with compilation utilities.
class Cursor:
def __init__(self, *args): ...
type: str # "system", "bitmap", or "color"
data: tuple
def set_cursor(*args) -> None: ...
def get_cursor() -> Cursor: ...
def compile(strings: tuple[str, ...], black: str = "X", white: str = ".", xor: str = "o") -> tuple[tuple[int, ...], tuple[int, ...]]: ...
# Pre-defined cursors
arrow: Cursor
diamond: Cursor
ball: CursorSpecialized functionality including FreeType font rendering, comprehensive NumPy integration, camera input, version information, power management, and modern SDL2 features.
# FreeType fonts
class Font:
def render(self, text: str, fgcolor: Color, bgcolor: Color | None = None) -> tuple[Surface, Rect]: ...
# Complete NumPy integration
def array2d(surface: Surface) -> numpy.ndarray: ...
def pixels2d(surface: Surface) -> numpy.ndarray: ...
def array_red(surface: Surface) -> numpy.ndarray: ...
def make_surface(array: numpy.ndarray) -> Surface: ...
# Version information
ver: str
vernum: PygameVersion
SDL: SDLVersion
# Power management
class PowerState:
battery_percent: int | None
on_battery: bool
charging: bool
# SDL2 Window management
class Window:
def __init__(self, title: str = 'pygame window', size: tuple[int, int] = (640, 480)): ...Core types used throughout pygame-ce:
class Color:
def __init__(self, r: int, g: int = None, b: int = None, a: int = 255): ...
r: int
g: int
b: int
a: int
class Rect:
def __init__(self, left: int, top: int, width: int, height: int): ...
x: int
y: int
width: int
height: int
w: int # alias for width
h: int # alias for height
class Surface:
def get_size() -> tuple[int, int]: ...
def get_rect(**kwargs) -> Rect: ...
# Event types (constants)
QUIT: int
KEYDOWN: int
KEYUP: int
MOUSEBUTTONDOWN: int
MOUSEBUTTONUP: int
MOUSEMOTION: int