SDL Event Handling tcod.event

A light-weight implementation of event handling built on calls to SDL.

Many event constants are derived directly from SDL. For example: tcod.event.KeySym.UP and tcod.event.Scancode.A refer to SDL’s SDLK_UP and SDL_SCANCODE_A respectfully. See this table for all of SDL’s keyboard constants.

Printing any event will tell you its attributes in a human readable format. An events type attribute if omitted is just the classes name with all letters upper-case.

As a general guideline, you should use KeyboardEvent.sym for command inputs, and TextInput.text for name entry fields.

Example:

import tcod

KEY_COMMANDS = {
    tcod.event.KeySym.UP: "move N",
    tcod.event.KeySym.DOWN: "move S",
    tcod.event.KeySym.LEFT: "move W",
    tcod.event.KeySym.RIGHT: "move E",
}

context = tcod.context.new()
while True:
    console = context.new_console()
    context.present(console, integer_scaling=True)
    for pixel_event in tcod.event.wait():
        event = context.convert_event(pixel_event)  # Convert mouse pixel coordinates to tile coordinates
        print(event)  # Print all events, for learning and debugging
        if isinstance(event, tcod.event.Quit):
            raise SystemExit()
        elif isinstance(event, tcod.event.KeyDown):
            print(f"{event.sym=}, {event.scancode=}")  # Show Scancode and KeySym enum names
            if event.sym in KEY_COMMANDS:
                print(f"Command: {KEY_COMMANDS[event.sym]}")
        elif isinstance(event, tcod.event.MouseButtonDown):
            print(f"{event.button=}, {event.integer_position=}")  # Show mouse button and tile
        elif isinstance(event, tcod.event.MouseMotion):
            print(f"{event.integer_position=}, {event.integer_motion=}")  # Current mouse tile and tile motion

Python 3.10 introduced match statements which can be used to dispatch events more gracefully:

Example:

import tcod

KEY_COMMANDS = {
    tcod.event.KeySym.UP: "move N",
    tcod.event.KeySym.DOWN: "move S",
    tcod.event.KeySym.LEFT: "move W",
    tcod.event.KeySym.RIGHT: "move E",
}

context = tcod.context.new()
while True:
    console = context.new_console()
    context.present(console, integer_scaling=True)
    for pixel_event in tcod.event.wait():
        event = context.convert_event(pixel_event)  # Converts mouse pixel coordinates to tile coordinates.
        match event:
            case tcod.event.Quit():
                raise SystemExit()
            case tcod.event.KeyDown(sym=sym) if sym in KEY_COMMANDS:
                print(f"Command: {KEY_COMMANDS[sym]}")
            case tcod.event.KeyDown(sym=sym, scancode=scancode, mod=mod, repeat=repeat):
                print(f"KeyDown: {sym=}, {scancode=}, {mod=}, {repeat=}")
            case tcod.event.MouseButtonDown(button=button, integer_position=tile):
                print(f"MouseButtonDown: {button=}, {tile=}")
            case tcod.event.MouseMotion(integer_position=tile, integer_motion=tile_motion):
                assert isinstance(pixel_event, tcod.event.MouseMotion)
                pixel_motion = pixel_event.motion
                print(f"MouseMotion: {pixel_motion=}, {tile=}, {tile_motion=}")
            case tcod.event.Event() as event:
                print(event)  # Print unhandled events

Added in version 8.4.

class tcod.event.Point(x: T, y: T)[source]

A 2D position used for events with mouse coordinates.

Changed in version 19.0: Now uses floating point coordinates due to the port to SDL3.

x: T

A pixel or tile coordinate starting with zero as the left-most position.

y: T

A pixel or tile coordinate starting with zero as the top-most position.

classmethod __class_getitem__(params)

Parameterizes a generic class.

At least, parameterizing a generic class is the main thing this method does. For example, for some generic class Foo, this is called when we do Foo[int] - there, with cls=Foo and params=int.

However, note that this method is also called when defining generic classes in the first place with class Foo(Generic[T]): ….

class tcod.event.MouseButton(value)[source]

An enum for mouse buttons.

Added in version 16.1.

LEFT = 1

Left mouse button.

MIDDLE = 2

Middle mouse button.

RIGHT = 3

Right mouse button.

X1 = 4

Back mouse button.

X2 = 5

Forward mouse button.

__repr__() str[source]

Return the enum name, excluding the value.

classmethod __contains__(member)

Return True if member is a member of this enum raises TypeError if member is not an enum member

note: in 3.12 TypeError will no longer be raised, and True will also be returned if member is the value of a member in this enum

__dir__()

Returns public methods and other interesting attributes.

classmethod __getitem__(name)

Return the member matching name.

classmethod __iter__()

Return members in definition order.

classmethod __len__()

Return the number of members (no aliases)

class tcod.event.MouseButtonMask(value)[source]

A mask enum for held mouse buttons.

Added in version 16.1.

LEFT = 1

Left mouse button is held.

MIDDLE = 2

Middle mouse button is held.

RIGHT = 4

Right mouse button is held.

X1 = 8

Back mouse button is held.

X2 = 16

Forward mouse button is held.

__repr__() str[source]

Return the bitwise OR flag combination of this value.

__contains__(other)

Returns True if self has at least the same flags set as other.

__iter__()

Returns flags in definition order.

__dir__()

Returns public methods and other interesting attributes.

classmethod __getitem__(name)

Return the member matching name.

class tcod.event.Event(*, sdl_event: Any = None, timestamp_ns: int = 0)[source]

The base event class.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

class tcod.event.Quit(*, sdl_event: Any = None, timestamp_ns: int = 0)[source]

An application quit request event.

For more info on when this event is triggered see: https://wiki.libsdl.org/SDL_EventType#SDL_QUIT

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.KeyboardEvent(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, scancode: Scancode, sym: KeySym, mod: Modifier, repeat: bool = False, which: int = 0, window_id: int = 0, pressed: bool = False)[source]

Base keyboard event.

Changed in version 12.5: scancode, sym, and mod now use their respective enums.

scancode: Scancode

The keyboard scan-code, this is the physical location of the key on the keyboard rather than the keys symbol.

sym: KeySym

The keyboard symbol.

mod: Modifier

A bitmask of the currently held modifier keys.

For example, if shift is held then event.mod & tcod.event.Modifier.SHIFT will evaluate to a true value.

repeat: bool

True if this event exists because of key repeat.

which: int

The SDL keyboard instance ID. Zero if unknown or virtual.

Added in version 21.0.

window_id: int

The SDL window ID with keyboard focus.

Added in version 21.0.

pressed: bool

True if the key was pressed, False if the key was released.

Added in version 21.0.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.KeyDown(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, scancode: Scancode, sym: KeySym, mod: Modifier, repeat: bool = False, which: int = 0, window_id: int = 0, pressed: bool = False)[source]

A KeyboardEvent where the key was pressed.

mod: Modifier

A bitmask of the currently held modifier keys.

For example, if shift is held then event.mod & tcod.event.Modifier.SHIFT will evaluate to a true value.

pressed: bool

True if the key was pressed, False if the key was released.

Added in version 21.0.

repeat: bool

True if this event exists because of key repeat.

scancode: Scancode

The keyboard scan-code, this is the physical location of the key on the keyboard rather than the keys symbol.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

sym: KeySym

The keyboard symbol.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The SDL keyboard instance ID. Zero if unknown or virtual.

Added in version 21.0.

window_id: int

The SDL window ID with keyboard focus.

Added in version 21.0.

class tcod.event.KeyUp(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, scancode: Scancode, sym: KeySym, mod: Modifier, repeat: bool = False, which: int = 0, window_id: int = 0, pressed: bool = False)[source]

A KeyboardEvent where the key was released.

mod: Modifier

A bitmask of the currently held modifier keys.

For example, if shift is held then event.mod & tcod.event.Modifier.SHIFT will evaluate to a true value.

pressed: bool

True if the key was pressed, False if the key was released.

Added in version 21.0.

repeat: bool

True if this event exists because of key repeat.

scancode: Scancode

The keyboard scan-code, this is the physical location of the key on the keyboard rather than the keys symbol.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

sym: KeySym

The keyboard symbol.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The SDL keyboard instance ID. Zero if unknown or virtual.

Added in version 21.0.

window_id: int

The SDL window ID with keyboard focus.

Added in version 21.0.

class tcod.event.MouseState(*, sdl_event: Any = None, timestamp_ns: int = 0, position: Point[float] = (0.0, 0.0), tile: Point[int] | None = (0, 0), state: MouseButtonMask = MouseButtonMask(0), which: int = 0, window_id: int = 0)[source]

Mouse state.

Added in version 9.3.

Changed in version 15.0: Renamed pixel attribute to position.

position: Point[float]

The position coordinates of the mouse.

state: MouseButtonMask

A bitmask of which mouse buttons are currently held.

which: int

The mouse device ID for this event.

Added in version 21.0.

window_id: int

The window ID with mouse focus.

Added in version 21.0.

property integer_position: Point[int]

Integer coordinates of this event.

Added in version 21.0.

property tile: Point[int]

The integer tile coordinates of the mouse on the screen.

Deprecated since version 21.0: Use integer_position of the event returned by Context.convert_event instead.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.MouseMotion(*, sdl_event: Any = None, timestamp_ns: int = 0, position: Point[float] = (0.0, 0.0), tile: Point[int] | None = (0, 0), state: MouseButtonMask = MouseButtonMask(0), which: int = 0, window_id: int = 0, motion: Point[float] = (0.0, 0.0), tile_motion: Point[int] | None = (0, 0))[source]

Mouse motion event.

Changed in version 15.0: Renamed pixel attribute to position. Renamed pixel_motion attribute to motion.

Changed in version 19.0: position and motion now use floating point coordinates.

motion: Point[float]

The pixel delta.

property integer_motion: Point[int]

Integer motion of this event.

Added in version 21.0.

property tile_motion: Point[int]

The tile delta.

Deprecated since version 21.0: Use integer_motion of the event returned by Context.convert_event instead.

property integer_position: Point[int]

Integer coordinates of this event.

Added in version 21.0.

position: Point[float]

The position coordinates of the mouse.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

state: MouseButtonMask

A bitmask of which mouse buttons are currently held.

property tile: Point[int]

The integer tile coordinates of the mouse on the screen.

Deprecated since version 21.0: Use integer_position of the event returned by Context.convert_event instead.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The mouse device ID for this event.

Added in version 21.0.

window_id: int

The window ID with mouse focus.

Added in version 21.0.

class tcod.event.MouseButtonEvent(*, sdl_event: Any = None, timestamp_ns: int = 0, position: Point[float] = (0.0, 0.0), tile: Point[int] | None = (0, 0), button: MouseButton, which: int = 0, window_id: int = 0)[source]

Mouse button event.

Changed in version 19.0: position and tile now use floating point coordinates.

Changed in version 21.0: No longer a subclass of MouseState.

position: Point[float]

The coordinates of the mouse.

button: MouseButton

Which mouse button index was pressed or released in this event.

Changed in version 21.0: Is now strictly a MouseButton type.

which: int

The mouse device ID for this event.

Added in version 21.0.

window_id: int

The window ID with mouse focus.

Added in version 21.0.

property integer_position: Point[int]

Integer coordinates of this event.

Added in version 21.1.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.MouseButtonDown(*, sdl_event: Any = None, timestamp_ns: int = 0, position: Point[float] = (0.0, 0.0), tile: Point[int] | None = (0, 0), button: MouseButton, which: int = 0, window_id: int = 0)[source]

Mouse button has been pressed.

button: MouseButton

Which mouse button index was pressed or released in this event.

Changed in version 21.0: Is now strictly a MouseButton type.

property integer_position: Point[int]

Integer coordinates of this event.

Added in version 21.1.

position: Point[float]

The coordinates of the mouse.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The mouse device ID for this event.

Added in version 21.0.

window_id: int

The window ID with mouse focus.

Added in version 21.0.

class tcod.event.MouseButtonUp(*, sdl_event: Any = None, timestamp_ns: int = 0, position: Point[float] = (0.0, 0.0), tile: Point[int] | None = (0, 0), button: MouseButton, which: int = 0, window_id: int = 0)[source]

Mouse button has been released.

button: MouseButton

Which mouse button index was pressed or released in this event.

Changed in version 21.0: Is now strictly a MouseButton type.

property integer_position: Point[int]

Integer coordinates of this event.

Added in version 21.1.

position: Point[float]

The coordinates of the mouse.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The mouse device ID for this event.

Added in version 21.0.

window_id: int

The window ID with mouse focus.

Added in version 21.0.

class tcod.event.MouseWheel(*, sdl_event: Any = None, timestamp_ns: int = 0, x: int, y: int, flipped: bool, position: Point[float] = (0.0, 0.0), which: int = 0, window_id: int = 0)[source]

Mouse wheel event.

x: int

Horizontal scrolling. A positive value means scrolling right.

y: int

Vertical scrolling. A positive value means scrolling away from the user.

flipped: bool

If True then the values of x and y are the opposite of their usual values. This depends on the operating system settings.

position: Point[float]

Coordinates of the mouse for this event.

Added in version 21.2.

which: int

Mouse device ID for this event.

Added in version 21.2.

window_id: int

Window ID with mouse focus.

Added in version 21.2.

property integer_position: Point[int]

Integer coordinates of this event.

Added in version 21.2.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.TextInput(*, sdl_event: Any = None, timestamp_ns: int = 0, text: str)[source]

SDL text input event.

Warning

These events are not enabled by default since 19.0.

Use Window.start_text_input to enable this event.

text: str

A Unicode string with the input.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.WindowEvent(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, type: Final[_WindowTypes], window_id: int, data: tuple[int, int])[source]

A window event.

Example:

match event:
    case tcod.event.WindowEvent(type="WindowShown", window_id=window_id):
        print(f"Window {window_id} was shown")
    case tcod.event.WindowEvent(type="WindowHidden", window_id=window_id):
        print(f"Window {window_id} was hidden")
    case tcod.event.WindowEvent(type="WindowExposed", window_id=window_id):
        print(f"Window {window_id} was exposed and needs to be redrawn")
    case tcod.event.WindowEvent(type="WindowMoved", data=(x, y), window_id=window_id):
        print(f"Window {window_id} was moved to {x=},{y=}")
    case tcod.event.WindowEvent(type="WindowResized", data=(width, height), window_id=window_id):
        print(f"Window {window_id} was resized to {width=},{height=}")
    case tcod.event.WindowEvent(type="WindowMinimized", window_id=window_id):
        print(f"Window {window_id} was minimized")
    case tcod.event.WindowEvent(type="WindowMaximized", window_id=window_id):
        print(f"Window {window_id} was maximized")
    case tcod.event.WindowEvent(type="WindowRestored", window_id=window_id):
        print(f"Window {window_id} was restored")
    case tcod.event.WindowEvent(type="WindowEnter", window_id=window_id):
        print(f"Mouse cursor has entered window {window_id}")
    case tcod.event.WindowEvent(type="WindowLeave", window_id=window_id):
        print(f"Mouse cursor has left window {window_id}")
    case tcod.event.WindowEvent(type="WindowFocusGained", window_id=window_id):
        print(f"Window {window_id} has gained keyboard focus")
    case tcod.event.WindowEvent(type="WindowFocusLost", window_id=window_id):
        print(f"Window {window_id} has lost keyboard focus")
    case tcod.event.WindowEvent(type="WindowClose", window_id=window_id):
        print(f"Window {window_id} has been closed")
    case tcod.event.WindowEvent(type="DisplayChanged", data=(display_id, _), window_id=window_id):
        print(f"Window {window_id} has been moved to display {display_id}")
    case tcod.event.WindowEvent(type=subtype, data=data, window_id=window_id):
        print(f"Other window event {subtype} on window {window_id} with {data=}")

Changed in version 21.0: Added data and window_id attributes and added missing SDL3 window events.

type: Final[Literal['WindowShown', 'WindowHidden', 'WindowExposed', 'WindowMoved', 'WindowResized', 'PixelSizeChanged', 'MetalViewResized', 'WindowMinimized', 'WindowMaximized', 'WindowRestored', 'WindowEnter', 'WindowLeave', 'WindowFocusGained', 'WindowFocusLost', 'WindowClose', 'WindowTakeFocus', 'WindowHitTest', 'ICCProfileChanged', 'DisplayChanged', 'DisplayScaleChanged', 'SafeAreaChanged', 'Occluded', 'EnterFullscreen', 'LeaveFullscreen', 'Destroyed', 'HDRStateChanged']]

The current window event. This can be one of various options.

window_id: int

The SDL window ID associated with this event.

data: tuple[int, int]

The SDL data associated with this event. What these values are for depends on the event sub-type.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.WindowMoved(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, type: Final[_WindowTypes], window_id: int, data: tuple[int, int])[source]

Window moved event.

property x: int

Movement on the x-axis.

property y: int

Movement on the y-axis.

data: tuple[int, int]

The SDL data associated with this event. What these values are for depends on the event sub-type.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

type: Final[Literal['WindowShown', 'WindowHidden', 'WindowExposed', 'WindowMoved', 'WindowResized', 'PixelSizeChanged', 'MetalViewResized', 'WindowMinimized', 'WindowMaximized', 'WindowRestored', 'WindowEnter', 'WindowLeave', 'WindowFocusGained', 'WindowFocusLost', 'WindowClose', 'WindowTakeFocus', 'WindowHitTest', 'ICCProfileChanged', 'DisplayChanged', 'DisplayScaleChanged', 'SafeAreaChanged', 'Occluded', 'EnterFullscreen', 'LeaveFullscreen', 'Destroyed', 'HDRStateChanged']]

The current window event. This can be one of various options.

window_id: int

The SDL window ID associated with this event.

class tcod.event.WindowResized(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, type: Final[_WindowTypes], window_id: int, data: tuple[int, int])[source]

Window resized event.

Changed in version 19.4: Removed “WindowSizeChanged” type.

property width: int

The current width of the window.

property height: int

The current height of the window.

data: tuple[int, int]

The SDL data associated with this event. What these values are for depends on the event sub-type.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

type: Final[Literal['WindowShown', 'WindowHidden', 'WindowExposed', 'WindowMoved', 'WindowResized', 'PixelSizeChanged', 'MetalViewResized', 'WindowMinimized', 'WindowMaximized', 'WindowRestored', 'WindowEnter', 'WindowLeave', 'WindowFocusGained', 'WindowFocusLost', 'WindowClose', 'WindowTakeFocus', 'WindowHitTest', 'ICCProfileChanged', 'DisplayChanged', 'DisplayScaleChanged', 'SafeAreaChanged', 'Occluded', 'EnterFullscreen', 'LeaveFullscreen', 'Destroyed', 'HDRStateChanged']]

The current window event. This can be one of various options.

window_id: int

The SDL window ID associated with this event.

class tcod.event.JoystickEvent(*, sdl_event: Any = None, timestamp_ns: int = 0, which: int)[source]

A base class for joystick events.

Added in version 13.8.

which: int

The ID of the joystick this event is for.

property joystick: Joystick

The Joystick for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.JoystickAxis(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, which: int, type: Final[Literal['JOYAXISMOTION']] = 'JOYAXISMOTION', axis: int, value: int)[source]

When a joystick axis changes in value.

Added in version 13.8.

axis: int

The index of the changed axis.

value: int

The raw value of the axis in the range -32768 to 32767.

property joystick: Joystick

The Joystick for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The ID of the joystick this event is for.

class tcod.event.JoystickBall(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, which: int, type: Final[Literal['JOYBALLMOTION']] = 'JOYBALLMOTION', ball: int, dx: int, dy: int)[source]

When a joystick ball is moved.

Added in version 13.8.

ball: int

The index of the moved ball.

dx: int

The X motion of the ball.

dy: int

The Y motion of the ball.

property joystick: Joystick

The Joystick for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The ID of the joystick this event is for.

class tcod.event.JoystickHat(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, which: int, type: Final[Literal['JOYHATMOTION']] = 'JOYHATMOTION', x: Literal[-1, 0, 1], y: Literal[-1, 0, 1])[source]

When a joystick hat changes direction.

Added in version 13.8.

x: Literal[-1, 0, 1]

The new X direction of the hat.

y: Literal[-1, 0, 1]

The new Y direction of the hat.

property joystick: Joystick

The Joystick for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The ID of the joystick this event is for.

class tcod.event.JoystickButton(*, sdl_event: Any = None, timestamp_ns: int = 0, which: int, button: int, pressed: bool)[source]

When a joystick button is pressed or released.

Added in version 13.8.

Example:

for event in tcod.event.get():
    match event:
        case JoystickButton(which=which, button=button, pressed=True):
            print(f"Pressed {button=} on controller {which}.")
        case JoystickButton(which=which, button=button, pressed=False):
            print(f"Released {button=} on controller {which}.")
button: int

The index of the button this event is for.

pressed: bool

True if the button was pressed, False if the button was released.

property type: Literal['JOYBUTTONUP', 'JOYBUTTONDOWN']

Button state as a string.

Deprecated since version 21.0: Use pressed instead.

property joystick: Joystick

The Joystick for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The ID of the joystick this event is for.

class tcod.event.JoystickDevice(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, type: Final[Literal['JOYDEVICEADDED', 'JOYDEVICEREMOVED']], which: int)[source]

An event for when a joystick is added or removed.

Added in version 13.8.

Example:

joysticks: set[tcod.sdl.joystick.Joystick] = {}
for event in tcod.event.get():
    match event:
        case tcod.event.JoystickDevice(type="JOYDEVICEADDED", joystick=new_joystick):
            joysticks.add(new_joystick)
        case tcod.event.JoystickDevice(type="JOYDEVICEREMOVED", joystick=joystick):
            joysticks.remove(joystick)
which: int

When type=”JOYDEVICEADDED” this is the device ID. When type=”JOYDEVICEREMOVED” this is the instance ID.

property joystick: Joystick

The Joystick for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.ControllerEvent(*, sdl_event: Any = None, timestamp_ns: int = 0, which: int)[source]

Base class for controller events.

Added in version 13.8.

which: int

The ID of the controller this event is for.

property controller: GameController

The GameController for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

class tcod.event.ControllerAxis(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, which: int, type: Final[Literal['CONTROLLERAXISMOTION']] = 'CONTROLLERAXISMOTION', axis: int, value: int)[source]

When a controller axis is moved.

Added in version 13.8.

axis: int

Which axis is being moved. One of ControllerAxis.

value: int

The new value of this events axis.

This will be -32768 to 32767 for all axes except for triggers which are 0 to 32767 instead.

property controller: GameController

The GameController for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The ID of the controller this event is for.

class tcod.event.ControllerButton(*, sdl_event: Any = None, timestamp_ns: int = 0, which: int, button: ControllerButton, pressed: bool)[source]

When a controller button is pressed or released.

Added in version 13.8.

button: ControllerButton

The button for this event. One of ControllerButton.

pressed: bool

True if the button was pressed, False if it was released.

property type: Literal['CONTROLLERBUTTONUP', 'CONTROLLERBUTTONDOWN']

Button state as a string.

Deprecated since version 21.0: Use pressed instead.

property controller: GameController

The GameController for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The ID of the controller this event is for.

class tcod.event.ControllerDevice(*, sdl_event: _C_SDL_Event = None, timestamp_ns: int = 0, which: int, type: Final[Literal['CONTROLLERDEVICEADDED', 'CONTROLLERDEVICEREMOVED', 'CONTROLLERDEVICEREMAPPED']])[source]

When a controller is added, removed, or remapped.

Added in version 13.8.

property controller: GameController

The GameController for this event.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

which: int

The ID of the controller this event is for.

class tcod.event.Undefined(*, sdl_event: Any = None, timestamp_ns: int = 0)[source]

This class is a place holder for SDL events without their own tcod.event class.

__repr__() str[source]

Return debug info for this undefined event, including the SDL event name.

sdl_event: Any

Holds a python-cffi SDL_Event* pointer for this event when available.

property timestamp: float

The time of this event in seconds since SDL has been initialized.

See also

tcod.event.time

Added in version 21.0.

timestamp_ns: int

The time of this event in nanoseconds since SDL has been initialized.

Added in version 21.0.

tcod.event.get_mouse_state() MouseState[source]

Return the current state of the mouse.

Added in version 9.3.

tcod.event.add_watch(callback: _EventCallback) _EventCallback[source]

Add a callback for watching events.

This function can be called with the callback to register, or be used as a decorator.

Callbacks added as event watchers can later be removed with tcod.event.remove_watch.

Warning

How uncaught exceptions in a callback are handled is not currently defined by tcod. They will likely be handled by sys.unraisablehook. This may be later changed to pass the exception to a tcod.event.get or tcod.event.wait call.

Parameters:

callback (Callable[[Event], None]) – A function which accepts Event parameters.

Example:

import tcod.event

@tcod.event.add_watch
def handle_events(event: tcod.event.Event) -> None:
    if isinstance(event, tcod.event.KeyDown):
        print(event)

Added in version 13.4.

tcod.event.remove_watch(callback: Callable[[Event], None]) None[source]

Remove a callback as an event watcher.

Parameters:

callback (Callable[[Event], None]) – A function which has been previously registered with tcod.event.add_watch.

Added in version 13.4.

class tcod.event.EventDispatch(**kwargs)[source]

Dispatches events to methods depending on the events type attribute.

To use this class, make a sub-class and override the relevant ev_* methods. Then send events to the dispatch method.

Changed in version 11.12: This is now a generic class. The type hints at the return value of dispatch and the ev_* methods.

Deprecated since version 18.0: Event dispatch should be handled via a single custom method in a Protocol instead of this class. Note that events can and should be handled using The match statement.

Example:

import tcod

MOVE_KEYS = {  # key_symbol: (x, y)
    # Arrow keys.
    tcod.event.KeySym.LEFT: (-1, 0),
    tcod.event.KeySym.RIGHT: (1, 0),
    tcod.event.KeySym.UP: (0, -1),
    tcod.event.KeySym.DOWN: (0, 1),
    tcod.event.KeySym.HOME: (-1, -1),
    tcod.event.KeySym.END: (-1, 1),
    tcod.event.KeySym.PAGEUP: (1, -1),
    tcod.event.KeySym.PAGEDOWN: (1, 1),
    tcod.event.KeySym.PERIOD: (0, 0),
    # Numpad keys.
    tcod.event.KeySym.KP_1: (-1, 1),
    tcod.event.KeySym.KP_2: (0, 1),
    tcod.event.KeySym.KP_3: (1, 1),
    tcod.event.KeySym.KP_4: (-1, 0),
    tcod.event.KeySym.KP_5: (0, 0),
    tcod.event.KeySym.KP_6: (1, 0),
    tcod.event.KeySym.KP_7: (-1, -1),
    tcod.event.KeySym.KP_8: (0, -1),
    tcod.event.KeySym.KP_9: (1, -1),
    tcod.event.KeySym.CLEAR: (0, 0),  # Numpad `clear` key.
    # Vi Keys.
    tcod.event.KeySym.h: (-1, 0),
    tcod.event.KeySym.j: (0, 1),
    tcod.event.KeySym.k: (0, -1),
    tcod.event.KeySym.l: (1, 0),
    tcod.event.KeySym.y: (-1, -1),
    tcod.event.KeySym.u: (1, -1),
    tcod.event.KeySym.b: (-1, 1),
    tcod.event.KeySym.n: (1, 1),
}


class State(tcod.event.EventDispatch[None]):
    """A state-based superclass that converts `events` into `commands`.

    The configuration used to convert events to commands are hard-coded
    in this example, but could be modified to be user controlled.

    Subclasses will override the `cmd_*` methods with their own
    functionality.  There could be a subclass for every individual state
    of your game.
    """

    def ev_quit(self, event: tcod.event.Quit) -> None:
        """The window close button was clicked or Alt+F$ was pressed."""
        print(event)
        self.cmd_quit()

    def ev_keydown(self, event: tcod.event.KeyDown) -> None:
        """A key was pressed."""
        print(event)
        if event.sym in MOVE_KEYS:
            # Send movement keys to the cmd_move method with parameters.
            self.cmd_move(*MOVE_KEYS[event.sym])
        elif event.sym == tcod.event.KeySym.ESCAPE:
            self.cmd_escape()

    def ev_mousebuttondown(self, event: tcod.event.MouseButtonDown) -> None:
        """The window was clicked."""
        print(event)

    def ev_mousemotion(self, event: tcod.event.MouseMotion) -> None:
        """The mouse has moved within the window."""
        print(event)

    def cmd_move(self, x: int, y: int) -> None:
        """Intent to move: `x` and `y` is the direction, both may be 0."""
        print("Command move: " + str((x, y)))

    def cmd_escape(self) -> None:
        """Intent to exit this state."""
        print("Command escape.")
        self.cmd_quit()

    def cmd_quit(self) -> None:
        """Intent to exit the game."""
        print("Command quit.")
        raise SystemExit()


root_console = libtcodpy.console_init_root(80, 60)
state = State()
while True:
    libtcodpy.console_flush()
    for event in tcod.event.wait():
        state.dispatch(event)
dispatch(event: Any) T | None[source]

Send an event to an ev_* method.

* will be the event.type attribute converted to lower-case.

Values returned by ev_* calls will be returned by this function. This value always defaults to None for any non-overridden method.

Changed in version 11.12: Now returns the return value of ev_* methods. event.type values of None are deprecated.

ev_quit(event: Quit, /) T | None[source]

Called when the termination of the program is requested.

ev_keydown(event: KeyDown, /) T | None[source]

Called when a keyboard key is pressed or repeated.

ev_keyup(event: KeyUp, /) T | None[source]

Called when a keyboard key is released.

ev_mousemotion(event: MouseMotion, /) T | None[source]

Called when the mouse is moved.

ev_mousebuttondown(event: MouseButtonDown, /) T | None[source]

Called when a mouse button is pressed.

ev_mousebuttonup(event: MouseButtonUp, /) T | None[source]

Called when a mouse button is released.

ev_mousewheel(event: MouseWheel, /) T | None[source]

Called when the mouse wheel is scrolled.

ev_textinput(event: TextInput, /) T | None[source]

Called to handle Unicode input.

ev_windowshown(event: WindowEvent, /) T | None[source]

Called when the window is shown.

ev_windowhidden(event: WindowEvent, /) T | None[source]

Called when the window is hidden.

ev_windowexposed(event: WindowEvent, /) T | None[source]

Called when a window is exposed, and needs to be refreshed.

This usually means a call to libtcodpy.console_flush is necessary.

ev_windowmoved(event: WindowMoved, /) T | None[source]

Called when the window is moved.

ev_windowresized(event: WindowResized, /) T | None[source]

Called when the window is resized.

ev_windowminimized(event: WindowEvent, /) T | None[source]

Called when the window is minimized.

ev_windowmaximized(event: WindowEvent, /) T | None[source]

Called when the window is maximized.

ev_windowrestored(event: WindowEvent, /) T | None[source]

Called when the window is restored.

ev_windowenter(event: WindowEvent, /) T | None[source]

Called when the window gains mouse focus.

ev_windowleave(event: WindowEvent, /) T | None[source]

Called when the window loses mouse focus.

ev_windowfocusgained(event: WindowEvent, /) T | None[source]

Called when the window gains keyboard focus.

ev_windowfocuslost(event: WindowEvent, /) T | None[source]

Called when the window loses keyboard focus.

ev_windowclose(event: WindowEvent, /) T | None[source]

Called when the window manager requests the window to be closed.

ev_joyaxismotion(event: JoystickAxis, /) T | None[source]

Called when a joystick analog is moved.

Added in version 13.8.

ev_joyballmotion(event: JoystickBall, /) T | None[source]

Called when a joystick ball is moved.

Added in version 13.8.

ev_joyhatmotion(event: JoystickHat, /) T | None[source]

Called when a joystick hat is moved.

Added in version 13.8.

ev_joybuttondown(event: JoystickButton, /) T | None[source]

Called when a joystick button is pressed.

Added in version 13.8.

ev_joybuttonup(event: JoystickButton, /) T | None[source]

Called when a joystick button is released.

Added in version 13.8.

ev_joydeviceadded(event: JoystickDevice, /) T | None[source]

Called when a joystick is added.

Added in version 13.8.

ev_joydeviceremoved(event: JoystickDevice, /) T | None[source]

Called when a joystick is removed.

Added in version 13.8.

ev_controlleraxismotion(event: ControllerAxis, /) T | None[source]

Called when a controller analog is moved.

Added in version 13.8.

ev_controllerbuttondown(event: ControllerButton, /) T | None[source]

Called when a controller button is pressed.

Added in version 13.8.

ev_controllerbuttonup(event: ControllerButton, /) T | None[source]

Called when a controller button is released.

Added in version 13.8.

ev_controllerdeviceadded(event: ControllerDevice, /) T | None[source]

Called when a standard controller is added.

Added in version 13.8.

ev_controllerdeviceremoved(event: ControllerDevice, /) T | None[source]

Called when a standard controller is removed.

Added in version 13.8.

ev_controllerdeviceremapped(event: ControllerDevice, /) T | None[source]

Called when a standard controller is remapped.

Added in version 13.8.

classmethod __class_getitem__(params)

Parameterizes a generic class.

At least, parameterizing a generic class is the main thing this method does. For example, for some generic class Foo, this is called when we do Foo[int] - there, with cls=Foo and params=int.

However, note that this method is also called when defining generic classes in the first place with class Foo(Generic[T]): ….

tcod.event.get_keyboard_state() NDArray[np.bool_][source]

Return a boolean array with the current keyboard state.

Index this array with a scancode. The value will be True if the key is currently held.

Example:

state = tcod.event.get_keyboard_state()

# Get a WASD movement vector:
x = int(state[tcod.event.Scancode.D]) - int(state[tcod.event.Scancode.A])
y = int(state[tcod.event.Scancode.S]) - int(state[tcod.event.Scancode.W])

# Key with 'z' glyph is held:
is_z_held = state[tcod.event.KeySym.z.scancode]

Added in version 12.3.

tcod.event.get_modifier_state() Modifier[source]

Return a bitmask of the active keyboard modifiers.

Added in version 12.3.

tcod.event.time_ns() int[source]

Return the nanoseconds elapsed since SDL was initialized.

Added in version 21.0.

tcod.event.time() float[source]

Return the seconds elapsed since SDL was initialized.

Added in version 21.0.

Getting events

The primary way to capture events is with the tcod.event.get and tcod.event.wait functions. These functions return events in a loop until the internal event queue is empty. Use isinstance(), tcod.event.EventDispatch, or match statements (introduced in Python 3.10) to determine which event was returned.

tcod.event.get() Iterator[Event][source]

Return an iterator for all pending events.

Events are processed as the iterator is consumed. Breaking out of, or discarding the iterator will leave the remaining events on the event queue. It is also safe to call this function inside of a loop that is already handling events (the event iterator is reentrant.)

tcod.event.wait(timeout: float | None = None) Iterator[Event][source]

Block until events exist, then return an event iterator.

timeout is the maximum number of seconds to wait as a floating point number with millisecond precision, or it can be None to wait forever.

Returns the same iterator as a call to tcod.event.get.

This function is useful for simple games with little to no animations. The following example sleeps whenever no events are queued:

Example:

context: tcod.context.Context  # Context object initialized earlier.
while True:  # Main game-loop.
    console: tcod.console.Console  # Console used for rendering.
    ...  # Render the frame to `console` and then:
    context.present(console)  # Show the console to the display.
    # The ordering to draw first before waiting for events is important.
    for event in tcod.event.wait():  # Sleeps until the next events exist.
        ...  # All events are handled at once before the next frame.

See tcod.event.get examples for how different events are handled.

Keyboard Enums

  • KeySym: Keys based on their glyph.

  • Scancode: Keys based on their physical location.

  • Modifier: Keyboard modifier keys.

class tcod.event.KeySym(value)[source]

Keyboard constants based on their symbol.

These names are derived from SDL except for numbers which are prefixed with N (since raw numbers can not be a Python name). Alternatively KeySym["9"] can be used to represent numbers (since Python 3.13).

Added in version 12.3.

Changed in version 19.0: SDL backend was updated to 3.x, which means some enums have been renamed. Single letters are now uppercase.

Changed in version 19.6: Number symbols can now be fetched with KeySym["9"], etc. With Python 3.13 or later.

UNKNOWN

0

BACKSPACE

8

TAB

9

RETURN

13

ESCAPE

27

SPACE

32

EXCLAIM

33

QUOTEDBL

34

HASH

35

DOLLAR

36

PERCENT

37

AMPERSAND

38

QUOTE

39

LEFTPAREN

40

RIGHTPAREN

41

ASTERISK

42

PLUS

43

COMMA

44

MINUS

45

PERIOD

46

SLASH

47

N0

48

N1

49

N2

50

N3

51

N4

52

N5

53

N6

54

N7

55

N8

56

N9

57

COLON

58

SEMICOLON

59

LESS

60

EQUALS

61

GREATER

62

QUESTION

63

AT

64

LEFTBRACKET

91

BACKSLASH

92

RIGHTBRACKET

93

CARET

94

UNDERSCORE

95

BACKQUOTE

96

A

97

B

98

C

99

D

100

E

101

F

102

G

103

H

104

I

105

J

106

K

107

L

108

M

109

N

110

O

111

P

112

Q

113

R

114

S

115

T

116

U

117

V

118

W

119

X

120

Y

121

Z

122

DELETE

127

SCANCODE_MASK

1073741824

CAPSLOCK

1073741881

F1

1073741882

F2

1073741883

F3

1073741884

F4

1073741885

F5

1073741886

F6

1073741887

F7

1073741888

F8

1073741889

F9

1073741890

F10

1073741891

F11

1073741892

F12

1073741893

PRINTSCREEN

1073741894

SCROLLLOCK

1073741895

PAUSE

1073741896

INSERT

1073741897

HOME

1073741898

PAGEUP

1073741899

END

1073741901

PAGEDOWN

1073741902

RIGHT

1073741903

LEFT

1073741904

DOWN

1073741905

UP

1073741906

NUMLOCKCLEAR

1073741907

KP_DIVIDE

1073741908

KP_MULTIPLY

1073741909

KP_MINUS

1073741910

KP_PLUS

1073741911

KP_ENTER

1073741912

KP_1

1073741913

KP_2

1073741914

KP_3

1073741915

KP_4

1073741916

KP_5

1073741917

KP_6

1073741918

KP_7

1073741919

KP_8

1073741920

KP_9

1073741921

KP_0

1073741922

KP_PERIOD

1073741923

APPLICATION

1073741925

POWER

1073741926

KP_EQUALS

1073741927

F13

1073741928

F14

1073741929

F15

1073741930

F16

1073741931

F17

1073741932

F18

1073741933

F19

1073741934

F20

1073741935

F21

1073741936

F22

1073741937

F23

1073741938

F24

1073741939

EXECUTE

1073741940

HELP

1073741941

MENU

1073741942

SELECT

1073741943

STOP

1073741944

AGAIN

1073741945

UNDO

1073741946

CUT

1073741947

COPY

1073741948

PASTE

1073741949

FIND

1073741950

MUTE

1073741951

VOLUMEUP

1073741952

VOLUMEDOWN

1073741953

KP_COMMA

1073741957

KP_EQUALSAS400

1073741958

ALTERASE

1073741977

SYSREQ

1073741978

CANCEL

1073741979

CLEAR

1073741980

PRIOR

1073741981

RETURN2

1073741982

SEPARATOR

1073741983

OUT

1073741984

OPER

1073741985

CLEARAGAIN

1073741986

CRSEL

1073741987

EXSEL

1073741988

KP_00

1073742000

KP_000

1073742001

THOUSANDSSEPARATOR

1073742002

DECIMALSEPARATOR

1073742003

CURRENCYUNIT

1073742004

CURRENCYSUBUNIT

1073742005

KP_LEFTPAREN

1073742006

KP_RIGHTPAREN

1073742007

KP_LEFTBRACE

1073742008

KP_RIGHTBRACE

1073742009

KP_TAB

1073742010

KP_BACKSPACE

1073742011

KP_A

1073742012

KP_B

1073742013

KP_C

1073742014

KP_D

1073742015

KP_E

1073742016

KP_F

1073742017

KP_XOR

1073742018

KP_POWER

1073742019

KP_PERCENT

1073742020

KP_LESS

1073742021

KP_GREATER

1073742022

KP_AMPERSAND

1073742023

KP_DBLAMPERSAND

1073742024

KP_VERTICALBAR

1073742025

KP_DBLVERTICALBAR

1073742026

KP_COLON

1073742027

KP_HASH

1073742028

KP_SPACE

1073742029

KP_AT

1073742030

KP_EXCLAM

1073742031

KP_MEMSTORE

1073742032

KP_MEMRECALL

1073742033

KP_MEMCLEAR

1073742034

KP_MEMADD

1073742035

KP_MEMSUBTRACT

1073742036

KP_MEMMULTIPLY

1073742037

KP_MEMDIVIDE

1073742038

KP_PLUSMINUS

1073742039

KP_CLEAR

1073742040

KP_CLEARENTRY

1073742041

KP_BINARY

1073742042

KP_OCTAL

1073742043

KP_DECIMAL

1073742044

KP_HEXADECIMAL

1073742045

LCTRL

1073742048

LSHIFT

1073742049

LALT

1073742050

LGUI

1073742051

RCTRL

1073742052

RSHIFT

1073742053

RALT

1073742054

RGUI

1073742055

MODE

1073742081

AUDIONEXT

1073742082

AUDIOPREV

1073742083

AUDIOSTOP

1073742084

AUDIOPLAY

1073742085

AUDIOMUTE

1073742086

MEDIASELECT

1073742087

WWW

1073742088

MAIL

1073742089

CALCULATOR

1073742090

COMPUTER

1073742091

AC_SEARCH

1073742092

AC_HOME

1073742093

AC_BACK

1073742094

AC_FORWARD

1073742095

AC_STOP

1073742096

AC_REFRESH

1073742097

AC_BOOKMARKS

1073742098

BRIGHTNESSDOWN

1073742099

BRIGHTNESSUP

1073742100

DISPLAYSWITCH

1073742101

KBDILLUMTOGGLE

1073742102

KBDILLUMDOWN

1073742103

KBDILLUMUP

1073742104

EJECT

1073742105

SLEEP

1073742106

__eq__(other: object) bool[source]

Compare with another KeySym value.

Comparison between KeySym and Scancode is not allowed and will raise TypeError.

__hash__() int[source]

Return the hash for this value.

__repr__() str[source]

Return the fully qualified name of this enum.

property keysym: KeySym

Return a keycode from a scancode.

Returns itself since it is already a KeySym.

See also

Scancode.keysym

property label: str

A human-readable name of a keycode.

Returns “” if the keycode doesn’t have a name.

Be sure not to confuse this with .name, which will return the enum name rather than the human-readable name.

Example:

>>> import tcod.event
>>> tcod.event.KeySym.F1.label
'F1'
>>> tcod.event.KeySym.BACKSPACE.label
'Backspace'
property scancode: Scancode

Return a scancode from a keycode.

Based on the current keyboard layout.

class tcod.event.Scancode(value)[source]

A Scancode represents the physical location of a key.

For example the scan codes for WASD remain in the same physical location regardless of the actual keyboard layout.

These names are derived from SDL except for the numbers which are prefixed with N (since raw numbers can not be a Python name.)

Added in version 12.3.

UNKNOWN

0

A

4

B

5

C

6

D

7

E

8

F

9

G

10

H

11

I

12

J

13

K

14

L

15

M

16

N

17

O

18

P

19

Q

20

R

21

S

22

T

23

U

24

V

25

W

26

X

27

Y

28

Z

29

N1

30

N2

31

N3

32

N4

33

N5

34

N6

35

N7

36

N8

37

N9

38

N0

39

RETURN

40

ESCAPE

41

BACKSPACE

42

TAB

43

SPACE

44

MINUS

45

EQUALS

46

LEFTBRACKET

47

RIGHTBRACKET

48

BACKSLASH

49

NONUSHASH

50

SEMICOLON

51

APOSTROPHE

52

GRAVE

53

COMMA

54

PERIOD

55

SLASH

56

CAPSLOCK

57

F1

58

F2

59

F3

60

F4

61

F5

62

F6

63

F7

64

F8

65

F9

66

F10

67

F11

68

F12

69

PRINTSCREEN

70

SCROLLLOCK

71

PAUSE

72

INSERT

73

HOME

74

PAGEUP

75

DELETE

76

END

77

PAGEDOWN

78

RIGHT

79

LEFT

80

DOWN

81

UP

82

NUMLOCKCLEAR

83

KP_DIVIDE

84

KP_MULTIPLY

85

KP_MINUS

86

KP_PLUS

87

KP_ENTER

88

KP_1

89

KP_2

90

KP_3

91

KP_4

92

KP_5

93

KP_6

94

KP_7

95

KP_8

96

KP_9

97

KP_0

98

KP_PERIOD

99

NONUSBACKSLASH

100

APPLICATION

101

POWER

102

KP_EQUALS

103

F13

104

F14

105

F15

106

F16

107

F17

108

F18

109

F19

110

F20

111

F21

112

F22

113

F23

114

F24

115

EXECUTE

116

HELP

117

MENU

118

SELECT

119

STOP

120

AGAIN

121

UNDO

122

CUT

123

COPY

124

PASTE

125

FIND

126

MUTE

127

VOLUMEUP

128

VOLUMEDOWN

129

KP_COMMA

133

KP_EQUALSAS400

134

INTERNATIONAL1

135

INTERNATIONAL2

136

INTERNATIONAL3

137

INTERNATIONAL4

138

INTERNATIONAL5

139

INTERNATIONAL6

140

INTERNATIONAL7

141

INTERNATIONAL8

142

INTERNATIONAL9

143

LANG1

144

LANG2

145

LANG3

146

LANG4

147

LANG5

148

LANG6

149

LANG7

150

LANG8

151

LANG9

152

ALTERASE

153

SYSREQ

154

CANCEL

155

CLEAR

156

PRIOR

157

RETURN2

158

SEPARATOR

159

OUT

160

OPER

161

CLEARAGAIN

162

CRSEL

163

EXSEL

164

KP_00

176

KP_000

177

THOUSANDSSEPARATOR

178

DECIMALSEPARATOR

179

CURRENCYUNIT

180

CURRENCYSUBUNIT

181

KP_LEFTPAREN

182

KP_RIGHTPAREN

183

KP_LEFTBRACE

184

KP_RIGHTBRACE

185

KP_TAB

186

KP_BACKSPACE

187

KP_A

188

KP_B

189

KP_C

190

KP_D

191

KP_E

192

KP_F

193

KP_XOR

194

KP_POWER

195

KP_PERCENT

196

KP_LESS

197

KP_GREATER

198

KP_AMPERSAND

199

KP_DBLAMPERSAND

200

KP_VERTICALBAR

201

KP_DBLVERTICALBAR

202

KP_COLON

203

KP_HASH

204

KP_SPACE

205

KP_AT

206

KP_EXCLAM

207

KP_MEMSTORE

208

KP_MEMRECALL

209

KP_MEMCLEAR

210

KP_MEMADD

211

KP_MEMSUBTRACT

212

KP_MEMMULTIPLY

213

KP_MEMDIVIDE

214

KP_PLUSMINUS

215

KP_CLEAR

216

KP_CLEARENTRY

217

KP_BINARY

218

KP_OCTAL

219

KP_DECIMAL

220

KP_HEXADECIMAL

221

LCTRL

224

LSHIFT

225

LALT

226

LGUI

227

RCTRL

228

RSHIFT

229

RALT

230

RGUI

231

MODE

257

AUDIONEXT

258

AUDIOPREV

259

AUDIOSTOP

260

AUDIOPLAY

261

AUDIOMUTE

262

MEDIASELECT

263

WWW

264

MAIL

265

CALCULATOR

266

COMPUTER

267

AC_SEARCH

268

AC_HOME

269

AC_BACK

270

AC_FORWARD

271

AC_STOP

272

AC_REFRESH

273

AC_BOOKMARKS

274

BRIGHTNESSDOWN

275

BRIGHTNESSUP

276

DISPLAYSWITCH

277

KBDILLUMTOGGLE

278

KBDILLUMDOWN

279

KBDILLUMUP

280

EJECT

281

SLEEP

282

APP1

283

APP2

284

__eq__(other: object) bool[source]

Compare with another Scancode value.

Comparison between KeySym and Scancode is not allowed and will raise TypeError.

__hash__() int[source]

Return the hash for this value.

__repr__() str[source]

Return the fully qualified name of this enum.

property keysym: KeySym

Return a KeySym from a scancode.

Based on the current keyboard layout.

property label: str

Return a human-readable name of a key based on its scancode.

Be sure not to confuse this with .name, which will return the enum name rather than the human-readable name.

See also

KeySym.label

property scancode: Scancode

Return a scancode from a keycode.

Returns itself since it is already a Scancode.

See also

KeySym.scancode

class tcod.event.Modifier(value)[source]

Keyboard modifier flags, a bit-field of held modifier keys.

Use bitwise and to check if a modifier key is held.

The following example shows some common ways of checking modifiers. All non-zero return values are considered true.

Example:

>>> import tcod.event
>>> mod = tcod.event.Modifier(4098)
>>> mod & tcod.event.Modifier.SHIFT  # Check if any shift key is held.
<Modifier.RSHIFT: 2>
>>> mod & tcod.event.Modifier.LSHIFT  # Check if left shift key is held.
<Modifier.NONE: 0>
>>> not mod & tcod.event.Modifier.LSHIFT  # Check if left shift key is NOT held.
True
>>> mod & tcod.event.Modifier.SHIFT and mod & tcod.event.Modifier.CTRL  # Check if Shift+Control is held.
<Modifier.NONE: 0>

Added in version 12.3.

NONE = 0
LSHIFT = 1

Left shift.

RSHIFT = 2

Right shift.

SHIFT = 3

LSHIFT | RSHIFT

LCTRL = 64

Left control.

RCTRL = 128

Right control.

CTRL = 192

LCTRL | RCTRL

LALT = 256

Left alt.

RALT = 512

Right alt.

ALT = 768

LALT | RALT

LGUI = 1024

Left meta key.

RGUI = 2048

Right meta key.

GUI = 3072

LGUI | RGUI

NUM = 4096

Numpad lock.

CAPS = 8192

Caps lock.

MODE = 16384

Alt graph.