CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygame

Cross-platform library for developing multimedia applications and video games in Python built on top of SDL

Overview
Eval results
Files

event-input.mddocs/

Event Handling and Input

Event queue management and input handling system. Pygame's event system provides a unified way to handle all input from keyboard, mouse, joystick, and system events like window closing or resizing.

Capabilities

Event Queue Management

Control the event queue and retrieve events for processing.

def pump() -> None:
    """
    Process events internally without removing them from queue.
    Call this if not using other event functions to keep system responsive.
    """

def get(eventtype = None, pump: bool = True, exclude = None) -> list[pygame.event.Event]:
    """
    Get list of events from the queue.

    Args:
        eventtype: Event type(s) to get (None for all, int/list for specific)
        pump (bool): Whether to pump events first
        exclude: Event type(s) to exclude

    Returns:
        list[pygame.event.Event]: List of events
    """

def poll() -> pygame.event.Event:
    """
    Get single event from the queue.

    Returns:
        pygame.event.Event: Next event or event with type NOEVENT if queue empty
    """

def wait(timeout: int = 0) -> pygame.event.Event:
    """
    Wait for a single event.

    Args:
        timeout (int): Maximum time to wait in milliseconds (0 = wait forever)

    Returns:
        pygame.event.Event: Next event
    """

def peek(eventtype = None, pump: bool = True) -> bool:
    """
    Check if events are waiting in the queue.

    Args:
        eventtype: Event type(s) to check for
        pump (bool): Whether to pump events first

    Returns:
        bool: True if matching events are in queue
    """

def clear(eventtype = None, pump: bool = True) -> None:
    """
    Remove all events from the queue.

    Args:
        eventtype: Event type(s) to remove (None for all)
        pump (bool): Whether to pump events first
    """

Event Filtering

Control which events are allowed in or blocked from the queue.

def set_blocked(eventtype = None) -> None:
    """
    Block events from appearing in the queue.

    Args:
        eventtype: Event type(s) to block (None for all)
    """

def set_allowed(eventtype = None) -> None:
    """
    Allow events to appear in the queue.

    Args:
        eventtype: Event type(s) to allow (None for all)
    """

def get_blocked(eventtype: int) -> bool:
    """
    Check if an event type is blocked.

    Args:
        eventtype (int): Event type to check

    Returns:
        bool: True if event type is blocked
    """

Event Creation

Create and post custom events to the queue.

def post(event: pygame.event.Event) -> bool:
    """
    Post an event to the queue.

    Args:
        event (pygame.event.Event): Event to post

    Returns:
        bool: True if event was posted successfully
    """

def Event(type: int, **attributes) -> pygame.event.Event:
    """
    Create a new event object.

    Args:
        type (int): Event type constant
        **attributes: Event-specific attributes

    Returns:
        pygame.event.Event: New event object
    """

def custom_type() -> int:
    """
    Create a new custom event type.

    Returns:
        int: New event type constant for custom events
    """

def event_name(type: int) -> str:
    """
    Get name string for an event type.

    Args:
        type (int): Event type constant

    Returns:
        str: Event type name
    """

Input Control

Control input grabbing and keyboard behavior.

def set_grab(bool) -> None:
    """
    Control input event grabbing.

    Args:
        bool (bool): True to grab input, False to release
    """

def get_grab() -> bool:
    """
    Check if input is grabbed.

    Returns:
        bool: True if input is grabbed
    """

def set_keyboard_grab(bool) -> None:
    """
    Control keyboard grabbing.

    Args:
        bool (bool): True to grab keyboard, False to release
    """

def get_keyboard_grab() -> bool:
    """
    Check if keyboard is grabbed.

    Returns:
        bool: True if keyboard is grabbed
    """

Event Types and Objects

Event Class

class Event:
    def __init__(self, type: int, **attributes):
        """
        Event object representing an input or system event.

        Args:
            type (int): Event type constant
            **attributes: Event-specific data
        """

    type: int  # Event type constant

    # Common event attributes (vary by event type):
    # key: int - Key code for KEYDOWN/KEYUP
    # unicode: str - Unicode character for KEYDOWN
    # mod: int - Key modifier flags
    # pos: tuple[int, int] - Mouse position for mouse events
    # button: int - Mouse button number
    # rel: tuple[int, int] - Mouse relative movement
    # size: tuple[int, int] - New window size for VIDEORESIZE
    # joy: int - Joystick device index
    # axis: int - Joystick axis number
    # value: float - Joystick axis value

Event Type Constants

# System events
NOEVENT: int        # No event (returned by poll() when queue empty)
QUIT: int           # User clicked window close button

# Keyboard events
KEYDOWN: int        # Key was pressed
KEYUP: int          # Key was released
TEXTINPUT: int      # Text input (Unicode)
TEXTEDITING: int    # Text editing (IME)

# Mouse events
MOUSEBUTTONDOWN: int  # Mouse button pressed
MOUSEBUTTONUP: int    # Mouse button released
MOUSEMOTION: int      # Mouse moved
MOUSEWHEEL: int       # Mouse wheel scrolled

# Joystick events
JOYAXISMOTION: int     # Joystick axis moved
JOYBUTTONDOWN: int     # Joystick button pressed
JOYBUTTONUP: int       # Joystick button released
JOYHATMOTION: int      # Joystick hat moved
JOYDEVICEADDED: int    # Joystick connected
JOYDEVICEREMOVED: int  # Joystick disconnected

# Window events
VIDEORESIZE: int      # Window was resized
VIDEOEXPOSE: int      # Window was exposed and needs refresh
WINDOWSHOWN: int      # Window was shown
WINDOWHIDDEN: int     # Window was hidden
WINDOWMOVED: int      # Window was moved
WINDOWFOCUSGAINED: int # Window gained focus
WINDOWFOCUSLOST: int   # Window lost focus

# User events
USEREVENT: int        # First user event type (use for custom events)

Usage Examples

Basic Event Loop

import pygame
import sys

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

running = True
while running:
    # Process all events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            print(f"Key pressed: {pygame.key.name(event.key)}")
        elif event.type == pygame.MOUSEBUTTONDOWN:
            print(f"Mouse clicked at {event.pos}")

    # Game logic here...

    clock.tick(60)

pygame.quit()
sys.exit()

Advanced Event Handling

import pygame

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

# Only allow specific events to save processing
pygame.event.set_blocked(None)  # Block all events
pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN])

running = True
while running:
    # Check for events without removing them
    if pygame.event.peek(pygame.QUIT):
        running = False
        break

    # Get only keyboard events
    key_events = pygame.event.get(pygame.KEYDOWN)
    for event in key_events:
        if event.key == pygame.K_SPACE:
            print(f"Space pressed! Unicode: {event.unicode}")
            print(f"Modifiers: {event.mod}")

    # Poll for single event (non-blocking)
    event = pygame.event.poll()
    if event.type == pygame.MOUSEBUTTONDOWN:
        print(f"Mouse button {event.button} at {event.pos}")

    pygame.display.flip()

pygame.quit()

Custom Events

import pygame

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

# Create custom event types
PLAYER_HIT = pygame.event.custom_type()
POWER_UP = pygame.event.custom_type()

# Set timer to post events
pygame.time.set_timer(PLAYER_HIT, 2000)  # Every 2 seconds

running = True
score = 0

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == PLAYER_HIT:
            print("Player was hit!")
            score -= 10

            # Post another custom event
            power_event = pygame.event.Event(POWER_UP, {'type': 'health', 'value': 5})
            pygame.event.post(power_event)

        elif event.type == POWER_UP:
            print(f"Power up! Type: {event.type}, Value: {event.value}")
            score += event.value

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_p:
                # Manually post custom event
                hit_event = pygame.event.Event(PLAYER_HIT, {'damage': 25})
                pygame.event.post(hit_event)

    print(f"Score: {score}")
    pygame.display.flip()

pygame.quit()

Event Queue Management

import pygame

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

running = True
frame_count = 0

while running:
    frame_count += 1

    # Every 60 frames, clear all events except QUIT
    if frame_count % 60 == 0:
        quit_events = pygame.event.get(pygame.QUIT)
        pygame.event.clear()  # Clear all other events
        for event in quit_events:
            pygame.event.post(event)  # Put QUIT events back

    # Process events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # Check event name for debugging
        event_name = pygame.event.event_name(event.type)
        print(f"Event: {event_name}")

    # Pump events if not using get/poll/wait
    # pygame.event.pump()

    pygame.display.flip()

pygame.quit()

Input Grabbing

import pygame

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

# Grab input to keep it within window
grab_input = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_g:
                # Toggle input grabbing
                grab_input = not grab_input
                pygame.event.set_grab(grab_input)
                print(f"Input grab: {'ON' if grab_input else 'OFF'}")

            elif event.key == pygame.K_k:
                # Toggle keyboard grabbing
                kb_grab = not pygame.event.get_keyboard_grab()
                pygame.event.set_keyboard_grab(kb_grab)
                print(f"Keyboard grab: {'ON' if kb_grab else 'OFF'}")

        elif event.type == pygame.MOUSEMOTION:
            print(f"Mouse at: {event.pos}, Movement: {event.rel}")

    pygame.display.flip()

pygame.quit()

Install with Tessl CLI

npx tessl i tessl/pypi-pygame

docs

advanced-drawing.md

audio-sound.md

core-system.md

drawing-shapes.md

event-input.md

game-objects.md

graphics-display.md

index.md

input-devices.md

joystick-gamepad.md

math-utils.md

surface-image.md

text-font.md

time-animation.md

transform-image.md

tile.json