Skip to main content

TTY Engine

A terminal rendering, physics and sound engine for Python.

Build animated, interactive scenes out of text, with collisions, joints, lighting, FIGlet fonts, images and audio, using nothing but the standard library.

Python Status License Platforms Commits PyPI

Installation · Quick start · How it works · Usage guide · Examples · Configuration · Requirements · Changelog · License


TTY Engine draws everything as styled text and updates the terminal once per frame. Objects are assembled from small components, which are attached automatically based on the keyword arguments you pass when creating them. A box of text becomes a physics body as soon as you give it a velocity, and a light source as soon as you give it a light.

  • No dependencies. Image decoding (PNG, JPEG, GIF, BMP, PNM; many more when ffmpeg is installed), FIGlet text, the audio mixer and the terminal and input handling are all implemented in the standard library.
  • Component-based objects. transform, physics, pen, force, joint and light cover position and style, collisions, drawing, area forces, linked bodies and lighting.
  • Rich text output. Truecolor, transparency and fades, bundled FIGlet fonts, and image-to-text conversion.
  • Input and sound included. Keyboard and mouse input with press, release and held states, plus a built-in mixer with a small synthesizer.
  • Simple structure. Write a class (or just a function) with start, update and final methods, and hand it to start().

Installation

Install from PyPI
pip install ttyengine

To get the latest unreleased changes, install straight from the repository:

pip install git+https://github.com/asard6348/tty-engine

To work on the engine itself, clone it and install in editable mode:

git clone https://github.com/asard6348/tty-engine
cd tty-engine
pip install -e .

The test suite runs with the standard library only:

python -m unittest discover -s tests

ttyengine.__version__ reports the installed version.

Optional extras
Extra Command What it adds
keyboard pip install "ttyengine[keyboard]" Key press and release tracking through the keyboard package, which makes inp.held() accurate. It needs root on Linux and macOS and is skipped over SSH.
ffmpeg pip install "ttyengine[ffmpeg]" A bundled ffmpeg for decoding compressed audio formats and image formats beyond PNG, JPEG, GIF, BMP and PNM (WebP, TIFF, TGA, AVIF, ...). An ffmpeg already on your PATH works too.

Without the keyboard package the engine tries the kitty keyboard protocol, then its own operating-system key tracking, then plain terminal input. See Input in the usage guide for what that changes.

Quick start

Hello, terminal
from ttyengine import start

class main:
    def start(self, scene, session):
        scene.obj().create('hello, tty', 5, -3)

        def quit():
            session.running = False
        session.inp.onpress('x', quit)

start(main)

Run it, and press x to exit. The text appears five columns from the left and three rows from the top, because y counts upward and the top of the screen is 0 (see Coordinates).

start(*launch, **settings) creates a Session, creates a World holding every handle you pass in, runs the session with your settings and returns a Simulation.

A function works too

A launched handle can be a plain function. It is treated as the handle's start method:

from ttyengine import start

def main(scene, session):
    scene.obj().create('just a function', 2, -2)

start(main)

How it works

Structure: simulation, session, world, scene
flowchart TD
    A[Simulation] --> B[Session]
    B --> C["Terminal · Input · Sound · Compositor"]
    B --> D[World]
    D --> E[Scene]
    D --> F["Handles<br>(start / update / final)"]
    E --> G[Objects]
    G --> H["Components<br>(transform, physics, light, ...)"]
Layer Role
Simulation The top-level container returned by start(). It exposes sessions, worlds, handles and scenes, and has session(), world(), launch(), run() and stop() for building more.
Session Owns the terminal. It provides input (session.inp), sound (session.sound) and styling helpers (session.style, session.styler), and runs the main loop until session.stop() is called or session.running is set to False.
World A scene together with the handles that drive it. A session can hold several worlds, which are composited into a single frame.
Scene The simulated space: objects, gravity, camera, lights and the background color.
Handle Your code. A class (or function) whose start, update and final methods are called by the world.
Object A bag of components. Created with scene.obj().create(...).
The frame loop

Every frame, each active world goes through the same steps:

  1. update is called on every handle, highest priority first.
  2. scene.tick() advances the simulation: physics, fades, joints and lights.
  3. final is called on every handle, after the physics has settled.
  4. The scene's pending changes are flushed and the compositor builds the frame, which is written to the terminal in a single synchronized update.

Use update for input and decisions, and final for anything that should react to where physics left things, such as a camera that follows an object.

The frame rate is controlled per scene through scene.framerate (60 by default, capped by scene.maxframerate). Physics advances one step per tick, so velocities are measured in cells per tick.

Coordinates
  • The origin (0, 0) is the top-left corner of the view.
  • x grows to the right.
  • y grows upward, so anything visible on screen below the origin has a negative y.
  • The camera (scene.camx, scene.camy) is the world position of the top-left corner of the view.
scene.obj().create('top-left corner', 0, 0)
scene.obj().create('three rows down', 0, -3)

Mouse positions are reported in terminal cells counted from the top-left. With the camera at its default position, a mouse cell (x, y) corresponds to the world position (x, -y).

Objects and components

An object starts out empty. create() looks at its keyword arguments, attaches the components that own them, and passes each value on. transform is always attached; the others are added the first time you use one of their settings.

Component Added when you pass What it does
transform always Position, text, colors, opacity, rotation, flipping, shadow, visibility (show), drawing order (z) and whether spaces are drawn (spaces).
physics xvel, yvel, bounciness, gravity, friction, mass, phantom, ... Velocity, collisions, bouncing, friction and touch callbacks.
pen pen={...} Paints characters at a point relative to the object. Settings: char, x, y, radius, shape.
force force=... or force={...} Pushes other objects, optionally limited by a radius or a filter. Settings: strength, affect, cap, position, radius, torque, shield.
joint preset, joints, elasticity, kind, limit, target, ... Links objects together as a rope, rod, spring, hinge, slider or fixed joint. A pinned ball joint can also limit and motor the follower's rotation with limit, target, gain and effort.
light light=True or light={...} Turns the object into a light source. Settings: color, alpha, radius, falloff, shadows, cone, direction, glow and more. scene.ambient sets the base brightness.
humanoid humanoid={'parts': {...}} Builds a posable figure from a graph of parts, with the object as its root part. Settings: parts, solid, physics, style, joints, poses, cycles, axis, elasticity, spaces.

Settings can be given flat, or grouped under the component's name. The two calls below are equivalent:

scene.obj().create('x', 3, -4, bounciness=0.5, friction=0.1)
scene.obj().create('x', transform={'x': 3, 'y': -4},
                   physics={'bounciness': 0.5, 'friction': 0.1})

Some names are shared between components, such as x, y and radius, so pen, force and light are configured through their grouped form:

scene.obj().create('*', 20, -6, light={'color': 'yellow', 'radius': 12})
scene.obj().create('@', 10, -6, force={'strength': 2, 'radius': 8})
scene.obj().create('+', 5, -2, pen={'char': '*', 'radius': 2})
Handles and their parameters

A handle may define any of start, update and final. Each one receives only the arguments it asks for, matched by parameter name:

Name Value
scene The world's scene.
session The running session, which gives you session.inp, session.sound and session.running.
world The world that owns the handle.
handle The handle itself, which can be paused or cancelled.
sound Shortcut for session.sound.
simulation The Simulation, for creating more sessions and worlds.

A world's scene.canvas and scene.view (also available as scene.termx, scene.termy, scene.dimx, scene.dimy, scene.dimxoffset and scene.dimyoffset) are filled in as soon as the world is created, using the terminal size, the session's region and the world's own region, so start and any code that runs before session.run() already sees the real values. They keep following the terminal while the session runs, unless autoterm or autodim is turned off. See Regions.

class main:
    priority = 5            # higher runs first within a frame (default 0)

    def start(self, scene):                 # once, when launched
        ...
    def update(self, scene, session):       # every frame, before physics
        ...
    def final(self, scene):                 # every frame, after physics
        ...
Waiting, timers and tasks

A handle can pause its own code, or schedule code to run later, without stopping anything else. The frame loop, physics, rendering, input and the handle's other functions keep running. Request the handle argument like any other (see the table above).

handle.wait(duration, frames=False) suspends the function that calls it. The rest of that function runs once duration seconds have passed, or duration frames with frames=True:

def final(self, scene, handle):
    if self.scored():
        self.reset_ball()       # runs now
        handle.wait(1)          # this function stops here for one second
        self.release_ball()     # runs one second later

handle.until(condition, timeout=None, frames=False) suspends until condition() returns true. It returns True when the condition was met and False when timeout ran out first:

def start(self, handle, session):
    if not handle.until(lambda: session.inp.held('space'), timeout=5):
        print('nobody pressed space')

handle.after(delay, fn, frames=False) and handle.every(interval, fn, frames=False, delay=None) run fn later, once or repeatedly. fn receives the same arguments as start, update and final (scene, handle and so on, matched by name), and every first fires after delay, which defaults to interval. Both work from anywhere, including input callbacks and helper functions, and both return a Task:

blink = handle.every(0.5, lambda scene: scene.obj().create('*', 2, -2))
handle.after(10, blink.cancel)

Task is one scheduled callback or one suspended function. It is created by after and every, or directly with Task(handle, fn, delay=0.0, interval=None, frames=False), and from ttyengine import Task imports it. A task is cancelled the same way as a handle:

Member Meaning
task.cancel() Stops the task. A function suspended in wait or until never runs the code after it, and a repeating task stops repeating. world.cancel(task) does the same.
task.done True once the callback has finished (a repeating task never is).
task.cancelled True after cancel().
task.result The return value of the last run.

handle.tasks lists every live task of the handle: its timers and its suspended start, update and final calls. handle.cancel() cancels all of them, and cancelling one task leaves the handle and its other tasks running, so a "skip the cutscene" button is for task in handle.tasks: task.cancel().

Things to know:

  • start, update and final each wait on their own. A wait in final does not stop update, so players can keep moving while the ball is held.
  • While a function is waiting, the world does not call it again. It is called normally once it has finished.
  • start can wait too. Its code resumes on the following frames, and a function used as a handle (see A function works too) can wait the same way.
  • Write wait and until directly in start, update, final or the function you pass to after or every. Inside a helper they cannot suspend the caller: wait just sleeps, which blocks the whole engine for that time, and until raises a RuntimeError. Called from an input callback, wait also just sleeps.
  • Everything is checked once per frame, so a delay is accurate to one frame time.
  • While a handle is paused (handle.pause = True), its world is paused or the session is paused, the clock of its waits and timers stands still, and frame counts only advance on frames the handle actually ran. Time spent paused does not count towards a delay.
  • Only one piece of your code runs at a time, so a waiting function never runs at the same moment as the frame loop and needs no locking. An error raised after a wait is reported like any other error inside a handle.

pause is a property on handles, worlds and the session, as are pausephysics and pauserendering on worlds and the session. They accept any truthy or falsy value and store a bool.

Usage guide

Creating, changing and removing objects
obj = scene.obj().create('hello', 10, -4, fg='cyan')

obj.transform.x += 1          # components are plain attributes
obj['x'] = 12                 # or read and write settings by name

copy = obj.clone(x=30)        # same settings, with overrides
obj.ondiscard(lambda: print('gone'))
obj.discard()                 # remove it from the scene

obj.kwargs() returns the settings that were set explicitly, which is what clone() uses.

Keyboard and mouse input

Input lives on session.inp. Callbacks receive as many of their possible arguments as their signature accepts, so a callback can take none, some or all of them.

inp = session.inp

inp.onpress('space', jump)                 # on key down
inp.onrelease('space', stop_jump)          # on key up
inp.onkey(None, log_key, event='press')    # every key; cb(key, event)
inp.onpress('x', quit, once=True)          # remove itself after firing
inp.onpress('a', go_left, caps=True)       # matches 'a' and 'A'

inp.held('left')                           # True while the key is down
inp.held(['left', 'a'])                    # True if any of them is down
inp.held()                                 # list of every key currently down

inp.onmouse('click', on_click)             # cb(x, y, data, event)
inp.onmouse('move', on_move)               # 'click', 'release', 'move', 'wheel' or 'any'
inp.mouse                                  # current mouse position

Key names include letters, digits, up, down, left, right, space, esc, enter, tab, backspace and shift.

Callbacks can be removed again with offpress, offrelease, offkey, offmouse and stop_all.

Mouse state is also available directly: inp.mouse is the current position, inp.mouseheld(button) tells whether a button is down (0 left, 1 middle, 2 right) and inp.wheel is the last wheel step (1 up, -1 down, 0 none). onmouse('move', ...) fires for motion with or without a button held.

How accurate held() and onrelease() are depends on the input backend. The engine uses the first one that works:

  1. The keyboard package, which reports real presses and releases. It needs root on Linux and macOS, and is skipped over SSH.
  2. The kitty keyboard protocol, in terminals that support it, which does the same.
  3. Operating-system key tracking built into the engine, which needs no extra package and also reports real presses and releases: evdev on Linux (read access to /dev/input, through root or the input group), a low-level keyboard hook on Windows, and an event tap on macOS (it needs Input Monitoring permission). It is skipped over SSH.
  4. Plain terminal input otherwise. Terminals do not send release events, so a key counts as held while it keeps repeating. Pass delay= to held() or onrelease() to control how long a key stays held after its last repeat.

inp.backend reports the one in use: 'keyboard', 'kitty', 'evdev', 'kernel' (Windows and macOS) or 'terminal'. To force a backend, pass backend= to Session() ('auto', 'keyboard', 'kitty', 'kernel' or 'evdev', or 'terminal'); a forced backend that is unavailable raises RuntimeError.

Backends with real key events repeat a held key's onpress callbacks the way a terminal would: first after repeatdelay seconds (default 0.5), then repeatrate times per second (default 30). Both are Session() options, and a repeatrate of 0 turns repeating off.

Physics

Giving an object any physics setting makes it a physics body. By default bodies are dynamic (they move) and solid (they block other solids).

scene.gravity = (0, -1)                     # (x, y) acceleration for the whole scene

ball  = scene.obj().create('O', 10, 0, bounciness=0.8)
floor = scene.obj().create('#' * 40, 0, -10, dynamic=False)   # immovable
Setting Meaning
xvel, yvel, avel Linear velocity in cells per tick, and angular velocity.
dynamic False makes the object immovable, so it acts as a wall or floor.
solid Whether other solid bodies are blocked by it.
phantom Lets other bodies pass through, while still reporting overlaps.
bounciness, friction Surface behavior on contact.
mass Defaults to the number of visible characters.
precision The largest distance, in cells, a body moves per sub-step while checking for collisions. Defaults to scene.precision (0.5). Free space is crossed in one jump, so it only costs time near obstacles.
rprecision How coarsely a rotating body is tested for collisions, in degrees per piece. Automatic by default: a piece moves the outermost cell by at most precision cells, and never less than 3 degrees. Assign a number (for example rprecision=3) to pin it, or None to return to automatic.
gravity An (x, y) pair that overrides the scene's gravity for this object.
drag Overrides the scene's drag for this object.
bouncethreshold Impact speed below which a collision does not bounce. Defaults to scene.bouncethreshold (0.25); set it to 0 to let shallow impacts bounce. When two bodies disagree, the lower value wins.

Reacting to contact. Two tools cover the two common cases:

# Blocked by a solid: check the contact flags after the tick.
ball.physics.touch          # (touching_horizontally, touching_vertically)

# Overlapping something: ontouch fires while the objects overlap, which makes
# a phantom object a good trigger zone.
zone = scene.obj().create('[    ]', 20, -5, dynamic=False, phantom=True)

def entered(other):
    print('something is inside the zone')

player.physics.ontouch(entered)

ontouch(callback, when=None, once=False) accepts a when(other) filter and can be limited to a single call with once=True.

ontouch fires when one body moves into another. A body that is only resting against, or pushed against by, another body does not trigger it, so use touch, sides and grounded for that case.

Letting bodies pass through each other. ghost(other) stops two bodies from colliding, and unghost(other) makes them collide again. other is an object, or a function that is called with the other object (and, if it takes a second parameter, the overlapping cells) and returns True while the pair should pass through each other. Ghosting works in both directions, so unghost clears it whichever of the two bodies it was set on, and it returns True when something was removed. Pairs that a joint keeps apart stay ghosted, and a function is removed by passing the same function again.

bullet.physics.ghost(shooter)       # the bullet passes through the shooter
...
bullet.physics.unghost(shooter)     # now it collides with the shooter again

Headings and bouncing. transform.forward and transform.bounce use the object's rotation as the heading unless you pass angle=. Assigning the result to rotation also turns the sprite and its collision cells, so keep a separate heading and pass it as angle when the object should not rotate:

heading = ball_heading                                  # your own variable, in degrees
if ball.transform.approaching(normal, angle=heading):  # True when moving into the surface
    heading = ball.transform.bounce(normal, angle=heading)
heading = ball.transform.bounce(normal, angle=heading, incoming_only=True)   # same check in one call
dx, dy = ball.transform.forward(1, angle=heading)
Humanoid figures

A humanoid component turns an object into the root of a jointed, posable figure. A figure is a graph of parts: every part is built from the text you give it, one part has no parent and becomes the object itself, and every other part hangs off a parent through a joint. Nothing is built in, so the same component makes people, spiders, robots or trees.

parts = {
    'torso': '###\n###\n###',
    'head': {'text': 'O', 'parent': 'torso', 'at': 'top', 'joint': 'neck'},
    'left_arm': {'text': '|\n|\n|', 'parent': 'torso', 'at': 'top_left', 'pin': 'top', 'shift': (-0.5, 0),
                 'joint': 'shoulder', 'group': 'arm'},
    'right_arm': {'mirror': 'left_arm'},
    'left_thigh': {'text': '|\n|\n|', 'parent': 'torso', 'at': 'bottom_left', 'pin': 'top', 'shift': (0.5, 0),
                   'joint': 'hip', 'group': 'thigh', 'density': 10},
    'right_thigh': {'mirror': 'left_thigh', 'flip': False},
    'left_shin': {'text': '|\n|\n|', 'parent': 'left_thigh', 'joint': 'knee', 'group': 'shin',
                  'density': 10},
    'right_shin': {'mirror': 'left_shin', 'flip': False},
}
poses = {'arms_out': {'arm': 90}, 'crouch': {'thigh': -60, 'shin': 100}}
cycles = {'walk': {'left_thigh': {'amp': -32}, 'right_thigh': {'amp': 32}, 'arm': {'amp': 35}}}
body = scene.obj().create(None, 20, -10, humanoid={'parts': parts, 'poses': poses, 'cycles': cycles})
figure = body.humanoid

figure.apply_pose('arms_out')            # poses and cycles are plain dicts: figure.poses, figure.cycles
figure.pose('arms_out')                  # a registered pose name works too
figure.pose({'left_thigh': -30})         # angles are degrees from the rest pose, clamped to joint limits
figure.velocity = (0.2, None)            # moves every part together
figure.animate('walk', phase)            # call each frame with a growing phase
figure.jump(0.6)                         # only while grounded
figure.detach('left_shin')               # frees a part and everything attached to it
figure.ragdoll()                         # releases every joint; figure.ragdoll(False) stiffens them again

Placement. A part is placed by two anchors that meet at its joint: at is a point on the parent and pin is a point on the part itself. An anchor is a name (top, bottom, left, right, center, top_left, top_right, bottom_left, bottom_right) or an (x, y) pair of fractions of the part's size. at defaults to bottom and pin defaults to the opposite point, so a part sits against the parent on the side of its anchor. shift=(dx, dy) moves the joint in cells. The part is snapped to whole cells and the joint sits exactly on its pin.

Mirroring. {'mirror': 'name'} reflects another part across the vertical centre line of the root (or of the part named by the axis setting), inherits its text, density, solid, z, physics, style, group and joint, and hangs from the mirror of the source's parent unless parent is given. A mirrored joint has its limits and rest angle reversed, and so do the angles you pass through a group name; set flip to False to keep the same direction on both sides.

Naming. A pose, cycle, style, get, set_text or remove_part key is a part name or a group. Every part belongs to a group with its own name and to any group names it lists (a string or a list), and mirrored parts share the groups of their source. An exact part name sets the raw angle; a group name applies it with the sign flip of each member.

Joints. joint is a preset name from joint.presets or a dict of joint settings (range, rest, elasticity, durability, ...). The default is hinge. The joints setting overrides joints by group or part name.

Ragdoll. figure.ragdoll(on=True, solid=None, limits=True) turns every pose-driven joint into a free hinge that keeps its length, so the figure collapses under gravity and swings with impacts. solid=True forces every part to collide with the world while it is limp, while the default None keeps each part's own solid setting, and limits=True keeps the joint ranges. While limp, pose and animate do nothing; ragdoll(False) stiffens the joints in their current angles, after which pose works again. figure.ragdolled tells the current state.

Elasticity. The elasticity setting is optional and means what it means for every joint: unset, each joint keeps the joint default of 1; set, it is the default for all joints of the figure, and a joint dict or the joints setting can still override it per part or group. Standing and limp figures use the same value. Values slightly above 1 soften the correction and can remove the sub-cell wobble a heavy standing figure may keep at exactly 1, and values above about 3 make the figure sag.

Limp figures. A ragdoll's limbs are real rigid bodies: each limb is a ball joint pinned at its attach point with its own mass, moment of inertia and angular velocity, and the joint limits are angular impulses between the two bodies, so spin and momentum are conserved and only contacts and friction remove energy. elasticity sets how firmly the pins pull back together, as it does for every other joint of the figure.

Cycles. A cycle channel is bias + amp * sin(phase + shift), or a bare number for amp; rectify=True clamps the sine to positive values. figure.sample(cycle, phase, scale=1.0) returns the angles and figure.animate(cycle, phase, weight=1.0, scale=1.0) applies them.

Other part settings. text, parent, at, pin, shift, joint, mirror, flip, group, density (mass per non-blank cell), solid, z, physics, style and spaces. spaces (default False, also a humanoid setting) makes a part's size ignore a trailing newline like the renderer does; with spaces=True the empty last line counts as a row, so '█\n' * 3 is four rows tall and whatever hangs from it sits one row lower. A part's solid is unset by default and then follows the figure's solid, whose default None makes every part collide with the world; solid=False on a part keeps it from ever colliding and solid=True makes it always collide. The figure's solid can also be a bool or a list of part or group names. The parts of one figure never collide with each other. add_part(name, spec) and add_parts({...}) grow a figure later.

Camera
scene.camx = 40                       # move the view
scene.follow(hero)                    # center the view on an object
scene.follow(hero, smooth=8)          # ease toward it instead of snapping
scene.follow(hero, offset=(0, 3))     # keep the target slightly off-center

Call follow() from final so the camera sees the object's position after physics. scene.camrotation rotates the view.

Text, colors, fonts and images

session.style() returns an ANSI-styled string that you can pass to create() like any other text. The engine reads the colors back out of it, so styled text keeps its layout.

title = session.style('TTY', font='slant', color='cyan')
scene.obj().create(title, 2, -1)

session.style('warning', color='orange', bold=True)
session.style('tint', color=(255, 80, 120), bgcolor='darkblue')
  • Colors can be a name ('red', 'brightcyan', 'darkgreen', 'gray', ...) or an (r, g, b) tuple.
  • FIGlet fonts are bundled. session.styler.fonts() lists them, and font= accepts any name from that list.
  • Shapes are available through session.styler.shapes: circle, ellipse, block, triangle, diamond and line.
  • Images are converted to text with session.styler.image(path, width=..., height=...). PNG, JPEG, GIF, BMP and PNM are decoded by the engine itself, and other formats (WebP, TIFF, TGA, ...) are decoded through ffmpeg when it is available. If you give neither width nor height, the image is 80 columns wide (or its own pixel width, if that is smaller), so the result is the same on every terminal. shades is the string of characters from darkest to brightest, and defaults to a 256-step gradient from a space to █. It is plain monochrome unless you pass color=True, and bgcolor= (a name or (r, g, b)) fills every cell with that background and blends transparent pixels into it.
ring = session.styler.shapes.circle(5)
scene.obj().create(ring, 10, -4)

photo = session.styler.image('logo.png', width=40)
scene.obj().create(photo, 0, -2)

Per-object appearance is set on the transform: fg, bg, alpha, bgalpha, rotation, flip and shadow.

Fades and smooth movement
obj.transform.fade(0, time=1)                          # fade out over one second
obj.transform.fade(0, time=1, discard=True)            # ...and remove it afterwards
obj.transform.fade(1, time=0.5, delay=0.2, ease='linear')

scene.fade((0, 0, 0), time=2)                          # fade the whole scene to black

transform.lerp(weight, **targets) moves any numeric setting a fraction of the way toward a target, which is handy for smoothing inside update:

def update(self):
    self.hero.transform.lerp(0.2, x=self.target_x)
Sound

Audio goes through session.sound, which every handle can also receive as the sound parameter. Files are decoded and cached on first use, and the engine can synthesize simple sounds without any audio files.

sound.beep()                                       # short blip
sound.play(sound.tone(440, 0.5, wave='sine'))      # a sustained note
sound.play(sound.melody('C4 E4 G4:2', beat=0.25))  # note names, optional :beats

voice = sound.play('music.wav', loop=True, volume=0.6)
voice.pitch = 3                 # semitones
voice.pan = -0.5                # left
voice.stop(fade=1.0)

play() returns a Voice, which you can pause, resume, seek, fade and give an oncomplete callback. WAV files load without extra tools, and compressed formats need the ffmpeg extra. Pass Session(sound=False) to turn audio off entirely.

Several worlds and sessions

Each world has its own scene and handles, and the session composites its worlds into one frame. This is useful for a HUD layered over a game, or a menu with its own camera.

Give a world its own region to confine it to one part of the screen, for example a status bar or a sidebar (see Regions).

from ttyengine import Session

session = Session()
game = session.World()
hud  = session.World()

game.launch(game_handle)
hud.launch(hud_handle)

session.run()

The Simulation returned by start() exposes sessions, worlds, handles and scenes, and handles can reach it through their simulation parameter.

Regions: one line, one column, a panel or inline output

The engine does not have to own the whole terminal. A session draws inside a region of the screen, and every world can draw inside a region of that. This is how you use TTY Engine for a status line, a progress bar, a sidebar or a full text UI, not only for games.

Level Setting Meaning
Session Session(region=...) or session.region The part of the terminal the engine draws in. Anything outside it is left untouched.
World session.World(region=...) or world.region The part of the session's region this world draws in. None means all of it.
Scene scene.canvas, scene.view What the world ended up with: the size of the area it may draw in, and the visible window inside it.

A region can be written in any of these forms:

from ttyengine import region

region.line(-1)                          # one row: the last line of the terminal
region.column(0)                         # one column: the first one
region.top(3)  region.bottom(2)          # bars across the full width
region.left(20)  region.right(20)        # panels across the full height
region.box(5, 2, 40, 10)                 # x, y, width, height
region.centered(60, 20)                  # a fixed size in the middle
region.inline(4)                         # 4 rows below the cursor (see below)

(5, 2, 40, 10)                           # a plain tuple: x, y, width, height
{"top": 1, "bottom": 1}                  # insets: everything but the first and last row
{"left": 2, "right": 2, "top": 1}        # keys: x/left, y/top, width, height, right, bottom
(0, 0, "50%", "100%")                    # percentages of the available space
("end", "end", 20, 3)                    # "start", "center" or "end" for x and y
None                                     # everything

Rules for the values:

Value x, y width, height
A number Cells from the top left Size in cells
A negative number Cells from the far edge (-1 is the last row or column) Leave that many cells unused at the far end
None 0 The rest of the available space
"40%" That share of the available space That share of the available space
"start", "center", "end" Align inside the available space n/a

Regions are always clamped to the space they are resolved in, so they never fail on a small terminal. Invalid values raise ValueError. region.resolve(spec, width, height) returns the resulting Region(x, y, width, height) for any spec, and the session's resolved_region shows what it currently covers.

from ttyengine import Session, region

session = Session(region=region.line(-1), clearonstop=False)   # a status line

Several worlds can share one session, each with its own region:

session = Session()
header  = session.World(region=region.top(1))
sidebar = session.World(region={"top": 1, "bottom": 1, "width": 24})
body    = session.World(region={"top": 1, "bottom": 1, "left": 24})
footer  = session.World(region=region.bottom(1))

Each scene sees only its own area: scene.view is (x, y, width, height) of the visible window and scene.canvas is the size of the space it sits in. The camera, follow() and focus() use the view's size, and everything outside the view is clipped. You can also set it by hand with any region (set autodim=False on the world so it is not reset every frame):

scene.view = region.bottom(2)
scene.view = {"left": 1, "right": 1}

Inline output. region.inline(rows) reserves rows at the current cursor position instead of at a fixed place on the screen, for spinners, progress bars and live tables inside an ordinary command-line program. The engine scrolls the terminal if there is not enough room below the cursor, keeps the normal screen (no alternate screen) and leaves the scrollback alone. When the session stops, the rows are cleared and the cursor goes back to where the region started, or with clearonstop=False the last frame stays and the cursor moves below it.

from ttyengine import start, region

start(progress, region=region.inline(2), clearonstop=False)

Outside the whole-terminal case the engine does not use the alternate screen, and when the session stops the cursor returns to where it was before.

The older names keep working: termxoffset, termyoffset, termwidth and termheight read and write the parts of session.region, and scene.termx, scene.termy, scene.dimx, scene.dimy, scene.dimxoffset and scene.dimyoffset are the numbers behind scene.canvas and scene.view (dimyoffset is the negative of the view's y).

Networking: UDP, TCP, servers and peer-to-peer

ttyengine.net shares a running simulation between processes over TCP, UDP or both, using only the standard library. A Node is one participant: it can listen (host), connect (connect) or do both, so the same code builds a dedicated server, a client, or a peer-to-peer mesh. A Sync shares engine state over a node.

from ttyengine import Session, net

node = net.Node('alice')
node.host(7777)                                  # listen on tcp and udp port 7777

other = net.Node('bob')
other.connect(('127.0.0.1', 7777), 'udp')        # or 'tcp', or 'auto'
  • Topology. By default a node that hosts relays messages between the nodes connected to it (a star). Node(mesh=True) makes every node that joins also connect to the nodes already there, so each pair talks directly and nothing is relayed. Node(password=...) rejects nodes with a different password; the check is an HMAC over a per-connection nonce, so the password is never sent and a captured handshake cannot be replayed. A relayed message is only accepted from the node it claims to come from, or from the host this node joined, and Sync honours forwarded entities only from that host.
  • Transports. TCP links use length-prefixed frames. UDP links add a handshake, reliable ordered delivery with retransmission and fragmentation for large messages, a latest-wins unreliable mode, keep-alives and round-trip timing. Everything is non-blocking and driven by node.update(), which Sync.attach calls every frame.
  • Messages. node.send(channel, data, to=None, reliable=True) and node.on(channel, callback) carry any mix of None, bool, int, float, str, bytes, list, tuple, dict and set. '@join' and '@leave' report peers coming and going.

Every layer of the simulation is shared the same way, from the session down to a single variable:

from ttyengine.net import Node, Sync

sync = Sync(node)
session = Session()
sync.share(session, 'game')          # session -> worlds -> scenes -> objects -> components -> variables
sync.attach(session)                 # pump the network inside the frame loop
Share What travels
session bgcolor, fgcolor, pause, pausephysics, pauserendering and its worlds
world layer, pause, pausephysics, pauserendering and its scene
scene gravity, drag, precision, bouncethreshold, aspect, ambient and its objects
obj every setting of every component it has (transform, physics, joint, light, force, pen), plus plain attributes you name
(obj, 'x', 'y') just those variables
  • Roots have names. share(target, 'name') must be called with the same name on every node that takes part. The cameras, terminal settings and other per-screen values are not shared unless you ask for them with vars=.
  • Choosing variables. vars=('transform.x', 'hp') shares exactly those variables of the object ('transform' means the whole component, a bare name such as 'x' is looked up like obj['x'], and names that are not settings are read as plain attributes). vars={'obj': (...), 'scene': (...)} applies to every layer of that kind below the root and exclude= removes variables the same way. ignore(obj) and filter= keep objects out of the shared scene.
  • Ownership. Each entity has one owner and only the owner's changes are accepted. Roots belong to the host (owner=net.LOCAL or a peer id changes that), objects belong to the node that created them. sync.transfer(obj, peer) hands an object over, and sync.transfer(obj, peer, vars=('physics.xvel',)) hands over single variables, so a client can steer an object the host simulates.
  • Replicas. An object owned by another node is frozen: the local physics and joints skip it and the owner's values are applied instead. Sync(replicas='live') keeps simulating it between updates. When an owner leaves, orphans='drop' removes its objects, 'adopt' gives them to the lowest remaining node id and 'keep' leaves them in place.
  • Reliability. share(..., reliable=False) sends variable changes as latest-wins datagrams and refreshes the full state every Sync(resync=1.0) seconds so lost packets heal. Creating and removing entities is always reliable. Sync(rate=30) limits how often changes are sent.
  • Unshareable values. Values that cannot travel, such as the functions used for light.affect or force.affect, are skipped and listed in sync.skipped. Naming one in vars= raises NetError. Custom components join in with net.register(MyComponent).

Examples

Every example below is a complete program. Press x or close the terminal to exit where an exit key is set.

Move a character with the arrow keys
from ttyengine import start

class main:
    def start(self, scene, session):
        self.hero = scene.obj().create('@', 20, -8)
        session.inp.onpress('x', lambda: setattr(session, 'running', False))

    def update(self, session):
        held = session.inp.held
        t = self.hero.transform
        if held('left'):  t.x -= 1
        if held('right'): t.x += 1
        if held('up'):    t.y += 1
        if held('down'):  t.y -= 1

start(main)
A bouncing ball
from ttyengine import start

def main(scene, session):
    scene.gravity = (0, -1)
    scene.obj().create('O', 20, -1, bounciness=0.8)
    scene.obj().create('#' * 60, 0, -15, dynamic=False)
    session.inp.onpress('x', lambda: setattr(session, 'running', False))

start(main)
Text that follows the mouse

The handler moves the object by the distance between its center and the mouse. Assigning an absolute position would not work here, because center() already includes the object's current position. Pass local=True to center() or extent() to get the values relative to the object's own position instead.

from ttyengine import start

def main(scene, session):
    label = scene.obj().create('hi', 10, -5)

    def follow(x, y):
        t = label.transform
        cx, cy = t.center()
        t.x += x - cx
        t.y += -y - cy        # mouse rows count down, world y counts up

    session.inp.onmouse('move', follow)
    session.inp.onpress('x', lambda: setattr(session, 'running', False))

start(main)
A trigger zone with a sound
from ttyengine import start

class main:
    def start(self, scene, session, sound):
        self.player = scene.obj().create('@', 2, -8, xvel=0)
        zone = scene.obj().create('[ ]', 30, -8, dynamic=False, phantom=True)

        self.player.physics.ontouch(lambda other: sound.beep(660), once=False)
        session.inp.onpress('x', lambda: setattr(session, 'running', False))

    def update(self, session):
        held = session.inp.held
        self.player.physics.xvel = (1 if held('right') else 0) - (1 if held('left') else 0)

start(main)
A styled title that fades out
from ttyengine import start

def main(scene, session):
    title = scene.obj().create(
        session.style('TTY ENGINE', font='slant', color='cyan'), 4, -3)
    title.transform.fade(0, time=3, delay=1, discard=True)

start(main)
A camera that follows the player
from ttyengine import start

class main:
    def start(self, scene, session):
        self.hero = scene.obj().create('@', 0, -8)
        for i in range(0, 400, 20):
            scene.obj().create('|', i, -8)         # markers to show the scrolling
        session.inp.onpress('x', lambda: setattr(session, 'running', False))

    def update(self, session):
        held = session.inp.held
        self.hero.transform.x += (1 if held('right') else 0) - (1 if held('left') else 0)

    def final(self, scene):
        scene.follow(self.hero, smooth=6)

start(main)

Configuration

Session settings

Settings are passed to start(), Session() or run(), and are stored as attributes on the session, so many of them can also be changed while it is running.

Setting Default Meaning
mouse True Report mouse clicks, drags and motion.
vsync True Present each frame as one synchronized update (terminals such as kitty then paint it all at once instead of progressively) and in step with the display's refresh. On Windows the compositor waits for the desktop compositor's vertical blank; on other systems it locks presentation to the detected refresh rate with a fixed-phase clock, since a terminal has no direct access to the display.
refresh None Display refresh rate in Hz (24 to 1000) used by vsync. None detects it, falling back to 60. The TTYENGINE_REFRESH environment variable overrides detection. Setting it also makes Windows use the timer instead of the desktop compositor.
fullscreen auto Use the alternate screen. By default this is chosen from whether the engine draws in the whole terminal or only a region.
hidecursor auto Hide the text cursor while running.
no_color None True strips color codes from all output. Any value other than None overrides the NO_COLOR environment variable.
optimize True Switch the terminal into the modes the engine needs (raw input, hidden cursor, no line wrapping, synchronized output).
pausephysics False Stop physics for every world.
pauserendering False Stop drawing for every world.
region None The part of the terminal the engine draws in: a ttyengine.region preset, (x, y, width, height), a dict such as {"top": 1, "bottom": 1}, or None for the whole terminal. See Regions. termxoffset, termyoffset, termwidth and termheight are older names for its four parts.
autoterm True Keep each scene's canvas size in sync with the region. The size is applied when a world is created and again every frame.
autodim True Keep each scene's view in sync with its canvas, or with the world's own region when it has one. It is applied when a world is created and again every frame.
autobg True Fill the background automatically.
outerbg True Fill the area outside the region with the background color.
autofps True Tie each scene's maximum frame rate to the measured terminal latency.
clearonstop True Clear the screen, or just the region when the engine draws in part of it, when the session stops.

Constructor-only options on Session():

Option Meaning
inp=False Disable the input system (session.inp becomes None).
sound=False Disable audio (session.sound becomes None).
style=False Disable the styling layer.
watchfocus, trackmotion Control whether terminal focus changes and mouse motion are tracked.
ffmpeg Path to an ffmpeg executable for audio and image decoding. It applies even with sound=False.
backend, repeatdelay, repeatrate Which keyboard backend to use and how a held key repeats. See Keyboard and mouse input.
Manual setup

Build the objects yourself when you need Session options such as sound=False, or several sessions and worlds:

from ttyengine import Session

session = Session(sound=False)
world = session.World()
world.launch(main)
session.run()
Error reporting

An uncaught error inside the engine (a handle, a callback or the main loop) restores the terminal, prints the traceback to stderr and exits with code 1. Colors and screen clearing are used only when stderr is a terminal, so redirected output stays plain.

On Windows, a console opened by double-clicking a script closes as soon as the script exits, which hides the traceback. The engine then waits for Enter before exiting. This is detected automatically, and you can override it with the TTYENGINE_HOLD environment variable (auto, always or never).

The same reporting is available for code outside the engine:

from ttyengine import errors

errors.install()

errors.attempt(risky, fatal=False)

errors.install() replaces sys.excepthook so any uncaught exception is printed and, where needed, held open. errors.attempt(func, fatal=False) reports an exception and returns None instead of exiting. Both accept hold=True, hold=False or hold='auto', and attempt also accepts a code for the exit status.

Colors and ANSI wrapping

Set the NO_COLOR environment variable to any non-empty value to strip color codes from everything the engine writes. Attributes such as bold are kept. start(no_color=True), Session(no_color=True) and Compositor(no_color=True) do the same per instance, and any value other than None overrides the environment.

Every ANSI code can be surrounded by a prefix and a suffix, both when the engine writes it and when it reads it from your text. Set them with the TTYENGINE_ANSI_PREFIX and TTYENGINE_ANSI_SUFFIX environment variables (backslash escapes such as \001 are decoded) or in code:

from ttyengine import ansi

ansi.set_wrapper(prefix='\x01', suffix='\x02')

A value of None falls back to its environment variable, and both are empty by default.

Requirements

  • Python 3.8 or newer.
  • Windows, macOS or Linux, in a terminal that supports ANSI escape sequences. Truecolor and the kitty keyboard protocol are used when the terminal offers them.
  • No required packages. The optional keyboard and ffmpeg extras add accurate key tracking, compressed-audio decoding and more image formats.
  • The project is in alpha, so APIs may still change. See the changelog for what changed in each release.

License

TTY Engine is licensed under the Mozilla Public License 2.0. Bundled FIGlet fonts and code are covered by ttyengine/figlet-LICENSE.txt.

Metadata

Release files for ttyengine 0.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ttyengine 0.2.4
File Size Uploaded Provenance Actions
ttyengine-0.2.4.tar.gz 1.9 MB With provenance Details for ttyengine-0.2.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ttyengine 0.2.4
File Interpreter ABI Platform Actions
ttyengine-0.2.4-py3-none-any.whl Python 3 none any Details for ttyengine-0.2.4-py3-none-any.whl

Total release size: 3.8 MB

Release files / ttyengine-0.2.4.tar.gz

Download URL ttyengine-0.2.4.tar.gz
Size 1.9 MB
Tags Source
SHA-256 checksum
How to use checksums
1fc072823d69a06051d858eeb6b1554f2929fc3c9ebf519bb9b83e499b946ef9
BLAKE2b-256 checksum
How to use checksums
d4bf221466356a7b6b205af25117773b603eb27c2879f6e9003880160c04917c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / ttyengine-0.2.4-py3-none-any.whl

Download URL ttyengine-0.2.4-py3-none-any.whl
Size 1.9 MB
Tags Python 3
SHA-256 checksum
How to use checksums
8d3b2fd069860bfdca317830d0efba7c1a7636a2158792194b2be3e7089f693f
BLAKE2b-256 checksum
How to use checksums
64e930e2ad3f2387738de2bd678c28141a5279187a83a788433b46c819c1a875
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Security for ttyengine 0.2.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ttyengine-0.2.4.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page