Standard Controls

move, jump, shoot at the cursor, and rebind any of it.

▶ Run in browser

Tags: input actions rebinding keyboard mouse controller touch

The controls nearly every game has, declared once as typed actions, and a rebind screen that lets the player change every one of them.

Declaring the actions

The game’s input_context names each action and lists its bindings, and the bindings decide its type: "move": [Axis2D.WASD, Controller.LEFT_STICK] is a Vec2 read with Input.value("move"), while jump (Space, pad A) and shoot (Pointer.PRIMARY, pad X) are buttons. @on_input("jump") runs once per press. shoot fires toward Input.mouse_position; a click or tap works, and a finger on the drawn TouchController stick steers instead.

The rebind screen

Tab, pad Start or the Controls button opens it. Its InputContext carries hides=InputContext.ALL, so the game stands still behind it, and declares a close action of its own (Tab, Esc, Start, Back).

Each cell is a button that adds an InputListener when pressed. The listener hears the player’s next raw press before anything else and claims it, so choosing Space for jump does not also jump, and the cell binds it with one line, InputMap.rebind(target, heard, slot=..., role=...). Esc, or whatever the pad’s Back now is, cancels. Input.label prints every control the way the hardware names or numbers it.

There are two tables over one map:

  • Pad controls rebind an engine entry: InputMap.rebind(Controller.A, heard) points Controller.A at another physical button, and every action naming Controller.A follows. “Swap A and B” is InputMap.swap(Controller.A, Controller.B) for a pad with them the wrong way round.

  • Actions rebind one slot of an action, the keyboard and mouse column or the pad column, and for move one direction of it through BindingRole. A pad press is bound by the entry that names it, so it follows the pad table.

“Map a controller” is for a device no controller database recognises, such as a flight stick, which has only numbered controls. It asks for each standard name in turn and maps the press on that device alone, so the game’s actions play on it unchanged; the mapping is filed under the device’s guid in InputMap.export(). “Reset to defaults” is InputMap.clear_rebinds(): every change is one override layer above the declared bindings, so dropping it is the whole reset, device mappings included.

Controls: WASD / left stick / drawn stick - Move Space / pad A - Jump Click or tap / pad X - Shoot at the cursor Tab / pad Start / Controls - Open the rebind screen (Tab, Esc or Start closes it) Esc / pad Back - Cancel a rebind, or close the screen

Source

  1# /// simvx
  2# tags = ["input", "actions", "rebinding", "keyboard", "mouse", "controller", "touch"]
  3# web = { width = 960, height = 540, responsive = true }
  4# ///
  5"""Standard Controls: move, jump, shoot at the cursor, and rebind any of it.
  6
  7The controls nearly every game has, declared once as typed actions, and a
  8rebind screen that lets the player change every one of them.
  9
 10## Declaring the actions
 11The game's ``input_context`` names each action and lists its bindings, and the
 12bindings decide its type: ``"move": [Axis2D.WASD, Controller.LEFT_STICK]`` is a
 13``Vec2`` read with ``Input.value("move")``, while ``jump`` (Space, pad A) and
 14``shoot`` (``Pointer.PRIMARY``, pad X) are buttons. ``@on_input("jump")`` runs
 15once per press. ``shoot`` fires toward ``Input.mouse_position``; a click or tap
 16works, and a finger on the drawn ``TouchController`` stick steers instead.
 17
 18## The rebind screen
 19Tab, pad Start or the Controls button opens it. Its ``InputContext`` carries
 20``hides=InputContext.ALL``, so the game stands still behind it, and declares a
 21``close`` action of its own (Tab, Esc, Start, Back).
 22
 23Each cell is a button that adds an ``InputListener`` when pressed. The listener
 24hears the player's next raw press before anything else and claims it, so
 25choosing Space for jump does not also jump, and the cell binds it with one
 26line, ``InputMap.rebind(target, heard, slot=..., role=...)``. Esc, or whatever
 27the pad's Back now is, cancels. ``Input.label`` prints every control the way the
 28hardware names or numbers it.
 29
 30There are two tables over one map:
 31
 32- **Pad controls** rebind an engine entry: ``InputMap.rebind(Controller.A, heard)``
 33  points ``Controller.A`` at another physical button, and every action naming
 34  ``Controller.A`` follows. "Swap A and B" is ``InputMap.swap(Controller.A,
 35  Controller.B)`` for a pad with them the wrong way round.
 36- **Actions** rebind one slot of an action, the keyboard and mouse column or
 37  the pad column, and for ``move`` one direction of it through ``BindingRole``.
 38  A pad press is bound by the entry that names it, so it follows the pad table.
 39
 40"Map a controller" is for a device no controller database recognises, such as
 41a flight stick, which has only numbered controls. It asks for each standard
 42name in turn and maps the press on that device alone, so the game's actions
 43play on it unchanged; the mapping is filed under the device's guid in
 44``InputMap.export()``. "Reset to defaults" is ``InputMap.clear_rebinds()``:
 45every change is one override layer above the declared bindings, so dropping it
 46is the whole reset, device mappings included.
 47
 48Controls:
 49  WASD / left stick / drawn stick  - Move
 50  Space / pad A                    - Jump
 51  Click or tap / pad X             - Shoot at the cursor
 52  Tab / pad Start / Controls       - Open the rebind screen (Tab, Esc or Start closes it)
 53  Esc / pad Back                   - Cancel a rebind, or close the screen
 54"""
 55
 56from simvx.core import (
 57    Anchor,
 58    Axis2D,
 59    BindingRole,
 60    CanvasLayer,
 61    Colour,
 62    ControlInput,
 63    Controller,
 64    DeviceType,
 65    Input,
 66    InputContext,
 67    InputListener,
 68    InputMap,
 69    Key,
 70    Label,
 71    Node,
 72    Node2D,
 73    Panel,
 74    Pointer,
 75    Vec2,
 76    on_input,
 77)
 78from simvx.core.ui import Button, HBoxContainer, TouchController, VBoxContainer
 79from simvx.graphics import App
 80
 81SPEED = 240.0
 82JUMP_SPEED = 420.0
 83GRAVITY = 1400.0
 84BULLET_SPEED = 600.0
 85
 86# The devices each column of the action table listens to. A column's slot is
 87# its source's position in the action's binding list, so they line up.
 88DESK = (DeviceType.KEYBOARD, DeviceType.MOUSE)
 89PAD = (DeviceType.CONTROLLER,)
 90
 91# The pad entries the device table shows: the ones this game binds, and Back, which cancels.
 92PAD_ENTRIES = (Controller.A, Controller.B, Controller.X, Controller.Y, Controller.START, Controller.BACK)
 93
 94# What "Map a controller" asks for: the buttons above, then the movement stick one axis at a time.
 95MAPPED_NAMES = (*PAD_ENTRIES, Controller.LEFT_X, Controller.LEFT_Y)
 96
 97ACTION_ROWS = (
 98    ("Jump", "jump", BindingRole.WHOLE),
 99    ("Shoot", "shoot", BindingRole.WHOLE),
100    ("Move up", "move", BindingRole.UP),
101    ("Move down", "move", BindingRole.DOWN),
102    ("Move left", "move", BindingRole.LEFT),
103    ("Move right", "move", BindingRole.RIGHT),
104)
105
106CELL = (130, 28)
107
108
109def cancels(raw) -> bool:
110    """Whether the press *raw* cancels a rebind: Esc, or whatever the pad's Back is now."""
111    return raw is Key.ESCAPE or raw == InputMap.resolve(Controller.BACK)
112
113
114def bound(action: str, slot: int, role: BindingRole):
115    """What one row shows as bound: the whole source, or one direction of it."""
116    source = InputMap.get_sources(action)[slot]
117    return source if role is BindingRole.WHOLE else getattr(source, role.value)
118
119
120class Player(Node2D):
121    """A disc that walks on the ground plane and hops off it."""
122
123    dynamic = True
124    height = 0.0  # how far above its shadow the disc is
125    lift = 0.0
126
127    def jump(self) -> None:
128        if self.height == 0.0:
129            self.lift = JUMP_SPEED
130
131    def on_fixed_update(self, dt: float) -> None:
132        if self.height > 0.0 or self.lift > 0.0:
133            self.height = max(0.0, self.height + self.lift * dt)
134            self.lift = 0.0 if self.height == 0.0 else self.lift - GRAVITY * dt
135
136    def on_draw(self, renderer) -> None:
137        renderer.circle((0, 0), 18, fill=(1.0, 1.0, 1.0, 0.12))  # the shadow
138        renderer.circle((0, -self.height), 18, fill=(0.4, 0.8, 1.0, 1.0))
139
140
141class Bullet(Node2D):
142    """A shot flying in a straight line until it leaves the screen."""
143
144    dynamic = True
145
146    def __init__(self, velocity: Vec2, **kwargs):
147        super().__init__(**kwargs)
148        self.velocity = velocity
149
150    def on_update(self, dt: float) -> None:
151        self.position += self.velocity * dt
152        width, height = self.viewport_size
153        if not (-20 <= self.position.x <= width + 20 and -20 <= self.position.y <= height + 20):
154            self.destroy()
155
156    def on_draw(self, renderer) -> None:
157        renderer.circle((0, 0), 5, fill=(1.0, 0.8, 0.3, 1.0))
158
159
160class Game(Node2D):
161    """Walk, hop and shoot at the cursor; open the rebind screen with Tab."""
162
163    input_context = {
164        "move": [Axis2D.WASD, Controller.LEFT_STICK],
165        "jump": [Key.SPACE, Controller.A],
166        "shoot": [Pointer.PRIMARY, Controller.X],
167        "controls": [Key.TAB, Controller.START],
168    }
169
170    def on_ready(self) -> None:
171        width, height = self.viewport_size
172        self.player = self.add_child(Player(name="Player", position=(width / 2, height / 2)))
173        hud = self.add_child(CanvasLayer(name="HUD"))
174        hud.add_child(
175            Button("Controls", on_press=self.open_controls, anchor=Anchor.TOP_RIGHT, inset=12, size=(128, 32))
176        )
177        self.drawn_pad = self.add_child(TouchController())
178
179    def on_update(self, dt: float) -> None:
180        self.player.position += Input.value("move") * SPEED * dt
181
182    @on_input("jump")
183    def jump(self, event) -> None:
184        self.player.jump()
185
186    @on_input("shoot")
187    def shoot(self, event) -> None:
188        aim = Input.mouse_position - self.player.position
189        if aim.length() > 0:
190            self.add_child(Bullet(aim.normalized() * BULLET_SPEED, position=self.player.position))
191
192    @on_input("controls")
193    def open_controls(self, event=None) -> None:
194        if self.find(RebindScreen, direct=True) is None:
195            self.add_child(RebindScreen(self.drawn_pad))
196
197
198class RebindScreen(CanvasLayer):
199    """The pad's controls and the actions' bindings, one cell per thing a player can rebind."""
200
201    input_context = InputContext(
202        {"close": [Key.TAB, Key.ESCAPE, Controller.START, Controller.BACK]},
203        name="rebind screen",
204        hides=InputContext.ALL,
205    )
206
207    def __init__(self, drawn_pad: TouchController, **kwargs):
208        super().__init__(**kwargs)
209        # Put away while the screen is open, so it neither covers the tables nor takes a tap meant for them.
210        self.drawn_pad = drawn_pad
211
212    def on_ready(self) -> None:
213        self.drawn_pad.visible = False
214        panel = self.add_child(Panel(anchor=Anchor.FULL_RECT, inset=24))
215        panel.bg_colour = Colour.hex("#1A1A2E")
216        page = panel.add_child(VBoxContainer(anchor=Anchor.FULL_RECT, inset=(18, 12), separation=8.0))
217        page.add_child(Label("Pick a cell, then press the control it should be (Esc or Back cancels)"))
218        tables = page.add_child(HBoxContainer(separation=24.0))
219        self.status = page.add_child(Label(""))
220
221        pad = tables.add_child(VBoxContainer(separation=6.0))
222        pad.add_child(Label("Pad controls"))
223        for control in PAD_ENTRIES:
224            row = pad.add_child(HBoxContainer())
225            row.add_child(Label(Input.label(control), size=(70, 28)))
226            row.add_child(RebindButton(control, PAD, size=CELL))
227        pad.add_child(Button("Swap A and B", on_press=self.swap_ab, size=(200, 28)))
228        pad.add_child(Button("Map a controller", on_press=self.map_controller, size=(200, 28)))
229
230        actions = tables.add_child(VBoxContainer(separation=6.0))
231        actions.add_child(Label("Actions"))
232        for title, action, role in ACTION_ROWS:
233            row = actions.add_child(HBoxContainer(separation=8.0))
234            row.add_child(Label(title, size=(110, 28)))
235            row.add_child(RebindButton(action, DESK, slot=0, role=role, size=CELL))
236            if role is BindingRole.WHOLE:
237                row.add_child(RebindButton(action, PAD, slot=1, role=role, size=CELL))
238            else:  # move's pad source is a whole stick: shown, not rebound per direction
239                row.add_child(Label(Input.label(bound(action, 1, BindingRole.WHOLE)), size=CELL))
240
241        footer = page.add_child(HBoxContainer())
242        footer.add_child(Button("Reset to defaults", on_press=self.reset, size=(180, 30)))
243        footer.add_child(Button("Close", on_press=self.destroy, size=(120, 30)))
244
245    def on_exit_tree(self) -> None:
246        self.drawn_pad.visible = True
247
248    def refresh(self) -> None:
249        for cell in self.find_all(RebindButton):
250            cell.refresh()
251
252    def map_controller(self) -> None:
253        if self.find(MappingWalk, direct=True) is None:
254            self.add_child(MappingWalk(self.status))
255
256    def swap_ab(self) -> None:
257        InputMap.swap(Controller.A, Controller.B)
258        self.refresh()
259
260    def reset(self) -> None:
261        InputMap.clear_rebinds()
262        self.refresh()
263
264    @on_input("close")
265    def close(self, event) -> None:
266        self.destroy()
267
268
269class RebindButton(Button):
270    """One cell of the rebind screen: press it, then press the control it should be.
271
272    *target* is an action's name, whose *slot* and *role* the cell rebinds, or
273    an engine entry such as ``Controller.A``, which the cell points at a raw control.
274    """
275
276    def __init__(self, target, devices, *, slot: int = 0, role=BindingRole.WHOLE, **kwargs):
277        super().__init__(**kwargs)
278        self.target, self.devices, self.slot, self.role = target, devices, slot, BindingRole(role)
279        self.listener: InputListener | None = None
280        self.pressed.connect(self.listen)
281
282    def on_ready(self) -> None:
283        self.refresh()
284
285    def refresh(self) -> None:
286        if self.listener is not None:
287            self.text = "press..."
288        elif isinstance(self.target, str):
289            self.text = Input.label(bound(self.target, self.slot, self.role))
290        else:
291            raw = InputMap.resolve(self.target)
292            self.text = Input.label(raw) if raw is not None else "unbound"
293
294    def listen(self) -> None:
295        if self.listener is not None:  # a second press cancels
296            self.listener.destroy()
297            self.listener = None
298        else:
299            self.listener = self.add_child(InputListener(devices=self.devices))
300            self.listener.heard.connect(self.captured)
301        self.refresh()
302
303    def captured(self, heard: ControlInput) -> None:
304        self.listener = None
305        if not cancels(heard.control):
306            InputMap.rebind(self.target, heard, slot=self.slot, role=self.role)
307        self.ancestor(RebindScreen).refresh()
308
309
310class MappingWalk(Node):
311    """Ask for each standard name in turn and map the press onto the controller it came from.
312
313    The listener hands back the raw control with the device that sent it, so the
314    rebind lands on that device alone. Esc stops the walk, keeping what was mapped so far.
315    """
316
317    def __init__(self, status: Label, **kwargs):
318        super().__init__(**kwargs)
319        self.status = status
320        self.remaining = list(MAPPED_NAMES)
321
322    def on_ready(self) -> None:
323        self.ask()
324
325    def ask(self) -> None:
326        if not self.remaining:
327            self.finish("Mapped")
328            return
329        name = self.remaining[0]
330        verb = "Push the stick along" if name in (Controller.LEFT_X, Controller.LEFT_Y) else "Press"
331        self.status.text = f"{verb} {Input.label(name)} on the controller to map (Esc stops)"
332        listener = self.add_child(InputListener(devices=(DeviceType.KEYBOARD, *PAD)))
333        listener.heard.connect(self.heard)
334
335    def heard(self, heard: ControlInput) -> None:
336        if heard.control is Key.ESCAPE:
337            self.finish("Stopped; mapped")
338            return
339        if heard.device_id in Input.controllers:  # any other key just asks again
340            InputMap.rebind(self.remaining.pop(0), heard)
341        self.ask()
342
343    def finish(self, outcome: str) -> None:
344        self.status.text = f"{outcome} {len(MAPPED_NAMES) - len(self.remaining)} controls"
345        self.destroy()
346
347
348if __name__ == "__main__":
349    App(title="Standard Controls", width=960, height=540).run(Game())