Files
libstormgames/controls_menu.py
Storm DragonandClaude Opus 5.5 4ef866717c Keyboard and game controller support through actions, with rebinding and rumble.
Games name their actions with default keys and controller inputs and ask
Controls whether they are held, pressed or how far they are pushed. Library
menus, text display, message boxes, cut scenes, power bars and pause work
with a controller. controls_menu lets players rebind and set rumble; only
changes from the defaults are saved in config.ini.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 20:17:31 -05:00

374 lines
18 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A menu where the player changes a game's controls and controller options.
controls_menu() lists each of the game's actions with what it is bound to,
grouped as the game grouped them, then rumble, rumble strength, the button
names to use, and Reset all controls. Every change is saved straight away,
and only bindings that differ from the game's defaults are saved.
Rebinding listens for the next key or controller input. The library's own
menu controls (the arrow keys, Enter and Escape, and the d-pad, left stick,
cross and circle on a controller) cannot be changed, so the player can always
get back out.
"""
import pygame
from .controls import (Binding, Controls, buttonNameSchemes, buttonSchemeTitles, key_save_name,
modifierKeyCodes, padButtonNames, padTriggers, pad_button, releaseThreshold, stickDirections,
translate_event)
from .i18n import _, reset_language
from .menu import is_language_reset
from .speech import Speech
listenTimeoutMs = 5000
# How far a stick or trigger must go to count while listening, well past the centre.
listenThreshold = 0.7
rumbleStrengthStep = 10
modifierMasks = (("ctrl", pygame.KMOD_CTRL), ("shift", pygame.KMOD_SHIFT), ("alt", pygame.KMOD_ALT),
("meta", pygame.KMOD_META))
def _starting_input(event):
"""The input that opened listening, to be ignored until it is let go."""
button = pad_button(event)
if button:
return ("pad", button)
if getattr(event, "type", None) == pygame.KEYDOWN:
return ("key", event.key)
return None
def capture_input(controls, ignore=None, timeoutMs=listenTimeoutMs):
"""Wait for one key or controller input and return it as a Binding.
A key pressed with Ctrl, Shift, Alt or Meta held becomes a binding such as "ctrl+s", and a modifier
key let go on its own becomes that key. A controller button counts when it is let go, or as the
held part of a binding such as "l1+west" when another input is pressed while it is down. Sticks and
triggers count once pushed well past the centre. ignore, an input such as ("key", K_RETURN), is
not taken until it has been let go. Returns "cancel" for Escape, or None when nothing came within
timeoutMs; the time starts again after each input.
"""
devices = controls.devices
deadline = devices.ticks() + timeoutMs
heldPad = None
heldModifier = None
while True:
remaining = deadline - devices.ticks()
if remaining <= 0:
return None
event = devices.wait(min(remaining, 50))
padState, _axisState = controls.read_pad()
keys = devices.key_state()
if ignore is not None:
if ignore[0] == "key":
if not controls._key_down(keys, ignore[1]):
ignore = None
elif padState.get(ignore[1], 0.0) < releaseThreshold:
ignore = None
eventType = getattr(event, "type", pygame.NOEVENT)
if eventType == pygame.QUIT:
pygame.event.post(event)
return "cancel"
if eventType == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return "cancel"
if ignore == ("key", event.key):
continue
deadline = devices.ticks() + timeoutMs
if event.key in modifierKeyCodes:
heldModifier = event.key
continue
mods = getattr(event, "mod", 0)
names = [name for name, mask in modifierMasks if mods & mask]
return Binding("+".join(names + [key_save_name(event.key)]), "keyboard")
if eventType == pygame.KEYUP and heldModifier is not None and event.key == heldModifier:
return Binding(key_save_name(event.key), "keyboard")
if eventType == pygame.CONTROLLERBUTTONDOWN:
name = padButtonNames.get(event.button)
if name is None or ignore == ("pad", name):
continue
deadline = devices.ticks() + timeoutMs
if heldPad is not None and heldPad != name:
return Binding(f"{heldPad}+{name}", "pad")
heldPad = name
continue
if eventType == pygame.CONTROLLERBUTTONUP and padButtonNames.get(event.button) == heldPad and heldPad:
return Binding(heldPad, "pad")
for name in list(padTriggers) + list(stickDirections):
if padState.get(name, 0.0) >= listenThreshold and ignore != ("pad", name) and name != heldPad:
return Binding(f"{heldPad}+{name}" if heldPad else name, "pad")
# The button's release can be missed; a held button that is no longer down counts as let go.
if heldPad is not None and padState.get(heldPad, 0.0) == 0.0:
return Binding(heldPad, "pad")
def _axis_from_direction(binding):
"""A stick direction pushed for an axis action becomes the whole axis, reversed if pushed the negative way."""
if binding.device != "pad" or binding.modifiers or binding.kind != "button":
return None
direction = stickDirections.get(binding.trigger[1])
if direction is None:
return None
axisName, sign = direction
return Binding(axisName if sign > 0 else f"-{axisName}", "pad")
class ControlsMenu:
"""The state of one visit to the controls menu."""
def __init__(self, sounds, controls, title):
self.sounds = sounds
self.controls = controls
self.speech = Speech.get_instance()
self.title = title
self.items = [("action", action.actionId, action.group) for action in controls.game_actions()]
self.items += [("rumble", None, "options"), ("strength", None, "options"), ("names", None, "options"),
("resetAll", None, "options"), ("back", None, None)]
self.index = 0
self.resetPending = False
def say(self, text):
# Said even if it was just said, since hearing the change is the point.
try:
self.speech.lastSpoken["text"] = None
except Exception:
pass
self.speech.speak(text)
def play(self, name):
try:
self.sounds[name].play()
except Exception:
pass
def group_title(self, group):
if group == "options":
return _("Controller options")
return self.controls.group_label(group)
def label(self, index=None):
kind, actionId, _group = self.items[self.index if index is None else index]
controls = self.controls
if kind == "action":
# Translators: an action and what it is bound to, such as "Horn: H, L1".
return _("{action}: {bindings}").format(action=controls.actions[actionId].label,
bindings=controls.describe(actionId))
if kind == "rumble":
return _("Rumble, {state}").format(state=_("on") if controls.rumbleEnabled else _("off"))
if kind == "strength":
return _("Rumble strength, {percent} percent").format(percent=controls.rumbleStrength)
if kind == "names":
scheme = _(buttonSchemeTitles[controls.buttonNames])
if controls.buttonNames == "auto":
scheme = _("{choice}, {scheme}").format(choice=scheme,
scheme=_(buttonSchemeTitles[controls.button_scheme()]))
return _("Button names, {scheme}").format(scheme=scheme)
if kind == "resetAll":
return _("Reset all controls")
return _("Back")
def announce_move(self, previousIndex):
group = self.items[self.index][2]
if group is not None and group != self.items[previousIndex][2]:
# Translators: a group of controls, then the control, such as "Driving. Horn: H, L1".
self.say(_("{group}. {item}").format(group=self.group_title(group), item=self.label()))
else:
self.say(self.label())
def run(self):
first = self.items[0][2]
opening = self.label()
if first is not None:
opening = _("{group}. {item}").format(group=self.group_title(first), item=opening)
self.say(_("{title}. {item}").format(title=self.title or _("Controls"), item=opening))
pygame.event.clear()
while True:
event = translate_event(pygame.event.wait())
if event.type == pygame.QUIT:
return
button = pad_button(event)
if event.type == pygame.CONTROLLERBUTTONDOWN:
# Buttons the library's menus do not use: square adds a binding, select resets one.
if button == "west":
self.on_action_key("add", event)
elif button == "select":
self.on_action_key("reset", event)
continue
if event.type != pygame.KEYDOWN:
continue
if is_language_reset(event):
self.say(reset_language())
continue
key = event.key
if key == pygame.K_ESCAPE:
return
if key in (pygame.K_UP, pygame.K_DOWN, pygame.K_HOME, pygame.K_END):
last = len(self.items) - 1
target = {pygame.K_UP: max(0, self.index - 1), pygame.K_DOWN: min(last, self.index + 1),
pygame.K_HOME: 0, pygame.K_END: last}[key]
if target != self.index:
previous = self.index
self.index = target
self.resetPending = False
self.play("menu-move")
self.announce_move(previous)
continue
kind = self.items[self.index][0]
if kind == "back" and key == pygame.K_RETURN:
self.play("menu-select")
return
if kind == "action":
if key == pygame.K_RETURN:
self.on_action_key("replace", event)
elif key == pygame.K_INSERT:
self.on_action_key("add", event)
elif key == pygame.K_DELETE or button == "north":
self.on_action_key("remove", event)
elif key == pygame.K_BACKSPACE:
self.on_action_key("reset", event)
elif kind in ("rumble", "strength", "names") and key in (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_RETURN):
self.change_option(kind, -1 if key == pygame.K_LEFT else 1)
elif kind == "resetAll" and key == pygame.K_RETURN:
if self.resetPending:
self.controls.reset_all()
self.resetPending = False
self.play("menu-select")
self.say(_("All controls reset to their defaults."))
else:
self.resetPending = True
self.say(_("Press Enter again to reset all controls."))
def change_option(self, kind, direction):
controls = self.controls
if kind == "rumble":
controls.rumbleEnabled = not controls.rumbleEnabled
elif kind == "strength":
controls.rumbleStrength = max(0, min(100, controls.rumbleStrength + direction * rumbleStrengthStep))
else:
index = buttonNameSchemes.index(controls.buttonNames)
controls.buttonNames = buttonNameSchemes[(index + direction) % len(buttonNameSchemes)]
controls.save()
self.play("menu-move")
self.say(self.label())
if kind in ("rumble", "strength"):
# Felt straight away, so the player knows what the setting does.
controls.rumble_pattern("thud")
def on_action_key(self, mode, event):
if self.items[self.index][0] != "action":
return
actionId = self.items[self.index][1]
if mode == "reset":
self.controls.reset_action(actionId)
self.play("menu-select")
self.say(_("Reset. {item}").format(item=self.label()))
return
message = self.rebind(actionId, mode, _starting_input(event))
# A stick still pushed, or a button still down, from listening must not also move the menu.
self.controls.ignore_held_inputs()
self.say(message)
def rebind(self, actionId, mode, ignore):
"""Listen and change one action's bindings. Returns what to say."""
controls = self.controls
action = controls.actions[actionId]
if mode == "remove":
self.say(_("Press the key or button to remove from {action}.").format(action=action.label))
elif action.axis:
self.say(_("{action}: push a stick to the {positive}, or press a key or button for {positive}.").format(
action=action.label, positive=action.positiveLabel))
else:
self.say(_("Press a key or button for {action}.").format(action=action.label))
captured = capture_input(controls, ignore)
if not isinstance(captured, Binding):
return _("Cancelled.")
if mode == "remove":
return self.remove_binding(actionId, captured)
binding = captured
if action.axis:
binding = _axis_from_direction(captured)
if binding is None:
self.say(_("Now {negative}.").format(negative=action.negativeLabel))
negative = capture_input(controls, ("pad", captured.trigger[1]) if captured.device == "pad"
else ("key", captured.trigger[1][0]))
if not isinstance(negative, Binding):
return _("Cancelled.")
if negative.device != captured.device or negative.kind != "button" or \
captured.kind != "button" or negative.modifiers != captured.modifiers:
return _("Both directions must be single inputs on the same device. Cancelled.")
held = captured.text.split("+")[:-1]
negativeName = negative.text.split("+")[-1]
positiveName = captured.text.split("+")[-1]
binding = Binding("+".join(held + [f"{negativeName}/{positiveName}"]), captured.device)
current = controls.bindings[(actionId, binding.device)]
if binding in current and mode == "add":
return _("{binding} is already set for {action}.").format(binding=controls.binding_name(binding),
action=action.label)
conflicts = controls.conflicts(actionId, binding)
if conflicts:
otherNames = ", ".join(controls.actions[otherId].label for otherId, _existing in conflicts)
self.say(_("{binding} is already {other}. Press it again to swap, or Escape to cancel.").format(
binding=controls.binding_name(binding), other=otherNames))
again = capture_input(controls)
if not isinstance(again, Binding) or not (again == binding or again.inputs() <= binding.inputs()):
return _("Cancelled.")
if mode == "replace":
newList = [binding]
displaced = [existing for existing in current if existing != binding]
else:
newList = current + [binding]
displaced = []
controls.bindings[(actionId, binding.device)] = newList
spoken = [self.label()]
for otherId, existing in conflicts:
otherList = [other for other in controls.bindings[(otherId, binding.device)] if other != existing]
# A swap: the other action takes what this one had on the device.
otherList += [moved for moved in displaced if moved not in otherList]
displaced = []
controls.bindings[(otherId, binding.device)] = otherList
spoken.append(_("{action}: {bindings}").format(action=controls.actions[otherId].label,
bindings=controls.describe(otherId)))
controls._rebuild()
controls.save()
self.play("menu-select")
return ". ".join(spoken)
def remove_binding(self, actionId, captured):
controls = self.controls
action = controls.actions[actionId]
current = controls.bindings[(actionId, captured.device)]
wanted = captured.inputs()
remaining = [binding for binding in current if binding != captured and not (binding.inputs() & wanted)]
if len(remaining) == len(current):
return _("{binding} is not set for {action}.").format(binding=controls.binding_name(captured),
action=action.label)
controls.bindings[(actionId, captured.device)] = remaining
controls._rebuild()
controls.save()
self.play("menu-select")
return _("Removed. {item}").format(item=self.label())
def controls_menu(sounds, controls=None, title=None):
"""A menu of the game's controls and controller options, for a game's options menu.
Up and Down move between the items, and Home and End to the first and last. On an action:
Enter listens for a new binding, which replaces that action's bindings on the same device
(keyboard or controller); Insert adds one instead; Delete listens for a binding to remove;
Backspace puts the action back to its defaults. On a controller, cross, square, triangle and
select do the same. Listening stops after five seconds with no input, or at Escape. A binding
already used by another action in the same group can be swapped by pressing it again. Left and
Right, or Enter, change rumble, rumble strength and the button names. Reset all controls needs
Enter twice. Escape, or Enter on Back, returns.
Args:
sounds (dict): The game's sounds, for menu-move and menu-select.
controls (Controls): The controls to change; the game's own if not given.
title (str): Said when the menu opens; "Controls" if not given.
"""
controls = controls if controls is not None else Controls.get_instance()
ControlsMenu(sounds, controls, title).run()