Reference guide

Start

How a Scena script starts — the import, the window, the game loop — and the rules and words the rest of the Guide uses.

Minimal script / init → Minimal script
Coming from Scratch, Unity or Pygame → From another engine
Rules → Rules
Units, Entity, point, frame… → Vocabulary
PNG / SVG file → Image files
st / canvas / clock… → Global singletons
setup / update / on_key → Script callbacks
Formula, check, event or process? → Which to use

The Guide's examples assume from scena import * and init(…) at the start and run() at the end. from scena import * is the only import: everything the Guide shows comes from it.

From another engine

The Scratch, Unity, Godot or Pygame way, and the Scena way. The idea is the same; the spelling changes.

You would writeIn Scena
“forever” (Scratch), while running: with pygame.event.get()def update(dt): runs every frame; Scena runs the loop. A while inside update freezes the window: use if. A sequence with waits is a task (async def + await wait(1), with run_task)
“wait 1 seconds”, time.sleep(1)after(1, f); in a task, await wait(1). time.sleep stops the whole game
clock.tick(60)Not needed: update(dt) receives the frame's time. The rate is canvas.framerate = 60
Update() / FixedUpdate() in a classon_update(self, dt)
Start() / Awake()setup(self)
Godot: _process(delta), _ready(), queue_free()on_update(self, dt), setup(self), self.destroy(). A child that moves with its parent: child["center"] @= lambda: parent.center + Vec2(20, 0)
OnTriggerEnter2D(other), OnCollisionEnter2D, rect.colliderect(other) every frameon_collide(self, other) in the class, or @collide("hero", "coin"): runs when they start touching. To ask right now: test_collision(a, b)
OnMouseDown(), “when this sprite clicked”on_click(self), or @click(obj). A click anywhere: def on_mouse_click(x, y, button): at the top of the file
Destroy(obj, 0.4), “delete this clone”obj.destroy(); after a while, after(0.4, obj.destroy)
transform.position, transform.rotation.center (move it with move_to / move_by), .angle, .scale
“hide” / “show”, SetActive(false)visible = False / True hides only the drawing (it still collides); active = False stops everything
“glide 1 secs to x: y:”move_to(x, y, time=1) (the time goes by name)
“point towards”obj.rotate_to(heading(obj, target))
“broadcast message” / “when I receive”Call the function. Or count: st.waves += 1 with @on_change(st["waves"]), which compares once per frame (two writes that go back to the old value in the same frame do not fire it)
“create clone of myself”obj.clone(); see what the copy takes along in the clone table
x += vel * dtWorks: obj.move_by(obj.vel.x * dt, obj.vel.y * dt) in update (or on_update). Scena does not move anything by its vel on its own; vel is the velocity that bounce= reads and rewrites
self.vel = 200 (the speed, a number)vel is every object's 2D velocity (self.vel = (200, 0)), the one resolve(…, bounce=) uses; you do the moving, with move_by(vel.x * dt, vel.y * dt). A number of your own needs another name: self.speed = 200
cooldown -= dt … if cooldown <= 0: cooldown = 0.6Works, but it throws away whatever went past zero, and the rhythm changes with the frame rate. @every(0.6) or ready("shot", 0.6) keep the remainder

Minimal script

Every script has three parts. from scena import * and init(…) set up the game's space. The body of the file creates the objects — each constructor already puts its object on the screen. run() opens the window and runs the game, calling update(dt) every frame.

from scena import *
init(width=1200, height=800)

SkyGradient("night")
Stars()
Vignette()
t = Triangle(center=(400, 300), radius=50, color="cyan")

def update(dt):
    t.rotate_by(30 * dt)

run()
init

init(width=2000, height=1200, title="Scena", window_scale=0.8, display="windowed", ui_scale=, ui_font=)

Sets up the design space and the window; it does not open the window (run() does). It already runs on its own at import scena, with the defaults. Call it again right after from scena import * if the script reads canvas.width / .height before run(). run() takes no size.

ParameterPassType (default)Meaning
widthname=number2000Width of the design space (canvas.width). Not the OS window in pixels.
heightname=number1200Height of the design space (canvas.height). y-up, origin at the bottom-left corner.
titlename=str"Scena"The OS window's title.
window_scalename=number0.8Fraction of the largest windowed window that fits the desktop (the design's aspect, decorations on, taskbar visible). 1.0 = as large as the area allows. 0.8 = 80% of that, centered. Startup only: used up when the window opens. There is no canvas.window_scale.
displayname=str"windowed"Shortcut for canvas.display. Only "windowed" · "maximized" · "fullscreen". The windowed window is created first (scale, centered); then it switches to the mode.
ui_scalename=numbercurrentWrites ui.scale. Leaving it out keeps the current value (import default: 1).
ui_fontname=strcurrentWrites ui.font (a family, or a .ttf / .otf file). Leaving it out keeps the current value.

The OS window follows from the design's aspect, the monitor's desktop area, the window's real borders and window_scale. It always starts centered. There is no x= / y= / window_width= in pixels — drag the window if you need a specific spot.

Don't confuse

Looks likeIt isIt is not
init(width=, height=) is the OS window's sizethe design space. The windowed window fits the desktop with the same aspect; window_scale=1 is the largest windowed fit. display="maximized" fills the area (black bars). display="fullscreen" covers the monitor.canvas.window_scale

Rules

Five rules that hold everywhere in Scena.

  1. A constructor places. Circle() shows up right away. So do Rain(), Vignette(), Slider().
  2. Materials and effects only show up applied to an object (or to the background). Gradient, Color, Blur, Neon, Sheet draw nothing on their own: they go in .fill, .visual, set_color, Sprite(sheet) or canvas.background.
  3. = copies now. @= links live. c.radius = 10 · c["radius"] @= lambda: player.hp * 10 — see Reactive.
  4. A property is state. A method is an action. c.visible = False · c.move_by(20, 0)
  5. Sizes in design units, y up, angles in degrees. The origin is the bottom-left corner; 0° points right. See units. Widgets are pinned to the window and ignore the camera.

Each parameter table explains itself: common parameters (layer=, group=, a widget's 1st argument) appear again in every table, so you never have to jump to another section.

Vocabulary

The words the Guide always uses in the same sense. When a section says “units”, “point”, “Graphic” or “frame”, this is what it means.

TermWhat it is
design unit (“units”)The measure of everything in Scena: position, size, radius, thickness, speed (units per second). The space runs from 0 to the width and from 0 to the height given to init: with init(width=2000, height=1200), the center of the screen is (1000, 600). The window scales that whole space to fit the monitor, so 1 unit is not 1 pixel — the game looks the same on any screen. y grows upward; (0, 0) is the bottom-left corner; angles are in degrees, 0 = to the right, counterclockwise.
frameOne turn of the game: read the keyboard and mouse, run update(dt) and the on_updates, move, collide, draw. About 60 per second. dt is how many seconds have passed since the previous frame — multiply speeds by it (200 * dt = 200 units per second).
EntityEvery game object: Shape, Sprite, Text, SpatialFx, widgets and the Entity() with no drawing. Every Entity can have its own fields (ship.hp), timers (after / every), a mode, groups and destroy().
GraphicAn Entity with a drawn body and a pose: Shape, Sprite (and Svg) and Text. Only a Graphic can be clicked or dragged, travel with move_to and have a .box. SpatialFx and widgets are not Graphics.
poseWhere the object is and which way it faces: center, angle, scale and the mirror (flip_x / flip_y). The verbs in Move change the pose; color and visual are not part of it.
ShapeA geometric Graphic: Circle, Rect, Square, Concave, Line, Ellipse, Polygon, RegularPolygon, Triangle, Point, Track.
pointWherever the API asks for a place (move_to, center=, about=, query_point…), any of these works: a tuple (x, y), a Point, a Vec2, a Graphic (its center counts) or mouse. The position is copied at that instant; to follow it, use lambda: (Reactive). More in Points.
field / AttributeA value Scena keeps track of: st.score, ship.hp, c.radius. When it changes, whatever depends on it (an @= formula, an @when, a widget) finds out. Attribute is the name of the class behind it.
link (@=)Make a field follow a formula: c["radius"] @= lambda: ship.hp works it out again whenever ship.hp changes. The opposite of =, which copies the value once.
HandleThe object that verbs which take time return (after, tween, move_to(…, time=) or speed=, play_sound…): use it to cancel, pause or wait for that task. See Handle.
modeThe chapter of behavior an Entity is in right now (e.mode = e.diving). What it starts (timers, movements) stops when it ends. See Mode.
stageThe top of the file: what it creates (objects, timers, sounds, layers) lasts the whole game and works in every act. What an act creates leaves with it. See The stage and the act.
slot (name=)A name that holds a single task: after(2, hint, name="hint") called again with the same name replaces the previous one instead of adding another. A slot belongs to a place: the object of the call (ship.after(…, name=)); for a bare call, whoever is in the running mode (inside a mode's body, an act's mode included); outside a mode (the top of the script, an act's setup, callbacks), the game / the current act. The same name in two places is two slots: a bare play_sound(…, name="music") in an act's setup and another bare one in the act's mode play together. For a single task, always call from the same place — an act's soundtrack with self.play_sound(…, name="music"), which is the same slot as a bare call in the act's mode. A timer or sound of the stage (the top of the script) whose name the act reuses, from any of those places, is paused during the act and comes back after the change: the stage's soundtrack does not play along with the act's. A stage task does not pause: its name in a bare call in the act is an error.
a world with a floorA game with gravity (platformer, runner) writes collision.floor = True: whatever rests on something below stands on it (it doesn't slide down the ramp, it rides along with the elevator). Without that line, the default, no side is special: a game seen from above, in space or without gravity. See A world with a floor.
place × travelPlacing puts the object straight in its spot (center = …, move_to without time=) and goes through walls. Traveling moves it there (move_by, move_to(…, time=) or speed=, move_along), and a resolve() wall stops it midway; the @collide of a fast traveler checks the whole path (Fast objects). Turning in place and scaling (rotate_* / scale_*) are never stopped by a wall: it only pushes the object out afterward. Turning around another point (rotate_by(…, about=)) carries the center along, and that is traveling.
held × on the frame it is pressedkeyp("A") is True on every frame the key is held; keyp.once("A") only on the frame it was pressed. @when fires when the condition turns from False to True, not while it stays True.
channelIn Transients, the place of one kind of effect: a new flash replaces the running flash, but lives alongside a pop.
HUDText and controls pinned to the window (score, lives, menus), on the "ui" layer: they don't move with the camera.

Image files

Where Scena looks for the image files (PNG, JPG, SVG and XML / JSON atlases) you pass by name: next to the script or in its media/ folder.

Sprite, Sheet, Svg, Texture and Wallpaper use the same search. The name is used as given — the framework does not look into subfolders on its own.

  1. An absolute path. Only that file. It exists or it is missing.
  2. The script's folder. Next to the .py you ran.
  3. media/ next to the script. Sprite("ship.png") finds media/ship.png.
  4. The folder you ran Python from. The cwd. Last resort.
Sprite("ship.png")
Sprite("sprites/ship.png")   # media/sprites/ship.png next to the script
Texture("floor.png")
Wallpaper("sky.jpg")

A missing file does not stop the game: a checkerboard shows in place of the image, with a warning, and the object works normally. In the REPL or with python -c, the search starts in the current folder. Atlases: the PNG sits next to the XML / JSON that describes it. A pattern with * (Sheet and strip, File patterns) searches the same folders and uses only the first one that has a matching file.

Global singletons

These objects already exist after from scena import * — you don't build them, you just use them. The classes, functions and effects come with the same import; the search box at the top of the page indexes all of them.

PropertyType (typical value)Read/WriteMeaning
stStateread / writeYour game's values (score, lives, level), tracked by Scena. Keeping values.
canvasCanvasread / writeThe screen: camera, background, full-screen effects, layers. World.
clockClockread / writeGame time: dt, time, pause and slow motion. clock.
keypKeyPressedreadKeyboard: which key is held, which one was just pressed. Keyboard.
mouseMousereadPointer: position in the world, and buttons. Mouse.
audiomixerread / writeSound as a whole: master volume, mute, meters. audio.
uistackread / writeThe widgets' size and font, and the column they stack in. UI.
groupgroupsread / writeFinds objects by tag: group["enemy"]. Groups.
collisionqueriesread / writeCollision questions (what is at this point?) and drawing the colliders. Collision.

Script callbacks

Functions with fixed names that you write in the script and run() calls at the right moment: setup once, when the window opens; update every frame; on_key_down when a key is pressed; and so on. The full table is in Script callbacks.

def setup(canvas):
    canvas.fx_quality = "high"

def update(dt, canvas):
    if keyp("RIGHT"):
        player.move_by(200 * dt, 0)

def on_key_down(key):
    if key == "ESC":
        canvas.reset_view()

def on_mouse_scroll(xoffset, yoffset):
    factor = 1.1 if yoffset > 0 else 1 / 1.1
    canvas.zoom_by(factor, about=(mouse.x, mouse.y))

Each function asks only for the parameters it wants: Scena passes the ones it declares. update(dt) and update(dt, canvas) both work. Catalog: Script callbacks and Entity callbacks.

Which to use

Your code runs in three ways: a formula stays true, a check is made every frame, an event runs once, at one instant. What takes time is a process, and every process has an owner. Choose by what the game needs: none of them is just for beginners, and a big game uses them all.

I wantI use
something to always match something else (the lamp's color)a formula: lambda, @=
to know a state every frame (is the key held?)a check in update or in on_update
to react to an instant (a key, a click, a hit, leaving the screen)an event: on_key_down, on_click, @collide, @leave_playfield
to react when a condition becomes true@when
once, laterafter
again and againevery
a sequence with waits, for what the object is doingan async mode
one more sequence, or one that belongs to no objectrun_task

Check or event. For a state (is the key held?), the check; for an instant (the key just went down), the event. A flash inside if keyp("SPACE") restarts on every frame the key is held.

Processes. after, every, a movement with time=, a sound, a sequence: they all return the same Handle. One thing at the end of a process: then= / on_done=. Two waits or more: an async function — a mode, when it is what the object is doing (one at a time), or a task, when it runs alongside or belongs to no object.

Owner. A process's owner is the place where it started — the game or the act, an object, a mode — and the process ends when its owner ends: changing mode cancels what the old mode started. See scope and cancelling.

Where else to look — Reactive · Draw · Frame · Script callbacks

Draw

The objects that appear on screen: geometric shapes (Shapes), images (Sprite), curves (Track), text (Text) and effects in the world (SpatialFx). Each constructor already puts the object on screen. To lay out a fleet or a grid: Place. To move and animate: Move.

Circle / Rect / Line… → Shapes
Image / atlas → Sprite
Curve → Track
Text → Text
Fire / rain in the world → SpatialFx
Object with no drawing → Entity

Every object on screen

What holds for every object that appears on screen — Shape, Sprite, Text and SpatialFx: hiding, parking, destroying, layer, group and .center. It is written here once; the section for each type does not repeat it.

ship.visible = False
# park: it disappears, timers and collision stop
# (a sound from the ship keeps playing; its on_done waits for the ship to come back)
ship.active = False
# cancels timers/tweens/mode; the Entity stays alive
ship.cancel_process()
# gone for good. is_alive becomes False
ship.destroy()
Constructor (every object on screen)

A name with =: pass it by name. Works on Shape, Sprite and SpatialFx.

ParameterPassType (default)Meaning
layer=name=str, int or None"default"Drawing layer. A number = a position (created on the spot). None = outside the list.
group=name=str or list or NoneA tag, or a list of tags. E.g. group="wasp".
ship = Sprite("ship.png", layer="ui", group=["wasp", "enemy"])
# ship: the variable is how you find this object later.
# layer: drawn on the "ui" layer (outside the world's normal order).
# group: joins group["wasp"] and group["enemy"] at the same time.

There is no id= and no lookup by name: keep the object in a variable. To find it where the variable does not reach (another function, another class), give it a tag and read the group: Sprite("hero.png", group="hero") … group["hero"].first.

On every object on screen

Properties

PropertyType (typical value)Read/WriteMeaning
.centerpoint(400, 300)read / writeThe object's center: the point that move_to puts in place and that it turns around. Every object on screen has one. On a Point, it is the Point itself (p.center is p).
visibleboolFalseread / writeHides the drawing. It stays on its layer.
activeboolFalseread / writeParks: hides, removes collision, pauses timers and on_update. The parts go along: the markers from show_handles() disappear and do not drag until it comes back. Prefer it to destroying and re-creating.
is_aliveboolTruereadTrue until destroy(). if ship: is the same test. Independent of visible. The parts (ship.center, seg.p1) die with it: they can still be read, but changing them raises an error.
.layerstr, int or None"default"read / writeCurrent layer. Write it to change it (a number creates the layer on the spot).
time_scalenumber1read / writeAn extra multiplier on this Entity (timers, tweens, wait, on_update). Default 1. See clock.

Methods

MethodSignatureReturnsMeaning
destroy()No parameters—Takes the object out of the game: it disappears and stops colliding. Cancels its timers, tweens and mode, and the quick effects under way (without calling on_done). On a part (c.center) it raises TypeError: a part lives, parks and dies with its owner.
cancel_process()No parametersselfCancels this Entity's timers / tweens / sounds / mode; it stays alive. Does not fire on_destroy or @exit_mode. See scope.
move_to_front() / move_to_back()No parameters—Drawing order within the layer. top still stays above default. Not on SpatialFx.
tag / untag / taggedParameters: names (names); tagged takes name (name)tag/untag return nothing; tagged returns True/Falsetag puts the object in groups, untag takes it out, tagged("x") says whether it is in group "x". The same names as in collision and group["wasp"]. A part of the shape (c.center, seg.p1, a vertex) has no tags: tag on it raises TypeError — tag the owner.
on_updateParameters: e (object), dt (number)—fn(e, dt) every frame, even during await. See Frame.
on_destroyParameters: e (object)—Once, from inside destroy().
setup(self)Parameters: self (this object)—A method you write in a subclass; Scena calls it right after the constructor. It is not the script's setup(canvas).
clone(center=, scale=, layer=, group=)Parameters: center (point, optional), scale (number), layer (str), group (str or list)the copied objectA copy. center= puts the copy at that point (omitted: where the original is). Runs setup(). No timers / mode / click callbacks. Not on SpatialFx. Clone.
look_like(other)Parameters: other (another object)—Copies another object's look (color, outline, visual, add-ons). Not on SpatialFx.
prepare_fx(*visuals)Parameters: visuals (Visual)—Computes the Sprite's silhouette for those visuals ahead of time (avoids a hitch on the first switch). Does nothing on Shape / Entity.

Don't confuse

Looks likeIt isIt is not
Hiding = removingvisible=False hides, and the object stays. destroy() removes — the Python reference remains, but if ship: becomes false. ship.move_by after that raises DestroyedError (the message says where the destroy() happened). .center still reads.a live object
ship.enabled = FalseAttributeError. Parking is ship.active = False. .enabled exists elsewhere, with another meaning: on a widget, it shows it disabled (dimmed, not responding); on a Post, a background or a sound effect, it turns that effect on and off.the same as .active

Shapes

Shapes are the geometric forms: circle, rectangle, line, ellipse, polygon, point. They appear as soon as they are created; with no arguments (Circle()) they start at a medium size in the middle of the world, (width / 2, height / 2) of init — the middle of the screen while the camera has not moved; after a pan_to or set_origin("center"), pass center=. All of them take color=, visual=, line_width=, layer= and group=.

c = Circle(center=(400, 300), radius=50, color="cyan")
c.set_color("tomato")
c.visual = Neon()
c.show_handles()
Constructor (every Shape)

Every Shape (Circle, Rect, Line, Polygon…) takes these, besides layer= and group= (Every object on screen):

ParameterPassType (default)Meaning
color=name=color"cyan"Paints the inside and an outline in a contrasting tone. On Line, it paints the stroke. Omitted: the default color (set_defaults).
visual=name=VisualNeon()Starts with that visual — the same as c.visual = Neon() afterwards. Use color= or visual=, not both.
line_width=name=number1.5Thickness of the outline (on Line, of the stroke), in design units. Change it later with .line_width.

Defaults for the next shapes

set_defaults(…) chooses the look of the Shapes created after the call — so you do not repeat color= / visual= on each one. Those already created do not change. It lasts until the next call; in an act, an act change goes back to what the top of the file left.

set_defaults(visual=Neon())
set_defaults("coral", line_width=2.0, dash="dot")

set_defaults(visual=None, line_width=, dash=, line_cap=, line_join=, line=, fill=, blend=, line_filter=, fill_filter=)

ParameterPassType (default)Meaning
visual1stcolor, Gradient, Texture or Visual"coral"The basic look: a color ("coral"), a Gradient / Texture or a visual (Neon()).
line_width · dash · line_cap · line_joinname=number / str2.0 / "dot"The outline: thickness, dash pattern, ends and corners — the same values as the properties in Shape reference.
fill · linename=color, Gradient or TextureMaterial of the inside / of the outline, like .fill / .line.
blendname=str"add"How they mix with what is already drawn. See Blend.
fill_filter · line_filtername=filterBlur(sigma=2)Pixel filter on the inside / on the outline. See Filters.
Shape reference

Properties

PropertyType (typical value)Read/WriteMeaning
.colorcolor"cyan"read / writePrimary solid color: the fill on area shapes, the stroke on Line. Writing it calls set_color. It reads the current color: with a visual, that is the color the visual paints now, which may not be the one you gave — a Halo makes the body translucent, lighter or darker (alpha included), so c.color = "red" followed by c.color reads that tone. A visual that paints its own material or its own palette (Flame, Swell, Water, Metal(), Shield()) has no single color: there .color reads the color you gave. To keep your color, store it in a variable or in st.
.visualVisual or NoneNeon()read / writeThe main visual (one per object). None removes the visual; add-ons stay.
.glow / .shadow / .tailbool or color or GlowTrueread / writeAdd-ons. Sprite also has .hue and .gray. Shortcut: True / color / number / object. Reading returns the settings object (Glow, Shadow…) or None.
.fill / .linecolor or GradientGradient("sunset")read / writeThe material of the inside (.fill) or of the outline (.line): a color, a Gradient or a Texture. A Gradient only shows when you put it here. With a visual on, the visual follows the new value (an outline visual follows .line; a body visual, .fill): writing before or after setting the visual gives the same result.
.blendstr"add"read / writeHow fill and line mix with the canvas. Default "normal". With a visual on, it works like .line_width: a visual that fixes its own blend (Halo adds light) keeps it. Blend.
.line_widthnumber1.5read / writeStroke thickness. Default 1.5 (Shape). Also a constructor keyword on the shapes that draw a stroke. Point and Anchor refuse it. It stays writable afterwards. With a visual on, it gives the same as writing it before setting the visual: a visual that uses the thickness (Neon, Laser…) follows the new value; one that fixes its own (Rim, Halo, Shield…) keeps it, and the value shows with visual = None. Text has its own.
.dashstr"dash"read / writeStroke pattern. Default "solid". "solid" · "dash" · "dot" · "dot-dash". With a visual on, like .line_width.
.line_capstr"round"read / writeThe stroke's ends. Default "round" (rounded). "butt": flat, stops at the end point. "square": flat, half the line width past the end point. ("project", the old name of "butt", raises TypeError with the fix.)
.line_joinstr"miter"read / writeThe stroke's corners. Default "miter". "miter" · "bevel" · "round".
.is_collapsedboolFalsereadRead-only. True if the extent has no inside (an axis at 0 / radius=0 / length=0). It is not fill or visible. Silent — no warning. Point / Track / free polygon: always False.

Methods

MethodSignatureReturnsMeaning
set_color(…)Parameters: colors (name, Color or RGB; positional)—Changes the object's color: inside, outline and the visual — the same as color= in the constructor, with or without a visual (the outline is derived from the color, and an outline visual follows that outline). Every visual that takes color= shows the new color: a visual created with a color (Neon("red"), Laser("blue"), Rim("gold")…) starts following the object, Metal() becomes metal of the new color. A visual without color= (Flame, Water, Shield(style="nebula")…) keeps the color and warns: it shows when the visual is removed. The same color forms.
show_handles() / no_handles() / show_points()No parameters—show_handles() shows draggable markers on the points that define the shape (center, ends, vertices), so you can adjust it with the mouse; no_handles() hides them. show_points() shows every point, just to look. The markers go away with the shape on destroy().
clone(center=, scale=, layer=, group=)Parameters: center (point, optional), scale (number), layer (str), group (str or list)the copied objectA free copy (the geometry is copied now, with no links). center= moves the copy to that point (the geometric center lands there, as with move_to); a function raises TypeError (link it afterwards: dup.center @= …). It does not inherit timers or mode. frame= is Sprite-only.
look_like(other)Parameters: other (another object)—Copies another object's look (color, outline, visual, add-ons).
save_visual() / restore_visual()No parameters—Remembers the current look (add-ons included) and goes back to it later (it keeps a single look). A second save_visual does nothing until restore_visual. Different from .visual = None (removes the visual; add-ons stay).

An incomplete construction model (Circle(p1=…) without p2) raises ValueError. It does not fall back to the default.

A filled circle — or a slice of one, with angle= / spread=. Circle() already appears in the middle. Also Circle.from_points, Circle.from_corners and tangent_lines_from.

c = Circle(center=(400, 300), radius=50, color="cyan")
c = Circle(center=(400, 300), radius=50)
Circle(p1=(100, 200), p2=(300, 200))   # diameter
p = c.point_at_angle(45)               # throwaway Point on the edge
dots = Track(c).spaced_points(8)       # 8 (x, y) tuples on the outline
c = Circle(center=(400, 300), radius=50, color="cyan")
c.set_color("tomato")
c.visual = Neon()
c.move_by(200 * dt, 0)
c.move_by(angle=90, distance=40)
c.move_by(distance=120 * dt)
c.rotate_by(30 * dt)
Constructor

Circle(center=, radius=, color=, layer=, group=)

A name with =: pass it by name. (Circle has no argument passed by position only.)

ParameterPassType (default)Meaning
centername=pointdesign centerA point (x, y). E.g. center=(400, 300).
radiusname=numbermedium sizeRadius in design units. E.g. radius=50.
boxname=Box or formulacellA region (Box): the circle fits inside it, with radius = half the shorter side. With radius=, it only centers on it. With a formula (box=lambda: …), it follows the region. box=.
colorname=colorgame defaultFill + contrasting stroke. E.g. color="cyan".
layername=str or None"default"Drawing layer
groupname=str or list or NoneA tag, or a list of tags
Construction models
CallMeaning
Circle()Design center, medium size
center=, radius=The usual way
center=, perimeter_point=Radius up to that point
p1=, p2=Diameter
angle=, spread=Arc: direction and opening, in degrees; the same as query_sector. spread=360 is the whole circle. Either one works on its own. With perimeter_point= or p1=, p2=, angle= turns the edge to that direction.
use_centerDefault True: a pie slice. False: a segment (chord + arc). Clicks and collision follow that area; spread=360 stays the disc.
box=Inscribes. See Place
Circle reference

Properties

PropertyType (typical value)Read/WriteMeaning
.center .radiuspoint or number(400, 300)read / writeGeometry. Read and write it.
.angle .spreadnumber0 / 360read / writeArc, in degrees. .angle is the direction (0 = +x). .spread is the whole opening (60 = ±30). On a circle placed by its edge (perimeter_point= or p1=, p2=), .angle is the direction to .p1: the arc opens toward that point, and writing .angle turns the edge around the center.
.p1 .p2point(0, 0)read / writeEnds of the diameter. .p1 is the .perimeter_point and lies in the .angle direction (in the center=, radius= model): it turns with rotate_by and mirrors with the flip. circle.box.right_center is circle.p1.
.visualVisual or NoneNeon()read / writeMain visual. Neon(), Halo(), … (not Glow — use .glow).
.glow / .shadow / .tailbool or color or GlowTrueread / writeAdd-ons. See Add-ons.

Methods

MethodSignatureReturnsMeaning
set_color(…)Parameters: colors (name, Color or RGB; positional)—Recolors. It also recolors a visual created with a color (Neon("red"), Laser("blue")…: it starts following the object) and a Metal / Shield() (with or without a color).
point_at_angle(angle)Parameters: angle (angle, degrees)PointA point on the circumference. 0 = +x, counterclockwise. A throwaway result (it does not join the game). For N evenly spaced points: Track(c).spaced_points(n).

Don't confuse

Looks likeIt isIt is not
A Circle with an imageAn image does not go into a Circle. Use Sprite, or c.fill = Texture("…").—
A Circle's arc is only drawingClicks and collision follow the painted slice (pie or segment). spread=360 is the disc. intersections still uses the circumference. A curved wall: Track.arc.—

A rectangle, which can turn (angle=) and have rounded corners (corner_radius=). You place it by its center, by one corner or by two opposite corners. Rect() appears in the middle, at a medium size. rect.corners returns the four corners.

Rect()
Rect(center=(400, 300), width=120, height=60, color="navy")
Rect(top_left=(80, 200), width=160, height=80)
Rect(center=(400, 200), width=140, height=70, corner_radius=16)
Rect(p1=(100, 300), p2=(300, 300), height=40, anchor="square")
Constructor

Rect(center=, width=, height=, angle=, corner_radius=, color=, layer=, group=)

A name with =: pass it by name.

ParameterPassType (default)Meaning
centername=pointdesign centerPoint
width / heightname=numbermedium sizeSides
boxname=Box or formulacellA region (Box): the rectangle fills the whole region (its place, size and angle). With a formula (box=lambda: …), it follows the region. box=.
anglename=number0Degrees, counterclockwise
corner_radiusname=number0Rounded corners (design units), a plain number only. Clicks follow the fill; collision stays the rectangle.
colorname=colorgame defaultFill
Construction models
CallMeaning
Rect()Design center, medium size
center=, width=, height=The usual way
top_left=, width=, height=Corner + size
p1=, p2=Opposite corners, exactly where you put them (a value or a lambda). angle= tilts the box between them — the width and height follow; it does not turn a rectangle of fixed size. The corner names (bottom_left…) are given the first time you read a corner; so link p1 / p2 with @= before reading the corners.
p1=, vec=A pinned corner + a local extent (width, height), signed, along the already-turned sides. It is not a world delta (that is Line(p1=, vec=))
p1=, p2=, height=, anchor=Axis p1→p2 + thickness; see the anchors below
box=Fills. See Place
Rect reference
PropertyType (typical value)Read/WriteMeaning
.center .width .height .anglepoint or number(400, 300)read / writeGeometry
.corner_radiusnumber8read / writeRounded corners, a plain number only (it does not link). Clicks follow the fill; collision stays the rectangle. Default 0.
.top_left .top_right .bottom_left .bottom_rightpoint(80, 200)read / writeCorners, in the box's frame. They get their names on first use (as they appear then); after that each name follows its point — when dragged, linked with @=, turned or mirrored. The screen edges: rect.box.top / .right.
.top_center .bottom_center .left_center .right_centerpoint(400, 240)readMidpoints of the sides (anchor="cap" uses left_center/right_center)
.left_square_center .right_square_centerpoint(120, 300)readCenters of the squares of side height at the ends (anchor="square")
.boxBoxpanel.boxreadA copy of the frame, taken now, with the names: rect.box.top_right is rect.top_right. Layout: panel.box.inset(8).grid(8, 8) — Place.

Don't confuse

Looks likeIt isIt is not
corner_radius changes the collisionClicks follow the rounded corner. Collision stays the rectangle. Linked corners stay alive. corner_radius is a plain number — a function raises an error.—
angle= with p1=, p2= turns the boxangle= tilts the box with the corners pinned and changes its size. To turn a rectangle of fixed size, use center= + angle=, or rotate_by.—
.top_right is always the top-right cornerIt is the corner that was there on first use, and the name follows that point. Drag p1 past p2 and top_right is still p2, even at the bottom left — whatever is linked to top_right never jumps to another point. The .box keeps the same names. For the screen, use the edges: rect.box.top / .right.A name recomputed every frame
flip_x on a Rect turns the boxIt mirrors: each named point goes to its mirror image around the center (top_left ends up where top_right was). The box does not move.A half turn

Writing a derived point. The midpoints of the sides (.top_center, .left_center…) and the centers of the end squares are read-only: to change them, change width / height / center. To move the rectangle until one of them sits at a given place: r.move_to(1, 2, about=r.top_center).

p1=, p2=, height=, anchor=. The orientation comes from p1→p2; height is the thickness (≥ 0); .width becomes the length along the axis. anchor is required: "cap" (midpoints of the short walls = .left_center/.right_center), "square" (centers of the squares of side height = .left_square_center/.right_square_center), "side_left" / "side_right" (corners of a long side; the box sits to the left or to the right of p1→p2). These derived points exist in every model, not only in the p1=, p2=, height=, anchor= model.

A square: a Rect with equal sides. The size is length=; width / height only read that value.

Square()
Square(center=(400, 300), length=80, color="gold")
Square(top_left=(100, 200), length=60)
Square(center=(400, 200), length=70, corner_radius=12)
Constructor

Square(center=, length=, angle=, corner_radius=, color=, layer=, group=)

A name with =: pass it by name.

ParameterPassType (default)Meaning
centername=pointdesign centerPoint
lengthname=numbermedium sizeLength of the side, in design units.
top_leftname=point(100, 200)Places the square by its top-left corner, instead of center=.
boxname=Box or formulacellInscribes (shorter side). With length=: only centers. With a formula (box=lambda: …), it follows the region. box=.
anglename=number0Degrees
corner_radiusname=number0Rounded corners. Clicks follow the fill; collision stays the square. Inherited from Rect.
Square reference
PropertyType (typical value)Read/WriteMeaning
.lengthnumber80read / writeSide. Write it here.
.width / .heightnumber120readMirrors of the side. Writing them raises an error.
.corner_radiusnumber8read / writeRounded corners. Clicks follow the fill; collision stays the square.

Do not assign width / height on a Square.

A straight segment between two ends (p1, p2) — or defined by center, length and heading. It has a stroke only: color= / set_color paint the line, and line_width is its thickness.

Line()
Line(center=(240, 160), length=200, angle=30, color="cyan")
Line(p1=(80, 80), p2=(400, 240), color="cyan", line_width=5)
ln.visual = Laser()
Constructor

Line(center=, length=, angle=, color=, line_width=, layer=, group=)

A name with =: pass it by name. Or the way with ends: p1=, p2=.

ParameterPassType (default)Meaning
centername=pointdesign centerMiddle of the segment
length / anglename=numbermedium size / 0A pair: length and degrees
p1 / p2name=pointEnds (the full way)
colorname=colorgame defaultStroke
line_widthname=number1.5Stroke thickness. Omitted, it stays 1.5.
Construction models
CallMeaning
Line() / center=Horizontal in the middle, medium size
length=, angle=Size + orientation at the design center
center=, length=, angle=Center, length and heading
p1=, p2=Ends (both required)
p1=, angle=, length=Polar, from one end
p1=, vec= / p1=, dx=, dy=Vector
p1=, parallel_to=, length=Parallel to another Line
dist=, parallel_to=A parallel copy offset by dist (positive = to the left of the p1 → p2 direction)
p1=, perpendicular_to=, length=Perpendicular to another Line, starting at p1 (to the left of that Line's direction)
circle=, at_angle=, length=Tangent: at_angle is the position on the circle; the heading angle is at_angle + 90
circle=, from_point=, side=A tangent from a point outside until it touches the circle. side="left" / "right" picks which of the two
Line reference
PropertyType (typical value)Read/WriteMeaning
.p1 .p2 .length .anglepoint or number(0, 0)read / writeGeometry
.centerpoint(400, 300)read / writeMiddle of the segment

Don't confuse

Looks likeIt isIt is not
Line(width=…)The length is length=, not width=. The stroke thickness is line_width.—
An area visual (Neon, Gel…) on a LineAn area visual on a Line vanishes into the stroke. Prefer Laser / set_color.—

An ellipse (an oval), with width, height and rotation. It can start inscribed in a Rect and follow it: from_rect=.

Ellipse()
Ellipse(center=(400, 300), width=140, height=70)
Ellipse(from_rect=box, padding=8)
Constructor

Ellipse(center=, width=, height=, angle=, color=, layer=, group=)

A name with =: pass it by name.

ParameterPassType (default)Meaning
centername=pointdesign centerPoint
width / heightname=numbermedium sizeTotal width and height (the whole axes, not half of them), before rotation.
boxname=Box or formulacellFills the region once (from_rect= follows a Rect). With a formula (box=lambda: …), it follows the region. box=.
from_rect / paddingname=Rect / number— / 0The ellipse sits inscribed in the Rect and follows it live (moving or turning the Rect moves the ellipse). padding= shrinks that box on each side: a 100 × 50 Rect with padding=8 gives an 84 × 34 ellipse.
anglename=number0Degrees
Construction models
CallMeaning
Ellipse()Design center, medium size
center=, width=, height=The usual way
fp1=, fp2=, major_axis=Foci + major axis. All three take a lambda. A number that is too small raises an error; a formula that shrinks the axis flattens the ellipse onto the segment between the foci
from_rect=, padding=Pose linked to a Rect
box=Fills a Box (once). See Place

Don't confuse

Looks likeIt isIt is not
Ellipse(from_rect=…) copies the Rectfrom_rect= links the pose to the Rect. Moving the Rect moves the ellipse.—

A polygon with the vertices you give in points= (the number of vertices does not change later). With no points: a medium quadrilateral in the middle. signed_area and perimeter_length read the area and the perimeter.

Polygon()
Polygon(points=[(100, 80), (220, 90), (200, 180), (90, 160)], color="coral")
Polygon(points=[(0, 0), (80, 0), (40, 60)], visual=Neon())
Constructor

Polygon(points=, color=, visual=, layer=, group=)

A name with =: pass it by name. Use color= or visual=, not both.

ParameterPassType (default)Meaning
pointsname=listmedium quadrilateralA list of (x, y), one per vertex. The number of vertices is fixed once it is created. E.g. points=[(0, 0), (40, 10), (20, 50)].
colorname=colorgame defaultFill + contrasting stroke. E.g. color="coral".
visualname=VisualNeon()A visual in the constructor (instead of color=).
layername=str or None"default"Drawing layer
groupname=str or list or NoneA tag, or a list of tags
Polygon reference
PropertyType (typical value)Read/WriteMeaning
.pointslist[(0, 0), (40, 10), (20, 50)]readVertices (a Point each; how many is fixed). To link a vertex: tri.points[1] @= lambda: a.center. To move one: tri.points[1].move_to(x, y). tri.points[1] = … and tri["points"] @= … raise an error that shows these forms.
.centerpoint(400, 300)readThe polygon's center: the average of the vertices. Read-only; to move it, use move_to / move_by.

Don't confuse

Looks likeIt isIt is not
Changing the number of vertices laterThe number of vertices does not change later. For a regular N-gon, use RegularPolygon.—

A polygon with equal sides — pentagon, hexagon… n= is the number of sides (default 6) and does not change later.

RegularPolygon()
RegularPolygon(n=5, center=(400, 300), radius=50, color="cyan")
Constructor

RegularPolygon(n=, center=, radius=, angle=, color=, layer=, group=)

A name with =: pass it by name.

ParameterPassType (default)Meaning
nname=integer6Number of sides, ≥ 3. Fixed once it is created.
centername=pointdesign centerPoint
radiusname=numbermedium sizeCircumradius (center → vertex)
anglename=number0Heading, in degrees, from the center to the first vertex (0 = a vertex pointing right).
boxname=Box or formulacellInscribes (circumradius = half the shorter side). With a formula (box=lambda: …), it follows the region. box=.
Construction models
CallMeaning
n=, center=, radius=Circumradius
n=, center=, side=Side length
n=, vertex=, side=Places the polygon by its first vertex (vertex=), instead of the center, with sides of length side=.
box=Inscribes. See Place

Don't confuse

Looks likeIt isIt is not
flip_x renumbers the verticesIt mirrors in place: each points[k] goes to the mirror image of the old points[k], and the list now runs clockwise (signed_area turns negative, as on a mirrored free Polygon). Whatever is linked to hexagon.points[2] does not jump to another vertex.Renumbering

n= does not change later. A triangle (isosceles too): Triangle.

An isosceles triangle: two equal sides (side) and the base, opposite the apex, base_ratio times that length. Without base_ratio it is equilateral (three equal sides). angle is where the tip (the apex) points, as with every heading: 0 to the right, 90 straight up. Good for ships and arrows: you can see it turn.

Triangle()
Triangle(center=(400, 300), radius=50, color="cyan")
ship = Triangle(center=(400, 300), radius=30, angle=90, base_ratio=0.6)
t.rotate_by(30 * dt)
Constructor

Triangle(center=, radius=, angle=, base_ratio=, color=, layer=, group=)

A name with =: pass it by name.

ParameterPassType (default)Meaning
centername=pointdesign centerPoint
radiusname=numbermedium sizeDistance from the center to the apex. The center is the centroid (the balance point). On the equilateral triangle, it is the circumradius.
sidename=number60Or the size by the two equal sides, instead of radius=.
vertexname=point(0, 0)With side=: places the triangle by its apex instead of its center.
base_rationame=number1The base divided by side, between 0 and 2 (outside that, ValueError). 1 is equilateral; smaller is pointier, larger is wider. Changing it later keeps what placed the triangle: with radius, the center and the apex; with side, the equal sides. It links with @= and animates with tween.
boxname=Box or formulacellFills the box, with its angle: the apex at the middle of the right side, the base is the box's height (the base_ratio comes from the box). With base_ratio=: the largest triangle with that ratio that fits, centered. With radius= / side=: only centers. With a formula (box=lambda: …), it follows the region. box=.
anglename=number0Where the apex points: 0 → right, 90 → straight up. face=True flies apex first.

Do not pass n=: it is always 3 (TypeError). Three free corners: Polygon(points=[…]). EquilateralTriangle became Triangle in 0.9.0 (the old name raises TypeError with the fix).

A box with a scoop (scoop): a piece of a circle or of an ellipse cut out of it. A quarter-pipe, the curved corner of a pinball table, the inside curve of a track, a half-pipe. You place it like a Rect (every model, the named points, angle); the curve comes from the box.

Concave()
ramp = Concave(top_left=(0, 200), width=200, height=200)           # quarter-pipe
nook = Concave(top_left=(0, 600), width=80, height=80, scoop="bottom_right")
halfpipe = Concave(center=(400, 100), width=400, height=250,
                   scoop="top_center", rim=(0, 50))                # a floor of 50
deck = Concave(top_left=(0, 200), width=200, height=200, rim=(20, 0))
Constructor

Concave(center=, width=, height=, angle=, scoop=, rim=, color=, layer=, group=)

A name with =: pass it by name. The models are the Rect ones.

ParameterPassType (default)Meaning
centername=pointdesign centerPoint
width / heightname=numbermedium sizeSides of the box. The curve reaches the far sides: a square box gives a quarter circle; another ratio, a quarter ellipse.
scoopname=text"top_left"The named point where the center of the curve sits. A corner ("top_left", "top_right", "bottom_left", "bottom_right") cuts out a quarter; the midpoint of a side ("top_center", "bottom_center", "left_center", "right_center") cuts out half an ellipse — a semicircle when the box is 2:1. Locked at construction.
rimname=number or pair0The solid left at the ends of the curve, along the width and the height: rim=0 leaves the ends knife-thin; rim=(20, 0) gives the quarter-pipe a deck of 20 at the top and no step at the floor. The curve's radius on each axis is the box's reach minus the rim. ≥ 0 (negative: ValueError). It links with @=; scale_by scales it.
boxname=Box or formulacellFills the region, like Rect. With a formula (box=lambda: …), it follows the region. box=.
anglename=number0Degrees, counterclockwise
Construction models
CallMeaning
Concave()Design center, medium size, scoop at top_left
center=, width=, height=The usual way
top_left=, width=, height=Corner + size
p1=, p2=Opposite corners, as on the Rect. The scoop stays at its named point even if p1 goes past p2.
p1=, vec=A pinned corner + a local extent (width, height)
p1=, p2=, height=, anchor=Axis p1→p2 + thickness; the anchors of the Rect
box=Fills. See Place
Concave reference
PropertyType (typical value)Read/WriteMeaning
.center .width .height .anglepoint or number(400, 300)read / writeThe box, as on Rect. The corners and side midpoints (.top_left, .top_center…) are the box's — the scoop one is the center of the curve, outside the solid.
.scooptext"top_left"readWhere the curve is. Writing it raises an error (make another Concave). flip_x / flip_y mirror the shape: the name follows its point.
.rimVec2Vec2(20, 0)read / writeTakes a number (both axes) or a pair; c.rim.x is one axis. It links with c.rim @= lambda: ….
.boxBoxramp.boxreadThe frame of the box, with the names.

Don't confuse

Looks likeIt isIt is not
A Concave is a RectIt uses the same frame, but it does not collide as a box: it is solid up to the curve. isinstance(c, Rect) is False. Rounded (convex) corners are Rect(corner_radius=); Concave has no corner_radius.—
Collision follows the drawn curveAlmost: the curve is drawn as a true arc and collides as chords at most 0.25 units from it (like the Circle pie slice). The chord ends lie on the curve: a ball stops up to 0.25 short of the drawn curve, never past it. Clicks (contains_point) follow the exact curve; a point right on the curve counts as inside. A ball rolls up the ramp and comes back.A box
scoop changes laterIt is locked at construction, like RegularPolygon's n. To mirror it: flip_x / flip_y. The rim changes freely.—

A Point is an (x, y) position that lives in the game: it can be linked, dragged and used by other objects (the end of a Line, the center of a Circle). Invisible by default; color= shows it as a marker and handle=True makes it draggable (both move it to the top layer).

p = Point(200, 150)
p = Point(200, 150, color="cyan")   # visible guide (not draggable)
p = Point(canvas.game_view.center)  # a copy of the view's center
p.visible = True
p.handle = True
# visible + draggable Point on top
a = Anchor(400, 300)
b = Anchor(500, 300, color="lime")
Constructor

Point(x, y, color=, visible=, layer=, group=) · Point(point, …) · Point(lambda: …) · Anchor(x, y, color=, group=)

A name without =: 1st, 2nd in order; or a single point / lambda. No visual= (a marker, not a visual).

ParameterPassType (default)Meaning
x1stnumber0Position. Only x → y=0.
y2ndnumber0Position
point1st (alone)pointbox.centerA copy: Point, Vec2, (x, y), Graphic (its center), mouse. A callable → a link of the whole Point (like center=).
colorname=color—Paints the marker and shows it as a guide (visible, not draggable). With color=, the marker uses that color instead of the automatic one. With visible=False: it only paints, and stays hidden.
visiblename=boolFalseShows / hides. True shows the Point (on the "top" layer if there is no layer=). It wins over the effect of color=.
layername=str or NoneNoneLayer. Omitted = outside the drawing list until shown.
groupname=str or list or NoneA tag, or a list of tags
Point reference

Properties

PropertyType (typical value)Read/WriteMeaning
.x .ynumber400read / writeCoordinates
x, y = ptwo numbersx, y = ship.centerreadUnpacks the current coordinates (like tuple(p)): a copy, the names do not follow the point. Works for Vec2 and mouse. p[0] raises TypeError: use p.x. Passing the Point itself works as before (a copy in center=, a link in @= / lambda).
.centerpointpreadThe Point itself (p.center is p): it exists so that every object has a .center, like Circle and Sprite. To move it, write .x / .y or use move_to.
.visibleboolFalseread / writeA guide on screen. No handle.
.handleboolTrueread / writeTrue: the Point appears and can be dragged with the mouse. On a Point linked with @=, it raises LinkedAttributeError.

Methods

MethodSignatureReturnsMeaning
.distance(other)Parameters: other (point)numberEuclidean distance. Also distance(p1, p2).
.heading(other)Parameters: other (point)numberHeading to other, in degrees (0 = +x, −180…180). Also heading(p1, p2).
set_color(…)Parameters: colors (name, Color or RGB; positional)selfRecolors the marker (the inside only). After that, it no longer uses the automatic color of a guide / draggable marker.
Point.temp(x, y)Parameters: x (number), y (number)PointThrowaway. It does not join the game.

== on a Point compares the object, not the position. elevator.center == (400, 120) is always False, even with the elevator there; the same goes for a Vec2 and for another Point at the same place. Scena warns in the console (a Python warning pointing at your line). To test the position: distance(elevator.center, (400, 120)) == 0 (or < 1 if the movement does not land exactly). To know whether it is the same object: a is b.

Anchor

A shortcut: a Point that is visible and draggable on top, always: a.draggable = False (or handle = False) raises TypeError — for a point the mouse does not move, use Point(x, y, visible=True). No incoming link: a["field"] @= … raises LinkedAttributeError. It takes the same points as Point(point) (a copy). color= paints the marker (omitted: automatic red).

a = Anchor(400, 300)
a = Anchor(400, 300, color="cyan")
a = Anchor(canvas.game_view.center)
b = Anchor(600, 300)
Line(p1=lambda: a.center, p2=lambda: b.center)   # follows the drag

Linking to an Anchor takes a lambda. Line(p1=a.center, …) (or p1=a) copies the position once: the line stays where it started when the Anchor is dragged. To follow it: p1=lambda: a.center (Formulas in constructors).

ParameterPassType (default)Meaning
x, y / pointby positionnumber or pointThe same as Point (a copy; no formula).
colorname=colorred (auto)Marker color. Omitted: the automatic color of draggable markers.
groupname=str or listTag(s)

Don't confuse

Looks likeIt isIt is not
Point(canvas.game_view.center) follows the viewIt copies the position once (game_view is a new Box on every read). To follow it: Point(lambda: canvas.game_view.center) or @=. A single lambda links the whole Point; for one axis only: Point(lambda: mouse.x, 0).a link
Point(…, color=…) can be draggedcolor= only shows the marker. To drag: p.handle = True or Anchor(…). All of a shape's points: shape.show_handles().handle
p.handle()handle is a property: p.handle = True.a method
x, y = ship.center follows the shipTwo numbers from now (a copy). To follow it, read ship.center.x where you need it or link with @= / lambda.a link

Sprite

A Sprite is an image on the screen — a still PNG or an animation. The Sprite is the object (position, size, rotation, collision); the Sheet is the catalog of frames and animations (clips) it takes its image from, and a Sheet never appears on its own. A still PNG needs no Sheet. Here “frame” also means each frame of the animation (frame= picks one); “every frame” still means each pass of the game loop.

# A still PNG: no Sheet.
potion = Sprite("potion.png", height=48, center=(200, 300))

# A PNG laid out as a grid, with one animation: fps= on the Sheet registers the clip, and the Sprite plays it right away.
snail = Sheet("snail.png", cols=8, fps=6)
Sprite(snail, height=36, center=(400, 300))

# Several clips: the Sheet names them, the Sprite picks one with play.
hero_sheet = Sheet("hero.png", cols=4, rows=3)
hero_sheet.clip("walk", [3, 4, 5, 6], fps=12)
hero_sheet.clip("jump", [7, 8, 9], fps=10)
hero = Sprite(hero_sheet, height=64, center=(600, 300))
hero.play("walk")

# One PNG per frame: a * where the name changes picks them all,
# in order (Idle__000.png, Idle__001.png, …).
ninja = Sheet(anchor="bottom", pixel_size=0.16)
ninja.strip("idle", "ninja/Idle__*.png", fps=8)
ninja.strip("running", "ninja/Run__*.png", fps=12)
fighter = Sprite(ninja, center=(800, 300))
fighter.play("running")
TypeRoleGoes into the game?
SheetCatalog: the pixels, how to cut them (grid, atlas, several files) and the named clips (clip, strip).No. It goes in Sprite(sheet). One Sheet serves many Sprites.
SpriteThe object on the screen: position, size, which frame / clip plays (play), facing and collision (hitbox).Yes, in the constructor. File: lookup. Missing: a checkerboard + a warning, and the Sprite carries on.

I have these files → Loading sprites
Clips, play, different sizes per clip → Animating sprites
Turn, aim, flip, tilt on a ramp → Facing sprites
Collider shape, hurtbox, weak spot → Sprite hitbox
Clone, class with defaults, Svg, appearance, click → More Sprite features

Sprite constructor

Sprite(source, height=, width=, size=, center=, box=, frame=, offset=, hitbox_shape=, hitbox_source=, hitbox_anchor=, hitbox_scale=, flip_x=, flip_y=, art_angle=, angle=, visual=, shield_scale=, group=, layer=)

Name without =: 1st, in order: the file of a still image (PNG) or a Sheet. Name with =: by name. Catalog settings (cols= / atlas= / fps= / name= / yoyo=) belong on the Sheet — on the Sprite they are a TypeError.

ParameterPassType (default)Meaning
source1ststr or SheetA PNG (still image) or a Sheet. Lookup: Image files. E.g. Sprite("ship.png"). Several files: Sheet("a.png", "b.png"), then Sprite(sheet). A pattern with * is a TypeError (it means several frames): Sprite(Sheet("robot/Run (*).png", fps=12)).
height / width / sizename=numberPNG sizeDesign units, not pixels. size = the longer side. It measures the constructor frame (frame=; without it, the first frame of the first clip) and sets the Sprite's scale. With none of them, the Sheet's pixel_size applies (if it has one). See Different sizes.
centername=pointdesign center(x, y). It is the frame's pivot (with Sheet(anchor="bottom"), the feet).
boxname=Box or formulacellFits (keeping the PNG's aspect), or only centers if height= / width= / size= is given. Do not mix it with center=. With a formula (box=lambda: …), it follows the region: it grows through scale. box=.
framename=integer or str0The cell shown still: an index, or a name in the atlas. When the Sheet has a clip, an explicit frame= wins over autoplay.
offsetname=pair of numbers(0, 0)Shifts the drawing and the collider relative to center, in design units. It turns with the Sprite and mirrors with the flip. E.g. offset=(10, 0). Per clip, in art pixels: clip(offset=).
hitbox_shape / hitbox_source / hitbox_anchor / hitbox_scalename=str, number, tuple or pair"auto"The main hitbox: which shape, from which art, which point stays put, how much it shrinks. Later: sprite.hitbox.shape / .source / .anchor / .scale. See Sprite hitbox.
flip_x / flip_y / art_anglename=bool / numberFalse / 0Mirroring, and “which way the PNG points”. See Facing sprites.
anglename=numberrest_headingStarting heading in the world, in degrees. Omitted: the PNG appears as it was drawn. See Facing sprites.
visual / shield_scalename=Visual / numberNone / 1.4A Visual in the constructor. shield_scale is the size of the Shield around the silhouette. See Appearance and clicks.
group / layername=str—The same as in Every object on screen.
Sprite reference

Properties — image and size

PropertyType (typical value)Read/WriteMeaning
frameinteger or str0read / writeCurrent cell. An index, or a name in the atlas. Writing a value stops the animation and shows that cell.
sheetSheetreadThis Sprite's catalog. Changes (clip / strip) are made on the Sheet, before you place the fleet — not through the shared catalog of Sprite("x.png").
width / height / sizenumber64read / writeSize of the current frame, in design units. play / frame= change what you read when the new frame has another size. Writing rescales every clip.
offsetpair(10, 0)read / writeShift of the drawing and the collider relative to center, in design units.
.boxBoxship.boxreadThe whole drawn cell (with the PNG's transparent margin), where it is drawn: pivot, offset, flip and scale all count. By the names: after a flip_x, box.top_center is still above the head. Higher on the screen: box.top. Measure.
.art_boxBoxship.art_boxreadOnly the frame's visible pixels on the screen (without the margin). It moves with the animation. Measure.
.is_collapsedboolFalsereadTrue if the drawn frame has no inside (w or h is zero, scale included). The constructor rejects a size ≤ 0; collapsing later is allowed and silent.

Properties — facing

PropertyType (typical value)Read/WriteMeaning
flip_x / flip_yboolTrueread / writeMirrors the drawing and the collider. Rewrites .angle. Flip.
art_anglenumber90read / writeWhere the PNG's nose points, in degrees (0 = +x, 90 = +y), before the flip. Aim.
rest_headingnumber90readThe heading at which the PNG appears as drawn: art_angle after the flip. reset_rotation() comes back here.
tiltnumber · contact · "ground""ground"read / writeTilts only the drawing, around hitbox.anchor. It does not turn the body. Tilt.

Properties — collision

PropertyType (typical value)Read/WriteMeaning
hitboxHitboxhero.hitboxreadThe main hitbox (stands, hits, resolve): .shape / .source / .anchor / .scale (writing them during the game works), .active, .box. Hitbox.
hitboxestuple of Hitboxhero.hitboxesreadAll of them: the main one first, then the extra ones from add_hitbox.

Properties — appearance

PropertyType (typical value)Read/WriteMeaning
.visualVisual or NoneHalo()read / writeMain Visual. None removes the Visual; add-ons stay.
.alphanumber0.5read / writeOpacity of the body, 0–1. It applies only to the image: Visuals that wrap the Sprite (Shield, Electric…) keep their own opacity.
.blendstr"add"read / writeHow the image mixes with what is already drawn. The same names as Shape. Default "normal". Blend.
.glow / .shadow / .hue / .gray / .tailbool or color or GlowTrueread / writeAdd-ons. .gray removes the color (0–1). See Add-ons.
shield_scalenumber1.4read / writeSize of the Shield oval relative to the silhouette.

Methods

MethodSignatureReturnsMeaning
play(clip, loops=, next=, min_hold=, resume=)Parameters: clip (str), loops (number), next (str), min_hold (number), resume (True/False)selfPlays a clip from the Sheet. A visual, not a mode. Full table just below.
add_hitbox(group=, shape=, source=, anchor=, scale=, active=, px_rect=, px_circle=)Parameters: group (str or list), shape (str), source (default "each"), anchor, scale, active (True/False), px_rect (x, y, w, h), px_circle (x, y, r)HitboxAn extra hitbox, detection only. px_rect / px_circle: a shape by hand, instead of the four art parameters. Parts, Attack boxes.
showing(frames)Parameters: frames (clip name, index, frame name, or tuple / list)boolIs the frame on the screen one of these? It goes by the frame (right with yoyo, next=, an interrupted attack). Attack boxes.
remove_hitbox(part)Parameters: part (Hitbox)selfRemoves the extra hitbox. The Sprite leaves the groups that hitbox put it in; a group it was already in on its own stays. The main hitbox does not come off: sprite.hitbox.active = False.
reset_rotation()Optional: time, ease, then, on_done—Turns to rest_heading and sets tilt to zero. It does not clear the flip.
clone(center=, layer=, group=, frame=, scale=)Parameters: center (point), layer (str), group (str or list), frame (number), scale (number)the copied objectA new Sprite with this one's appearance. Clone.
set_alpha(alpha)Parameters: alpha (number 0–1)selfThe same as .alpha = alpha. It is not Shape.set_alpha (that one recolors fill/line).
look_like(other)Parameters: other (another object)—Copies the appearance of another object (color, Visual, add-ons).
save_visual() / restore_visual()No parameters—Remembers the current appearance (add-ons included) and goes back to it later (it keeps a single appearance). A second save_visual does nothing until restore_visual.
prepare_fx(Halo, Aura)Parameters: visuals (Visual)—Computes the silhouette of every frame ahead of time (avoids a hitch on the first Visual change). With no arguments: the current Visual, if it needs it.
play(clip, …)

sprite.play(clip, *, loops=, next=, min_hold=, resume=)

ParameterPassType (default)Meaning
clip1ststrA name registered with sheet.clip / strip / fps= on the Sheet. E.g. sprite.play("walk") or sprite.play(clip="walk").
loops=name=integer or Noneloops=1 plays once and holds the last frame (or the first when yoyo=True), unless next= is given. Omitted: forever.
next=name=str or NoneThe clip that follows after loops. It is not then=. E.g. next="idle".
min_hold=name=number0Seconds. Until the current clip has played this long, requests for another clip are ignored.
resume=name=boolFalseWhen coming back to this clip, it continues from the remembered phase instead of restarting at frame 0. Leave it off for hit/hurt clips that must always start over.
Sheet

A Sheet holds the frames of one or more images and the animations (clips) made from them. It does not appear on the screen: hand it to a Sprite (Sprite(sheet)). One Sheet serves many Sprites.

Sheet(source, *files, cols=, rows=, cell=, atlas=, fps=, name=, yoyo=, anchor=, pixel_size=)

ParameterPassType (default)Meaning
source1ststr, list or NoneA PNG, a file pattern ("robot/Run (*).png", Pattern) or a list of PNGs (2 Files), or left out with Sheet() (an option in 5 Strip). Atlas only: an XML/JSON on its own finds the PNG it lists. Lookup: Image files. E.g. Sheet("hero.png", cols=4, rows=3).
extra files2nd…strShortcut: Sheet("a.png", "b.png") = Sheet(["a.png", "b.png"]). A pattern here or in the list turns into its files, in its place. Incompatible with cols= / rows= / cell= / atlas= (use strip). A list in source= + extras: TypeError.
cols / rowsname=integer or NoneA regular grid. E.g. cols=4. Together: cols=4, rows=3. rows= without cols=: TypeError (a vertical strip is cols=1).
cellname=pair of numbers or NoneCell size in pixels. E.g. cell=(32, 32). Do not mix it with cols= / atlas=.
atlasname=str or NoneJSON/XML, with the PNG in source. E.g. atlas="sheet.json".
fpsname=number or NoneRegisters a clip over every cell already loaded. Without name=: "default". Grid and list. Packed atlas: TypeError.
namename=str or NoneThat clip's name. Needs fps=. In 5 Strip, name="idle" on the first file matches the strip calls that follow.
yoyoname=boolFalseBack and forth in the constructor's clip. Needs fps=.
anchorname=str or pair"center"The point of each PNG that sits on the Sprite's center: "center", "bottom", "top", "left", "right" or (ax, ay). A pivot written in the atlas wins. Different sizes.
pixel_sizename=number > 0 or NoneNoneThe size of one PNG pixel, in design units: pixel_size=3 → each pixel is worth 3 (pixel art at 3×); 0.5 → two pixels per unit (a large PNG). Sprites of this Sheet with no height= / width= / size= / box= draw at the PNG size × pixel_size — all at the same scale, without measuring each one. An explicit size on the Sprite wins. E.g. Sheet("tiles.png", cell=(16, 16), pixel_size=3).

Properties

PropertyType (typical value)Read/WriteMeaning
nframesinteger8readHow many cells the catalog has now.
namestuple of strreadCell names (atlas / several files). A regular grid usually uses indices.
anchorstr or pair"center"readThe constructor's anchor=.
pixel_sizenumber or None3.0readThe constructor's pixel_size= (None if it was not given).

Methods

MethodSignatureReturnsMeaning
clip(name, frames, fps=, yoyo=, offset=)Parameters: name (str), frames (list or omitted), fps (number, default 8), yoyo (bool), offset (pair of numbers)the SheetNames a sequence of cells already in the catalog (indices or atlas names). Without frames: every current cell. offset=(dx, dy): Different sizes. E.g. hero.clip("walk", [3, 4, 5, 6], fps=12).
strip(name, source, cols=, rows=, cell=, fps=, yoyo=, offset=)Parameters: name (str), source (str, pattern with * or list), cols / rows / cell, fps (number), yoyo (bool), offset (pair of numbers)the SheetAdds more frames and registers the clip (5 Strip). source: a strip file (a grid with cols=, or a single frame), a pattern ("ninja/Run__*.png": one file per frame, in order — File patterns) or a list of files. cols= / rows= / cell= with a pattern or a list: TypeError. Name first, like clip. Call it during setup, not every frame. E.g. hero.strip("walk", "walk.png", cols=8, fps=12), ninja.strip("running", "ninja/Run__*.png", fps=12).
frame_index(key)Parameters: key (number or str)integerResolves a cell index or name.

Don't confuse

Looks likeIt isIt is not
Sprite("hero.png", cols=4, fps=8)a TypeError that points to the Sheet. cols= / rows= / cell= / atlas= / fps= / name= / yoyo= belong to the catalog.a shortcut on the Sprite
Sprite("x.png").sheet.clip(…)refused (TypeError). Sprite("x.png") shares one catalog among all the Sprites of that file. For clips, build a Sheet first.a copy made on demand
play(…, fps=)not there. The pace lives in the clip — another pace is another clip.—

Sprite · How to

Loading sprites

Six ways, depending on the files you have. In all of them, the Sheet builds the catalog and the Sprite places it.

You haveWay
One still PNG (potion, shot, ship)1 PNG — no Sheet
One PNG per frame (Run (1).png, Run (2).png…)2 Files
One packed PNG + XML/JSON, with animations3 Atlas
One PNG laid out as a regular grid4 Grid
One strip PNG per animation (idle.png, walk.png), or a pack of loose PNGs with several animations (Idle__000.png…, Run__000.png…)5 Strip
An atlas of items / ships; each Sprite stays on one frame6 Still image

One file, one still image. No Sheet, no clip, no play. The constructor already places the Sprite on the screen.

Sprite("potion.png", height=48, center=(x, y), group="potion")
Sprite(source="shot.png", height=18, center=(x, y))

Every Sprite("shot.png") shares one catalog (it decodes the file and computes the hitbox once). That is why this catalog refuses clip / strip. A Sheet("x.png") with no layout is a one-cell catalog of your own, and it takes clips.

Several files, each one a frame. A pattern with * takes them all at once; Sheet([...]) (or several positional arguments) lists them one by one; clip names sequences; play on the Sprite.

robot = Sheet("robot/Run (*).png", fps=12)   # Run (1).png, Run (2).png, … in order
Sprite(robot, height=56, center=(x, y))       # one clip → it starts playing

hero = Sheet(["Idle_0.png", "Idle_1.png", "Run_0.png", "Run_1.png"])
# the same: Sheet("Idle_0.png", "Idle_1.png", "Run_0.png", "Run_1.png")
hero.clip("idle", [0, 1], fps=6, yoyo=True)
hero.clip("run",  [2, 3], fps=12)
s = Sprite(hero, height=48, center=(x, y))
s.play("run")

"robot/Run (*).png" loads every file in that folder that matches, one per frame, in order. Rules: File patterns.

A pattern, a list or extra positional files = one file per frame. In this way, cols= / atlas= is a TypeError — that is 5 Strip. fps= in the constructor registers a clip over all the files. The frames also have names (the file's, without the extension): hero.clip("idle", ["Idle_0.png", "Idle_1.png"]).

PNGs of different sizes per animation (a lower slide, a wider fall) are common in trimmed packs. See Different sizes.

One PNG + a packed atlas (Kenney XML or JSON). Clips by frame name. The way taught here: image + atlas=.

space = Sheet("space_sheet.png", atlas="space_sheet.xml")
space.clip("green", ["enemyGreen1.png", "enemyGreen2.png"], fps=6)
enemy = Sprite(space, height=40, center=(x, y))
enemy.play("green")

A convenience: Sheet("space_sheet.xml") finds the PNG listed in the XML/JSON. Prefer naming both. If source= and the atlas list different PNGs, the author's source wins (a warning, once). If the source is missing, a warning, and it falls back to the listed PNG (or a placeholder). fps= / name= / yoyo= in the constructor of a packed atlas is a TypeError — it does not play every cell. The atlas can also carry pivots (Different sizes) and collision boxes (Atlas boxes).

One file laid out as a grid, cols= × rows= (or cell= in pixels). Several clips, or one loop with fps= on the Sheet.

run = Sheet("hero.png", cols=4, rows=3)
run.clip("walk", [3, 4, 5, 6], fps=12)
run.clip("jump", [7, 8, 9], fps=10)
Sprite(run, center=(200, 400)).play("walk")

snail = Sheet("snail.png", cols=8, fps=6)   # "default" clip over every cell
Sprite(snail, height=36, center=(x, y))    # one clip → it starts playing

Layout: cols= alone (one row), cols= with rows=, or cell=(w, h). The image must divide exactly. A vertical strip: cols=1, rows=8. cols= + cell= is a TypeError.

Each strip loads one animation and names its clip at once: a strip file, or a pattern with that animation's loose PNGs.

hero = Sheet("idle.png", cols=4, fps=6, name="idle")
hero.strip("walk", "walk.png", cols=8, fps=12)
hero.strip("jump", "jump.png", cols=4, fps=10)
# by name: hero.strip(name="walk", source="walk.png", cols=8, fps=12)
s = Sprite(hero, height=48, center=(x, y))
s.play("walk")

name= on the first file names the first clip. Strips are a grid or a single frame (a packed atlas stays in Sheet(..., atlas=)). A Sprite on a Sheet that is still empty is a ValueError.

A pack of loose PNGs (one file per frame, one prefix per animation): the Sheet starts empty and each strip gets a pattern. One line per animation, each name written once.

ninja = Sheet(anchor="bottom", pixel_size=0.16)
ninja.strip("idle", "ninja/Idle__*.png", fps=8)
ninja.strip("running", "ninja/Run__*.png", fps=12)
ninja.strip("jumping", "ninja/Jump__*.png", fps=10)
player = Sprite(ninja, center=(x, y))
player.play("running")

Rules for *: File patterns. "ninja/Jump__*.png" does not take Jump_Throw__000.png: the rest of the name must match letter by letter. A list works too: ninja.strip("flight", ["a.png", "b.png"], fps=8). With a pattern or a list, cols= / rows= / cell= is a TypeError (there is no image to cut).

One PNG + an atlas; each Sprite locks onto a named frame. No clip, no play.

space = Sheet("space_sheet.png", atlas="space_sheet.xml")
Sprite(space, frame="playerShip1_blue.png", height=48, center=(x, y))
Sprite(space, frame="powerup_bolt.png", height=24, center=(x2, y2))

frame= (an index or a name) picks the cell. Default 0. One Sheet for the whole fleet: the pixels and the atlas are read once.

Define the clips on the Sheet before (or while) you create the Sprites. A Sheet shared by a fleet is one and the same object: a new clip shows up for all of them.

File patterns: *

Art packs often come with one PNG per frame: Run__000.png, Run__001.png… Instead of listing them one by one, write the name with * where it changes. The * means “anything here”: Scena loads every file in that folder whose name matches, one frame per file, in order.

# Sheet: a single animation; fps= registers the clip.
# Run (1).png, Run (2).png, … Run (8).png
robot = Sheet("robot/Run (*).png", fps=12)
Sprite(robot, height=56, center=(200, 300))

# strip: one animation per line, the clip name first.
# "idle" = Idle__000.png … Idle__009.png
ninja = Sheet(anchor="bottom", pixel_size=0.16)
ninja.strip("idle", "ninja/Idle__*.png", fps=8)
ninja.strip("running", "ninja/Run__*.png", fps=12)
ninja.strip("jumping", "ninja/Jump__*.png", fps=10)
player = Sprite(ninja, center=(500, 300))
player.play("running")

# Among other files: the pattern turns into its files.
mix = Sheet("ninja/Idle__*.png", "ninja/Dead__009.png")
  1. Only * is special. It stands for any piece of the name (even none). The rest must match letter by letter: "ninja/Jump__*.png" does not take Jump_Throw__000.png. Case counts: "ninja/idle__*.png" does not find Idle__000.png.
  2. Natural order. Numbers in the name count as numbers: Run (2) comes before Run (10), with or without leading zeros (Run__002).
  3. One folder only. The * goes in the file name, not in the folder ("*/Run.png" is a ValueError). The lookup is the one in Image files, and the first folder that has a matching file wins — it never mixes folders.
  4. Nothing matched? The game goes on. A checkerboard in its place, and a warning with the pattern and the folders it looked in (and the names that differ only in case). The clip exists and plays.
  5. One file per frame. There is no single image to cut: cols= / rows= / cell= / atlas= with a pattern is a TypeError, even if only one file matches.

Where it works: wherever several files work — in Sheet (as source, in a list or among the extra files) and in strip. Sprite("ninja/Run__*.png") is a TypeError: a Sprite given a file name is a still image. Write Sprite(Sheet("ninja/Run__*.png", fps=12)). The frames get the file's name without the extension ("Run__003"), for use in clip, frame= and showing. Two files with the same name in different folders (idle/1.png and run/1.png) keep the name "1" from working for either of them (a ValueError naming both); use the path ("idle/1.png") or the index.

Without a pattern, the same thing as a list: ninja.strip("running", ["ninja/Run__000.png", "ninja/Run__001.png"], fps=12). Use it to pick only some frames or to change the order.

Sprite · How to

Animating sprites

The clip lives on the Sheet (which frames, fps, yoyo); the Sprite picks one with play. Animation is a visual, not a mode: it survives e.mode = ….

A named sequence on the Sheet; play on the Sprite. The same clip again, while it plays, does nothing — safe to call in update. A loops=1 clip that has already ended starts over: to play it only once from update, check first (if not player.showing("dead"):).

hero = Sheet("hero.png", cols=4, rows=3)
hero.clip("idle", [0, 1, 2], fps=6, yoyo=True)
hero.clip("walk", [3, 4, 5, 6], fps=12)
sprite = Sprite(hero, center=(200, 400))   # 2+ clips → still on the first frame of "idle"
sprite.play("walk")
sprite.play("walk")                        # does nothing: the animation goes on
sprite.frame = 3                           # stops playback and shows cell 3
The Sheet hasSprite(sheet) starts
0 clipsStill on frame (default 0).
1 clipPlaying that clip (autoplay).
2+ clipsStill on the first frame of the first registered clip, until .play.
An explicit frame=Still on that cell — it wins over autoplay.

yoyo=True goes back and forth; yoyo=False starts over from the beginning. fps omitted in clip = 8. The time is the world's × the Sprite's time_scale: it pauses with the world, and sprite.time_scale = 0.5 animates in slow motion.

Which frame am I on? sprite.showing("walk"), showing(3) or showing((3, 7)) say whether the frame on the screen is one of these — for example, dust on the footstep frames: if player.showing((3, 7)): drop_dust(). To switch on an attack box on certain frames: Attack boxes.

A short reaction: it plays once and goes back to the base clip.

hero = Sheet("hero.png", cols=4, rows=3)
hero.clip("idle", [0, 1, 2], fps=6, yoyo=True)
hero.clip("hit", [9, 10], fps=12)
hero.clip("die", [11], fps=8)
sprite = Sprite(hero, center=(200, 400))
sprite.play("hit", loops=1, next="idle")   # once, then "idle"
sprite.play("die", loops=1)                # once, and hold the last frame

loops=1 without next= holds the last frame (the first, in a yoyo clip). next= is a clip name, not a callback — to run code at the end, use after.

Pick the clip every frame from the state. min_hold and resume keep it from flickering and restarting.

# grounded can flicker for one frame — min_hold keeps the clip from restarting;
# resume=True continues the phase on the way back (leave it off for one-shot reactions).
if not grounded:
    sprite.play("jump", min_hold=0.06)
elif sprite.vel.x != 0:
    sprite.play("walk", min_hold=0.08, resume=True)
else:
    sprite.play("idle", min_hold=0.08, resume=True)

Off by default: without min_hold / resume, each switch takes effect at once and starts over from frame 0. To turn the hero toward the way it runs: Flip.

Packs trimmed per animation have PNGs of different sizes. One scale per Sprite and a shared registration point solve it without editing the art.

ninja = Sheet(anchor="bottom")
ninja.strip("idle", "ninja/Idle__*.png", fps=8)
ninja.strip("sliding", "ninja/Slide__*.png", fps=12)
player = Sprite(ninja, height=70, center=(x, y))   # center = the feet
player.play("sliding")                            # ~56 tall, on the ground

# or: the scale on the art, once — no height= on each Sprite
tiles = Sheet("tiles.png", cell=(16, 16), pixel_size=3)
ground_tile = Sprite(tiles, center=(x, y))        # 16 px cell × 3 = 48
RuleWhat it does
Sheet(pixel_size=)The art's scale, once on the Sheet: the size of one PNG pixel in design units (3 = pixel art at 3×; 0.5 = two pixels per unit). Sprites of the Sheet with no size in the constructor draw at the PNG size × pixel_size: a 16 px tile and a 32 px hero stay 1:2, without measuring each Sprite. A size on the Sprite wins (for that Sprite). A standalone PNG: Sprite(Sheet("tree.png", pixel_size=3)).
One scale per Spriteheight= / width= / size= measure the constructor frame (frame=; without it, the first frame of the first clip). The other frames draw at their PNG size × that scale: a 351 px slide next to a 439 px idle, with height=70, ends up 56 tall. sprite.height reads the current frame. Writing the size rescales every clip.
Sheet(anchor=)Which point of each PNG sits on center. "bottom": the bottom center of every frame sits at the feet, and a shorter frame stays on the ground. Values: "center" (default), "bottom", "top", "left", "right" or (ax, ay), y up.
Atlas pivotA pivot written in the atlas (pivot / anchor / origin in JSON, pivotX / pivotY in XML) wins over anchor=.
clip(…, offset=(dx, dy))The fine adjustment when one clip does not line up with the others: it moves that clip's art in art pixels (y up, +x = right in the unflipped art). It mirrors with flip_x. Also in strip(…, offset=). A cell has only one offset: the same cell in two clips with different offsets is a ValueError.
Sprite(offset=)Another adjustment: it shifts the whole Sprite (drawing and collider) in design units, in every clip.

The collision body measures its own reference frame, not the frame that is playing: the hero does not grow or shrink when it switches clips. See Body.

Sprite · How to

Facing sprites

Three different questions: where the PNG points (art_angle), where the Sprite points in the world (.angle) and how much the drawing tilts without moving the collider (tilt). flip_x / flip_y mirror it.

art_angle says where the nose is drawn in the PNG. With it, .angle becomes the heading in the world — the same number as heading().

# The ship is drawn pointing up (+y).
ship = Sprite("ship.png", height=48, art_angle=90)
ship.angle                          # 90: it appears as drawn

ship.rotate_to(heading(ship, mouse))   # the nose points at the mouse
bullet.move_to(goal, time=1.2, face=True)
ship.reset_rotation()                  # back to rest_heading (90)
FieldMeaning
art_angleDegrees, the same convention as the world (0 = +x, 90 = +y): the nose of the pixels, before the flip. One value per Sprite, for every frame. Default 0 (art facing right). Writing it later does not rewrite .angle.
.angleHeading in the world: where the painted front points. The constructor starts at rest_heading, so the PNG appears as drawn.
rest_headingRead-only. The heading at which the PNG appears with no rotation: art_angle after the flip. A ship with art_angle=90 → 90; a ninja with art_angle=0 + flip_x → 180. Shape: 0.
reset_rotation()Turns to rest_heading and sets tilt to zero. It does not clear the flip. It takes time= / ease= like the other moves.

It mirrors around the pivot, before the rotation. The collider and the parts mirror along with it, without being recomputed.

# The ninja is drawn facing right.
if keyp("LEFT"):
    hero.flip_x = True     # faces left; angle becomes 180
elif keyp("RIGHT"):
    hero.flip_x = False    # angle goes back to 0

Turning on a flip rewrites .angle (flip_x → 180 − θ, flip_y → −θ) so that .angle is still the way the painted front points. Writing the same value again does nothing. clip(offset=), Sprite(offset=), hitbox_anchor and the tilt pivot mirror along with it. Do not use a negative scale to mirror — drawing uses the absolute value.

tilt tilts only the drawing — on a ramp, for example. The body stays upright, and center stays where resolve put it.

collision.floor = True      # "ground" belongs to a world with a floor
hero = Sprite(ninja, hitbox_shape="rect", hitbox_anchor="bottom")

def update(dt):
    hero.tilt = "ground"   # or AUTO_GROUND: follows the ground; in the air it goes back to 0

# Other ways:
hero.tilt = 22             # just that angle
hero.tilt = 0              # off
ValueEffect
numberTurns the drawing by that angle. It does not shift it.
"ground" / AUTO_GROUNDReads, every frame, the slope_angle of a "bottom" contact (touching). In the air: 0. It belongs to a world with a floor (collision.floor = True); with no floor, it warns once.
a contact cUses c.slope_angle and stays until you overwrite it. In update, reset it to zero before the loop over the contacts.

The pivot is the hitbox_anchor of the computed collider (not the PNG's rectangle). With a "bottom" anchor and a "bottom" contact, "ground" and tilt = c also bring the drawing down onto the ramp's plane, only along the normal (they do not slide sideways). With "center", the drawing does not come down to the ramp. Parts follow the tilt; the body does not. reset_rotation() sets it to zero.

Don't confuse

Looks likeIt isIt is not
On a ramp, hero.angle = rest_heading + slopeturning the collider too, and the hero stumbles. Use tilt: only the drawing.tilt
ship.rotate_to(heading(ship, goal) + art_angle)adding art_angle twice. .angle is already the heading in the world: ship.rotate_to(heading(ship, goal)).a manual adjustment
A “rotated” frame in a packed atlaspart of how the atlas is packed, resolved when it is read. It has nothing to do with art_angle.art_angle

Sprite · How to

Sprite hitbox

The shape a Sprite collides with. Every hitbox is a Hitbox: the main one (sprite.hitbox) for floor, walls and resolve; extra ones (add_hitbox) that only detect — a hurtbox, a weak spot. Both have the same properties: shape · source · anchor · scale · active · box.

Main (sprite.hitbox)Extra (add_hitbox)
Created byThe constructor: Sprite(hitbox_shape=…, hitbox_scale=…)sprite.add_hitbox(group=…, scale=…)
How manyOne (every Graphic has it; on a Shape it is the geometry itself)Several
Used forresolve (standing, bumping), a @collide that names the SpriteDetection only, through the groups it claims
GroupsThe Sprite's (sprite.tag(…))The ones it claims (group=)
Default sourceThe constructor's frame: steady while it animates"each": follows the current frame
Switch off only this onesprite.hitbox.active = False (the extras keep going)extra.active = False
Measuresprite.hitbox.boxextra.box
Follows tiltNo (stays upright)Yes
Frame with no artFalls back to the drawing's boxNo collider on that frame
Shape by hand—px_rect= / px_circle=, in the frame's pixels (Attack boxes)
Switched on by frame—part["active"] @= lambda: sprite.showing(…)

Both take the same four parameters. In the Sprite constructor they carry the hitbox_ prefix (the Sprite has its own scale); on the hitbox they don't: Sprite(hitbox_scale=0.8) is sprite.hitbox.scale = 0.8, and on an extra it is add_hitbox(scale=0.8) / extra.scale = 0.8.

ParameterQuestionValuesDefault
hitbox_shape= · .shapeWhich shape?"auto" · "rect" · "ellipse" · "circle" · "hull""auto"
hitbox_source= · .sourceFrom which art?frame · clip · tuple of clips · "all" · "clip" · "each"the constructor's frame (part: "each")
hitbox_anchor= · .anchorWhich point stays put?"center" · "bottom" · "top" · "left" · "right" · (ax, ay)"center"
hitbox_scale= · .scaleHow much to shrink / stretch?number or (sx, sy)(1.0, 1.0)

When it is computed. The first time the Sprite enters collision (@collide, resolve, collidable = True). A purely decorative Sprite never pays. The result is cached per image: a hundred Sprite("shot.png") share a single computation. After that the main hitbox stays frozen while the clip plays — except with "each" (every frame) and "clip" (on every clip change). See it: collision.show_colliders() or Ctrl+Shift+7 — main hitboxes in a resolve in gold, other main hitboxes in green, extras in cyan.

Measure the Sprite

ReadMeasuresWhich frame
sprite.width / heightThe size you gave (the setting; writing rescales).fixed
sprite.boxThe whole drawn cell, transparent margin included, where it is drawn.the one on screen
sprite.hitbox.boxThe main hitbox, as collision uses it. This is the one for floor_below(dx=).the source's (default: fixed)
extra.boxThat extra hitbox (None on a frame with no collider).the source's (default: the one on screen)
sprite.art_boxOnly the visible pixels of the frame on screen.the one on screen

Each read is a new Box, as things are right now: hit_width = hero.hitbox.box.width. Hitbox boxes are aligned to the screen (left / right / bottom / top); box and art_box turn with the Sprite. Measuring does not sign anything up for collision.

The main hitbox. Pick the shape with hitbox_shape= and the art that defines it with hitbox_source= (later: sprite.hitbox.shape / .source).

Sprite("ship.png")                          # "auto": picks the shape on its own
Sprite("ball.png", hitbox_shape="circle")
Sprite("swordsman.png", hitbox_shape="hull")

hero_sheet = Sheet("hero.png", cols=4, rows=3)
hero_sheet.clip("idle", [0, 1], fps=6)
hero_sheet.clip("running", [2, 3, 4, 5], fps=12)
hero_sheet.clip("dead", [9, 10, 11], fps=8)
hero = Sprite(hero_sheet, hitbox_shape="rect", hitbox_source=("idle", "running"))

shape — which shape

ValueFitWhen to use
"auto"Tries a circle, an ellipse, two ellipses, a convex hull and a rectangle, and keeps the best fit for the lowest cost. It prefers to err on the inside: a phantom touch is worse than a missed one.Ships, enemies, loose objects.
"rect"The silhouette's box: covers all the art, flat base.Anything that walks — platformers.
"ellipse"An ellipse in the silhouette's box. Nearly square becomes a circle.Oval bodies.
"circle"A circle that covers the art.Balls, coins.
"hull"The silhouette's convex hull (a little bigger than the art).Pointy shapes.

Naming a shape means covering the art with it. Only "auto" chooses by precision.

source — from which art

One rule: one frame is that frame; several frames are their union (the silhouettes are overlaid at the pivot and fitted once — not a union of shapes).

ValueWhich artComputed
omittedThe constructor's frame (frame=; without it, the first frame of the first clip).once
3 / "Idle__004"That frame (index or name in the atlas).once
"running"Union of that clip's frames.once
("idle", "running")Union of those clips, and only those. An empty tuple or an unknown name: ValueError.once
"all"Union of every registered clip. With no clips (a fleet of still images): the constructor's frame. Not the whole atlas.once
"clip"Union of the clip that is playing. Nothing playing: the constructor's frame.on every clip change
"each"The current frame.every frame

The tuple is the right choice when one clip is very different from the others: above, the wide frames of "dead" do not widen the hitbox of a walking hero. With "auto" + "each" / "clip", the kind of shape is chosen the first time; after that only the size changes. The main hitbox measures its reference frames, not the frame that is playing: the hero does not grow when a taller clip plays.

"each" and "clip" move the foot line on every frame / clip. For anything that walks on the floor, use a fixed set ("all", one clip or a tuple).

The computed shape covers the silhouette. scale shrinks or stretches it around anchor (in the constructor: hitbox_scale= / hitbox_anchor=).

# Platformer recipe: a steady box, feet on the floor, narrower than the art.
hero = Sprite(
    hero_sheet,
    hitbox_shape="rect",
    hitbox_source="all",
    hitbox_anchor="bottom",
    hitbox_scale=(0.55, 1.0),
)

Sprite("swordsman.png", hitbox_shape="hull", hitbox_anchor=(-0.5, 0))
AnchorPairCollider point
"center"(0, 0)center (moves nothing)
"bottom"(0, -1)middle of the base
"top"(0, 1)middle of the top
"left"(-1, 0)middle of the left side
"right"(1, 0)middle of the right side
—(-0.5, 0.2)left of center, a little above

The anchor does three things:

  1. It fixes the scale. (0.55, 1.0) + "bottom" narrows without lifting the feet.
  2. It pins the shape to the art. The anchor point lines up with the silhouette box of the frames in this computation (source) — not with the whole Sheet. A circle or ellipse with "bottom" rests its base on the foot line.
  3. It is the pivot for tilt. With a flip, the point mirrors along with the collider.

The pair is not limited to −1…1 (it can go past the edge). Written as a name, it reads back as a name; as a pair, it reads back as a pair. scale: one number applies to both axes; it always reads back as (sx, sy); 0 flattens that axis; a negative number, nan or inf is a ValueError. The PNG's transparent margin stays in the file — height= still measures that canvas; it is the hitbox computation that finds the silhouette.

A single main hitbox gives stability. When the pose really changes (the hero goes into the water and swims horizontally), switch it by hand: all four parameters can be written during the game.

STANDING = ("idle", "running", "jumping")

hero = Sprite(ninja, group="hero", hitbox_shape="rect", hitbox_source=STANDING,
               hitbox_anchor="bottom", hitbox_scale=(0.55, 1.0))

def enter_water():
    hero.hitbox.source = ("swimming", "floating")   # union of the two clips
    hero.hitbox.anchor = "center"
    hero.hitbox.scale = (1.0, 0.55)             # horizontal pose: flattens the height
    hero.play("swimming")

def leave_water():
    hero.hitbox.source = STANDING
    hero.hitbox.anchor = "bottom"
    hero.hitbox.scale = (0.55, 1.0)
    hero.play("idle")

It is still the same Sprite: groups, collision functions and resolve do not change. Writing shape or source computes it again (cached after the first time); anchor and scale only reposition. You can also change the shape: hero.hitbox.shape = "ellipse".

TopicRule
By hand × "clip"hitbox_source="clip" switches on its own, but for every clip: the foot line follows each one. It suits things that fly or a top-down view. For anything that walks, switch by hand only at the moments that call for it.
The hitbox grows into a wallIf the new shape cuts into a solid that was clear, resolve pushes it back out through that face. See resolve.
Wrong nameChecked on write: an unknown clip or frame is a ValueError. If the Sheet loses the clip later, the computation uses the constructor's frame and warns once.

An extra hitbox that owns a group and only detects. The main hitbox still takes care of floor and walls.

hero = Sprite(ninja, group="hero", hitbox_shape="rect", hitbox_source="all",
               hitbox_anchor="bottom", hitbox_scale=(0.55, 1.0))
hurt = hero.add_hitbox(group="hurt")      # silhouette of the current frame; only detects

resolve(hero, "ground")                    # the main hitbox stands on the ground

@collide("bullet", "hurt")                   # the part answers for "hurt"
def wounded(bullet, victim, info):             # victim is hero; info.b_hitbox is hurt
    victim.hp -= 1
    bullet.destroy()

What group="hurt" does. Two things: the Sprite joins the "hurt" group (like any tag: group["hurt"] lists the Sprite, hero.tagged("hurt") is True), and the part claims the group — in collision, under "hurt", the one that shows up is the extra, not the main hitbox. A part can claim several groups (group=["hurt", "mark"]). Two colliders of the same Sprite do not answer for the same group: a second part with "hurt" raises an error.

What answers

You writeWhat collides
@collide(bullet, hero) · ANYTHING · on_collideThe main hitbox. Naming the Sprite means the main hitbox (@collide(bullet, hero.hitbox) raises an error: name the Sprite).
@collide("bullet", "hurt")The part that claims "hurt".
@collide("bullet", hurt)The part (the Hitbox object).
Collision functionAlways receives the Sprite. info.a_hitbox / info.b_hitbox say which part (None = the main one). CollisionInfo.
resolve(hurt, …)TypeError: a part does not resolve.
resolve("enemy", …) with parts in "enemy"Moves the Sprites by their main hitbox. A boss with a weak spot and wasps in the same group still stand.
info.push_apart() / bounce_apart() / resolve() on a part's contactRaises an error. normal, point and depth can still be read.
touching_sides / touching_contactsOnly the main hitbox. Extras never count.

A Sprite never collides with its own parts, and two parts of the same Sprite never form a pair.

Switching on and off

I wantWriteEffect
Invincible for a whilehero.untag("hurt") … hero.tag("hurt")The Sprite leaves the group; the part still owns "hurt" and comes back with the tag.
Switch off only the extrahurt.active = FalseLeaves play (fires the exits). True switches it back on.
Switch off only the main onehero.hitbox.active = FalseGoes through floor and walls (a ghost); the extras keep detecting. True switches it back on. Everything: collidable = False.
Give up the claimhurt.remove_from_group("hurt")The part drops the group and the Sprite leaves it.
Remove the parthero.remove_hitbox(hurt)The Sprite leaves the groups the part put it in. A boss with group="enemy" stays in "enemy" when its weak spot add_hitbox(group=["enemy", "weak"]) is removed.

The group counts for detection and resolution. If "enemy" is a side of a resolve, untag("enemy") also takes the Sprite off the floor. For invincibility, toggle a group that is not a side of a resolve (such as "hurt").

Lifetime

  • Dies with the Sprite: destroy() fires the exits and kills the parts (is_alive False, host None).
  • hero.active = False and collidable = False switch off every hitbox; turning them back on switches them back on.
  • A frame with no art (with "each") = the part is absent on that frame. @collide / @collide_exit fire when it appears / disappears.
  • Follows the drawing: pose, flip, scale, offset, current frame and tilt.
  • clone() does not copy parts. Create them in the class's setup():
class Hero(Sprite):
    def setup(self):
        self.hurt = self.add_hitbox(group="hurt")

Queries and cost

A query with no group (query_point, query_circle, raycast(group=None), collides_with()) sees only the main hitboxes. With the group, it sees the parts: collision.raycast(tower, p2=hero, group="hurt"), collides_with("hurt"). A query never hits the parts of whoever is asking. See Queries.

Each part costs ~11–12 µs per step on this development machine: 20 animated Sprites with one part add up to ~0.26 ms; 100, ~1.2 ms. Fine for a hero, a boss and a squad. A fleet of 100 that needs only one collider keeps just the main hitbox.

A JSON / XML atlas can carry collision boxes per frame (hitboxes). Every "auto" computation of the Sprite uses them instead of the silhouette.

fighter = Sheet("fighter.png", atlas="fighter.json")   # frames with "hitboxes"

# A main hitbox with an explicit shape ignores the boxes: it keeps the silhouette.
p1 = Sprite(fighter, hitbox_shape="rect", hitbox_source="all", hitbox_anchor="bottom")

# An "auto" + "each" extra reads the current frame's boxes.
strike_boxes = p1.add_hitbox(group="strike")
  • They apply to every "auto" computation — the main hitbox included, because "auto" is the default. An explicit shape ("rect", "ellipse", "circle", "hull") ignores them.
  • Today, in practice, it is one set of boxes per Sprite: give the main hitbox an explicit shape and let an "auto" extra read the boxes.
  • With "each", each frame uses its own boxes. A computation over several frames at once (clip, tuple, "all") uses the boxes of the set's first frame.
  • hitbox_anchor="bottom" rests on the written boxes, not on the silhouette.

The area that hits (the sword, the punch): a part with its shape set by hand, which switches on by itself on the frames of the strike.

hero_sheet.clip("strike", [10, 11, 12, 13, 14, 15], fps=14)
STRIKE = (12, 13, 14)                              # frames with the sword stretched out

sword = hero.add_hitbox(group="attack", px_rect=(430, 180, 90, 80))
sword["active"] @= lambda: hero.showing(STRIKE)

def attack():
    hero.play("strike", loops=1, next="idle")   # the box switches on and off by itself

@collide("attack", "enemy")
def landed(hero, enemy, info):
    enemy.destroy()

Shape by hand: px_rect and px_circle

ParameterNumbers
px_rect=(x, y, w, h)Top-left corner and size, in the frame's pixels.
px_circle=(x, y, r)Center and radius, in the frame's pixels.

The numbers are the ones your image editor shows for that frame: origin at the top-left corner, y pointing down. It is an address in the image; the rest of Scena keeps y pointing up. The box stays attached to the drawing: Sheet(anchor=), clip(offset=), offset, flip, rotation, scale and tilt carry it along — you never add offsets yourself. It can go past the edge of the frame.

  • One PNG per frame, or one frame in Aseprite: the number the editor shows.
  • A grid sheet (cols=) opened as a single image: subtract the cell's origin (column × cell width, row × cell height).
  • A packed atlas: pixels of the original, untrimmed frame; Scena undoes the trimming and the rotation.
  • The same numbers on a frame of another size land somewhere else. Switch the part on only on the frames you measured.
  • One shape per part, and it does not mix with shape= / source= / anchor= / scale= (TypeError). sword.px_rect = None goes back to the art.
  • Only on a sheet Sprite: on an Svg it is a TypeError.

Switching on by frame: showing and @=

hero.showing(frames) says whether the frame on screen is one of these: a clip name, an index, a frame name, or a tuple / list mixing them. It goes by frame, so it stays right through yoyo, resume=, next= and an interrupted strike.

sword["active"] @= lambda: … links the switch to a formula. Scena computes it at the start of each frame's collision step — after update, on_update and any play() — and on every read of sword.active. The formula can read anything (hero.showing(…)), even values that are not Scena fields — as in group[...] @=.

I wantWriteEffect
The box only on the strike's framessword["active"] @= lambda: hero.showing(STRIKE)Comes in on the strike's first frame, leaves after the last.
Let go of the formulasword["active"].unlink()The last value stays; .active = … works again.
Invincible for 1.5 shurt.active = False and after(1.5, rearm)Time decides, not the drawing: a plain write.
Write while the formula is linkedsword.active = TrueLinkedAttributeError: let go first with unlink().

Why not @when? It runs after collision: the box switches on and off one frame late (one game loop). A line in update (sword.active = hero.showing(STRIKE)) works, but it lags if a play() comes after it in the same game frame, and it stays on if the hero changes mode in the middle of the strike and nobody writes the line again.

The formula only reads: do not move things or change groups inside it. If it raises an error, the message points to the @= line and to the add_hitbox line. Boxes written in the atlas: Atlas boxes.

Hitbox

Every hitbox. The main one is g.hitbox on any Graphic (on a Shape, the geometry itself: shape is read-only, the other three raise TypeError; Text has none). Extras: sprite.add_hitbox(…) — calling Hitbox(…) directly raises TypeError. It is not an Entity: no pose, no drawing, no own fields. Extras on Sprite and Svg (px_rect / px_circle only on a sheet Sprite).

After remove_hitbox or the owner's destroy(), reads still work (hb.shape, hb.scale; hb.box is None) and every write raises DestroyedError saying where it was destroyed — guard with if hb.is_alive:. Read-only fields (box, host, is_alive, layer, group) say what to write instead.

Properties

PropertyType (typical value)Read/WriteMeaning
shape / source / anchor / scalestr, pair or tuple"each"read / writeThe four parameters. On an extra, source defaults to "each".
.boxBox or Nonehero.hitbox.box.widthreadThis hitbox as it is now, aligned to the screen. None on a frame with no collider. Measures even when switched off. Measure.
px_rect / px_circletuple or None(430, 180, 90, 80)read / writeExtras only. A shape by hand in the frame's pixels (y down). Writing one clears the other; None goes back to the art. Attack boxes.
.activeboolTrueread / writeSwitches only this hitbox on / off (on the main one, the extras keep going; collidable switches them all off). It can be linked to a formula (below); then writing raises LinkedAttributeError.
.groupfrozenset{"hurt"}readExtra: the groups it claims. Main: the Sprite's groups minus the ones an extra claims (the extra answers for those). Read-only: change it with hb.tag / untag (main: sprite.tag).
.hostSprite or NonereadThe owner. None once removed or once the owner is destroyed.
.is_aliveboolTruereadTrue until remove_hitbox or the owner's destroy().

Methods

MethodSignatureReturnsMeaning
add_to_group(groupid) / remove_from_group(groupid)Parameters: groupid (str)the partExtras only. Claims / drops a group. Dropping also takes the Sprite out of the group. On the main hitbox, tagged(name) answers (it is name in hitbox.group); the others raise TypeError.
tag(*names) / untag(*names) / tagged(name)Parameters: names (names); tagged takes name (a name)the part / boolThe same thing, in the tag vocabulary.
part["active"] @= fn / part["active"].unlink()Parameters: fn (function with no arguments that returns True / False)—Links the switch to a formula (main or extra), computed in each frame's collision step. unlink() lets go and keeps the last value. Only "active" can be linked.

Don't confuse

Looks likeIt isIt is not
sprite.box.width as the hitbox widthsprite.hitbox.box.width. The drawing's box includes the PNG's transparent margin.the collider
sprite.hitbox.active = False = collidable = FalseSwitches off only the main hitbox; the extras keep going. collidable = False switches them all off.switching off the Sprite
Track(sprite) as a hurtboxTrack(sprite) is the live outline (for building, drawing). A hurtbox is add_hitbox.a damage collider
A click hits the hitbox@click / contains_point look at the current frame's alpha. collision.query_point looks at the bodies.the hitbox
hitbox_source="all" = the whole SheetThe union of the registered clips. An atlas with lasers and ships does not go in whole.every cell
px_rect with y pointing upThe frame's pixels as the editor shows them: y pointing down, origin at the top-left corner. The rest of Scena has y pointing up.a world coordinate
showing("strike") = the strike clip is playingThe strike clip's frames are on screen. A frame two clips share counts for both.the current clip's name
@when to switch on the strike boxpart["active"] @= lambda: … is computed before the collision of the same game frame. @when runs after: one frame late.the way to switch on the box
The Shield follows the hitboxThe Shield uses the frames' silhouette (× shield_scale). The hitbox parameters do not change it.the collider

Sprite

More Sprite features

Past the basics: copying a Sprite, giving a class defaults, using SVG as a sprite, appearance and clicks.

A new Sprite that looks like this one. Useful for building a fleet from a template. It is not a pool.

class Ship(Sprite, source="playerShip1_blue.png", height=48, group="ship"):
    pass

_SHIP = Ship(layer=None)    # template: off screen
_SHIP.active = False        # neither runs nor collides
ship_a = _SHIP.clone(center=(120, 400))
ship_b = _SHIP.clone(center=(240, 400))
ship_c = _SHIP.clone(center=(360, 400))
Copied (a snapshot of now)Fresh
Sheet, frame, size, offset, hitbox parameters, art_anglesetup() always runs
Pose: angle, scale, flip, tilt (the clone points where the original points; clone(scale=) multiplies)
Visual and add-ons (look_like)Own fields, mode, timers, click callbacks
Groups (tags included), unless group=Hitbox parts (create them in setup())
visibleAnimation position

layer= is placement: omitted, it uses the class default; layer=None stays off screen (a template). group= replaces the groups entirely. Clone a clean template, not a hero that is already tagged ("shielded" would come along). To shoot, build a new one: Shot(center=…) costs the same as clone().

Shapes, Text and Track follow the same rule: the clone matches the original, with the same pose and the same points (a Rect's p1 is still its p1), and center= puts it somewhere else (_ROCK.clone(center=(300, 50))). frame= exists only on Sprite: on the others it raises TypeError. A Text pinned by top_left= makes a clone pinned by the same corner.

Appearance defaults go on the class line. Each instance only says where it goes.

space = Sheet("space_sheet.png", atlas="space_sheet.xml")

class Shot(Sprite, source=space, frame="laserBlue01.png", height=18,
           art_angle=90, group="shot"):
    def setup(self):
        self.damage = 1

Shot(center=ship.center)
Shot(center=ship.center, frame="laserRed01.png")   # the instance wins

These work on the class line: source, frame, height / width / size, the four hitbox parameters, offset, visual, shield_scale, group, flip_x / flip_y, art_angle. A subclass inherits and overrides them. Placement (center, layer, box) is refused on the class. Do not write frame = … or height = … as an attribute in the class body: Scena does not read the value from there, and the class definition raises TypeError with the fix. Pass it on the class line.

Svg is a Sprite whose body comes from an SVG: <svg …> markup or a file. A still image: no clips, no play.

compass = Svg("compass.svg", height=48, center=(x, y))
Svg("<svg …>", height=48)
compass.svg = lib.render()   # reloads (markup or file)

Svg(source, height=, width=, size=, center=, box=, hitbox_shape=, hitbox_source=, hitbox_anchor=, hitbox_scale=, group=, layer=)

ParameterPassType (default)Meaning
source1ststr<svg …> text or a file name. Without < it is a file. Search: Image files. E.g. Svg("compass.svg").
height / width / sizename=number or NoneDesign units. E.g. height=48.
centername=pointdesign center(x, y).
boxname=Box or formulacellSame as Sprite. With a formula (box=lambda: …), it follows the region: grows through scale. box=.
hitboxname=—The same parameters as Sprite; "all" / "each" / "clip" come out the same (one frame). add_hitbox works too.
PropertyType (typical value)Read/WriteMeaning
.svgstr"<svg …>"read / writeThe current markup — the text, never the path. Assigning reloads it (markup or file). The same string does nothing. On failure: a warning, and the last good body stays. None clears it: back to the checkerboard, like Svg(None).
.boxBoxicon.boxreadA copy of the visual frame, taken now, with the names: after a flip_x, box.top_center is still over the head. Higher on screen: box.top. Place.

It becomes a bitmap when it loads: camera zoom smooths it, it does not redraw the vector. cols= / atlas= / fps=, play and strip are a TypeError. clone() copies the markup.

The visuals and add-ons from Appearance work on Sprite. A few details are Sprite's own.

sprite.alpha = 0.5
sprite.blend = "add"
sprite.glow = True
sprite.visual = Halo()
sprite.shield_scale = 1.6            # Shield oval bigger than the silhouette

# Loading screen: warm up before switching visuals during play.
sprite.prepare_fx(Halo, Aura)
  • alpha and blend apply to the image.
  • Silhouette visuals (Halo, Aura, Rim, Laser…) compute the current clip's silhouette when you assign .visual. prepare_fx(*visuals) computes every frame in advance; with no arguments, the current visual. Which visuals a Sprite takes: Visual.
  • Shield wraps the union of the frames' silhouettes, times shield_scale (default 1.4). Changing clips does not make the shell jump.
  • look_like(other) copies the visual and add-ons; save_visual() / restore_visual() store them and bring them back.
  • Clicks: @click and contains_point look at the current frame's alpha (tilt included). A transparent pixel does not click. It is not the hitbox.

Track

A curve. It serves two purposes: a track for move_along and a stroke you can draw (a curved wall, a ring that fills up). Default: invisible, like Point. Any Shape is also a track: bug.move_along(hexagon, time=4).

orbit = Track.circle(center=lambda: earth.center, radius=120)
moon.move_along(orbit, time=4, loops="forever")
wasp.move_along(Track.eight(width=90, height=40), time=2.5)
track = Track(points=[(80, 200), (240, 380), (520, 160)], color="gold")
t1 = Track(sprite1)

Anchored or floating. This is the choice that changes how a track behaves:

AnchoredFloating
Where it isAt a place in the world. The traveler goes to it.No place of its own for the trip: the curve starts where the traveler is (or at the point at= of move_along).
WhenYou passed a placement word: center=, points=, p1=, start=, or a Shape (Track(hexagon)).Sizes only: Track.eight(width=90), Track.circle(radius=80), vectors= without start=, Track(), a preset name ("eight").
Typical useAn orbit around a planet, a curved wall, a fixed path in the level.“Do a figure eight from where you are”: patrol, dodge, dance.

An explicit floating= always wins. Every Track has a real .center — floating is not “no position”; .is_floating only says whether the track's pose holds the traveler.

Giving it a place later anchors it. A track that floats only because it was made without a placement anchors when you give it a place later: linking the center (orbit["center"] @= lambda: earth.center), writing .center = or moving it (move_to, move_by). That is the missing placement, the same as center= in the constructor; anything already traveling on it starts following it. Rotating or scaling is not placement. With floating=True (or is_floating = True) it keeps floating: moving it only changes where it is drawn.

Visible or not. A motion-only track (no color= / visual= / line_width= / visible=True / layer=) stays out of the draw list — you can travel on it, and it goes away when nothing holds on to it. With a style, visible=True or an explicit layer=, it enters the canvas as a Shape (stroke, clicks and collision); hidden with visible = False, it stays there (it just does not show): an invisible collision strip — the track of a race, queried with collision.query_point — does not go away. To see tracks during development: show_tracks(True) (magenta; it does not turn on visible) — see Debug.

Four ways to give the shape: positions (points=), relative steps (vectors=), the outline of a Shape, or a preset.

Track()                                          # Track.eight(); floats
Track(points=[(60, 80), (200, 300), (420, 120)]) # curve (smooth=1)
Track(points=[...], smooth=0, closed=True)       # polyline
Track(vectors=[Vec2(50, 0), (0, 80), (-40, 20)], smooth=0)  # relative steps, floats
Track(hexagon)            # live outline; clone() freezes it
Track(sprite)             # live outline of the silhouette (the hurtbox is add_hitbox)
Track(ellipse, floating=True)  # live outline; its position does not hold the traveler
Track.circle(center=(400, 300), radius=120)   # anchored in the world
Track.eight(width=90, height=40)              # floats until someone travels on it

points= are positions in the world (a Vec2 in there is also a position); linking a point with a lambda makes the track follow it. vectors= are steps from the previous point (a turtle path). Both together (or with radius=) raise TypeError. smooth=1 (the default) curves through the points; 0 is a polyline. Track(shape) follows the Shape's live outline; Track(sprite), the painted silhouette. u=0 is at the first vertex (angle 0 on round shapes), counterclockwise.

Ready-made shapes. Centered family (center=): circle, arc, eight, star, spiral, shuttle. Start-point family (p1= / start=): line, wave.

Track.line(length=200)                        # +x, floats
Track.line(length=200, angle=90)              # +y
Track.line(vec=Vec2(120, -40))                # length + direction
Track.line(length=400, angle=-30, p1=(1050, 450))  # planted, u=0 at p1
Track.line(p1=(0, 0), p2=(200, 0))            # two points, anchored
Track.circle(radius=80, center=(400, 300))
Track.arc(radius=80, from_angle=0, to_angle=180)
Track.eight(width=90, height=40)
Track.eight(width=90, height=40, center=(400, 300), floating=True)  # drawn there; the traveler does the eight from where it is
Track.star(points=5, radius=70)
Track.spiral(turns=3, radius=80)
Track.wave(length=200, amplitude=30, waves=3)
Track.wave(length=200, start=(100, 300))
Track.shuttle(length=180)                     # out and back along both sides, closed

Start-point presets plant u=0 with p1= / start=; center= does not apply to them. .center is still the geometric middle. Full table: Presets, below.

Read points of the curve by u: 0 is the start, 1 is the end, and u grows evenly with distance (u=0.5 is halfway along) — to place things along it.

x, y = track.at(0.25)
ang = track.angle_at(0.25)
tx, ty = track.tangent_at(0.25)
pts = track.spaced_points(8)          # closed: the start is not repeated
pts = Track(rail).spaced_points(5)    # open: includes the ends
track.u = 0.5
ship["center"] @= lambda: track.cursor   # places — to travel: move_along

Samples return tuples, not Points, and already include the track's pose (local_at does not). .cursor is the Point at u: linking a center to it places (no sweep against walls).

begin / end trim the stroke: drawing, clicks and collision. Animating end from 0 to 1 “draws” the curve.

ring = Track.circle(center=(400, 300), radius=80, color="gold", line_width=5)
ring.end = 0
tween(ring["end"], 1, time=1.4, ease="ease_out")
# a window that moves around a loop (closed wraps around)
crawl = Track.circle(center=(400, 300), radius=100, color="cyan", line_width=4)
crawl.begin = 0
crawl.end = 0.2

The window does not change the curve: at(u), length and move_along follow the whole curve. Closed with begin > end wraps around the loop; open with begin >= end neither draws nor collides. The stretch of one trip is something else: span= on move_along.

They deform the curve on the object itself and return the Track (chainable).

base = Track(points=[(80, 200), (520, 200)], smooth=0)
base.zigzag(amount=24, waves=6)     # changes this Track, returns self
base.orbit(radius=12, laps=4)
base.wander(amount=10, seed=3)
# clone() first if you want the original straight line

To keep the original, clone() first: the clone freezes the current view (including reversed() and modifiers) into a polyline.

A stroke with line_width collides like a thick line: that makes a curved wall.

wall = Track.arc(
    center=(400, 300), radius=80, from_angle=0, to_angle=90,
    color="gold", line_width=8, group="wall",
)
resolve(player, "wall", bounce=0.0)

The collision is the stroke (line_width thick), trimmed by begin / end. Closed = a ring, not a disk. A filled slice (clicks and collision on the disk): Circle(angle=, spread=). A motion-only track: leave it unregistered (the default).

Constructor

Track() · Track(points=, smooth=, closed=, quality=, line_width=, color=, begin=, end=, floating=, angle=) · Track(vectors=, start=, smooth=, closed=, floating=) · Track(shape, floating=) · Track(center=, radius=, floating=)

Sizes only → floats until move_along (at= picks another starting point for that trip). A placement word given → anchored. An explicit floating= always wins. u=0 at the first vertex (angle 0 on round shapes), counterclockwise. Moving, rotating or scaling the track (center / angle / scale) does not rebuild the points; at(u) already returns the position with the current place and rotation. angle= in the constructor is the initial pose.

ParameterPassType (default)Meaning
source1stShape or SpriteTrack(hexagon): the track is that Shape's live outline (or the Sprite's silhouette). Anchored (pose linked to the source). floating=True turns off only the position — the source's outline / rotation / scale stay live. clone() freezes it.
pointsname=list of pointsPositions in the world. Each point is copied if it is a tuple, a Point or a Vec2 (where it is now), or linked if it is a function ([(0, 0), lambda: ship.center]); the list itself is fixed (points=lambda: […] raises TypeError). At least 2. Anchored. With linked points, .center is derived (the middle of the points; read-only). A Vec2 here is a position, not a step. floating=True frees the pose from the listed points.
vectorsname=list of Vec2 or (dx, dy)Turtle path: each item is a step from the previous one. Without start= it floats; with start= it is anchored (u=0 at that point). Open. Don't mix with points= / radius=. Don't use center=.
smoothname=number or False10 / False = polyline. 1 = curve. >1 = overshoots the points.
closedname=boolLoop. Default: Track() (= eight) closed; points= / vectors= open.
qualityname="high" or "low""high"Samples per segment. Only if you ask — never picked on its own because there is a link.
center / radiusname=point / numberWith radius=: the circle model (without center= it floats). center= plants the centered presets (circle / arc / star / eight / spiral / shuttle). Don't mix radius= with points= / vectors=. On line / wave / vectors= use p1= / start=.
startname=pointOnly on vectors= (and the Track.wave preset). Plants u=0. Omitted → floats.
floatingname=bool or omittedExplicit always wins. Without it: placement given → anchored; sizes only → floats until it gets a place (linking / writing .center, move_to, move_by), which anchors it. With floating=True moving it does not anchor it.
anglename=degrees0Initial heading (pose). Not part of the local polyline. On line / shuttle, angle= is that heading: the segment is built along +x and rotated, so Track.line(angle=30).angle is 30.
color / visualname=color or VisualStyle. color= sets the stroke. Either one, when you make it, makes the Track visible and puts it on the layer; a style given later (t.color = "white") does not show an invisible Track: write t.visible = True. Track is a Shape: the same .dash / .line_cap / .line_join (strings). scale enlarges the whole drawing, stroke included; to grow only the shape of a circle / arc, change radius.
line_widthname=numberStroke thickness. Also counts as style. Not width= — that is the size of Track.eight.
begin / endname=number 0…10 / 1Window of the stroke (drawing, clicks and collision). Default: the whole path. Outside 0…1 it is clamped. Does not change length / at / move_along.
visiblename=boolFalseLike Point: True moves it up to the layer. Without a style and without this, it stays out of the draw list.
layer / groupname=as for any object on screenAn explicit layer= also registers the Track on the canvas.
Construction models
CallMeaning
Track()The same as Track.eight(). Sizes only — floats.
points=Curve (default smooth=1). Open. Anchored at the points. Positions in the world — a Vec2 is also a position. Linked points: .center is derived (read-only).
points=, smooth=0Polyline.
vectors=Relative steps (Vec2 or (dx, dy)). Open. Without start= it floats. Don't mix with points= / radius=.
Track(shape)Live outline. Anchored. floating=True turns off the position. If the source is destroyed, the trip goes on with the last outline read.
center=, radius=Circle. Anchored only with center= (unless floating= says otherwise).
Presets

They take the same smooth= quality= line_width= color= begin= end= floating= angle= layer= group= as the constructor. Centered family: center=. Start-point family: p1= (line) or start= (wave). A position in the preset → anchored; sizes only → floats; an explicit floating= always wins.

CallMeaning
Track.line(length=, angle=, p1=) · Track.line(vec=, p1=) · Track.line(p1=, p2=)Open segment. smooth=0. Sizes only → floats; p1= plants u=0. p1=/p2= anchors (both required); .center is derived (the midpoint; read-only). length=/angle= or vec= — not both, and don't mix them with p1=/p2=. angle in degrees (0 = +x). Length omitted = a medium size. Don't use center=. Several steps: Track(vectors=[…], smooth=0).
Track.circle(radius=, center=)Closed circle. Without center= it floats. radius omitted = a medium size.
Track.arc(radius=, from_angle=, to_angle=, center=)Open arc. Angles in degrees. Default 0 → 180. Without center= it floats. Curved wall: color= + line_width= + group= / @collide.
Track.eight(width=90, height=40, center=)Closed figure eight. u=0 at the crossing (= center). Without center= it floats. Track() is this.
Track.star(points=5, radius=, inner=, center=)Closed star. points ≥ 3 (the number of tips, not a list). inner omitted = 40% of the radius. Without center= it floats.
Track.spiral(turns=3, radius=, center=)Open spiral. u=0 at the innermost point (= center). Without center= it floats. radius omitted = a medium size.
Track.wave(length=200, amplitude=30, waves=3, start=)Open wave. start= plants u=0. Without start= it floats. Don't use center=.
Track.shuttle(length=, angle=, center=) · Track.shuttle(vec=, center=)A closed 1-D stroke: it goes out to both sides from the center and back. length= is the total width (as in Track.line). Arc length per lap = 2 * length. Without center= it floats. length=/angle= or vec= — not both. loops="forever" does not need yoyo=.
Track reference

Properties

PropertyType (typical value)Read/WriteMeaning
.centerpointread / writeGeometric middle / pose. Write or link it to move the track without rebuilding the points. On linked points= and on Track.line(p1=, p2=) it is derived (writing raises DerivedAttributeError). On a track that floats for lack of a placement, linking / writing anchors it; with floating=True it does not change is_floating.
.radiusnumberread / writeOnly on the circle / arc model.
.lengthnumberreadTotal length of the curve, in design units. Read-only: to change it, change the shape (radius=, points=…).
.unumber0read / writeParameter 0…1. Writing it moves the cursor.
.begin / .endnumber 0…10 / 1read / writeWindow of the stroke (drawing, clicks and collision). Tween: tween(track["end"], 1, time=1.2). Closed with begin > end: wraps around the loop. Open with begin >= end: does not draw (or collide). The fill disappears while the window is not the whole path. Not the span= of move_along.
.cursorPointreadThe point at u; computed only when you read or link it. ["center"] @= lambda: cursor places — it does not sweep.
.closedboolreadLoop. Read-only.
.is_floatingboolread / writeWhether this track's pose holds the traveler. True: the curve starts where the traveler is (or at at=). Every Track has a real .center — floating is not “no position”. Writing it here (or floating= in the constructor) is your word: nothing else changes it. Without it, a track made without a placement floats until it gets a place (linking / writing .center, move_to, move_by) and then anchors — anything already traveling on it starts following it.
.smooth / .qualitynumber / "high" or "low"read / writeRead and write them. Writing recomputes the curve's points.
.visibleboolFalseread / writeLike Point: True promotes it to the layer; False takes it out of the draw list.

Methods

MethodSignatureReturnsMeaning
at(u)Parameters: u (0 to 1)(x, y)The point of the curve at u, already with the track's current place and rotation. Does not return a Point.
local_at(u)Parameters: u (0 to 1)(x, y)A sample in local space (no pose).
angle_at(u)Parameters: u (0 to 1)degreesHeading of the tangent. 0 = +x, counterclockwise.
tangent_at(u)Parameters: u (0 to 1)(tx, ty)Unit tangent in the world.
sample_span(a, b, n=32)Parameters: a (0 to 1), b (0 to 1), n (integer)list of (x, y)A stretch in the world, n samples.
spaced_points(n)Parameters: n (integer)list of (x, y)n points at constant speed (arc length). Closed: the return point is not repeated. Open: includes both ends. Tuples, not Point. A Shape's outline: Track(rail).spaced_points(8).
reversed()No parametersTrack (view)Instant: the same track, traveled backwards. reversed().reversed() is the original. The view has no pose of its own: center, angle, scale, flips and the verbs are the original track's. For this trip only: span=(1, 0).
zigzag(amount=20, waves=6, *, kind="sine")Parameters: amount (number), waves (number), kind ("sine" or "saw")selfMakes it wavy, on the object itself. clone() if you want the smooth copy.
orbit(radius=20, laps=8)Parameters: radius (number), laps (number)selfCoils around the curve. On the object itself.
wander(amount=6, seed=0)Parameters: amount (number), seed (integer)selfA stable random drift. On the object itself.
clone(floating=)Parameters: floating (bool, omitted copies the original)TrackFreezes the current view (including reversed and modifiers) into a polyline. Copies is_floating; clone(floating=True) turns off the pose on the clone.

Functions

MethodSignatureReturnsMeaning
show_tracks(enabled=True)Parameters: enabled (on, True/False)—A magenta overlay of the active trips and of the still Tracks on a layer. It does not turn on visible. Also collision.show_tracks. Ctrl+Shift+7 (the inspection zoom of Ctrl+Shift+8 does not show the tracks). Off: zero extra work per frame. It is debugging, not game logic — see Debug.

Don't confuse

Looks likeIt isIt is not
The stroke thickness is width=line_width=. Track.eight(width=…) is the size of the eight.Track(..., width=)
Track.arc and Circle(angle=, spread=)Track.arc(from_angle=, to_angle=) is the path (it has a direction and collides as a stroke). Circle(angle=, spread=) is the filled slice.the same shape
reversed() and span=(1, 0)track.reversed() is a reversed view of the track (O(1)). span=(1, 0) reverses just one trip.the same effect

History

A History keeps the last objects (or positions) you add and drops the oldest on its own — once there are more than max_points= or they are older than duration= seconds. Use it for trails made of pieces (dots, segments), snakes, queues. It does not draw: what shows up are the objects you put in it (add), and what leaves is destroyed. snapshot stores only a position. For a continuous stroke that fades: Contrail.

dots = History(max_points=40, on_leave=lambda dot: dot.dissolve_out(0.3))

def drop_dot():
    dot = dots.add(Circle(center=tip.center, radius=4))
    dot.visual = Halo("cyan")

every(0.05, drop_dot)
History constructor

History(*, max_points=, duration=, on_leave=, destroy_on_leave=True)

The two limits are independent and can be rewritten later. Lowering a limit evicts at once (oldest first, full exit). duration= is checked every frame; with only max_points= (or neither) the History stays idle until add / snapshot / pop / discard / clear.

ParameterPassType (default)Meaning
max_points=name=int or NoneNoneCapacity. When it overflows, the oldest leaves. To grow the trail: h.max_points += 1.
duration=name=number or NoneNoneThe longest time, in seconds, each thing is kept; the oldest leaves on its own even without a new add. None: no time limit.
on_leave=name=function or Nonelambda d: …A side effect on leaving. One argument: the thing, still alive. It does not replace the destroy. Also h.on_leave = fn. Don't mix it with an on_leave method in a subclass.
destroy_on_leave=name=boolTrueDefault: an Entity it holds is destroyed on leaving (it waits for a dissolve_out / fade_out / implode / burn_out in progress to finish). False: forgets it without destroying it (cards already played). Constructor only; afterwards it is read-only.
Read / write / remove
NameSignatureReturnsMeaning
add(thing)Parameters: thingthingStores the object. On leaving: on_leave, then it is destroyed if it is a live Entity (deferred while dissolve_out / fade_out / implode / burn_out plays). A part of another object and a live value (mouse, Vec2) raise TypeError at once; the same object stored twice raises ValueError (it would be destroyed twice).
snapshot(point) / snapshot(x, y)Parameters: point (point) or x, yPointStores a copy of the position, which follows nothing. Nothing to destroy.
history[i] / [a:b]index / slicevalue / list0 = oldest, -1 = newest. A slice is a copy (not a live view).
.first / .lastanyreadShortcuts for [0] and [-1].
len(history) / for v in history——From oldest to newest.
pop(index=-1)Parameters: index (int)valueTakes it out alive. No on_leave, no destroy — it is yours now.
discard(value)Parameters: valueboolRemoves by identity (not equality). Full exit. No error if it is missing.
clear()No parameters—Everything leaves, from oldest to newest (full exit).
.max_points / .durationint / float / Noneread / writeLive limits. Lowering one evicts at once.
segments = History(max_points=100, duration=2.0)

def sample():
    start = segments.last.p2 if segments else tip.center
    segment = segments.add(Line(p1=start, p2=tip.center))
    segment.visual = Laser("red")

every(0.05, sample)

Don't confuse

Looks likeIt isIt is not
add(tip) or add(tip.center) stores the poseadd(tip) makes the History the owner of tip, and it destroys tip on leaving. add(tip.center) raises TypeError — the part belongs to tip. A position: snapshot(tip).an automatic copy
History draws the trailstorage only. A continuous stroke: Contrail. Circles / segments: add(Circle(...)) / add(Line(...)).Track / MotionTrail / .tail
on_leave= on a subclass with def on_leavea TypeError — the callback and the method do not stack.both together
on_leave cancels the destroyan extra. The destroy goes away only with destroy_on_leave=False. A death verb in on_leave finishes before the destroy.a replacement for the destroy
snapshot of a destroyed entity (or of its .center / .p1)a DestroyedError, with the hint to use e.every(...).the last point, silently

Contrail

A Contrail draws a trail: a continuous line through an object's last positions, which can fade from head to tail (fade=). You only say when to store a position — contrail.snapshot(ship), usually with ship.every(0.05, …) — and the stroke updates on its own. It is a History with a stroke, positions only (add raises).

trail = Contrail(max_points=100, duration=2.0, fade=True, ease="ease_out",
                 visual=Laser("red"), line_width=3)
dst.every(0.05, lambda: trail.snapshot(dst))  # stops on destroy; pauses with dst.active = False

# faceted polyline
Contrail(smooth=0, line_join="miter", visual=Laser("red"))

# grows like a snake
trail.max_points += 1

# base alpha (fade multiplies on top of it — head = 0.5, tail → 0)
Contrail(duration=1.0, color=Color("cyan").with_alpha(0.5), fade=True)
Contrail constructor

Contrail(*, max_points=, duration=, fade=, ease=, color=, visual=, line_width=, line_join=, smooth=, on_leave=, layer=)

The same limits as History. A private stroke (not a Track). smooth=1 by default (cubic); smooth=0 = polyline. No stroke= — use color=.

ParameterPassType (default)Meaning
max_points= / duration=name=int / number / NoneThe same as in History (live; lowering one evicts at once).
fade=name=boolFalseTrue: alpha 0 at the tail → 1 at the head (a multiplier on the color's alpha).
ease=name=name or function"linear"The curve of the fade. Only with fade=True. Default "linear". The same catalog as tween.
color=name=colorgame defaultThe stroke color; e.g. Color("cyan").with_alpha(0.5). Alpha = the 4th channel — there is no alpha=.
visual=name=VisualNoneThe stroke's Visual (e.g. Laser("red")). Mutually exclusive with color= in the constructor, as in Shape.
line_width=name=number1.5Stroke thickness, in design units. Also contrail.line_width = … later.
line_join=name=str"round"The stroke's corners (useful with smooth=0). Default "round". Faceted: "miter". It does not make a curve.
smooth=name=number or False10 / False = polyline. 1 = a Catmull-Rom curve (cubics in the path). >1 = overshoots the points. The same as Track.smooth.
on_leave=name=function or NoneA side effect when the tail recedes (a spark, a sound). The stroke always updates on its own.
layer=name=layer name"default"The stroke's layer: on a layer behind (canvas.layers.create("trail", below="default")) the trail passes behind the ship. Also contrail.layer = … later.
Methods and properties
NameSignatureReturnsMeaning
snapshot(point) / snapshot(x, y)Parameters: Point / (x, y) / GraphicPointAlways stores an unlinked Point. contrail.snapshot(dst) is enough. add raises TypeError.
len / index / iterate / .first / .last——Inherited from History (the values are Points).
.color / .visual / .line_width / .line_join / .line_cap—read / writeRead and change the trail's stroke, as on a Shape.
.smoothnumberread / writeRebuilds the path (cubic or polyline).
.fade / .easebool / callableread / writeRebuild the stroke. ease= requires fade=True.
.max_points / .duration—read / writeThe same as in History.
pop / discard / clear——The same as in History; the stroke follows.
destroy()No parameters—Empties it without on_leave and destroys the private stroke. Calling it again does nothing. Afterwards, changing it (snapshot, add, pop, assignments) raises DestroyedError. Reading (len, index) still works.
Track(points=list(contrail), smooth=0)—TrackFreezes the current shape for move_along — no special API.

Don't confuse

Looks likeIt isIt is not
Contrail is a Tracka History with a minimal private stroke. No move_along / presets / begin/end.Track(points=…)
line_join="round" curves the trailonly a rounding of the polyline's corners (smooth=0). The curve is smooth=1.Catmull-Rom
fade= paints the head opaquea multiplier on the color's alpha — head = your alpha, tail → 0.an absolute ramp up to 1.0
Sampling set in the constructordst.every(0.05, lambda: trail.snapshot(dst)) — the rhythm is separate from the storage. The timer belongs to the object being read.sample(...) / record(every=) / Graphic.contrail(...)
The module's every samples the herohero.every(...), which stops on destroy and pauses with active = False. The module's every raises DestroyedError on its next firing and does not pause when the object is parked. A bare every fits mouse or the body of a mode.the framework retiring the timer silently
A teleport continues the stroketrail.clear() together with the new position — otherwise the next sample draws a streak from where it was.the framework guessing the jump was a teleport
snapshot after destroy, or of a destroyed sourcea DestroyedError. Cancel the handle when you destroy the Contrail; tie the timer to the source with e.every.nothing happens / the last point
Circles / segments in a ContrailHistory with add(Circle(...)) / add(Line(...)).shape_factory= / add on the Contrail

Text

A piece of text on screen — a score, a caption, a title. It stays fixed to the window (HUD) or sits in the world with the objects, depending on how you place it (table below). The box follows the text (or has a fixed width=) and grows downward.

Text("SCORE")                                   # HUD, in the automatic column
st.score = 0
hud = Text("", top_left=(20, 780), font_size=20)
hud["text"] @= lambda: f"Stars {st.score}"
Text("HP", center=ship.center)                  # in the world, moves with the camera
Text("GAME OVER\nPress SPACE", center=(500, 400))
Place withWhere it goes
nothing (just the text)The ui layer, in the automatic column — the same stack as the widgets. stack=False keeps it out of the column.
top_left= / top_center= / top_right=Pins that point of the box; the text grows away from it (always downward) — a new line or a larger font_size does not push the top. With layer left out: the ui layer (and it advances the column). With layer="default": a caption in the world.
center=Without layer=: in the world (default), moves with the camera. With layer="ui": on the window.
box=The box's center at the region's center, the region's width. Out of the column. Prefer canvas.ui_view.

Lines. \n is a hard line break (height = n × the line metric). Without width= the box follows the widest line; with width=, whatever does not fit is cut off (no automatic wrapping). align= aligns each line inside the box and never moves the anchor. The HUD column does not rearrange itself if the number of lines changes after the Text is built.

st.score = 0
score = Text("", top_right=(980, 780), font_size=20)
score["text"] @= lambda: f"{st.score}"
Text("READY", top_left=(20, 720), width=160, background="maroon")
Text("Kills 3\nTime 1:02", top_right=(980, 700), align="left")
Text("HP 100/100", center=ship.center, width=120, align="center")

# follow another object: a lambda in the point (or in one axis)
panel = Rect(center=(500, 300), width=300, height=120, layer="ui")
Text("Menu", top_left=lambda: panel.top_left)
Text("x", top_left=(lambda: mouse.x, 760))
Text constructor

Text(text, top_left=, top_center=, top_right=, center=, box=, width=, align=, layer=, font=, font_size=, color=, background=, glow=, stack=, group=, angle=)

1st: the text, or a field it shows (st["score"]). Leave out center=/layer= → the ui layer + the automatic stack (the same as the widgets'). center= without a layer → the default world layer. A point (top_left= …) on the ui layer also advances the column. There is no x1= / y1= / pos=: the error points to the point.

ParameterPassType (default)Meaning
text1ststr, field or function"SCORE"The text; or a field (st["score"]), which the Text shows and follows one way only (like t["text"] @= st["score"]: t.text = … raises LinkedAttributeError; to change what shows, change the field); or a function, which links. A number raises an error: write a string (Text(str(n))). Text(st.nickname) is the text as it is now and does not follow; the field is st["nickname"]. Reading t.text gives the text that shows now, a str like any other (it works as a dictionary key, in in, in join), also when it is linked; the link is t["text"] (t["text"] @= …, t["text"].unlink()).
top_left= / top_center= / top_right=name=point(20, 780)Only one. Pins that point of the box (the visual top); the text grows downward and away from it — a new line or a larger font_size does not push the top. With none: the column's stack. layer left out → ui (advances the column); layer="default" → a caption in the world, out of the column. A value is copied; a lambda links, as in Rect(top_left=): top_left=lambda: panel.top_left, or a mixed tuple (lambda: mouse.x, 760) (only x links). A Point you pass is copied. Moving (move_by, move_to, time=, tween, dragging) takes the point along; move_to(x, y) puts the middle of the current string at (x, y). With a linked anchor, moving raises LinkedAttributeError (use t["top_left"].unlink()).
width=name=number120A fixed box. Left out → follows the string. Whatever does not fit is cut off (no wrapping). \n is a hard line break (height = n × the line metric). The column does not rearrange itself if the number of lines changes later.
align=name=str"left""left" / "center" / "right" (or XPos.LEFT / XPos.CENTER / XPos.RIGHT). Aligns each line inside the box (width= or the widest line); never moves the anchor. The default follows the anchor: top_left → "left", top_right → "right", top_center / center= / box= → "center". Any combination works (e.g. a block at top_right= with its lines aligned left).
stack=name=boolTrueFalse: the Text stays out of the HUD's automatic column (useful for an FPS counter). Default True on the HUD.
center=name=point(400, 300)Pose in the world (or on the window if layer="ui") — the center of the box
box=name=Boxcanvas.ui_view.inset(24)The box's center at the region's center (center= on ui), the region's width if left out. Out of the column. Do not mix with center= / top_left= …. Prefer ui_view. box=.
font= / .fontname=str"pixel.ttf"An installed family, or a .ttf / .otf file (found the same way as an image). Left out, it uses ui.font. .font returns the font's name (a string). Assigning it measures the text again. A missing font: a warning and the default one. No bold / italic.
font_size=name=number13Height of the letters, in design units. Left out: the theme's (13 × ui.scale). Takes lambda:.
color=name=color"white"Color of the letters. Later: set_color(…) or .fill = Gradient(…).
angle=name=number0Turn in degrees, around the center of the box. Takes lambda:.
background=name=color"maroon"An opaque plate behind the text, the size of the box.
glow= / .glowname=bool or color or GlowTrueThe only add-on. True / a color / Glow / CheapGlow. No visual (.visual).
.fill / .line—color or GradientGradient("sunset")Fill / outline (a Gradient works)
.top_left / .top_center / .top_right / .center—Pointscore.top_rightPoints of the current box as drawn — turned and scaled about the center (the read already sees the current string). The anchor writes; the others are derived (writing raises an error). rotate_by / scale_by turn about the center and take the anchor along (an anchor linked with a lambda raises an error; force=True unlinks it). Text does not mirror: flip_x / flip_y = True raises an error (mirrored text cannot be read). To follow it: Line(p1=lambda: score.top_right, …).
.box—Boxhud.box.heightA copy of the layout box (to measure it, to place something beside it).

Don't confuse

Looks likeIt isIt is not
Text(…, layer="top") stays fixed to the windowthe "top" layer, which still moves with the camera. HUD: layer="ui", or leave out center=.HUD
align="right" pins the right edgealign= only aligns the lines inside the box. To pin the right edge: top_right=.anchor
Text for the player to type inText only shows. To type: TextInput. A Slider's label is still label= (a string). The automatic column: ui.stack_reset / stack_origin / stack_from / stack_column.an input box

SpatialFx

A SpatialFx is an effect that sits at a place in the world — a campfire, rain over an area, a portal, a jet. Like a Shape, the constructor already puts the effect on screen, and it has a layer, groups, timers, destroy(), and it can collide (by the area it covers). Unlike a Shape, it has no exact outline and cannot be clicked or dragged.

FamilyEffectsPlacement
PointFire, Sparks, GlowSpot, Orb, Sunburst, Starburst, Warp, Portalcenter= and the size in radius= (the jet Fire uses width=)
AreaRainA rectangle: p1= / p2= (opposite corners) or center=, width=, height=
BeamJetA segment: p1= / p2=, or origin= with angle= and length=

Once it is created, you change its parameters by assignment (fire.amount = 2), and they apply on the next frame. To move it, write or link its center: fire.center = (300, 120), fire["center"] @= lambda: torch.center or tween(fire.center, (300, 120), time=1) — SpatialFx has no move_to / rotate_to. They all take soft_edge=: the width of the fading edge, as a fraction of the size (0 = a hard edge; each effect has its own default). Not to be confused with a visual (it paints an object), a Post (the whole screen) or an Impact (a burst that goes away by itself).

Fire(center=(200, 150))
Warp(center=(400, 220), radius=90, color="cyan")
Rain(p1=(300, 250), p2=(700, 550))

Always by name: Fire(200, 150), at= and x= raise TypeError with the right spelling (center=). shape.visual = Rain() and canvas.effects.add(Fire()) also raise TypeError: the effect is in the world as soon as it is created.

Reading the parameters. color= tints the effect; left out, each effect uses its own color (orange fire, blue Warp…). amount= is the strength: 1 is the default, 0 turns it off, 2 is strong. speed= is the pace of the animation: 1 normal, 2 twice as fast, 0 freezes it. center=, radius=, width= and length= are in design units. All of them change later by assignment: fire.amount = 2. The numbers (amount, speed, twist, glow…) also link and tween like radius: fire["amount"] @= lambda: st.heat, tween(fire["amount"], 0, time=1) (that is how an effect fades out or in), or amount=lambda: … when you make it.

Entity

Entity() creates a game object that draws nothing: a wave director, an enemy spawner, a clock. It has everything the other objects have — own fields, timers, mode, groups, on_update — except the drawing. Shape, Sprite and SpatialFx are Entities too; this constructor is the one that does not paint. Like a drawn shape, it lives until destroy() or until the end of the act, with or without a variable: Director() alone on a line is enough.

director = Entity()
director.after(1.5, start_wave, name="wave")

class Director(Entity):
    def setup(self):
        self.wave = 0

    def on_update(self, dt):
        if ready("spawn", 1.2):
            start_wave()
Entity constructor

Entity(layer=, group=)

A name with =: pass it by name.

ParameterPassType (default)Meaning
layername=str or NoneNoneNone = out of the drawing list (the usual choice here).
groupname=str or list or NoneA tag, or a list of tags. E.g. group="wasp".
class Spawner(Entity):
    def setup(self):
        self.timer = 0

spawner = Spawner(group="spawners")
# No drawing (a plain Entity): only timers, mode and on_update.
# group lets you find them all with group["spawners"].
Entity reference

Properties

PropertyType (typical value)Read/WriteMeaning
.layer / .groupstr"hud"read / write.layer (str or None), .group (write a str or a list; reads a read-only frozenset — .group.add raises AttributeError, use tag / untag). The same as on every object on screen.
activeboolFalseread / writeParks it: hides and pauses it. With no drawing, visible hardly matters. To remove it: destroy().
modemode or Nonee.mode = e.divingread / writeA chapter of behavior. See Mode. The same mode again does nothing.
own fieldsAttributeself.hp = 3read / writeAn attribute created in setup (self.hp = 3) becomes an Attribute. Keeping values.

Methods

MethodSignatureReturnsMeaning
destroy()No parameters—Removes it. With no drawing, visible hardly matters. .active becomes False.
cancel_process()No parametersselfCancels timers / tweens / sounds / mode; the Entity stays alive. The mode becomes None without @exit_mode. See scope.
goto_mode(fn)Parameters: fn (the chapter's function)—Forces exit + entry, even if it is already in that mode. See Mode.
after / everyParameters: delay or interval (seconds), fn (function)HandleTimers on this Entity — they survive a mode change; they die on destroy / cancel_process. See scope.
tweenParameters: target (Attribute or Point), to (the same type as the current value)HandleInterpolates an Attribute / Point on this Entity (number, tuple, Vec2, Color…). See tween.
setup(self)Parameters: self (this object)—After the constructor. The own fields are born here: self.hp = 3. Write setup, not __init__: an __init__ that does not call super().__init__(**kwargs) raises TypeError when the object is created.
on_update(self, dt)Parameters: self (this object), dt (number)—Every frame, on this Entity. See Frame.
on_destroy(self)Parameters: self (this object)—Once, from inside destroy(). It does not fire on a mode change.
Subclassing Shape / Sprite / SpatialFx / Text

Parameters on the class line become the defaults of that type. The pose (center, layer) stays on the instance. It works the same for a spatial effect — class Energy(Orb, radius=16, color="gold", group="energy") — and for a text: class Scoreboard(Text, font_size=32, color="gold", group="hud"), and Scoreboard("0", top_left=(20, 580)).

class Bolt(Circle, radius=8, color="gold", group="bolt"):
    def on_update(self, dt):
        self.move_by(0, 560 * dt)
Bolt(center=(x, y))

class Ship(Sprite, source="playerShip1_blue.png", height=48, group="ship"):
    def setup(self):
        self.hp = 3
Ship(center=(x, y))
Goes on the classDoes not
color visual groupcenter layer
Size: radius width/height length/anglePose per instance (center=)
Sprite: source= frame= height=class Bolt(Circle): radius = 8 — TypeError on the class: it goes on the class line
Text: font_size font color background glow align width groupThe text and the position (center top_left … box layer stack angle)
—Widgets, Entity, Endless: no class parameters (an error with the fix); pass them on the instance
SpatialFx: the type's parameters (radius amount color length…), group soft_edgePoints (center p1 p2 origin); Fire's style= — it picks another class: write Fire(style=…)

Don't confuse

Looks likeIt isIt is not
class Bolt(Circle): radius = 8parameters on the class line, not attributes in the body. A value in the body with a Scena name (radius = 8, visible = False, group = "x") raises TypeError when the class is defined, with the fix: the class line (class Bolt(Circle, radius=8)) or setup (self.visible = False).—
def __init__(self): in a subclassa replacement for Scena's constructor. What the object does when it is born goes in def setup(self):, which Scena calls with the object ready. An __init__ of your own (for your own parameters) takes **kwargs and calls super().__init__(**kwargs); without that call, creating the object raises TypeError with the fix.—

Where else to look — Place · Appearance · Move · Geometry

Appearance

How an object looks on the screen: its color and material (solid color, gradient, image), how it blends with what is behind it, the lasting effects (visual, add-ons, filters) and the passing ones (transients). Color, Gradient and Texture only appear once applied to an object — in .fill, .visual or set_color.

Color / Gradient / Texture → Color / Gradient
Choosing colors (ramp, palette) → Palettes and ramps
Blend → Blend
.glow / .shadow / .tail → Add-ons
Neon / Halo / … → Visual
Death / hit / knock → Transients
Blur / DropShadow → Filters

Color / Gradient / Texture

Three ways to paint: a solid color (Color or just its name, "coral"), a gradient (Gradient) or an image (Texture). On their own they do not appear: they go in .fill, .visual, set_color or canvas.background. RGB is 0–1. A name that is almost right ("blu"): a warning + the closest color ("blue"). An unknown name: a warning + magenta, with Did you mean. To choose colors (ramps, palettes): Palettes and ramps.

Wherever the framework asks for a color (color=, set_color, Glow("cyan"), canvas.background = "navy", Text(..., color=) / background=), any of these forms works:

FormExample
Name"coral" · "dark red" · "sky blue"
Hex"#33ccff" · "#RRGGBBAA"
RGB 0–1(0.2, 0.4, 0.8) · (0.2, 0.4, 0.8, 0.5)
ColorColor("cyan") · Color(0.2, 0.4, 0.8)
c = Circle(color="coral")
c.set_color("tomato")
c.fill = Gradient("sunset", angle=-90)
c.fill = Texture("tex2.png", fit="tile", tile_size=40)
Color("cyan")
Color(0.2, 0.4, 0.8)
Color("#33ccff")
Color.from_hsv(0.55, 0.8, 0.9)
Color.random()
Color("red").jitter()
c.set_color("navy")
c.set_alpha(0.8)
gold = Color("gold").lighter(0.15)

Color harmonies: triadic, analogous, shades, contrast_color, muted_version.

Color reference

Immutable: lighter / with_alpha / jitter return a new Color. A color is shared (every shape with the default color uses the same one), so color.alpha = 0.5 raises AttributeError with the fix: color.with_alpha(0.5) or shape.set_alpha(0.5).

A color compares by value, however it is written: ball.color == "red", == "#ff0000" and == (1, 0, 0) are True, and print shows the channels. In a set or dict of strings it is not found (its hash is the value's, not the string's): ball.color in {"red", "blue"} gives False. Compare with a list (in ["red", "blue"]) or use Color("red") as the key; Scena warns when it sees .color in {"…"}.

Properties

PropertyType (typical value)Read/WriteMeaning
.rgbtuple(1, 0.8, 0, 1)readTuple (r, g, b, a) in 0–1.
.alphanumber0.8readAlpha 0–1. A different alpha: with_alpha(a) (a new Color) or shape.set_alpha(a).
.hsl / .hsv / .brightnesstuple or number(0.5, 0.8, 0.6)readRead-only. HSL/HSV: (h, s, l|v, a).

Methods

MethodSignatureReturnsMeaning
Color(name) / Color(r, g, b[, a]) / Color("#RRGGBB")Parameters: r, g, b, a (numbers 0–1), or a color name / "#RRGGBB"ColorConstructor. Color(None) is “no color” (false in an if).
Color.from_hsl(h, s, l[, a]) / Color.from_hsv(h, s, v[, a])Parameters: h, s, l|v, a (numbers 0–1)ColorFactories. The hue h wraps around; S / L / V / alpha are clamped. HSV: saturation and brightness apart — good for vivid colors.
Color.from_rgb(r, g, b[, a]) / Color.from_name(name[, a])Parameters: r, g, b, a (channels 0–1) · name, aColorShortcuts, the same as Color(...).
ColorNames.is_known(name) / ColorNames.get(name)Parameters: name (name, str)True/False · (r, g, b)Does the name make a color? It takes the same spellings as Color(name) (capitals, hyphens, joined or apart, dark / light / faded in front: "lightcyan" is "light cyan"; a near typo becomes the closest color, with a warning). get returns the 0–1 tuple; an unknown name: a warning + magenta, like Color.
Color.random(saturation=, value=, alpha=)Parameters: saturation / value (number or (lo, hi)), alphaColorA random hue in HSV. Vivid by default: S=0.65, V=0.85. A range: saturation=(0.3, 0.9).
jitter(hue=, saturation=, value=)Parameters: hue / saturation / value (number, ± half)ColorA nearby color (HSV). Default hue=0.04 (~±14°) — reds stay red. Widen it for “warm tones”. A gray stays gray (only the value varies).
with_alpha(alpha)Parameters: alpha (number 0–1)ColorA copy with another alpha.
lighter(amount=0.1) / darker(amount=0.1)Parameters: amount (number)ColorA copy with the lightness (HSL) amount higher / lower; hue and saturation stay. amount defaults to 0.1.
saturate(amount=0.1) / desaturate(amount=0.1) / hue_cycle(amount=0.1)Parameters: amount (number)ColorA copy. amount defaults to 0.1. saturate on a gray returns the same gray (gray has no hue).
vibrant_version(amount=0.5) / whiter_version(amount=0.4)Parameters: amount (number)ColorMore neon (HSV; a gray stays gray, only lighter) · a mix toward white. Defaults 0.5 / 0.4.
Color.interpolate(color1, color2, t, color_space=)Parameters: color1 (Color), color2 (Color), t (number), color_space (ColorSpace)ColorA mix. t is usually 0–1. Default ColorSpace.OKLAB (even to the eye — plain RGB passes through gray/brown in the middle). Also: HSL / HSV (the shortest way around the hue circle; a gray end takes the other end's hue, so white → blue stays bluish) · RGB.
a.lerp(b, t)Parameters: b (Color), t (number)ColorInstance shortcut for Color.interpolate (OKLAB). Used by lerp / tween.
complementary()No parametersColorThe opposite color on the circle.
Gradient("sunset")
Gradient("navy", "cyan", angle=90)
Gradient("plasma", type="radial")
Gradient("heat", type="radial", size=700)
c.fill = Gradient("sunset", angle=-90)
brick.visual = Gradient("ruby")          # fill + a darker outline
g = Gradient("ocean").darker(0.15)     # a new ramp (each stop)
Gradient reference

Gradient(*colors, type="linear", size=, angle=0)

A name without =: the colors in order (a preset, two colors, or a ramp). The rest by name.

ParameterPassType (default)Meaning
*colors1st, 2nd…str or Color"rdyl"A preset name, or the ramp. One color: dark → light.
typename=str"linear"linear · radial · sweep.
anglename=number0Degrees. Linear and sweep. 0 = from left to right; 90 = from bottom to top (the first color at the bottom); -90 = from top to bottom. The same on a shape and on a Wallpaper. The sky presets ("sunset", "day") start at the top: angle=-90.
sizename=number or Nonefits the objectIn design units. Linear: the distance from the center to each end of the gradient. Radial: the radius. Sweep ignores it.

Properties

PropertyType (typical value)Read/WriteMeaning
.typestr"linear"readRead-only. "linear" · "radial" · "sweep". The same value passed in type=.

Methods

MethodSignatureReturnsMeaning
darker(amount=0.1)Parameters: amount (number)GradientA new, darker ramp: each stop with Color.darker(amount). amount defaults to 0.1 (how much the HSL lightness goes up/down). Type, size and angle stay the same. Use: g2 = Gradient("ocean").darker(0.2) · brick.visual = g.darker().
lighter(amount=0.1)Parameters: amount (number)GradientA new, lighter ramp: each stop with Color.lighter(amount). amount defaults to 0.1. Same geometry as the ramp. Use: g2 = Gradient("navy", "cyan").lighter(0.15).
mean_color()No parametersColorWeighted average of the stops (RGB integral along the ramp). Use: c.line = g.mean_color().darker(0.2).
set_alpha(alpha)Parameters: alpha (number 0–1)GradientAlpha on every stop (mutable, in place: it changes the shapes that use this Gradient). Unlike darker / lighter, which return a copy. shape.set_alpha(a) gives the shape a new Gradient and leaves the others alone.

A material: it must be applied in .fill, .visual, set_color or canvas.background. On a Shape with an area, visual = Gradient(…) / set_color(Gradient(…)) / Paint(Gradient(…)) fills it and draws an outline with mean_color().darker(0.2) (the line_width thickness does not change). Paint(g, line=False) or Fill leave the outline out. Texture / ProceduralFill stay fill only.

Texture("tex2.png")
Texture("tex2.png", fit="cover")
Texture("tex2.png", fit="tile", tile_size=40)
Texture("tex2.png", shift=HueShift(amount=0.33))
Texture reference

Texture(source, filename=, image=, fit="cover", tile_mode=, scale=1, tile_size=, angle=0, color=, shift=)

A name without =: 1st in order (a file or an image). The rest by name. Lookup: Image files.

ParameterPassType (default)Meaning
source1ststr"tex2.png"The image file (PNG / JPG). Lookup: Image files.
filename / imagename=str / Skia imageNoneInstead of source: the path by name, or a Skia image already loaded. Rare — the usual way is the 1st argument.
fitname=str"cover"How the image fills the shape: "cover" (covers it all, crops what is left over) · "contain" (fits whole, leaves a border) · "stretch" (stretches on both axes) · "tile" (repeats in tiles of tile_size). The same names as the Wallpaper.
tile_sizename=number or (w, h)40With fit="tile": the size of each tile, in design units. With another fit it is a TypeError (it would change nothing).
scalename=number1Extra zoom on the image (greater than 0): 2 shows the image at twice the size.
anglename=number0Turns the image, in degrees, counterclockwise (like the Gradient's angle): inside the shape, or on a Wallpaper around the center of the screen (with fit="tile", around the world's (0, 0) point). Turned, a "cover" image leaves the corners empty; tile_mode="mirror" fills them.
shiftname=HueShift or RecolorHueShift(amount=0.33)Changes the colors of the pixels: HueShift turns the hue; Recolor swaps one band of color for another. See Add-ons / Visual.
colorname=colorimage averageIt does not paint the image: it is the color the visuals use as the “object's color” (the glow of a Neon, for example). Left out: the average of the visible pixels.
tile_modename=str"decal"What shows outside the image: "decal" (nothing, transparent) · "clamp" (stretches the last row of pixels) · "repeat" (repeats) · "mirror" (repeats, mirroring). Left out: "repeat" with fit="tile", otherwise "decal". In tile, "clamp" becomes "repeat".

Properties

PropertyType (typical value)Read/WriteMeaning
.fitstrreadRead-only. The same value passed in fit=.
.tile_modestrreadRead-only. The same value passed in tile_mode=.
pond = Rect(center=(300, 120), width=240, height=60)
pond.fill = WaterFill()                     # water seen from the side
pond.fill = WaterFill(kind="top", speed=0.5)  # seen from above, slower
torch = Circle(center=(100, 200), radius=30)
torch.fill = FlameFill()
torch.fill = WaveFill("teal", amount=0.8)   # liquid of any color
torch.fill = AuroraFill(color="lime")
torch.fill = SwellFill()
Procedural reference

Ready-made animated fills. They go in .fill (or set_color); the outline stays your own. They are the material behind the visuals Water / Flame / Swell / Wave / Aurora — use the visual when you want the whole effect (border, glow), and the fill when you want only the inside.

FactorySignatureReturnsMeaning
WaterFill(kind="side", amount=1.0, speed=1.0)Parameters: kind ("side" / "top"), amount (number), speed (number)ProceduralFillWater. "side" = a platform seen from the side (surface on top); "top" = a pond seen from above.
FlameFill(amount=1.0, speed=1.2)Parameters: amount (number), speed (number)ProceduralFillFire rising inside the shape.
SwellFill(amount=1.0, speed=1.0)Parameters: amount (number), speed (number)ProceduralFillAn abstract flow (not water seen from the side).
WaveFill(color=None, amount=1.0, speed=1.0)Parameters: color (color), amount (number), speed (number)ProceduralFillA body of liquid of any color.
AuroraFill(color=None, amount=1.0, speed=0.9)Parameters: color (color), amount (number), speed (number)ProceduralFillVertical aurora bands, of any color.
ProceduralFill(kind=, amount=1.0, speed=1.0, seed=0.0, color=None)Parameters: kind (shader name), amount, speed, seed (numbers), color (color)ProceduralFillThe class behind the factories. Prefer the factories; an unknown kind raises ValueError with the list.

amount is the intensity (0 = off, 1 = default); speed multiplies the animation's time. Fill(…) takes only a solid color: for a visual with a procedural fill, Paint(WaterFill()).

plate = Rect(center=(200, 150), width=120, height=60)
plate.visual = Fill("red")                  # fill only, no outline
plate.visual = Stroke("navy", width=4)      # outline only
plate.visual = Paint(Gradient("sunset"))    # ramp + a darker outline
plate.visual = Paint("coral", line=False)   # color without an outline
Paint / Fill / Stroke reference

Simple color visuals, for wherever a visual would go (shape.visual = …, set_defaults(visual=…)). They are not animated visuals: they only decide fill, outline and thickness.

ClassSignatureReturnsMeaning
Paint(material, alpha=None, *, color=, line=True)Parameters: material (color, Gradient, Texture or ProceduralFill), alpha (0–1), color (the same as material, by name), line (True/False)PaintFill and outline at once, like set_color: the material paints the inside and the outline gets a contrasting tone. With no arguments: steel blue + a contrasting outline. line=False removes the outline.
Fill(color="steel blue", alpha=None)Parameters: color (solid color), alpha (0–1)FillFill only. Gradient / Texture / a visual raise TypeError — use Paint(Gradient(…)).
Stroke(color="black", width=None)Parameters: color (solid color), width (number)StrokeOutline only; width changes the line_width.

Visual and Recipe are the classes behind every visual in the catalog (they are there for isinstance(v, Visual)). You do not build them: pick a ready-made visual.

Color names

The CSS color names work too ("beige", "saddle brown", "midnight blue"), joined or apart. dark / light / faded in front are always Scena's modifier: "dark slate gray" is "slate gray" darkened.

Basics

black
white
red
green
blue
yellow
cyan
magenta

Whites and lights

alice blue
antique white
azure
beige
bisque
blanched almond
cornsilk
floral white
gainsboro
ghost white
honeydew
ivory
lavender blush
linen
mint cream
misty rose
moccasin
navajo white
old lace
papaya whip
peach puff
seashell
snow
white smoke
wheat

Grays

gray
grey
dim gray
dim grey
silver
slate gray
slate grey

Reds

indian red
salmon
crimson
firebrick
maroon
coral

Pinks

pink
hot pink
deep pink
pale violet red
medium violet red
rosy brown

Oranges

orange
peach
tomato
orange red

Browns

brown
chocolate
sienna
tan
sandybrown
sandy brown
peru
saddle brown
burlywood

Yellows

gold
goldenrod
khaki
lemonchiffon
green yellow
pale goldenrod

Greens

forest green
lime
lime green
lawn green
yellow green
sea green
olive
teal
sage
emerald
aqua
chartreuse
olive drab
olive green
pale green
spring green
medium spring green
medium sea green
medium aquamarine
aquamarine

Blues

navy
royal blue
sky blue
deep sky blue
dodger blue
steel blue
cadet blue
cornflower blue
turquoise
midnight blue
medium blue
powder blue
slate blue
medium slate blue
medium turquoise
pale turquoise

Purples

purple
violet
blue violet
indigo
lavender
plum
orchid
medium orchid
fuchsia
medium purple
rebecca purple
thistle

Metallics

silver
bronze
copper
Gradient presets

Harmonious ramps

emerald
ruby
safira
copper
amethyst
deep_ocean
outono
bliz
retrowave
floresta
sakura
citrus
vaporwave
moss
nebula
tropical
cyberpunk
mediterranea
drosa
synthwave
aurora
candy
gold
lava
acid
mana
rainbow
linho
azul_ambar
gotic
terrasol
campo
oliva_areia
azul_creme
creme_ambar
azulejo
marmore
terracota
plasma
magma
vrds
ocean
ylorrd
white_blue
bugn
inferno
heat
grayscale
red
orange
yellow
green
blue
cyan
purple
magenta
rdyl

Through white / specular

neon
beam
flare
chrome

Scales

seismic
coolwarm
cool
brbg
rdbu
health

Scenic

day
dawn
sunset
dusk
night
space
overcast
desert
forest
toxic
ember
ice
underwater

Themed palettes

carrara
deep_blue
mata
vitral
sema
marroco
8bit
papagaio
especiarias
klimt
lisboa
concreto
monet
toscana
chartres
sumie

Don't confuse

Looks likeIt isIt is not
Color(255, 128, 0)ValueError: RGB is 0–1. Divide by 255, or use hex ("#ff8000").0–255
line.set_color("red") paints the fillOn a Line, set_color paints the stroke.fill

Palettes and ramps

Tools to choose colors that go together (they paint nothing). Colormap is a continuous ramp: ask for the color at any point t from 0 to 1. Palette is N colors taken from the ramp, read by an index that wraps around. Both return Color and use the same presets as Gradient.

tints = Palette("plasma")              # 6 colors from the preset
hud.fill = tints[wave_number]          # wrapping index

ramp = Colormap.from_colors("red", "blue")
halfway = ramp.get_color(0.5)          # the midpoint (OKLAB)
Colormap

A color ramp that you sample (it draws nothing on its own). It is the table behind Gradient("plasma") and Palette("plasma"). Create the ramp, then ask for a color at t (0–1). Default interpolation: ColorSpace.OKLAB.

ramp = Colormap.from_colors("red", "blue")
ramp.get_color(0.0)          # red
ramp.get_color(0.5)          # the midpoint (OKLAB)
ramp.random()                # a random color on the ramp

Colormap.from_colors("red", "yellow", "blue")
Colormap.from_preset("plasma")
Colormap([(0.0, "navy"), (0.4, "cyan"), (1.0, "white")])
MethodSignatureReturnsMeaning
Colormap.from_colors(*colors, color_space=)Parameters: colors (name / Color / RGB), color_space (ColorSpace.OKLAB)ColormapA ramp with evenly spaced colors (2 → the ends; 3+ → equal steps). OKLAB by default.
Colormap.from_preset(preset, color_space=)Parameters: preset (name), color_space (ColorSpace.OKLAB)ColormapThe same presets as Gradient, or a color name (dark → light). OKLAB by default.
Colormap([(t, color), …], color_space=)Parameters: colors (list of pairs: position 0–1, color), color_space (ColorSpace.OKLAB)ColormapExplicit stops. OKLAB by default.
get_color(t)Parameters: t (number 0–1)ColorThe color at position t on the ramp.
random()No parametersColorShortcut for get_color(random.random()) — a random color between the stops.
Palette

Discrete samples of a ramp. It draws nothing on its own — it returns Color. The same presets as Gradient. Default: 6 points, OKLAB interpolation. The index wraps around (modulo); get_next() moves its own cursor forward.

Palette(*source, steps=6, color_space=ColorSpace.OKLAB)

A name without =: a preset, a list of colors, or colors in order. steps and color_space by name.

tints = Palette("plasma")              # 6 colors from the preset
tints = Palette("plasma", steps=8)

# a list or loose arguments — the same ramp
Palette(["red", "yellow", "blue"])
Palette("red", "yellow", "blue", steps=5)

# wrapping index: any counter works
hud.fill = tints[wave_number]

# or in sequence, without keeping an index
def spawn():
    Circle(fill=tints.get_next())

# from a Gradient / Colormap you already made
accents = Palette(Gradient("sunset"), steps=4)
Parameter / methodSignatureReturnsMeaning
steps=integer, default 6—How many colors the palette takes from the ramp, evenly spaced from start to end.
color_space=ColorSpace, default OKLAB—How the in-between colors are mixed. ColorSpace.OKLAB (the default) gives steps that look even to the eye; RGB passes through grayish tones in the middle. Also HSL / HSV.
Palette(preset)Parameters: preset (str), steps=6, color_spacePaletteSamples the preset (the same table as Gradient). With no arguments: "plasma".
Palette(["red", "yellow", "blue"])Parameters: list or *colors, steps, color_spacePaletteA ramp with these colors, then steps samples. Also: stops [(t, color), …], a Colormap or a Gradient.
palette[i]Parameters: i (int)ColorThe sample at the index. It wraps around: palette[6] == palette[0] if steps=6. A slice (palette[:3]) does not wrap.
get_next()No parametersColorThe next sample; its own cursor, wrapping. for color in palette goes through once (it is not this cursor).
reset(index=0)Parameters: index (int)PaletteMoves the get_next cursor (modulo). Chainable.
random()No parametersColorOne of the samples, at random (discrete). Colormap.random() samples the continuous ramp.
len(palette) / .colorsNo parametersint / listHow many samples. .colors returns a copy.

Don't confuse

Looks likeIt isIt is not
Color.random() · ramp.random() · palette.random() · color.jitter()Color.random() = any hue (vivid). ramp.random() = a continuous sample of this ramp. palette.random() = one of the N samples. color.jitter() = a variation near one color.the same draw
Palette("plasma")It samples the shared preset table (like Colormap.from_preset)It does not build a Gradient — Gradient paints; Palette returns Color
palette[i]A wrapping index (never IndexError on an int)A plain list — a slice does not wrap; for is finite

Blend

Blend chooses how an object's colors combine with what is already drawn behind it: on top ("normal", the default), adding light ("add", for lasers and glows), darkening ("multiply", for shadows)… The same setting on Shape and Sprite: .blend = "add".

On a Shape, it blends fill and line. On a Sprite, it blends the image (the PNG). Reading it returns the same string. It does not link with @=.

# Shape: a stroke of light (adds to the background)
ray = Line(p1=(120, 80), p2=(280, 240), color="cyan")
ray.set_alpha(0.3)
ray.blend = "add"

# Sprite: a brighter PNG over what is below
ship.blend = "add"

# Ink / shadow (multiplies the colors)
stain.blend = "multiply"

ship.blend = "normal"          # back to normal

"add" brightens even an opaque PNG (it adds the RGB where they overlap). A PNG with alpha (glass, holes) takes part in the mix. sprite.alpha is another setting: it makes the image transparent (0–1) without changing the formula — the two combine.

Everyday

NameDoes
"normal"Default. The source on top, honoring alpha.
"add"Adds the colors. Laser, shot, glow, light particles. Blows out to white where they overlap.
"multiply"Multiplies. Darkens. Shadow, ink, tinted glass.
"screen"The inverse of multiply. Brightens. Smoke, soft glow (blows out less than add).

Contrast

NameDoes
"overlay"Multiply on a dark destination, screen on a light one.
"hard-light"Like overlay, with the source as a hard light.
"soft-light"A soft version of hard-light.

Darker / lighter

NameDoes
"darken"Keeps the darker channel of source and destination.
"lighten"Keeps the lighter channel.

Comparison

NameDoes
"difference"Absolute difference. Invert / compare.
"exclusion"Like difference, with less contrast.
"subtract"Subtracts the source from the destination. Today it paints the same as "difference".

Dodge / burn

NameDoes
"color-dodge"Brightens the destination according to the source. A strong glow.
"color-burn"Darkens the destination according to the source.

HSL (the source's color, the rest from the destination)

NameDoes
"hue"The source's hue; the destination's saturation and lightness.
"saturation"The source's saturation; the rest from the destination.
"color"The source's hue + saturation; the destination's lightness.
"luminosity"The source's lightness; the destination's color.

An unknown name: TypeError with the list. It does not link with @=. Use =. look_like / save_visual / restore_visual copy the blend. A visual (Halo, Neon…) may rewrite the fill's blend while it is on; visual = None gives yours back. sprite.alpha / set_alpha fade only the image — on a Shape, set_alpha changes the alpha of the fill/line. See Appearance and clicks.

Add-ons

Add-ons are five effects added on top of an object's appearance, each in its own property: a glow around it (.glow), a shadow (.shadow), a motion trail (.tail) and, on Sprite only, a turned hue (.hue) and grayscale (.gray). Each is turned on with an assignment and lives alongside the visual and the other add-ons.

PropertyWhat it doesOnShortcuts
.glowA halo of light around the body.Shape, Sprite, TextTrue = a glow in the object's color · a color ("cyan") · Glow(…) / CheapGlow(…) to tune it
.shadowA shadow offset down and to the right.Shape, SpriteTrue · a color · Shadow(…)
.tailGhost copies behind the object as it moves.Shape, SpriteTrue · a color · Tail(…)
.hueTurns the PNG's colors around the hue circle (red → green → blue).Spritea number of turns (0.33 = a third: red becomes green) · True = 0.33 · HueShift(…)
.grayTakes the color out (a disabled button, a character turned to stone).SpriteTrue = all gray · a number from 0 to 1 (0.5 = half gray) · Grayscale(…)

To turn one off, assign False or None. Reading the property returns the settings object (Glow, Shadow…) or None. visual = None removes only the visual: the add-ons stay. save_visual() / restore_visual() save and bring back the add-ons too. CheapGlow also goes in .glow (there is no .cheapglow); assigning Glow / Shadow to .visual raises TypeError with the hint.

ship.glow = True
ship.glow = "cyan"
sting.glow = CheapGlow("tomato", radius=8)
ship.shadow = Shadow("navy")
sprite.hue = 0.33
sprite.gray = True          # gray (a disabled button); 0.5 = half
bolt.tail = True
# no angle=: it follows the motion
ship.tail = Tail(color="gold", size=1.4, amount=1.15)
bolt.tail = Tail(angle=180)
ship.tail = Tail(
    angle=lambda: ship.angle + 180,
    size=lambda: 1.4,
    amount=lambda: 1.15,
)
Text("GO", glow=True)

tail = True and Tail(…) without angle= follow the motion (a trail behind the velocity; it fades when the object stops). Tail(angle=180) locks the direction (90 = up). angle / size / amount take lambda: — evaluated again every frame. Do not use ship.visual = Glow().

Reading the parameters. radius= and offset= in design units; sigma= is how much it blurs (bigger = softer); amount= is the intensity (1 = default); alpha= is the opacity, from 0 to 1.

Visual

A visual is a ready-made look, almost always animated, that changes how an object is drawn — neon, hologram, metal, water, an energy shield. Each object has one visual at a time, in .visual: ship.visual = Neon(). It works with no arguments, in the object's color. The exceptions have their own palette: Metal() is chrome and Shield() is the lime-green bubble, whatever the object's color (and the object's color does not change); Metal("gold") / Shield("cyan") give the color. None removes the visual and goes back to the look from before (the add-ons stay). save_visual / restore_visual bring back the look on the screen (add-ons included).

There are body visuals (Neon, Gel, Sphere, Aurora, Metal, Halo(style="fill")…) and outline visuals (Rim, Laser, Ink, Halo, ElectricBolt, Tracer…). Without color=, a body visual follows the object's color and an outline visual follows the object's outline (.line). The object's color (color=, set_color) gives an outline derived from it — darker on a light color, lighter on a dark one —, and that is the one the outline visual follows: Circle(color="red") with Laser() gives a pinkish laser; for a red laser, Laser("red") or .line = "red". color= in the constructor paints the visual and stays on the object: on a body visual it becomes the object's color, on an outline visual it becomes only the outline (Rim("red") is the same as .line = "red" and then Rim(); once the visual is removed, the inside keeps its own color). Left out, it follows the object (or its own palette, in Metal and Shield). Writing .fill / .line, .line_width, .blend or .dash before or after putting on the visual gives the same drawing. A visual that sets its own thickness, blend or dash (Rim, Halo, Shield, Bolt…) keeps its own while it is on — the Rim's border changes with Rim(width=) — and the value you wrote shows when the visual comes off (visual = None). The rule: a visual that takes color= shows set_color — set_color / .color = recolor every visual that takes color=, whether it was made with a color or not (Neon("red"), Laser, Rim, Halo(style="line")…, Metal, the Shield bubble); a visual without color= keeps the color and warns. A visual is not a transient. A glow on many objects: .glow, not N× Neon.

Each effect states whether it works on Shape, Sprite or both (the chips below and the tag on the panel). In the signature, a name without = is the 1st, 2nd… in order (Neon("cyan")). A name with = goes by name (amount=1.2).

ship.save_visual()
ship.visual = Neon("tomato")
ship.color = "lime"
ship.glow = True
after(0.4, ship.restore_visual, name="bonus")

visual = None ≠ restore_visual(): None goes back to the look without a visual (the add-ons stay); the save / restore pair goes back to exactly the saved look (with the add-ons). One slot per object; use name= in the after to renew the duration.

Reading the parameters. color= tints the effect; left out, it follows the object's color. amount= is the intensity: 1 is the default, 0 turns it off, 2 is strong. speed= is the animation's pace: 1 normal, 2 twice as fast, 0 freezes it. width= is a thickness in design units. Visuals that paint a color of their own (glow, border, body) take color= as the 1st argument; procedural materials (Flame, Swell, Water), pixel operators (Grayscale, HueShift, Recolor) and EmissiveBloom do not — change the color with set_color on the object.

Transients

Transients are short effects on an object: flashing when it takes damage, growing suddenly and going back to size, fading out when it dies, appearing when it is born. You call the verb (ship.flash(0.12)), it ends on its own and the lasting look (.visual) does not change. Each kind of effect has a channel: a new effect on the same channel replaces the previous one, and different channels run together. It works on Shape and Sprite.

The first number = the duration. The rest by name — including style= (when there is one) and on_done= (a callback when it ends or is cancelled). Tabs below: the signature and parameters of each verb.

ship.flash(0.12)
ship.pop(scale=1.2)
ship.knock(distance=16, angle=30)
ship.dissolve_out(0.4, style="vortex", on_done=ship.destroy)
ship.dissolve_out(0.45, style="wipe", angle=0)
ship.dissolve_out(0.35, style="fade")

The first number is always the duration in seconds. Color, scale, intensity, amount, style go by name: pop(scale=1.4), flash(intensity=0.6), dissolve_out(style="noise"). Dissolve style: noise · vortex · wipe · fade. Do not use visual = Neon() just for a flash. A new effect on the same channel replaces the one in progress and calls the old one's on_done right away (the same on_done as a normal end — it is not told that it was cut short). Trigger at the end: When it ends.

ChannelMethodsWhen it ends
lifedissolve_out burn_out fade_out implode dissolve_in fade_indeath: visible=False (hides, does not destroy: to remove it, on_done=shape.destroy); spawn: shows it at the start; on_done
flashflash blinkclears; on_done
textflash_text(text, duration=1, *, on_done=None) — only Text and widgets. Shows text for duration seconds in place of the usual text (scoreboard.flash_text("+100", 0.5))shows the usual text again (if the text is linked to a field, it stays linked); on_done
pulsepulse_outlineclears; on_done
poppopclears; on_done
knockknockclears; on_done
sparkspark_burstclears; never hides; on_done
—clear_transientscancels them all; calls each one's on_done

Reading the parameters. The 1st number is always the duration, in seconds. intensity= / amount=: 1 is the default. on_done= is the function called at the end (or when another effect on the same channel interrupts it).

Filters

A filter works on an object's pixels after they are drawn — it blurs, casts a shadow, thickens, makes them glow. It goes in one of two properties: fill_filter acts on the inside, line_filter on the outline (or on a Line's stroke). It works on Shape, Sprite and Text.

For ready-made effects, prefer what already exists: the common glow and shadow are the add-ons .glow / .shadow; an animated look is a visual; an effect on the whole screen is a Post. The filter is the fine tuning of a single object. None removes the filter. One instance can go on many objects (halo = GlowFilter(…) on a whole fleet costs less than one per object). Two filters together: one's input= takes the other, or ComposeFx(outer, inner). A visual or a SpatialFx here raises TypeError.

c.fill_filter = Blur(sigma=4)
c.fill_filter = DropShadow(offset=12, sigma=8)
c.fill_filter = None

Reading the parameters. radius=, offset= and sigma= in design units (sigma is how much it blurs). input= chains: the filter acts on the result of another one (Blur(sigma=2, input=DropShadow())).

The filter goes in fill_filter (inside) or line_filter (outline). To make many objects glow, use the .glow add-on or a single shared GlowFilter — not a Halo visual on each one.

Where else to look — Draw · World · Sound

Reactive

Reactive is how you make one value follow another without writing code every frame. c.radius = ship.hp copies the number once; c["radius"] @= lambda: ship.hp links: from then on the radius follows the HP by itself, whenever the HP changes. To run an action when something changes (play a sound, switch levels), use @when / @on_change; to act after some time, Schedule.

Link a field / replace contents (<<) → Link
What can go on the right → What can be linked
A lambda in a for loop → Lambda
A lambda in the constructor → Formulas in constructors
The game's score (st) / HP on the Entity → Keeping values
What else controls a field → Persistent drivers

Link

Three operators put a value in a field. = copies the current value. @= links the field to a formula: Scena redoes the math whenever something the formula reads changes. << copies the values of another object into this one, without swapping the object. @= always takes brackets on the left — c["radius"] @= lambda: … — because c.radius would already be the number, not the field.

st.score = 0
st.lives = 3
st["hud"] @= lambda: f"Stars {st.score}"          # @= creates the field if missing

c.radius = 10
c.radius = other.radius
c["radius"] @= lambda: player.hp * 10
hero["grounded"] @= lambda: "bottom" in hero.touching_sides
line["p1"] @= lambda: rect.top_left
turret["angle"] @= lambda: dial.value
ship["scale"] @= lambda: 1 + 0.2 * st.pulse

# the whole mouse is a point (direct link). .x / keyp still need a lambda — see Frame
cursor["center"] @= mouse
c.center["x"] @= lambda: 1200 if keyp("D") else 800

# copy now
Circle(center=player.center, radius=player.hp)
# live link
Circle(center=lambda: player.center, radius=lambda: player.hp * 10)

# << : replaces the contents; the object on the left stays the same
pos = Vec2(0, 0)
pos << Vec2(50, 50)          # same pos; new values
c.center << other.center     # other stays in the game
# c.absorb(other)            # this one does remove other

c["radius"].unlink()
c.unlink_all()
Rules
CaseMeaning
=Copies the current value. No link afterwards.
<<Replaces the contents inside the object on the left (A << B). A is still the same object (whoever kept it sees the new values). It does not link. A linked field: the same LinkedAttributeError as =. Across types, it copies what the target can be: ellipse << hero.box fills the box (like Ellipse(box=)), rect << square; anything else refuses with the fix (Circle(box=region)). It is not absorb (that one copies and destroys the other).
["field"] @=Links. Right side: something reactive from Scena, or a callable. A bare number or expression: TypeError — use lambda: player.hp * 10.
ConstructorBare argument = copy. Callable = link. Details: Formulas in constructors.
ship.field @=Not the same as the bracket: Python reads ship.field first. On a scalar field (ship.hp, p.x) that is already a float — Python's own TypeError, with no Scena message. Prefer ship["field"] @= lambda: ….
.unlink() / unlink_all()c["radius"].unlink() frees that field from its formula; c.unlink_all() frees every linked field of the object (and of its parts, like center.x).
Linked field + = / <<LinkedAttributeError. Unlink first. In the pose verbs / tween: the same, unless force=True (warns and frees it) — Move. The same family of error applies when another persistent driver already controls the field.
WidgetThe 1st argument is the field the widget reads and writes (Slider(st["volume"]), linked both ways). It is not @=.
A lambda that reads nothing Scena tracksTypeError — the formula must name something reactive (see What can be linked). It does not freeze silently.

Don't confuse

Looks likeIt isIt is not
A << Ba copy of the values of B into A. A is still the same object. B stays where it was.@= (it does not link) · A = B (swaps the Python reference) · absorb (copies and destroys the other)
c.absorb(other)c << other followed by destroy(other).<< alone

What can be linked

On the left of @= goes the field that will change; on the right, the formula — usually a lambda:. The formula must read at least one thing Scena tracks (a field, an object, st, clock, keyp, mouse): that is how Scena knows when to redo the math.

The right side must name something Scena tracks. A plain Python variable does not say when it changes: @= refuses it with TypeError.

What is reactive (it can appear on the right and trigger updates):

  • Point, Vec2, Shape (Circle, Rect, Line, …), Sprite, Entity — and their fields (c.radius, ship.center, hero.hp…)
  • st (and any State) — st.score, st.lives…
  • clock, keyp, mouse — frame input (always inside lambda:)
  • mic.level, audio.level, h.level (from a play_sound) and their .spectrum() — sound measurements, updated once per frame (Microphone)
  • A standalone field: Attribute(0.0)

Fields you create on an Entity join this world by themselves — Keeping values.

Canonical forms

The two everyday spellings. The expression on the right returns something that fits the target, and names at least one reactive object:

# thing["field"] @= lambda: expression that fits the field
dst["xyz"] @= lambda: src.abc

# Point: a lambda that returns the pair
circle1["center"] @= lambda: (a.x * 2 + 10, b.abc / 2)
# a pair of lambdas (one per axis) — the constructor spelling:
# Circle(center=(lambda: a.x * 2 + 10, lambda: b.abc / 2))

The general rule, day to day:

thing["field"] @= lambda: obj1.field_a + obj2.field_b

Concrete examples:

c["radius"] @= lambda: ship.hp * 0.1
hud["text"] @= lambda: f"Wave {st.wave}"
cursor["center"] @= mouse
twin["angle"] @= (lambda h=host: h.angle)

In a for loop, each lambda needs its own object: lambda h=host: h.angle — see Lambda.

Inside the formula, use the dot. The lambda already keeps the math alive: Scena reads st.score in the code and redoes the math when the field changes. Brackets inside it (lambda: st["score"] * 2, f"{st['score']}", c["radius"]) would give the field, not the number: @= (and a constructor's lambda) refuses with TypeError, pointing at the line and the dot spelling. A bracket alone on the right, with no lambda, is the direct link: c["radius"] @= st["size"].

Shorter forms, also valid

They work, but they are not the suggested path. Without lambda, both sides must already be objects Scena tracks (a field, a Point, a Vec2) — Python does not compute the expression first:

thing1 @= src                  # if thing1 and src are Scena objects (Point, Vec2, field)
dst["xyz"] @= src["abc"]       # if xyz and abc are reactive fields
line["p1"] @= rect.top_left    # links straight to the Point on the right, no math
orbit.center @= earth.center

A number or an already-computed expression (host.angle, player.hp * 10) becomes a float before @= sees it — TypeError. Use lambda:.

Named function

When the math has several cases, write a def and link the function (no parentheses). Scena reads the function's code once to learn what it depends on — just like a lambda:

def score_text():
    if st.won:
        return "You win!"
    if st.dead:
        return f"Game over — stars {st.stars}"
    return f"Stars {st.stars}   Lives {st.lives}"

scoreboard["text"] @= score_text       # no () — links the function, not its result
scoreboard["text"] @= lambda: score_text()   # also valid: Scena follows the function

It also works right in the constructor: Text(score_text, top_left=(20, 580)) makes the same link.

You can use if, local variables, len / min / round, math, Scena functions and other functions from the same file (up to 3 levels deep). Scena refuses with TypeError what it cannot see by reading the code — otherwise the link would sit still without warning:

  • for / while / [… for … in …] — the items only exist when it runs. Do it in update().
  • Reading a group (len(group["enemy"])) — use update() or a group formula.
  • Changing a Scena object inside the formula (c.radius = 5) — the formula only reads and returns.
  • An index that changes into a list of objects (balls[st.i].radius) — name the object.
  • Calling a function from another file, getattr / eval, a def or lambda inside the formula, try.

Does not work — a plain Python variable does not tell Scena when it changes; neither does a bare number:

x = 10
c["radius"] @= lambda: x * 2  # TypeError: the formula names nothing reactive

# also TypeError — host.angle has already become a float
# twin["angle"] @= host.angle

# right: brackets on the field, or a lambda that names the Shape
twin["angle"] @= host["angle"]
twin["angle"] @= lambda: host.angle

# right: put it in st (or an Attribute) and name that
st.x = 10
c["radius"] @= lambda: st.x * 2

You can create a reactive value by hand, without a Shape:

from scena import Attribute, State

pulse = Attribute(0.0)           # a standalone field, outside any object
hud = State(name="hud")          # another set of fields, like st
hud.level = 0

ring["scale"] @= lambda: 1 + pulse
label["text"] @= lambda: f"{hud.level}"

Don't confuse

Looks likeIt isIt is not
lambda: x + c.radius with a plain xvalid: it updates when c.radius changes (and reads x again at that moment). @= only refuses when the formula reads only plain variables and nothing Scena tracks.frozen
c.radius @= lambda: …an error: c.radius is already a float, so Python raises its own TypeError, with no Scena message. A scalar needs brackets: c["radius"] @= …. A compound value (c.center, a Vec2, an Attribute) accepts thing @=, but the path we teach is the same bracket + lambda.another spelling of the bracket
c["glow"] @= … (visual)a refusal: visuals, add-ons and filters (.visual, .glow, .shadow…) do not link. Use = and on_update / @when. Color and visibility do link: Linked color and visibility.a reactive field
Frame input in @=clock / keyp / mouse always inside lambda: (lambda: clock.time, lambda: keyp("D"), lambda: mouse.x) — never a bare number, nor once / dx. See Frame.the current value
A widget linked to a formulaa control the user's gesture does nothing to: the formula is in charge.a free control
r["damage"] @= lambda: r.width * 2 (a field of the object reading its own size)a known limit: an own field cannot read the size of its own object (width, radius…) nor its computed points (corners, the center of a Polygon) — those come from the whole object, and the new field is part of it. CircularReferenceError with the explanation. Use a property on the class (@property def damage(self): return self.width * 2) or compute it in update(dt). The object's own fields (r.charge), the center of a Rect or Circle and the fields of other objects can be read.a circular reference of your own

Lambda

lambda: keeps the math for Scena to redo later. In a for loop, pin the object: lambda b=ball: b.center.

Without lambda, Python computes right away and Scena gets a number. With lambda:, Scena keeps the math and redoes it when the source changes:

c["radius"] @= lambda: player.hp * 10
cursor["center"] @= lambda: mouse

The lambda looks up the name when it updates, not when you wrote the line. In a for loop, the name ball moves from one circle to the next. In the end, every lambda sees the last one — and every line follows it.

# wrong — all 20 lines follow the last ball
for i in range(20):
    ball = Circle(center=canvas.game_view.center, radius=16)
    Line(p1=(50, 50), p2=lambda: ball.center)

# right — b=ball keeps this ball now
for i in range(20):
    ball = Circle(center=canvas.game_view.center, radius=16)
    Line(p1=(50, 50), p2=lambda b=ball: b.center)

In the body use b.center, not ball.center. The center stays live; only which ball is fixed. If the name never changes (a point1 created once), lambda: point1 is enough — everyone is meant to follow the same point.

A callback that writes an attribute (after, on_done, …): a lambda only takes an expression — an assignment with = does not fit. Use setattr:

# wrong — SyntaxError (a lambda takes no assignment)
# after(1.0, lambda: player.active = True)

after(1.0, lambda: setattr(player, "active", True))
ship.dissolve_out(0.4, on_done=lambda: setattr(ship, "active", False))

If you want the spelling player.active = True

def wake():
    player.active = True
after(1.0, wake)

Formulas in constructors

An object can also be born linked: pass a lambda: instead of a value and the parameter follows the formula, like an @= written right after. A value without lambda is copied once. The geometry parameters (position, size, angle) and the color accept a lambda — layer and tag do not.

Without lambda, Python computes right away and the object is born with that number / point. With lambda:, Scena keeps the math and redoes it when the source changes — the same as an @= afterwards:

# copy now — player can move; this Circle stays where it was born
Circle(center=player.center, radius=player.hp)

# live link — follows the player and the HP
Circle(center=lambda: player.center, radius=lambda: player.hp * 10)

A point takes a lambda that returns the pair, or a pair of lambdas (one per axis). The pair is a constructor spelling; after creation use c["center"] @= lambda: (…, …) or link each axis.

Circle(center=lambda: player.center)
Circle(center=(lambda: a.x * 2 + 10, lambda: b.abc / 2))
p = Point(0, 300)
p["x"] @= lambda: mouse.x                 # one axis linked, the other copied
Line(p1=(50, 50), p2=lambda: ball.center)

The rule is the same in every geometry constructor: callable → link; anything else → copy. A point without lambda (center=player.center) copies — it does not follow. To follow, use lambda: (or @= afterwards).

Who accepts a lambda

General rule: geometry parameters and the color accept lambda formulas. The others do not.

ConstructorParameters that linkDo not link (copy / refuse)
Shape — Circlecenter, radius, perimeter_point, p1, p2, angle, spread, colorlayer, group, box, use_center
Shape — Rect / Square / Ellipsethe model's geometry: center, width, height, angle, top_left, p1, p2, vec, length, color, …corner_radius (does not link), layer / group, box, anchor
Shape — Linecenter, angle, length, p1, p2, vec, dx, dy, dist, colorlayer / group; relations (parallel_to=, circle=…) already watch by themselves — they are not the author's lambda
Shape — Polygoneach vertex in points= (you can mix: some lambda, some copied)the number of vertices (locked at construction)
Shape — Concavethe model's geometry (the Rect's), rim and colorscoop (locked at construction), layer / group, box
Shape — RegularPolygon / Trianglecenter, radius, side, vertex, angle (Triangle: also base_ratio)n= (RegularPolygon; sides: an integer, locked at construction)
Pointthe whole point: Point(lambda: …); one axis: Point(lambda: mouse.x, 0); a pair: Point((lambda: src.x, 10))Point(other_point) copies (does not follow)
Vec2each component: Vec2(lambda: a.x, lambda: a.y); the whole vector: Vec2(lambda: v1 + v2)the result of math already done (Vec2(v1.x, v1.y) copies the floats)
Sprite / Svgonly center=width / height / size (numbers at creation), frame, hitbox, file, color / visual. fps= / cols= / atlas= go in the Sheet. Afterwards: sprite["width"] @= / ["angle"] @= / ["scale"] @=
Textcenter=, color=text= is a string, or a field (st["score"]) that the Text then shows — not a formula. font_size, top_left=. Afterwards: hud["text"] @= lambda: …
Trackcenter, radius, begin, end; each point in points=stroke, smooth, floating
SpatialFx (Fire, Rain, …)center, radius; for directed fire also width, length, anglecolor, style, layer / group
Boxthe same as the Rect's geometry (center, width, height, p1, p2, …)Box is not an Entity. Box(graphic) is a copy, taken now
Entity()—no geometry in the constructor. Own fields afterwards: self.hp = 3 (copy) or self["hp"] @= lambda: … (link)

Visuals, add-ons and the place in the game never link in the constructor: visual=, glow=, layer=, group=. visible is not even a constructor argument (only for Point and Track): write obj.visible = False on the next line. Color links: Rect(color=lambda: …, line_width=lambda: …), Text(…, color=lambda: …, background=lambda: …), Sprite(…, flip_x=lambda: …) — see Linked color and visibility. Widget: the 1st argument is the Attribute it reads and writes, not a lambda.

Don't confuse

Looks likeIt isIt is not
Circle(center=player.center) “follows” the playera copy of the point, taken now. To follow: center=lambda: player.center (or c["center"] @= lambda: player.center afterwards).the same as @=
Sprite(width=lambda: …)a refusal — size in the constructor is a number. Link it afterwards: sprite["width"] @= lambda: ….the Sprite's center=lambda: (that one is valid)
In a for loop, Line(p2=lambda: ball.center)every line following the last ball — pin it: lambda b=ball: b.center. See Lambda.—

Linked color and visibility

Color, visibility and mirroring link too: color, fill, line, line_width (shapes and Text), the Text's background, the Sprite's alpha, visible and flip_x / flip_y. The @= is the = redone whenever the source changes: under a visual, a linked color gives the same result as .color = ….

A health bar made only of formulas: its length and its color follow st.health.

st.health = 100
st.facing = 1
ramp = Colormap.from_colors("red", "lime")

bar = Rect(center=(120, 580), width=200, height=12)
bar["width"] @= lambda: 200 * st.health / 100
bar["fill"] @= lambda: ramp.get_color(st.health / 100)

alert = Text("LOW HEALTH", center=(400, 300), color="red")
alert["visible"] @= lambda: st.health < 20

hero = Sprite("hero.png", center=(400, 200))
hero["flip_x"] @= lambda: st.facing < 0
  • While linked, writing directly raises LinkedAttributeError: bar.fill = …, set_color, set_alpha, visual = Paint(…), a visual with its own color (Neon("red")), fade_out() on a linked visible. bar["fill"].unlink() frees it.
  • On a shape, color writes the fill and the outline: linking color and also fill or line raises on the second link. On a Text, color is only the fill.
  • A formula can read another object's color, but a color is not a link source: b["color"] @= a["color"] raises. Link both to the same formula.
  • A Point links none of these (Scena paints and shows the markers); a Track does not link visible; a Text does not mirror. Visuals, add-ons and filters (visual, glow, shadow…) do not link.
  • The formula's value follows the rule of =: a name, hex or tuple becomes a Color; a negative line_width reads 0 and an alpha stays between 0 and 1, as in any formula.
  • In the constructor, a lambda links: Rect(color=lambda: …, line_width=lambda: …), Text(…, color=lambda: …, background=lambda: …), Sprite(…, flip_x=lambda: …).

Keeping values: st and Entity fields

Two places for your values: st, for the values of the game as a whole (score, lives, wave, options), and fields on the Entity itself, for what belongs to it (HP, grounded, ammo). In both, the field is born on the first write (st.score = 0, ship.hp = 3) and Scena already tracks it: @= formulas, @when and widgets can read from it.

Sprite, Circle, Rect, Line, Text, SpatialFx — and Entity() with no drawing — are Entities. Geometry already exists (center, radius, width…); what you invent is an own field. Score, wave, a game-wide flag: st. HP, grounded, ammo: on the Entity that owns them.

An own field (hp, grounded, wave) becomes an Attribute on the first write. From then on Scena tracks the field: widgets, @=, @when and @on_change can read from it.

st.score = 0                  # creates the field
st.lives = 3
st["hud"] @= lambda: f"Stars {st.score}"   # @= creates the field if missing

ship = Sprite("ship.png")     # a Sprite is an Entity
c = Circle()                  # so is a Circle
director = Entity()           # no drawing, same fields

ship.hp = 100                 # creates the field — already tracked
c["radius"] @= lambda: ship.hp * 10

# @= on the bracket also creates it, if the name does not exist yet
hero["grounded"] @= lambda: "bottom" in hero.touching_sides

ship["shield"] @= lambda: st.lives * 10
st reference

st already exists — it is a State. It holds the fields of the game as a whole. The ship's HP lives on the ship, not here.

You do not construct it. from scena import * already brings the object. Widgets, @=, @when and @on_change read from here. For another separate set (HUD, debug), create another State: hud = State(name="hud"). name is only the label in error messages — it is not a key.

PropertyType (typical value)Read/WriteMeaning
st.score = 0valuest.score = 0read / writeCreates (or writes) the field. st.score reads the value that is there now, like an Entity field: st.mic is None, type(st.score) and best = st.score (a copy) work as with a plain variable.
st["score"]fieldSlider(st["volume"])readThe field: the place where the value lives. It is what links and tracking take: widgets (Slider(st["volume"])), Text(st["score"]), @on_change(st["wave"]), @when(st["alive"]), tween(st["t"], …), @=. Always outside a lambda: inside one, st.score. Used as a number (if st["alive"]:, st["score"] + 1, in an f-string), it raises TypeError with the dot spelling. .value reads the value; .unlink() removes a formula.
st["hud"] @=linkst["hud"] @= lambda: …read / writeLinks that field. @= creates the field if missing (starting value 0). Reading a field that does not exist raises an error.
st.keys() / st.exists("score")names / boolreadLists the fields; tells whether one has been created.
.namestr"st"readA diagnostic label. The global one is "st".
State(name="hud")Statehud = State(name="hud")—Another set of fields, just like st. An empty name raises ValueError.
CaseMeaning
st.keyReads the value. st.key = … writes it. st.f **= 2, st.pos += Vec2(1, 0), st.pos << (3, 4), st.pos.do_rotation(90), st.pos.x = 5 and st.items += [x] write to the same field and notify whatever is linked. st.items.append(x) changes the list without notifying the links (write st.items += [x]); that is why a formula that reads inside a list or dict in st (st.inv["gems"], ", ".join(st.items)) gives a warning when it is linked, and the way that notifies is to write the whole value (st.inv = {**st.inv, "gems": n}) or keep each number in its own field (st.gems). On a field with a formula (st["pos"] @= …), changing the Vec2 in place raises, like st.pos = …. A Vec2 that another st field or one of your fields already holds, or that has a formula, comes in as a copy: st.start = st.pos keeps where it was, and does not move along with st.pos.
Slider(st.volume)TypeError with the fix: st.volume is the current number, and the widget needs the field, st["volume"]. The same for Text, @on_change, @when, until, tween and @= with a Vec2 (c["center"] @= st.pos, st.pos @= …). With a number, st.x @= … gives Python's own TypeError (unsupported operand type(s) for @=): write st["x"] @= …. A string in Text(st.player_name) gives no error: it shows the current name and does not follow it; to follow it, Text(st["player_name"]). Before 0.8.0, st.key returned the field: st.mic is None was always False and best = st.score followed the score.
st["key"] @=The same spelling as geometry. Creates the field if missing (starting value 0). Reading it (st.key, st["key"] on the right) requires that it exists.
Entity fields: create, read and link
CaseMeaning
ship.hp = 100Creates (or writes) the field. It is already a reactive source.
ship["hp"] @= lambda: …Links. Creates the field if missing (default 0).
ship.hp @= …Python's TypeError — use brackets. See Rules.
ship.aim = Vec2(50, 0)A Vec2 in an own field can change whole or in place, and whatever reads ship.aim in a formula sees both: ship.aim = vec_from_angle(30, 50), ship.aim << (80, 0), ship.aim += (10, 0), ship.aim *= 2, ship.aim.x = 70, ship.aim.do_rotation(90). Linking the vector: ship["aim"] @= lambda: … or ship.aim @= lambda: …, the same link (ship["aim"].unlink() drops it, ship["aim"].is_linked tells); a field that holds no vector yet refuses the bracket: write ship.aim = Vec2(0, 0) first. A list or a dict: ship.items += [x] and ship.d |= {…} notify; ship.items.append(x) changes the list without notifying the links, as in st.
ship.foe = enemyAn object in an own field (or in an st field, st.foe = enemy): a formula that reads through it, lambda: ship.foe.radius * 2 or lambda: st.foe.center.x, follows the object the field holds now. After ship.foe = other, it follows other and stops listening to the previous one. With None along the way, guard the read: lambda: st.foe.radius if st.foe else 0. An own field must hold the object when the formula is linked (an st field may be None).
print(ship.hpt)A missing name on read → AttributeError. A typo shows up here, not at = / @=.
Color and visibility (.color, .fill, .visible, .flip_x…)Not an own field, but it links: @= redoes the = when the source changes (Linked color and visibility). Visuals and add-ons (.visual, .glow) refuse @=: use = and on_update / @when.
ship.x = 10Graphic and SpatialFx have no .x / .y — AttributeError, with no field created. Read ship.center.x. Move with move_to / move_by. Link with ship.center["x"] @=. Point.x still exists. A bare Entity still keeps e.x as an own field.

Don't confuse

Looks likeIt isIt is not
st.score and ship.hp are the same idea (a tracked field)different places: the whole game vs this object. Reserved names (visible, layer, center…) do not become own fields.creating ship.score in place of the game's score

Advanced

Persistent drivers

Besides @=, other things also write a field every frame. Only the @= formula is exclusive — the others add up, in any order.

A persistent driver is something that writes the pose (or a field) without the author calling a one-shot verb every frame: the @= formula, mouse dragging (draggable), the wheel (wheel_rotate), a tween / move_to(..., time=) / move_along in flight, or a standing collision resolve(). Only the formula is exclusive: a field linked with @= accepts no other driver (and vice versa), in either order. The others coexist: a move_by(time=) before or after resolve() gives the same result (it stops at the wall), and a draggable shape can have a movement in flight.

DriverWhat it claimsIf you @= on topHow to release
@= (formula)the linked field itself—.unlink() / unlink_all()
draggable / on_drag_tothe parts the drag's move_to writes (e.g. center)LinkedAttributeError right awaydraggable = False (or clear the callbacks)
wheel_rotatethe parts of rotate_by (includes angle)LinkedAttributeErrorwheel_rotate = False
tween / move_to(time=) / move_alongthe target, for the Handle's durationLinkedAttributeError at the @= (not on the next frame)handle.cancel() or wait for the end (with loops="forever", only cancel())
resolve(a, b)usually the center of each sideLinkedAttributeError at the @= or at the resolve itselfunresolve(a, b)
c.draggable = True
# LinkedAttributeError — the center already has a driver (draggable)
# c["center"] @= lambda: src

c.draggable = False
c["center"] @= lambda: src          # now ok

h = c.move_to(400, 200, time=2.0)
# LinkedAttributeError — "move_to(time=2) pushes it"
# c["center"] @= lambda: src
h.cancel()
c["center"] @= lambda: src

resolve(ball, "wall")
# LinkedAttributeError if ball.center is already linked
unresolve(ball, "wall")

enemy.draggable = True
enemy.move_by(200, 0, time=2, loops="forever")   # ok: they coexist
# holding the enemy with the mouse freezes its patrol;
# letting go → it carries on from where the enemy was dropped

Rule: an @= formula against any other driver on the same part → a hard error, in either order (the message names the line where the object was created, e.g. the Sprite made at game.py:151). The other drivers never refuse each other. Holding with the mouse freezes the movements (tween / move_*(time=)) on the parts the drag (or the wheel) writes; on release they carry on, before on_drag_to — so a “go back home” (move_to(home, time=0.3)) in on_drag_to works. While you hold it, the drag also beats what your on_update writes to the object (a per-frame gravity move_by): every frame it goes back under the cursor; on release, your code is in charge again. This is not handle.pause(): h.paused stays yours alone. Redeclaring the same kind (a second tween on the same key, a new @= on the same field) → warns and replaces. force=True still exists only on the one-shot verbs of Move / tween — not on the draggable / wheel_rotate flags.

Don't confuse

Looks likeIt isIt is not
Linking from the draggable center (Line(p1=lambda: c.center) or line["p1"] @= c.center) gives an errorOK — whatever reads the center does not compete with the drag; only what writes to it doeslinking into a draggable center
A linked radius + draggableOK — the drag does not write radiuslocking the whole Circle
move_to / confine in your on_updatea one-shot call by the author — not a persistent driverthe same as draggable / tween

Where else to look — Move (force=) · Collision (resolve) · Handle

Where else to look — Frame · React · Move · UI

World

What belongs to the whole screen, not to one object: the background, effects over the whole picture, bursts that last an instant, the camera, the window and quality, layers and groups.

Background → Background
Vignette / Bloom → Post · flash / explosion_at / fade_out → Impacts
Zoom / pan / frame_to → Camera
FPS / quality → Presentation
layer= → Layers
group["wasp"] → Groups

Background

The screen's background, drawn behind everything. It has a base — a color, a gradient, a sky or an image; always exactly one — and extras stacked on top: stars, clouds, haze, dust. Each background shows up as soon as you create it; keep what it returns to change its parameters, hide it or take it away. A color, a Gradient or a Texture becomes the base when you assign it to canvas.background.

SkyGradient("night")
Stars()
Stardust()
Chromadust()
Nebuladust()
cl = Clouds(amount=0.45)
cl.amount = a * b + 0.5
cl.enabled = False
cl.remove()
canvas.background.remove(cl)   # same
canvas.background.clear()      # extras only; the base stays
canvas.set_fly(Tunnel())
Wallpaper(Gradient("black", "navy", angle=90), pan_response=0.05)
Wallpaper("bg1.jpg", tile_mode="mirror", pan_response=0.15)

Space dust: Stardust (two colors), Chromadust (a palette that cycles; reflect=True makes it go back and forth), Nebuladust (three colors in patches). They are not the SpatialFx Starburst, the Chroma post or Nebula (bands).

canvas.background

Assigning replaces the base. Every background (Wallpaper, SkyGradient, Stars, Tunnel…) already shows up when created. Gradient / Color / Texture must be applied here (or inside a Wallpaper). An image file: Wallpaper("bg1.jpg"). Constructor parameters are attributes of the instance you can assign, and take effect on the next frame — the exceptions for Wallpaper / SkyGradient are below.

canvas.background = "navy"
canvas.background = (0.1, 0.1, 0.15)
canvas.background = Color("black")
canvas.background = Gradient("sunset", angle=-90)
Wallpaper("bg1.jpg", fit="cover")
canvas.background.base = Color(0.05, 0.05, 0.08)

Properties

PropertyType (typical value)Read/WriteMeaning
canvas.backgroundstackcanvas.backgroundread / writeReading it gives the whole background (base + extras), the live one — not a copy. Assigning a color, Gradient or Texture replaces only the base; assigning what you read (canvas.background = canvas.background) changes nothing. To keep the background and go back to it later, keep the base: saved = canvas.background.base … canvas.background = saved.
.baseWallpaperColor("navy")read / writeThe wallpaper. There is always one.
.enabledboolFalseread / writeHides the extras only. The base still draws.

Methods

MethodSignatureReturnsMeaning
.add(field)Parameters: field (a background: Stars, Clouds…)the backgroundStacks an extra. If it is already on the stack, does nothing. It is for a background made with Stars.temp(…) (made without stacking) or taken away with remove. Returns the instance.
.remove(field)Parameters: field (a background: Stars, Clouds…)—Takes an extra away. Calling it again does nothing. Same as field.remove(). The base does not leave this way.
.clear()No parameters—Takes away the extras only. The base stays.
.reset_base()No parameters—The base goes back to the default black.
list(canvas.background)Parameters: the stack (canvas.background)listExtras only, not the base.
canvas.set_fly(Tunnel())Parameters: field (a background, or None)—Clears the extras and keeps that one background. None = just clear.
Wallpaper

The base of the background: a color, a gradient, an image or a Texture covering the whole screen. Creating a Wallpaper already makes it the base (canvas.background.base).

Wallpaper(source, filename=, image=, fit="cover", tile_mode=, scale=1, tile_size=, underlay=, pan_response=0, zoom_response=0, rotation_response=0, scroll=(0, 0), enabled=True)

Name without =: 1st in order (color, gradient, texture or file). The rest by name. No args: opaque black. A string with . or / is a file; otherwise it is a color. Image parameters only apply to a file. Creating a Wallpaper already makes it the base. Search: Image files.

Wallpaper("navy")
Wallpaper(Gradient("black", "navy", angle=90), pan_response=0.05)
Wallpaper("space.jpg", tile_mode="mirror", pan_response=0.15, zoom_response=0.3)
Wallpaper("bg2.png", fit="contain")
Wallpaper(path, fit="tile", tile_size=200, tile_mode="mirror")
ParameterPassType (default)Meaning
source1stcolor or Gradient or file or TextureblackWhat the base is made of. A color name, tuple, Color, Gradient, Texture, file ("bg1.jpg") or Image. A Texture keeps here what it does on a shape: angle, shift and set_alpha. A Visual / SpatialFx / filter raises TypeError. E.g. Wallpaper("navy").
filenamename=strNoneInstead of source: the file path.
imagename=ImageNoneInstead of source: a skia.Image already loaded.
fitname=str"cover"Image only: cover · contain · stretch · tile.
tile_modename=str"decal"Image only: what shows beyond the image's border when the camera moves or zooms out. "decal" (nothing; the underlay shows) · "clamp" (stretches the last row of pixels) · "repeat" (repeats) · "mirror" (repeats mirrored, with no seam). Left out: "repeat" with fit="tile", otherwise "decal". In tile, "clamp" becomes "repeat".
scalename=number1Image only: extra zoom. Must be > 0.
tile_sizename=number or pair of numbers¼ of the shorter sideImage / fit="tile" only: the cell, in design units. With another fit it is a TypeError.
underlayname=colorblackImage only: color of the bands left over in fit="contain" and of everything beyond the border with tile_mode="decal". None = does not paint what is left over.
pan_responsename=number0Response to the camera's pan. 0 = stuck to the screen. 1 = 1:1 with the world.
zoom_responsename=number0How much the camera's zoom affects the pattern.
rotation_responsename=number0Fraction of the camera's rotation.
scrollname=point(0, 0)Drift in design units / s, independent of the camera.
enabledname=boolTrueHides the drawing without taking it off the stack.
fitBehavior
coverScales evenly until it covers; crops the rest.
containScales evenly until it fits; letterbox with underlay.
stretchStretches on both axes.
tileRepeats a cell of tile_size.

A camera that moves: in cover / contain / stretch the image ends at the border. With pan_response, zoom_response or rotation_response, the camera gets there: pass tile_mode="mirror" (the image goes on mirrored, with no seam) or "repeat". Without tile_mode, the underlay (black) shows beyond the border. E.g. Wallpaper("bg1.jpg", tile_mode="mirror", pan_response=0.1).

Assigning a color / tuple / Gradient / Texture already wraps it in a Wallpaper. An image: the constructor itself. fit= on a color raises TypeError. Reading .fit / .tile_mode on an image source gives back the same string. Afterwards: source, the camera settings (pan_response / zoom_response / rotation_response / scroll) and enabled are attributes of the instance you can assign. filename / image / fit / tile_mode / scale / tile_size / underlay stay fixed in the source — to change them, replace .source or build another Wallpaper. wp.remove() on the base raises TypeError; replace canvas.background.base.

SkyGradient

A sky in a vertical gradient (top, horizon, ground), as the base of the background. horizon is the height of the horizon line, from 0 (bottom) to 1 (top). Creating one already makes it the base; the last Wallpaper / SkyGradient created wins.

SkyGradient(palette="day", top=, middle=, bottom=, horizon=0, fade=0.003, pan_response=0, zoom_response=0, rotation_response=0, scroll=(0, 0), enabled=True)

Name without =: 1st in order (the preset). The rest by name. No args: "day". palette / top / middle / bottom stay fixed at construction — to change the ramp, replace the base. horizon / fade / the camera settings / enabled take effect live. sky.remove() raises TypeError.

SkyGradient("night")
SkyGradient("sunset")
SkyGradient("day", horizon=0.42)
SkyGradient(top="navy", middle="sky blue", bottom="navy")
ParameterPassType (default)Meaning
palette1ststr"day"day · dawn · sunset · dusk · night · space · overcast · desert · forest · toxic · ember · ice · underwater. Any top / middle / bottom skips the preset and fills in the rest from day.
topname=colorfrom the presetColor of the zenith (top of the screen).
middlename=colorfrom the presetColor of the atmosphere, at the horizon.
bottomname=colorfrom the presetColor below the horizon (solid). With horizon=0 it does not show.
horizonname=number0The horizon line (0–1, y-up from the bottom). 0 = sky all the way down (middle at the bottom). Line it up with Ground.
fadename=number0.003Blends middle → bottom below the line. 0 = a sharp cut. The same parameter as in Ground.
pan_responsename=number0Response to the camera's pan. 0 = stuck to the screen. 1 = 1:1 with the world.
zoom_responsename=number0How much the camera's zoom affects the pattern.
rotation_responsename=number0Fraction of the camera's rotation.
scrollname=point(0, 0)Drift in design units / s, independent of the camera.
enabledname=boolTrueHides the drawing without taking it off the stack.

canvas.background = Neon() / Rain() / Blur() raise TypeError. A material is not placed on its own: assign it or use Wallpaper(…). SkyGradient.remove() / a wallpaper that is the base: TypeError — replace .base.

Reading the parameters. amount= is density or brightness (1 = default); speed= is the background's own motion (0 = still); alpha= is the opacity, from 0 to 1. The camera settings, on every background: pan_response= 0 keeps the background stuck to the screen and 1 makes it move along with the world (values in between give parallax); zoom_response= / rotation_response= do the same for zoom and rotation; scroll=(dx, dy) is a constant drift in units per second; enabled=False hides it. res_scale= (on the cloud and dust backgrounds: Clouds, ChurningClouds, Stardust, Chromadust, Nebuladust, FilamentField) is the internal resolution (1 = full; lower = cheaper and blurrier).

Post

A Post is an effect over the whole picture of the world, applied after everything is drawn: vignette, bloom, film grain, a CRT screen, light. It stays on while it is in the canvas.effects stack — creating it already stacks it. Keep what it returns to change its parameters, hide it or take it away. For a burst that lasts an instant (a flash, a shake, an explosion at a point, darkening the screen), use an Impact.

Vignette()
bloom = Bloom(intensity=0.8)
bloom.intensity = 1.0
bloom.enabled = False
grain = Grain()
grain.remove()
canvas.effects.remove(grain)   # same
canvas.effects.clear()
canvas.effects

Creating an effect already puts it on the stack. .add is for putting back an effect taken away with remove, or one made with Bloom.temp(…) (which creates it without stacking). The order in which the effects apply is fixed, not the order you created them in: blurs first, then added light, color, overlays, distortions and, last, the special (shader) effects. Constructor parameters are attributes of the instance you can assign, and take effect on the next frame. Impacts (flash, *_at, cover) do not go on this stack.

bloom = Bloom(intensity=0.8)
bloom.intensity = 1.0
bloom.enabled = False          # stays on the stack, does not draw
bloom.remove()
canvas.effects.remove(bloom)   # same
canvas.effects.clear()
canvas.effects.add(bloom)      # puts it back
list(canvas.effects)

Properties

PropertyType (typical value)Read/WriteMeaning
canvas.effectsstackcanvas.effectsreadThe list of the Posts that are on. Creating a Post already puts it here; do not assign canvas.effects = ….
.enabledboolFalseread / writeFalse turns all the Posts off at once. Each effect also has .enabled.

Methods

MethodSignatureReturnsMeaning
.add(effect)Parameters: effect (post)the effectStacks it. If it is already on the stack, does nothing. It is for an effect made with Bloom.temp(…) (made without stacking) or taken away with remove. Returns the instance.
.remove(effect)Parameters: effect (post)—Takes it off the stack. Calling it again does nothing. Same as effect.remove(). The Python object lives on; .add puts it back.
.clear()No parameters—Takes away every post.
list(canvas.effects)Parameters: the stack (canvas.effects)listIn construction order.

ColorWash: after construction the palette is .colors (not color / color2 / color3). Haze.kind only picks defaults at construction — change amount / speed / bias.

Hide a post with enabled, not visible. add(Neon()) is the wrong family.

Reading the parameters. amount= / intensity= is the strength (0 turns it off). speed= is the animation's pace (0 freezes it). target= / center= is a point or an object; left out, it follows the mouse. Sizes in “screen pixels” depend on the window size.

Impacts

Impacts are bursts that last an instant, fired by the canvas: you call one, it happens and goes away on its own — there is nothing to keep or take away. On the whole screen (flash, shake, glitch), at a point (explosion_at and the other *_at) or as a cover that darkens the screen (fade_out / fade_in). The same effect on an object is a Transient; something that stays in a place is a SpatialFx; an effect that lasts on the screen is a Post.

canvas.flash(0.6)
canvas.shake(10)
canvas.explosion_at(x, y)
canvas.fireworks_at(hero)
canvas.zap_at(info.point, style="fork")
canvas.hit_at(info, angle=90)
canvas.debris_at(x, y, color="peru")
canvas.fade_out(0.5, on_done=load_next)
canvas.fade_in(0.5)

*_at take (x, y) or a point (tuple, Point, Vec2, Graphic, info); None does nothing. After a point, the other parameters go by name (amount=, radius=). The cover is drawn after the widgets (over the HUD too) and holds until fade_in; it runs even with clock.paused (it is a screen transition, not game time); canvas.covered is 0…1 (read-only). No then= — only on_done. Iris: fade_out(…, style="iris", center=hero) — center= is a point, copied now (left out = center of the frame).

Reading the parameters. The place comes first: x, y or a point (tuple, Point, object, a collision's info); the rest goes by name. amount= is the strength (1 = default); radius= is in design units; shake= / flash= turn on or off the shake and the flash that come with the effect.

Camera

The camera chooses which part of the world shows in the window: shifting the view (pan), moving closer (zoom) and rotating. It does not move the objects — only the view; widgets and the ui layer stay still in the window. Without time= the change is immediate; with time= it animates and returns a Handle, with the same parameters as Move (ease=, loops=, yoyo=…).

canvas.set_origin("center")
canvas.pan_to(200, 80)                      # x, y
canvas.pan_to((200, 80))                    # tuple
canvas.pan_to(Vec2(200, 80))                # Vec2
canvas.pan_to(boss)                         # Point / Graphic (center)
canvas.pan_by(40, 0)                        # dx, dy
canvas.pan_by((40, 0))                      # tuple
canvas.pan_by(Vec2(40, 0))                  # Vec2 — not Point
canvas.pan_to(200, 80, time=0.8, ease="ease_out")
canvas.pan_to(door, speed=300)               # same speed, near or far
canvas.zoom_to(2.0, about=(mouse.x, mouse.y), time=0.6)
canvas.pan_to(400, 300, time=1.0, loops="forever", yoyo=True)
await parallel(
    canvas.pan_to(boss, time=1.0),
    canvas.zoom_to(2.2, time=1.0),
)
canvas.frame_to(focus, pad=0.1, time=1.2)
canvas.reset_view(time=0.5)

canvas.frame_to(group["fleet"].box, pad=0.15)  # None = stays still
# margin in units (not a fraction): canvas.frame_to(box.outset(40))

Following an object. There is no canvas.follow, and time= / speed= will not do it (the destination is read once, at the moment of the call, and the camera goes to where the target was). Call pan_to every frame in update, with slack (deadzone) and lag (chase; to follow at a fixed speed, approach instead of chase):

def update(dt):
    look = (canvas.pan_x, canvas.pan_y)
    tx, ty = deadzone(look, hero.center, size=(160, 90))
    canvas.pan_to(chase(look, (tx, ty), rate=6.0))

The size of the design space (canvas.width / height) and canvas.playfield: Place › Screen regions.

canvas (camera) reference

Properties

PropertyType (typical value)Read/WriteMeaning
canvas.zoomnumber1readUniform scale. 1 = no zoom.
canvas.pan_x / .pan_ynumber80readThe world point now at the center of the window.
canvas.rotationnumber1readRotation of the view, in degrees.
canvas.game_viewBoxcanvas.game_viewreadWhat the camera sees now, in the world. With the camera still at the start: from (0, 0) to (canvas.width, canvas.height), center in the middle. A new Box on every read. With the camera rotated it is the upright (unrotated) rectangle that holds the view: its corners are off the screen. See Place.
canvas.ui_viewBoxcanvas.ui_viewreadThe whole window, from (0, 0) to (width, height), for the HUD. It does not move with the camera. A new Box on every read.
canvas.cull_offscreenboolTrueread / writeDoes not draw what is out of view. Default True. The objects keep running update and colliding. False draws everything: Presentation.

Methods

MethodSignatureReturnsMeaning
set_origin(where, *, time=None, ease="linear", loops=1, yoyo=False, then=, on_done=)Parameters: where (str), time, ease, loops, yoyo, then, on_done—Pan only. "corner": (0, 0) at the bottom-left corner. "center": in the middle of the window. Zoom and rotation stay. With time=, backgrounds and layers with pan_response follow the camera during the animation, with no jump at the end. No force=.
zoom_to / zoom_byParameters: factor (number), time, ease, loops, yoyo, then, on_done, about—Absolute / multiplies. about= is the anchor point (world): (x, y), Point, Vec2 or Graphic (center). Left out: the center of the view — the pan does not change. Time parameters: time= / ease= / loops= / yoyo= / then= / on_done= / about=. No force=.
pan_tox, y · (x, y) · Vec2 · Point · Graphic; time, speed, ease, loops, yoyo, then, on_done—Puts a world point at the center. Forms: two numbers; a tuple (x, y); Vec2; Point; Graphic (uses its center). Time parameters: time= or speed= (world units per second; the duration is the distance from the current view to the destination ÷ speed) / ease= / loops= / yoyo= / then= / on_done=. Does not take angle + distance. No about= / force=.
pan_bydx, dy · (dx, dy) · Vec2; time, speed, ease, loops, yoyo, then, on_done—Shifts the content. Forms: two numbers; a tuple (dx, dy); Vec2. Not a Point or a Graphic. Takes the same time parameters as pan_to, speed= included (the length of the shift ÷ speed). Does not take angle + distance. No about= / force=.
rotate_to / rotate_byParameters: angle (degrees), time, ease, loops, yoyo, then, on_done, about—Rotates the view, in degrees. about= optional (default: the center of the view); the same kind of point as for zoom. With time=: the short arc in rotate_to; rotate_by uses the sign as written. Takes the time parameters and about=. No force=.
frame_to(target, *, pad=0, rotate=False, time=None, ease="linear", loops=1, yoyo=False, then=, on_done=)Parameters: target (a shape, Box, rectangle or None), pad (number), rotate (True/False), time, ease, loops, yoyo, then, on_done—Frames the target. Target: a shape / Box / tuple (left, top, w, h), or None (nothing to frame: stays still; with time= a Handle that moves nothing for the whole time — it still takes all three motions). pad is a fraction of the target on each side (0.1 → 10%; size × (1+2p)) — the same family as playfield.pad. Negative tightens the framing. Room in design units: frame_to(box.outset(40)), not pad=. A collapsed Box (width/height 0) frames tight, with no error. rotate=True lines up with the target's angle. The destination is read at the start. No force=.
reset_view(*, time=None, ease="linear", loops=1, yoyo=False, then=, on_done=)Parameters: time, ease, loops, yoyo, then, on_done—Takes the camera back to the start: zoom 1, rotation 0, origin at the corner. With time=, backgrounds and layers with pan_response follow the camera during the animation, with no jump at the end. No force=.

time= / ease= / loops= / yoyo= / then= / on_done=: the same as the verbs in Move. about= only on zoom_* / rotate_*. No force= (the camera is not an Entity). Without time=: immediate, returns canvas. With time=: a Handle. yoyo=True needs loops > 1 (or "forever"); with loops=1 it raises an error.

Three motions

The camera has three independent motions: pan, zoom and rotation. Two verbs of the same motion do not add up: the second cancels the first. Different motions run together.

MotionUsed by
panpan_to / pan_by / set_origin. Also zoom/rotation when there is an about=.
zoomzoom_to / zoom_by.
rotationrotate_to / rotate_by.
all threeframe_to / reset_view.
  • Different motions together: pan_to(…, time=1) and zoom_to(…, time=1) (without about=).
  • The same motion: the second call cancels the first.
  • about= pins a world point to the screen — that is pan. Do not mix it with another pan_to (the last one wins).
  • The destination is read at the moment of the call: about= / pan_to / frame_to do not chase a shape.
  • then= only from inside a mode (like the script's tween).

Don't confuse

Looks likeIt isIt is not
canvas.pan_to(hero, time=0.5) follows the heroa destination read at the moment of the call: the camera goes to where the hero was. To follow, pan_to every frame (above). shake is hit feedback, not pan. frame_to(group["…"].box) takes None (an empty group) without a guard.canvas.follow

Presentation

How the game is shown: the window mode (canvas.display), how many frames per second (canvas.framerate), the quality of the effects (canvas.fx_quality) and whether what is out of view gets drawn (canvas.cull_offscreen). By default the window is "windowed" and Scena tunes the rest on its own (FX Auto): it starts at "high" quality at ~60 fps and lowers the quality if the computer cannot keep up. Writing framerate or fx_quality turns that tuning off.

init(width=1000, height=700, window_scale=1.0)
init(width=1000, height=700, display="fullscreen")
canvas.display = "maximized"
canvas.display = "windowed"

canvas.framerate = "vsync60"   # default: locked to the monitor, ~60
canvas.framerate = "vsync30"   # locked to the monitor, ~30
canvas.framerate = "vsync"     # every monitor refresh (144 on a 144 Hz one)
canvas.framerate = 30          # fixed clock at 30 fps
canvas.framerate = "max"       # no cap (bench)

canvas.fx_quality = "high"
canvas.fx_quality = "medium"

canvas.cull_offscreen = False  # draws everything, even what is out of view
canvas.display

The mode of the system window. String. Default "windowed". Assigning sets that mode (it does not toggle). You can assign it before run() (it applies when the window opens) or during the game (it changes at once, like the shortcuts). Read it back to sync a checkbox. Only these three values — no "full" / "max".

PropertyType (typical value)Read/WriteMeaning
"windowed"str"windowed"read / writeDefault. A window in the design's aspect, centered on the desktop. No black bars: the window is the design rectangle. Dragging resizes it with the aspect locked. Starting size: window_scale.
"maximized"str"maximized"read / writeFills the desktop (the taskbar stays). The content does not stretch: black bars fill what is left. The title bar's Maximize button is the same mode. Shortcut: Ctrl+Shift+M.
"fullscreen"str"fullscreen"read / writeCovers the monitor: no border, no taskbar. Black bars fill what is left, as in maximized. Ctrl+Shift+F again goes back to the previous mode (e.g. maximized). Shortcut: Ctrl+Shift+F.

init(display=) does the same as assigning canvas.display. Widgets stay in the design rectangle (not on the bars). The design never stretches.

canvas.framerate

How frames are delivered. String or number. Default "vsync60". Assigning turns FX Auto off; with Auto on, reading returns the current step ("vsync60" or "vsync30"). You can assign it before run(). A wrong value raises an error at once and changes nothing ("vsinc" → Did you mean 'vsync'?). Debug shortcut: Ctrl+Shift+4 (vsync → vsync60 → vsync30 → 60 → 30 → max; the HUD shows the real rate).

PropertyType (typical value)Read/WriteMeaning
"vsync60"str"vsync60"read / writeDefault. Locked to the monitor, at the rate closest to 60: every monitor refresh on a 60 Hz monitor, every other one on a 120 Hz monitor, 72 per second on a 144 Hz monitor. Each frame appears exactly when the monitor redraws (the vblank), always at the same pace, and dt becomes an exact multiple of the monitor's period.
"vsync30"str"vsync30"read / writeLocked to the monitor, at the rate closest to 30 (twice the interval of "vsync60"). It is FX Auto's last resort when the computer cannot keep up (at "low", or at the current quality when what weighs is the game's logic).
"vsync"str"vsync"read / writeOne frame per monitor refresh: the full rate (120 on a 120 Hz monitor). Smoother, but the work per second goes up with it.
a numbernumber30read / writeA fixed clock at that rate (finite, > 0). It does not follow the monitor: motion can stutter for a while when that rate is close to the monitor's. Prefer a "vsync…".
"max"str"max"read / writeNo cap: as many frames as the computer can make. For measuring performance.
canvas.fx_quality

The quality of the visual effects. String or FxQuality (FxQuality.LOW / MEDIUM / HIGH / MAX — the same values as the strings). Default "high". Shortcut: Ctrl+Shift+3 (cycles low → medium → high; max is left out).

PropertyType (typical value)Read/WriteMeaning
"high"str"high"read / writeDefault. Screen effects (Post) at half resolution; effects on objects in full.
"medium"str"medium"read / writeScreen effects at half resolution; SpatialFx and heavy effects in a simpler version. Also: "med".
"low"str"low"read / writeScreen effects at ¼ resolution; light versions of everything.
"max"str"max"read / writeEverything at full resolution. For diagnosis; it is not part of the shortcut's cycle.
canvas.cull_offscreen

Skip drawing what the camera does not see. bool. Default True. Scena tests each object: if its box (with room for glow, outline and effects) does not touch the view, it is not drawn that frame. Only drawing changes: out of view, the object keeps running update, moving and colliding. You can assign it before run() or during the game (an options screen can change it).

PropertyType (typical value)Read/WriteMeaning
TrueboolTrueread / writeDefault. Tests the objects and skips the ones out of view; a layer with parallax (pan_response other than 1) or scroll is tested against its own view (layer.view). Widgets, the background and screen effects are always drawn.
FalseboolFalseread / writeDraws every visible object; whatever is outside the window simply does not appear.

The test costs almost nothing. An object standing still keeps its box until it changes; one that only moves carries its box along. On a layer where nothing (or almost nothing) was out of view, Scena waits a few frames before testing again. So a one-screen game stays practically the same, and a world bigger than the window gets much faster. Measured: a level of 1500 tiles draws in 3 ms instead of 8; the level of tutorial 27 runs ~9% faster; a bullet hell with shots that leave the screen, ~7%. False is there for comparing.

set_fx_auto

set_fx_auto(enabled=True, refresh_hz=None, params=None)

Turns FX Auto on or off: the automatic tuning of quality and fps. On by default ("high" quality at ~60 fps). It measures how long each frame takes and, if the computer cannot keep up, lowers the quality (high → medium → low, at "vsync60") and then the fps (low at "vsync30"). If what does not fit is the game's logic (update, processes, collisions) and not the drawing, lowering the quality would not help: it goes straight to "vsync30" at the current quality (high@30), and only if frames actually miss the vsync. Shortcut: Ctrl+Shift+2.

ParameterPassType (default)Meaning
enabled1stboolTrueFalse turns the tuning off: quality and fps stay where you put them.
refresh_hzname=number or NoneNoneThe monitor's rate for the plan (60, 120…). None measures it on its own.
paramsname=tuning objectNoneAn escape hatch for performance tests. Leave it out.

canvas.framerate and canvas.fx_quality turn FX Auto off (the same as Ctrl+Shift+2). Benches should call set_fx_auto(False) (and usually canvas.framerate = "max"). The design's size: init(width=, height=), read-only in canvas.width / .height. window_scale=1 is the largest windowed window (aspect locked, desktop showing around it) — it is not maximize. Maximize / fullscreen: canvas.display. There is no canvas.maximized / canvas.fullscreen / toggle_fullscreen().

Layers

Layers decide the drawing order: what is on a higher layer appears in front. Three already exist: default (where everything is born), top (in front of the world) and ui (fixed to the window, for the HUD). Create others by number (layer=10: just the position) or by name (canvas.layers.create: with parallax, and a way to hide everything at once). above / below return the number next to a layer.

Circle(center=(100, 100), radius=20, layer=10)   # z=10, created on the spot
Sprite("cloud.png", layer=below("default"))      # behind default
far = canvas.layers.create("far", pan_response=0.15, below="default")
Sprite("mountain.png", layer="far")    # moves at 15% of the camera
Text("SCORE")                          # ui layer (window)
Rect(center=(80, 700), width=120, height=36, layer="ui")
canvas.layers["top"].post_fx = False   # top stays sharp; ui already comes after the post
Layer by number

layer=<int>

The first use creates the layer with z equal to the number (neutral, visible). The same number puts things on the same layer. The z is frozen — the position is its name. A namespace apart from strings: 10 ≠ "10". canvas.layers.create(10) → TypeError (strings only). No parallax parameters — for that, give it a name. Ceiling: z ≤ 100. bool is not accepted. The default layer has the value 0.

above / below

above(name) · below(name)

Global functions (like chase). name is a str or an int and must exist. Returns an int to use in layer=. above() refuses at once (ValueError) a number that lands on top or above it (ceiling: z ≤ 100). below() has no floor.

CallTypeMeaning
below("default")int-1One step below the anchor layer.
above("default")int1One step above.
above(10)int11A numeric anchor works too (once layer 10 exists).
canvas.layers.create

canvas.layers.create(name, z=, pan_response=, zoom_response=, rotation_response=, scroll=, below=, above=)

The name without =: 1st in order (str only). The rest by name. The camera response freezes at creation; only the scroll speed changes later (layer.scroll).

ParameterPassType (default)Meaning
name1ststrThe layer's name. E.g. canvas.layers.create("spawn"). Int → TypeError.
pan_responsename=number10 = stuck to the screen. 1 = follows the world. >1 = foreground.
zoom_responsename=number1How much the camera's zoom affects this layer.
rotation_responsename=number1The fraction of the camera's rotation.
scrollname=point(0, 0)Drift in design units / s, independent of the camera. It adds to pan_response. To start still: create it with a speed and then set layer.scroll = (0, 0) (scroll=(0, 0) at creation leaves the layer neutral).
zname=integer0Order. Or below= / above= — just one. z ≤ 100.
below / abovename=str/int or NoneRelative order: the target's z minus / plus 1. default and top are reserved and neutral. E.g. below="default". Two layers created with below="default" end up at the same z; layers with the same z draw in creation order (the newest on top). To stack them, chain: create("backdrop", below="road").
visiblename=boolTrueWhether the layer is visible when created. Later: canvas.layers["name"].visible.
canvas.layers

Properties

PropertyType (typical value)Read/WriteMeaning
.defaultstr"default"read / writeThe layer objects are built on when layer= is left out (Shape/Sprite; a Text without center= uses ui).
"far" in canvas.layersbool"far" in canvas.layersreadDoes the layer exist? Also: 10 in canvas.layers.
canvas.layers["far"]layercanvas.layers["far"]readThe layer object — see the box below. Also: canvas.layers[10].

Methods

MethodSignatureReturnsMeaning
create(name, *, z=, above=, below=, visible=True, pan_response=1, zoom_response=1, rotation_response=1, scroll=(0, 0))Parameters: name (str); z (int) or above= / below= (layer name); visible (True/False); pan_response, zoom_response, rotation_response (parallax, numbers); scroll (pair)the layerA new named layer (returns the same layer object as canvas.layers["far"]). Parallax freezes at creation. String only.
using(name="far")Parameters: name (layer name)Use in a withInside the with, .default becomes that layer.
list()No parameterslistLists {name, z, visible, object_count} in drawing order.
clear(hard=False)Parameters: hard (True/False)—Removes the objects from all layers. hard=True calls destroy.
canvas.layers["name"] (the layer)

Properties

PropertyType (typical value)Read/WriteMeaning
.visibleboolcanvas.layers["far"].visible = Falseread / writeShows or hides the whole layer.
.zintegercanvas.layers["far"].z = -1read / writeReorders. Not allowed on "top" / "ui" / a numeric layer. z ≤ 100.
.post_fxboolcanvas.layers["top"].post_fx = Falseread / writeFalse: the top layer does not get the Posts (Bloom etc.) and stays sharp. Only works on "top"; ui never gets Posts.
.scrollpointclouds.scroll = (0, 0)read / writeThe drift speed (units / s). It changes without a jump: (0, 0) stops it, chase(clouds.scroll, (0, 0), 3) slows it down. Only on a layer created with a response (pan_response= … scroll=); on a neutral layer it raises an error with the right create.
.viewBoxhills.view.rightreadThe window this layer shows, in its own coordinates. Neutral layer = canvas.game_view; ui = canvas.ui_view; parallax layer = the part it shows now (it moves less than the camera). To create scenery coming in from the right: hills.view.right + 200.
.namestr or intcanvas.layers["far"].namereadThe name (str) or the position (int) — read-only (writing raises AttributeError). To rename: create another layer and move the objects with obj.layer = "renamed".

Methods

MethodSignatureReturnsMeaning
.delete(destroy_shapes=True)Parameters: destroy_shapes (True/False)—Removes a custom layer (named or numeric). default / top / ui cannot be removed.
.clear(hard=False)Parameters: hard (True/False)—Removes the objects of this layer. hard=True calls destroy.
On the object
PropertyType (typical value)Read/WriteMeaning
layer="default" / "top" / "ui"str"ui"read / writeLayers that already exist. ui stays fixed to the window and does not get the Posts. On a click, the order of who answers: widgets, then ui, then the world.
layer=10int10read / writeA position. Created on the spot; z frozen. Also: layer=below("default").
shape.layerstr, int or None"top"read / writeChanges this object's layer.

A parallax layer is decoration: no game physics. Collision / SpatialFx on ui raise an error. top ≠ HUD. A number ≠ a string with the same digits (10 ≠ "10"); a numeric z is frozen; no pan_response on a numeric layer — give it a name.

Endless world

Endless fills the part of a layer that the camera shows: it cuts the axis into cells (slots), builds each cell a little before it comes on screen and destroys the ones left far behind. For runners, flappy games, a ship in a cave, a sky of clouds that never ends. It decides when and where; you decide what.

canvas.layers.create("buildings", pan_response=0.5)
canvas.layers.create("course", below="default")     # a layer of its own, behind the player
Endless("buildings", ["building1.png", "building2.png"], height=300, bottom=80, gap=(40, 200))

def pipes(slot):
    if slot.i < 2:
        return []                                    # empty cell
    middle = slot.rng.uniform(230, 650)              # same cell, same numbers
    return [Rect(top_left=(slot.left, middle - 90), width=70, height=middle - 170, group="wall"),
            Rect(top_left=(slot.left, 800), width=70, height=710 - middle, group="wall")]

course = Endless("course", pipes, step=260)

def update(dt):
    canvas.pan_to(bird.center.x + 120, canvas.pan_y)   # the camera moves
    canvas.playfield.set(canvas.game_view.outset(60))
    st.score = max(0, course.index_at(bird.center.x) - 1)

Pieces: an image path (with height=: the size of each one), a list of paths (one per cell, picked at random) or a function fn(slot) that returns an object, a list of objects or [] (an empty cell). The function builds in the cell's absolute coordinates (slot.left, slot.right…). Endless never moves the pieces.

Random draws: swap random. for slot.rng. (and chance(p) for slot.chance(p)). Each cell has its own draw: going back to a cell builds the same piece. The global random would give a different piece on the way back, without warning. seed= with a number repeats the same world in every run; without seed, a new world every run (.seed tells which one came up).

Endless reference

Endless(layer, pieces, axis=, step=, gap=, start=, seed=, bottom=, left=, group=, height=, width=, size=)

ParameterPassType (default)Meaning
layer1ststr or intA layer of its own, created with canvas.layers.create(...). default / top / ui raise an error: pieces created mid-game would paint over the player. A parallax layer: decoration only (nothing collidable).
pieces2ndpath, list of paths or functionWhat goes in each cell. A mixed list (image + function) raises an error: vary it inside the function with slot.rng.choice([...]).
axisname="x" / "y" / "xy""x"Horizontal (runner), vertical (a ship climbing) or a grid (a map seen from above).
stepname=number, pair or functionNoneThe cell's size. Required with a function. "xy": a pair (width, height). Varied widths: step=lambda slot: slot.rng.choice([160, 320]). Without step (images only): the image's size + gap.
gapname=number or (min, max)0Space after each image; a pair is drawn per cell. Only for images without step.
startname=number or pairNoneWhere cell 0 starts. Default: the edge of the screen when the Endless is born (the first screen comes already full).
seedname=int or NoneNoneSame number = same world. None = a new world every run.
bottomname=numberNoneImages with axis="x": the y of their base. Default: the bottom of the screen.
leftname=numberNoneImages with axis="y": the x of their left side. Default: the left of the screen.
groupname=str or listNoneThe images' group. The function gives its pieces their group.
height · width · sizename=numberNoneThe size of each image, as in Sprite(path, height=…). Without it, the image gets the size of a Sprite with no size (48 on the longer side). A strip of scenery almost always wants the screen's height=. The function gives its pieces their size.

Reads and control

MemberReturnsMeaning
.pieceslistThe live pieces it built, in axis order.
.index_at(x)int (or (i, j))The cell that holds x (with "xy": index_at((x, y))). Score per stretch, checkpoints, difficulty.
.seedintThe seed in use — pass it in seed= to repeat the run.
.active = False—Freezes the filling (the pieces stay).
.destroy()—Stops and destroys its pieces. In an Act, change_act does this for you.

slot (what the function receives)

FieldReturnsMeaning
slot.i · slot.jintIndex: 0, 1, 2… ahead of start; −1, −2… behind. j only in "xy".
slot.left · slot.right · slot.bottom · slot.topnumberThe edges along the endless axis, in world coordinates (left/right in "x", bottom/top in "y", all four in "xy"). The other axis is yours.
slot.boxBoxThe cell ("xy").
slot.rngrandom.RandomThis cell's draw: slot.rng.uniform(…), slot.rng.choice(…), slot.rng.randint(…).
slot.chance(p)boolLike chance(p), on the cell's draw.

Two ways to make an endless game

Every endless game has two frames of reference: the world (ground, pipes, coins, towers) and the screen (the player's ship, enemy formations). The camera decides which one stays still; whatever lives on the other one costs a ride-along line per frame (group[...].move_by).

The camera movesThe camera stays still
Genresrunner, platformer, flappy, ship in a cavevertical shooter with enemy waves
World thingsbuilt once at the slot's coordinates; they do not moveride-along: group["ground"].move_by(0, -v * dt)
Screen thingsride-along: group["onscreen"].move_by(dx, 0)screen = world: Tracks with fixed points work
Parallaxon its own (pan_response)the layer's scroll (layer.scroll changes the speed)
Endlessgame and decorationdecoration only; the game arrives over time (every)
Clearing what leavescanvas.playfield.set(canvas.game_view.outset(m)) every framethe default playfield is enough
Stopping at game overstop the camera: everything stopsclouds.scroll = (0, 0)

The ride-along works because offsets add up: a move_along in progress plus a move_by every frame give the sum of the two.

# Still camera (vertical shooter): the sky moves, the waves arrive over time.
canvas.layers.create("clouds", scroll=(0, -180))

def cloud(slot):
    x = slot.rng.uniform(0, 600)
    return Sprite(slot.rng.choice(["cloud1.png", "cloud2.png"]), center=(x, slot.bottom))

Endless("clouds", cloud, axis="y", step=240)

def boss_arrived():
    canvas.layers["clouds"].scroll = (0, 0)          # the scenery stops

Keeping what changed

Going back to a cell builds everything again: a coin you took comes back. To keep it, use slot.i as the key:

taken = set()

def stretch(slot):
    made = [Rect(top_left=(slot.left, 40), width=800, height=40, group="ground")]
    if slot.i not in taken:
        coin = Circle(center=(slot.left + 400, 120), radius=12, group="coin")
        coin.stretch = slot.i
        made.append(coin)
    return made

@collide("hero", "coin")
def took(hero, coin):
    taken.add(coin.stretch)
    coin.destroy()

Who owns each piece: what the function returns belongs to the Endless (it destroys it when the cell falls behind, going by the cell's position). What the function creates and does not return is yours — an enemy that walks away should not be returned. A piece you destroy (a coin taken) only comes back when its cell leaves the screen and comes back. Other objects on the same layer are not touched.

Terrain: what must match at the seam between cells (the height of the ground) is a function of the world x — neighboring cells ask about the same x. slot.rng is for decisions inside the cell (a tree here, a tower there).

A still camera + Endless on a game layer: the window does not move, so it fills the first screen and stops. Moving the pieces (the conveyor-belt habit) takes them off screen and nothing new arrives — Scena warns once. With a still camera, move the camera, or use a layer with scroll for decoration only. Create the Endless in the Act that uses it.

Groups

A group is a tag. Whatever has the tag is in the group; group["wasp"] is a live view of that set — whoever joins later shows up on the next read.

A name no object uses is an empty group, not an error: after renaming a tag in only one place, group["shots"].destroy() does nothing. Check the name (Scena warns when the name is close to that of a group that exists).

wasp = Sprite("x.png", group="wasp")   # joins the "wasp" group
wasp.hp = 1
group["wasp"].move_by(0, 10)            # acts on all of them
foe = group["wasp"].nearest(player.center, where=lambda w: w.hp > 0)
group["wasp"].destroy()

An object joins a group through a tag: in the constructor (group=) or later (tag). The group has no .add / .remove.

for x in (100, 200, 300):
    Circle(center=(x, 100), radius=10, group="wasp")
ship = Sprite("ship.png", group=["player", "hurt"])
ship.tag("shielded")
ship.untag("hurt")
ship.tagged("player")               # True
copy = ship.clone()                 # copies the tags
elite = ship.clone(group="elite")   # replaces them

An Entity can be in several groups. group= on clone replaces the tags (it does not mix them); leaving it out copies the current ones; group=None = none. Clone a clean template, not an object already tagged. There is no id: the tag is the only name for finding an Entity later (group["hero"].first). A destroyed object leaves its groups at once: group["wasp"] read right after destroy() no longer holds it.

Count, test, pick by position and iterate. The order is the order in which members joined the group — not their position on screen.

for x in (100, 200, 300):
    Circle(center=(x, 100), radius=10, group="wasp")
group["wasp"].hp = 3
w = group["wasp"][1]

group["wasp"].count           # or len(group["wasp"])
group["wasp"].empty
w in group["wasp"]
leader = group["wasp"].first  # or [0]
newest = group["wasp"].last   # or [-1]
i = group["wasp"].index(w)    # 0 = the first to join
mid = group["wasp"][1:3]      # a list, not a group

for w in group["wasp"]:
    w.hp -= 1

The for uses whoever was in the group when the loop began: you can destroy a member midway without breaking it; whoever joins midway only shows up on the next read. A member that leaves and comes back goes to the end. .index(w) and .first / .last use this live rank — if someone ahead leaves, the ones behind move up. For a formation, sort (sorted(group["wasp"], key=lambda w: float(w.center.x))) or keep a fixed number in an own field (w.slot = i, or phase= on move_along).

group["wasp"].move_by(0, 10) calls the same method on each member, with the same arguments. It is the for, written short.

for w in group["wasp"]:
    w.move_by(0, 10)

group["wasp"].move_by(0, 10)   # the same thing
group["wasp"].hp = 3           # writes to all of them
group["wasp"].tag("shielded")  # the group's own: tags all of them

What comes back depends on what the method returns for one member:

If each one returns…The group returns…
the object itself — an instant action, such as move_by without time=the group (you can chain)
something else — a Handle, a copy, a channel…a list with each one's result
# with time=: each one returns a Handle → a list
handles = group["wasp"].move_by(0, 80, time=0.4)
await parallel(*handles)

# with speed=: each one works out its own duration (the far one takes longer)
handles = group["wasp"].move_to(400, 120, speed=250)

# move_along always returns a Handle → a list
handles = group["wasp"].move_along(track, time=4)
await parallel(*handles)

# clone returns a copy → a list of copies
copies = group["wasp"].clone()

Reading an attribute: one member → the value; several → a list of values. Writing (group["wasp"].hp = 3) puts the same value in all of them. A member without the method (or the name) raises an error. In an empty group there is no member to call: the method does nothing and returns None — neither the group nor a list (with time= or speed=, it returns a single Handle; with speed= that Handle finishes on the next frame, since there is no distance to cover); reading any field (center, angle, hp…) raises AttributeError saying the group is empty — there is no member to read from. For the position of a group that may become empty, use centroid or box (None if empty). If you are going to use the return value (e.g. await parallel(*handles)), test group["wasp"].empty first.

.destroy(), .tag(), .untag(), .nearest(), .filter(), .index(), .first / .last belong to the group (see the reference); they are not “call it on each one and collect”.

The same arguments for everyone. A different phase, destination or time per member: write the for. There is no group.every / group.on_update: the fleet's loop lives in update or in a Director.

Find a member, count the ones that pass a test, measure the fleet.

foe = group["wasp"].nearest(player.center, where=lambda w: w.hp > 0)
close = group["wasp"].nearest(player.center, within=200)   # or None
n = group["wasp"].count_where(lambda w: w.hp > 0)
if group["wasp"].any(lambda w: w.hp <= 1):
    canvas.flash(0.2)
group["wasp"].filter(lambda w: w.hp <= 0).destroy()
mid = group["wasp"].centroid    # (x, y) or None
box = group["wasp"].box         # Box or None — frame_to(box) is safe when empty

nearest returns a member or None, not a list. filter returns a copy (it does not follow the group). centroid and box are None on an empty group.

Set operators between groups. The result is a copy: whoever joins later is not in it.

alive = group["wasp"] | group["drone"]    # union
hurt = group["wasp"] & group["hurt"]      # intersection
solo = group["wasp"] - group["elite"]     # difference
group["elite"] <= group["wasp"]           # subset
group["wasp"].issuperset("elite")         # superset
snapshot = group["wasp"].as_set()         # a Python set of the current members

Each operator has a method with the same effect, which also takes the tag's name: .union("drone"), .intersection(), .difference(), .symmetric_difference(), .issubset(), .issuperset(). .is_live tells whether the view still follows the group: True on group["wasp"] and on a formula group; False on a copy. For a combination that follows: Named live group.

Gives a name to a live combination: it is recomputed on every read. The expression has to stay inside lambda:, so that it is redone on every read.

group["enemies"] @= lambda: group["wasp"] | group["boss"]   # required: | & - give a copy; the lambda: redoes the expression on every read
group["enemies"] @= group["wasp"]                           # optional: a bare live group is an alias
group["enemies"] @= "wasp"                                  # optional: a bare tag string is an alias
group["enemies"] @= (group["a"] | group["b"])               # forbidden without lambda: raises an error with a hint to wrap it in a lambda

await until_empty("enemies")
group["enemies"].unlink()     # the name goes back to being an empty tag group

An alias without lambda only works for a live group or the tag's name. A union, an intersection or a filter has already been computed: @= refuses it (it does not freeze it silently). This does not use the @= link of fields: if two names depend on each other (A uses B and B uses A), the error only shows up on reading. .is_linked tells whether the name has a formula.

Similar, elsewhere: the active switch of an attack box is also linked with @= (sword["active"] @= lambda: hero.showing(STRIKE)) and is recomputed in each frame's collision step. See Attack boxes.

@collide does not follow a formula group — use the source tags. @click(group["…"]) follows the tag, like @collide: whoever joins later is clickable too.

Wait for the wave to end: await until_empty(...), in an async mode.

await until_empty("wasp")
await until_empty(group["wasp"])
await until_empty("enemies")      # a formula group too

It takes the name, group["wasp"] or a formula group — not the result of filter / | (a copy). Do not use until(lambda: group["wasp"].empty): use until_empty. See async wait.

group["…"] reference

Join and leave (on the Entity)

NameSignatureReturnsMeaning
group=Parameters: str or list—In the constructor. A tag, or a list of tags. E.g. group="wasp".
tag(*names)Parameters: names (names)the object itselfJoins the group.
untag(*names)Parameters: names (names)the object itselfLeaves the group.
tagged(name)Parameters: name (name)True/FalseIs this Entity in the group?
clone(group=)Parameters: group (str, list or None)the copied objectLeaving it out copies the current tags. Passing it replaces them (it does not mix). group=None = none.

Read and iterate

NameType (typical value)Returns / readMeaning
group["wasp"]Parameters: name (name)the groupWho is in the group now. Brackets, like a dict — group("wasp") no longer works. No .add / .remove — objects join and leave with tag / untag.
.count / len(…)integer3readHow many members now. Tag: O(1). Formula group: counts again (O(n)).
.emptyboolTruereadTrue if there is no one. Do not use it in until() — use until_empty.
w in group["wasp"]boolTruereadIs this Entity in the group? A string ("ship" in group["wasp"]) raises TypeError: to test a tag, w.tagged("wasp").
.first / .lastobjectwreadThe first to join / whoever is at the end now. The same as [0] / [-1]. Empty group: an error (not None).
group["wasp"][0]objectwreadThe member at that position, as in a list. [-1] = the last, [-2] = the one before last. Out of range / empty group: an error. The inverse is .index(w).
group["wasp"][1:3]list[w, w]readA slice: a list of those members (a copy, not a live group). An empty range → an empty list, no error. The list has no .destroy() / .first — use .filter or a for.
.index(item)Parameters: item (Entity)integerThe position in joining order (0 = the first). It takes the object itself (a string raises TypeError). If the object is not in the group, it raises an error — it does not return -1. A live rank. In a for, use enumerate.

Act on all

NameSignatureReturnsMeaning
group["wasp"].method(…)The method's argumentsthe group, or a listCalls it on each member. See the return rule in Act on all.
group["wasp"].hp = 3assignment to all—Puts the value in each member. If any member lacks that name, it raises an error.
.tag(*names) / .untag(*names)Parameters: names (names)the groupAdds / removes the tag on all current members.
.destroy()No parametersthe groupDestroys all current members.

Search

NameSignatureReturnsMeaning
.nearest(point, where=, within=)Parameters: point (point), where (function), within (number)object or NoneThe closest one. point is (x, y) or something with .x / .y (e.g. player.center). where= picks who takes part (lambda w: …). within= = the maximum distance. No one (or no one close enough) → None. A list / a mix: nearest(origin, items).
.filter(pred)Parameters: pred (function)a copyA copy holding only those that pass the test. That copy does not change later. Then .destroy().
.any(pred) / .all(pred)Parameters: pred (function)True/FalseSome / all pass the test. all on an empty group: True.
.count_where(pred)Parameters: pred (function)integerHow many pass the test.
.centroidpoint or NonereadThe mean point of the members. Empty: None.
.boxBox or NonereadA new Box that covers the members (angle 0). Empty: None. With one member (or all at the same point) it can be collapsed (width/height 0). It works in frame_to with no guard.

Combine (copies)

NameTypeReturnsMeaning
group["a"] | group["b"]group copygroup (copy)Union. Also .union().
group["a"] & group["b"]group copygroup (copy)Intersection. Also .intersection().
group["a"] ^ group["b"]group copygroup (copy)In only one of the two. Also .symmetric_difference().
group["a"] - group["b"]group copygroup (copy)Difference. Also .difference().
group["a"] <= group["b"] / .issubset(other)boolTrueTrue/FalseSubset: every member of a is in b (equal sets count too). Takes the group or the name. Empty group: True. Not a copy.
group["a"] >= group["b"] / .issuperset(other)boolTrueTrue/FalseSuperset: a holds every member of b (equal sets count too). Takes the group or the name. Not a copy.
.as_set()No parameterssetFreezes the view into a Python set of the current members.
.is_liveboolTruereadDoes the view follow the group? True on a tag or a formula group; False on a copy.

Named live group and waiting

NameSignatureReturnsMeaning
group["enemies"] @= lambda: …Parameters: lambda, live group or name (str)the groupNames a live combination (recomputed on every read). Without the lambda:, a union or a filter on the right-hand side raises an error. Alias: group["e"] @= group["wasp"] or @= "wasp".
.is_linkedboolTruereadDoes this name have a formula?
.unlink()No parametersthe groupRemoves the formula. The name goes back to being an empty tag group.
await until_empty("wasp")Parameters: group_or_id (name or the group)Waits (use await)Waits for the group to become empty. Takes the name, group["wasp"], or a formula group. The result of filter / | does not work.

Don't confuse

Looks likeIt isIt is not
group["a"] | group["b"] follows whoever joins latera copy of the moment. A live combination: group["enemies"] @= lambda: group["a"] | group["b"].a live group
group["wasp"][0] is the leftmost onethe first to join the group. A re-tag goes to the end; .index changes if someone ahead leaves. Formation: sorted(…) or a fixed number in an own field.the position on screen
@collide(player, …) with the objectgone on destroy(). Group names in @collide see whoever joins later — prefer them if the Entity dies and comes back.the same as the group's name

Where else to look — Place · Appearance · Frame · Move

Place

Tools for placing objects. A Box is an invisible rectangular region: you measure it, shrink it (inset), slice it into strips (strip) and grids (grid), find its neighbor (beside) and create objects fitted into it with box=. Rect draws; Box only measures — it is not a game object.

Constructors / corners / inset / strip / beside → Box
Fleet / board → grid
Rect(box=) / Sprite / Text → box=
Screen in the world / HUD / leaving the level → Screen regions
Level made in the editor (Level, make()) → Level

Box

A Box is a rectangular region that does not show on the screen: it is for measuring and placing. You build it like a Rect (center= + width= + height=, a corner, p1= / p2=…) or from an object (ship.box), but it has no color, layer or group — and there is no empty Box().

zone = Box(center=(400, 300), width=800, height=220)
inner = zone.inset(24)
halo = zone.outset(24)
hud = zone.strip("top", 40)                 # strip inside
sidebar = zone.beside("right", width=120)   # neighbor outside
cell = canvas.game_view.inset(40).grid(4, 3).cell(0, 0)
Rect(box=cell, color="navy")

# the same models as Rect:
Box(top_left=(80, 640), width=160, height=80)
Box(p1=(100, 100), p2=(500, 300))
Box(p1=(100, 300), p2=(500, 300), height=40, anchor="square")
Box reference

Box(center=, width=, height=, angle=) · Box(source) · Box.from_graphic(graphic)

Constructors

CallMeaning
center=, width=, height=The usual way. angle= is optional.
top_left=, width=, height=Corner + size
p1=, p2=Opposite corners
p1=, vec=One corner (p1) and a vector to the opposite corner (vec), in design units
p1=, p2=, height=, anchor=Axis + thickness — the same as Rect ("cap" / "square" / "side_left" / "side_right")
Box(source)source is a Graphic (Rect, Sprite, Text…) or another Box. The same copy as graphic.box — the frame with its names (a Box is a Rect that does not draw)

Measuring a group

MethodSignatureReturnsMeaning
group["wasp"].boxNo parametersBox or NoneAn axis-aligned box that covers every member (a new Box), or None if the group is empty. Angle 0. It is not a Box constructor.

Properties

PropertyType (typical value)Read/WriteMeaning
.center .width .height .anglepoint or number(400, 300)read / writeGeometry. Corners: .top_left · .right_center · … — as in Rect, each name stays tied to its corner: after a rotation, .top_left is still the same corner, even if it is no longer at the top left on the screen. A Box made from another one (graphic.box, Box(b), inset, cells) keeps the names: cell (0, 0) of a board stays the same after you rotate or mirror it.
.left .right .bottom .topnumber80readSides. y up: top is the largest y. Read-only: to change the area, create another Box (e.g. box.outset(40)).
.col_index / .row_indexint or None0read / writeOn a grid cell. None on a standalone Box.
.is_collapsedboolFalsereadRead-only. True if the width or the height is 0 (a line or a point). The same “no interior” rule as contains_point. No warning.

Methods

MethodSignatureReturnsMeaning
inset(margin)Parameters: margin (number)BoxShrinks evenly inward. A copy. Room inside box=: box=cell.inset(8) — there is no padding= in the constructor. A negative margin raises ValueError.
outset(margin)Parameters: margin (number)BoxGrows evenly outward (the twin of inset). A copy, with the same center and angle. A negative margin raises ValueError. A collapsed source (a line or a point) gets an interior. It is not pad= / padding= (a fraction) — the margin is in units: frame_to(box.outset(40)).
strip(side, thickness)Parameters: side ("left"/"right"/"top"/"bottom"), thickness (number)BoxA strip inside, flush with a named side ("top" = the side of top_left / top_right). The strip has the thickness you ask for and spans the whole side of the Box. If the thickness is larger than the Box, the strip is the size of the Box, with no warning. A negative thickness or an unknown side raises ValueError. Compare: beside (outside); a grid for fleets.
beside(side, *, width=, height=, gap=0)Parameters: side; width/height optional; gap (number)BoxA neighbor outside, flush with a named side. Sizes you leave out are inherited; both left out → the same size. gap is the space between the sides. A negative size or gap, or an unknown side, raises ValueError. Compare: strip (inside).
grid(cols, rows, gap=0)Parameters: cols (int), rows (int), gap (number or pair)GridSlices the Box. gap is the space between cells. See Grid.
contains_point(x, y=None)Parameters: x (a point, or the number x with y)True/FalseGeometry only. It does not register clicks. For a board: g.cell_at(mouse.x, mouse.y).
rotate_to / rotate_byvalue (number); about= (point, optional); force=Falsethe same Box (changes it)Rotates the region in place and returns self — not a copy (unlike inset / outset). No time=: this is not Move's rotate_to (that one is for objects on the screen, with time= and a Handle). about= is the pivot (default: the center) — a tuple, Point, Vec2, Graphic or mouse, copied now. A grid made from it inherits the angle.

Box() raises an error. There is no default region. Four positional numbers do not work either: corners vs x, y, w, h. isinstance(box, Entity) is False. There is no @click / on_click on a Box. An inset / gap that is too large turns it into a line or a point with no warning — use .is_collapsed if you need to detect it. outset does not collapse; outset(m).inset(m) always gets the Box back, but inset(m).outset(m) only does when the inset did not squeeze it all the way down. strip = a strip inside; beside = a neighbor outside; a grid for fleets / equal cells.

Grid

A grid slices a Box into equal columns and rows — for fleets, boards, inventories. box.grid(8, 3) returns the grid; go through its cells with for or ask for one with .cell(col, row). Row 0 is the top one (the visual top of the Box).

zone = Box(center=(canvas.game_view.center.x, 520), width=820, height=220)
fleet = zone.grid(8, 3, gap=16)          # or gap=(gx, gy); the same as Grid(zone, 8, 3, gap=16)
for cell in fleet:
    Wasp(space, box=cell, height=40, group="wasp")

top_left = fleet.cell(0, 0)              # col, row
third = fleet.cell(2)                    # flat index: col = n % cols
for row_cells in fleet.rows:
    ...

hit = fleet.cell_at(mouse.x, mouse.y)    # None in a gap or outside
if hit is not None:
    piece = Rect(box=hit)
Grid reference
MethodSignatureReturnsMeaning
for cell in giterable—Row 0 first, left → right.
g.cell(col, row)col (int), row (int)BoxColumn first, like (x, y).
g.cell(n)n (int)BoxFlat: col = n % col_count, row = n // col_count.
.rows / .colslists—Lists of lists. Counts: .row_count / .col_count.
.cell_at(x, y)point or x, yBox or NoneThe inverse. On a rotated grid it converts to local coordinates first. A gap → None. A cell with zero area can still be reached with .cell(col, row), but cell_at never finds it.
cell.col_index / .row_indexint—Its place in the grid. There is no pointer back to g. The neighbor: g.cell(cell.col_index + 1, cell.row_index).
g[col, row]TypeError—Reserved. Use g.cell(col, row).

A grid on a Box with angle= makes its cells at the same angle. cell_at takes that into account. A click on the rotated board lands in the right cell.

box=

box= creates an object already fitted into a region (a Box, a grid cell): a Rect fills it, a Circle is inscribed in it, a Sprite fits inside it and keeps the image's proportions. With an explicit size, the object is only centered in it. To leave some room, shrink the region first: box=cell.inset(8).

cell = canvas.game_view.inset(24).grid(4, 3).cell(0, 0)
Rect(box=cell, color="navy")              # fills
Circle(box=cell)                         # inscribed (the shorter side)
zone = Box(p1=(200, 200), p2=(100, 400))
Sprite(box=zone)                         # fits whole, keeps the aspect
Sprite(box=cell, height=40)              # only centers; height wins
Text("Score", box=canvas.ui_view.grid(1, 8).cell(0, 0), layer="ui")

squares = panel.box.inset(8).grid(8, 8)
for cell in squares:
    Square(box=cell, color="gold")
Fit contract
Typebox= aloneWith an explicit size
Rect / EllipseFills (pose + size + angle)Mixing them raises an error
Circle / Square / regular N-gonInscribed (the shorter side). Circle does not inherit the angleOnly centers (radius= / length= / side=)
TriangleFills (the apex along the width; inherits the angle). With base_ratio=: fits, centered, with that proportionOnly centers (radius= / side=)
Sprite / SvgFits (the PNG's aspect; inherits the angle)Only centers (height= / width= / size=)
Textcenter= the center of the region (ui layer); align="center"; the region's width if left out; outside the columnDo not mix with center= / top_left= / top_center= / top_right=

A region that moves: pass a formula. box=cell fits once (a value copies); box=lambda: … fits again whenever something the formula reads changes (a formula links). It works on shapes (Rect, Square, Concave, Ellipse, Circle, RegularPolygon, Triangle) and on Sprite, Svg and SpriteButton.

shield = Rect(box=lambda: hero.box.beside("right", gap=8), color="cyan")
marker = Circle(box=lambda: board.cell(st.spot), color="gold")
banner = Rect(box=lambda: canvas.game_view.strip("top", 40), color="navy")

The shield follows the hero when it walks, turns or grows; the marker jumps to the cell that st.spot names; the banner follows the camera. Like any linked shape, it refuses move_by / rotate_by / scale_by (“its center follows its box= formula”). To let it go: force=True on the verb, or unlink_all() — it stays where it is. If the hero is destroyed, the shape is let go too, at its last place. A Sprite (or Svg) follows the region by changing its scale, so every frame of the animation keeps the same size as the others; with height=, only the center follows. Text does not take a formula in box= (its width decides where the lines break): link its center= instead.

Every object with a rectangular frame has .box — a copy of the frame, taken now, with the Graphic's names (rect.box.top_right is rect.top_right; sides on the screen: .left / .top / …): Rect, Square, Ellipse, Circle (the square of the diameter, turned toward the rim point p1), Sprite, Svg. Line / free Polygon / Track / Point raise TypeError. The layout verbs live on Box (panel.box.inset(8).grid(8, 8)), not on the Shape. To keep the pose inside a Box: confine.

box= does not mix with center= / width= on a Rect. box=region is a copy: the object does not follow the region afterward; to follow it, use box=lambda: region. A HUD after a pan: ui_view, not game_view. If the region shrank to a line or a point (an inset that is too large), the object is born invisible; check with .is_collapsed on the Box or on the object.

Screen regions

Three ready-made regions of the canvas: game_view (the part of the world the camera shows), ui_view (the window, for the HUD) and playfield (the play area, to know when something left it). You read them the same way; they are for different things.

Circle(box=canvas.game_view.inset(80).grid(3, 3).cell(1, 1))
hud = canvas.ui_view.strip("top", 80)
Text("SCORE", box=hud, layer="ui")
rail = canvas.game_view.strip("left", 120)
sidebar = canvas.game_view.beside("right", width=120)

# leaving the level — not layout:
canvas.playfield.pad = 0.4
@leave_playfield("bolt")
def leftover(shot):
    shot.destroy()

safe = canvas.playfield.inset(40)   # a Box; the playfield's .pad does not change
outer = canvas.playfield.outset(40)  # a larger halo; .pad does not change
band = canvas.playfield.strip("top", 80)  # a copy; .pad does not change
canvas reference
PropertyType (typical value)Read/WriteMeaning
canvas.width / .heightnumber2000readThe size of the design space. Set it in init(width=…, height=…) before run(). The OS window is something else: window_scale and canvas.display.
canvas.aspect_rationumber1.67readwidth / height.
canvas.game_viewnew Boxcanvas.game_viewreadA window on the world (what the camera sees). For ships, formations, “the top of the screen”. Each read is a new Box. With a rotated camera: it is the upright rectangle that holds the rotated view, larger than the screen.
canvas.ui_viewnew Boxcanvas.ui_viewreadA window on the view, [0, W] × [0, H]. HUD / layer="ui" / view Text. It does not move with the camera.
canvas.playfieldplayfieldcanvas.playfieldreadThe exit area for @leave_playfield, fixed in the world (default: the init space with a 25% margin on each side, so 1.5× larger; it does not follow the camera). It is not a Box. inset / outset / grid / beside / strip return Box copies and do not write .pad. Alias: canvas.bounds.

There is no canvas.center / canvas.screen / canvas.view. The center of what you see: canvas.game_view.center (world) or canvas.ui_view.center (HUD).

A Box cut from game_view in setup stays in the world when the camera moves. Usually that is what a formation wants. For a layout that follows the view, read game_view again in update. A HUD laid out in the world goes wrong after a pan. Leaving the level: @leave_playfield.

With a rotated camera, game_view is larger than the screen. It is the upright (unrotated) rectangle that holds the rotated view, so its corners, and the cells of a grid made from it, fall off the screen; confine(canvas.game_view) lets the object out through the corners. To keep it on the screen with a rotated camera, rotate the region too: Box(center=canvas.game_view.center, width=canvas.width / canvas.zoom, height=canvas.height / canvas.zoom, angle=-canvas.rotation).

Level

Reads a level file made in the level editor (python -m scena_editor). It only reads: Level("level1.json") creates nothing on the screen. Your code decides what each item becomes.

level1 = Level("level1.json")
for p in level1.group("platform"):
    block = p.make()                    # the Rect as it was drawn, in the group "platform"
    block.mass = STATIC
for e in level1.group("star"):
    Sprite("star_gold.png", size=28, center=e.center)   # a point is a place
level1["backdrop"].make()                  # image: the Sprite at the editor's size and rotation
pond = level1["pond"].make(color="steel blue")
area = level1["arena"].box              # or just the region (Sprite(box=), confine, a grid…)
start = level1["start"].center
route = level1["drone_route"].points      # a list of Vec2 for move_along
Level reference

Level(path) — a relative path is looked up like Sprite images: next to the script, in its media/ folder, in the current folder.

Level

MemberReturnsMeaning
Level(path)LevelReads the .json file the editor saved. path is the file name, looked up like images. A file that is not found raises ValueError with the folders it searched. A file Scena cannot read (invalid JSON, a malformed item, a version from a newer Scena) raises LevelFormatError, a ValueError that names the file and the item: except ValueError catches both.
level["name"]LevelItemThe item with that name (names are unique in a level). An unknown name raises ValueError, with a suggestion; if the name is a group's, the message says level.group(...).
level.group("g")list of LevelItemThe items that have the group g, in file order (drawing order). A group no item has raises ValueError — a typo does not become an empty list.
for item in level · len(level) · "name" in level—Every item, in file order. Guides (images that are only a reference in the editor) are not part of the level.
.names · .groupstuple of namesEvery name; every group in use (in order of first use).
.size · .box(width, height) · BoxThe level's area, from (0, 0) to size. .box is a new Box on every read — for canvas.playfield.set(level1.box), canvas.frame_to(level1.box), confine.
.pathtextThe absolute path of the file that was read.
level.sheet("name") · .sheetsSheet · tuple of namesThe level's sprite sheets (the file's sheets table). sheet("name") is the same Sheet for every frame of that sheet, created on first use: a clip registered on it plays on what make() creates. Creating it checks each item's frame: an unknown frame raises LevelFormatError with the item. An unknown name raises ValueError, with a suggestion. The editor only keeps the sheets some item uses: a sheet meant only for the code (the power-up boxes the code creates at the level's points) is gone on the next save — load it in code, Sheet("sheet.png", atlas="sheet.xml").

LevelItem — every item

MemberReturnsMeaning
.kindtext"rect" · "ellipse" · "concave" · "circle" · "line" · "polygon" · "regular_polygon" · "triangle" · "track" · "point" · "image"
.name · .groupstext or None · tupleThe name and groups given in the editor. An item can be in several groups.
.centerVec2The center. A line: its middle; a polygon or a track: the middle of the box around it; a point: the point itself.
make(**kwargs)the new shapeCreates the shape as it was drawn, in the item's groups: rect → Rect, ellipse → Ellipse, concave → Concave (with scoop and rim), circle → Circle, line → Line, polygon → Polygon, regular_polygon → RegularPolygon, triangle → Triangle (with base_ratio), track → Track (with the item's smooth; 0 if the file has none), point → Point, image → Sprite (the editor's size and rotation; a sheet frame → Sprite(item.sheet, frame=item.frame, …)). Other keywords are passed on (layer=, color=, visual=); group= adds to the item's groups. Geometry (center=, width= …) raises TypeError: it comes from the level. The same table as the editor's “Copy as code”.

LevelItem — by kind

KindFields.box
rect · ellipse.width .height .angleAn oriented Box (with the rotation)
concave.width .height .angle .scoop (text) .rim (Vec2)An oriented Box (the box)
image.width .height .angle; a whole image has .image (absolute path), a sheet frame has .sheet (the Sheet) and .frame (index or name) — asking for the other form's field raises AttributeError (a sheet's file would show every frame)An oriented Box
circle.radiusthe square around it
line.p1 .p2 (Vec2), .length, .angle (heading from p1 to p2; both as item.make() reads them)none — raises AttributeError with a hint
regular_polygon.radius (center to vertex), .n (sides), .angle (heading of vertex 0)none
triangle.radius (center to apex), .angle (heading of the apex), .base_ratio (base / side; 1 = equilateral)none
polygon · track.points (a new list of Vec2); a track also has .closed and .smooth (0 = straight lines, 1 = a curve; on a smooth track the points are the control points — move_along(item.make()) follows the curve)none
pointonly .centernone

The item in another model

make() creates the shape in the file's model: the rectangle by its center (center, width, height, angle), the line by its ends (p1, p2). The model decides what the shape stores and what it computes. In a Rect built by its center, width = 300 grows both ways, and top_left is computed: it takes neither = nor @=. For another model, write the constructor with the item's numbers; the Box from item.box has every named point.

b = level1["elevator"].box
door = Rect(top_left=b.top_left, width=b.width, height=b.height, angle=b.angle)  # grows from the corner
bridge = Rect(p1=b.bottom_left, p2=b.top_right, angle=b.angle)    # by two corners (copies)
beam = Rect(p1=b.left_center, p2=b.right_center, height=b.height, anchor="cap")  # by the axis
c = level1["rope"]
rope = Line(p1=c.p1, angle=c.angle, length=c.length, group=c.groups)  # pinned at p1: a pendulum
laser = Line(center=c.center, length=c.length, angle=c.angle)          # grows from the middle

These are copies, like every read from the level. make() puts the shape in the item's groups; here, pass group=item.groups. A concave one also takes scoop=item.scoop, rim=item.rim. The same goes for a shape that already exists, reading its parts (Rect(top_left=r.top_left, width=r.width, height=r.height, angle=r.angle)). The error message of a computed field already shows that line, ready to use.

The level and the window

The level's size (level1.size, the frame the editor shows) is the area of the world; the window is something else, and your code decides how one shows the other. Level only reads the file, so you can read the level before init() and open the window at its size: one unit of the level is one unit of the window, and the camera does not need to move. A level larger than the screen (the ninja level is 4000 × 750) fits in a window of any size you want, and the camera shows the right part: canvas.frame_to(level1.box) frames the whole level.

level1 = Level("level1.json")     # before init(): it only reads the file
w, h = level1.size
init(width=w, height=h)          # the window at the level's size

init(width=1280, height=720)     # or: any window...
canvas.frame_to(level1.box)      # ...and the camera frames the whole level

Frames from a sprite sheet

An image in the level can be a frame from a sheet (spritesheet): a grid (columns and rows, or the cell size) or an atlas (the coordinates in a .xml or .json file), the same cuts as Sheet. The level file stores the sheet once and, in each item, which frame it shows. Timing stays in the code: the clips go on the level's Sheet.

level1 = Level("level1.json")
for t in level1.group("ground"):
    t.make()                              # the frame, at the editor's size and rotation
level1.sheet("water").clip("ripple", [40, 41, 42], fps=6)
for a in level1.group("water"):
    a.make().play("ripple")                 # the same Sheet: the clip is on it

The level editor

The editor comes with Scena (pip install scena). In the terminal, either of these opens (or creates) the level: scena-editor level1.json or python -m scena_editor level1.json — the second always works, because it uses the same Python as your games.

An icon to open the editor with a double click: run scena-editor --shortcut (or python -m scena_editor --shortcut) once. On Windows it shows up in the Start menu and on the desktop; on macOS, in Applications (~/Applications); on Linux, in the applications menu. If you reinstall Python, run it again. Editor errors go to a log file, whose path shows in the status bar.

Tools (on the left, icons with their key in the corner): Rect (R), Ellipse (E), Circle (C), Line (L), Polygon (G), Triangle (D: Base ratio in the panel), Regular polygon (N), Track (A: Smooth in the panel), Concave (U: a box with a scoop; Scoop and Rim in the panel), Point (P), Image (I: a picture, or a sheet's .xml / .json atlas). Dragging draws; a click creates the shape with a side of 100 (96 or 128 on the grids from 8 to 64, so the corners land on the grid). Smooth and Base ratio have a slider, with the number next to it: dragging shows the shape changing, and Undo takes back the whole drag. On the top bar: Undo / Redo, Select (V) and Pan (H, or Space+drag). The panel on the right gives the name, groups (comma-separated), position and size. Shift while dragging: no grid. Cmd/Ctrl+C copies the items — and the code that creates them (Rect(center=…)) goes to the clipboard. The editor's numbers are the same as the code's.

Frames from a sheet: choose an atlas with the Image tool, or select an image and click Choose frame…. The sheet appears in place of the level, and the panel on the right shows the cut: the whole image, columns × rows, the cell size or the atlas. The mouse wheel zooms, dragging pans, F fits and Esc cancels. A click picks the frame, which keeps the image's center, rotation and scale: a strip of 17 cherries placed whole becomes one cherry of the same size. The status bar shows the frame under the pointer, or the Sheet message when the cut does not work.

Don't confuse

Looks likeIt isIt is not
item.make() vs item.boxmake() = the shape drawn in the editor. .box = the region, for another use (Sprite("x.png", box=item.box), confine, a grid). Two purposes, not two spellings.Level(...) creates nothing on its own; neither does level.group(...).
Rect(p1=block, p2=…)The center of block as a point: a shape in place of a point counts as its center.It does not copy the block in another model. Read its parts: Rect(p1=block.p1, p2=block.p2, angle=block.angle).
The level's groupsLabels from the editor. make() applies them to the shape, so group["platform"] finds the blocks made this way.They are not live groups: level.group("g") reads the file, not the registry.
The editor's numbersThe same as the code's: design units, y up, center, counterclockwise rotation in degrees.There is no conversion. Changing a value you read (item.center) does not change the level: they are copies.

Where else to look — Draw · World · Geometry

Frame

What you read every frame: time (clock), the keyboard (keyp) and the mouse. Ask in update — “is the arrow key held?” — and act: that is the check, asked every frame. All three can also go in an @= formula. To run something once when a condition becomes true, see React.

Held / every frame → Frame
When it becomes true / leaves the screen → React
Bodies touch → Collision
In N seconds / every N → Schedule
This number goes from A to B → Move
This Entity is in this chapter → Mode
The whole map → Which to use

clock

clock is the game's clock: dt (seconds in this frame), time (seconds since the start) and the pause and slow-motion controls (paused, scale). Its times are already on the game's scale — in slow motion dt gets smaller; paused, it is 0. clock.real_dt / clock.real_time are real time (the wall clock), unscaled. e.time_scale makes a single Entity slower or faster. For a rhythm, “once every N seconds”: ready.

def update(dt):
    ship.move_by(0, 200 * clock.dt)

ship.on_update = lambda e, dt: e.rotate_by(40 * dt)
clock.paused = True
clock reference

Properties

PropertyType (typical value)Read/WriteMeaning
clock.dt / .timenumber0.016readGame time: dt = seconds in this frame, time = seconds since the start. It shrinks in slow motion (scale) and is 0 while paused. At most 0.25 s per frame: after a freeze (a breakpoint, dragging the window) the world moves only that much — .time falls behind the wall clock.
clock.real_dtnumber0.016readReal seconds in this frame (wall clock): it ignores pause and slow motion and has no 0.25 s cap. Useful for widgets and for measuring FPS.
clock.scalenumber1read / write1 normal, 0 paused, 0.5 slow motion.
clock.pausedboolFalseread / writeShortcut for scale == 0. False brings back the previous scale. The pause starts on the next frame: the frame in which you press P already has its dt, so its on_update functions, timers and tweens still advance once. After that the on_update functions keep being called, with dt = 0: a key read there (keyp.once("W")) still acts during the pause. To freeze the object, start its on_update with if clock.paused: return.
e.time_scalenumber1read / writeAn extra multiplier on this Entity (timers, tweens, wait, on_update). Default 1.

Methods

MethodSignatureReturnsMeaning
e.on_updateParameters: e (object), dt (number)—fn(e, dt) every frame for this Entity, even during await. In the class: def on_update(self, dt).
In @= (reactive)

clock can go in a formula: name it in a lambda. The formula then depends on the whole clock (clock.time is not a field that links on its own) and is recomputed every frame.

from math import cos, sin
moon["center"] @= lambda: (
    earth.center.x + 200 * cos(clock.time),
    earth.center.y + 200 * sin(clock.time),
)
st["pulse"] @= lambda: abs(sin(clock.time * 3))
You canYou can't
field @= lambda: … clock.time … (also .dt, .frame, .scale, …)field @= clock.time — a bare number → TypeError; use lambda
@when(lambda: clock.time > 5) (Scena checks the condition every frame)clock["time"] @= … — time/dt are not fields you link with @=
Only clock.dt in update — no extra costship.angle = lambda: clock.time * 40 — use ship["angle"] @= lambda: …

Don't confuse

Looks likeIt isIt is not
A formula with clock.time only updates when something changesupdated every frame: each frame advances the clock, so a formula that reads clock.time is re-evaluated every frame. If no formula reads clock, this costs nothing. The first dt counts from the start of run() (after setup), not from init.—

chance / ready / recently. A one-shot roll (a 30% drop): chance. A rate / cooldown: ready. Remembering a value for X seconds: recently.

Keyboard

keyp tells you, in update, the state of the keyboard. keyp("A") is True while A is held (Shift held with it does not get in the way; Ctrl / Alt / Cmd do); keyp.once("A") only on the frame A is pressed (to jump, to shoot once); keyp.only("A") requires that no other key is held; keyp("CTRL+R") reads a shortcut. It also goes in an @= formula (below).

def update(dt):
    if keyp("LEFT"):
        player.move_by(-200 * dt, 0)
    if keyp.held("A"):
        player.move_by(-280 * dt, 0)
    if keyp.only("SPACE"):
        shoot()
    if keyp.once("R"):
        canvas.reset_view()
    if keyp.once("CTRL+R"):
        restart()
    if flag1 and flag2 and keyp.once("SPACE"):
        act()
keyp reference
MethodSignatureReturnsMeaning
keyp("A")Parameters: key (key name)True/FalseA held, without Ctrl/Alt/Cmd (those make shortcuts). Shift does not get in the way: “hold Shift to run” still reads keyp("RIGHT") and keyp.once("SPACE"); with Shift and R, keyp("R") and keyp("SHIFT+R") are both True. Another plain key held at the same time changes nothing: with LEFT and RIGHT held, keyp("LEFT") and keyp("RIGHT") are True (only keyp.only requires the key to be alone, without Shift either).
keyp.held("A")Parameters: key (key name)True/FalseA held; modifiers ignored.
keyp.once("A")Parameters: key (key name)True/FalseTrue only on the frame A is pressed. The first read uses up the press: after that it gives False until the key is released and pressed again. A press nobody read on that frame does not show up later: in if armed and keyp.once("SPACE"), a SPACE pressed while armed was False does not count when armed becomes True. To keep the press, keep it yourself: if keyp.once("UP"): st.wants_jump = True.
keyp.only("A")Parameters: key (key name)True/Falsekeyp("A") and no other physical key — not even Shift: keyp.only("R") is not Shift+R.
keyp("SHIFT+A")Parameters: key (shortcut, e.g. "SHIFT+A")True/FalseShortcut: True while Shift and A are held together. Another plain key held at the same time does not get in the way; one extra modifier makes it False — in a shortcut, Shift counts too: keyp("CMD+Z") is not Cmd+Shift+Z.
"SPACE" "ESC" "LEFT" "F1"Key names (str)—The other special keys: "ENTER" "TAB" "BACKSPACE" "DEL" "INS" "HOME" "END" "PAGEUP" "PAGEDOWN", the arrows ("UP" "DOWN" "LEFT" "RIGHT") and "F1"…"F12". Modifier families: "SHIFT" "CTRL" "ALT" "CMD". Punctuation is "K1"…"K12" (table below). Upper or lower case does not matter. An unknown name fails right away: keyp("ESCAPE") → ValueError suggesting "ESC"; keyp(5) → TypeError. keyp["A"] is not a query: TypeError asking for keyp("A") or keyp.once("A").
mouse.press(Mouse.BTN_LEFT)Parameters: button (mouse button, int 0–7)True/FalseA button by number (Mouse.BTN_LEFT / BTN_RIGHT / BTN_MIDDLE). A press that a widget (or a SpriteButton) took reads False until the button is released, just as a focused TextInput hides keys from keyp (mouse). mouse.press("left") → TypeError with the hint.
Punctuation keys (K1–K12)

A punctuation key has a number, not a character: keyp("K11"), key == "K7". The name is the key's position on the keyboard — the same in every layout. What is printed on the key changes (on ABNT2, K7 is Ç). keyp(".") or keyp("PERIOD") → ValueError suggesting "K11".

def update(dt):
    if keyp.once("K10"):       # comma (US and ABNT2)
        previous_camera()
    if keyp.once("K11"):       # period
        next_camera()
    if keyp("CTRL+K3"):        # Ctrl + the = key
        canvas.zoom_by(1.02)
NameWhere it isKey on USKey on ABNT2
"K1"left of 1`'
"K2"right of 0--
"K3"2nd right of 0==
"K4"right of P[´
"K5"2nd right of P][
"K6"above Enter (US) / left of Enter (ABNT2 and other ISO)\]
"K7"right of L;Ç
"K8"2nd right of L'~
"K9"left of Z (ISO keyboards only)—\
"K10"right of M,,
"K11"2nd right of M..
"K12"3rd right of M/;

Limits of the physical keyboard: the ABNT2 /? key (right of K12) has no name — the system does not identify it. On an Apple ISO keyboard, the keys left of 1 and left of Z arrive swapped (K9 ↔ K1). The numeric keypad and Caps Lock have no name: keyp and on_key do not see them.

Don't confuse

Looks likeIt isIt is not
I want the typed character (?, :, ç)on_char(char) — it follows the layout and Shift. keyp is a position: game controls.keyp("?") — ? is Shift + K12 only on US.
In @= (reactive)

keyp can go in a formula: pressing or releasing a key makes Scena recompute the formulas that read it. In a formula, use the “held” reads (keyp("D"), held, only, a shortcut) — not once.

c.center["x"] @= lambda: 1200 if keyp("D") else 800
gate["open"] @= lambda: keyp.held("SHIFT")
# “when pressed”: @when, not once inside @=
@when(lambda: keyp("Y"))
def on_y():
    restart()
You canYou can't
field @= lambda: … if keyp("D") … / held / only / shortcutkeyp.once inside @= — the lambda may be re-evaluated; once uses up the press
@when(lambda: keyp("Y")) — fires when it goes from False to True@when + keyp.once together — @when already fires only when it goes to True
Just reading in update — no extra cost while no formula uses keypkeyp["A"] @= … — keyp has no fields to link; it is only read

Held: update or @=. Pressed once: keyp.once in update, or @when(lambda: keyp("…")).

Don't confuse

Looks likeIt isIt is not
keyp.once at the start of an anda check that uses up the key press. To combine conditions, put once last: if flag1 and flag2 and keyp.once("SPACE"): fires once, on the frame the key is pressed, only when both flags are already True. If once comes first, the and uses up the press even with a flag False.—

A press one or more frames before the condition (jumping just before landing): recently("jump", keyp.once("UP"), hold=0.12). The request stays alive for hold. The note above only covers the same frame.

keyp.once sees the press even if the key was already released by the same read (a slow frame). keyp("A") does not: it only says what is held now.

Keys already held when the window opens count as held: keyp("A") is already True, but keyp.once("A") does not fire — there was no press.

Keys with a focused TextInput. A focused TextInput keeps the text and editing keys (letters, digits, space, arrows, Enter, Esc, Tab…) and Cmd/Ctrl + A / C / X / V / Z / Y: callbacks and keyp do not see them. The other keys go through to the game — Cmd/Ctrl + another letter (keyp.once("CMD+S") works), F1–F12, Page Up / Down, and Shift / Ctrl / Alt / Cmd alone — and the box saves its text first, like an Enter, but without losing focus and without running on_submit: what the box shows is what the game reads. Shortcuts ("CTRL+R") in the key callbacks: see Callbacks. To react when a game condition becomes true: @when. Bodies overlapping: Collision.

Mouse

mouse tells you where the pointer is and which buttons are pressed, in the same world coordinates as the objects (the camera is already taken into account). It is a point itself: move_to(mouse), no (mouse.x, mouse.y) needed. To click or drag an object, use Click / drag. It also goes in an @= formula (below).

def update(dt):
    if mouse.press(Mouse.BTN_LEFT):
        marker.move_to(mouse)

def on_mouse_scroll(xoffset, yoffset):
    factor = 1.1 if yoffset > 0 else 1 / 1.1
    canvas.zoom_by(factor, about=mouse)

mouse is a point: it works wherever the API expects a place (move_to(mouse), query_point(mouse), about=mouse…). That copies the position as it is now. To follow it: Circle(center=lambda: mouse) or center @= mouse. Both numbers at once: x, y = mouse (also a copy).

mouse reference

Properties

PropertyType (typical value)Read/WriteMeaning
mouse.x / .ynumber300readThe pointer's position in design units, in world space (the camera is already taken into account). Read once per frame: after canvas.pan_by / zoom_by in the same update, mouse.x is still the value from before the camera moved, until the next frame. x, y = mouse copies both at once.
mouse.dx / .dynumber0readHow far the pointer moved since the previous frame, in units.

Methods

MethodSignatureReturnsMeaning
mouse.press()No parametersTrue/FalseAny button (except one a widget took, as in the row below).
mouse.press(Mouse.BTN_LEFT)Parameters: button (mouse button: Mouse.BTN_LEFT / RIGHT / MIDDLE)True/FalseThat button. A press a widget took (dragging a Slider, holding down a Button or a SpriteButton, even a disabled one) reads False until the button is released: the brush does not paint under the slider or the tool icon. A press on another object (draggable, @click, a Sprite with on_click) is still True.
mouse.click_pos(button)Parameters: button (mouse button)point(x, y) of the last click. A click on a widget or under a modal menu does not count.
In @= (reactive)

mouse is reactive (like clock / keyp). The whole pointer links directly (center @= mouse). .x / .y / .press are properties — name mouse in a lambda. Same rule as the keyboard: held (a state) works; “just pressed” does not.

canvas is reactive too: lambda: canvas.game_view.center, lambda: canvas.zoom or lambda: canvas.layers["back"].view.left follow every camera move and every layer scroll (canvas.ui_view only changes with init).

cursor["center"] @= mouse
cursor.center["x"] @= lambda: mouse.x
st.aiming = 0.0
st["aiming"] @= lambda: 1.0 if mouse.press(Mouse.BTN_LEFT) else 0.0

# still fine in update (movement / one-shot gesture)
def update(dt):
    if mouse.press(Mouse.BTN_RIGHT):
        canvas.pan_by(mouse.dx, mouse.dy)
You canYou can't
["center"] @= mouse / field @= lambda: mouse.x / (mouse.x, mouse.y) / mouse.press(…)field @= mouse.x — a bare number → TypeError; use lambda or @= mouse on the whole point
@when(lambda: mouse.press(Mouse.BTN_LEFT))mouse.dx / .dy in @= — a delta (like keyp.once); read it in update
Just reading in update — no extra cost while no formula uses mousemouse["x"] @= … — mouse has no fields to link; it is only read

["center"] @= mouse is placing. Since it places (it does not travel), the object goes through the walls of resolve(). To click or drag an object: Click / drag. mouse.x / .y are in world space; a HUD object (the "ui" layer) is pinned to the window, so these coordinates do not work on it directly: with the camera panned / zoomed, button.contains_point(mouse) answers in the world and gets it wrong. To know whether the pointer is over a HUD object, read button.pointer_hover (click and hover already use the view).

@= on mouse / mouse.x is live on the first drawn frame. The engine samples the pointer when the window opens (and again if the camera moves while the cursor stays still). Circle(center=mouse) or center=(mouse.x, mouse.y) in the body of the script is still (0, 0): there is no window at init. mouse.dx / on_mouse_move do not fire on that sample.

Don't confuse

Looks likeIt isIt is not
The order in which things get the clickfor press/scroll: widgets → shapes (top, then the rest) → the script's callback. on_mouse_move runs alongside; it is not exclusive.exclusive

Where else to look — Reactive · React · Move

Move

Move, rotate and scale objects — at once or over a stretch of time (time=), in a straight line, along a curve or held inside a region — and animate any field from one value to another (tween). To call a function after a while: Schedule. For a sequence of steps with waits: Mode.

move_to / rotate / scale → move / rotate / scale
Parameters that take time (time= / ease= / loops=…) → Time parameters (time=)
Travel along a curve → move_along
Hold inside a region → confine
Interpolate an Attribute → tween

move / rotate / scale

Verbs that change the position, angle and size of a Graphic (Shape, Sprite, Text). A SpatialFx moves by its .center — see SpatialFx. Without time= the change happens at once and the verb returns the object itself. With time= it happens gradually over those seconds and the verb returns a Handle; it also takes ease= / loops= / yoyo= / then= / on_done= / force= (see Time parameters). Moving and rotating can also travel by speed: speed= instead of time= (units or degrees per second), and the duration comes from the distance.

Absolute (destination)Relative (delta)
Movemove_to(x, y) — Vec2 / Point, about=move_by(dx, dy) — Vec2, polar angle= / distance=, just distance= (forward)
Rotaterotate_to(θ) — short arcrotate_by(dθ) — as written
Scalescale_to(s)scale_by(f)
Along a curvemove_along(track, time=) or move_along(track, speed=)

Collision: place × travel. At once (= / *_to without time=) it places — it goes through the wall. move_by, move_along and move_to(…, time=) (or speed=) travel — the resolve() wall stops them midway, and the @collide of a fast traveler checks the path (Fast objects). Rotating in place and scaling (rotate_* / scale_*, with or without time=) are never stopped by the wall: it only pushes the object away afterwards, if it was left touching. Rotating around another point (rotate_by(…, about=)) travels: the center moves, and the wall stops it. Reset / respawn: hero.center = spawn_point. See Place × travel.

An absolute place. Without time= it places. With time= it travels — each frame it covers a piece of the way, and a wall can stop it midway. With speed= instead of time=, it travels at that speed (units per second): far away takes longer, close by arrives soon. By default the center reaches the destination; about= picks another point of the shape.

c.move_to(400, 200)                 # x, y
c.move_to(Vec2(400, 200))           # Vec2 as the 1st
c.move_to(p)                        # Point as the 1st
c.move_to(400, 200, time=1.2, ease="ease_out")
c.move_to(400, 200, time=1.0, loops="forever", yoyo=True)
missile.move_to(target, time=1.2, face=True)
hero.move_to(mouse, speed=220)               # on a click: walk to the pointer
drone.move_to(drone.dock, speed=300, ease="ease_out")   # all of them return at the same pace

move_to(x, y, *, time=None, speed=None, ease="linear", loops=1, yoyo=False, face=False, then=, on_done=, about=, force=False) · move_to(point, *, …)

ParameterPassType (default)Meaning
x, y1st · 2ndnumber400The destination as two coordinates.
point1stpointThe destination as a single argument: any point — a tuple (x, y), Point, Vec2, a Graphic (its center counts) or mouse. It does not take angle= / distance= (those belong to move_by).
about=name=point or NoneThe point that lands exactly on the destination (not the one that stays fixed). Default: the shape's center. With face=True, the rotation is around this point.
time parametersname=—time= or speed= (the distance from the traveling point to the destination, measured at the call; a None axis does not count) · ease= · loops= · yoyo= · face= · then= · on_done= · force=.

Shifts the object from where it is — an offset, not a destination. It always travels: a resolve() wall stops it midway. Write the offset in one of these ways, one per call: dx, dy · a Vec2 · angle= and distance= · just distance=, toward where the object points. With time= (or speed=), the offset is computed at the start and does not change during the trip.

c.move_by(40, 0)                        # dx, dy
c.move_by(Vec2(40, 0))                  # Vec2 as the 1st
c.move_by(angle=90, distance=40)        # polar (both together)
ship.move_by(distance=200 * dt)         # forward (no angle=: uses ship.angle)
ship.move_by(distance=-80 * dt)         # reverse: backs up without turning
c.move_by(200 * dt, 0)
c.move_by(0, 80, time=0.4)
c.move_by(40, 0, time=0.5, loops="forever", yoyo=True)
bolt.move_by(angle=45, distance=500, time=1.0, face=True)
guard.move_by(300, 0, speed=60, loops="forever", yoyo=True)   # patrols at 60 per second

move_by(dx, dy, *, time=None, speed=None, ease="linear", loops=1, yoyo=False, face=False, then=, on_done=, force=False) · move_by(Vec2, *, …) · move_by(angle=, distance=, *, …) · move_by(distance=, *, …)

ParameterPassType (default)Meaning
dx, dy1st · 2ndnumber20Cartesian offset.
Vec21stVec2The delta as a single argument. A Point raises TypeError — use move_to. A tuple (dx, dy) is not accepted.
angle=, distance=name=number90Polar. Degrees, 0 = +x. Without angle=, it moves where the object points: it reads angle at the time of the call (like raycast(length=)); a negative distance backs up and the direction does not change. angle= without distance= raises TypeError. Do not mix with dx/dy in the same call.
time parametersname=—time= or speed= (the size of the offset ÷ speed) · ease= · loops= · yoyo= · face= · then= · on_done= · force=. No about=.

Turns the object to the angle θ (degrees, counterclockwise, 0 = to the right). Without time= it turns at once; with time= it turns gradually the shortest way (at exactly 180° apart, it turns counterclockwise). With speed= (degrees per second), the duration is that short arc ÷ speed. A resolve() wall does not interrupt the turn: it only pushes the object away afterwards, if it was left touching.

c.rotate_to(45)
c.rotate_to(180, time=0.6, ease="ease_in_out")
c.rotate_to(90, time=0.5, loops="forever", yoyo=True)
turret.rotate_to(aim_angle, speed=90)   # the turret turns at 90° per second

rotate_to(θ, *, time=None, speed=None, ease="linear", loops=1, yoyo=False, then=, on_done=, about=, force=False)

ParameterPassType (default)Meaning
θ1stnumber45Absolute angle.
about=name=point or NoneThe point the object turns around; it stays still. Default: the object's center.
time parametersname=—time= or speed= (degrees per second) · ease= · loops= · yoyo= · then= · on_done= · force=.

Turns dθ more degrees from the current angle (positive = counterclockwise, negative = clockwise). It can go past 180°: 360 makes a full turn. .angle accumulates, without wrapping back to 0–360 (50°/s for 8 s reads 400); to compare directions, use % 360.

c.rotate_by(30 * dt)
c.rotate_by(360, time=1.2)
c.rotate_by(45, time=0.4, loops=4, yoyo=True)
wheel.rotate_by(-720, speed=180)         # two turns at 180° per second: 4 s

rotate_by(dθ, *, time=None, speed=None, ease="linear", loops=1, yoyo=False, then=, on_done=, about=, force=False)

ParameterPassType (default)Meaning
dθ1stnumber30Degrees to add.
about=name=point or NoneThe point the object turns around; it stays still. Default: the object's center.
time parametersname=—time= or speed= (degrees per second; the size of dθ ÷ speed, also with about=) · ease= · loops= · yoyo= · then= · on_done= · force=.

Changes the object's size to value times its original size (1 = original, 2 = double, 0.5 = half), the same in width and height.

c.scale_to(1.5)
c.scale_to(0.5, time=0.3, ease="ease_out")
c.scale_to(1.05, time=0.45, ease="steps", loops="forever", yoyo=True)

scale_to(value, *, time=None, ease="linear", loops=1, yoyo=False, then=, on_done=, about=, force=False)

ParameterPassType (default)Meaning
value1stnumber1.5Absolute factor (1 = original size).
about=name=point or NoneThe point the object grows or shrinks from; it stays still. Default: the object's center.
time parametersname=—time= · ease= · loops= · yoyo= · then= · on_done= · force=. No speed=: a scale is a ratio, not a distance.

Multiplies the current scale. With time=, the factor is frozen at the start.

c.scale_by(2)
c.scale_by(0.5, time=0.25)
c.scale_by(1.1, time=0.3, loops="forever", yoyo=True)

scale_by(factor, *, time=None, ease="linear", loops=1, yoyo=False, then=, on_done=, about=, force=False)

ParameterPassType (default)Meaning
factor1stnumber1.2Relative factor (2 = double the current one).
about=name=point or NoneThe point the object grows or shrinks from; it stays still. Default: the object's center.
time parametersname=—time= · ease= · loops= · yoyo= · then= · on_done= · force=. No speed=: a scale is a ratio, not a distance.
.angle / .scale / reset_rotation
c.angle = 45
c.scale = 1.5
c.reset_rotation()
turret["angle"] @= lambda: dial.value
ship["scale"] @= lambda: 1.0 + 0.15 * st.pulse

Properties

PropertyType (typical value)Read/WriteMeaning
.angle / .scalenumber15read / writeAbsolute state. angle is the heading — where the object points (0 = +x, counterclockwise) — and it is a field, like width: =, @= and the constructor parameter do the same thing, and the point the object was positioned by stays still (center, top_left, p1, vertex; a Rect p1=, p2= tilts). Where the direction comes from the points (Line p1=, p2=, Rect anchor=, Ellipse by its foci, Circle by its rim point, Polygon), changing angle turns it around the center. Sprite / Svg / Text / Point / Track are positioned by the center (Text with an anchor: by the anchor). The verbs rotate_to / rotate_by turn the whole object around the center (or about=). scale is a shortcut for scale_to around the center. An Entity that is not a Graphic (like Entity()) has no real angle: reading it raises AttributeError, and writing it only creates an own field with that name, without turning anything. .scale multiplies the drawing and the collider: .width / .height stay the size you gave (a Sprite with height=40 and scale_to(1.08) still reads height 40); the size on screen is .box.
.rest_headingnumber90readThe angle at which the object has “no rotation” — where the art points; reset_rotation() goes back to it. Shape: 0. Sprite: the art's direction (art_angle), with the flip already counted — see Facing sprites.
.tiltnumber · contact · "ground""ground"read / writeSprite. Tilts only the drawing, without turning the collider. See Tilt.

Methods

MethodSignatureReturnsMeaning
reset_rotation(*, time=None, speed=None, ease="linear", then=, on_done=, about=, force=False)Parameters: time (number), speed (degrees per second), ease (str), then, on_done, about (point), force—Undoes the rotation: brings the object back to the rest_heading angle (Shape: 0; Sprite: the art's direction). It also zeroes .tilt. It does not clear flips. It takes the same time parameters as rotate_to (speed= included), without loops= / yoyo= (a single destination).

Don't confuse

Looks likeIt isIt is not
move_by(p) with a Pointa TypeError. A destination is move_to(p). A delta: dx, dy, Vec2 or angle=/distance=. A bare tuple does not go into move_by. Polar does not exist in move_to.a delta given as a Point
move_by(distance=…, face=True) turns toward where it goesa TypeError. Without angle= the direction already is the angle; face= would turn the object by its own motion (with a negative distance, a U-turn on every call). To back up: drop face=. To turn around: rotate_by(180) first. Or pass angle=.turning
move_to(..., about=, face=True) turns around the centera turn around the about= point — otherwise the anchor would leave the destination the moment it rotates. Among the move verbs, only move_to has about=.the center
turret["angle"] @= … turns around any pointa link (@=) that writes the field: the positioning point stays still (or it turns around the center, where the direction comes from the points). For another pivot, call the verb with about=.rotate_to(…, about=)
x.angle = 30 does the same as x.rotate_to(30)the same only on an object positioned by its center. A Rect top_left= keeps its top_left with angle =; rotate_to turns it around the center — like top_left = versus move_to.—

Time parameters (time=)

The parameters every verb that takes time accepts: how long it lasts (time=) or, instead, how fast it goes (speed=), with which curve (ease=), how many times it repeats (loops=, yoyo=) and what to do at the end (then=, on_done=). They apply to move_to, move_by, rotate_to, rotate_by, scale_to, scale_by, move_along, reset_rotation (without loops= / yoyo=), tween and the camera (without force=). speed= applies only to the verbs that cover a distance: move_to, move_by, move_along, rotate_to, rotate_by, reset_rotation and, on the camera, pan_to / pan_by.

h = ship.move_to(400, 200, time=1.2, ease="ease_out")
ship.rotate_by(360, time=1.0, loops="forever")
ship.scale_to(1.2, time=0.3, loops=4, yoyo=True)
ship.move_to(600, 200, time=1.0, on_done=lambda: play_sound("pop"))
hero.move_to(mouse, speed=200)          # 200 units per second: far away takes longer
turret.rotate_to(90, speed=45)          # 45 degrees per second

Without time= or speed= (except move_along, which requires one of the two, and tween, which requires time=): it happens at once and returns the object. With time= or speed=: it interpolates and returns a Handle. time= and speed= together raise TypeError: both say how long it lasts. ease= / then= / on_done= / loops= / yoyo= require time= or speed= (without them there is no curve: rotate_by(10, ease="ease_in_out") raises an error). start= exists only in tween — to place and then travel with a pose verb, use two lines (center = … and then move_to(..., time=)). The contract for the end: When it ends.

ParameterPassType (default)Meaning
time=name=number or NoneNoneSeconds for one lap. Without it: at once. With it: it interpolates and returns a Handle. In tween it is required; in move_along, pass time= or speed=.
speed=name=number > 0 or NoneNoneA speed instead of a duration: units per second (in move_to / move_by / move_along / pan_to / pan_by) or degrees per second (in rotate_to / rotate_by / reset_rotation). The duration is the distance ÷ speed, measured once, at the call: in move_to, from the traveling point to the destination (a None axis does not count; with about=, from that point); in move_by, the size of the delta; in move_along, the track's length × the portion in span; in rotate_to, the short arc. After that it is the same trip as with time=: the destination does not change if the target moves, and a track that grows later does not change the duration. With ease=, speed is the average speed (in the middle it goes past it). With loops=, it applies per lap (per leg with yoyo=). A zero distance ends on the next frame, with on_done. 0, a negative number, nan or text raise an error. It does not exist in scale_*, tween or the other camera verbs (scale and zoom are ratios, not distances): there, speed= raises TypeError.
ease=name=curve name or function"linear"The curve. Default "linear". Names: linear · ease_in · ease_out · ease_in_out · quad · inv_quad · smoothstep · sigmoid · bounce · elastic · steps · xpsin · erratic, or your own function that takes t from 0 to 1 (the time already elapsed) and returns how much of the way is done (0 to 1). An unknown name → ValueError with the list. spring / wobble do not go here — only in remap(…, modifier=). With loops= / yoyo=, the curve runs forward in each leg (it is not mirrored in time).
loops=name=1, N or "forever"1Same spelling as move_along / play_sound. Default 1. "forever" never fires then= / on_done= — stop it with handle.cancel() or destroy.
yoyo=name=boolFalseOdd laps reverse direction (start and end swap) instead of starting over. Needs loops > 1 (or "forever"); with loops=1 it raises an error. A finite loops=N: it lands at the start if N is even, at the end if N is odd. In move_along, it reverses the span, not the phase.
face=name=boolFalseOnly in move_to / move_by / move_along. Optional: writes .angle in the direction of travel (the straight line or the tangent). Delta ~0 / no motion: it keeps the rotation. With yoyo (and in move_along also with span=(1,0)) it flips 180° the other way. It does not require time= in move_to / move_by.
then=name=mode functionThe mode to enter when the tween ends (finite laps). Pass the mode's function (leaving, self.diving), without (). It is not a callback.
on_done=name=function or NoneNoneA callback when the tween ends (without changing mode). Pass a function to call. The same as passing fn to after. Do not use it together with then=.
about=name=point or NoneNoneA reference point for the motion. It applies to rotate_* / scale_* / reset_rotation / move_to, and on the camera to zoom_* / rotate_*. Default: the object's center (camera: the center of the view). In rotate_* / scale_* the point stays fixed; in move_to it is the point that lands exactly on the destination. move_to(..., about=, face=True) turns around that same point, not the center.
force=name=boolFalseOnly in the object verbs (move / rotate / scale, tween, move_along) — the camera has none. If the field the verb needs to change is linked with @=: False (default) raises LinkedAttributeError; True removes the link (its own and its parts', like center.x), shows a warning and goes on. An escape hatch, not everyday use. See Persistent drivers.

Don't confuse

Looks likeIt isIt is not
time= and duration are the same thingtwo different things: a pose verb takes time= (the trip's seconds); a transient or a screen overlay lasts duration (the seconds the effect stays). sprite.flash(duration) and canvas.flash(intensity) do not have the same first argument: on the sprite it is the duration; on the canvas, the intensity.synonyms
speed= and h.speed are the same thinga request and a reading: speed= asks for the trip's average speed, turned into a duration at the call. h.speed reads how far the object moved this frame, per second. With ease="linear" the two match; with a curve, h.speed starts below and goes past the request in the middle.always the same number
move_to(target, speed=) chases the targeta destination copied at the call, as with time=. If the target moves, the object arrives where the target was. To chase a target that moves, at a steady speed, call approach in update, every frame: enemy.move_to(approach(enemy.center, player.center, 120)).chasing
time= and speed= togethera choice of one: time= fixes the duration and the speed comes from the distance; speed= fixes the speed and the duration comes from the distance. Both together raise TypeError.a combination
The Handle of a trip writes .vela reading only: with time= or speed=, h.velocity / h.speed / h.heading tell what this frame moved, in units per second — but they do not write .vel. For physics: crate.vel = h.velocity. Whatever stands on the platform does not need it: resolve already carries it along. See Handle..vel

move_along

Makes the object travel along a curve: a Track, the outline of any Shape, or a ready-made shape by name ("eight", "circle"…). time= is how long one lap lasts; or pass speed= (units per second along the track) and the lap lasts the length ÷ speed. It always travels: a resolve() wall stops the object on the way. To go to a point in a straight line: move_to(..., time=).

# first step: a string = a floating preset (loops=1)
ship.move_along("eight", time=2)
ship.move_along("circle", time=4, loops="forever")
# a size / your own track: a full Track
wasp.move_along(Track.eight(width=90, height=40), time=2.5)
ship.move_along(Track.circle(center=(400, 300), radius=120), time=4, loops="forever")
bug.move_along(hexagon, time=3, phase=0.2)
ship.move_along(Track(vectors=[(80, 0), (0, 50), (-30, 20)], smooth=0), time=1.2)
moon.move_along(orbit, time=6, face=True, loops="forever", yoyo=True)
# the same speed on tracks of different sizes
small.move_along(Track.circle(radius=60), speed=80, loops="forever")
big.move_along(Track.circle(radius=200), speed=80, loops="forever")

move_along(target, *, time=None, speed=None, ease="linear", span=(0, 1), phase=0, loops=1, yoyo=False, face=False, at=None, then=, on_done=, force=False)

ParameterPassType (default)Meaning
target1stTrack, Shape or strThe track. A Track; a Shape (the object follows its outline, wherever the Shape is, even if it moves); or the name of a ready-made shape, at the default size and placed where the object is: "circle" · "eight" · "star" · "wave" · "spiral" · "arc" · "line" · "shuttle". "zigzag" raises an error (use "eight"). For another size: Track.eight(width=…). A point / (x, y) → TypeError; use move_to(..., time=).
span=name=(u0, u1)(0, 1)Which stretch of the track to cover, from 0 (start) to 1 (end): (0, 1) is the whole lap, (0, 0.5) only the first half, (1, 0) goes backwards — only on this trip; the track does not change.
phase=name=number0.15How far ahead on the track this object starts, as a fraction of the lap (0 to 1): 0.25 starts a quarter of the way along. For a line of objects on the same track, give each one a different phase= in a for (see the example below). yoyo= does not change phase=.
at=name=point or NoneWhere the start of the stretch (span) is put — any point, copied now. Default: where the object is when the trip starts. It only works for tracks with no fixed place (floating ones: the ready-made names, a Track.eight(width=…) with only a size, or Track(…, floating=True)). On a track with a fixed place (made with center= / start=, or a Shape's outline) it raises TypeError — wrap it with Track(source, floating=True).
time parametersname=—time= or speed= (one of the two; with speed=, one lap lasts track.length × the size of the span ÷ speed, measured at the call — phase= does not change the math) · ease= · loops= (default 1) · yoyo= (reverses the span) · face= (tangent) · then= / on_done= (at the end of finite laps) · force=. No about=.
TopicRule
Fleetgroup["wasp"].move_along(…) calls it on each member and returns a list of handles. A different phase per member: the for with phase=. To wait: await parallel(*handles). See Acting in bulk.
An open preset in a loop"wave" / "spiral" / "arc" / "line" with loops="forever": pass yoyo=True — otherwise the object jumps at the seam of the open path. Closed ones ("eight", "circle", "shuttle", …) wrap around on their own.
Same key as move_toA move_along and a move_to(..., time=) on the same object cancel each other: the last one wins.
The followed Shape goes awayIf the Shape whose outline the object follows is destroyed, the object keeps going along the last shape that outline had. The trip is only cancelled if the Shape goes away before the trip's first frame.
HandleIt reports what this frame moved: h.velocity (units per second), h.speed, h.heading (the tangent — the same as face=), h.u (the track parameter) and h.lap (the lap, starting at 0; loops="forever" keeps counting). With speed= and ease="linear", h.speed reads the requested speed. It does not write .vel.
# fleet: a list of handles
handles = group["wasp"].move_along(track, time=4)
for i, w in enumerate(group["wasp"]):
    w.move_along(track, time=4, loops="forever", phase=i * 0.15)
await parallel(*handles)

Don't confuse

Looks likeIt isIt is not
move_along(point) / move_along((x, y))a TypeError. To glide to a point: move_to(..., time=). move_along is a curve: a Track, a Shape's outline, or a preset name.a straight line to the point
ship["center"] @= lambda: track.cursor travelsplacing: it writes the point every frame and goes through walls. To travel: move_along.traveling

confine

Keeps an object inside a region (a Box or a Graphic): when it goes past the edge, confine holds it there (exactly on the edge: with the default by="center", the center sits on it), bounces it or takes it to the opposite side (Asteroids style). It is a call you make in update, right after moving. For walls that push, use resolve; to know when something left the play area, @leave_playfield.

PLAY = canvas.game_view.inset(40)

class Ship(Sprite):
    def on_update(self, dt):
        self.move_by(dx, 0)
        sides = self.confine(PLAY)          # by="center", action="clamp"
        if sides:
            canvas.shake(2)

# platform: the sprite's box stays inside
enemy.confine(platform_box, by="box")

# the ball bounces off the edges (needs .vel)
ball.vel = Vec2(220, 140)
ball.move_by(ball.vel.x * dt, ball.vel.y * dt)
ball.confine(arena, action="bounce")

# Asteroids-style wrap
ship.confine(canvas.game_view, action="wrap")

g.confine(region, *, by="center", action="clamp") → frozenset

ParameterPassType (default)Meaning
region1stBox or GraphicPLAYThe region where the object must stay. It can be rotated: the sides ("left" / "right" / "top" / "bottom") turn with it (as in inset / grid / contains_point). It also takes Rect / Square / Ellipse / Circle / Sprite / Svg (the same contract as box=). The region is always a rectangle: an Ellipse or a Circle counts by its frame (the ellipse's rectangle, rotated with it; the square of the diameter, rotated toward the rim point p1), not by its curve.
by=name=str"center"What is compared to the region. See the by= tab.
action=name=str"clamp"What to do on crossing the effective edge. See the action= tab.

Returns a frozenset of the region's local edges it acted on in this call ("left" / "right" / "top" / "bottom"), or an empty one if nothing happened. In a rotated region, "left" is the local left — the same orientation contract as Grid / Box. Use the return value to react (a shake, a sound, flipping something else); there is no callback.

Which part of self must respect the region.

ValueMeaning
"center" (default)Only the center. The same as the hand-written pattern (if x < 40: center.x = 40). On a Sprite with Sheet(anchor="bottom"), the center is the feet: they are what stays on the edge.
"box"The object's outline stays entirely inside. For that, the region shrinks by half the outline's width and height, measured along the region's sides: the frame of a Rect / Square / Sprite / Svg / Text, the radius of a Circle, the true ellipse of an Ellipse, the vertices of a Triangle / RegularPolygon / Polygon, the ends of a Line, the path of a Track. The measure follows the rotation: a triangle that turns while touching the wall is pushed as it turns, and stays entirely inside. An object bigger than the region: it is held at the center on that axis (a remainder, not an error) — the same spirit as Box.inset.
"overlap"The opposite of "box": the object may stick partly out; the action only fires once its outline has left the region completely (the Asteroids ship: ship.confine(canvas.game_view, by="overlap", action="wrap") vanishes entirely before coming back on the other side). For that, the region grows by half the outline's width and height.
# patrol on a platform: the sprite does not “fall” halfway off
enemy.confine(platform, by="box")

# let it leave until it disappears, then wrap / destroy
sides = shot.confine(view, by="overlap", action="wrap")

For a Sprite, graphic.box is the rectangle of the drawn image (the size you asked for with height= / box=), not the silhouette. The silhouette is only hitbox_shape="auto", in collision. Line / free Polygon / Track / Point have no .box, but by="box" / "overlap" work on them: they are measured by their points (the ends, the vertices, the path; a Point is itself).

What happens when the reference has crossed the effective edge.

ValueMeaning
"clamp" (default)Stops the reference at the edge. It does not touch .vel.
"bounce"Holds it at the edge (like "clamp") and flips the sign of self.vel on the local axis crossed (measured along the region's sides, even when rotated). Requires self.vel to be set already — otherwise TypeError with a hint. The ball comes back at the same speed (it does not lose strength). To bounce weaker, read the return value and reduce .vel yourself.
"wrap"Takes the object to the opposite edge, keeping how far it went past (15 beyond → it comes in 15 inside the other side), with no visible jump.
ball.vel = Vec2(220, 140)

def on_update(self, dt):
    self.move_by(self.vel.x * dt, self.vel.y * dt)
    sides = self.confine(arena, action="bounce")
    if "bottom" in sides:
        play_sound("thud")

A single string (action=), not a bounce= + wrap= combo — this is not collision resolution.

The frozenset of edges is the hook for reacting.

sides = hero.confine(PLAY)
if "left" in sides or "right" in sides:
    hero.flash(0.15)
# empty → it did not touch the edge this frame

The names follow the region's own sides. With angle=30, "top" is the “upper” edge of the tilted region, not the world's +y. The same way Grid.cell_at already thinks of an oriented Box.

confine@leave_playfieldresolve
RoleHolds / wraps / bounces the pose nowTells you when the center leaves the playfieldPushes apart bodies that collide
WhenIn your update / on_updateA step of the frame (after collision)A step of the frame (collision)
RegisteredNo — just the callYes (group or method)Yes (resolve(a, b))
Changes the pose?YesNo (callback only)Yes (stops the body at the wall and pushes it away)

Do not use confine and a tween / move_along / resolve() wall on the same axis — they are separate authorities with no defined precedence. Cleanup when the shot leaves the world: @leave_playfield.

Contract

Method

MethodSignatureReturnsMeaning
g.confine(region, *, by=, action=)Parameters: region (Box or Graphic), by (str), action (str)frozensetKeeps the object in the region. Writes the center (and .vel if action="bounce"). The returned edges follow the region's sides.

Errors

CaseError
An unknown by= / action=TypeError with the allowed list
action="bounce" without self.velTypeError — hint: self.vel = Vec2(…)

Don't confuse

Looks likeIt isIt is not
Calling confine(PLAY) once makes it hold forevera call that acts only on that frame: call it in update / on_update, after moving.a rule registered once (like resolve or @leave_playfield)

A region that shrank down to a point (for example, an inset bigger than the region) is not an error: the object stays at its center, as in the rest of Box.

tween

tween(field, value, time=) takes a field from its current value to value in time seconds. The value can be a number, a tuple / list of numbers, a Vec2, a Color (the value changes gradually, in a straight line, from the current one to the final one — like lerp) or a point. For position, angle and size, prefer their own verbs (move_to…). A new tween on the same field cancels the previous one. It takes the time parameters of the move verbs: time= (required) / ease= / loops= / yoyo= / then= / on_done= / force=. Only here: start= (the initial value; without it, the current value). What to do at the end: When it ends. An object's color, visible and flips cannot be tweened (TypeError with the recipe): animate a color field and link the object's color to it. Neither can glow. line_width and a Sprite's alpha are numbers and can be tweened.

tween(ship["radius"], 80, time=0.4, ease="ease_out")
tween(ship.center, (400, 200), time=1.2)
tween(ship.center, (400, 200), time=1.2, start=(0, 0))
ship.tween(ship["hp"], 0, time=0.6)
# TypeError: tween(ship["color"], …) is not allowed — animate a color field and link:
st.tint = Color("red")
tween(st["tint"], Color("blue"), time=1)
ship["color"] @= lambda: st.tint
tween reference

Options

PropertyType (typical value)Read/WriteMeaning
time=number—parameterHere: seconds, required (without time=, TypeError). It interpolates. The full rule: time parameters.
ease=str or function"linear"parameterHere: the tween's curve. time parameters.
start=same type as to(0, 0)parameterThe initial value. Without it: it uses the current value at the moment of the call. With it: the interpolation starts there — the same format as to (number, point, Color, …). Only in tween, not in move_to / rotate_to / scale_to.
loops=1, N or "forever"1parameterHere: laps. "forever" never fires then= / on_done=. Requires time=. time parameters.
yoyo=boolFalseparameterHere: odd laps reverse direction. Needs loops > 1 or "forever". time parameters.
then=mode functionparameterHere: the mode to enter at the end. time parameters.
on_done=function or NoneparameterHere: a callback at the end. time parameters.
force=boolFalseparameterHere: a field linked with @=: False raises LinkedAttributeError; True removes the link and warns. time parameters.
name=str or None"pulse"parameterSlot: a new tween with the same name=, on the same object (or bare, in the same place), replaces the previous one instead of adding another. Without name=: each call is a new tween.

Methods

MethodSignatureReturnsMeaning
tween(target, to, *, time, ease="linear", start=, loops=1, yoyo=False, then=, on_done=, force=False, name=)Parameters: target (the target, Attribute or Point), to (same type as the current value), time (number), ease (str), start (same type as to), loops, yoyo, then, on_done, force, nameHandleThe target: a field (ship["radius"], ship["hp"]), a field of st (st["t"]; st.t is the number and raises an error) or a Point (ship.center). Color and glow cannot be a target. to must match the current value — a number, a flat tuple/list, Vec2, Color, a point (Graphic, mouse: copied now). start= is optional (the same format as to). It goes from the start to to gradually, in a straight line (like lerp). An incompatible type raises an error right away. time= is required.
e.tween(target, to, *, time, ease="linear", start=, loops=1, yoyo=False, then=, on_done=, force=False, name=)Parameters: target (the target, Attribute or Point), to (same type as the current value), time (number), ease (str), start (same type as to), loops, yoyo, then, on_done, force, nameHandleThe same, on this Entity. It survives a mode change; it dies on destroy.

Don't confuse

Looks likeIt isIt is not
tween(…) in the mode's body survives the changeowned by the mode: a bare tween(…) in the mode's body belongs to the mode and stops when the mode ends. e.tween belongs to the object and keeps going. See scope and cancelling.—

tween(shape.center, …) places. It writes the point every frame, like center =. The resolve() wall does not stop it midway. To travel (the resolve() wall stops it midway): move_to(..., time=), move_by(..., time=) or move_along. The same goes for center @= (including track.cursor).

yoyo=True with loops=1 raises an error. There is nothing to bounce back. With a finite loops=N and yoyo: it lands at the start if N is even, at the end if N is odd. A linked target: force=True (a warning + unlink) or unlink first.

Where else to look — Schedule · Collision · Draw · Time parameters (time=)

Schedule

Do something N seconds from now (after) or every N seconds (every), limit how often an action can happen (ready), and remember that something happened a moment ago (recently). To run something when a condition becomes true, see @when.

after / every → after / every
Cooldown → ready
Time window → recently
then= / on_done= → When it ends
What a tween returns → Handle
The whole map → Which to use

after / every

after(seconds, function) calls the function once, after that much time; every(seconds, function) calls it again at each interval — the first time after one interval, not right away. It fires on the first frame where the time has already passed: with 1/60 s frames, after(0.5) is frame 30 and every(0.25) is frames 15, 30, 45… A frame longer than the interval fires as many times as it should: the rhythm does not depend on the FPS. An after that sets itself again inside its own function is not a steady rhythm: each round starts on the frame where the previous one fired, so the intervals become “at least p” and the delay adds up (up to one frame per round). For a rhythm that changes (invaders that speed up), use every(p, step, name="march") and, only when the rhythm changes (an invader died), call it again with the new p: the name replaces the previous one. The same goes for movements chained with on_done (move_by(…, time=0.12, on_done=next_hop)): each step starts on the frame where the previous one ended. For a path of several steps at a steady rhythm, use move_along on a Track. The time is game time: pause and slow motion apply. Ignore the Handle it returns, keep it to cancel, or give a name= — calling again with the same name replaces the previous one. Inside a mode, bare after / every stop when the mode ends; e.after / e.every keep going (scope and cancelling).

after(2.0, boom)
every(1.2, drop, name="spawn")
ship.after(0.4, then=diving)
h = after(3.0, then=leaving)
h.cancel()
h.pause()
h.resume()

At the module level. The Handle lives in fn.handle.

@after(2.0)
def boom():
    explode()
# boom.handle.cancel()

@every(1.2, name="drop")
def drop():
    spawn()

In a class, @after / @every apply to each object: the timer starts when the object is created and belongs to it (it survives a mode change and stops at destroy).

class Wasp(Sprite):
    @every(2.4, name="fire")
    def volley(self):
        shoot(self)

    @after(0.4)
    def armed(self):
        self.mode = self.diving
after / every reference

Options

PropertyType (typical value)Read/WriteMeaning
then=mode functionparameterOnly in after: the mode to enter when the time is up. time parameters.
on_done=function or NoneparameterOnly in after: the function to call when the time is up (the same as fn). time parameters.
name=str"spawn"parameterSlot: a new timer with the same name=, on the same object (or bare, in the same place), replaces the previous one instead of adding another. Without name=, each call is a new timer.

Methods

MethodSignatureReturnsMeaning
after(delay, fn=None, *, then=, on_done=, name=)Parameters: delay (number, seconds), fn (function), then (mode function), on_done (function), name (str)HandleOnce, after delay seconds: calls fn (or on_done=, which is the same) or enters the mode then=.
every(interval, fn, *, name=)Parameters: interval (number), fn (function), name (str)HandleRepeats. No then= and no on_done= (it never ends).
e.after / .everyParameters: delay or interval (seconds), fn (function)HandleOn this Entity, always. An fn that asks for a parameter with no default value receives the object (ball.after(4, vanish) with def vanish(ball)); with no parameter, it receives nothing. It survives a mode change; it dies at destroy / cancel_process. See scope.
@after / @everyDecorator — schedules the function—At the module level: the timer starts right away (it counts game time, which runs from run() on: @every(0.4) first calls 0.4 s after the start); the Handle is in fn.handle. On a class method: it starts when each object is created. Without parentheses (@every above the def) it raises an error with the right spelling; the same goes for @when, @on_change, @collide_with and @exit_mode.

Don't confuse

Looks likeIt isIt is not
on_done= and then= togetherone or the other: fn / on_done= calls a function; then= changes the mode. Both together raise an error. after(d, boom) ≡ after(d, on_done=boom). Don't mix @every with @collide / @when / @on_mode on the same def.—
every(0, fn) for every framea ValueError. Every frame is on_update (Entity) or update(dt) (script) — both receive dt. The interval must be > 0.EVERY_FRAME or an interval of 0

ready

ready(name, interval) is a cooldown: it returns True once per interval — “can I shoot again yet?”. The rhythm is exact on average: what one frame overshoots counts toward the next, so two Trues in a row can come a little closer than the interval when it is not a whole number of frames. The first call already returns True. It counts game time (pause applies). Called every frame (button held), it keeps the rhythm at any frame rate; after a while without calls (the button was released, even for one frame), it gives True once again, with no burst, and the rhythm restarts from that True.

def update(dt):
    if ready("fire", 0.18):
        shoot()
    if keyp.once("R"):
        ready.reset("fire")
ready reference

ready(name, interval)

Parameters: name (str), interval (number, seconds). Returns True/False.

MethodSignatureReturnsMeaning
ready(name, interval)Parameters: name (str), interval (number, seconds)True/FalseTrue when the interval is up. The name is the slot. Passing the interval again updates the period.
e.ready(name, interval)Parameters: name (str), interval (number, seconds)True/FalseThe same reading, in a slot of this Entity. Two enemies with self.ready("fire", …) don't share a cooldown. It is not a Handle — it dies with the instance; destroy / cancel_process don't touch it.
ready.reset(name)Parameters: name (str)—Resets: the next question returns True.
ready.disable(name) / .enable(name)Parameters: name (str)—Pauses / resumes the slot. Disabled → always False.
ready.remove(name)Parameters: name (str)—Deletes the slot. The next call with an interval creates it again (and returns True).

A one-off roll (30% drop): chance. ready is an interval, not a probability. A callback N seconds from now: after / every. Remembering a boolean for a moment: recently.

recently

recently(name, value, hold=) remembers for a moment that something was true: it returns True if value was true at some point in the last hold seconds. Use it to give the player some slack — jumping right after running off a ledge (coyote time), pressing jump a little before landing — or for “was hit a moment ago”.

def update(dt):
    on_ground = "bottom" in hero.touching_sides
    # Coyote: stays "on the ground" for 80ms after leaving the ledge.
    can_jump = recently("on_ground", on_ground, hold=0.08)
    # Buffer: UP up to 120ms before landing still counts.
    if recently("jump", keyp.once("UP"), hold=0.12) and can_jump:
        hero.vel.y = JUMP
        recently.reset("jump")        # jumped: use up the buffer and the coyote,
        recently.reset("on_ground")   # or the boost comes back on the next frames
recently reference

recently(name, value, hold=0.1)

Parameters: name (str), value (anything — it counts as true if if value: would pass), hold (number, seconds). Returns True/False.

MethodSignatureReturnsMeaning
recently(name, value, hold=)Parameters: name (str), value (anything), hold (number)True/FalseTrue if value is true now, or was in the last hold seconds. The name is the slot. Passing hold again updates the window.
e.recently(name, value, hold=)Parameters: name (str), value (anything), hold (number)True/FalseThe same reading, with the memory of this Entity. In a fleet with self.recently("hit", …), the ships don't mix up their memories. It is not a Handle — it dies with the instance.
recently.reset(name)Parameters: name (str)—Forgets: the next question is False until value is true again.
recently.remove(name)Parameters: name (str)—Deletes the slot. The next call creates it again.

recently returns True on every frame while the window lasts, not just once. It is meant for states and animation. An action that changes movement can't be repeated without harm: setting vel.y = JUMP again on each frame of the window undoes those frames' gravity, and the jump goes higher (in the example above, about 150 instead of 115) — that is why the example calls recently.reset when jumping. Nor is it for what must happen only once (creating an object, playing a sound, adding points): use keyp.once / @when. A periodic cooldown: ready.

When it ends

Verbs that take time — after, move_to(…, time=), tween, transients, play_sound, fades — accept a trigger for when they end: on_done= calls a function; then= changes the mode. This section covers only that; the rest of each verb is in its own section.

then= expects a mode: the mode's function (leaving, self.diving), without (). It is not a callback.

on_done= expects a callback: a function to call, without changing the mode.

after(0.4, then=diving)
ship.move_to(400, 90, time=0.8, then=leaving)
ship.tween(ship["radius"], 80, time=0.4, on_done=boom)
ship.dissolve_out(0.4, on_done=ship.destroy)
canvas.fade_out(0.5, on_done=load_next)
Wherethen= (mode)on_done= (callback)
afterEnters that mode.Calls the function. The same as passing fn.
pose / tween with time=Enters that mode (a finite number of loops). loops="forever" never fires.Calls the function (a finite number of loops). loops="forever" never fires.
transientNot available.Calls when the effect ends — also when a new effect on the same channel replaces it midway.
play_soundEnters that mode.Calls at the natural end (not on cancel, nor after the owner has ended).
canvas.fade_out / fade_inNot available.Calls when the fade finishes. After fade_out the screen stays covered until you call fade_in.
play(clip, next=)Chains a clip (min_hold= / resume= in the Sprite's Clip panel). It is not this contract.

then=ship.destroy does not destroy: destroy is not a mode. To remove the object at the end: on_done=ship.destroy, after(0.2, ship.destroy), a dying mode, or await and then destroy(). A new transient on the same channel replaces the old one and calls the old one's on_done right away (with no sign that it was cut short).

Handle

A Handle is the object that verbs which take time return — after, every, tween, move_to(…, time=), move_along, play_sound, wait. It stands for that task while it runs: keep it to cancel (h.cancel()), pause, read the progress, or wait for the end with await h in an async mode. If you need none of that, ignore the return value. .elapsed / .remaining are in world seconds. In move_along and in move_to / move_by with time=: also .velocity / .speed / .heading. In play_sound: .volume / .pan / .pitch / .level.

h = after(2.0, boom)
h.remaining   # 2.0, then counts down
h.cancel()
if h.done:
    pass

pen = every(0.03, stamp).pause()
pen.resume()

@every(1.2, name="drop")
def drop():
    spawn()
drop.handle.cancel()

async def diving(e):
    await e.move_to(player.center.x, 90, time=0.8)
    await wait(0.2)

# take on the velocity of the travel (you write .vel)
h = platform.move_along(rail, time=4, loops="forever")

def drop_crate():
    crate.vel = h.velocity        # the crate leaves at the platform's velocity
Handle reference

Properties

PropertyType (typical value)Read/WriteMeaning
.doneboolTruereadIt has already finished (successfully or cancelled).
.cancelledboolFalsereadIt was stopped by cancel / a mode change / destroy.
.pausedboolFalsereadFrozen with pause(). True only while alive and frozen. Read-only.
.elapsednumber1.2readGame seconds since the task started (or since the last firing of every).
.remainingnumber0.8readThe opposite of .elapsed: seconds left until the end (after / wait / tween) or until the next firing (every). 0 if it has already finished or was cancelled. Read-only.
fn.handleHandledrop.handlereadModule-level decorator: the Handle of that @after / @every.

Motion readings

PropertyType (typical value)Read/WriteMeaning
.velocityVec2Vec2(80, 0)readUnits per second on this frame (world); after the end, it keeps the last frame's (the on_done reads the arrival velocity). Only in move_along / move_to(..., time=) / move_by(..., time=). It does not write Graphic.vel. Read-only.
.speednumber80readThe magnitude of .velocity. Read-only.
.headingnumber90readDegrees, counterclockwise from +x (like .angle / face=). On the track: the tangent; in move_to / move_by: the direction of the delta. Read-only.
.unumber0.25readWhere the object is on the track, from 0 (start) to 1 (end), already counting span= / phase=. Only move_along. Read-only.
.lapinteger0readThe number of the current lap, starting at 0. loops="forever" keeps counting. Only move_along. Read-only.

Methods

MethodSignatureReturnsMeaning
await hNo parametersWaits (use await)In an async mode or a task. A Handle that is already .done goes through at once. A cancelled one raises Cancelled. A task returns the value of its return.
.cancel()No parameters—Stops now. Safe to call twice, even after destroy.
.pause()No parametersthe Handle itselfFreezes this task's clock (every / after / wait / tween / play_sound). Calling it again does nothing. Returns self. On until / parallel / race it raises TypeError.
.resume()No parametersthe Handle itselfUnfreezes. It does not bring back a Handle that was cancelled or has finished. Calling it again does nothing. Returns self.

Don't confuse

Looks likeIt isIt is not
Handle(...)made by the verb: after, every, tween, wait, move_to(..., time=), play_sound. Keep what it returns: h = after(2.0, fn)something you build by hand — Handle(...) gives a TypeError that says so

Cancelled is a BaseException. except Exception does not catch it. There is no cancel("spawn") by string: the slot is name=; a specific task is its Handle.

Don't write h.remaining = …. TypeError. To renew the duration, after(2.0, fn, name="tail") (the slot replaces it). To stop, h.cancel().

Don't write h.paused = …. TypeError. Use h.pause() / h.resume(). Pausing the world is clock.paused; parking the Entity is e.active = False.

.velocity does not write the Graphic's .vel. Copy it if the physics needs it: crate.vel = h.velocity (not for whatever rides on top: resolve already carries it along). Only bounce= (collision), confine(…, action="bounce") and your own code write .vel. after / every / rotate_* / scale_* / tween raise AttributeError (they have no velocity). A Handle that is already .done or cancelled keeps the last frame's (useful in on_done).

Where else to look — Move · Mode · React · Sound

Mode

A mode is the chapter of behavior an Entity is in: in formation, diving, dying. Each mode is a function; e.mode = e.diving enters it (the function runs). Whatever the chapter starts (timers, movements, sounds) stops on its own when the chapter ends; see Scope and cancelling. For an action that finishes and moves on to another mode, use then=. For a sequence of steps with waits, use an async mode.

Enter a chapter → mode
wait / parallel / race → async / wait
A sequence on the side, or one nobody owns → tasks
Cancel the chapter → Scope and cancelling
The whole map → Which to use

mode

e.mode is the current mode (the function) or None. Write it to switch: the old mode ends and the new one starts. Compare with ==. Writing the same mode again does nothing; to restart it, use goto_mode.

@on_mode
async def diving(e):
    await e.move_to(player.center.x, 90, time=0.8, ease="ease_in")
    await wait(0.2)
    e.mode = leaving

wasp.mode = diving
class Wasp(Sprite):
    @on_mode
    def entering(self):
        self.move_to(self.slot_x, self.slot_y, time=1.0, then=self.formation)

    @on_mode
    def formation(self):
        every(2.0, self.shoot)          # gone when the mode changes
        after(3.0, then=self.diving)    # same

    @on_mode
    async def diving(self):
        await self.move_to(player.center.x, 90, time=0.75)
        await wait(0.12)
        self.mode = self.formation

wasp.mode = wasp.entering

class Director(Entity):
    def setup(self):
        self.mode = self.directing

    @on_mode
    async def directing(self):
        while True:
            self.start_wave()
            await until_empty("wasp")
            await wait(1.4)
Mode reference

Properties

PropertyType (typical value)Read/WriteMeaning
e.modemode or Nonee.mode = e.divingread / writeThe current function, or None. Compare with ==. The same mode does nothing.
e.mode_timenumber1.2readSeconds in this chapter. Resets to zero on entering / re-entering.

Methods

MethodSignatureReturnsMeaning
e.goto_mode(fn)Parameters: fn (the chapter's function)—Always exits and enters (same mode or not).
@on_modeDecorator — marks only—Marks the function as a mode, for whoever reads the code and for the debug tools. It changes nothing at run time: e.mode = fn works with or without it.
@exit_mode(formation)Parameters: enter_fn (the chapter's function, e.g. formation)—Decorator: the marked function runs when the Entity leaves the formation mode (by a mode change, then= or e.mode = None). Use it for appearance and own fields; the mode's timers and movements already stop on their own. The function is a plain one (def), not async.

Don't confuse

Looks likeIt isIt is not
self.mode = self.diving()The mode is the function, not the call: self.mode = self.diving. Assigning the same mode does nothing; force it with goto_mode. then= is When it ends, not a callback. With no mode set, .mode is None.calling the function

async / wait

In an async def mode, await pauses the chapter until something happens (a time with wait, a condition with until, a group becoming empty with until_empty, other tasks finishing with parallel / race) and then goes on to the next line. It only works inside an async mode or a task (or a function they call with await); in update or in a @collide, start the sequence with run_task(…) or use after.

await wait(0.4)
await until(lambda: ship.hp <= 0)
await until_empty("wasp")
await parallel(h1, h2)
i = await race(h1, h2)   # 0 or 1; cancels the other

async def pause(s):
    await wait(s)

async def diving(e):
    await pause(0.4)
Wait reference
MethodSignatureReturnsMeaning
await wait(0.4)Parameters: delay (seconds)Waits (use await)Pauses. Without await it does not block: error. Only in the async code the mode or the task is running, helpers included.
await until(lambda: ship.hp <= 0)Parameters: pred (condition, function)Waits (use await)Waits until the function returns True (Scena checks it every frame). Pass a function (lambda: …) or a field (until(st["over"])), not the condition already computed: a bare True/False raises TypeError, and so does st.over (that is the value). Same script rule as wait.
await until_empty("wasp")Parameters: group_or_id (name or the group)Waits (use await)Empty group. Takes the name, group["wasp"] (a live view, not a copy), or a formula group. Do not use until(group.empty).
await parallel(h1, h2)Parameters: h1 (Handle), h2 (Handle), …Waits (use await)Waits for all of them. Cancelling cancels the rest. Pass the Handle to parallel / race before the next await.
await race(h1, h2)Parameters: h1 (Handle), h2 (Handle), …integerThe first one to finish; cancels the others. Result: an index starting at 0.
set_watchdog(enabled=False)Parameters: enabled (on, True/False)—By default, an async mode stuck in a loop with no await is stopped with an error (the watchdog). set_watchdog(False) turns that check off; only for demos and performance measurements.

wait(0.4) without await does not pause the script. It returns a Handle and the rest runs on. Outside an async mode or a task (update, on_update, @collide, a sync mode) it is a TypeError. Inside, without await (and without passing it to parallel / race), it is a TypeError naming the line and the missing await. Outside async code, start the sequence with run_task(…) or use after(…).

Only modes and tasks are async. Scena runs an async mode and a task (run_task) as a script; everything else it only calls. That is why async def setup, async def on_update, an async @every / @when / @collide / on_click / on_done=, or after(1, lambda: self.walk()) with an async walk are a TypeError: the body would never run. The same goes for a function Scena asks a question: a filter (group["x"].filter / any / all / count_where, nearest(where=)), the condition of until / @when, the target of @on_change, resolve(only=) and a @= formula: the answer of an async function is not a value. Write a plain def and start the sequence from it: as a task (self.run_task(self.intro), run_task(intro)) or as a mode (self.mode = self.intro). An async helper is fine when the mode or the task calls it with await. Calling an async function without await (self.intro() alone on a line) runs nothing: Scena warns (SCENA WARNING) with the line.

tasks

A task is an async def sequence that runs alongside everything else without being a mode: run_task(reveal) runs reveal() right away up to the first await and carries on over the next frames. Use it for a button that sets off an animation in steps, a power-up that lasts a few seconds while the ship changes modes, a countdown on the screen.

A loop with await wait(p) goes around once every p seconds at least, always on a whole frame: wait(0.02) waits 2 frames at 60 Hz (0.033 s) and 3 at 144 Hz (0.021 s), so “move 5 every 0.02 s” moves faster on faster screens. For speed, move with dt in update (or on_update) or use @every, which keeps the remainder between rounds.

async def reveal():
    await panel.move_to(600, 300, time=0.5)
    await wait(0.2)
    await parallel(panel.rotate_by(90, time=0.3),
                   caption.move_by(0, 40, time=0.3))

start_btn.on_click = lambda: run_task(reveal, name="reveal")   # another click restarts it

class Ship(Sprite):
    @collide_with("powerup")
    def grab(self, item, info):
        item.destroy()
        self.run_task(self.triple_shot, name="power")      # survives mode changes

    async def triple_shot(self):
        self.shots = 3
        await wait(4)
        self.blink(2.0)
        await wait(2)
        self.shots = 1

Mode or task?

A mode is what the object is doing, one at a time; entering another cancels the previous one. A task is extra work (a power-up, a blink, a countdown) or a sequence on the screen that does not belong to a single object. Several tasks run together.

Owner

The same as for after: an object's method (run_task(self.flicker)) or a lambda that uses self → the task belongs to that object and ends at destroy; inside a mode's body → it belongs to the mode and ends when the mode exits; a loose call → it belongs to the current Act (to the whole game, if called at the top of the file). panel.run_task(reveal) gives the task to panel (it survives the panel's mode changes) and calls reveal(panel) if reveal takes a parameter. Arguments: run_task(lambda: reveal(panel, 2)).

Clicked again?

  • run_task(reveal) on every click: the runs go on together.
  • run_task(reveal, name="reveal"): a new click cancels the run in progress (and what it started) and starts over.
  • To ignore clicks while it runs, keep the Handle: if h is None or h.done: h = run_task(reveal).

What a task starts is its own

An after, a wait, a movement or another task started inside the task ends with it: cancelling the task (h.cancel(), name=, the owner destroyed, the Act changed) cancels that work. A task that finishes normally lets that work go on. The first part (up to the first await) runs right away, where you called run_task; the rest runs in the frame's process step, like an async mode.

A task at the top of the file, before run(). Its first part runs there, at the top: what it makes belongs to the top of the file and survives Act changes, and a change_act in it raises an error (the game has not started yet). Start with await wait(0) so the rest runs once the game is going. Such a task belongs to the whole game: a tween on an st field that it starts goes on after change_act (st belongs to no Act) — keep the Handle and cancel it, or give it name=.

Task reference
MethodSignatureReturnsMeaning
run_task(fn, *, name=None)Parameters: fn (async function, or a lambda that calls one), name (slot, text)HandleRuns fn as a task. Owner as with after. name=: a new task with the same name cancels the one running.
e.run_task(fn, *, name=None)Parameters: fn (async function), name (slot, text)HandleThe task belongs to e: it ends at destroy / cancel_process and survives mode changes. fn receives e if it takes one parameter.
await hNo parametersthe value the task returnsWaits for the task to end (in an async mode or another task). Also works in parallel(h1, h2) / race(h1, h2).
h.cancel()No parameters—Stops the task and what it started. h.done, h.elapsed as on any Handle; h.pause() does not work on a task (pause the owner with active = False).

run_task(reveal()) with parentheses is a TypeError. Pass the function; for arguments, run_task(lambda: reveal(panel, 2)). A plain def function is refused too (call it directly or use after), and so is a mode (@on_mode): enter it with self.mode =.

When what the task is waiting for is cancelled from outside, the task stops and Scena warns with the reason: the object that was moving was destroyed, another movement took the same property. If that is expected, put try: … except Cancelled: around the await; for the task to end along with the object, start it on the object: panel.run_task(reveal). Cancelling the task itself (owner destroyed, name=, h.cancel()) is silent.

A task waiting on an until that never becomes true gives no warning: the game goes on and the sequence simply does not continue. To see what each task and each mode is waiting for, for how long and on which line: Ctrl+Shift+6 or show_processes(). A wait of 5 s or more on an until shows up as SLOW.

Scope and cancelling

A mode is a chapter of behavior. Everything you start while that chapter is running goes away when the chapter ends, unless you say otherwise with e.after / e.every / e.tween / e.run_task.

What a mode is

A mode is the function in e.mode: the Entity's current chapter (formation, diving, dying…). Entering the chapter runs the body once; leaving cancels that chapter's work and calls @exit_mode, if there is one. Compare with ==. For an action that finishes and moves on to another mode, use then=. For a sequence of steps with waits, use an async mode with await.

The one rule

What the mode starts while it is running belongs to the mode and goes away when you leave. Outside the mode's body (setup, on_update, @collide, @when, loose script) there is no “current chapter”: the work belongs to the object you call it on (ship.after: the owner is ship) or, for a loose call, to the whole game (if made at the top of the file) or to the current Act (if made later; see Acts).

For work to survive a mode change, call it on the object explicitly: ship.after(…), ship.every(…), ship.tween(…). These live until destroy or cancel_process.

What cancels (and what does not)

These calls, in the mode's body, take on the chapter's scope and are cancelled on a change:

  • after / every (loose call)
  • wait / until / until_empty / parallel / race
  • tween(…) (without the e.)
  • move_to / move_by / move_along / rotate_* / scale_* with time=
  • play_sound (loose call)
  • run_task(…) (loose call) and what that task starts
  • the mode's async script

These are not cancelled on a mode change:

  • e.after / e.every / e.tween / e.play_sound / e.run_task: Entity scope (they die at destroy / cancel_process; at destroy, a sound that ends on its own finishes playing)
  • script timers (module level, no mode running): these go away when the Act changes (change_act, see Acts) if they were created after the top
  • transients (blink, flash, dissolve_out, …) and sprite.play
  • event functions (@collide, @when, on_click)
Where / howScopeMode change
In the mode's body: after / every / wait / tween / move_*(time=) / …"mode"cancels
e.after / e.every / e.tween / e.run_taskalways the Entitydoes not cancel (dies at destroy / cancel_process)
after(…, bomb.destroy) of another Entity, from inside the modethat other Entitynot cancelled with this mode
The Entity's setup / on_update / @collide: after(0.1, self.shoot) or a lambda / inner def that uses self (after(0.1, lambda: self.set_color("red")))the Entity (self)does not cancel (there is no surrounding mode); dies at destroy: a destroyed enemy does not shoot afterward. Exception: in on_destroy the lambda belongs to the script and runs after the death
loose script at the top of the file (after(…), play_sound(…), tween(…))"game": the whole gamedoes not cancel; lasts the whole game
loose script after the top (update, event functions, an Act's setup)"act": the current Actdoes not cancel; goes away at change_act
transients / playoutside the schedulerdoes not cancel

Sound is the exception: when the owner ends, a sound that ends on its own finishes playing. This holds for a mode change, destroy() and change_act. play_sound("boom.wav") right before self.destroy() or change_act(…) is heard in full. Only sounds that would never end are cut: loops="forever", a name= slot (music, ambience), a paused sound, the mic monitor. A sound with a fade_out in progress ends on its own: the fade finishes. The on_done / then= of a sound whose owner has ended does not run. h.cancel() and cancel_process() cut everything. Every cut has a ramp of ~5 ms (no click).

cancel_process(): restart without destroying

Keeps the Entity; cancels everything it has in progress (timers, tweens, movements with time=, sounds, both the mode's and the Entity's own) and sets mode to None without firing @exit_mode or on_destroy. Own fields, tags, active, on_update and @when stay. Transients: clear_transients().

I wantI use
Pause a Handle (it stays pending)h.pause() / h.resume()
Pause the Entity's timers (they stay pending)e.active = False
Cancel timers, tweens, sounds and the modee.cancel_process()
Remove for goode.destroy()
Leave the mode with exit hookse.mode = None
# Restart: destroy the disposable fleet; restart what stays
group["wasp"].destroy()
group["bolt"].destroy()
player.cancel_process()
player.clear_transients()
player.hp = 3
player.active = True
avatar.goto_mode(avatar.playing)       # force re-enter; playing is a mode of the class
director.goto_mode(director.directing)

There is no global reset_all for the author. A Handle you kept becomes .cancelled (you can ignore it or cancel it again).

Usage patterns

@on_mode
def formation(self):
    every(2.0, self.shoot)              # gone when leaving formation
    after(3.0, then=self.diving)        # same
    self.move_along(track, time=2.4, loops="forever")  # same

@on_mode
def hurt(self):
    # i-frames: must survive if the mode changes midway
    self.after(0.7, lambda: self.untag("hurt"), name="hurt")

A loose call in the mode = the chapter. self.after / self.every = the Entity. The two are not synonyms.

@exit_mode and try/finally

The chapter's timers and movement already cancel on their own. Use @exit_mode for what is not a Handle: appearance (glow, visual…), own fields, flags:

@on_mode
def charging(self):
    self.glow = True
    after(0.5, then=self.diving)   # cancels on its own if you leave early

@exit_mode(charging)
def charging_exit(self):
    self.glow = False              # appearance: needs @exit_mode

This works for a sync or an async mode. The exit hook is always a plain function (not async).

In an async mode, try/finally also works when the cleanup needs to sit next to the setup (rare: most Handles go away on their own):

@on_mode
async def formation(self):
    self.glow = True
    try:
        every(2.0, self.shoot)
        while True:
            await wait(5.0)
            if chance(0.5):
                self.mode = self.diving
                return
    finally:
        self.glow = False   # also runs if the mode is cancelled

Prefer @exit_mode for appearance / own fields (one place, every way out). Prefer not to cancel a Handle by hand: the mode's scope already does that. destroy() and cancel_process() do not fire @exit_mode; use on_destroy for “the Entity is gone”, or set e.mode = None first if you need the exit hooks, then cancel_process() for whatever is left.

Where else to look — Schedule · Entity · React

Acts

An act is one part of the game — title, level, game over — written as a class, class Play(Act); change_act moves from one to the next, with no cleanup code for you to write. What the top of the file creates stays on the stage for the whole game. What an act creates leaves with it, and what it changes goes back to how it was. Acts are optional: a game without acts (run()) works as always.

Write an act → Act
Start / change / restart → change_act
What leaves, what comes back, what stays → The stage and the act
Score, lives, level → Game data
@when, @collide and fades in an act → Act rules

Act

An act is a plain class. setup(self) builds it; on_update, @when and modes run the logic of this act. No cleanup code: everything it created leaves on the change.

# ---- the stage: top of the file, lasts the whole game ----
def new_game():                   # the data of a game that starts
    st.score = 0
    st.lives = 3

st.best = 0                       # lasts across games
new_game()                        # run(Play) directly also finds st ready

class Hero(Sprite): ...           # classes are just definitions

# ---- acts ----
class Title(Act):
    def setup(self):
        Text("GALAGA", center=(500, 500), font_size=72)

    def on_update(self, dt):
        if keyp.once("SPACE"):
            new_game()
            change_act(Play)

class Play(Act):
    def setup(self):
        Hero(center=(500, 70))
        scoreboard = Text("", top_left=(20, 760))
        scoreboard["text"] @= lambda: f"Score {st.score}   Lives {st.lives}"

    @when(lambda self: st.lives == 0)
    def lost(self):
        self.after(1.5, lambda: change_act(GameOver))

class GameOver(Act):
    def setup(self):
        Text("GAME OVER", center=(500, 400))
        self.after(8, lambda: change_act(Title))

run(Title)
In an act class
WriteMeaning
setup(self)Builds the act. No parameters — data comes from st.
on_update(self, dt)Per-frame logic of this act.
@every / @after / @when / @on_changeRules of the act: switched on when it starts, gone when it ends.
self.mode = self.fleetA mode of the act (chapters inside an act).
self.after(…) / self.play_sound(…)Owned by the act: they stop on the change (a sound that ends on its own plays to the end).
self.notice = Text(…)The act's memory — only for an object that a later method uses.
on_destroy(self)Runs first on the change, with the act's objects still alive. Rarely needed: everything else leaves and goes back on its own.

The simple way is plain classes: class Play(Act), and what repeats goes in an act that reads st (st.round) or in a function at the top called from setup. An act can inherit from another (class Boss(Play)): the base's on_update, @every and @when apply once in the child act, and the base's setup runs only if the child calls super().setup(). No __init__, no setup(self, lives). An act has no body: @collide_with, class-level @leave_playfield, on_click and on_collide raise an error when the class is defined. So do self.destroy(), self.active, self.tag(…), self.visible and self.cancel_process() — the message says what to use.

In 0.6.0, Scene and change_scene were renamed Act and change_act; with from scena import * the old names no longer exist (NameError): replace Scene with Act and change_scene with change_act.

change_act

run(Title) starts with the first act. change_act(Play) changes at once: the previous act leaves, the new one is built, and the next line already runs in the new one. Always a new act — change_act(Play) inside Play restarts it.

class Play(Act):
    def on_update(self, dt):
        if keyp.once("R") and st.lives > 0:
            change_act(Play)            # restarts: always a new Play

    @on_mode
    async def fleet(self):
        build_fleet()
        await until_empty("enemy")
        st.round += 1
        change_act(Play)                # last line: the mode stops here

Make change_act the last thing. After it, the previous act's objects are dead and whatever you create already belongs to the new act (the same advice as for destroy()). It works anywhere a call works: update, a timer, @when, @collide, on_done=, the last line of an async mode. The same key press does not carry over to the new act: keyp.once is used up by whoever reads it first.

MistakeFix
Play()You don't build acts by hand: change_act(Play) — or run(Play) for the first one.
change_act(Play()) / change_act("Play")Pass the class: change_act(Play).
change_act(Play, lives=2)Only the act. Data goes in st: st.lives = 2, then change_act(Play).
change_act before runThe game has not started yet: run(Title).
change_act in a game started with run()To use acts, start with run(Title).
change_act in an on_destroy during a changeAn error that names the hook and the act that was leaving; the change ends in the act asked for first. Act flow belongs in the act: an @when of the act.

The stage and the act

The top of the file builds the stage: it stays for the whole game and works in every act. Everything created after that — by any code, even a shot fired from Hero.on_update — belongs to the current act and leaves with it.

On an act changeWhat
LeavesObjects (Shape, Sprite, Text, SpatialFx, Entity, widgets) — on_destroy runs. Timers, tweens, sounds and camera tweens with no owner on the stage — but a sound that ends on its own plays to the end (without on_done); a "forever" loop, one with name= and a paused one are cut off. Bare @when / @on_change / @collide / @leave_playfield written in setup. Post and background created in the act. Formula groups (group["targets"] @= …) created in the act. A collision tag that no remaining rule names stops enrolling members (an object that only that tag put into collision leaves it; a collidable = True you wrote stays). A camera movement with time=, whoever owns it. The script's ready / recently slots. Pending shake / flash / explosion_at. @= links between objects that leave together go away silently.
Goes back to what the top left (or to the default)Camera, canvas.background, canvas.effects and the background (list and .enabled), canvas.playfield, clock.scale / clock.paused, collision.resolve_enabled, collision.floor, canvas.layers.default, set_defaults, the resolve pairs, the top's formula groups, the HUD column (the act's next Text or widget without y always starts in the same place).
Staysst. Objects on the stage and their timers (radio.play_sound(…)) — except what the act handed them: a method of the act (or a function that reads the act's self) in hero.every(…), hero.on_update or hero.mode leaves with the act. A stage timer or sound whose name= the act reused is paused during the act and comes back after the change — whether reused in a bare call, on the act itself (self.every(…, name=), self.play_sound(…, name=)) or with a method of the act as the callback. A stage task (run_task at the top) does not pause: reusing its name in a bare call in the act (no owner: run_task, after, every, tween, play_sound) is an error that gives the fix (another name, or cancel() on it first). With an owner (hero.run_task(…, name=), self.every(…, name=)) it is another slot, and the stage task keeps going. Layers on the stage (a layer created in the act leaves with it; restarting the act creates it again). Preferences: the audio volume, fx_quality, post_fx_scale, display, framerate, ui.scale / ui.font. The fade (fade_out / fade_in).

Rule of thumb: if it should start from scratch every time, create it in setup. If it should survive every act, create it at the top. Music played at the top carries across acts; music played in setup stops on the change.

I need…How
Data that carries across acts (score, high score, did they win?)st
Act music that fades out softly on the changeKeep the Handle and start the fade in the act's on_destroy: self.music.fade_out(0.5). It finishes fading in the new act.
Something started mid-game that outlives the act (music turned on by a key)An owner at the top: radio = Entity(), then radio.play_sound(…) / radio.after(…) from anywhere.
An object in every act, shown only laterCreate it at the top and hide it on the next line (panel.visible = False); an act shows it (panel.visible = True). The state is the object's own: the change does not hide it again.
An object created inside an act that becomes part of the stageThere is no such thing: it goes away on the change → move it to the top.

Ownerless work (bare after(…), play_sound(…), tween(…)) has h.scope == "game" when it starts at the top and "act" after that — "act" work leaves on the change. The SCENA WARNING for ownerless work says <game> / <act> the same way.

An @= that the act makes on a stage object (hud["text"] @= lambda: f"Score {st.score}" in setup) belongs to the act: on the change the link leaves and the field goes back to what it was before — the stage's link, if there was one, or the value (hud.text goes back to ""). Restarting the act links it again without a warning, and the next act can write hud.text = "SHIPS". This also holds when the formula read an object of the act or the act itself (self.score).

Game data

Everything the next act needs to know lives in st. A new game is a function at the top (new_game()), called at the top and by the act that starts a game. An act change never clears st.

st.won = True
change_act(GameOver)               # GameOver.setup reads st.won

class Play(Act):
    def setup(self):
        st.score_on_entry = st.score   # in case a restart should undo points

Restarting (R) keeps st as it is: the lives and score so far. Whatever must be undone is saved on entry, in plain sight in the code.

Entities find each other by group, never through the act: group["hero"].nearest(self). The act does not keep the hero — the HUD and the losing rule read st.

self.enemies = group["enemy"] is an error on any Entity: look a group up where you use it; don't store it. Fields hold any value except a function; a stored object that has died reads as false (if self.notice:). A hero at the top of the file belongs to the stage: it keeps lost lives and tags, and shows up on the title — create it in setup.

Act rules

A rule (@collide, @when, @on_change…) applies according to the moment it is registered, not where it is written: at the top of the file, the whole game; in an Entity class, that object; inside setup, only this act.

@collide("shot", "enemy")            # top: the whole game (idle where there are no shots)
def hit(shot, enemy):
    shot.destroy()

class Practice(Act):
    def setup(self):
        @collide("enemy_shot", "hero")      # only in this act
        def harmless(shot, hero):
            shot.destroy()

The top's update and on_key_down run in every act. An act's logic goes in its on_update; the act's keys and mouse go in there too (keyp.once("R"), mouse.press()). A def update(self, dt) or def on_key_down(self, key) inside the act class would never run: it is a TypeError on the class line, with the act's spelling.

@when fires when the condition turns true (false → true). A condition that is already true when the act starts never fires: restarting Play with st.lives == 0 would leave the act stuck. Guard the change (keyp.once("R") and st.lives > 0) or check the state in setup.

Transitions

You put fades together yourself — there is no fade= on change_act. The fade belongs to the stage and carries across the change:

canvas.fade_out(0.5, on_done=lambda: change_act(Play))     # previous act

class Play(Act):
    def setup(self):
        canvas.fade_in(0.5)                                  # new act

Don't confuse

Looks likeIt isIt is not
Act × modeA mode is a chapter of one object's behavior (self.mode = self.dive; the same mode again does nothing; then= enters a mode). An act is the part of the game the player is in (change_act(GameOver); always new; owner of everything created in it). An act can have modes.There is no then= for acts, no stack of acts, no pause act — pausing is clock.paused = True.

Where else to look — Mode · Scope and cancelling · st · Camera

Sound

Playing a file is play_sound("laser.wav"). It returns the same Handle as in Schedule — cancel, await, on_done, then=, name=. The sound belongs to whoever played it, like a timer (scope and cancelling): the mode, the Entity, or the whole game / the current Act — and when that owner ends, a sound that ends on its own finishes playing. Sound("x.wav") only loads the file (like Sheet): it does not play or show up on its own. Effects (echo, filter…) go on the Handle while the sound plays; to apply them once and keep the result, use Sound.bake.

Play / audio data / bake → play_sound
Master volume, level, spectrum, amp_db → audio
Capture / record → Microphone · mic.record
Filters / echo / distortion → effects

play_sound

play_sound plays a sound file (or a Sound already loaded, or the microphone) and returns a Handle to control that playback: volume, pause, fade, effects. Sound("x.wav") only loads the sound, without playing it. h.pause() holds the sound; h.resume() continues it.

import random
play_sound("laser.wav")
play_sound("hit.wav", volume=0.6, pan=-0.2, pitch=1.05)
h = play_sound("laser.wav", on_done=ship.destroy)

play_sound("theme_a.mp3", name="music", loops="forever")
play_sound("theme_b.mp3", name="music", loops="forever", crossfade=1.0)

laser = Sound("laser.wav", volume=0.7)
play_sound(laser, pitch=random.uniform(0.95, 1.05))   # live rate (changes the duration)
crunch = laser.bake(Distortion(), transpose=3, pitch=1.1)
play_sound(crunch)   # PCM already processed — cheap

class Ship(Sprite):
    @on_mode
    def flying(self):
        play_sound("thrust_loop.wav", loops="forever")   # stops when the mode ends

    @on_mode
    def cruising(self):
        self.hum = self.play_sound("engine.wav", loops="forever")  # outlives the mode

    @exit_mode(cruising)
    def cruising_exit(self):
        self.hum.fade_out(0.3)

The two name="music" above swap because they run in the same place. The slot is per place (slot): a bare call in an act's setup and a bare call inside one of the act's modes are two slots, and both songs play. For music in an act that switches between phases: self.play_sound("theme.ogg", name="music", loops="forever") in the act, always.

No sound on Python 3.15. Sound uses the miniaudio package, which has no ready-made build for Python 3.15 yet (nor for Windows or Linux on ARM). There pip install scena installs Scena without it and the game runs silent: the first sound shows a SCENA WARNING, every sound becomes 1 second of silence, and Handles keep time as usual (on_done, await). For sound, use Python 3.14 (on ARM no Python has the build), or run python -m pip install miniaudio (it needs a C compiler).

play_sound reference

Function / audio data

MethodSignatureReturnsMeaning
play_sound(source)Parameters: source (file path, Sound or Microphone); volume (1 = original; can go above 1), pan (−1 left … 1 right), pitch (1 = normal; 2 = an octave higher and twice as fast), loops=1 (int or "forever"), fade_in (seconds rising from silence), crossfade (with name=: seconds of mixing with the sound that was playing in that name=), on_done, then, nameHandlePlays. Who owns it: in a mode's body → the mode; e.play_sound → the Entity; a bare call → the whole game (at the top of the file) or the current Act (later — see Acts). When the owner ends, a sound that ends on its own finishes playing; a "forever" loop / name= / a paused sound are cut. A missing / corrupted file: silence for its nominal duration + a warning in the banner (once per asset). The Handle keeps running — on_done and loops still behave. A clip still being recorded raises RuntimeError — mic.stop() or await first.
Sound(path)Parameters: path (str); volume (its default volume); stream (True/False, optional)SoundAudio data. Does not play. Short clips (< 8 s) go into memory; long ones stream. stream= forces the choice. No .effects.
Sound.bake(*fx, transpose=0, pitch=1)effects from the catalog; transpose (semitones, same duration); pitch (rate, changes the duration)SoundApplies transpose, pitch and the effects once and returns a new Sound, already processed — playing that Sound costs nothing extra. Order: transpose → pitch → effects; the Echo/Reverb tail is included in the new sound.
e.play_sound(src)Same as play_soundHandleAlways Entity scope: survives a mode change; stops at destroy (a sound that ends on its own finishes playing).

On the sound Handle

PropertyType (typical value)Read/WriteMeaning
.volume / .pan / .pitchnumber0.6read / writeChange the sound right away, while it plays. Volume can go above 1; Scena only keeps the sum of all sounds from clipping. Pan −1…1. Pitch 1 = normal (rate — changes the duration; cheap). On a mic monitor, pitch is ignored.
.fade_to(v, time=)methodh.fade_to(0.2, time=0.4)methodVolume ramp. World clock (follows clock.scale), like any tween.
.fade_out(time=)methodh.fade_out(0.3)methodRamps to 0 and stops (a natural end: on_done fires). It is not cancel. No Echo/Reverb tail afterward.
.levelnumber 0…10.4readHow loud this sound is right now, from 0 (silence) to ~1 (the maximum), already smoothed (audio.level_tau). For bars: amp_db(.level).
.spectrum(bins=8)list[0.1, 0.8, …]methodSplits this voice's sound into bins bands, from the lows (~40 Hz) to the highs (~16 kHz); each value (0…1) says how much sound is in that band right now. Smoothed like .level (audio.level_tau). A sound-only attribute: on a Handle that is not a sound it raises AttributeError with the hint — the same goes for .volume, .pan, .pitch, .fade_to, .fade_out, .level, .effects.
.effectsstackh.effects.add(LowPass())readSee effects. Only on the Handle / mic — not on Sound.

From the generic Handle

PropertyType (typical value)Read/WriteMeaning
.remainingnumber0.4readTime until the audible end (clip + Echo/Reverb tail, if any). Same contract as the Handle — not specific to sound.

Sound("laser.wav") does not play. It only loads the file. Use play_sound. A fade is never automatic: if you want one, write fade_in= / .fade_out() / crossfade=. When the mode ends, a sound that ends on its own finishes playing; a sound with loops="forever", with name= or paused is cut right away (with a ~5 ms ramp, no click).

on_done fires only at the natural end (the Echo/Reverb tail included). .cancel(), .pause(), a mode change and name= (a cut) do not fire it. loops="forever" never ends on its own. Live pitch= ≠ transpose= in bake (the latter keeps the duration).

audio

audio is the game's sound as a whole: overall volume, mute, and meters of what is playing (level, spectrum) — for bars that jump with the music. amp_db converts those readings to the scale the ear hears, ready for a bar's height.

audio.volume = 0.8
audio.level_tau = 0.08

play_sound("theme.mp3", loops="forever")

N = 8
bars = [Rect(width=18, height=4, color="cyan") for _ in range(N)]

def update(dt):
    spec = audio.spectrum(bins=N)
    for i, bar in enumerate(bars):
        bar.height = 8 + 160 * amp_db(spec[i])   # floor=-60 by default
        bar.center = (80 + i * 28, 120 + bar.height / 2)
audio reference
PropertyType (typical value)Read/WriteMeaning
audio.volumenumber0.8read / writeMaster gain. 0 silences everything without cancelling any Handle.
audio.mutedboolFalseread / writeTrue silences everything; False goes back to the volume from before.
audio.level_tauseconds0.08read / writeHow long the smoothing of level / spectrum takes to catch up with the sound, in seconds (in the mix, in each sound and in the mic). Smaller = jumpier bars. ≤ 0 raises ValueError.
audio.levelnumber 0…10.4readHow loud the whole game's sound is right now (all sounds added together), from 0 (silence) to ~1 (the maximum), already smoothed. Read-only. For bars: amp_db(audio.level). Link it: bar["width"] @= lambda: 300 * amp_db(audio.level) follows the sound, once per frame. The h.level of a play_sound links the same way.
audio.spectrum(bins=8)list8 numbersmethodSplits the game's sound into bins bands, from the lows (~40 Hz) to the highs (~16 kHz); each value (0…1) says how much sound is in that band right now. You only choose the number of bands (bins=).
amp_db(x, floor=-60)number 0…1amp_db(audio.level)functionConverts a 0…1 reading (level or a spectrum value) to the ear's scale (decibels), also 0…1, ready for a bar's height: 1 stays 1; anything floor decibels below the maximum (default −60) or lower becomes 0. Values ≤ 0 give 0; values above 1 stay at 1.

.level / .spectrum are linear (0…1). For bars, use amp_db. Otherwise the lows drown out the rest. The smoothing is built in; there is no need to average in update.

Microphone

Microphone() opens the computer's microphone — nothing is captured before that. With it you measure the voice's volume (mic.level), listen live (play_sound(mic)) and record (clip = mic.record(); the clip plays after mic.stop() or await).

mic = Microphone()          # the system's default input
print(mic.level)
bar = Rect(top_left=(20, 20), width=0, height=10)
bar["width"] @= lambda: 300 * amp_db(mic.level)   # follows the voice
play_sound(mic)             # listen live (with mic.effects)
mic.effects.add(Echo())     # only on what you hear live — the recording has no echo

clip = mic.record()         # Sound, still recording
mic.stop()                  # clip ready; the mic stays open
play_sound(clip)

h = play_sound(clip)
h.effects.add(Echo())       # effect on playback
play_sound(clip.bake(Distortion()))

clip = await mic.record(seconds=2)
mic.close()                 # releases the device; not the same as stop()
Microphone reference
MethodSignatureReturnsMeaning
Microphone(backends=None)Parameters: backends (list of miniaudio.Backend; advanced — tests / diagnostics)MicrophoneOpens the system's default input. No device: a SCENA WARNING and a silent mic (.level stays 0). A recording with seconds= still ends, full of zeros, so the await does not get stuck. There is no choice of input or output device.
.record(seconds=None)seconds (of captured samples, not of game clock); on_done, thenSoundStarts recording a clip without the effects in mic.effects (they only apply to what you hear live). It does not play yet. seconds= must be finite, > 0 and ≤ 30 (ValueError otherwise). Without seconds=, it records until stop() or the 30 s cap. At the cap: a normal end + one warning per mic. Already recording, or the mic is closed: RuntimeError. Who owns it: in a mode's body → the mode; a bare call → the whole game (at the top of the file) or the current Act (later — see Acts). on_done / then= run on the next frame, only at a natural end.
.stop()No parameters—Ends the recording and keeps the clip. The mic stays open. The clip plays on the very next line; on_done waits for the next frame. With no recording running: RuntimeError — call record() first.
.recordingboolboolRead-only. True while recording.
.availableboolboolRead-only. True while a microphone is open; False with no microphone (the mic is silent, .level 0) or after close(). To offer another control: if not mic.available: ….
.level / .spectrum(bins=8)bins in spectrumnumber / listSame smoothing as audio.level_tau. Linear 0…1 — use amp_db for bars. A formula (@=) or a @when that reads the level follows the voice, once per frame. The mic must exist when the formula is linked: the @= learns what it follows at that moment.
.effectsStack—Live stack of the monitor. It does not go into the recording. Effects on the clip: h.effects on playback, or clip.bake(...).
.close()No parameters—Calling it again does nothing. Releases the device and zeroes .level / .spectrum. If it was recording, it keeps the audio already captured and does not fire on_done. Quitting the application closes every open microphone the same way.
clip.durationsecondsnumberGrows while recording (samples ÷ 44100). Stays fixed once the recording ends. Read-only.
await clipthe Sound returned by record()the same SoundWaits for the recording to end and returns the same clip, ready to play. await on a Sound loaded from a file raises TypeError.

How a recording ends

EndingKeeps the audioon_done / then=
mic.stop()yes — playable on the very next lineon the next frame
seconds= reachedyeson the next frame
30 s capyeson the next frame, plus a warning
the mode ends / destroy() / mic.close()yesno

Don't confuse

Looks likeIt isIt is not
clip right after record()a Sound still being made. play_sound / bake raise RuntimeError.playable — mic.stop() or await first.
mic.stop()ends the recording; the mic stays open.mic.close() (releases the device).
mic.effects applies to everythingmic.effects changes only what you hear live (play_sound(mic)).the recording — the clip always comes out without those effects.

pitch= on the mic monitor is ignored (it only makes sense for files). The monitor is the live play_sound(mic). The clip, once ready, takes pitch= and bake.

effects

Sound effects change how a sound sounds while it plays: muffled, like a radio, with an echo, in a room, distorted. Every playing sound (the Handle from play_sound) and the microphone monitor have an .effects stack: .add(…) puts an effect on, .remove() / .clear() take it off, .enabled = False turns it off without removing it. The parameters change live (lp.cutoff = 1500).

For a sound you play many times, always with the same effect, compute it once with Sound.bake(…): the result is a new Sound, already processed, that plays at no extra cost.

h = play_sound("shoot.wav")
h.effects.add(LowPass())
lp = h.effects.add(HighPass())
lp.cutoff = 1500
lp.enabled = False
lp.remove()
h.effects.clear()

# Once, then every play is cheap:
crunch = Sound("shoot.wav").bake(Distortion(), Wavefold(), transpose=3, pitch=1.1)
play_sound(crunch)
Catalog reference
NameParametersWhat it does
LowPass(cutoff=300)cutoff: cutoff frequency, in HzMuffles: lets the lows through and cuts the highs above cutoff — a sound “behind a wall”, or underwater. The lower the cutoff, the more muffled.
HighPass(cutoff=2000)cutoff: cutoff frequency, in HzThe opposite: cuts the lows below cutoff — the thin sound of a radio or a telephone.
Echo(delay=0.25, decay=0.6)delay: seconds between repeats · decay: how much of the volume each repeat keeps (0 to 0.95)Echo: the sound comes back several times, quieter each time. After the file ends, the echo goes on until it fades away.
Reverb(size=1.0, mix=0.6)size: size of the room (0.05 to 1.5) · mix: how much of the room you hear (0 = none, 1 = only the room)Ambience: the sound in a room, a cave or a hall. It also keeps sounding a little after the end.
Distortion(drive=8)drive: how hard the sound is pushed (greater than 0)“Dirty” distortion, like a guitar or a blown speaker. It changes the character, not the volume.
Wavefold(drive=3)drive: how many folds per peak (greater than 0)A metallic, arcade sound. More drive, brighter.

.enabled = False turns the effect off: it sounds exactly as it would without it. .remove() twice does nothing. cancel and fade_out stop the sound without waiting for the Echo/Reverb tail. Leaving the mode does not cut a sound that ends on its own: it finishes playing, tail included (when the owner ends). Sound has no .effects; use bake.

Where else to look — Handle · Mode · Reactive

React

Run code when something happens — an event, which runs once, at that moment: a condition becomes true (@when), a value changes (@on_change), a key is pressed (script callbacks), the mouse clicks an object, something leaves the play area. To read the keyboard every frame: Frame. Objects touching: Collision.

A bool became True → @when
A value changed → @on_change
Key / mouse / setup / update → Script callbacks
The Entity's setup / on_update / on_destroy → Entity callbacks
Click on an object → Click / drag
Left the playfield → @leave_playfield
Bodies touch → Collision
Held / every frame → Frame
In N seconds → Schedule
This Entity is in this chapter → Mode
Widget (Button.on_click, linked value) → UI
The whole map → Which to use

@when

@when(condition) runs the function once when the condition turns from False to True — “when HP reaches 0, die”. The condition is checked every frame; while it stays True, the function does not run again.

A Python expression (player.hp <= 0) is evaluated now, when the decorator runs. For Scena to check the condition every frame, pass a function: lambda: …. A bool field (st["alive"]) can go in as is at module level. In a class: lambda self: ….

st.hp = 3
@when(lambda: st.hp <= 0)
def on_death():
    player.destroy()

@when(lambda: keyp("Y"))
def on_y():
    restart()

unregister_event(on_death)

It needs a lambda. The expression must return True or False — otherwise TypeError.

It fires when the condition turns from False to True. While it stays True, it does not fire again.

@when(lambda: player.hp <= 0)
def on_death():
    player.destroy()

@when(lambda: keyp("Y"))
def on_y():
    restart()

A bare expression (@when(player.hp <= 0)) is evaluated once, when the decorator runs — it is not checked again. At module level a bool field works too: @when(st["alive"]) (with brackets: st.alive is the current value).

In a class: lambda self: …. A bare field (st["hp"]) works only at module level.

class Ship(Sprite):
    @when(lambda self: self.hp <= 0)
    def on_death(self):
        self.destroy()
Contract
PartMeaning
@when(cond)Bool. It needs a lambda (a True/False expression). It fires when the condition turns from False to True. While it stays True, it does not fire again. At module level, a bool field: @when(st["alive"]).
When it is checkedEvery frame, and after writes to own fields / State. flush() runs the pending checks now, without waiting for the end of the frame.
Methodlambda self: …. It applies to every object of the class, from the moment it is created.
Several @when on the same defFine: both expressions fire the same body. Mixing with @on_change is a TypeError.
Mixing with @every / @collide / @on_modeTypeError.
unregister_event(fn)Removes every @when / @on_change from that function.
until / wait / parallelAn async wait in Mode. Not an event. until also needs a callable: lambda: ship.hp <= 0.

Do not combine @when with keyp.once. @when already fires only when the condition turns True. A widget linked to a formula: the gesture does nothing (that is Reactive, not an event).

@on_change

@on_change(value) runs the function every time the value changes, and can receive the new value. It works for any type: number, text, tuple.

It takes a field (st["wave"], st["pos"]) or a lambda. Without brackets, st.wave is the current number and raises an error. An object's field needs a lambda: a bare c.radius takes the current number. In a class: lambda self: ….

st.pos = (0, 0)
@on_change(st["pos"])
def on_pos(value):
    marker.center = value

@on_change(lambda: c.radius)
def on_radius(value):
    ring.radius = value

It fires when the new value is != the previous one. Callback: no args, or one arg (the new value).

st.wave = 1
@on_change(st["wave"])
def on_wave(value):
    spawn(value)

@on_change(lambda: c.radius)
def on_radius(value):
    ring.radius = value

In a class: lambda self: …. A bare field (st["hp"]) works only at module level. Callback: def fn(self) or def fn(self, value).

class Ship(Sprite):
    @on_change(lambda self: self.hp)
    def on_hp(self, value):
        self.flash(0.12)
Contract
PartMeaning
@on_change(target)Any value. Something reactive in Scena (an Attribute) or a lambda. It fires when the new value is != the previous one. Callback with 0 or 1 arg (the new value).
When it is checkedEvery frame, and after writes to own fields / State. flush() runs the pending checks now, without waiting for the end of the frame.
Methodlambda self: …. It applies to every object of the class, from the moment it is created. Callback: def fn(self) or def fn(self, value).
Several @on_change on the same defFine: both expressions fire the same body. Mixing with @when is a TypeError.
Mixing with @every / @collide / @on_modeTypeError.
unregister_event(fn)Removes every @when / @on_change from that function.

An object's field needs a lambda. @on_change(c.radius) receives only the current number and raises TypeError: write @on_change(lambda: c.radius).

Script callbacks

Functions with fixed names that you define in the script; run() calls them: setup when the window opens, update every frame, on_key_down / on_mouse_click… when there is input. To know whether a key is held, keyp in update is usually simpler (Frame). Click on an object: Click / drag. In a class: Entity callbacks.

def setup(canvas):
    canvas.fx_quality = "high"

def update(dt, canvas):
    if keyp("RIGHT"):
        player.move_by(200 * dt, 0)

def on_key_down(key):
    if key == "ESC":
        canvas.reset_view()

def on_mouse_click(x, y, button):
    marker.move_to(x, y)

def on_mouse_scroll(xoffset, yoffset):
    factor = 1.1 if yoffset > 0 else 1 / 1.1
    canvas.zoom_by(factor, about=(mouse.x, mouse.y))

The engine sends the full tuple and drops what the function does not ask for. update(dt) and update(dt, canvas) both work. The same goes for on_mouse_up(x, y, button) vs. the version with click_x, click_y.

The keyboard sends only key — there is no second mods parameter. Modifiers are keys of their own: "SHIFT", "CTRL", "ALT", "CMD". A shortcut: keyp("CTRL+R"). Never key == "CTRL+R".

Signatures
MethodSignatureReturnsMeaning
setupParameters: canvas (the canvas)—Once, with the window open. Not the Entity's setup(self).
updateParameters: dt (number), canvas (the canvas)—Every frame, after input. Take only dt if you do not need the canvas. In the script the name is update, not on_update.
on_key_downParameters: key (str)—A key was pressed. A friendly name in capitals, the same as keyp's (punctuation arrives as "K1"…"K12" — table). An ordinary key arrives only with no Ctrl / Alt / Cmd held: Ctrl+R does not call on_key_down("R") — use keyp("CTRL+R"). Shift does not block: with Shift held, SPACE calls on_key_down("SPACE"). key == "ESCAPE" → ValueError suggesting "ESC".
on_key_upParameters: key (str)—A key was released. The same key. It arrives only for a key whose on_key_down arrived (a shortcut like CMD+S sends neither of the two for "S"); it arrives even if a modal menu opened in between or if the act changed while the key was held (walking right up to the door, the on_key_up("RIGHT") arrives in the new act).
on_keyParameters: key (str)—On the press and, while the key stays held, on each auto-repeat. The same key. A key pressed before change_act does not repeat in the new act (its on_key_up arrives).
on_charParameters: char (str)—A Unicode character.
on_mouse_downParameters: x (number), y (number), button (number: Mouse.BTN_LEFT, BTN_RIGHT…)—A mouse button went down; x, y in the world. Who receives it first: widgets, then objects, then this function.
on_mouse_upParameters: x (number), y (number), button (number: Mouse.BTN_LEFT, BTN_RIGHT…), click_x (number), click_y (number)—The button was released; x, y is where it was released, in the world. click_x, click_y (optional) is where the button was pressed — useful for measuring the drag. You can leave both out and keep x, y, button. It also arrives when the act changed with the button held; then there is no on_mouse_click or on_mouse_drag in the new act.
on_mouse_clickParameters: x (number), y (number), button (number: Mouse.BTN_LEFT, BTN_RIGHT…)—A click (press+release in the same place). World. Not shape.on_click.
on_mouse_double_clickParameters: x (number), y (number), button (number: Mouse.BTN_LEFT, BTN_RIGHT…)—A double click. World.
on_mouse_moveParameters: x (number), y (number)—The mouse moved; x, y in the world. It runs alongside the other mouse events, without blocking them.
on_mouse_dragParameters: x (number), y (number), button (number: Mouse.BTN_LEFT, BTN_RIGHT…)—A drag with a button held. World. Not shape.on_drag_to.
on_mouse_scrollParameters: xoffset (number), yoffset (number)—The mouse wheel turned (yoffset > 0 = up). Who receives it first: the widget under the pointer (it keeps the wheel; a Slider changes its value), then an object held with wheel_rotate, then this function. An object without wheel_rotate does not hold the wheel.
post_drawParameters: skia_canvas (Skia canvas), scene_image (image)—Escape hatch: you draw the final screen image yourself, in place of the whole post-processing effect list (Post). Not an event.

A shortcut is not an event name: never key == "CTRL+R". A focused TextInput: see Keyboard. Button.on_click (receives the button, or nothing) is UI.

The script has no other way to receive events besides the ones in this section and in the map at the top: @when / @on_change, click on an object, @leave_playfield, collision, reading every frame in Frame, @= in Reactive, timers in Schedule, @on_mode in Mode, widgets in UI.

Entity callbacks

Methods with fixed names that Scena calls on an Entity: setup when it is born, on_update every frame, on_destroy when it is destroyed. They work on every Entity (Shape, Sprite, SpatialFx and the Entity() with no drawing). Write them as methods of the class or assign a function to the object (ship.on_update = …). The script's names (setup(canvas), update) are something else — Script callbacks.

class Ship(Sprite):
    def setup(self):
        self.hp = 3

    def on_update(self, dt):
        self.rotate_by(40 * dt)

    def on_destroy(self):
        canvas.burst_at(self)

ship.on_update = lambda e, dt: e.rotate_by(40 * dt)
Signatures
MethodSignatureReturnsMeaning
setupParameters: self (this object)—Once, after the constructor. Own fields are born here: self.hp = 3. Not the script's setup(canvas).
on_updateParameters: self (this object), dt (number)—Every frame, on this Entity, even during await. On an instance: fn(e, dt). See Frame.
on_destroyParameters: self (this object)—Once, from inside destroy(). It does not fire on a mode change.
on_click / on_hover / on_hover_exitParameters: self (this object)—Shape, Sprite and Text (hover on widgets too). The method already turns on clickable (for the click) or makes the object a hover target, like assigning on the instance. See Click / drag.
on_drag_to / on_drag_overParameters: self (the dragged object), to_shape (the droppable underneath, or None), pos (point)—On the dragged object. The method turns on draggable. self is already the object being dragged: the method does not receive the piece again (def on_drag_to(self, piece, target, pos) raises TypeError when the object is created).
on_drop_byParameters: self (the target), from_shape (the dragged object), pos (point)—On the target. The method turns on droppable.
on_collide / on_collide_stay / on_collide_exitParameters: me (object), other (object), info (CollisionInfo)—Shape, Sprite and SpatialFx. See Collision.

Click / drag / hover

Clicking, dragging, dropping and hovering the mouse over a Shape, Sprite or Text (and a Button). Just declare the gesture's function: it turns on the right property (clickable, draggable…) by itself. Who receives the click, from top to bottom: widgets → ui → top → other layers → script.

Three ways to write the same gesture: a decorator (@click, @hover, @drag_to…), a callback on the object (shape.on_click = fn — an alternative to the decorator) and the properties alone (clickable / draggable). Every Graphic (Shape, Sprite, Text) has these properties and callbacks; SpatialFx does not. The gesture's function can receive the target or ask for nothing — that is why the same function serves a Shape and a Button. A parameter with a default value does not receive the target, so lambda f=f: choose(f) in a loop works.

@click(c1, c2, box)
def on_click(shape):
    shape.set_color("gold")

reset = Button(label="Reset")

@click(reset, restart_icon)   # Button and Shape: the same function
def restart():
    st.score = 0

@click(group["click_group"])
def on_group(shape):
    shape.set_color("gold")
@drag_to(token)
def on_drag(from_shape, to_shape, pos):
    from_shape.center = pos

@drag_over(token)
def on_over(from_shape, to_shape, pos):
    zone.set_color("yellow" if to_shape is zone else "gray")

@drop_by(zone)
def landed(from_shape, to_shape, pos):
    from_shape.center = zone.center

One hover target at a time: the topmost one under the cursor, among widgets, ui and the world. Entered → @hover; left → @hover_exit. Every entry has exactly one exit.

@hover(group["cards"])
def lit(card):
    card.set_color("gold")

@hover_exit(group["cards"])
def unlit(card):
    card.set_color("gray")

Three different tests, each answering one question — do not swap one for another:

if ship.contains_point(mouse):
    ...  # this object (by its drawing), in the world. Also contains_point(x, y)

def on_update(self, dt):
    self.set_color("gold" if self.pointer_hover else "gray")  # a state, not an event

hits = collision.query_point(mouse)  # without group=: registered hitboxes

The exit is immediate: hiding, destroying, moving out from under the cursor, clickable = False, a widget on top or a modal Menu. The entry waits for the mouse to move: a shape that slides under a still cursor only gets hover on the next movement. A shape with only @hover does not block clicks: the click goes through to the one below.

# wheel turns it while the button is held on the body
rect.wheel_rotate = True
rect.show_handles()
rect.show_points()

a1 = Anchor(120, 620)
a2 = Anchor(280, 660, color="dark red")
Line(p1=lambda: a1.center, p2=lambda: a2.center)
a = Circle(center=(900, 150), radius=55, color="red")
b = Circle(center=(930, 170), radius=40, color="green")
# only within the same layer
b.move_to_front()
a.move_to_back()

hud = Rect(center=(930, 170), width=85, height=65, layer="top", color="navy")
Decorators

They turn on the right property on the target (clickable, draggable, droppable) and tie the function to the gesture. The target is a Graphic (Shape, Sprite or Text), not a SpatialFx. @click also takes a Button; @hover / @hover_exit take any widget. Slider / CheckBox / DropDown / TextInput in @click raise an error: use @on_change(w.data). @click(group["…"]) follows the tag, like @collide: it turns on the current members and anyone who joins later (group=, add_to_group), and turns off anyone who leaves. A refused member raises an error before any member is turned on (and a refused object that joins later raises an error on the line that put it in the tag). A function set by hand (card.on_click = f) is not replaced when the object joins or leaves the tag (the decorator, when it runs, sets its own on the members at that moment). Made inside an act, it goes away with the act. A union (group["a"] | group["b"]) or a .filter(…) is a snapshot: it turns on only the members of that moment. No target (@click()) or no parentheses (@click above the def) raises an error: without parentheses, Python would hand the function itself to @click and it would never run. Above a method in a class it also raises an error, because there is no object there yet: in a class, the gesture is the method with the fixed name (def on_click(self); or, for another name, self.on_click = self.tapped in setup). In an act, write @click(start_btn) inside setup.

MethodSignatureReturnsMeaning
@click(c1, c2)Function receives: target (Shape, Sprite, Text or Button)—Turns on clickable. A click on the body, with the left button (the right one does not fire it: use mouse.press(Mouse.BTN_RIGHT) or on_mouse_down).
@hover(card)Function receives: target (object)—The cursor entered: the object became the hover target. It does not turn on clickable.
@hover_exit(card)Function receives: target (object)—It stopped being the hover target (the cursor left, or it vanished, was destroyed, was covered).
@drag_to(shape)Function receives: from (object), to (object or None), pos (point)—The drag of this shape was released. The values arrive by position: a function with 2 parameters receives (from, to) — the point is the 3rd (def dropped(card, target, pos)).
@drag_over(shape)Function receives: from (object), to (object or None), pos (point)—During the drag, on each mouse movement (not every frame): to is the target under the piece, or None outside any target.
@drop_by(zone)Function receives: from (object), to (the target), pos (point)—Turns on droppable. Something was dropped on it.

from, to and pos in the three drag decorators:

ParameterPassType (default)Meaning
from1stShapetokenThe shape being dragged.
to2ndShape or NonezoneThe topmost droppable under the pointer: first those on the ui layer, then those in the world, wherever the drag comes from — the seed from the inventory (layer="ui") lands in the world's flower bed, the world's stone lands in the HUD's trash can. None if there is none.
pos3rdpoint(mouse.x, mouse.y)(x, y) where the pointer is (over) or was released (to / drop), in the space of the object that owns the function: in drag_to / drag_over the dragged object's (that is why from_shape.center = pos works), in drop_by the target's (Plant(center=pos) is born in the flower bed). World for world objects, screen (view) for layer="ui"; with no camera the two are the same.
@drag_to(token)
def on_drag(from_shape, to_shape, pos):
    from_shape.center = pos
    if to_shape is zone:
        from_shape.set_color("gold")
Callbacks

An alternative to the decorators. The same gestures, the same signature. A property on the object: assigning it also turns on the flag. Use one or the other — the last one written wins.

token = Circle(center=(200, 200), radius=24, color="coral")
token.clickable = True
token.on_click = lambda shape: shape.set_color("gold")

token.draggable = True
def on_drag(from_shape, to_shape, pos):
    from_shape.center = pos
token.on_drag_to = on_drag
MethodSignatureReturnsMeaning
on_clickParameters: shape (object)—Same as @click(shape). shape.on_click = fn or a method in the class.
on_drag_toParameters: from (object), to (object or None), pos (point)—Same as @drag_to(shape). On the dragged shape, on release.
on_drag_overParameters: from (object), to (object or None), pos (point)—Same as @drag_over(shape). On the dragged shape, during the drag.
on_drop_byParameters: from (object), to (the target), pos (point)—Same as @drop_by(zone). On the droppable target, on release.
on_hoverParameters: shape (object)—Same as @hover(shape). Makes the shape a hover target without making it clickable.
on_hover_exitParameters: shape (object)—Same as @hover_exit(shape).
On every Graphic

Every Graphic (Shape, Sprite, Text) has these methods and properties. SpatialFx does not — it is not a Graphic. Widgets are UI.

Properties

PropertyType (typical value)Read/WriteMeaning
clickableboolTrueread / writeAccepts clicks. A decorator / callback turns it on by itself.
draggableboolTrueread / writeDrags the whole body.
droppableboolTrueread / writeA drop target. @drop_by turns it on.
pointer_hoverboolTruereadRead. True on the hover target: the topmost clickable / draggable / on_hover object under the cursor. A state, updated once per frame. A decoration with none of these is always False (and does not block). Not contains_point.
pointer_pressedboolTruereadRead. True while the left button, pressed on this shape, stays held and the cursor is over it (releasing there would click). It goes False when the cursor leaves and back to True when it returns; while dragging it stays True. It ends on release and when the shape goes away (visible = False, active = False, destroy()), stops being clickable / draggable, or a modal menu opens. Good for a "pressed-in" look.
wheel_rotateboolTrueread / writeTrue: with the mouse button held over the object, the mouse wheel turns it. Independent of draggable.

Methods

MethodSignatureReturnsMeaning
contains_point(x, y=None)Parameters: x (a point, or the number x with y)True/FalseDoes this object contain the point? Drawing geometry (the same shape the click tests). Point, tuple, mouse, Graphic. The point is in the world: on an object on the "ui" layer with the camera panned / zoomed / rotated, contains_point(mouse) is not the click — use pointer_hover. Sprite: the current frame's alpha, not the PNG's rectangle or the hitbox. Circle: the painted slice (pie or segment). Rect corner_radius: the click follows the corner; collision stays the rectangle.
show_handles() / show_points()No parameters—show_handles() shows the free points that define the shape (corners, center, ends) as drag handles: dots you drag with the mouse to change the shape. show_points() only marks all the points, with no dragging, to check the geometry. An Anchor is born as a drag handle, on the top layer.
move_to_front() / move_to_back()No parameters—Order within the layer. An object on layer="top" stays above those on the "default" layer (the default one), whatever the order.
token = Circle(center=(200, 200), radius=24, color="coral")
token.clickable = True
token.draggable = True
token.on_click = lambda shape: shape.set_color("gold")

zone = Rect(center=(500, 300), width=120, height=80, color="navy")
zone.droppable = True

An invisible object does not click. Who receives the click: widgets → objects on the ui layer → world. pointer_hover comes from clickable / draggable / on_hover. There is no hoverable: @hover already makes it a target. Three tests: contains_point = this drawing; pointer_hover = the topmost target; collision.query_point without group= = registered hitboxes.

@leave_playfield

@leave_playfield runs a function when an object's center leaves the play area (canvas.playfield) — to destroy the shot that left the screen, to lose a life when the star falls.

@leave_playfield("bullet")
def leftover(shot):
    shot.destroy()

canvas.playfield.pad = 0.4
# or explicit:
canvas.playfield.set(left=-40, bottom=-40, right=1040, top=840)
# or a Box:
canvas.playfield.set(canvas.game_view.outset(300))

The rectangle is the playfield, fixed in the world — it does not follow the camera. It is not canvas.game_view (the window). Laying out ships / HUD: Place.

A moving camera (runner, flappy): the playfield falls behind. Make it follow the window with one line per frame, in update: canvas.playfield.set(canvas.game_view.outset(300)).

Only an object that was inside can leave: an object born outside the playfield that moves away (the shot of a tower the camera left behind) never fires @leave_playfield and stays alive forever. Create it inside the area (shoot only when the tower is on screen) or destroy it after a while (shot.after(3, shot.destroy)).

Default (no need to set it): the design rectangle with pad=0.25 on each side (1.5×, centered). It only takes effect when some @leave_playfield is in use.

Two @leave_playfield("bullet") both run, in the order they were written (like @collide). One made inside an act goes away on the act change.

canvas.playfield reference

Properties

PropertyType (typical value)Read/WriteMeaning
canvas.playfield.pad = 0.4number0.4read / writeA fraction on each side (size × (1+2p)). 0.0 would be exactly the screen's limit. Negative shrinks inside the design rectangle.
.left .right .bottom .topnumber-40read / writeSides. y up: top is the largest y. Writable one by one.
.width .height .centernumber or point120readDerived, read-only. .center has .x / .y.
.padnumber0.4read / writeA number if the mode is pad; None if the sides are explicit. Negative = an area smaller than the design; pad <= -0.5 collapses to the center (it does not flip the sides).

Methods

MethodSignatureReturnsMeaning
canvas.playfield.set(box) / canvas.playfield.set(left=, bottom=, right=, top=)Parameters: box (Box) — or left (number), bottom (number), right (number), top (number)—An axis-aligned rectangle, in the world: a Box (read once) or the four sides, all required. Both together: error.
.inset(margin) / .outset(margin) / .grid(…) / .beside(…) / .strip(…)same as BoxBox / GridCopies for layout. They do not write .pad. See Place.

Ctrl+Shift+7 draws the playfield (cyan) when some @leave_playfield is in use. Alias: canvas.bounds.

At module level: one or more group names. Objects that join the group later are watched too. Callback: fn(item).

@leave_playfield("bolt", "sting")
def leftover(shot):
    shot.destroy()

@leave_playfield("star")
def missed(star):
    star.destroy()
    st.lives -= 1

In a class: no group names. It applies to every object of the class, from the moment it is created. Callback: fn(self).

class Bolt(Sprite):
    @leave_playfield
    def leftover(self):
        self.destroy()

It fires only after the center has been inside once. A spawn outside does not count. Do not mix it with @collide / @every on the same def. You do not have to destroy: you can park, lose a life, reappear on the other side. Do not use the playfield to position the fleet — that is Box / game_view. To keep the pose inside a region (clamp / bounce / wrap): confine.

Where else to look — Frame · Collision · Mode · Reactive

Collision

Know when two objects touch (@collide) and make one stop against the other — walls, floors, platforms (resolve). Only what you enroll takes part, by naming it in a @collide or a resolve(). Shape, Sprite and SpatialFx use the same system. To know whether something left the play area: @leave_playfield; where two outlines cross: intersections.

A function that runs when two bodies touch → Detect (@collide / @collide_with / on_collide)
What the collision function receives → CollisionInfo
Wall, floor, bounce → Make it solid (resolve / .mass / bounce=)
On the floor? → Touching (touching_sides)
Which block am I standing on? → Touching (touching_contacts)
Will I fall if I walk on? End of the platform → Floor ahead (floor_below)
Dash, your own controller → Manual resolution
Who is here / radius → Queries
collidable / collider shape → What collides
Debug overlay → Debug

Detect

@collide calls a function of yours when two objects (or groups) touch. Say which two — @collide("bullet", "enemy") — and write the function that reacts: a function in the module, a method of the class or a property on the object. All three forms have the same three phases: started touching, still touching, stopped touching.

Just touching counts. Two objects that share a border already touch (that is what keeps an object resting on the floor “touching”). In a grid of same-size cells (snake, Tetris, match-3), the head touches the neck right at the start: make each cell 1 or 2 units smaller than the grid step.

@collide("bullet", "enemy")
def on_hit(me, other, info):
    other.destroy()

@collide_stay("zone", "player")
def inside(me, other, info):
    other.hp -= clock.dt

@collide(player, ANYTHING)
def bump(me, other, info):
    other.flash(0.1)

Without a named pair (or on_collide / ANYTHING), no collision function runs. Each of the pair's two sides is a group name (tag), an object, group["tag"], ANYTHING or a hitbox part — or a list of them. Anything else (5, None, a dict, an effect) raises TypeError right away, in @collide and in resolve / unresolve. Group names see whoever joins later; an object passed directly leaves the pair when it is destroyed (destroy()), and the new object you create in its place does not join — prefer the group name if the Entity dies and comes back.

PhaseWhenFunctionMethodObject
enterFirst frame of overlap.@collide(a, b)@collide_with(b)on_collide
stayEach following frame they still overlap.@collide_stay(a, b)@collide_with_stay(b)on_collide_stay
exitThey stopped touching. info.point is None.@collide_exit(a, b)@collide_with_exit(b)on_collide_exit

ANYTHING is the wildcard: that side × everything enrolled. Callback: fn(me, other) or fn(me, other, info) — me is the object of @collide's 1st argument, other that of the 2nd; info is a CollisionInfo.

Several handlers on the same contact all run, even if one of them destroys one of the two: the ones after it receive the already dead object (you can read it; destroy() again does nothing). So a Bullet with @collide_with("enemies") that does self.destroy() and an Enemy with @collide_with("bullets") that destroys itself and adds a point give the same score, whichever is created first — and the same holds for a module function together with a method. That contact's exit waits for the remaining handlers: on a contact you always see the enter, then the exit (a counter with += 1 on enter and -= 1 on exit goes back to zero, whichever handler destroys). The destroyed object's own exit hooks (its on_collide_exit, its class's @collide_with_exit methods) and the exits of its other contacts run at the moment of destroy(), while it still exists. An object that died in a contact does not start another one in the same frame: a bullet hits only one enemy. On an act change in the middle of the contact, the handlers of the act that left do not run.

Each rule has its own contact. A rule's enter runs when the rule starts to apply to the two — because they started touching, or because one of them got the tag while they were already touching (hero.tag("shield") inside the lava fires @collide("shield", "lava")), or because the rule was created at that moment — and its stay comes from the next frame on. The exit runs when the rule stops applying: they separated, or one of them lost the tag (untag), even if another rule still joins the two. That is why a rule does the same thing with or without other rules for the same pair. Removing the tag and adding it back in the same frame changes nothing; a tag given inside a handler counts from the next frame on.

Fast object. An object that travels (move_by, move_to(…, time=), move_along, or turning around another point with rotate_by(…, about=)) more than half its own thickness in a frame is checked along the frame's whole path, not only where it stopped. A fast bullet does not pass through the enemy, at any frame rate. If the path crosses several, the nearest one's enter runs first: destroying the bullet there stops the others. The contact with an object already passed lasts one frame (enter now, exit on the next); info.point is where it hit and info.depth is 0. Placing (center = …, move_to without time=, @=, tween) is not checked along the path — for that, use raycast from the previous position to the new one. Spinning in place is not either: a blade that spins very fast can skip a thin object between two frames.

A function in the module. Both sides in the call. Scope: the pair.

@collide("bullet", "enemy")
def on_hit(me, other, info):
    other.destroy()

@collide_stay("zone", "player")
def inside(me, other, info):
    other.hp -= clock.dt

@collide_exit("player", "door")
def left_door(me, other, info):
    me.set_color("cyan")

A class method. self is the class's object; other is the target. The target follows the same rules as a side of @collide (tag, shape, ANYTHING). Scope: self × the target.

class Wasp(Sprite):
    @collide_with("bolt")
    def on_hit_bolt(self, bolt, info):
        self.hp -= 1

    @collide_with_stay("acid_pool")
    def in_acid(self, pool, info):
        self.hp -= clock.dt

Callback: fn(self, other) or fn(self, other, info).

A property on the object — Shape, Sprite and SpatialFx. Scope: this object × any other enrolled one. A plain Rect is not enrolled: the bullet that passes through the alien with nothing happening needs bullet.collidable = True (or its own on_collide, or a @collide with both groups).

ball.on_collide = lambda me, other, info: me.set_color("yellow")
def drain(me, other, info):
    other.hp -= clock.dt                 # a lambda can't do -=; use def
ball.on_collide_stay = drain
ball.on_collide_exit = lambda me, other, info: me.set_color("cyan")

class Probe(Circle):
    def on_collide(self, other, info):
        self.flash(0.1)

Assigning enrolls the object and declares an ANYTHING interest: it is the same as @collide_with(ANYTHING) (and _stay / _exit). As a class method: fn(self, other) or fn(self, other, info). It does not filter the other side — for a specific pair, use @collide(a, b). Only one per phase on the object: the last one written wins.

on_collide = None removes that callback's ANYTHING interest: the engine stops testing this body against all the others, unless @collide_with(ANYTHING) or @collide(…, ANYTHING) still declares it. The module's @collide(a, b) functions keep firing.

Order. You can combine the forms. On the same contact, the object's function (on_collide) runs first, then the pair's function (@collide); if both exist, both fire (with @collide_with(ANYTHING) and on_collide in the same class, Scena warns once).

Don't confuse

Looks likeIt isIt is not
@collide and @collide_with on the same defTypeError. A plain function uses @collide(a, b); a method uses @collide_with.two spellings of the same decorator
A collectible / sensor in a resolve()A collectible / sensor is only @collide, never resolve(). A coin pushes no one. See Make it solid.solid
Outlines that crossDetect is about bodies overlapping. Outlines crossing: intersections. Leaving the playfield: @leave_playfield.@collide

CollisionInfo

CollisionInfo is the collision function's third parameter (info): it tells where the two objects touched, in which direction and how much they overlap, on that frame. You don't build one — Scena hands it to you. It exists without resolve(): it comes from @collide, on_collide and test_collision.

@collide("bolt", "wasp")
def boom(me, other, info):
    canvas.explosion_at(info.point, amount=0.8, shake=False)
    # or: canvas.explosion_at(*info.point, amount=0.8, shake=False)
    # or: canvas.explosion_at(info, amount=0.8, shake=False)
    other.destroy()

@collide_stay(player, "ramps")
def on_ramp(me, other, info):
    if abs(info.slope_angle) <= 45:      # the threshold is the script's call, not the engine's
        player.vel = info.slide_along(player.vel)
    else:
        ...                               # too steep — treat it as a plain wall

info.a is me and info.b is other. info.point is the useful place for VFX — the middle of the contact points (info.points). Enter / stay always have a point (without an exact contact point, a point on the object's border is used). Exit has no point (points empty → point is None — the engine does not keep the last stay).

CollisionInfo reference

Contact

PropertyType (typical value)Read/WriteMeaning
info.a / info.bEntityinfo.areadThe two bodies of this pair. In the callback: a is me, b is other. Hitbox part: here you get the Sprite that owns it.
info.a_hitbox / info.b_hitboxHitbox or Noneinfo.b_hitbox is hurtreadEach side's part (add_hitbox); None = the body. With a part, push_apart / bounce_apart / resolve raise TypeError (a part only detects).
info.normalVec2info.normalreadFrom a toward b (unit length). Zero if there is none.
info.depthnumberinfo.depthreadHow much they overlap. 0 when a fast object has already gone past the other.
info.pointpoint or Noneinfo.pointreadA usable (x, y) — the middle of the contact points. Enter / stay: always a tuple (at least a point on the object's border). None only on exit. Fast object: the place of impact, even if the object is already further on.
info.pointslistinfo.pointsreadEvery point where the two touch (a list). Empty only on exit. For your own physics, or a spark at each point.
info.sidestr or Noneinfo.side == "bottom"readThe side of a in the contact: top/bottom/left/right.

Slope

NameType / signatureReturnsMeaning
info.slope_anglenumberinfo.slope_anglereadThe surface's angle in degrees (0 = flat floor). Continuous — not the 4 buckets of side.
info.tangentVec2info.tangentreadUnit vector along the surface (perpendicular to normal).
info.slide_along(velocity)Parameters: velocity (Vec2)Vec2Projects a velocity onto the tangent — walking/sliding on a slope.

Methods that push (info.resolve, push_apart, bounce_apart, mtv_split, velocity_split, reflect_velocity): Manual resolution.

Don't confuse

Looks likeIt isIt is not
VFX at info.points[0]That is a corner of the face. Use info.point. canvas.explosion_at / burst_at / ripple_at / wave_at / bubbles_at / fireworks_at / zap_at / hit_at / debris_at take (x, y) or a point (tuple, Point, Vec2, Graphic, info). None does nothing — on exit, explosion_at(info.point) is silent; *info.point on exit raises TypeError.the last contact, kept
In the collision function, me.vel / other.vel already reflect the impactStill the ones from update(dt): resolve() runs later. info keeps no velocity — read it on the bodies. info.bounce_apart() / info.resolve(bounce=…) inside it write .vel right away.the velocity after the impact
Fast bullet: info.point is where the bullet isWhere it hit. The bullet stays where the frame took it (Scena does not pull it back): for the explosion, use info.point, not me.center.the bullet's position

Make it solid

resolve(a, b) enrolls a pair to separate on its own every frame: it follows the path of the movement and stops at the point of impact, then slides along the surface. Detection (@collide) and resolution are separate enrollments.

Stacks. Two crates one on top of the other stand; three or more movable crates stacked up (or a crate much heavier than the light ones under it) can sink a little into each other, more so at low frame rates: resolve does not promise stacks. Keep stacked crates at similar masses, or make the stack a single object, or STATIC if it should not move.

wall = Rect(center=(400, 300), width=200, height=30, group="walls")
wall.mass = STATIC

player.mass = 1.0

resolve(player, "walls")          # enroll + detect + push
resolve(player, "walls", bounce=0.0)  # + zero the velocity along the normal

# reset: places, does not travel — a wall in the way does not stop the hero
player.center = start_pos

unresolve(player, "walls")

.mass decides who gives way in the push. STATIC does not give way: floor, wall, platform.

Every frame, Scena follows the movement path of the enrolled pair and stops at the impact, slides along the surface and undoes whatever overlap is left. The sides are objects or group names (whoever joins the group later is in too). Default mass 1.0; <= 0 raises an error. Two equal masses push each other half and half.

Pieces laid side by side are rarely perfect: a rotated row of blocks, a rounded coordinate. In a world with a floor (collision.floor = True), an object on the floor that walks against the side of a still piece rising up to 2 above its feet climbs that step and keeps walking. A bigger step is a wall. In the air there are no steps: hitting the corner from the side is a wall.

A collectible or sensor is not solid: only @collide. A coin pushes no one:

@collide("hero", "star")
def caught(me, star, info):
    star.destroy()
    st.score += 1

resolve(hero, ANYTHING) makes everything enrolled solid, including coins, bullets and sensors: the hero pushes the coin instead of passing through it (the coin's @collide keeps firing). There is no way to mark a body “not solid”: name the solid groups, resolve(hero, ["walls", "crates"]). ANYTHING is for when everything in the world is solid (a world made only of blocks and walls).

A floor that must not give way is STATIC. When neither body is STATIC, the push is split by mass, whichever was created first: a crate of mass 1 moves half the step of the player pushing it, one of mass 50 barely moves. That holds for floors, walls and platforms too: left at the default mass 1, they give way under a hero of mass 1 (the hero's gravity sinks the floor). A platform you move with move_by that should carry whoever is on top is STATIC.

Whoever is on top rides along, in a world with a floor (collision.floor = True). An object resting on top of another one in the resolve (its "bottom" side touching) moves with it in the frame, sideways and up and down, with move_by, time= or move_along, at any frame rate; its own movement adds to that (walking on the elevator). A wall in the elevator's path holds back whoever is on top. An object that jumps or bounces stops riding along. A pushed crate does not carry the one above it: only a platform (STATIC, or without .vel) carries.

Don't copy the elevator's velocity to whoever is on top. hero.vel.x += elevator_vel (or hero.vel = h.velocity) makes the hero move twice: resolve already carries it along.

A STATIC never gives way: a stack of heavy crates does not sink the bottom one into the floor, and a light ball hit by a heavy one does not go through the floor or a thin wall. The crates of a stack can still sink a little into each other and jitter (Scena is not a physics engine). Two objects born inside each other separate along the side where they overlap, whatever the .vel.

bounce= says what happens to .vel on contact. Leaving it out is not the same as 0.

CallEffect
resolve(a, b)Position only: stops at the impact; neither reads nor writes .vel.
resolve(a, b, bounce=0.0)Position + an inelastic impulse along the normal: removes the component going in and keeps the tangent one (walking on a slope).
resolve(a, b, bounce=1.0)Elastic. > 1 = super bounce. Only runs if the moving body has a .vel.

“No bounce” in everyday speech usually means bounce=0.0; leaving the parameter out is position only. .mass decides who absorbs the impact; bounce= decides how much of the normal velocity survives. Two equal masses with bounce=0 end up moving together — not a bug.

There is no friction. Surfaces are smooth: bounce=0 removes only the velocity going into the wall, and the sideways velocity stays forever — the ball slides down the slope and a stack never comes to rest. Brake it yourself in on_update(self, dt): self.vel.x *= 0.5 ** dt (loses half the sideways velocity per second, the same at any frame rate).

ball = Circle(center=(200, 200), radius=15)
ball.mass = 1.0
ball.vel = Vec2(180, 0)

floor.mass = STATIC
resolve(ball, floor, bounce=1.0)   # elastic
resolve(ball, wall, bounce=0.0)    # inelastic — zeroes the normal component of .vel

There are two patterns for zeroing the velocity against a wall:

collision.floor = True   # a world with gravity (A world with a floor)

# A — the engine zeroes the normal velocity on contact
resolve(player, "walls", bounce=0.0)

# B — position only in resolve; you handle the velocity (same recipe as the slope)
resolve(player, "walls")

def update(dt):
    player.vel.y -= GRAVITY * dt
    ...
    for c in player.touching_contacts:
        if c.side == "top" and player.vel.y > 0:
            player.vel.y = 0.0   # head against the ceiling — the other one is above
    player.move_by(player.vel.x * dt, player.vel.y * dt)

.vel is None until you assign it; the script moves with move_by(vel * dt). move_along / move_to(..., time=) / move_by(..., time=) do not write .vel — to take on the travel's rate: crate.vel = h.velocity (Handle). Whoever is on the platform already rides along; don't copy its velocity.

Broken on contact. Destroying (or parking) the partner in @collide does not cancel the bounce: with resolve(ball, "brick", bounce=1) and a @collide(ball, "brick") that does brick.destroy(), the ball breaks the brick and bounces back from where it touched, as off a whole brick: on this frame the dead brick still holds the ball, but it does not move or count as a contact. Breaking it on the next frame (a flag in @collide, the destroy() in update) gives the same bounce. Only the part coming head-on changes: whatever grazes past or moves away keeps the same velocity. With bounce=0, a floor that vanishes when the hero lands holds the fall on that frame, and on the next one the hero falls. At the seam of two bricks the ball touches both at once, and both respond together: it bounces straight back, whatever order they were created in.

In a game with gravity, the world has a floor: collision.floor = True. An object that touches what is below it stands on it.

collision.floor = True              # this world has a floor (the gravity is yours)
resolve("hero", "ground", bounce=0)

With a floor, resolve treats a body's bottom side as its feet: an object that was on the floor at the start of the frame is pulled back to a floor within reach (it walks down a slope without hopping, and does not flicker between “on the floor” and “in the air” on short frames), a moving platform carries whoever is on top, a step of up to 2 is climbed by walking, and an object standing on a slope does not slide.

Without the line (the default), the world has no floor: a game seen from above (racing, maze, RPG), in space or without gravity. No side is special, and rotating the whole world rotates all movement with it: a car that scrapes a wall below it leaves that wall the way it leaves a wall beside it.

A platformer without collision.floor = True. The hero does not ride along with the elevator, slowly slides down the slope and, on 120 Hz screens, flickers between “on the floor” and “in the air” (the jump sometimes fails). floor_below and tilt = "ground" in a world without a floor warn once (SCENA WARNING).

In a world with a floor, the pair's bounce= decides when an object on the floor leaves it:

bounce=Sticking to the floor
omitted, 0 or up to 0.5 — walkersSticks. It leaves the floor only when, on the same frame, the velocity (.vel) points away from the floor and the body actually moves away from it (as in a jump). Walking up a slope or being carried by an elevator gives a large upward velocity, and the object still stays on the floor.
above 0.5 — balls, projectilesDoes not pull back a real bounce: the engine trusts the leaving velocity.

That is why resolve(ball, "wall", bounce=1) bounces and resolve(hero, "ground", bounce=0) stays steady. There is no “stick” option — bounce= already states the intent.

Placing jumps straight to the spot; traveling goes along the path. A wall only stops what travels.

Places (goes through the wall)Travels (the wall stops it midway)
center =, move_to / rotate_to / scale_to without time=, tween(shape.center, …), center @= (including track.cursor)move_by, move_to(..., time=), move_by(..., time=), move_along

@collide follows the same split: an object that travels fast is checked along its whole path (Fast object); a placed one, only where it stopped. Reset / respawn: hero.center = start_pos or an instant move_to — don't turn off collision.resolve_enabled for that. Sliding to a point and stopping at the wall: move_to(..., time=). See Move.

only= says on which sides of a the pair holds. Any other first contact passes through until the two separate. A platform you jump through from below is only="bottom".

resolve(hero, "thin", bounce=0.0, only="bottom")   # jump through from below, stand on top
resolve(hero, "thin", bounce=0.0, only={"bottom", "left", "right"})  # the sides hold
resolve(hero, "door", only="left")                 # one-way door

# drop down through the platform: DOWN + jump
def update(dt):
    st.drop_down = recently("drop_down", keyp("DOWN") and keyp.once("UP"), hold=0.15)
    ...

resolve(hero, "thin", bounce=0.0,
        only=lambda c: c.side == "bottom" and not st.drop_down)
With only="bottom"What happens
Jumps up from belowThe head hits ("top"): passes through.
The top of the jump ends inside the platformKeeps passing through and falls back down: it did not get past the top.
Gets past the top and fallsThe feet touch ("bottom"): stands on it.
Walks against the sidePasses through (as in Mario). To hold, list the sides.
Walks over adjoining blocks with a step of up to 2Climbs the step and stays on top (does not pass through). A bigger step is a side: passes through.
Standing on topA normal floor: touching_sides, coyote, tilt = "ground", elevator.
Falls very fastScena checks the frame's whole path: it catches the top and does not pass through.

The sides are those of a, the same words as a.touching_sides: "bottom" = standing. One side works, or a list / tuple / set (order does not matter). All four sides = no filter. A function receives the contact (TouchingContact, seen from a: .side, .other, .normal) and returns True to hold. It runs inside the collision, several times per frame: only read state. Effects (playing a sound, breaking the plank) go in @collide, which keeps firing while the object passes through. Scena checks: in resolve(), a function that writes (st.x = …, hero.vel.y = 0, destroy(), recently(…), keyp.once(…), chance(…), creating an object) raises TypeError pointing at the line; whatever escapes that reading (code without source) raises RuntimeError when it runs. Compute in update(), store it in st and only read it here — like st.drop_down in the example.

The side is that of the first contact, the same one a solid platform would use. Falling diagonally and touching the corner from the side passes through, just as it would slide down the wall of a solid platform.

Don't confuse

Looks likeIt isIt is not
only="top" for a jump-through platformonly="bottom": the side is the hero's (the feet), not the platform's.the platform's side
The same platform in "platform" and "thin", with only= on just one of themValueError: two registrations disagree. Give the one-way platforms a group of their own.the first one wins
resolve("crate", "crate", only="bottom")ValueError: a group against itself sees each contact from both sides. Use {"top", "bottom"}, {"left", "right"} or a function.stackable crates
only= on a slope steeper than 45°The sides are 45° bands of the world. For a steep one-way slope, use a function with c.normal.“on top” of the slope

Removing a pair: unresolve(a, b), with the same sides as resolve.

unresolve(player, "walls")
collision.resolve_enabled = False   # advanced: turns off all resolution

collision.resolve_enabled = False turns off, for every pair, stopping along the path, separating and sticking to the floor. @collide, queries and raycast go on; touching_* stays empty while it is off. It is not the way to reset (see Place × travel).

resolve reference

Properties

PropertyType (typical value)Read/WriteMeaning
STATICconstantwall.mass = STATICread / writeImmovable — floor, wall. float("inf").
shape.massnumber1.0read / writeWeight in the push. Default 1.0. <= 0 raises an error.
shape.velVec2 or Noneball.vel = Vec2(0, -200)read / writeThe body's velocity. None until assigned. Read and written by resolve(..., bounce=). It is not linked with @= (the engine writes to it): to follow state, write it every frame — ship.vel = vec_from_angle(st.a * 30, 10) in on_update. Pose tweens do not write it — the Handle reports the rate (Handle).
collision.floorboolTrueread / writeDoes the world have a floor? Default False (seen from above, space, no gravity: no side is special). True in a game with gravity: an object that touches what is below it stands on it (slope, elevator, step). See A world with a floor. Resets on an act change.
collision.resolve_enabledboolTrueread / writeAdvanced. False: no pair stops along the path, separates or sticks to the floor. @collide, queries and raycast go on. touching_* is emptied while it is off.

Methods

MethodSignatureReturnsMeaning
resolve(a, b, bounce=, only=)Parameters: a (object or group name), b (object or group name), bounce (number, optional), only (side, list / set of sides or function of the contact, optional)—Registers the pair. Every frame: stops the movement at the impact, slides along the surface, undoes whatever overlap is left. Without bounce= → does not read .vel. With it: 0 inelastic, 1 elastic, >1 super bounce. only=: only these sides of a hold; the rest passes through (One-way). Calling the same pair again replaces bounce= and only=.
unresolve(a, b)Parameters: a (object or group name), b (object or group name)—Cancels the enrollment. Same sides as resolve.

Touching

touching_sides says which sides of the object rest against something solid, as of the last collision check (the previous frame's) — only pairs in resolve(), not sensors. It is the platformer's "am I on the ground?", and a platformer is a world with a floor (collision.floor = True): that is what keeps "bottom" steady on short frames and on slopes.

collision.floor = True              # a world with a floor (A world with a floor)
player["grounded"] @= lambda: "bottom" in player.touching_sides

def update(dt):
    if keyp("SPACE") and player.grounded:
        player.vel.y += JUMP
    player.tilt = "ground"   # slope: tilts only the drawing (Facing sprites)

for c in player.touching_contacts:
    if c.side == "bottom":
        dust_at(c.point)

# which block am I standing on? (None in the air)
standing_on = next((c.other for c in player.touching_contacts if c.side == "bottom"), None)
touching reference
PropertyType (typical value)Read/WriteMeaning
touching_sidesfrozenset{"bottom"}readSides in contact with a resolve() pair. Reactive when a formula depends on it (e.g. grounded @=).
touching_contactstupleplayer.touching_contactsreadOne TouchingContact per resolve() pair. Not reactive. Table below.

Each item of touching_contacts (TouchingContact)

Properties

PropertyType (typical value)Read/WriteMeaning
.otherGraphicc.otherreadThe other body of the pair.
.sidestr or None"bottom"read"top" · "bottom" · "left" · "right" — the side of this body that touches.
.slope_anglenumber22readAngle of the surface in degrees (0 = flat ground). Sprite.tilt = c with the "bottom" anchor turns to that angle and sets the drawing against the plane, along the normal only. tilt = c.slope_angle only turns.
.normalVec2c.normalreadUnit normal (this body → the other).
.tangentVec2c.tangentreadUnit tangent to the surface.
.pointpoint or Nonec.pointreadContact point in the world (the middle of the contact points, or the resting point — the corner it rests on, for a corner on a face). VFX / dust. It can be None.

Methods

MethodSignatureReturnsMeaning
.slide_along(velocity)Parameters: velocity (Vec2)Vec2Projects the velocity onto the tangent (walking / sliding on a slope).

Walked off the platform or jumped → the side goes away at once. Coyote time and jump buffering are your own timers on top of it (recently). touching_contacts can hold more than one item (wall + floor in a corner).

Don't confuse

Looks likeIt isIt is not
@collide(hero, "block") to know which block the hero stands ontouching_contacts (the c.other of the "bottom" contact): it comes from the position already resolved and is steady at any frame rate. @collide on a resolve() pair does not flicker while the body is still, but at the seam between two blocks, with uneven frames, a round body can enter and leave the next block for a few frames.the enter/exit of @collide per block
A sensor / pickup shows up in touching_*never the case: @collide without resolve() detects overlap, but it does not become a floor.a sensor contact
touching_contacts is this frame's contactthe previous frame (like touching_sides). To decide in the same frame, use @collide_stay with info.side, before the automatic resolve.the current frame
On a slope, turn the hero with .anglea turn of the collider, which then stumbles. Use tilt — the drawing only, with hitbox_anchor="bottom". See Tilt..angle

Floor ahead

object.floor_below(dx=) returns the floor the object would stand on after walking dx, or None if it would fall. It is the platformer's ledge: the enemy that turns back before falling, the hero teetering on the edge. It is a question for a world with a floor (collision.floor = True); in a world without one it warns once.

collision.floor = True              # a world with a floor (A world with a floor)
resolve(enemy, "ground", bounce=0.0)

def update(dt):
    ahead = enemy.hitbox.box.width * st.dir
    if "bottom" in enemy.touching_sides and not enemy.floor_below(dx=ahead):
        st.dir = -st.dir            # the toe reached the ledge: turn back
    enemy.move_by(60 * st.dir * dt, 0)

standing_on = hero.floor_below()    # which floor I am on (or None in the air)
if not hero.floor_below(dx=2 * st.dir):
    hero.play("teetering")          # one more step and it falls
floor_below reference
MethodSignatureReturnsMeaning
floor_below(dx=0, depth=None, group=None)Parameters (by name): dx (signed number, + = right), depth (≥ 0), group (tag or list)the object that serves as floor, or NoneWalks dx in short steps (climbs slopes up to 45°, stops at a wall) and asks whether there is a floor below. Read-only: it does not move, does not use up the pending movement, does not enroll anyone.

The same rules as the physics. The hitbox decides (not the drawing), a floor is a "bottom" contact (±45°, the same as touching_sides), and a drop deeper than depth is a fall. Without depth, the reach that resolve() steps down by itself applies (16 units): it walks down a smaller step; on a bigger one, the body falls. So None means "the physics will let it fall". depth only applies to steps and vertical drops: a slope up to 45° is floor with any depth. A box resting on just its corner is still on the floor; a circle starts to roll once the contact leaves the 45°.

What counts as floor. Without group=, whatever the body resolves against (resolve(body, …), with its only=): a coin, a sensor and an enemy with only @collide do not count. group="ground" names the floor — that is how a critter with no resolve(), moved by script, asks. With neither, it raises ValueError listing both ways out.

What dx asks. One number covers the cases: dx=0 is the floor right now; a small dx is "do I fall on the next step?"; dx = width is "has the toe gone past the ledge?" (the enemy that turns back); dx = width / 2 is "has the middle gone past?". Use the hitbox's width (hitbox.box.width), not the drawing's (box.width includes the PNG's transparent margin). A wall in the way is not a ledge: the answer is the floor where the walk stopped. Walls are "left" / "right" in touching_sides.

With show_colliders, each question shows where the walk ended: magenta = found a floor, red = would fall.

Don't confuse

Looks likeIt isIt is not
Compare x with the edge of the block underfootfloor_below: two blocks side by side do not turn into a "ledge" at the seam, and a slope does not turn into a cliff.c.other.box.right
A test point with collision.query_point in front of the footenough for a rectangle on flat ground. floor_below uses the whole hitbox and the physics' floor rule (slope, circle, step).the same question
floor_below() for "am I on the ground?""bottom" in touching_sides. floor_below() finds a floor up to 16 units below — also at the start of a jump.grounded

Manual resolution

For when the automatic resolve is not enough: a dash, a kinematic controller, a decision inside the collision function. Five tiers, one recipe — detect → separate position → separate velocity — with the same mass_a/mass_b/bounce=.

TierCallWhen
1resolve(a, b, bounce=)A standing registration — the everyday tier
2shape.resolve_now(target, bounce=)Detects + resolves now; returns a list of CollisionInfo
3info.resolve(bounce=)Inside the collision function — a pair already detected
4info.push_apart() / info.bounce_apart(bounce=)Advanced — applies with explicit masses, not necessarily .mass
5info.mtv_split() / info.velocity_split()Advanced — tuples only, you decide what "apply" means

The path for 95% of scripts: register once, or resolve on your own when the moment calls for it.

# Declarative (the engine runs it by itself):
resolve(player, "walls", bounce=0.0)

# Manual in update — before Scena checks the frame's collisions:
for info in player.resolve_now("walls", bounce=0.0):
    if info.side == "bottom":
        grounded = True

# Manual inside the collision function — a conditional resolve:
@collide_stay(player, "walls")
def touch(me, other, info):
    if not player.dashing:
        info.resolve(bounce=0.0)

The standing registration resolve(a, b) follows the path of the frame's movement. resolve_now / info.resolve only push an already overlapping pair apart along the shortest way that separates them (the MTV) — they do not look at the path.

An escape hatch: make-believe masses (not the bodies' real .mass) and partial effects that resolve() cannot express by itself.

# Tier 4 — applies right away, with masses chosen on the spot:
@collide(player, boulder)
def hit(me, other, info):
    info.push_apart(mass_a=1.0, mass_b=10.0)               # position only
    info.bounce_apart(mass_a=1.0, mass_b=10.0, bounce=0.3)  # + velocity

# Tier 5 — tuples only: you decide what "apply" means —
# here, half a push, for a softer bump:
@collide(player, cloud)
def hit(me, other, info):
    (dxa, dya), (dxb, dyb) = info.mtv_split(mass_a=1.0, mass_b=1.0)
    player.move_by(dxa * 0.5, dya * 0.5)
    cloud.move_by(dxb * 0.5, dyb * 0.5)

Here mass_a= / mass_b= do not need to be a.mass / b.mass: they are for a push that is just for effect, without touching the real mass. Without an explicit slop=, mtv_split / velocity_split make the bodies touch exactly (no gap); push_apart / bounce_apart (and resolve) leave the small gap that keeps stay from jittering.

Resolution methods on CollisionInfo
MethodSignatureReturnsMeaning
shape.resolve_now(target, bounce=)Parameters: target (object or group name), bounce (number, optional)list of CollisionInfoDetects and resolves now, without waiting for the frame's automatic check.
info.resolve(bounce=)Parameters: bounce (number, optional)—push_apart + (if bounce is given) bounce_apart. Left out = position only, like resolve(a, b) without bounce=.
info.push_apart(mass_a=, mass_b=)Parameters: mass_a (number), mass_b (number)—mtv_split + move_by on both bodies. Without explicit masses, it uses a.mass/b.mass.
info.bounce_apart(mass_a=, mass_b=, bounce=1.0)Parameters: mass_a (number), mass_b (number), bounce (number)—velocity_split + writes .vel. Here bounce is already 1.0 by default (unlike resolve(), which skips the velocity when it is left out).
info.mtv_split(mass_a=1, mass_b=1, slop=0)Parameters: mass_a (number), mass_b (number), slop (number)two offsets (dx, dy)Only the push tuple along the shortest way apart — no move_by. slop: how much of the overlap is left undone (0 = they touch exactly). A mass <= 0 raises an error.
info.velocity_split(mass_a=, mass_b=, bounce=, vel_a=, vel_b=)Parameters: mass_a (number), mass_b (number), bounce (number), vel_a (Vec2), vel_b (Vec2)two Vec2Only computes the two objects' new velocities after the impact — without writing .vel. vel_a/vel_b are required here (it does not read .vel by itself).
info.reflect_velocity(velocity, restitution=1)Parameters: velocity (Vec2), restitution (number)Vec2Reflects a velocity about normal. The mass_b=STATIC case of velocity_split — it still exists, but it is not the recommended primitive for a moving body.

Queries

Ask the system on the spot, without waiting for a collision function to fire: who is at this point, in this circle, in this cone, in front of this ray.

collision already exists after from scena import * — like canvas or clock. You do not build it. It is not a Shape. Scena checks collisions by itself every frame; the script does not need to call anything for that.

hits = collision.query_point(mouse)
near = collision.query_circle(mouse, radius=80)
enemies = collision.query_circle(mouse, radius=80, group="enemy")
seen = collision.query_sector(guard, radius=300, spread=60, group="enemies")
wedge = Circle(center=lambda: guard.center, radius=300, spread=60, use_center=True)
wedge["angle"] @= lambda: guard.angle
hit = collision.raycast(player, p2=mouse)
blocked = collision.raycast(hero, p2=enemy, ignore=enemy)
if hit:
    body, t, point = hit

info = test_collision(player, door)
victims = collision.query_shape(explosion, group=["ships", "asteroids"])
nearby = player.collides_with(group="enemy")

Who a query sees. Without group= (or with group=ANYTHING): only what is already enrolled (collidable, @collide, resolve, on_collide) — bodies, not parts. With group= (a tag, group['name'], a list / tuple / set): the members of that group, enrolled or not, without enrolling anyone. A Graphic at the origin is the one asking and is never a hit; ignore= adds to it (a body, a tag, group['name'], or a list).

collision reference
MethodSignatureReturnsMeaning
collision.query_point(x, y=None, *, group=, ignore=)Parameters: x (a point, or the number x with y); group, ignore (optional)listThe objects whose hitbox contains the point. A point (query_point(mouse)) or two numbers. Not contains_point (drawing / click).
collision.query_circle(x, y=None, radius=None, *, group=, ignore=)Parameters: x (a point, or the number x with y); radius (number ≥ 0); group, ignore (optional)listThe objects that overlap the circle. query_circle(x, y, radius) or query_circle(p, radius=80). After a point, radius= goes by name. A negative radius raises ValueError.
collision.query_sector(origin, angle=, radius=, spread=, group=, ignore=)Parameters: origin (point); angle (degrees, optional); radius and spread (numbers ≥ 0); group, ignore (optional)listWhat overlaps a sector (a radar). spread=60 is the whole opening (±30). With angle= left out, it uses a Graphic's .angle (on a Sprite that is already where the art points). Without a Graphic, angle= is required. spread=0 becomes just the sector's middle line: it returns every object that line touches. spread=360 is query_circle. Above 360 raises ValueError. Registration order, not sorted by distance. Blocked sight: raycast afterwards. Draw the same slice: Circle(center=, radius=, angle=, spread=) (use_center starts out True; False is the chord segment).
collision.query_shape(shape, group=)Parameters: shape (object), group (str or list)listWhat overlaps shape's geometry. group=: a tag, a list / set (OR), group['name'], ANYTHING. The probe itself is not a hit.
shape.collides_with(group=)Parameters: group (str or list)listA shortcut: query_shape(self, group=).
test_collision(a, b)Parameters: a (object), b (object)CollisionInfo, or NoneA one-shot test between two targets.
collision.raycast(p1, p2= / vec= / angle= length=)Parameters: p1 (point); one end: p2 (point), or vec (offset), or length with an optional angle; group, ignore (optional)tuple, or NoneThe first object the segment hits. A second argument without a name raises TypeError — the end goes by name: p2=, vec=, or angle= and length=. With angle= left out, it uses the Graphic's .angle. vec= does not take a Point, a Graphic or mouse. The end target counts, unless it is in ignore=. (object, t, point) or None: the object hit; t from 0 to 1, the fraction of the segment up to the impact (0 = it starts inside); the point of impact.

What collides

What enters the system (collidable) and with which shape. The hitbox is not the drawing.

ball.collidable = True
wasp.collidable = False   # opt-out, even with @collide("wasp", …)

collidable is a property on Shape, Sprite and SpatialFx — it turns the hitbox on in the registry (queries, a target of ANYTHING, debug outlines). It is not a method of collision: it lives on the body. Default False. @collide, resolve and on_collide = fn enroll by themselves. False takes it out of the system (and keeps it out) — even with @collide("wasp", …) — until it goes back to True. Two bodies with only the flag are not tested against each other every frame; name the pair or use on_collide / ANYTHING.

A point of a Shape (c.center, rope.p2, a vertex) is not an object that collides: collidable = True, on_collide, @collide and resolve with it raise TypeError. Collide with its owner (@collide(rope, wall); info.point says where it touched), test a point (wall.contains_point(rope.p2)) or create an object that follows it: tip = Point(lambda: rope.p2) — that one is yours; destroy it when you like. Queries (test_collision, collides_with) take the point.

BodyWhat collides
ShapeThe model's geometry (circle, rectangle, polygon…).
TrackA row of thin rectangles along the stroke, as thick as line_width. Closed = a ring (empty hole), not a disc. begin/end trim the stroke that collides.
SpriteThe computed hitbox (the body): shape and art chosen by hitbox_shape= / hitbox_source=, frozen while animating. See Sprite hitbox.
Sprite partsprite.add_hitbox(group=…) — an extra collider, detection only, that follows the drawing and answers for the groups it claims. See Parts.
SpatialFxThe domain (orb, area, beam) — not the glow.

It does not exist on a Widget, a Text, or on an Entity() with no drawing. A parallax / ui layer: TypeError. To see the outlines: collision.show_colliders() — pairs in resolve() in gold.

Collider

A Collider joins several shapes into a single body for collision — a boss made of a torso and a head, a ship of several pieces. @collide(body, "bolt") fires once for the body, and the function's me is the Collider, not the piece that was hit. The pieces still draw and move each on its own; the Collider only joins them for collision. A single shape does not need a Collider: name it directly in @collide / resolve.

torso = Rect(center=(500, 300), width=80, height=120)
head = Circle(center=(500, 390), radius=30)
body = Collider([torso, head])

@collide(body, "bolt")
def on_hit(me, other, info):
    other.destroy()

Collider(shapes)

Parameter / fieldPassTypeMeaning
shapes1stlist of Shapes[torso, head]The pieces of the body. body.shapes reads the ones still alive (a destroyed piece leaves the list).
on_collide / on_collide_stay / on_collide_exit—function or NoneThe same three phases as in Detect, on the whole body: body.on_collide = lambda me, other, info: … reacts to any enrolled object.

Weak spot: a piece that is also a body. A piece can be, besides a part of the Collider, a body of its own — with collidable = True, or because a rule names its group. They are two separate outlines: the rule for the piece's group sees the piece, and the rule for the body sees the body.

torso = Rect(center=(500, 300), width=80, height=120, group="weak_spot")
head = Circle(center=(500, 390), radius=30)
boss = Collider([torso, head])

@collide("bolt", "weak_spot")            # a shot in the torso: double damage
def on_weak_spot(shot, piece):
    shot.destroy()

boss.on_collide = lambda me, other, info: …   # a shot anywhere on the boss

The body never collides with its own pieces (nor pushes them in a resolve), and two pieces of the same Collider that are also bodies (two weak spots) do not collide with each other. A rule with ANYTHING sees both bodies: a shot in the torso is two contacts, one with the torso and one with the boss — name the group to count it once. In queries, the Collider comes before the pieces that are also bodies: collision.query_point (and query_circle, query_sector, query_shape) lists the boss first, and collision.raycast returns the boss when the ray enters both at the same point; raycast(…, group="weak_spot") returns the torso. The order of the lines changes none of this.

Where else to look — Move · React · Geometry

Geometry

Geometry math: vectors (Vec2), where two outlines cross, and point functions — distance, heading, midpoint, the nearest one. Angles in degrees. Math on values (remap, blend, chase, roll) is in Utilities.

Vector → Vec2
Outlines crossing → Crossings
distance / heading / closest_point → Points

Vec2

A Vec2 is an arrow: a displacement (dx, dy) or a velocity, with a length and a direction. You can add it to another, multiply it by a number, rotate it. Angles in degrees (0 = to the right).

v = Vec2(1, 0)
w = vec_from_angle(90, length=200)
a1 = v + w          # another Vec2
a2 = w - v          # another Vec2
a3 = w * 0.5        # another Vec2, half as long
a4 = w / 2          # another Vec2 (divided by 2)
ship.move_by(angle=w.angle, distance=w.length)

Changing the length and heading of an existing Vec2. .length and .angle are computed from .x / .y: read-only (v.length = 5 raises an error that shows the right form). To set a length and a heading, build the arrow with vec_from_angle(heading, length) and copy it into v with <<. v stays the same object, so whatever kept it (another object, a list, a formula that reads v) sees the new values. v = vec_from_angle(…), on the other hand, only makes the name v point to another Vec2; whatever kept the old one does not see the change. << is in Link.

v = Vec2(3, 4)                      # length 5, heading ≈ 53°
v << vec_from_angle(30, 10)         # heading 30°, length 10: x ≈ 8.66, y = 5
v << vec_from_angle(v.angle, 2)     # changes only the length (heading stays 30°)
v << vec_from_angle(90, v.length)   # changes only the heading (length stays 2)
Vec2 reference

Properties

PropertyType (typical value)Read/WriteMeaning
.x / .ynumber1read / writeThe components: how far the arrow goes in x and in y.
.length / .anglenumber200readLength and heading in degrees (0 = +x, from −180 exclusive to 180: an arrow pointing left reads 180), computed from .x / .y. To change them on v itself: v << vec_from_angle(heading, length) (only the length: v << vec_from_angle(v.angle, n); only the heading: v << vec_from_angle(degrees, v.length)). For a new Vec2: .normalize() * n (or cap it with .clamp_length) and .rotate(degrees).

Methods

MethodSignatureReturnsMeaning
Vec2(x, y)Parameters: x (number), y (number)Vec2Constructor.
vec_from_angle(angle, length=1, reference_vec=None)Parameters: angle (number), length (number), reference_vec (Vec2 or pair)Vec2Degrees. 0 = +x. With reference_vec, the angle counts from its direction (vec_from_angle(90, reference_vec=front) = 90° to the left of front). To move: move_by(angle=, distance=).
+ / -Parameters: other (another Vec2)Vec2Adds / subtracts another vector (or an (x, y) pair). v += w and v -= w change v itself. A Point is a place, not a displacement: v + p is the moved point (a Point), and v - p, v += p, v -= p raise TypeError (the vector between two points is p - q).
* / /Parameters: numberVec2Multiplies / divides by a scalar. Vec2 on the left: v * 2, v / 2. v *= 2 and v /= 2 change v itself, like +=. A True / False is not a number: v * True raises.
.dot(other)Parameters: other (Vec2)numberDot product: positive if the arrows point the same way, 0 if they are perpendicular, negative if opposite.
.normalize()No parametersVec2Same heading, length 1.
.rotate(angle)Parameters: angle (number)Vec2Rotates by degrees (counterclockwise).
.lerp(other, t)Parameters: other (Vec2), t (number)Vec2Blends with other: t=0 gives this vector, t=1 gives other, 0.5 the middle. Outside 0–1 it keeps going along the line (no clamping). There is also the lerp function.
.distance(other)Parameters: other (Vec2 or point)numberDistance. Same metric as distance (Point, tuple, Graphic, …).
.reflect(normal)Parameters: normal (Vec2)Vec2Reflects about the normal. The same as .reflect_about.
.cross(other)Parameters: other (Vec2)numberCross product in the plane: positive if other is to the left of this arrow (counterclockwise), negative if to the right.
.project_onto(onto)Parameters: onto (Vec2)Vec2Projection onto onto.
.reflect_about(normal)Parameters: normal (Vec2)Vec2Bounce off a surface with that normal: Vec2(1, -1).reflect_about(Vec2(0, 1)) → (1, 1).
.perp_left() / .perp_right()No parametersVec2Perpendicular to the left / to the right.
.clamp_length(min_length, max_length)Parameters: min_length (number), max_length (number)Vec2Same heading, length held between min_length and max_length: vel.clamp_length(0, 300) caps the speed at 300.
.to_tuple()No parameters(x, y)A pair of numbers. Also x, y = v (a snapshot of the current value). v[0] raises TypeError: use v.x.

Crossings

The points where the outlines of two shapes cross, as (x, y) tuples. It does not tell you whether one shape is inside the other (for that, @collide). To link a point to a crossing (@= or lambda: in the constructor), use intersection.

The list, now. Empty if the outlines do not meet.

hits = intersections(line, circle)
for x, y in hits:
    Circle(center=(x, y), radius=6, color="red")

hit = min(hits, key=lambda p: distance(line.p1, p)) if hits else None

intersection always returns a point, so it works in a constructor lambda: — here, the chord: the segment between the two crossings. To hide the chord when there are not 2 crossings, link visible with @=.

c1 = Circle(center=(400, 400), radius=120)
c2 = Circle(center=(520, 400), radius=90)

chord = Line(
    p1=lambda: intersection(c1, c2, 0),
    p2=lambda: intersection(c1, c2, 1),
)

chord["visible"] @= lambda: len(intersections(c1, c2)) == 2
Signatures
MethodSignatureReturnsMeaning
intersections(a, b)Parameters: a (shape), b (shape)list of pointsWhere the outlines cross now. [] if nowhere.
intersection(a, b, i=0)Parameters: a (shape), b (shape), i (integer)point (x, y)Crossing number i, for @= / the constructor. If there is none, it returns a point near both shapes instead of raising. i < 0 → ValueError.
What goes in / order / what intersection returns
TopicRule
AcceptedLine, Circle, Ellipse, Rect, Square, Concave, Polygon, RegularPolygon, Triangle, Box. Any other type (Point, Track, Sprite) → TypeError.
OutlineLine = the segment p1→p2 (thickness ignored). Circle = the full circle (arc ignored). Ellipse = the whole outline, with rotation. An ellipse flattened to zero = the segment of its major axis. Box / n-gon = its edges (corner_radius ignored). Concave = the box with its curve, as chords within 0.01 units of it.
OrderWith a Line: along it. Two circles: left → right of the line through the centers. If the first is a Circle / Ellipse: along it, from its local +x, in the direction of rotation. Otherwise: along the first.
How manyEllipse × circle or ellipse: up to 4 points. A tangent counts as 1.
What intersection returnshits[i] if it exists; otherwise the last crossing (at a tangent, 0 and 1 give the same point); otherwise a point near both shapes.

A circle inside a square, not touching its outline → []. This is not @collide nor CollisionInfo.points. It does not return a Point. Point / Track raise TypeError. A point on the body: closest_point.

Points

Distance, heading, midpoint, nearest item, projection onto the body. (x, y) tuples — they do not create a Point. point + (dx, dy) returns a new Point (place, not travel).

p = middle_point(a, b)
d = distance(hero, enemy_ship)
hero.angle = heading(hero, enemy_ship)
target = nearest(player, group["wasp"])
dot.center << closest_point(planet, mouse)
shot = Sprite("laser.png", center=ship.center + (0, 28))
beneath = ship.center - (0, 20)

Point. Where the API asks for a place, a point can be a Point, a Vec2, (x, y), a Graphic (its .center) or mouse. Wherever the API expects a place — move_to, center=, about=, snapshot, closest_point, pan_to, query_point, raycast, a tween of a point, move_along(at=), iris center= — any of these works. This copies the position now. To follow it: Circle(center=lambda: mouse) or center @= mouse. A displacement (move_by, pan_by, Track's vec= / vectors=) refuses a place. Graphic and SpatialFx have no .x / .y — the position is .center.

Helpers
MethodSignatureReturnsMeaning
middle_point(p1, p2, weight=0.5)Parameters: p1 (point), p2 (point), weight (number)point (x, y)An (x, y) tuple. Point, Vec2, tuple, Graphic or mouse.
distance(p1, p2)Parameters: p1 (point), p2 (point)numberEuclidean distance (≥ 0). Also p1.distance(p2) on a Point (and a Vec2).
heading(origin, target)Parameters: origin (point), target (point)numberHeading in degrees (0 = +x, from −180 exclusive to 180: pointing left reads 180), from origin to target. Also p1.heading(p2) on a Point.
nearest(origin, items, *, within=, where=)Parameters: origin (point), items (list), within (number), where (function)the item, or NoneThe item in items nearest to origin. Details in nearest reference, below.
closest_point(shape, p)Parameters: shape (shape), p (point)point (x, y)The point of the filled body nearest to p, always (x, y). Details in closest_point reference, below.
point + (dx, dy)(dx, dy) or Vec2PointTranslation. Also (dx, dy) + point. point - (dx, dy) goes the other way. point - other is the Vec2 between the two. point + other raises TypeError — for the midpoint, use middle_point. The result does not enter the game.
point += (dx, dy)—errorTypeError, on purpose: += would place the object straight at the spot, passing through walls. To travel: move_by. To place: center = center + (dx, dy).
point == other—True/FalseOn a Point, == compares the object, not the position: c.center == (400, 120) is always False, and two different Points at the same place are not equal either (Scena warns in both cases). Same position: distance(c.center, (400, 120)) == 0, or < 1 if the movement does not land exactly. Same object: a is b. On a Vec2 or a tuple, == compares the position.
shape.contains_point(x, y=None)Parameters: x (a point, or the number x with y)True/FalseDoes this object contain the point (in the world)? The drawing — Click / drag. It is not closest_point nor query_point. An object on the "ui" layer under a camera: pointer_hover.
box.contains_point(x, y=None)Parameters: x (a point, or the number x with y)True/FalseTrue if the point is inside this box. A Box is only an area: it does not receive clicks. To find the square of a board: grid.cell_at — Place.
heading reference

heading(origin, target)

Parameters: origin (point), target (point). Returns number (degrees).

The heading from origin to target — the angle to point from origin toward target. Assign it to .angle.

hero.angle = heading(hero, enemy_ship)
hero.angle = hero.center.heading(enemy_ship.center)  # same value
TopicRule
origin · targetWhere you look from and where you look to. The order matters: swapping them turns the heading by 180°.
What goes inPoint, Vec2, (x, y), Graphic, mouse — the same as for distance / nearest.
Same placeSame place → 0.
Sprite.angle is already a heading in the world (art_angle goes into the drawing). Do not add art_angle again.
nearest reference

nearest(origin, items, *, within=None, where=None)

Parameters: origin (point), items (list), within (number), where (function). Returns the item, or None.

Which item in the list is nearest to the origin. It returns the item itself — not a new Point.

ParameterPassType (default)Meaning
origin1stpoint(400, 300)Point, Vec2, (x, y), mouse, or anything with .center / .x/.y (Shape, Sprite).
items2nditerablegroup["wasp"]A list, a tuple, group["wasp"], poly.points, … Items with no position are skipped.
within=name=number or None200Maximum distance (inclusive). Leave it out = no limit. Negative → error.
where=name=function (True/False) or Nonelambda w: w.hp > 0A function that takes each item and returns True/False. Only the items that get True count.

A tie: the first one. Empty / nothing within within → None. For a named fleet, prefer group["wasp"].nearest(…) (same metric; it takes within= and where=).

target = nearest(player.center, group["wasp"])
snap = nearest(mouse, poly.points)
coin = nearest(player.center, coins, within=40)
foe = group["wasp"].nearest(player.center, within=200, where=lambda w: w.hp > 0)
closest_point reference

closest_point(shape, p)

Parameters: shape (shape), p (point). Always returns a point (x, y).

The nearest point on the filled body. Inside → the point itself (except for Line). To follow the pointer: dot["center"] @= lambda: closest_point(planet, (mouse.x, mouse.y)) or, in update, dot.center << closest_point(…), which copies the point into dot.center on that frame (place) — see Mouse.

dot["center"] @= lambda: closest_point(planet, (mouse.x, mouse.y))

# or in update:
def update(dt):
    dot.center << closest_point(planet, (mouse.x, mouse.y))

d = distance(player.center, closest_point(wall, player.center))
TopicRule
shape · pThe Shape to search and the reference point. Accepted Shapes: the same as in Crossings; any other type → TypeError.
InsideDisc / box / polygon → p. The circle's center → (cx + r, cy).

heading is not Handle.heading (how far the tween moved this frame) nor Vec2.angle_to (the angle between two arrows). nearest returns an item (a target, a vertex, …). closest_point returns a point on the shape. contains_point is True/False on the drawing (a click), not on the hitbox — Click / drag. To rank items: sorted(items, key=lambda p: distance(origin, p)).

Where else to look — Place · Collision · Draw · Utilities

UI

Interface controls — buttons, sliders, check boxes and text boxes, lists, menus — fixed to the window, above the game and out of the camera's reach. Without a position, they stack in a column together with the HUD Texts.

All widgets → Widgets
Stack in a column → Column
Button / Slider / CheckBox / TextInput / DropDown / Menu → the sections that follow
Extra space in the stack → ui.gap
Next column → ui.stack_column

Widgets

Widgets are the interface controls — Slider, Button, CheckBox, TextInput, DropDown — drawn on the window, above the game, without following the camera. They are for settings and tools (volume, options, the player's name).

Each widget is tied to a value: its 1st argument, an st field written with brackets (Slider(st["volume"])). Without brackets, st.volume is the current number, and the widget raises an error that shows the fix. The two move together both ways — moving the control writes the value, and writing the value in code (st.volume = 0.2) moves the control. Without top_left=, widgets stack in a column in the corner of the window, together with the HUD Texts. ui.scale and ui.font change the size and the font of all of them. Menu is something else: a question in the middle of the screen, outside the column. A button made from your own art: SpriteButton.

ui.scale = 0.85
ui.font = "Menlo"
st.volume = 0.5
st.mute = False
Text("Volume")
Slider(st["volume"], label="Volume", max_value=1)   # range 0…1
CheckBox(st["mute"], label="Mute")
Button(label="Reset", on_click=reset)
ui reference

Properties

PropertyType (typical value)Read/WriteMeaning
ui.scale / ui.fontnumber or str0.85read / writeSet them before creating the widgets; changing them later does not rebuild the column. ui.font is an installed family or a .ttf / .otf file (found the same way as an image). A missing font: a warning and the default one.
ui.min_label_spacenumber50read / writeMinimum width of the Slider's label column, in design units at ui.scale=1 (the theme multiplies it by ui.scale). Set it before building: only the widgets created after it take the value. Negative: ValueError.

Methods

MethodSignatureReturnsMeaning
ui.stack_reset() / stack_origin / stack_from / stack_columnParameters: see Column—The column's cursor. See Column.
ui.gap()No parameters—Extra space. See ui.gap.
ui.stack_column()Parameters: gap= optional—Next column, same top. See ui.stack_column.
Constructor (every widget)
ParameterPassType (default)Meaning
1st argument (cell)1stfieldst["volume"]The value the widget shows and edits. The two stay tied both ways: the gesture writes to the field; writing the value (st.volume = 0.2) moves the control. It is the field itself, with brackets (st["volume"]), not an @= formula; st.volume without brackets is the number and raises an error.
top_left=name=point(20, 300)Visual top-left corner, in window space. Leave it out to stack (the same column as HUD Text); with it, the column still advances. A copy: a lambda raises an error (a widget does not follow a formula). There is no x1= / y1=.
initial=name=any0.5Starting value. If it comes with an Attribute, this value is written to it.
width= / height=name=number260 / 28Size of the control, in design units. Left out: the theme's (260 × 28, times ui.scale). Slider only has width=; CheckBox uses size=.
widget reference
PropertyType (typical value)Read/WriteMeaning
.data / .valueAttribute or numberslider.dataread / write.data is the tied Attribute; .value is its value now. To show the value in a Text, link to the Attribute: hud["text"] @= lambda: f"{st.volume:.2f}".
visibleboolFalseread / writeFalse hides it: not drawn and gets no clicks. To show it turned off (dimmed, not responding): enabled = False.
pointer_hoverboolTruereadThis widget is the hover target (a widget wins over a Shape or Sprite under it). See Hover.
pointer_pressedboolTruereadPressed on this widget, still held and with the pointer over it. The same rule as for Shapes and Sprites; a turned-off widget never reads True.
on_hover / on_hover_exitfunction or Nonelambda w: …read / writeThe pointer came in / went out. fn(widget) or fn(). The same as @hover / @hover_exit.
group=str"opts"constructorWidgets are Entities. group["opts"].visible / .destroy() works on widgets and HUD Text together.
destroy()method—Takes it out of the game. When the last live item of the current column goes, the cursor goes back to the top of that column.
.boxBoxslider.box.top_rightreadA copy of the widget's rectangle on the window. To put something next to it: ui.stack_origin(slider.box.top_right + (16, 0)).

If the widget's Attribute is linked to a formula (st["volume"] @= …), the formula is in charge: dragging or clicking changes nothing. Changing ui.scale after the widgets are created does not rearrange the column. See Column.

Column

Without top_left=, widgets and HUD Text stack in a column, top to bottom, from the top-left corner of the window. ui.stack_origin / stack_from / stack_reset change where the column goes on; ui.gap() opens a space; ui.stack_column() starts another column beside it. Each item's position is computed when it is created.

st.volume = 0.5
st.mute = False
Text("Volume")
Slider(st["volume"], label="Volume", max_value=1)

ui.stack_column()
Button(label="Another column")

ui.stack_origin(400, 700)
Button(label="Absolute column")

ui.stack_from(hud)
CheckBox(st["mute"], label="Mute")

ui.stack_reset()
Text("Back at the top")
Methods on ui

ui.stack_reset() · ui.stack_origin(x, y) · ui.stack_from(item) · ui.stack_column()

Layout at construction. The next item created without top_left= uses the column; an explicit top_left= still advances the cursor.

MethodSignatureReturnsMeaning
ui.stack_reset()No parameters—The next item created without top_left= goes back to the default origin: (20, height − 40), with the height from init. Clears a pending ui.gap.
ui.stack_origin(x, y)Parameters: x, y (numbers) or a point—Visual top-left corner of the next item created without top_left= (like move_to: (x, y) or a point, e.g. slider.box.top_right + (16, 0)). No space before it. Starts another column at this point. Clears a pending ui.gap.
ui.stack_from(item)Parameters: item (widget or Text)—Goes on below the item's box. Applies the theme's spacing. Clears a pending ui.gap.
ui.stack_column()Parameters: gap= optional—Same visual top, x past the column. See ui.stack_column.
ui.gap()No parameters—Adds one extra theme space. See ui.gap.

Text(..., center=) and stack=False take no place in the column (FPS / SCENA WARNING / Menu). Destroying the last live item of the current column sends the cursor back to the top. Destroying only some of them does not. Changing ui.scale after building does not rearrange.

Button

An interface button with a caption: clicking calls the on_click function — on release, with the pointer still over it; releasing outside the button cancels the click. To turn an option on / off, use CheckBox; for a button made from your own art, SpriteButton.

The function can take nothing, or take the button itself — it gets the button when it asks for a parameter with no default value. That is why the same function serves a button and a Shape (@click(btn, shape)), and why lambda f=f: … or save_game(then=None) do not get the button. Optional: tied to an Attribute, the button writes value_on while it is held and value_off on release — a "hold to fire".

st.firing = False
Button(label="Reset", on_click=reset)
Button(st["firing"], label="Fire")      # st.firing is True while the button is held
Constructor

Button(cell, label=, on_click=, value_on=, value_off=, width=, height=, enabled=)

Name without =: 1st, in order. Name with =: by name.

ParameterPassType (default)Meaning
cell1stfieldOptional (left out: no field; None raises). It follows the button: value_on while held, value_off on release (it is not a toggle — for on/off use CheckBox). Destroyed with the mouse button held (or by a change_act in between), it also writes value_off, with no click: st.firing is not stuck at True. E.g. Button(st["firing"], …).
labelname=str"Button"Text written on the button.
on_clickname=function or NoneCallback: fn() or fn(btn). E.g. on_click=reset. Also btn.on_click = fn or @click(btn). Only Button has on_click.
value_on / value_offname=any or NoneValues written to cell on press / release. Default True / False.
widthname=number260Width of the button, in design units. Left out: the theme's (260 × ui.scale).
heightname=number28Height, in design units. Left out: the theme's (28 × ui.scale).
enabledname=boolTrueFalse: drawn dimmed and ignores clicks and keys (the click does not go through to the game; on_hover still fires). Also w.enabled = False. To hide it: visible = False.

SpriteButton

A game button made from your own art (PNG / JPG / Sheet). The behavior comes built in: it grows and brightens on hover, shrinks and darkens when pressed, clicks on release over it, turns gray when turned off. It is a Sprite (layer ui by default): play, .glow, fade_out… work. For tool buttons (settings, debugging), use Button.

st.coins = 0
start_btn = SpriteButton("button.png", center=(400, 300), label="Play",
                     on_click=start_game, click_sound="click.wav")
shop_btn = SpriteButton("button.png", center=(400, 200), label="Shop", breathe=True)
shop_btn["enabled"] @= lambda: st.coins >= 10    # gray until you have 10 coins
start_btn.label_text.glow = True                  # the label's Text: fine control
# Art per state (UI kits): swaps the image instead of the default effect
quit_btn = SpriteButton("quit.png", hover="quit_hover.png", pressed="quit_down.png",
                    center=(400, 100), label="Quit", label_inset=(0, 0, 0, 6))
# One art, many colors: turn the hue (it is a Sprite)
sell_btn = SpriteButton("button.png", center=(400, 40), label="Sell")
sell_btn.hue = 0.33                               # a third of the circle: red becomes green
Constructor

SpriteButton(source, center=, label=, font=, font_size=, label_color=, label_inset=, on_click=, enabled=, hover=, pressed=, disabled=, hover_sound=, click_sound=, hover_scale=, press_scale=, breathe=, breathe_time=, …)

Plus the Sprite parameters (width=, height=, size=, frame=, layer=, box=, …).

ParameterPassType (default)Meaning
source1stfile or SheetThe button's art. A Sheet with a clip animates as in a Sprite.
labelname=str, number, field or functionText centered over the art. It shrinks to fit (only in the drawing: font_size stays yours). A function or a field links it: label=lambda: f"Lives {st.lives}", label=st["lives"].
font / font_sizename=name or file / number40% of the heightFont and size of the label, as in Text.
label_colorname=color, Gradient or TexturewhiteColor of the label.
label_insetname=number or (left, top, right, bottom)0Margin of the label's box inside the art — for a border or a 3D "step" at the bottom. The label centers and fits in that box.
on_clickname=function or NoneOn release over it: fn() or fn(btn). Also btn.on_click = fn or @click(btn).
enabledname=bool or functionTrueFalse: gray and dimmed, does not click, does not grow. The press does not go through to what is under it (nor to mouse.press, as with any SpriteButton: the press belongs to the button); on_hover still runs. A function links it: enabled=lambda: st.coins >= 10 (or btn["enabled"] @= …).
hover / pressed / disabledname=file, frame or clipNoneArt for that state. With a file source: another file. With a Sheet: a frame name / index or a clip name from it. It replaces the default effect of that state (no growing / darkening / gray on top). The click area does not change.
hover_sound / click_soundname=file, Sound or NoneSound when the hover starts / on each click. The click sound keeps playing if the click calls change_act.
hover_scale / press_scalename=number1.06 / 0.94Drawn size on hover / when pressed. 1 turns it off. Only in the drawing: scale stays yours.
breathename=bool or numberFalsePulses slowly while idle: True = ±5%, or the amplitude (0.03). It pauses on hover, when pressed and when turned off.
breathe_timename=seconds1.6Duration of one breath.
SpriteButton reference
PropertyTypeRead/WriteMeaning
labelstr or None"Play"read / writeThe text shown. Write a string or a number. To link it: btn.label_text["text"] @= lambda: ….
label_textText or NonereadThe label's Text, for fine control: font_size, set_color(Gradient(…)), glow. Its pose is relative to the center of the label's box (label_text.move_to(0, 4) raises it by 4). It moves, turns and disappears with the button; it has no layer or destroy() of its own.
label_inset(left, top, right, bottom)read / writeMargin of the label's box.
enabledboolTrueread / writeTurned on. Linkable: btn["enabled"] @= lambda: ….
on_clickfunction or Noneread / writeThe click.
hover_sound / click_soundfile, Sound or Noneread / writeSounds.
hover_scale / press_scalenumber1.06read / writeDrawn size on hover / when pressed.
breathe / breathe_timenumber0.05read / writeAmplitude (0 = still) and duration of the breath.
pointer_hover / pointer_pressedboolreadHovered / pressed right now (see Click / drag).

label is the string shortcut (as in Button); label_text is the object. The click area is the convex outline of the art at rest: transparent corners do not click, holes inside the art do, and the hover's growing/shrinking does not change the area. The effect is drawing only — btn.scale, width and the collision hitbox do not change.

One art, many colors. .hue turns every color of the art around the hue circle (0.33: red becomes green; see Add-ons). To swap one color for an exact other: btn.visual = Recolor("red", to="green"). White or gray art has no hue, and neither one colors it: draw the base art in color. The label keeps its color; hover, press and the turned-off gray still apply on top.

Slider

A bar with a handle for picking a number within a range. Tied to a numeric Attribute: dragging writes the value, and changing the value moves the handle.

The range comes from min_value= / max_value= and the default is 0 to 100 — a volume from 0 to 1 needs max_value=1. slider.percentage reads the handle's position in the range, from 0 to 1. The mouse wheel over the Slider also changes the value: 1 per step with only_int=True, 2% of the range without it. The Slider does not correct the Attribute: a value already outside the range (or not an integer with only_int=True) stays as it is — the handle stops at the end — until a drag or the wheel writes a new value, always within the range.

st.volume = 0.5
st.lives = 3
Slider(st["volume"], label="Volume", max_value=1)
Slider(st["lives"], label="Lives", min_value=1, max_value=9, only_int=True)
Constructor

Slider(cell, label=, min_value=, max_value=, initial=, show_value=, only_int=, width=, enabled=)

Name without =: 1st, in order. Name with =: by name.

ParameterPassType (default)Meaning
cell1stfieldA numeric field. E.g. Slider(st["volume"], …).
labelname=str or NoneCaption to the left of the bar. Left out: the field's name (Slider(st["volume"]) shows st.volume).
min_value / max_valuename=number0 / 100The two ends of the bar. Equal, or a minimum above the maximum, raise ValueError.
initialname=number or NoneNoneStarting value; written to the Attribute. Without it and without an Attribute: the middle of the range.
only_intname=boolFalseTrue: the handle moves from integer to integer (lives, level).
show_valuename=boolTrueShows the current value to the right of the bar.
widthname=number260Width of the whole thing (caption + bar + number), in design units. Left out: the theme's (260 × ui.scale).
enabledname=boolTrueFalse: drawn dimmed and ignores clicks and keys (the click does not go through to the game; on_hover still fires). Also w.enabled = False. To hide it: visible = False.

CheckBox

A check box: it turns a boolean Attribute (True / False) on and off. Clicking flips the value; writing the value checks or unchecks the box. .checked is the value (True / False), like a Slider's .value: you can save it in JSON. The field is toggle["checked"] (to link it with @=).

st.mute = False
st.debug = False
CheckBox(st["mute"], label="Mute")
CheckBox(st["debug"], label="Colliders", initial=False)
Constructor

CheckBox(cell, label=, initial=, size=, enabled=)

Name without =: 1st, in order. Name with =: by name.

ParameterPassType (default)Meaning
cell1stfieldA bool field. E.g. CheckBox(st["mute"], …).
labelname=str"CheckBox"Caption to the right of the box.
initialname=boolFalseChecked or not at the start; written to the Attribute.
sizename=number18Side of the box, in design units. Left out: the theme's (18 × ui.scale).
enabledname=boolTrueFalse: drawn dimmed and ignores clicks and keys (the click does not go through to the game; on_hover still fires). Also w.enabled = False. To hide it: visible = False.

TextInput

A one-line text box — the player's name, a seed, a console. Tied to a text or number Attribute: Enter, Tab or clicking outside write what was typed; Esc undoes the edit. While the box has the focus (the cursor blinking in it), the text keys belong to it, not to the game.

st.player_name = ""                  # st.name is reserved (it is the State's name)
st.seed = ""
TextInput(st["player_name"], placeholder="Name", label="Player", max_length=12)
TextInput(st["seed"], width=200, top_left=(20, 300))

def run(cmd):                        # console: Enter runs it and you keep typing
    print(cmd)
    console.text = ""
    console.focus()

console = TextInput(on_submit=run, width=400)
Constructor

TextInput(cell, placeholder=, label=, max_length=, on_submit=, width=, height=, initial=, top_left=, enabled=)

Name without =: 1st, in order. Name with =: by name.

ParameterPassType (default)Meaning
cell1stfieldA text or number field. The text is written to it on Enter, on Tab or when the box loses the focus. A bool field raises an error: use CheckBox. E.g. TextInput(st["player_name"], …).
placeholdername=str""Gray hint while the box is empty
labelname=str or NoneNoneCaption on the left. width includes the caption. When stacked, Sliders and TextInputs with a caption share the same caption column.
max_lengthname=int or NoneNoneMaximum number of characters when typing or pasting. A longer value set from code shows in full.
on_submitname=function or NoneRuns on Enter, after the text is written and the box loses the focus: fn() or fn(value) (the value already converted). It runs even when the text did not change; it does not run on a click outside, on Esc, or when the number does not convert. Also entry.on_submit = fn. To keep typing: entry.focus() inside the function.
initialname=str or numberNoneStarting text; written to the Attribute.
widthname=number260Width of the box, caption included, in design units. Left out: the theme's (260 × ui.scale).
heightname=number28Height, in design units. Left out: the theme's (28 × ui.scale).
enabledname=boolTrueFalse: dimmed, takes no focus, Tab skips it. Turning off a focused box writes its text.
.text—strThe text in the box right now — it may not be written to the field yet. When the field changes, the box shows the new value. Writing it changes what is shown; Enter or losing the focus writes it as if it were typed.
.is_valid—boolTrueRead-only. False when the last text written did not convert to the Attribute's type (e.g. "abc" in an int field); the field keeps its previous value, and the typed text stays in the box with an invalid background until you edit it, press Esc or the cell changes.
.focus()—methodGives the keyboard to the box, with its text selected (name screen, console). Raises an error if the box is hidden, turned off, destroyed, or a modal Menu is open.
.focused—boolRead-only. True while the box has the keyboard.

Keys: arrows, Home / End, Backspace / Del; Shift selects; Cmd (macOS) or Ctrl + A / C / X / V selects all and uses the clipboard; Option (macOS) or Ctrl + arrows / Backspace move by word. Dragging selects; a double click selects the word. Esc goes back to the field's value without writing and lets go of the focus. Tab / Shift+Tab go to the next / previous TextInput (in creation order). Text longer than the box scrolls.

Clicking in and leaving without editing never writes: 0.125 stays 0.125. While focused, keyp and on_key_* do not see the text and editing keys, nor Cmd/Ctrl + A / C / X / V / Z / Y (Z and Y do nothing: the box has no undo). Cmd/Ctrl + any other key, F1–F12 and Page Up / Down go through to the game, after the box writes its text as an Enter would, but the focus stays and on_submit does not run.

DropDown

A box that opens a list when clicked and lets you pick one option. Tied to an Attribute: the choice is written to it — the list item itself, not the text shown. dropdown.selected_index reads the position of the current option (0 = the first).

The list opens downward; near the bottom edge of the window, it opens upward. A list too long for the screen stops at the window's edge and scrolls with the mouse wheel (or two fingers on the trackpad); a small bar on the right shows where you are, and when it opens the current option appears in the middle. For a question that pauses the game, use Menu.

st.palette = "night"
st.weapon = "laser"
DropDown(st["palette"], options=["night", "sunset", "day"])
DropDown(st["weapon"], options=["laser", "rocket"], initial="laser")
Constructor

DropDown(cell, options=, initial=, width=, height=, enabled=)

Name without =: 1st, in order. Name with =: by name.

ParameterPassType (default)Meaning
cell1stfieldThe field for the selection. E.g. DropDown(st["palette"], …).
optionsname=list["night", "day"]The choices. The text shown is str() of each item. Without options=: three sample options ("Option 1"…). E.g. options=["night", "sunset", "day"].
initialname=an item of options"laser"Option selected at the start; written to the Attribute. Not in the list: the first one.
widthname=number260Width of the closed box, in design units. Left out: the theme's (260 × ui.scale).
heightname=number28Height, in design units. Left out: the theme's (28 × ui.scale).
enabledname=boolTrueFalse: drawn dimmed and ignores clicks and keys (the click does not go through to the game; on_hover still fires). Also w.enabled = False. To hide it: visible = False.
.text—strThe text of the current option, as it shows in the box. For reading only; the real choice is in the Attribute.

Menu

A Menu is a question in the middle of the window — pause, pick a ship, continue or quit. It appears when created; a click on an option picks it and closes the menu. Three ways to get the choice: an Attribute, the on_choose function, or await in an async mode. You pick with the mouse; it stays out of the widget column.

st.ship = "Blue"

def pick_ship(opt):
    pass

Menu(st["ship"], options=["Blue", "Red"], on_choose=pick_ship, title="Your ship")

async def pause_mode(e):
    answer = await Menu(options=["Continue", "Quit"], title="Paused", pause=True)

def update(dt):
    if keyp.once("ESC"):
        Menu(options=["Continue", "Title screen"], title="Paused", pause=True)
Constructor

Menu(cell, options=, on_choose=, title=, cols=1, modal=True, pause=False, center=, box=, font=, font_size=, color=, background=, icons=, group=)

options= is the only required one. cell is optional. center= and box= do not go together.

ParameterPassType (default)Meaning
cell1stfieldOptional. The field that gets the chosen option. E.g. Menu(st["ship"], …). None raises (it would be st.ship still empty, without brackets).
optionsname=list["Play", "Quit"]Choices. The label is str(). The chosen value is the item, not the text.
on_choosename=functionpick_shippick_ship(opt). Runs on every click, including the same option again. Does not run on destroy().
titlename=strBand at the top. Left out = only the options.
colsname=int1How many columns of options: 1 = a vertical list; len(options) = a single row; any other number = a grid.
modalname=boolTrueDarkens the game. Only one modal at a time; a second one raises an error naming the open one. False: no veil; a new one replaces the open one (the old one closes with None).
pausename=boolFalseTrue pauses the game (clock.paused) while the menu is open; on close, clock.paused goes back to what it was before. Works with modal=False.
centername=point or functionCenter on the window (view space), a value or a lambda. Followed every frame. The panel stays whole on the screen. It does not follow the camera.
boxname=BoxThe panel fills the box; the options are the size of their text, centered in it (a click on the panel outside them picks nothing). The font only shrinks if it does not fit, down to a readable minimum; below that it cuts and warns.
font / font_sizename=str / number"pixel.ttf"A family or a .ttf / .otf file. Leaving out font uses ui.font.
colorname=color"white"Color of the labels. When it is given, the highlight of the option under the mouse comes from this color.
backgroundname=color, Gradient or TextureGradient("red", "gold")Panel background. Gradient and Texture fit the panel as in a shape's fill: the gradient runs to the panel's edge, and the Gradient's size= is measured from the panel's center. The title band is a little lighter. Without color, the highlight of the option under the mouse comes from the background (the Gradient's mean_color(), the Texture's color). An animated fill (WaterFill …) or a value that is not a color raises an error at creation.
iconsname=list of filesOne image per option, above the label. The chosen value is still the option. A number of icons different from the number of options raises an error. A missing file: a checkerboard and a warning.
Menu reference
TopicRule
On choosingCloses, gives back the pause, writes the Attribute, completes the await, destroys itself, then calls on_choose.
await menuThe choice, or None if it closed without a choice. Never Cancelled. It does not need await. Leaving the mode destroys the menu.
destroy()Closes with no choice. Whoever is waiting gets None. on_choose does not run. .choice is read-only.
KeysWith a modal, keyp / mouse.press read false. The click that picks stays hidden until the button is released. Open the pause with keyp.once("ESC") — a key held during the menu does not count as a new press when it closes.
WhereWithout center / box: the size of its text, at the center of the view (not the HUD column). center=lambda: hero.center only follows the hero if the camera does not move.

Don't confuse

Looks likeIt isIt is not
DropDownMenu closes on choosing and blocks the game. DropDown stays in the column and does not pause.the same widget
A Button for each optionMenu is a single question. Several buttons stay on the screen.a menu

ui.gap

ui.gap() opens an extra space between the last item in the column and the next one. Each call adds one space; nothing is drawn.

st.volume = 0.5
st.palette = "night"
Text("Volume")
Slider(st["volume"], label="Volume", max_value=1)
ui.gap()
Button(label="Reset", on_click=reset)

ui.gap()
ui.gap()
DropDown(st["palette"], options=["night", "day"])
Call

ui.gap()

No arguments. No object. The extra space is the same as the theme's space between items (12 at ui.scale=1).

MethodSignatureReturnsMeaning
ui.gap()No parameters—Adds one extra space. The normal space between items stays.
Applies to——The next HUD Text or widget created without top_left=.
Empty column——The 1st item ignores the gap; it is kept for the 2nd.

ui.stack_reset / stack_origin / stack_from / stack_column clear pending gaps. An item with an explicit top_left= does not use them up. It is not a Box. See Column.

ui.stack_column

ui.stack_column() makes the next item start a new column, to the right of the current one and level with its top. Nothing is drawn.

st.volume = 0.5
st.pan = 0.0
st.mute = False
Slider(st["volume"], label="Volume", max_value=1)
Slider(st["pan"], label="Pan", min_value=-1, max_value=1)

ui.stack_column()
CheckBox(st["mute"], label="Mute")
Button(label="Reset", on_click=reset)

ui.stack_column(gap=24)
Text("One more")
Call

ui.stack_column() · ui.stack_column(gap=24)

The new x is the right edge of the widest item in the column, plus the space. The new y is the visual top of this column. Without gap=, the space is the theme's (12 at ui.scale=1).

MethodSignatureReturnsMeaning
ui.stack_column()Parameters: gap= (number, optional)—The next item created without top_left= starts another column to the right, at the same top.
gap=number—Horizontal space. Left out: the same theme space as between items.
Column width——Up to the right edge of the widest item that took a place in the column (HUD Text and widgets). Not the last item.
Empty column——Advances by the default widget width + the space. Two calls in a row skip an empty column.
Applies to——The next HUD Text or widget created without top_left=.

Don't confuse

Looks likeIt isIt is not
ui.stack_column() goes to a fixed point on the screenui.stack_column() takes x and y from the column it just built: x to the right of it, y at its top. It clears a pending ui.gap (the vertical gap does not become space between columns). The labels of the Sliders in the new column line up with each other, not with those of the previous column.an absolute point — that is ui.stack_origin(x, y)

Where else to look — Reactive · World · ui_view

Utilities

Small calculations that show up in every game: convert a value from one range to another (remap), blend two values (lerp), chase a target smoothly (chase) or at constant speed (approach), give a camera some slack (deadzone) and roll yes or no (chance). Math with points and vectors: Geometry.

Remap a range → remap
Blend two values → lerp
Chase with a lag → chase
Chase at constant speed → approach
Camera slack → deadzone
Yes/no → chance

remap

Takes a value from one range to another. Optional: a curve in between (modifier=).

x = remap(hp, 0, 100, 8, 40)
# hp 0 → 8 · hp 100 → 40 · hp 50 → 24

x = remap(hp, 0, 100, 8, 40, modifier="ease_in")
# normalize → curve → output; without modifier= it is linear
Signature

remap(value, in_min=0, in_max=1, out_min=0, out_max=1, modifier=None)

Parameters: value, in_min, in_max, out_min, out_max (numbers); modifier (name or function). Returns a number.

ParameterPassType (default)Meaning
value1stnumber0.5Input value.
in_min, in_max2nd, 3rdnumber (0, 1)0, 100Input range. in_min == in_max returns out_min.
out_min, out_max4th, 5thnumber (0, 1)0, 255Output range.
modifier=name=name or function"ease_in"A curve on [0,1]→[0,1], applied after normalizing. Without it: linear. The same names as ease=, plus spring · wobble (only here: they start and end at 0.5, so they swing around the middle of the output range). Or a callable. An unknown name → ValueError with the list.

Pipeline: normalizes value to [0,1] with in_min…in_max → applies modifier → scales to out_min…out_max.

Curves like bounce / elastic / spring can go outside [out_min, out_max] or not be monotonic. For a custom curve: modifier=lambda t: ….

lerp

Interpolates between two values of the same type. A number, a flat tuple/list of numbers, Vec2, Color, or two Points (returns (x, y)). t is not clamped — eases like elastic go past 0–1.

lerp(0, 100, 0.5)                        # 50
lerp((0, 0), (100, 40), 0.25)             # (25.0, 10.0)
lerp(Color("red"), Color("blue"), 0.5)    # blends in OKLAB
lerp(ship.center, target.center, 0.5)     # (x, y) — does not create a Point
Signature

lerp(a, b, t)

Parameters: a, b (same type / shape); t (number). Returns the same type as a (or (x, y) for Point).

ParameterPassType (default)Meaning
a, b1st, 2ndsame typeColor("red")The two ends. Number · tuple/list · Vec2 · Color · Point.
t3rdnumber0.5How far to go from a to b: 0 = a, 1 = b, 0.5 = halfway. Values outside 0–1 are not cut off (they go past a or b).

It is the same math tween uses to animate a field. Tuples and lists work only if they are flat: numbers, not tuples inside tuples.

Mismatched types or lengths raise an error right away. Not in the middle of the animation. lerp on two Points returns a tuple, not a new Point (a Point is a game object).

chase

chase brings a value closer to a target, a little each frame: fast when it is far and slow when it is close, without going past the target — and at the same pace at any frame rate. Good for a camera that follows, or an HP bar that drops smoothly. It takes the same types as lerp.

bar.width = chase(bar.width, hp, rate=8.0)
look = chase((canvas.pan_x, canvas.pan_y), hero.center, rate=6.0)
canvas.pan_to(look)
Signature

chase(current, target, rate, dt=None)

Parameters: current, target (same type / shape); rate (number); dt (number, optional). Returns the same type as lerp(current, target, t).

ParameterPassType (default)Meaning
current, target1st, 2ndsame type(100, 80)The two ends. Number · tuple · Vec2 · Color · Point (returns (x, y)).
rate3rdnumber6How fast it closes in, per second: every 1/rate of a second, the remaining distance drops to about a third. With rate=6, it has covered ~95% of the way in 0.5 s. Higher = gets there sooner.
dt4th or name=numberclock.dtOptional. Left out = the world's step (clock.dt). Pass dt= in on_update if the Entity has a time_scale, or for a step you compute yourself. dt == 0 (game paused) or rate == 0 returns current without changing anything; a negative dt or rate → ValueError.

It is lerp(current, target, 1 - exp(-rate * dt)). You call it in update. It does not register anything, does not keep running afterwards, does not compete with a tween. Camera recipe: Camera.

Don't confuse

Looks likeIt isIt is not
canvas.follow(hero) makes the camera followa verb that does not exist. Following is chase + pan_to every frame. pan_to(..., time=) (or speed=) freezes the destination at the moment of the call.pan_to(..., time=) alone
chase always moves at the same speeda slowdown: it brakes near the target and, in theory, never arrives exactly. Constant speed and an exact arrival is approach.approach

approach

approach goes from current to target always at the same speed, speed units per second, and arrives exactly: when one step or less is left, it returns the target itself. Called every frame with a moving target, it chases at constant speed. It is the sibling of chase, which slows down as it arrives.

enemy.move_to(approach(enemy.center, player.center, 120))
bar.width = approach(bar.width, hp * 2, 80)

pos = approach(elevator.center, (400, 120), 90)
elevator.move_to(pos)
if pos == (400, 120):
    print("arrived")
Signature

approach(current, target, speed, dt=None)

Parameters: current, target (two numbers or two points); speed (number); dt (number, optional). Returns a number, a Vec2 (if current is a Vec2) or (x, y).

ParameterPassType (default)Meaning
current, target1st, 2ndnumber or pointhero.centerWhere from and where to. Two numbers, or two points: Point, Vec2, (x, y), mouse or a shape's .center. Color → TypeError (use chase).
speed3rdnumber120Speed, in units per second. Each call moves speed * dt. Negative → ValueError.
dt4th or name=numberclock.dtOptional. Left out = the world's step (clock.dt, the same dt that update(dt) receives). Pass dt= in on_update if the Entity has a time_scale. dt == 0 (game paused) or speed == 0 returns current; a negative dt → ValueError.

A point moves in a straight line to the target; on a diagonal, at the same speed as on the horizontal. It never goes past the target or jitters around it, and the arrival is exact: the returned value equals the target (you can test it with ==, as in pos == (400, 120)), and move_to(pos) puts the center exactly there. Compare the returned value, not elevator.center == (400, 120): a Point is never equal to a tuple. You call it in update. It does not register anything, does not keep running afterwards, does not compete with a tween. It pairs with deadzone for a pet on a leash.

Pass the whole point, not x and y separately. approach(ball.center.x, mouse.x, 300) plus another call for y makes the diagonal move faster (√2 times) and reaches one axis before the other. With chase, splitting the axes gives the same result; with approach, it does not. Angles do not take the short way around either: from 350 to 10, approach goes through 180.

Don't confuse

Looks likeIt isIt is not
approach and chase do the same thingtwo different motions: chase brakes near the target and does not arrive exactly; approach moves at constant speed and arrives exactly.two spellings of the same math
move_to(target, time=2) chasesa one-time read: time= (and speed= too) reads the destination once, at the call. To follow a moving target, approach in update, every frame.move_to(..., time=)

deadzone

deadzone lets the target move freely inside a box of size size around current; only when the target leaves the box does the result move, just enough to bring it back to the box's border. For a camera that does not shake with every step the hero takes.

look = (canvas.pan_x, canvas.pan_y)
tx, ty = deadzone(look, hero.center, size=(160, 90))
if hero.grounded:
    ty = canvas.pan_y          # lock Y on the ground — a platformer rule, written by you
canvas.pan_to(chase(look, (tx, ty), rate=6.0))
Signature

deadzone(current, target, size)

Parameters: current, target (point); size (number or pair). Returns (x, y).

ParameterPassType (default)Meaning
current, target1st, 2ndpointhero.centerPoint, Vec2, (x, y) or Graphic (its center).
size3rdnumber or pair(160, 90)Full width and height of the box, in design units, centered on current (size=160 → 80 on each side). A number = a square (160 ≡ (160, 160)). float("inf") on an axis locks that axis (the result stays at current).

Pairs with chase for a camera with slack. It also works outside the camera (aiming, a pet on a leash). An invalid size → TypeError.

Inside the box the result is current. It does not wobble at rest. Rules like “do not follow y while the hero is on the ground” (common in platformers) go in an if of your own, not inside deadzone.

chance

chance(p) rolls the dice: it returns True with probability p, from 0 to 1. chance(0.30) is true 30% of the time.

if chance(0.30):
    drop_loot()
Signature

chance(p)

Parameters: p (number 0 to 1). Returns True/False.

TopicRule
p0 to 1. 0 never, 1 always. Anything else → error.
UseOne roll. It is not an interval — for a steady rhythm use ready.

chance in update rolls every frame. 0.30 at 60 fps ≈ 18 times per second. A steady rhythm: ready. A number in a range: from random import uniform.

Where else to look — Move · Geometry · Frame

Debug

Debugging tools for a running game — overlay methods and keyboard shortcuts — and the catalog of the exceptions Scena raises. The tools are not game-logic API — nothing here takes part in @collide, resolve or the outcome of the game.

show_colliders / show_tracks / show_processes → Methods
HUD / overlay / pause / fullscreen → Keyboard shortcuts
Exception → cause → fix → Error catalog

Methods

Functions that only draw debug overlays on top of the screen. No effect at all on collision, physics or game logic.

collision.show_colliders(enabled=True)
show_tracks(enabled=True)
show_processes(enabled=True)
Debug reference
MethodSignatureReturnsMeaning
collision.show_colliders(enabled=True)Parameters: enabled (on, True/False)—Draws the registered hitboxes (gold = resolve; cyan = an add_hitbox part; green = detection only). The rectangle of a moving object (gold) and its parts (cyan) show together. Ctrl+Shift+7. Queries: Queries. What enters the system: What collides.
show_tracks(enabled=True)Parameters: enabled (on, True/False)—Magenta overlay of the active move_along trips and of the Tracks sitting on a layer. It does not turn on Track.visible. Also collision.show_tracks (same method, another name). Ctrl+Shift+7 (the inspection zoom of Ctrl+Shift+8 does not show the tracks). Off: no extra work in the frame. See Track.
show_processes(enabled=True)Parameters: enabled (on, True/False)—A panel in the top right corner with what is running. One line per task (run_task, the body of an async mode): owner (the class; act / game with no owner; (parked) / (time 0) when the owner is stopped), function, kind, age, what it waits for (wait 0.3s left, move_to 0.6s left, until 4.1s, parallel 1/3 done, race of 3), the line of the await (inside a helper function too) and how much work it owns (+2 work). A task started by another one is indented under it. Then one line per mode (sync = def; with mode_time and the mode's timers). Identical lines become one: Wasp x12. A wait of 5 s or more in an until / until_empty (or a race / parallel with no clock) turns amber, SLOW — only in the panel, never a warning: waiting for a key on the title screen is normal. Ctrl+Shift+6 (the second press also shows the loose timers). Off: no extra work in the frame. See tasks.

Keyboard shortcuts

Shortcuts that work in any Scena game while it runs: all of them are Ctrl+Shift + a digit or letter, on Mac and PC (the F1–F7 keys usually belong to the system).

ShortcutWhat it does
Ctrl+Shift+1Turns the system HUD on / off (FPS, objs, mouse xy in the world; with tasks running, how many and how many are slow: tasks: 3 (1 slow)). Starts off.
Ctrl+Shift+2Turns automatic quality adjustment (FX Auto) on / off: when the game does not fit in the frame, Scena lowers the quality of the effects (high → medium → low) and, last, the rate (60 → 30 fps); if the game logic is what weighs, it goes straight to 30 and keeps the quality. Starts on, at high and 60 fps.
Ctrl+Shift+3Cycles the render profile: low → medium → high.
Ctrl+Shift+4Cycles the framerate: vsync → vsync60 → vsync30 → 60 → 30 → max.
Ctrl+Shift+6Process panel: off → tasks and modes → also the loose timers (every / after / sounds outside any mode or task) → off. The same panel: show_processes(enabled=True).
Ctrl+Shift+7Overlay: colliders + design frame + origin cross + move_along tracks. With @leave_playfield, the playfield too. The same drawing: collision.show_colliders(enabled=True) / show_tracks(enabled=True).
Ctrl+Shift+8Inspection zoom: 100% → 50% → 25%. Does not change canvas.zoom. Design frame / playfield; no tracks.
Ctrl+Shift+ECloses the SCENA WARNING banner (the badge above the FPS; e.g. a missing sound). An error in your code does not become a banner: it comes up with the traceback.
Ctrl+Shift+PTime: running → paused → ¼ → running. Gives back the script's clock.scale when the cycle completes.
Ctrl+Shift+FFullscreen: covers the monitor (no border, no taskbar). Keeps the aspect with black bars. If the window was maximized, pressing F again leaves fullscreen and goes back to maximized. The same as canvas.display = "fullscreen" (the shortcut toggles).
Ctrl+Shift+MMaximizes on the desktop (the taskbar stays). Content with black bars. The title bar's Maximize button is the same mode. From fullscreen, M leaves F and maximizes. The same as canvas.display = "maximized" (the shortcut toggles).
Ctrl+Shift+ZQuits.

Ctrl+Shift+5 does nothing. A Shape's drag handles show with shape.show_handles() — it is per object, there is no global shortcut. M and F toggle; in the script use canvas.display = … (absolute). There is no toggle_fullscreen().

Where else to look — Collision / Queries · Presentation · Frame