CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygame-ce

Python Game Development library providing comprehensive multimedia functionality for creating games and interactive applications.

Pending
Overview
Eval results
Files

advanced-features.mddocs/

Advanced Features

Specialized functionality including FreeType font rendering, comprehensive NumPy integration, camera input, version information, power management, and modern SDL2 features through the _sdl2 subpackage.

Capabilities

FreeType Font Rendering

Advanced font rendering with TrueType/OpenType font support, providing superior text quality and control.

def init(cache_size: int = 64, resolution: int = 72) -> None:
    """
    Initialize FreeType module.
    
    Parameters:
        cache_size: Maximum number of glyphs to cache
        resolution: DPI resolution for font rendering
    """

def quit() -> None:
    """Quit FreeType module."""

def get_init() -> bool:
    """Check if FreeType is initialized."""

def was_init() -> bool:
    """Check if FreeType was ever initialized."""

def get_version() -> str:
    """Get FreeType version string."""

class Font:
    def __init__(self, fontpath: str | None = None, size: int = 0, font_index: int = 0, resolution: int = 0, ucs4: bool = False):
        """
        Create FreeType font object.
        
        Parameters:
            fontpath: Path to font file (None for default)
            size: Font size in points
            font_index: Font face index for collections
            resolution: DPI resolution (0 for default)
            ucs4: Enable UCS-4 Unicode support
        """
    
    # Font properties
    name: str           # Font family name
    path: str           # Font file path
    size: int           # Font size in points
    height: int         # Line height in pixels
    ascender: int       # Ascender height
    descender: int      # Descender depth
    
    # Style properties
    style: int          # Style flags
    underline: bool     # Underline enabled
    strong: bool        # Bold enabled
    oblique: bool       # Italic enabled
    wide: bool          # Wide character spacing
    
    # Rendering properties
    antialiased: bool   # Anti-aliasing enabled
    kerning: bool       # Kerning enabled
    vertical: bool      # Vertical text layout
    rotation: int       # Text rotation angle
    fgcolor: Color      # Foreground color
    bgcolor: Color      # Background color
    
    def render(self, text: str, fgcolor: Color | None = None, bgcolor: Color | None = None, style: int = 0, rotation: int = 0, size: int = 0) -> tuple[Surface, Rect]:
        """
        Render text to new surface.
        
        Parameters:
            text: Text to render
            fgcolor: Foreground color (None for font default)
            bgcolor: Background color (None for transparent)
            style: Style flags
            rotation: Rotation angle in degrees
            size: Font size override (0 for font default)
        
        Returns:
            tuple[Surface, Rect]: Rendered surface and bounding rectangle
        """
    
    def render_to(self, surf: Surface, dest: tuple[int, int], text: str, fgcolor: Color | None = None, bgcolor: Color | None = None, style: int = 0, rotation: int = 0, size: int = 0) -> Rect:
        """
        Render text directly to surface.
        
        Parameters:
            surf: Target surface
            dest: (x, y) destination position
            text: Text to render
            fgcolor: Foreground color
            bgcolor: Background color
            style: Style flags
            rotation: Rotation angle
            size: Font size override
        
        Returns:
            Rect: Bounding rectangle of rendered text
        """
    
    def get_rect(self, text: str, style: int = 0, rotation: int = 0, size: int = 0) -> Rect:
        """
        Get bounding rectangle for text without rendering.
        
        Parameters:
            text: Text to measure
            style: Style flags
            rotation: Rotation angle
            size: Font size override
        
        Returns:
            Rect: Bounding rectangle
        """
    
    def get_metrics(self, text: str, size: int = 0) -> list[tuple]:
        """
        Get detailed metrics for each character.
        
        Parameters:
            text: Text to analyze
            size: Font size override
        
        Returns:
            list[tuple]: List of (min_x, max_x, min_y, max_y, advance_x, advance_y) for each character
        """

def get_default_font() -> str:
    """Get path to default font."""

def SysFont(name: str, size: int, bold: bool = False, italic: bool = False) -> Font:
    """
    Create font from system fonts.
    
    Parameters:
        name: Font family name
        size: Font size in points
        bold: Enable bold style
        italic: Enable italic style
    
    Returns:
        Font: System font object
    """

NumPy Integration (surfarray)

High-performance array operations for surface manipulation using NumPy.

def array2d(surface: Surface) -> numpy.ndarray:
    """
    Copy surface pixels to 2D array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array of pixel values
    """

def pixels2d(surface: Surface) -> numpy.ndarray:
    """
    Get reference to surface pixels as 2D array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array referencing surface pixels
    """

def array3d(surface: Surface) -> numpy.ndarray:
    """
    Copy surface to 3D RGB array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 3D array with RGB channels
    """

def pixels3d(surface: Surface) -> numpy.ndarray:
    """
    Get reference to surface as 3D RGB array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 3D array referencing surface RGB
    """

def array_alpha(surface: Surface) -> numpy.ndarray:
    """
    Copy alpha channel to array.
    
    Parameters:
        surface: Source surface with alpha
    
    Returns:
        numpy.ndarray: 2D array of alpha values
    """

def pixels_alpha(surface: Surface) -> numpy.ndarray:
    """
    Get reference to alpha channel as array.
    
    Parameters:
        surface: Source surface with alpha
    
    Returns:
        numpy.ndarray: 2D array referencing alpha channel
    """

def array_red(surface: Surface) -> numpy.ndarray:
    """
    Copy red color channel to array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array of red channel values
    """

def array_green(surface: Surface) -> numpy.ndarray:
    """
    Copy green color channel to array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array of green channel values
    """

def array_blue(surface: Surface) -> numpy.ndarray:
    """
    Copy blue color channel to array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array of blue channel values
    """

def array_colorkey(surface: Surface) -> numpy.ndarray:
    """
    Copy colorkey mask to array.
    
    Parameters:
        surface: Source surface with colorkey
    
    Returns:
        numpy.ndarray: 2D array of colorkey mask
    """

def pixels_red(surface: Surface) -> numpy.ndarray:
    """
    Get reference to red channel as array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array referencing red channel
    """

def pixels_green(surface: Surface) -> numpy.ndarray:
    """
    Get reference to green channel as array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array referencing green channel
    """

def pixels_blue(surface: Surface) -> numpy.ndarray:
    """
    Get reference to blue channel as array.
    
    Parameters:
        surface: Source surface
    
    Returns:
        numpy.ndarray: 2D array referencing blue channel
    """

def make_surface(array: numpy.ndarray) -> Surface:
    """
    Create surface from array.
    
    Parameters:
        array: NumPy array of pixel data
    
    Returns:
        Surface: New surface from array data
    """

def blit_array(surface: Surface, array: numpy.ndarray) -> None:
    """
    Copy array values directly to surface.
    
    Parameters:
        surface: Target surface
        array: Source array data
    """

def map_array(surface: Surface, array3d: numpy.ndarray) -> numpy.ndarray:
    """
    Map 3D array to surface pixel format.
    
    Parameters:
        surface: Reference surface for pixel format
        array3d: 3D RGB array to map
    
    Returns:
        numpy.ndarray: Mapped pixel array
    """

NumPy Integration (sndarray)

Audio array manipulation for advanced sound processing.

def array(sound: Sound) -> numpy.ndarray:
    """
    Copy sound samples to array.
    
    Parameters:
        sound: Source sound object
    
    Returns:
        numpy.ndarray: Array of audio samples
    """

def samples(sound: Sound) -> numpy.ndarray:
    """
    Get reference to sound samples as array.
    
    Parameters:
        sound: Source sound object
    
    Returns:
        numpy.ndarray: Array referencing sound samples
    """

def make_sound(array: numpy.ndarray) -> Sound:
    """
    Create sound from array.
    
    Parameters:
        array: NumPy array of audio samples
    
    Returns:
        Sound: New sound object
    """

Camera Input

Real-time camera capture for computer vision and augmented reality applications.

def init(backend: str | None = None) -> None:
    """
    Initialize camera module.
    
    Parameters:
        backend: Camera backend to use (None for auto-detect)
    """

def quit() -> None:
    """Quit camera module."""

def get_backends() -> list[str]:
    """
    Get available camera backends.
    
    Returns:
        list[str]: List of available backends
    """

def list_cameras() -> list[str]:
    """
    Get list of available cameras.
    
    Returns:
        list[str]: Camera device names
    """

class Camera:
    def __init__(self, device: str | int, size: tuple[int, int] = (640, 480), mode: str = 'RGB'):
        """
        Initialize camera object.
        
        Parameters:
            device: Camera device name or index
            size: (width, height) capture resolution
            mode: Color mode ('RGB', 'YUV', 'HSV')
        """
    
    def start(self) -> None:
        """Start camera capture."""
    
    def stop(self) -> None:
        """Stop camera capture."""
    
    def get_image(self, surface: Surface | None = None) -> Surface:
        """
        Capture image from camera.
        
        Parameters:
            surface: Optional surface to capture into
        
        Returns:
            Surface: Captured image
        """
    
    def query_image(self) -> bool:
        """
        Check if new image is available.
        
        Returns:
            bool: True if new image ready
        """
    
    def get_raw(self) -> bytes:
        """
        Get raw image data.
        
        Returns:
            bytes: Raw image buffer
        """

Version Information

Runtime version checking and compatibility information for pygame-ce and underlying SDL.

# Version strings and tuples
ver: str                    # pygame-ce version string (e.g., "2.5.5")
vernum: PygameVersion      # pygame-ce version tuple with comparison support
rev: str                   # Revision/build information
SDL: SDLVersion           # SDL version information

class PygameVersion(tuple):
    """pygame-ce version tuple with comparison and property access."""
    
    @property
    def major(self) -> int:
        """Major version number."""
    
    @property  
    def minor(self) -> int:
        """Minor version number."""
    
    @property
    def patch(self) -> int:
        """Patch version number."""

class SDLVersion(tuple):
    """SDL version tuple with comparison and property access."""
    
    @property
    def major(self) -> int:
        """SDL major version number."""
    
    @property
    def minor(self) -> int:
        """SDL minor version number."""
    
    @property
    def patch(self) -> int:
        """SDL patch version number."""

Power Management

Battery and power state monitoring for mobile and laptop applications.

class PowerState:
    """
    Power and battery status information.
    Immutable dataclass containing current power state.
    """
    
    battery_percent: int | None     # Battery percentage (0-100) or None if unknown
    battery_seconds: int | None     # Estimated battery seconds remaining or None
    on_battery: bool               # True if running on battery power
    no_battery: bool               # True if no battery is present
    charging: bool                 # True if battery is charging
    charged: bool                  # True if battery is fully charged
    plugged_in: bool              # True if AC power is connected
    has_battery: bool             # True if device has a battery

def get_power_info() -> PowerState:
    """
    Get current power and battery status.
    
    Returns:
        PowerState: Current power state information
    """

Modern SDL2 Features

Advanced window management and modern SDL2 functionality.

class Window:
    def __init__(self, title: str = 'pygame window', size: tuple[int, int] = (640, 480), position: tuple[int, int] | None = None, fullscreen: bool = False, **kwargs):
        """
        Create modern SDL2 window.
        
        Parameters:
            title: Window title
            size: (width, height) window size
            position: (x, y) window position (None for centered)
            fullscreen: Create fullscreen window
            **kwargs: Additional window options
        """
    
    # Window properties
    id: int                    # Window ID
    size: tuple[int, int]      # Window size
    position: tuple[int, int]  # Window position
    title: str                 # Window title
    
    # Window state
    borderless: bool           # Borderless window
    resizable: bool            # Resizable window
    always_on_top: bool        # Always on top
    
    def close(self) -> None:
        """Close window."""
    
    def destroy(self) -> None:
        """Destroy window."""
    
    def hide(self) -> None:
        """Hide window."""
    
    def show(self) -> None:
        """Show window."""
    
    def maximize(self) -> None:
        """Maximize window."""
    
    def minimize(self) -> None:
        """Minimize window."""
    
    def restore(self) -> None:
        """Restore window."""
    
    def set_windowed(self) -> None:
        """Set windowed mode."""
    
    def set_fullscreen(self, desktop: bool = False) -> None:
        """
        Set fullscreen mode.
        
        Parameters:
            desktop: Use desktop fullscreen (borderless windowed)
        """
    
    def set_title(self, title: str) -> None:
        """Set window title."""
    
    def get_title(self) -> str:
        """Get window title."""
    
    def set_icon(self, surface: Surface) -> None:
        """Set window icon."""
    
    def set_size(self, size: tuple[int, int]) -> None:
        """Set window size."""
    
    def get_size(self) -> tuple[int, int]:
        """Get window size."""
    
    def set_position(self, position: tuple[int, int], centered: bool = False) -> None:
        """
        Set window position.
        
        Parameters:
            position: (x, y) position
            centered: Center on screen if True
        """
    
    def get_position(self) -> tuple[int, int]:
        """Get window position."""
    
    def set_opacity(self, opacity: float) -> None:
        """
        Set window opacity.
        
        Parameters:
            opacity: Opacity value (0.0 to 1.0)
        """
    
    def get_opacity(self) -> float:
        """Get window opacity."""

Mask-based Collision Detection

Pixel-perfect collision detection using bitmasks.

class Mask:
    def __init__(self, size: tuple[int, int], fill: bool = False):
        """
        Create collision mask.
        
        Parameters:
            size: (width, height) mask dimensions
            fill: Fill mask initially
        """
    
    def get_size(self) -> tuple[int, int]:
        """Get mask dimensions."""
    
    def get_at(self, pos: tuple[int, int]) -> int:
        """
        Get bit at position.
        
        Parameters:
            pos: (x, y) position
        
        Returns:
            int: Bit value (0 or 1)
        """
    
    def set_at(self, pos: tuple[int, int], value: int = 1) -> None:
        """
        Set bit at position.
        
        Parameters:
            pos: (x, y) position
            value: Bit value to set
        """
    
    def overlap(self, othermask: Mask, offset: tuple[int, int]) -> tuple[int, int] | None:
        """
        Find overlap with another mask.
        
        Parameters:
            othermask: Other mask to test
            offset: (x, y) offset of other mask
        
        Returns:
            tuple[int, int] | None: First overlap point or None
        """
    
    def overlap_area(self, othermask: Mask, offset: tuple[int, int]) -> int:
        """
        Get overlap area with another mask.
        
        Parameters:
            othermask: Other mask
            offset: Offset of other mask
        
        Returns:
            int: Number of overlapping pixels
        """
    
    def count(self) -> int:
        """Count set bits in mask."""
    
    def outline(self, every: int = 1) -> list[tuple[int, int]]:
        """
        Get outline points of mask.
        
        Parameters:
            every: Sample every N points
        
        Returns:
            list[tuple[int, int]]: Outline points
        """

def from_surface(surface: Surface, threshold: int = 127) -> Mask:
    """
    Create mask from surface alpha/colorkey.
    
    Parameters:
        surface: Source surface
        threshold: Alpha threshold for mask creation
    
    Returns:
        Mask: Generated collision mask
    """

Usage Examples

FreeType Font Rendering

import pygame
import pygame.freetype

pygame.init()
pygame.freetype.init()

screen = pygame.display.set_mode((800, 600))

# Load custom font
font = pygame.freetype.Font("arial.ttf", 24)

# Basic text rendering
text_surface, text_rect = font.render("Hello World!", (255, 255, 255))
screen.blit(text_surface, (100, 100))

# Render with styles
font.style = pygame.freetype.STYLE_BOLD | pygame.freetype.STYLE_UNDERLINE
bold_surface, bold_rect = font.render("Bold Underlined", (255, 0, 0))
screen.blit(bold_surface, (100, 150))

# Render directly to surface
font.render_to(screen, (100, 200), "Direct Render", (0, 255, 0))

# Get text metrics without rendering
rect = font.get_rect("Measured Text")
print(f"Text size: {rect.size}")

pygame.display.flip()
pygame.freetype.quit()
pygame.quit()

NumPy Surface Manipulation

import pygame
import numpy as np

pygame.init()
screen = pygame.display.set_mode((800, 600))

# Create test surface
surface = pygame.Surface((100, 100))
surface.fill((255, 0, 0))  # Red

# Get array reference to surface pixels
pixels = pygame.surfarray.pixels2d(surface)

# Modify pixels using NumPy
# Create gradient effect
for x in range(100):
    for y in range(100):
        pixels[x, y] = int(255 * (x + y) / 200)

# Changes are immediately visible on surface
del pixels  # Release array reference

# Create surface from NumPy array
array = np.random.randint(0, 255, (200, 200), dtype=np.uint8)
noise_surface = pygame.surfarray.make_surface(array)

# Blit to screen
screen.blit(surface, (100, 100))
screen.blit(noise_surface, (300, 100))

pygame.display.flip()
pygame.quit()

Camera Capture

import pygame
import pygame.camera

pygame.init()
pygame.camera.init()

# List available cameras
cameras = pygame.camera.list_cameras()
print(f"Available cameras: {cameras}")

if cameras:
    # Create camera object
    camera = pygame.camera.Camera(cameras[0], (640, 480))
    camera.start()
    
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        
        # Capture image if available
        if camera.query_image():
            image = camera.get_image()
            screen.blit(image, (0, 0))
        
        pygame.display.flip()
        clock.tick(30)  # 30 FPS for camera
    
    camera.stop()

pygame.camera.quit()
pygame.quit()

Advanced Window Management

import pygame
import pygame._sdl2.video as video

pygame.init()

# Create modern SDL2 window
window = video.Window("Advanced Window", size=(800, 600))

# Window manipulation
window.set_opacity(0.9)  # Semi-transparent
window.maximize()
window.set_always_on_top(True)

# Multiple windows
window2 = video.Window("Second Window", size=(400, 300), position=(900, 100))

# Get window properties
print(f"Window ID: {window.id}")
print(f"Window size: {window.size}")
print(f"Window position: {window.position}")

# Event handling for windows
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.WINDOWEVENT:
            if event.window == window.id:
                print(f"Window event: {event}")

window.destroy()
window2.destroy()
pygame.quit()

Pixel-Perfect Collision with Masks

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))

# Load images with transparency
sprite1_img = pygame.image.load("sprite1.png").convert_alpha()
sprite2_img = pygame.image.load("sprite2.png").convert_alpha()

# Create masks from images
mask1 = pygame.mask.from_surface(sprite1_img)
mask2 = pygame.mask.from_surface(sprite2_img)

# Position sprites
pos1 = (100, 100)
pos2 = (150, 120)

# Check for pixel-perfect collision
offset = (pos2[0] - pos1[0], pos2[1] - pos1[1])
collision_point = mask1.overlap(mask2, offset)

if collision_point:
    print(f"Collision at: {collision_point}")
    
    # Get overlap area
    overlap_area = mask1.overlap_area(mask2, offset)
    print(f"Overlap area: {overlap_area} pixels")

# Draw sprites and collision info
screen.fill((255, 255, 255))
screen.blit(sprite1_img, pos1)
screen.blit(sprite2_img, pos2)

if collision_point:
    # Draw collision point
    collision_world = (pos1[0] + collision_point[0], pos1[1] + collision_point[1])
    pygame.draw.circle(screen, (255, 0, 0), collision_world, 5)

pygame.display.flip()
pygame.quit()

Constants

FreeType style constants:

# FreeType style flags
STYLE_DEFAULT: int    # Default style
STYLE_NORMAL: int     # Normal style
STYLE_OBLIQUE: int    # Italic/oblique
STYLE_STRONG: int     # Bold
STYLE_UNDERLINE: int  # Underlined text
STYLE_WIDE: int       # Wide character spacing

Install with Tessl CLI

npx tessl i tessl/pypi-pygame-ce

docs

advanced-features.md

audio-system.md

core-system.md

cursor-management.md

display-graphics.md

event-handling.md

index.md

input-systems.md

math-operations.md

midi-support.md

sprites-game-objects.md

typing-support.md

tile.json