diff --git a/AI-README.md b/AI-README.md index a4337a3..3513c08 100644 --- a/AI-README.md +++ b/AI-README.md @@ -130,6 +130,24 @@ not read events itself, such as one waiting while a sound plays. It takes only Escape presses off the queue and leaves every other event for the game. In a loop that already reads `pygame.event.get()`, check for Escape there instead. +## Keyboard and controllers + +Many players use a game controller. Rather than checking keys in the game's +own loop, give each thing the player can do an `sg.Action` with default keys +and controller inputs, make `controls = sg.Controls([...])` once after +`initialize_gui`, call `controls.update(events)` each frame and ask +`controls.pressed("jump")`, `controls.held("jump")` or `controls.value("steer")`. +Controller inputs are named by position (`south`, `east`, `west`, `north`, +`l1`, `r2`, `dpadUp`, `leftStickX`...), and bindings are text such as +`"left/right"`, `"l1+west"` or `"-leftStickY"`. Put `sg.controls_menu(sounds, +controls)` in the game's options menu so players can rebind; it saves only +changes from the defaults. Use `controls.rumble(low, high, durationMs)` or +`controls.rumble_pattern("thud")` for hits and other events a player should +feel; both do nothing without a controller. Library menus already work with a +controller; a game's own menu loop gets the same by reading +`sg.translate_event(pygame.event.wait())`. README.md has the full binding format. +Keep the keyboard keys listed under "Your own event loop" working as well. + ## Speech - `sg.speak(text, interrupt=True)`: speak, cutting off what was being said. diff --git a/README.md b/README.md index 9d8fc1c..b6cc078 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,8 @@ The library is organized into modules, each with a specific focus: - **speech**: Text-to-speech functionality - **scoreboard**: High score tracking - **input**: Input handling and dialogs +- **controls**: Keyboard and game controller actions, rebinding and rumble +- **controls_menu**: The menu where players change their controls - **display**: Text display and GUI functionality - **menu**: Menu systems - **utils**: Utility functions and Game class @@ -674,6 +676,103 @@ name = sg.get_input("Enter your name:", "Player") ``` +### Keyboard and Controllers + +Games ask about actions, never keys. Each action gets default keys and +controller inputs, and players can change them in `controls_menu`. Make the +controls once, after `initialize_gui`, so the player's saved bindings are read: + +```python +controls = sg.Controls([ + sg.Action("accelerate", "Accelerate", "driving", keys=["up"], pad=["r2", "south"]), + sg.Action("steer", "Steer", "driving", keys=["left/right"], pad=["leftStickX", "dpadLeft/dpadRight"], + axis=True), + sg.Action("horn", "Horn", "driving", keys=["h"], pad=["l1"]), +], groupLabels={"driving": "Driving"}) + +while playing: + events = pygame.event.get() + controls.update(events) # once a frame, with the events the game took + if controls.pressed("horn"): # true only in the frame it went down + sounds["horn"].play() + throttle = controls.value("accelerate") # 0 to 1: a trigger gives how far it is pulled + steering = controls.value("steer") # -1 to 1, with the stick's dead zone taken out + if controls.held("accelerate"): + ... +``` + +Controller inputs are named by position, so a binding means the same button +on every controller: `south`, `east`, `west`, `north` (cross, circle, square +and triangle), `l1`, `r1`, `l2`, `r2`, `l3`, `r3`, `select`, `start`, +`guide`, `touchpad`, `dpadUp`, `dpadDown`, `dpadLeft`, `dpadRight`, the +stick axes `leftStickX`, `leftStickY`, `rightStickX`, `rightStickY`, and one +direction of a stick, such as `leftStickUp`. Keys use pygame's key names, +such as `h`, `space` or `page up`; `ctrl`, `shift` and `alt` mean either one. + +- `"l1+west"`, `"ctrl+s"`: hold the first, press the last. While L1 is held, + a plain `west` binding gives way to `l1+west`. L1 still does its own + action when pressed, so a button used to hold should usually have none. +- `"left/right"`, `"dpadLeft/dpadRight"`: a pair for an axis, negative first. +- `"leftStickX"`, `"-leftStickY"`: a whole stick axis; `-` reverses it, so + pushing up gives a positive value. + +Names are spoken in PlayStation terms unless an Xbox or Nintendo controller +is connected or the player chooses otherwise in the controls menu. + +**Library menus work with a controller without any change to the game.** +The d-pad and left stick are the arrow keys and repeat while held; cross is +Enter, circle Escape, triangle Space, L1 and R1 Page Up and Page Down, L2 +and R2 Home and End. These cannot be rebound, and neither can the arrow keys, +Enter and Escape, so nobody can lock themselves out of a menu. A game with its +own menu loop gets the same with `sg.translate_event(pygame.event.wait())`. +Text entry (`get_input`) stays keyboard only. `pause_game` also resumes on +start. "Controller connected" and "Controller disconnected" are spoken when a +controller is plugged in or out. + +**Rumble** tells a player things that sound cannot, so use it: + +```python +controls.rumble(0.8, 0.3, 200) # low motor, high motor (0 to 1), milliseconds +controls.rumble_pattern("thud") # tap, thud, buzz or crash; add your own to sg.rumblePatterns +``` + +Both do nothing without a controller, or when the player turned rumble off. +The player's strength setting scales them. + +**The controls menu.** Offer `sg.controls_menu(sounds, controls)` in the +game's options menu. It lists each action with its bindings, such as +"Horn: h, L1", grouped by group, then rumble, rumble strength, button names +and Reset all controls. On an action, Enter (cross) listens for a new +binding, which replaces that action's bindings on the same device; Insert +(square) adds one; Delete (triangle) removes the one pressed; Backspace +(select) puts the action back to its defaults. Listening stops at Escape or +after five seconds with nothing pressed. A binding already used by another +action in the same group can be swapped by pressing it again; different groups +may share inputs. Reset all controls needs Enter twice. + +Only bindings that differ from the game's defaults are saved, in the game's +`config.ini`, so a default added in a later version still reaches players who +changed other controls. They can be edited by hand: + +```ini +[keyboard] +horn = j, ctrl+h + +[controller] +horn = r1, l1+west +steer = rightStickX + +[controller options] +rumble = on +rumble strength = 70 +button names = auto +``` + +An empty value, `horn =`, leaves the action with no binding on that device. +The library's own menu actions are always there for games to ask about too: +`menuUp`, `menuDown`, `menuLeft`, `menuRight`, `confirm` and `back`. + + ### Sound Effects ```python diff --git a/__init__.py b/__init__.py index 6a7aef8..28e0ce8 100755 --- a/__init__.py +++ b/__init__.py @@ -63,6 +63,10 @@ from .menu import game_menu, instruction_menu, learn_sounds, instructions, credi # Import speech preferences and their menu from .speech_options import SpeechPreferences, speech_options_menu +# Import keyboard and controller actions, and the menu to change them +from .controls import Action, Controls, translate_event, translate_events, rumblePatterns +from .controls_menu import controls_menu + # Update imports to reference Scoreboard methods high_scores = Scoreboard.display_high_scores has_high_scores = Scoreboard.has_high_scores @@ -126,6 +130,9 @@ __all__ = [ 'SpeechPreferences', 'speech_options_menu', + # Controls + 'Action', 'Controls', 'translate_event', 'translate_events', 'rumblePatterns', 'controls_menu', + # Translations 'set_language', 'set_language_reset', 'language_code', 'translated_file', diff --git a/controls.py b/controls.py new file mode 100644 index 0000000..22a8e9e --- /dev/null +++ b/controls.py @@ -0,0 +1,1026 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Keyboard and game controller input through one layer of actions. + +A game names what the player can do, such as accelerate, steer or jump, and +gives each action default keys and controller inputs. It then asks about +actions, never keys: + + controls = Controls([ + Action("steer", "Steer", "driving", keys=["left/right"], pad=["leftStickX", "dpadLeft/dpadRight"], axis=True), + Action("horn", "Horn", "driving", keys=["h"], pad=["l1"]), + ]) + while playing: + events = pygame.event.get() + controls.update(events) + if controls.pressed("horn"): + ... + steering = controls.value("steer") + +Controller inputs are named by position, not by label, so a binding means the +same button on every controller: south, east, west and north for the four +face buttons, l1, r1, l2, r2, l3, r3, select, start, guide, touchpad, +dpadUp, dpadDown, dpadLeft, dpadRight, and the sticks as leftStickX, +leftStickY, rightStickX and rightStickY, or one direction of one, such as +leftStickUp. Names are spoken in PlayStation terms unless the controller or +the player's setting says otherwise. + +Bindings are written as text, which is also how they are saved: + +- "h", "page up", "space": one key; "ctrl", "shift" and "alt" are either one. +- "ctrl+s", "l1+west": hold the first, press the last. +- "left/right", "dpadLeft/dpadRight": a pair, for an axis, negative first. +- "leftStickX", "-leftStickY": a whole stick axis, the second reversed. + +Every library menu accepts the controller through translate_event: the d-pad +and left stick are the arrow keys, cross is Enter and circle is Escape. Those +menu controls are fixed, so a player can always find their way back. +""" + +import os +import time + +import pygame + +from .i18n import _, N_ + +# Face buttons by position on every controller. Without this SDL 2 swaps A and B, and X and Y, on Nintendo +# controllers to match their labels. It must be set before the controller subsystem starts. +os.environ.setdefault("SDL_GAMECONTROLLER_USE_BUTTON_LABELS", "0") + +padButtons = { + "south": pygame.CONTROLLER_BUTTON_A, + "east": pygame.CONTROLLER_BUTTON_B, + "west": pygame.CONTROLLER_BUTTON_X, + "north": pygame.CONTROLLER_BUTTON_Y, + "select": pygame.CONTROLLER_BUTTON_BACK, + "guide": pygame.CONTROLLER_BUTTON_GUIDE, + "start": pygame.CONTROLLER_BUTTON_START, + "l3": pygame.CONTROLLER_BUTTON_LEFTSTICK, + "r3": pygame.CONTROLLER_BUTTON_RIGHTSTICK, + "l1": pygame.CONTROLLER_BUTTON_LEFTSHOULDER, + "r1": pygame.CONTROLLER_BUTTON_RIGHTSHOULDER, + "dpadUp": pygame.CONTROLLER_BUTTON_DPAD_UP, + "dpadDown": pygame.CONTROLLER_BUTTON_DPAD_DOWN, + "dpadLeft": pygame.CONTROLLER_BUTTON_DPAD_LEFT, + "dpadRight": pygame.CONTROLLER_BUTTON_DPAD_RIGHT, + # SDL's misc button (share, capture or mic) and touchpad click have no pygame constants. + "misc": 15, + "touchpad": 20, +} +padButtonNames = {number: name for name, number in padButtons.items()} + +padAxes = { + "leftStickX": pygame.CONTROLLER_AXIS_LEFTX, + "leftStickY": pygame.CONTROLLER_AXIS_LEFTY, + "rightStickX": pygame.CONTROLLER_AXIS_RIGHTX, + "rightStickY": pygame.CONTROLLER_AXIS_RIGHTY, +} +padTriggers = {"l2": pygame.CONTROLLER_AXIS_TRIGGERLEFT, "r2": pygame.CONTROLLER_AXIS_TRIGGERRIGHT} + +# One direction of a stick: the axis it is on and the sign. SDL's y axes are positive downwards. +stickDirections = {} +for _stick in ("leftStick", "rightStick"): + stickDirections.update({ + f"{_stick}Left": (f"{_stick}X", -1), f"{_stick}Right": (f"{_stick}X", 1), + f"{_stick}Up": (f"{_stick}Y", -1), f"{_stick}Down": (f"{_stick}Y", 1), + }) + +# Every controller input that is on or off, or pressed some way: buttons, triggers and stick directions. +padInputNames = list(padButtons) + list(padTriggers) + list(stickDirections) +padNameLookup = {name.lower(): name for name in padInputNames + list(padAxes)} + +keyModifiers = { + "ctrl": (pygame.K_LCTRL, pygame.K_RCTRL), + "shift": (pygame.K_LSHIFT, pygame.K_RSHIFT), + "alt": (pygame.K_LALT, pygame.K_RALT), + "meta": (pygame.K_LMETA, pygame.K_RMETA), +} +modifierKeyCodes = {code for codes in keyModifiers.values() for code in codes} + +stickDeadzone = 0.2 +triggerDeadzone = 0.1 +# An analog input counts as held from pressThreshold until it falls below releaseThreshold, +# so a stick resting near the line does not flicker between the two. +pressThreshold = 0.5 +releaseThreshold = 0.3 +repeatDelayMs = 500 +repeatIntervalMs = 100 +repeatTickMs = 25 + +# The fixed controller inputs of every library menu, and the key each one stands for. +# Inputs marked True repeat while held, like a held key. +menuPadKeys = { + "dpadUp": (pygame.K_UP, True), "leftStickUp": (pygame.K_UP, True), + "dpadDown": (pygame.K_DOWN, True), "leftStickDown": (pygame.K_DOWN, True), + "dpadLeft": (pygame.K_LEFT, True), "leftStickLeft": (pygame.K_LEFT, True), + "dpadRight": (pygame.K_RIGHT, True), "leftStickRight": (pygame.K_RIGHT, True), + "south": (pygame.K_RETURN, False), + "east": (pygame.K_ESCAPE, False), + "north": (pygame.K_SPACE, False), + "l1": (pygame.K_PAGEUP, True), + "r1": (pygame.K_PAGEDOWN, True), + "l2": (pygame.K_HOME, False), + "r2": (pygame.K_END, False), +} + +rumblePatterns = { + "tap": (0.0, 0.5, 80), + "thud": (0.9, 0.2, 180), + "buzz": (0.4, 0.6, 400), + "crash": (1.0, 1.0, 600), +} + +buttonNameSchemes = ("auto", "playstation", "xbox", "nintendo") +buttonSchemeTitles = { + "auto": N_("automatic"), + "playstation": N_("PlayStation"), + "xbox": N_("Xbox"), + "nintendo": N_("Nintendo"), +} + +# Spoken names of controller inputs. Each scheme overrides the shared names it labels differently. +sharedPadNames = { + "dpadUp": N_("d-pad up"), "dpadDown": N_("d-pad down"), + "dpadLeft": N_("d-pad left"), "dpadRight": N_("d-pad right"), + "leftStickUp": N_("left stick up"), "leftStickDown": N_("left stick down"), + "leftStickLeft": N_("left stick left"), "leftStickRight": N_("left stick right"), + "rightStickUp": N_("right stick up"), "rightStickDown": N_("right stick down"), + "rightStickLeft": N_("right stick left"), "rightStickRight": N_("right stick right"), + "leftStickX": N_("left stick left and right"), "leftStickY": N_("left stick up and down"), + "rightStickX": N_("right stick left and right"), "rightStickY": N_("right stick up and down"), + "touchpad": N_("touchpad"), + "misc": N_("misc button"), +} +schemePadNames = { + "playstation": { + "south": N_("cross"), "east": N_("circle"), "west": N_("square"), "north": N_("triangle"), + "l1": N_("L1"), "r1": N_("R1"), "l2": N_("L2"), "r2": N_("R2"), "l3": N_("L3"), "r3": N_("R3"), + "select": N_("share"), "start": N_("options"), "guide": N_("PS button"), "misc": N_("mute button"), + }, + "xbox": { + "south": N_("A"), "east": N_("B"), "west": N_("X"), "north": N_("Y"), + "l1": N_("LB"), "r1": N_("RB"), "l2": N_("LT"), "r2": N_("RT"), + "l3": N_("left stick click"), "r3": N_("right stick click"), + "select": N_("view"), "start": N_("menu"), "guide": N_("Xbox button"), "misc": N_("share"), + }, + "nintendo": { + "south": N_("B"), "east": N_("A"), "west": N_("Y"), "north": N_("X"), + "l1": N_("L"), "r1": N_("R"), "l2": N_("ZL"), "r2": N_("ZR"), + "l3": N_("left stick click"), "r3": N_("right stick click"), + "select": N_("minus"), "start": N_("plus"), "guide": N_("home"), "misc": N_("capture"), + }, +} + +# Saved key names that would clash with the binding separators or configparser get their own words. +keySaveNames = { + pygame.K_COMMA: "comma", pygame.K_PLUS: "plus", pygame.K_SLASH: "slash", pygame.K_PERCENT: "percent", + pygame.K_KP_PLUS: "keypad plus", pygame.K_KP_DIVIDE: "keypad slash", pygame.K_KP_ENTER: "keypad enter", + pygame.K_RETURN: "return", +} +# Spoken key names that read better than pygame's. +keySpokenNames = { + "return": N_("enter"), "up": N_("up arrow"), "down": N_("down arrow"), + "left": N_("left arrow"), "right": N_("right arrow"), "space": N_("space"), + "escape": N_("escape"), "backspace": N_("backspace"), "tab": N_("tab"), + "ctrl": N_("control"), "shift": N_("shift"), "alt": N_("alt"), "meta": N_("meta"), + "left ctrl": N_("left control"), "right ctrl": N_("right control"), +} + + +def _report(message): + """Print a problem for whoever runs the game from a terminal.""" + print(f"{message} [{time.ctime()}]") + + +def key_save_name(keyCode): + """The name a key is saved under, such as "page up", "h" or "comma".""" + if keyCode in keySaveNames: + return keySaveNames[keyCode] + name = pygame.key.name(keyCode) + if name.startswith("[") and name.endswith("]") and len(name) > 2: + name = f"keypad {name[1:-1]}" + if not name or name == "unknown key" or any(character in name for character in ",+/%"): + return f"key{keyCode}" + return name + + +_keyCodesByName = None + + +def key_code_for(name): + """The key code saved as name, or None if no key has it.""" + global _keyCodesByName + if _keyCodesByName is None: + _keyCodesByName = {} + for attribute in dir(pygame): + if attribute.startswith("K_"): + code = getattr(pygame, attribute) + _keyCodesByName.setdefault(key_save_name(code), code) + name = name.strip().lower() + if name in _keyCodesByName: + return _keyCodesByName[name] + if name.startswith("key") and name[3:].isdigit(): + return int(name[3:]) + return None + + +class Binding: + """One way to trigger an action, parsed from text such as "l1+west" or "left/right". + + device is "keyboard" or "pad". kind is "button" for one input, "pair" for a negative and a + positive input, or "axis" for a whole stick axis. modifiers must be held for it to count. + Inputs are ("key", keyCodes) or ("pad", name); a whole axis is ("axis", name). + """ + + def __init__(self, text, device): + self.device = device + self.text = text.strip() + self.inverted = False + body = self.text + parts = body.split("+") + # A trailing "+" is the plus key, written "plus", so any empty part is a mistake. + if any(not part.strip() for part in parts): + raise ValueError(f"empty part in {text!r}") + self.modifiers = tuple(self._parse_input(part, allowAxis=False) for part in parts[:-1]) + last = parts[-1].strip() + if "/" in last: + negative, _slash, positive = last.partition("/") + self.kind = "pair" + self.negative = self._parse_input(negative, allowAxis=False) + self.positive = self._parse_input(positive, allowAxis=False) + self.trigger = None + else: + if device == "pad" and last.startswith("-"): + self.inverted = True + last = last[1:] + self.trigger = self._parse_input(last, allowAxis=True) + self.kind = "axis" if self.trigger[0] == "axis" else "button" + if self.inverted and self.kind != "axis": + raise ValueError(f"only a whole axis can be reversed: {text!r}") + self.negative = self.positive = None + + def _parse_input(self, text, allowAxis): + text = text.strip() + if self.device == "keyboard": + if text.lower() in keyModifiers: + return ("key", keyModifiers[text.lower()]) + code = key_code_for(text) + if code is None: + raise ValueError(f"unknown key {text!r}") + return ("key", (code,)) + name = padNameLookup.get(text.lower()) + if name is None: + raise ValueError(f"unknown controller input {text!r}") + if name in padAxes: + if not allowAxis: + raise ValueError(f"a whole axis cannot be part of a pair or held: {text!r}") + return ("axis", name) + return ("pad", name) + + def inputs(self): + """The inputs this binding reacts to, each with the modifiers, for finding clashes.""" + if self.kind == "pair": + triggers = [self.negative, self.positive] + elif self.kind == "axis": + axisName = self.trigger[1] + triggers = [("pad", name) for name, (axis, _sign) in stickDirections.items() if axis == axisName] + else: + triggers = [self.trigger] + return {(self.modifiers, trigger) for trigger in triggers} + + def __eq__(self, other): + return isinstance(other, Binding) and (self.device, self.text.lower()) == (other.device, other.text.lower()) + + def __hash__(self): + return hash((self.device, self.text.lower())) + + def __repr__(self): + return f"Binding({self.text!r}, {self.device!r})" + + +def parse_bindings(texts, device): + """Bindings from a list of texts, or one comma-separated text, skipping and reporting bad ones.""" + if isinstance(texts, str): + texts = [part for part in texts.split(",") if part.strip()] + bindings = [] + for text in texts: + try: + binding = Binding(text, device) + except ValueError as error: + _report(f"Ignoring {device} binding {text!r}: {error}") + continue + if binding not in bindings: + bindings.append(binding) + return bindings + + +class Action: + """Something the player can do, with its default keys and controller inputs. + + Args: + actionId (str): What the game asks about, such as "horn". + label (str or function): What the controls menu says for it; a function is asked each time, + so a translated label follows a change of language. Defaults to actionId. + group (str): Actions in one group may not share an input; different groups may. + keys (list): Default keyboard bindings, such as ["h"] or ["left/right"]. + pad (list): Default controller bindings, such as ["l1", "west"] or ["leftStickX"]. + axis (bool): True for an action that goes both ways, such as steering, so the controls menu + asks for a stick or for a pair of inputs. + negativeLabel, positiveLabel (str): What the two directions of an axis are called; "left" and "right". + """ + + def __init__(self, actionId, label=None, group="game", keys=(), pad=(), axis=False, + negativeLabel=None, positiveLabel=None, fixed=False): + self.actionId = actionId + self._label = label + self.group = group + self.keys = list(keys) + self.pad = list(pad) + self.axis = axis + self._negativeLabel = negativeLabel + self._positiveLabel = positiveLabel + self.fixed = fixed + + @staticmethod + def _text(value, fallback): + if callable(value): + value = value() + return value if value else fallback + + @property + def label(self): + return self._text(self._label, self.actionId) + + @property + def negativeLabel(self): + return self._text(self._negativeLabel, _("left")) + + @property + def positiveLabel(self): + return self._text(self._positiveLabel, _("right")) + + def defaults(self, device): + return list(self.keys if device == "keyboard" else self.pad) + + +# The library's own menu actions. They cannot be rebound, so every menu always works. +menuActions = [ + Action("menuUp", N_("Menu up"), "menu", keys=["up"], pad=["dpadUp", "leftStickUp"], fixed=True), + Action("menuDown", N_("Menu down"), "menu", keys=["down"], pad=["dpadDown", "leftStickDown"], fixed=True), + Action("menuLeft", N_("Menu left"), "menu", keys=["left"], pad=["dpadLeft", "leftStickLeft"], fixed=True), + Action("menuRight", N_("Menu right"), "menu", keys=["right"], pad=["dpadRight", "leftStickRight"], fixed=True), + Action("confirm", N_("Confirm"), "menu", keys=["return", "keypad enter"], pad=["south"], fixed=True), + Action("back", N_("Back"), "menu", keys=["escape"], pad=["east"], fixed=True), +] + + +def controller_scheme(name): + """Which button names suit a controller, from the name SDL gives it.""" + lowered = (name or "").lower() + if any(word in lowered for word in ("xbox", "x-box", "xinput", "microsoft")): + return "xbox" + if any(word in lowered for word in ("nintendo", "switch", "joy-con", "joycon", "pro controller")): + return "nintendo" + return "playstation" + + +class PygameDevices: + """The real keyboard and controllers, through pygame and SDL's game controller API. + + Controls talks to the hardware only through this, so tests can give it a fake. + """ + + def __init__(self): + self.started = False + self.pads = {} + self.joystickCount = -1 + self.repeatEvent = None + + def start(self): + """Start the controller subsystem once pygame is running. Returns True when started.""" + if self.started: + return True + if not pygame.get_init(): + return False + try: + from pygame._sdl2 import controller + controller.init() + self.controllerModule = controller + self.repeatEvent = pygame.event.custom_type() + self.started = True + except Exception as error: + _report(f"Game controllers are unavailable: {error}") + self.started = False + return False + return True + + def check(self): + """Open new controllers and forget removed ones. Returns (added names, removed names).""" + if not self.started: + return [], [] + try: + count = pygame.joystick.get_count() + except pygame.error: + return [], [] + removed = [] + for instanceId, pad in list(self.pads.items()): + try: + attached = pad.attached() + except Exception: + attached = False + if not attached: + removed.append(getattr(pad, "name", "")) + del self.pads[instanceId] + added = [] + if count != self.joystickCount or removed: + self.joystickCount = count + for index in range(count): + try: + if not self.controllerModule.is_controller(index): + continue + instanceId = pygame.joystick.Joystick(index).get_instance_id() + if instanceId in self.pads: + continue + pad = self.controllerModule.Controller(index) + self.pads[instanceId] = pad + added.append(pad.name) + except Exception as error: + _report(f"Could not open controller {index}: {error}") + return added, removed + + def controllers(self): + return list(self.pads.values()) + + def key_state(self): + try: + return pygame.key.get_pressed() + except pygame.error: + return {} + + def ticks(self): + return pygame.time.get_ticks() + + def set_repeat_timer(self, running): + """Ask for one repeat tick soon, or stop. Each tick is asked for again while a menu input is held, + so the ticks stop by themselves once nothing reads them.""" + if self.repeatEvent is not None: + pygame.time.set_timer(self.repeatEvent, repeatTickMs if running else 0, 1 if running else 0) + + def wait(self, timeoutMs): + return pygame.event.wait(timeoutMs) + + +_sharedDevices = None + + +def shared_devices(): + global _sharedDevices + if _sharedDevices is None: + _sharedDevices = PygameDevices() + return _sharedDevices + + +def _default_config(): + from .services import ConfigService + return ConfigService.get_instance() + + +def _default_speak(text): + from .speech import speak + speak(text) + + +class Controls: + """The player's actions, from the keyboard and any connected controller. + + Making one makes it the game's controls, which library menus and controls_menu use. + Make it after initialize_gui, so the player's saved bindings can be read. + + Args: + actions (list): The game's Actions. The library's menu actions are always added. + config: Where bindings are saved, anything with localConfig (a ConfigParser) and + write_local_config(), such as ConfigService or Config. Defaults to the game's config.ini. + groupLabels (dict or function): What the controls menu says for each group; a group without + one is spoken with underscores read as spaces. + speak (function): Says hot-plug messages; defaults to the library's speak. + devices: The hardware; tests pass a fake. + """ + + _instance = None + keyboardSection = "keyboard" + padSection = "controller" + optionsSection = "controller options" + + @classmethod + def get_instance(cls): + """The game's controls, or controls with only the menu actions if the game made none.""" + if cls._instance is None: + cls() + return cls._instance + + def __init__(self, actions=(), config=None, groupLabels=None, speak=None, devices=None): + self.devices = devices if devices is not None else shared_devices() + self._config = config + self.groupLabels = groupLabels + self.speak = speak if speak is not None else _default_speak + self.actions = {} + for action in list(menuActions) + list(actions): + if action.actionId in self.actions: + raise ValueError(f"two actions are called {action.actionId!r}") + self.actions[action.actionId] = action + self.rumbleEnabled = True + self.rumbleStrength = 100 + self.buttonNames = "auto" + self.bindings = {} + for action in self.actions.values(): + for device in ("keyboard", "pad"): + self.bindings[(action.actionId, device)] = parse_bindings(action.defaults(device), device) + self._load() + self._rebuild() + self._held = set() + self._pressed = set() + self._padState = {} + self._axisState = {} + self._keyState = {} + self._previousAxes = {} + self._menuHeld = {} + self._repeatRunning = False + Controls._instance = self + + # Saved settings + + @property + def config(self): + if self._config is None: + self._config = _default_config() + return self._config + + def _load(self): + try: + parser = self.config.localConfig + except Exception as error: + _report(f"Could not read control settings: {error}") + return + byLowerId = {actionId.lower(): action for actionId, action in self.actions.items() if not action.fixed} + for device, section in (("keyboard", self.keyboardSection), ("pad", self.padSection)): + if not parser.has_section(section): + continue + for option, value in parser.items(section, raw=True): + action = byLowerId.get(option.lower()) + if action is None: + continue + self.bindings[(action.actionId, device)] = parse_bindings(value, device) + if parser.has_section(self.optionsSection): + section = self.optionsSection + try: + self.rumbleEnabled = parser.getboolean(section, "rumble", fallback=True) + self.rumbleStrength = max(0, min(100, parser.getint(section, "rumble strength", fallback=100))) + except ValueError as error: + _report(f"Ignoring a bad rumble setting: {error}") + names = parser.get(section, "button names", fallback="auto", raw=True).strip().lower() + self.buttonNames = names if names in buttonNameSchemes else "auto" + + def save(self): + """Save the bindings that differ from the game's defaults, and the controller options.""" + try: + parser = self.config.localConfig + for device, section in (("keyboard", self.keyboardSection), ("pad", self.padSection)): + if not parser.has_section(section): + parser.add_section(section) + for action in self.game_actions(): + current = self.bindings[(action.actionId, device)] + if current == parse_bindings(action.defaults(device), device): + parser.remove_option(section, action.actionId) + else: + parser.set(section, action.actionId, ", ".join(binding.text for binding in current)) + if not parser.items(section, raw=True): + parser.remove_section(section) + if not parser.has_section(self.optionsSection): + parser.add_section(self.optionsSection) + parser.set(self.optionsSection, "rumble", "on" if self.rumbleEnabled else "off") + parser.set(self.optionsSection, "rumble strength", str(self.rumbleStrength)) + parser.set(self.optionsSection, "button names", self.buttonNames) + self.config.write_local_config() + except Exception as error: + _report(f"Could not save control settings: {error}") + + # Bindings + + def game_actions(self): + """The actions a player can rebind, in the order the game gave them.""" + return [action for action in self.actions.values() if not action.fixed] + + def get_bindings(self, actionId, device): + """The bindings of one action on "keyboard" or "pad", as text.""" + return [binding.text for binding in self.bindings[(actionId, device)]] + + def set_bindings(self, actionId, device, texts, save=True): + """Replace the bindings of one action on one device. Fixed menu actions cannot change.""" + if self.actions[actionId].fixed: + raise ValueError(f"{actionId} cannot be rebound") + self.bindings[(actionId, device)] = parse_bindings(texts, device) + self._rebuild() + if save: + self.save() + + def reset_action(self, actionId, save=True): + action = self.actions[actionId] + for device in ("keyboard", "pad"): + self.bindings[(actionId, device)] = parse_bindings(action.defaults(device), device) + self._rebuild() + if save: + self.save() + + def reset_all(self): + for action in self.game_actions(): + self.reset_action(action.actionId, save=False) + self.save() + + def conflicts(self, actionId, binding): + """Other actions in the same group with a binding that shares an input with binding.""" + group = self.actions[actionId].group + wanted = binding.inputs() + found = [] + for other in self.game_actions(): + if other.actionId == actionId or other.group != group: + continue + for existing in self.bindings[(other.actionId, binding.device)]: + if existing.inputs() & wanted: + found.append((other.actionId, existing)) + return found + + def _rebuild(self): + """Work out which inputs to watch, and which held inputs change a plain binding into another.""" + self._watchedKeys = set() + self._chordTriggers = {} + for (actionId, device), bindings in self.bindings.items(): + for binding in bindings: + for modifiers, trigger in binding.inputs(): + for item in modifiers + (trigger,): + if item[0] == "key": + self._watchedKeys.add(item) + if modifiers: + self._chordTriggers.setdefault(trigger, set()).add(modifiers) + + # Hardware + + def start(self): + """Start listening to controllers. initialize_gui calls this; games need not.""" + if self.devices.start(): + # Controllers plugged in before the game started are not announced; only later changes are. + self.devices.check() + + def connected(self): + """True when at least one controller is connected.""" + return bool(self.devices.controllers()) + + def controller_names(self): + return [getattr(pad, "name", "") for pad in self.devices.controllers()] + + def _check_devices(self): + if not getattr(self.devices, "started", True) and not self.devices.start(): + return + added, removed = self.devices.check() + for _name in removed: + self.speak(_("Controller disconnected")) + for _name in added: + self.speak(_("Controller connected")) + + def read_pad(self): + """Every controller input now, without changing what this frame's held and pressed say. + + Returns ({input name: 0 to 1}, {axis name: -1 to 1}), with dead zones taken out. + """ + padState, axisState, _keyState = self._poll() + return padState, axisState + + def _poll(self): + """Read every controller input and the watched keys now.""" + pads = self.devices.controllers() + padState = {} + axisState = {} + for name, number in padButtons.items(): + padState[name] = 1.0 if any(self._safe(pad.get_button, number) for pad in pads) else 0.0 + for name, number in padTriggers.items(): + padState[name] = max([deadzone(self._safe(pad.get_axis, number) / 32767, triggerDeadzone) + for pad in pads] or [0.0]) + for name, number in padAxes.items(): + values = [deadzone(self._safe(pad.get_axis, number) / 32767, stickDeadzone) for pad in pads] + axisState[name] = max(values, key=abs) if values else 0.0 + for name, (axisName, sign) in stickDirections.items(): + padState[name] = max(0.0, axisState[axisName] * sign) + keys = self.devices.key_state() + keyState = {} + for item in self._watchedKeys: + keyState[item] = 1.0 if any(self._key_down(keys, code) for code in item[1]) else 0.0 + return padState, axisState, keyState + + @staticmethod + def _safe(method, number): + try: + return method(number) or 0 + except Exception: + return 0 + + @staticmethod + def _key_down(keys, code): + try: + return bool(keys[code]) + except (IndexError, KeyError, TypeError): + return False + + def _magnitude(self, item): + if item[0] == "key": + return self._keyState.get(item, 0.0) + return self._padState.get(item[1], 0.0) + + # Game frames + + def update(self, events=()): + """Read input for one frame. Call it once a frame with the events the game took from pygame. + + pressed() is then true for inputs that went down since the last update, held() for inputs + that are down now, and value() gives how far each action is pushed. + """ + self._check_devices() + if self._repeatRunning: + self.devices.set_repeat_timer(False) + self._repeatRunning = False + previousHeld = self._held + downEvents = set() + for event in events: + eventType = getattr(event, "type", None) + if eventType == pygame.KEYDOWN and not getattr(event, "controller", False): + for item in self._watchedKeys: + if event.key in item[1]: + downEvents.add(item) + elif eventType == pygame.CONTROLLERBUTTONDOWN: + name = padButtonNames.get(getattr(event, "button", None)) + if name: + downEvents.add(("pad", name)) + self._padState, axisState, self._keyState = self._poll() + self._previousAxes = self._axisState + self._axisState = axisState + held = set() + for item, value in [(("pad", name), value) for name, value in self._padState.items()] + \ + list(self._keyState.items()): + threshold = releaseThreshold if item in previousHeld else pressThreshold + if value >= threshold and value > 0: + held.add(item) + # A tap between two frames still counts, as held for this frame. + for item in downEvents: + held.add(item) + if item[0] == "key": + self._keyState[item] = 1.0 + else: + self._padState[item[1]] = max(self._padState.get(item[1], 0.0), 1.0) + # A key down while it was already held is the key repeating, not a new press. + self._pressed = {item for item in held if item not in previousHeld} + self._held = held + self._menuHeld = {name: True for name in menuPadKeys if ("pad", name) in held} + + def _modifiers_held(self, binding): + return all(item in self._held for item in binding.modifiers) + + def _suppressed(self, binding, trigger): + """A plain binding gives way to a binding of the same input with modifiers that are held.""" + if binding.modifiers: + return False + return any(all(item in self._held for item in modifiers) for modifiers in self._chordTriggers.get(trigger, ())) + + def _binding_state(self, binding): + """(held, pressed, value) for one binding this frame.""" + if not self._modifiers_held(binding): + return False, False, 0.0 + if binding.kind == "axis": + sign = -1 if binding.inverted else 1 + value = self._axisState.get(binding.trigger[1], 0.0) * sign + previous = abs(self._previousAxes.get(binding.trigger[1], 0.0)) + return abs(value) >= pressThreshold, abs(value) >= pressThreshold > previous, value + if binding.kind == "pair": + states = {} + for item in (binding.negative, binding.positive): + live = not self._suppressed(binding, item) + states[item] = (live and item in self._held, live and item in self._pressed, + self._magnitude(item) if live else 0.0) + negative, positive = states[binding.negative], states[binding.positive] + return (negative[0] or positive[0], negative[1] or positive[1], positive[2] - negative[2]) + if self._suppressed(binding, binding.trigger): + return False, False, 0.0 + return (binding.trigger in self._held, binding.trigger in self._pressed, self._magnitude(binding.trigger)) + + def _states(self, actionId): + if actionId not in self.actions: + raise KeyError(f"no action called {actionId!r}") + return [self._binding_state(binding) for device in ("keyboard", "pad") + for binding in self.bindings[(actionId, device)]] + + def held(self, actionId): + """True while any input of the action is down.""" + return any(state[0] for state in self._states(actionId)) + + def pressed(self, actionId): + """True only in the frame an input of the action went down.""" + return any(state[1] for state in self._states(actionId)) + + def value(self, actionId): + """How far the action is pushed, -1.0 to 1.0, with the dead zone taken out. Buttons give 0 or 1.""" + values = [state[2] for state in self._states(actionId)] + return max(values, key=abs) if values else 0.0 + + # Rumble + + def rumble(self, low, high, durationMs): + """Shake every connected controller: low and high are motor strengths from 0 to 1. + + Does nothing without a controller, or when the player turned rumble off. The player's + strength setting scales both motors. + """ + if not self.rumbleEnabled or self.rumbleStrength <= 0: + return False + scale = self.rumbleStrength / 100 + played = False + for pad in self.devices.controllers(): + try: + played = bool(pad.rumble(min(1.0, low * scale), min(1.0, high * scale), int(durationMs))) or played + except Exception as error: + _report(f"Rumble failed: {error}") + return played + + def rumble_pattern(self, name): + """Play a named rumble from rumblePatterns: "tap", "thud", "buzz" or "crash", or one a game adds.""" + return self.rumble(*rumblePatterns[name]) + + # Names + + def button_scheme(self): + """The button names in use: the player's choice, or the connected controller's kind.""" + if self.buttonNames != "auto": + return self.buttonNames + names = self.controller_names() + return controller_scheme(names[0]) if names else "playstation" + + def input_name(self, item): + """The spoken name of one input.""" + kind, value = item + if kind == "key": + for modifier, codes in keyModifiers.items(): + if value == codes: + return _(keySpokenNames[modifier]) + name = key_save_name(value[0]) + return _(keySpokenNames[name]) if name in keySpokenNames else name + scheme = self.button_scheme() + if scheme == "playstation" and value == "select" and \ + any(word in name.lower() for name in self.controller_names() for word in ("dualsense", "ps5")): + return _("create") + spoken = schemePadNames.get(scheme, {}).get(value) or sharedPadNames.get(value) or value + return _(spoken) + + def binding_name(self, binding): + """The spoken name of a binding, such as "L1 plus square" or "left stick left and right, reversed".""" + if binding.kind == "pair": + # Translators: the two inputs of a pair, such as "left arrow and right arrow". + name = _("{negative} and {positive}").format(negative=self.input_name(binding.negative), + positive=self.input_name(binding.positive)) + elif binding.kind == "axis": + name = self.input_name(binding.trigger) + if binding.inverted: + name = _("{input}, reversed").format(input=name) + else: + name = self.input_name(binding.trigger) + for modifier in reversed(binding.modifiers): + # Translators: hold one input and press another, such as "L1 plus square". + name = _("{held} plus {pressed}").format(held=self.input_name(modifier), pressed=name) + return name + + def describe(self, actionId): + """The action's bindings as spoken: keyboard first, then controller, or "not set".""" + names = [self.binding_name(binding) for device in ("keyboard", "pad") + for binding in self.bindings[(actionId, device)]] + return ", ".join(names) if names else _("not set") + + def group_label(self, group): + label = None + if callable(self.groupLabels): + label = self.groupLabels(group) + elif self.groupLabels: + label = self.groupLabels.get(group) + return label if label else group.replace("_", " ") + + # Library menus + + def translate_event(self, event): + """The event a library menu should act on: controller menu input becomes the matching key. + + The d-pad and left stick become the arrow keys, repeating while held; cross (south) becomes + Enter, circle (east) Escape, triangle (north) Space, L1 and R1 Page Up and Page Down, and + L2 and R2 Home and End. The key event made has button set to the input's position name and + controller set to True. Stick movement and repeat ticks that make no key come back as + NOEVENT; every other event, other controller buttons among them, comes back unchanged. + """ + self._check_devices() + eventType = getattr(event, "type", None) + repeatEvent = getattr(self.devices, "repeatEvent", None) + controllerEvents = (pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP, pygame.CONTROLLERAXISMOTION) + if eventType not in controllerEvents and (repeatEvent is None or eventType != repeatEvent): + return event + pressedButton = None + if eventType == pygame.CONTROLLERBUTTONDOWN: + pressedButton = padButtonNames.get(getattr(event, "button", None)) + self._padState, self._axisState, self._keyState = self._poll() + now = self.devices.ticks() + produced = None + stillHeld = {} + for name, (key, repeats) in menuPadKeys.items(): + value = self._padState.get(name, 0.0) + wasHeld = name in self._menuHeld + isHeld = value >= (releaseThreshold if wasHeld else pressThreshold) and value > 0 + if name == pressedButton: + if produced is None: + produced = (key, name) + stillHeld[name] = now + repeatDelayMs + continue + if isHeld and not wasHeld: + if produced is None: + produced = (key, name) + stillHeld[name] = now + repeatDelayMs + elif isHeld: + nextRepeat = self._menuHeld[name] + if repeats and nextRepeat is not True and now >= nextRepeat: + if produced is None: + produced = (key, name) + nextRepeat = now + repeatIntervalMs + stillHeld[name] = nextRepeat + self._menuHeld = stillHeld + # The game's next frame must not take an input held over from the menu for a new press. + self._held = {("pad", name) for name, value in self._padState.items() if value >= pressThreshold} + self._held |= {item for item, value in self._keyState.items() if value} + self._pressed = set() + needRepeat = any(menuPadKeys[name][1] for name in stillHeld) + if needRepeat or self._repeatRunning: + self.devices.set_repeat_timer(needRepeat) + self._repeatRunning = needRepeat + if produced is None: + if eventType in (pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP): + return event + return pygame.event.Event(pygame.NOEVENT) + key, name = produced + return pygame.event.Event(pygame.KEYDOWN, key=key, mod=0, unicode="", scancode=0, + button=name, controller=True) + + def ignore_held_inputs(self): + """Treat every controller input down now as already handled, by menus and by the next frame. + + For after listening for a binding, so a stick still pushed does not also move the menu. + """ + self._padState, self._axisState, self._keyState = self._poll() + self._menuHeld = {name: True for name in menuPadKeys if self._padState.get(name, 0.0) >= releaseThreshold} + self._held = {("pad", name) for name, value in self._padState.items() if value >= releaseThreshold} + self._held |= {item for item, value in self._keyState.items() if value} + self._pressed = set() + + def translate_events(self, events): + """translate_event for each of a list of events, leaving out what made nothing.""" + translated = (self.translate_event(event) for event in events) + return [event for event in translated if event.type != pygame.NOEVENT] + + +def deadzone(value, zone): + """value with the dead zone taken out and the rest stretched back to the full range.""" + value = max(-1.0, min(1.0, value)) + if abs(value) < zone: + return 0.0 + return (abs(value) - zone) / (1 - zone) * (1 if value > 0 else -1) + + +_controllerEventTypes = { + pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP, pygame.CONTROLLERAXISMOTION, + pygame.CONTROLLERDEVICEADDED, pygame.CONTROLLERDEVICEREMOVED, pygame.JOYDEVICEADDED, pygame.JOYDEVICEREMOVED, +} + + +def translate_event(event): + """Controls.translate_event on the game's controls. + + Before anything has made the game's controls, which initialize_gui does, a keyboard event + comes back as it is, without starting the controls. + """ + if Controls._instance is None and getattr(event, "type", None) not in _controllerEventTypes: + return event + return Controls.get_instance().translate_event(event) + + +def translate_events(events): + """translate_event for each of a list of events, leaving out what made nothing.""" + translated = (translate_event(event) for event in events) + return [event for event in translated if event.type != pygame.NOEVENT] + + +def pad_button(event): + """The position name of the controller button an event is about, or None.""" + if getattr(event, "button", None) in padButtons: + return event.button + if getattr(event, "type", None) in (pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP): + return padButtonNames.get(event.button) + return None diff --git a/controls_menu.py b/controls_menu.py new file mode 100644 index 0000000..ef5e8dd --- /dev/null +++ b/controls_menu.py @@ -0,0 +1,373 @@ +#!/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() + diff --git a/display.py b/display.py index d69bb3c..0478f1c 100644 --- a/display.py +++ b/display.py @@ -18,6 +18,7 @@ from setproctitle import setproctitle from .speech import Speech from .i18n import _ from .services import PathService, VolumeService +from .controls import Controls, translate_event # Keep track of the instructions for navigating display_text has been shown displayTextUsageInstructions = False @@ -54,6 +55,9 @@ def initialize_gui(gameTitle): # Enable key repeat for volume controls pygame.key.set_repeat(500, 100) + # Listen to game controllers, so every menu works with one + Controls.get_instance().start() + # Load sound files recursively including subdirectories soundData = {} try: @@ -188,7 +192,7 @@ def display_text(text, keyHandler=None): pygame.event.clear() while True: - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.KEYDOWN: # Check for Alt modifier mods = event.mod diff --git a/input.py b/input.py index ae33d12..193b6d9 100644 --- a/input.py +++ b/input.py @@ -11,6 +11,7 @@ Provides functionality for: import pygame import time from .speech import speak +from .controls import Controls, pad_button, translate_event from .i18n import _, ngettext, N_ # Translators: names of symbols, spoken as they are typed, since speech often skips punctuation. @@ -201,8 +202,14 @@ def character_name(character): def pause_game(): - """Pauses the game until user presses backspace.""" - speak(_("Game paused, press backspace to resume.")) + """Pauses the game until the player presses backspace, or start on a controller.""" + controls = Controls.get_instance() + if controls.connected(): + # Translators: start is the controller's own name for its start button, such as "options". + speak(_("Game paused, press backspace or {start} to resume.").format( + start=controls.input_name(("pad", "start")))) + else: + speak(_("Game paused, press backspace to resume.")) pygame.event.clear() try: pygame.mixer.pause() @@ -215,8 +222,10 @@ def pause_game(): pass while True: - event = pygame.event.wait() - if event.type == pygame.KEYDOWN and event.key == pygame.K_BACKSPACE: + event = translate_event(pygame.event.wait()) + if event.type == pygame.KEYDOWN and event.key == pygame.K_BACKSPACE: + break + if pad_button(event) == "start" and event.type == pygame.CONTROLLERBUTTONDOWN: break pygame.event.pump() diff --git a/locales/libstormgames.pot b/locales/libstormgames.pot index 3b80657..bbdf8a9 100644 --- a/locales/libstormgames.pot +++ b/locales/libstormgames.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: libstormgames\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-29 01:27-0500\n" +"POT-Creation-Date: 2026-11-29 19:37-0500\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -18,282 +18,746 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" -#: display.py:175 utils.py:260 +#: controls.py:136 +msgid "automatic" +msgstr "" + +#: controls.py:137 +msgid "PlayStation" +msgstr "" + +#: controls.py:138 +msgid "Xbox" +msgstr "" + +#: controls.py:139 +msgid "Nintendo" +msgstr "" + +#: controls.py:144 +msgid "d-pad down" +msgstr "" + +#: controls.py:144 +msgid "d-pad up" +msgstr "" + +#: controls.py:145 +msgid "d-pad left" +msgstr "" + +#: controls.py:145 +msgid "d-pad right" +msgstr "" + +#: controls.py:146 +msgid "left stick down" +msgstr "" + +#: controls.py:146 +msgid "left stick up" +msgstr "" + +#: controls.py:147 +msgid "left stick left" +msgstr "" + +#: controls.py:147 +msgid "left stick right" +msgstr "" + +#: controls.py:148 +msgid "right stick down" +msgstr "" + +#: controls.py:148 +msgid "right stick up" +msgstr "" + +#: controls.py:149 +msgid "right stick left" +msgstr "" + +#: controls.py:149 +msgid "right stick right" +msgstr "" + +#: controls.py:150 +msgid "left stick left and right" +msgstr "" + +#: controls.py:150 +msgid "left stick up and down" +msgstr "" + +#: controls.py:151 +msgid "right stick left and right" +msgstr "" + +#: controls.py:151 +msgid "right stick up and down" +msgstr "" + +#: controls.py:152 +msgid "touchpad" +msgstr "" + +#: controls.py:153 +msgid "misc button" +msgstr "" + +#: controls.py:157 +msgid "circle" +msgstr "" + +#: controls.py:157 +msgid "cross" +msgstr "" + +#: controls.py:157 +msgid "square" +msgstr "" + +#: controls.py:157 +msgid "triangle" +msgstr "" + +#: controls.py:158 +msgid "L1" +msgstr "" + +#: controls.py:158 +msgid "L2" +msgstr "" + +#: controls.py:158 +msgid "L3" +msgstr "" + +#: controls.py:158 +msgid "R1" +msgstr "" + +#: controls.py:158 +msgid "R2" +msgstr "" + +#: controls.py:158 +msgid "R3" +msgstr "" + +#: controls.py:159 +msgid "PS button" +msgstr "" + +#: controls.py:159 +msgid "mute button" +msgstr "" + +#: controls.py:159 +msgid "options" +msgstr "" + +#: controls.py:159 controls.py:165 +msgid "share" +msgstr "" + +#: controls.py:162 controls.py:168 +msgid "A" +msgstr "" + +#: controls.py:162 controls.py:168 +msgid "B" +msgstr "" + +#: controls.py:162 controls.py:168 +msgid "X" +msgstr "" + +#: controls.py:162 controls.py:168 +msgid "Y" +msgstr "" + +#: controls.py:163 +msgid "LB" +msgstr "" + +#: controls.py:163 +msgid "LT" +msgstr "" + +#: controls.py:163 +msgid "RB" +msgstr "" + +#: controls.py:163 +msgid "RT" +msgstr "" + +#: controls.py:164 controls.py:170 +msgid "left stick click" +msgstr "" + +#: controls.py:164 controls.py:170 +msgid "right stick click" +msgstr "" + +#: controls.py:165 +msgid "Xbox button" +msgstr "" + +#: controls.py:165 +msgid "menu" +msgstr "" + +#: controls.py:165 +msgid "view" +msgstr "" + +#: controls.py:169 +msgid "L" +msgstr "" + +#: controls.py:169 +msgid "R" +msgstr "" + +#: controls.py:169 +msgid "ZL" +msgstr "" + +#: controls.py:169 +msgid "ZR" +msgstr "" + +#: controls.py:171 +msgid "capture" +msgstr "" + +#: controls.py:171 +msgid "home" +msgstr "" + +#: controls.py:171 input.py:34 +msgid "minus" +msgstr "" + +#: controls.py:171 input.py:32 +msgid "plus" +msgstr "" + +#: controls.py:183 +msgid "down arrow" +msgstr "" + +#: controls.py:183 +msgid "enter" +msgstr "" + +#: controls.py:183 +msgid "up arrow" +msgstr "" + +#: controls.py:184 +msgid "left arrow" +msgstr "" + +#: controls.py:184 +msgid "right arrow" +msgstr "" + +#: controls.py:184 input.py:19 +msgid "space" +msgstr "" + +#: controls.py:185 +msgid "backspace" +msgstr "" + +#: controls.py:185 +msgid "escape" +msgstr "" + +#: controls.py:185 +msgid "tab" +msgstr "" + +#: controls.py:186 +msgid "alt" +msgstr "" + +#: controls.py:186 +msgid "control" +msgstr "" + +#: controls.py:186 +msgid "meta" +msgstr "" + +#: controls.py:186 +msgid "shift" +msgstr "" + +#: controls.py:187 +msgid "left control" +msgstr "" + +#: controls.py:187 +msgid "right control" +msgstr "" + +#: controls.py:357 +msgid "left" +msgstr "" + +#: controls.py:361 +msgid "right" +msgstr "" + +#: controls.py:369 +msgid "Menu up" +msgstr "" + +#: controls.py:370 +msgid "Menu down" +msgstr "" + +#: controls.py:371 +msgid "Menu left" +msgstr "" + +#: controls.py:372 +msgid "Menu right" +msgstr "" + +#: controls.py:373 +msgid "Confirm" +msgstr "" + +#: controls.py:374 controls_menu.py:170 speech_options.py:206 +msgid "Back" +msgstr "" + +#: controls.py:684 +msgid "Controller disconnected" +msgstr "" + +#: controls.py:686 +msgid "Controller connected" +msgstr "" + +#. Translators: the two inputs of a pair, such as "left arrow and right arrow". +#: controls.py:879 +#, python-brace-format +msgid "{negative} and {positive}" +msgstr "" + +#: controls.py:884 +#, python-brace-format +msgid "{input}, reversed" +msgstr "" + +#. Translators: hold one input and press another, such as "L1 plus square". +#: controls.py:889 +#, python-brace-format +msgid "{held} plus {pressed}" +msgstr "" + +#: controls.py:896 +msgid "not set" +msgstr "" + +#: controls_menu.py:148 +msgid "Controller options" +msgstr "" + +#. Translators: an action and what it is bound to, such as "Horn: H, L1". +#: controls_menu.py:156 controls_menu.py:331 +#, python-brace-format +msgid "{action}: {bindings}" +msgstr "" + +#: controls_menu.py:159 +#, python-brace-format +msgid "Rumble, {state}" +msgstr "" + +#: controls_menu.py:159 +msgid "off" +msgstr "" + +#: controls_menu.py:159 +msgid "on" +msgstr "" + +#: controls_menu.py:161 +#, python-brace-format +msgid "Rumble strength, {percent} percent" +msgstr "" + +#: controls_menu.py:165 +#, python-brace-format +msgid "{choice}, {scheme}" +msgstr "" + +#: controls_menu.py:167 +#, python-brace-format +msgid "Button names, {scheme}" +msgstr "" + +#: controls_menu.py:169 +msgid "Reset all controls" +msgstr "" + +#. Translators: a group of controls, then the control, such as "Driving. Horn: H, L1". +#: controls_menu.py:176 controls_menu.py:184 +#, python-brace-format +msgid "{group}. {item}" +msgstr "" + +#: controls_menu.py:185 +msgid "Controls" +msgstr "" + +#: controls_menu.py:185 speech_options.py:213 +#, python-brace-format +msgid "{title}. {item}" +msgstr "" + +#: controls_menu.py:238 +msgid "All controls reset to their defaults." +msgstr "" + +#: controls_menu.py:241 +msgid "Press Enter again to reset all controls." +msgstr "" + +#: controls_menu.py:266 +#, python-brace-format +msgid "Reset. {item}" +msgstr "" + +#: controls_menu.py:278 +#, python-brace-format +msgid "Press the key or button to remove from {action}." +msgstr "" + +#: controls_menu.py:280 +#, python-brace-format +msgid "" +"{action}: push a stick to the {positive}, or press a key or button for " +"{positive}." +msgstr "" + +#: controls_menu.py:283 +#, python-brace-format +msgid "Press a key or button for {action}." +msgstr "" + +#: controls_menu.py:286 controls_menu.py:297 controls_menu.py:316 +msgid "Cancelled." +msgstr "" + +#: controls_menu.py:293 +#, python-brace-format +msgid "Now {negative}." +msgstr "" + +#: controls_menu.py:300 +msgid "Both directions must be single inputs on the same device. Cancelled." +msgstr "" + +#: controls_menu.py:307 +#, python-brace-format +msgid "{binding} is already set for {action}." +msgstr "" + +#: controls_menu.py:312 +#, python-brace-format +msgid "" +"{binding} is already {other}. Press it again to swap, or Escape to cancel." +msgstr "" + +#: controls_menu.py:345 +#, python-brace-format +msgid "{binding} is not set for {action}." +msgstr "" + +#: controls_menu.py:351 +#, python-brace-format +msgid "Removed. {item}" +msgstr "" + +#: display.py:179 utils.py:264 msgid "" "Press space to read the whole text. Use up and down arrows to navigate the " "text line by line. Press c to copy the current line to the clipboard or t to " "copy the entire text. Press enter or escape when you are done reading." msgstr "" -#: display.py:182 utils.py:267 +#: display.py:186 utils.py:271 msgid "End of text." msgstr "" -#: display.py:232 utils.py:313 +#: display.py:236 utils.py:317 #, python-brace-format msgid "Copied {text} to the clipboard." msgstr "" -#: display.py:234 display.py:242 utils.py:315 utils.py:324 +#: display.py:238 display.py:246 utils.py:319 utils.py:328 msgid "Failed to copy the text to the clipboard." msgstr "" -#: display.py:240 utils.py:322 +#: display.py:244 utils.py:326 msgid "Copied entire message to the clipboard." msgstr "" -#: input.py:18 -msgid "space" -msgstr "" - -#: input.py:19 +#: input.py:20 msgid "backslash" msgstr "" -#: input.py:20 +#: input.py:21 msgid "slash" msgstr "" -#: input.py:21 +#: input.py:22 msgid "exclamation mark" msgstr "" -#: input.py:22 +#: input.py:23 msgid "quotation mark" msgstr "" -#: input.py:23 +#: input.py:24 msgid "hash" msgstr "" -#: input.py:24 +#: input.py:25 msgid "dollar sign" msgstr "" -#: input.py:25 +#: input.py:26 msgid "percent" msgstr "" -#: input.py:26 +#: input.py:27 msgid "ampersand" msgstr "" -#: input.py:27 +#: input.py:28 msgid "apostrophe" msgstr "" -#: input.py:28 +#: input.py:29 msgid "left parenthesis" msgstr "" -#: input.py:29 +#: input.py:30 msgid "right parenthesis" msgstr "" -#: input.py:30 +#: input.py:31 msgid "asterisk" msgstr "" -#: input.py:31 -msgid "plus" -msgstr "" - -#: input.py:32 +#: input.py:33 msgid "comma" msgstr "" -#: input.py:33 -msgid "minus" -msgstr "" - -#: input.py:34 +#: input.py:35 msgid "period" msgstr "" -#: input.py:35 +#: input.py:36 msgid "colon" msgstr "" -#: input.py:36 +#: input.py:37 msgid "semicolon" msgstr "" -#: input.py:37 +#: input.py:38 msgid "less than" msgstr "" -#: input.py:38 +#: input.py:39 msgid "equals" msgstr "" -#: input.py:39 +#: input.py:40 msgid "greater than" msgstr "" -#: input.py:40 +#: input.py:41 msgid "question mark" msgstr "" -#: input.py:41 +#: input.py:42 msgid "at sign" msgstr "" -#: input.py:42 +#: input.py:43 msgid "left bracket" msgstr "" -#: input.py:43 +#: input.py:44 msgid "right bracket" msgstr "" -#: input.py:44 +#: input.py:45 msgid "caret" msgstr "" -#: input.py:45 +#: input.py:46 msgid "underscore" msgstr "" -#: input.py:46 +#: input.py:47 msgid "grave accent" msgstr "" -#: input.py:47 +#: input.py:48 msgid "left brace" msgstr "" -#: input.py:48 +#: input.py:49 msgid "pipe" msgstr "" -#: input.py:49 +#: input.py:50 msgid "right brace" msgstr "" -#: input.py:50 +#: input.py:51 msgid "tilde" msgstr "" -#: input.py:78 +#: input.py:79 msgid "Enter text:" msgstr "" -#: input.py:86 +#: input.py:87 #, python-brace-format msgid "{count} character" msgid_plural "{count} characters" msgstr[0] "" msgstr[1] "" -#: input.py:90 +#: input.py:91 #, python-brace-format msgid "{prompt} Password field, {length}" msgstr "" -#: input.py:92 +#: input.py:93 #, python-brace-format msgid "{prompt} Default text: {text}" msgstr "" -#: input.py:94 +#: input.py:95 #, python-brace-format msgid "{prompt} Empty password field" msgstr "" -#: input.py:96 +#: input.py:97 #, python-brace-format msgid "{prompt} Empty text field" msgstr "" -#: input.py:111 +#: input.py:112 msgid "Submitted" msgstr "" -#: input.py:111 input.py:115 +#: input.py:112 input.py:116 msgid "Submitted: empty" msgstr "" -#: input.py:113 +#: input.py:114 #, python-brace-format msgid "Submitted: {text}" msgstr "" -#: input.py:120 +#: input.py:121 msgid "Cancelled" msgstr "" -#: input.py:128 input.py:136 +#: input.py:129 input.py:137 msgid "star deleted" msgstr "" -#: input.py:128 input.py:136 +#: input.py:129 input.py:137 #, python-brace-format msgid "{character} deleted" msgstr "" -#: input.py:130 input.py:138 +#: input.py:131 input.py:139 msgid "Nothing to delete" msgstr "" -#: input.py:145 input.py:149 input.py:173 +#: input.py:146 input.py:150 input.py:174 msgid "Beginning of text" msgstr "" -#: input.py:147 input.py:154 input.py:193 +#: input.py:148 input.py:155 input.py:194 msgid "star" msgstr "" -#: input.py:157 input.py:159 input.py:178 +#: input.py:158 input.py:160 input.py:179 msgid "End of text" msgstr "" -#: input.py:168 +#: input.py:169 msgid "Empty text field" msgstr "" -#: input.py:205 +#. Translators: start is the controller's own name for its start button, such as "options". +#: input.py:209 +#, python-brace-format +msgid "Game paused, press backspace or {start} to resume." +msgstr "" + +#: input.py:212 msgid "Game paused, press backspace to resume." msgstr "" -#: menu.py:32 +#: menu.py:33 msgid "play" msgstr "" -#: menu.py:33 +#: menu.py:34 msgid "high scores" msgstr "" -#: menu.py:34 +#: menu.py:35 msgid "learn sounds" msgstr "" -#: menu.py:35 +#: menu.py:36 msgid "instructions" msgstr "" -#: menu.py:36 +#: menu.py:37 msgid "credits" msgstr "" -#: menu.py:37 +#: menu.py:38 msgid "donate" msgstr "" -#: menu.py:38 +#: menu.py:39 msgid "exit game" msgstr "" -#: menu.py:481 +#: menu.py:482 msgid "No sounds available to learn." msgstr "" -#: menu.py:496 +#: menu.py:497 msgid "" "Starting with root directory sounds. Use left and right arrows or page up " "and page down to navigate categories." msgstr "" -#: menu.py:499 +#: menu.py:500 #, python-brace-format msgid "" "Starting with {category} sounds. Use left and right arrows or page up and " @@ -301,39 +765,39 @@ msgid "" msgstr "" #. Translators: a sound's name and what it is, as in "bell: the lap bell". -#: menu.py:526 +#: menu.py:527 #, python-brace-format msgid "{sound}: {description}" msgstr "" -#: menu.py:532 +#: menu.py:533 #, python-brace-format msgid "Root directory: {sound}, {number} of {total}" msgstr "" -#: menu.py:535 +#: menu.py:536 #, python-brace-format msgid "{category}: {sound}, {number} of {total}" msgstr "" -#: menu.py:539 +#: menu.py:540 #, python-brace-format msgid "{sound}, {number} of {total}" msgstr "" -#: menu.py:588 +#: menu.py:589 msgid "Could not play sound." msgstr "" -#: menu.py:608 +#: menu.py:609 msgid "Instructions file is missing." msgstr "" -#: menu.py:627 +#: menu.py:628 msgid "Credits file is missing." msgstr "" -#: menu.py:637 +#: menu.py:638 msgid "The donation page has been opened in your browser." msgstr "" @@ -369,92 +833,83 @@ msgstr "" msgid "Could not display high scores." msgstr "" -#: speech.py:180 +#: speech.py:181 msgid "Speech settings preview." msgstr "" -#: speech.py:436 speech.py:443 +#: speech.py:437 speech.py:444 msgid "Press any key to repeat or enter to continue." msgstr "" -#: speech.py:602 +#: speech.py:603 #, python-brace-format msgid "First: {message}" msgstr "" -#: speech.py:605 +#: speech.py:606 msgid "No previous messages" msgstr "" -#: speech.py:607 speech.py:621 speech.py:638 +#: speech.py:608 speech.py:622 speech.py:639 msgid "Speech history not available" msgstr "" -#: speech.py:619 +#: speech.py:620 msgid "No messages in history" msgstr "" -#: speech.py:633 +#: speech.py:634 #, python-brace-format msgid "Last: {message}" msgstr "" -#: speech.py:636 +#: speech.py:637 msgid "No next messages" msgstr "" -#: speech_options.py:32 +#: speech_options.py:33 msgid "Speech module" msgstr "" -#: speech_options.py:33 +#: speech_options.py:34 msgid "Speech voice" msgstr "" -#: speech_options.py:34 +#: speech_options.py:35 msgid "Speech rate" msgstr "" -#: speech_options.py:35 +#: speech_options.py:36 msgid "Speech pitch" msgstr "" -#: speech_options.py:36 +#: speech_options.py:37 msgid "Speech volume" msgstr "" #. Translators: a speech option and its value, such as "Speech rate, 25" or "Speech voice, System default". -#: speech_options.py:113 +#: speech_options.py:114 #, python-brace-format msgid "{setting}, {value}" msgstr "" -#: speech_options.py:114 +#: speech_options.py:115 msgid "System default" msgstr "" -#: speech_options.py:128 +#: speech_options.py:129 #, python-brace-format msgid "Could not change speech setting: {error}" msgstr "" -#: speech_options.py:156 +#: speech_options.py:157 msgid "No speech choices available." msgstr "" -#: speech_options.py:203 +#: speech_options.py:204 msgid "Speech settings need Speech Dispatcher." msgstr "" -#: speech_options.py:205 -msgid "Back" -msgstr "" - -#: speech_options.py:212 +#: speech_options.py:213 msgid "Speech options" msgstr "" - -#: speech_options.py:212 -#, python-brace-format -msgid "{title}. {item}" -msgstr "" diff --git a/menu.py b/menu.py index 78ef851..35e2bae 100644 --- a/menu.py +++ b/menu.py @@ -25,6 +25,7 @@ from .display import display_text from .scoreboard import Scoreboard from .services import PathService, ConfigService from .i18n import _, N_, reset_language, translated_file +from .controls import translate_event # What game_menu() says for its own items. A game's own items are spoken # as its optionLabels say, or as they are given with underscores read as spaces. @@ -91,7 +92,7 @@ def instruction_menu(sounds, instruction_text, *options): speech.speak(all_items[current_index]) last_spoken = current_index - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.KEYDOWN: if is_language_reset(event): speech.speak(reset_language()) @@ -239,7 +240,7 @@ def game_menu(sounds, playCallback=None, *customOptions, soundDescriptions=None, speech.speak(option_label(option, optionLabels)) lastSpoken = currentIndex - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.KEYDOWN: # Check for Alt modifier mods = pygame.key.get_mods() @@ -542,7 +543,7 @@ def learn_sounds(sounds, descriptions=None): speech.speak(announcement) lastSpoken = currentSoundIndex - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.KEYDOWN: if is_language_reset(event): speech.speak(reset_language()) diff --git a/sound.py b/sound.py index f04609d..524302a 100644 --- a/sound.py +++ b/sound.py @@ -16,6 +16,7 @@ import re import time import math from .services import VolumeService +from .controls import translate_events # Global instance for backward compatibility volumeService = VolumeService.get_instance() @@ -94,7 +95,7 @@ class Sound: channel.play(self.sounds[soundName]) while pygame.mixer.get_busy(): - for event in pygame.event.get(): + for event in translate_events(pygame.event.get()): if event.type == pygame.KEYDOWN and event.key in [pygame.K_ESCAPE, pygame.K_RETURN, pygame.K_SPACE]: pygame.mixer.stop() return None @@ -429,7 +430,7 @@ def _play_cutscene(sound, sounds=None): # Wait for completion or key press while pygame.mixer.get_busy(): - for event in pygame.event.get(): + for event in translate_events(pygame.event.get()): if event.type == pygame.KEYDOWN and event.key in [pygame.K_ESCAPE, pygame.K_RETURN, pygame.K_SPACE]: pygame.mixer.stop() return None diff --git a/speech.py b/speech.py index ef5ce32..97ded5f 100644 --- a/speech.py +++ b/speech.py @@ -15,6 +15,7 @@ from contextlib import contextmanager from sys import exit from .i18n import _ +from .controls import translate_event # Keep track of whether dialog instructions have been shown dialogUsageInstructions = False @@ -435,7 +436,7 @@ def _show_simple_message(speech, text): """Show a simple text message (original messagebox behavior).""" speech.speak(text + "\n" + _("Press any key to repeat or enter to continue.")) while True: - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.KEYDOWN: if event.key in (pygame.K_ESCAPE, pygame.K_RETURN): speech.speak(" ") @@ -486,7 +487,7 @@ def _show_dialog_sequence(speech, dialog_config, sounds): # Handle user input while True: - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: if allow_skip: diff --git a/speech_options.py b/speech_options.py index 1ed0d34..193a218 100644 --- a/speech_options.py +++ b/speech_options.py @@ -16,6 +16,7 @@ import time import pygame +from .controls import translate_event from .i18n import _, N_, reset_language from .menu import is_language_reset from .services import ConfigService @@ -212,7 +213,7 @@ def speech_options_menu(sounds, preferences=None, title=None): say(_("{title}. {item}").format(title=title or _("Speech options"), item=current_label())) pygame.event.clear() while True: - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.QUIT: return if event.type != pygame.KEYDOWN: diff --git a/tests/test_controls.py b/tests/test_controls.py new file mode 100644 index 0000000..49a90b3 --- /dev/null +++ b/tests/test_controls.py @@ -0,0 +1,575 @@ +"""Keyboard and controller actions, saved bindings, menu translation, rumble and the controls menu. + +A fake keyboard and controller stand in for the hardware. +Run from the library root: python -m unittest discover -s tests -v +""" + +import configparser +import importlib +import os +from pathlib import Path +import sys +from types import ModuleType +import unittest +from unittest.mock import Mock, patch + +os.environ.setdefault("SDL_VIDEODRIVER", "dummy") +os.environ.setdefault("SDL_AUDIODRIVER", "dummy") +import pygame # noqa: E402 + + +def load_controls(): + """Load the real controls code in a package of its own, so nothing is shared with other tests.""" + packageName = "_controls_test_library" + package = ModuleType(packageName) + package.__path__ = [str(Path(__file__).resolve().parents[1])] + with patch.dict(sys.modules, {packageName: package}): + controls = importlib.import_module(f"{packageName}.controls") + controlsMenu = importlib.import_module(f"{packageName}.controls_menu") + return controls, controlsMenu + + +def key_down(keyCode, mod=0): + return pygame.event.Event(pygame.KEYDOWN, key=keyCode, mod=mod, unicode="", scancode=0) + + +def key_up(keyCode, mod=0): + return pygame.event.Event(pygame.KEYUP, key=keyCode, mod=mod, unicode="", scancode=0) + + +def button_down(name): + return pygame.event.Event(pygame.CONTROLLERBUTTONDOWN, button=BUTTONS[name], instance_id=0) + + +def button_up(name): + return pygame.event.Event(pygame.CONTROLLERBUTTONUP, button=BUTTONS[name], instance_id=0) + + +BUTTONS = { + "south": pygame.CONTROLLER_BUTTON_A, "east": pygame.CONTROLLER_BUTTON_B, + "west": pygame.CONTROLLER_BUTTON_X, "north": pygame.CONTROLLER_BUTTON_Y, + "l1": pygame.CONTROLLER_BUTTON_LEFTSHOULDER, "r1": pygame.CONTROLLER_BUTTON_RIGHTSHOULDER, + "dpadDown": pygame.CONTROLLER_BUTTON_DPAD_DOWN, "dpadUp": pygame.CONTROLLER_BUTTON_DPAD_UP, + "select": pygame.CONTROLLER_BUTTON_BACK, "start": pygame.CONTROLLER_BUTTON_START, +} +AXIS_MOTION = pygame.event.Event(pygame.CONTROLLERAXISMOTION, axis=0, value=0, instance_id=0) + + +class FakePad: + def __init__(self, name="PS4 Controller"): + self.name = name + self.buttons = {} + self.axes = {} + self.rumbles = [] + + def get_button(self, number): + return self.buttons.get(number, 0) + + def get_axis(self, number): + return self.axes.get(number, 0) + + def rumble(self, low, high, durationMs): + self.rumbles.append((round(low, 3), round(high, 3), durationMs)) + return True + + def press(self, name, down=True): + self.buttons[BUTTONS[name]] = 1 if down else 0 + + def stick(self, axis, value): + self.axes[axis] = int(value * 32767) + + +class FakeDevices: + """The hardware: a keyboard state, controllers that can come and go, a clock and scripted events.""" + + started = True + repeatEvent = pygame.USEREVENT + 20 + + def __init__(self, pads=None): + self.pads = list(pads) if pads is not None else [FakePad()] + self.keys = {} + self.now = 0 + self.timerRunning = False + self.events = [] + self.pending = ([], []) + + def start(self): + return True + + def check(self): + added, removed = self.pending + self.pending = ([], []) + return added, removed + + def controllers(self): + return self.pads + + def key_state(self): + return self.keys + + def ticks(self): + return self.now + + def set_repeat_timer(self, running): + self.timerRunning = running + + def wait(self, timeoutMs): + if self.events: + step = self.events.pop(0) + if callable(step): + step = step() + return step if step is not None else pygame.event.Event(pygame.NOEVENT) + self.now += timeoutMs + return pygame.event.Event(pygame.NOEVENT) + + +class FakeConfig: + def __init__(self, text=""): + self.localConfig = configparser.ConfigParser() + self.localConfig.read_string(text) + self.writes = 0 + + def write_local_config(self): + self.writes += 1 + + def saved(self): + return {section: dict(self.localConfig.items(section, raw=True)) for section in self.localConfig.sections()} + + +class ControlsTestCase(unittest.TestCase): + def setUp(self): + self.module, self.menuModule = load_controls() + self.devices = FakeDevices() + self.pad = self.devices.pads[0] + self.config = FakeConfig() + self.spoken = [] + + def make(self, actions=None, config=None): + Action = self.module.Action + if actions is None: + actions = [ + Action("steer", "Steer", "driving", keys=["left/right"], pad=["leftStickX", "dpadLeft/dpadRight"], + axis=True), + Action("horn", "Horn", "driving", keys=["h"], pad=["l1"]), + Action("brake", "Brake", "driving", keys=["down", "space"], pad=["west"]), + Action("accelerate", "Accelerate", "driving", keys=["up"], pad=["r2", "south"]), + Action("weapon", "Weapon", "fighting", keys=["ctrl+w"], pad=["l1+west"]), + Action("look", "Look", "fighting", keys=["l"], pad=["-leftStickY"]), + ] + return self.module.Controls(actions, config=config or self.config, speak=self.spoken.append, + devices=self.devices) + + +class BindingTests(ControlsTestCase): + def test_bindings_parse_keys_pad_inputs_chords_pairs_and_axes(self): + Binding = self.module.Binding + chord = Binding("ctrl+s", "keyboard") + self.assertEqual(chord.modifiers, (("key", (pygame.K_LCTRL, pygame.K_RCTRL)),)) + self.assertEqual(chord.trigger, ("key", (pygame.K_s,))) + padChord = Binding("L1+West", "pad") + self.assertEqual((padChord.modifiers, padChord.trigger), ((("pad", "l1"),), ("pad", "west"))) + pair = Binding("left/right", "keyboard") + self.assertEqual((pair.kind, pair.negative, pair.positive), + ("pair", ("key", (pygame.K_LEFT,)), ("key", (pygame.K_RIGHT,)))) + axis = Binding("-leftStickY", "pad") + self.assertEqual((axis.kind, axis.trigger, axis.inverted), ("axis", ("axis", "leftStickY"), True)) + self.assertEqual(Binding("page up", "keyboard").trigger, ("key", (pygame.K_PAGEUP,))) + self.assertEqual(Binding("plus", "keyboard").trigger, ("key", (pygame.K_PLUS,))) + + def test_bad_bindings_are_skipped(self): + with patch("builtins.print"): + bindings = self.module.parse_bindings("h, nosuchkey, ctrl+, leftStickX", "keyboard") + padBindings = self.module.parse_bindings(["wobble", "leftStickX+east", "-south", "l1+leftStickX", "east"], + "pad") + self.assertEqual([binding.text for binding in bindings], ["h"]) + self.assertEqual([binding.text for binding in padBindings], ["l1+leftStickX", "east"]) + + def test_saved_key_names_avoid_the_separators(self): + for keyCode in (pygame.K_COMMA, pygame.K_PLUS, pygame.K_SLASH, pygame.K_KP_PLUS, pygame.K_KP_ENTER, + pygame.K_RETURN, pygame.K_KP1, pygame.K_PAGEUP): + with self.subTest(keyCode=keyCode): + name = self.module.key_save_name(keyCode) + self.assertFalse(set(name) & set(",+/%"), name) + self.assertEqual(self.module.key_code_for(name), keyCode) + + +class FrameTests(ControlsTestCase): + def frame(self, controls, *events): + controls.update(list(events)) + + def test_key_press_is_pressed_for_one_frame_and_held_until_let_go(self): + controls = self.make() + self.devices.keys[pygame.K_h] = True + self.frame(controls, key_down(pygame.K_h)) + self.assertTrue(controls.pressed("horn")) + self.assertTrue(controls.held("horn")) + self.frame(controls, key_down(pygame.K_h)) # the key repeating + self.assertFalse(controls.pressed("horn")) + self.assertTrue(controls.held("horn")) + self.devices.keys[pygame.K_h] = False + self.frame(controls) + self.assertFalse(controls.held("horn")) + + def test_a_tap_between_frames_still_counts(self): + controls = self.make() + self.frame(controls, key_down(pygame.K_h), key_up(pygame.K_h)) + self.assertTrue(controls.pressed("horn")) + self.frame(controls, button_down("l1")) + self.assertTrue(controls.pressed("horn")) + self.frame(controls) + self.assertFalse(controls.held("horn")) + + def test_controller_button_held_without_an_event(self): + controls = self.make() + self.pad.press("south") + self.frame(controls) + self.assertTrue(controls.pressed("accelerate")) + self.frame(controls) + self.assertFalse(controls.pressed("accelerate")) + self.assertEqual(controls.value("accelerate"), 1.0) + + def test_stick_value_has_a_dead_zone_and_reaches_the_ends(self): + controls = self.make() + for raw, expected in [(0.1, 0.0), (0.6, 0.5), (1.0, 1.0), (-1.0, -1.0)]: + with self.subTest(raw=raw): + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTX, raw) + self.frame(controls) + self.assertAlmostEqual(controls.value("steer"), expected, places=2) + + def test_keys_and_dpad_pairs_steer_both_ways(self): + controls = self.make() + self.devices.keys[pygame.K_LEFT] = True + self.frame(controls) + self.assertEqual(controls.value("steer"), -1.0) + self.devices.keys[pygame.K_LEFT] = False + self.pad.press("dpadDown", False) + self.pad.buttons[pygame.CONTROLLER_BUTTON_DPAD_RIGHT] = 1 + self.frame(controls) + self.assertEqual(controls.value("steer"), 1.0) + self.assertTrue(controls.held("steer")) + + def test_reversed_axis(self): + controls = self.make() + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, -1.0) # stick pushed up + self.frame(controls) + self.assertEqual(controls.value("look"), 1.0) + self.assertTrue(controls.pressed("look")) + + def test_trigger_gives_how_far_it_is_pulled(self): + controls = self.make() + self.pad.stick(pygame.CONTROLLER_AXIS_TRIGGERRIGHT, 0.6) + self.frame(controls) + self.assertAlmostEqual(controls.value("accelerate"), 0.556, places=2) + self.assertTrue(controls.held("accelerate")) + + def test_analog_held_does_not_flicker_near_the_line(self): + controls = self.make([self.module.Action("up", pad=["leftStickUp"])]) + for raw, expected in [(-0.65, True), (-0.5, True), (-0.4, False), (-0.55, False), (-0.65, True)]: + with self.subTest(raw=raw): + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, raw) + self.frame(controls) + self.assertEqual(controls.held("up"), expected) + + def test_a_held_modifier_gives_the_chord_and_hides_the_plain_binding(self): + controls = self.make() + self.pad.press("l1") + self.frame(controls, button_down("l1")) + self.assertTrue(controls.pressed("horn")) + self.pad.press("west") + self.frame(controls, button_down("west")) + self.assertTrue(controls.pressed("weapon")) + self.assertFalse(controls.pressed("brake")) + self.pad.press("l1", False) + self.pad.press("west", False) + self.frame(controls) + self.pad.press("west") + self.frame(controls, button_down("west")) + self.assertTrue(controls.pressed("brake")) + self.assertFalse(controls.pressed("weapon")) + + def test_keyboard_chord(self): + controls = self.make() + self.devices.keys[pygame.K_LCTRL] = True + self.devices.keys[pygame.K_w] = True + self.frame(controls, key_down(pygame.K_w, pygame.KMOD_LCTRL)) + self.assertTrue(controls.pressed("weapon")) + + def test_unknown_action_is_an_error(self): + controls = self.make() + with self.assertRaises(KeyError): + controls.held("fly") + + def test_menu_actions_are_always_there(self): + controls = self.make() + self.pad.press("east") + self.frame(controls) + self.assertTrue(controls.pressed("back")) + with self.assertRaises(ValueError): + controls.set_bindings("confirm", "pad", ["west"]) + + +class SavedBindingTests(ControlsTestCase): + def test_only_changes_from_the_defaults_are_saved(self): + controls = self.make() + controls.set_bindings("horn", "pad", ["r1", "west"]) + saved = self.config.saved() + self.assertEqual(saved["controller"], {"horn": "r1, west"}) + self.assertNotIn("keyboard", saved) + self.assertEqual(saved["controller options"], {"rumble": "on", "rumble strength": "100", + "button names": "auto"}) + controls.reset_action("horn") + self.assertNotIn("controller", self.config.saved()) + + def test_saved_bindings_come_back_and_a_new_default_still_arrives(self): + self.config.localConfig.read_string("[controller]\nhorn = r1\n[keyboard]\nbrake =\n") + Action = self.module.Action + controls = self.make([Action("horn", pad=["l1"]), Action("brake", keys=["down"]), + Action("lights", keys=["g"], pad=["north"])]) + self.assertEqual(controls.get_bindings("horn", "pad"), ["r1"]) + self.assertEqual(controls.get_bindings("brake", "keyboard"), []) + self.assertEqual(controls.get_bindings("lights", "pad"), ["north"]) + + def test_options_are_saved_and_read_back(self): + self.config.localConfig.read_string("[controller options]\nrumble = off\nrumble strength = 40\n" + "button names = xbox\n") + controls = self.make() + self.assertEqual((controls.rumbleEnabled, controls.rumbleStrength, controls.buttonNames), + (False, 40, "xbox")) + + def test_conflicts_are_only_within_a_group(self): + controls = self.make() + Binding = self.module.Binding + self.assertEqual([actionId for actionId, _b in controls.conflicts("horn", Binding("west", "pad"))], + ["brake"]) + self.assertEqual(controls.conflicts("weapon", Binding("west", "pad")), []) + self.assertEqual([actionId for actionId, _b in controls.conflicts("horn", Binding("dpadLeft", "pad"))], + ["steer"]) + + +class RumbleAndNameTests(ControlsTestCase): + def test_rumble_is_scaled_and_can_be_turned_off(self): + controls = self.make() + controls.rumbleStrength = 50 + self.assertTrue(controls.rumble(1.0, 0.4, 200)) + self.assertEqual(self.pad.rumbles, [(0.5, 0.2, 200)]) + controls.rumbleEnabled = False + self.assertFalse(controls.rumble_pattern("thud")) + self.assertEqual(len(self.pad.rumbles), 1) + + def test_rumble_without_a_controller_does_nothing(self): + self.devices.pads.clear() + self.assertFalse(self.make().rumble(1, 1, 100)) + + def test_names_follow_the_controller_or_the_setting(self): + controls = self.make() + self.assertEqual(controls.describe("weapon"), "control plus w, L1 plus square") + self.assertEqual(controls.describe("steer"), + "left arrow and right arrow, left stick left and right, d-pad left and d-pad right") + self.assertEqual(controls.describe("look"), "l, left stick up and down, reversed") + self.pad.name = "Xbox Wireless Controller" + self.assertEqual(controls.describe("horn"), "h, LB") + self.pad.name = "DualSense Wireless Controller" + self.assertEqual(controls.input_name(("pad", "select")), "create") + controls.buttonNames = "nintendo" + self.assertEqual(controls.describe("accelerate"), "up arrow, ZR, B") + controls.set_bindings("horn", "pad", []) + controls.set_bindings("horn", "keyboard", []) + self.assertEqual(controls.describe("horn"), "not set") + + def test_plugging_in_and_out_is_spoken(self): + controls = self.make() + self.devices.pending = (["PS4 Controller"], []) + controls.update([]) + self.devices.pending = ([], ["PS4 Controller"]) + controls.update([]) + self.assertEqual(self.spoken, ["Controller connected", "Controller disconnected"]) + + +class TranslateTests(ControlsTestCase): + def translate(self, controls, event): + return controls.translate_event(event) + + def test_buttons_become_menu_keys(self): + controls = self.make() + for name, key in [("south", pygame.K_RETURN), ("east", pygame.K_ESCAPE), ("dpadDown", pygame.K_DOWN), + ("north", pygame.K_SPACE), ("l1", pygame.K_PAGEUP)]: + with self.subTest(name=name): + event = self.translate(controls, button_down(name)) + self.assertEqual((event.type, event.key, event.button, event.controller), + (pygame.KEYDOWN, key, name, True)) + + def test_other_events_come_back_unchanged(self): + controls = self.make() + for event in (key_down(pygame.K_a), button_down("west"), pygame.event.Event(pygame.QUIT)): + with self.subTest(event=event): + self.assertIs(self.translate(controls, event), event) + self.assertEqual(self.translate(controls, AXIS_MOTION).type, pygame.NOEVENT) + + def test_held_stick_repeats_like_a_held_key_and_stops_when_let_go(self): + controls = self.make() + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, 0.9) + event = self.translate(controls, AXIS_MOTION) + self.assertEqual(event.key, pygame.K_DOWN) + self.assertTrue(self.devices.timerRunning) + tick = pygame.event.Event(self.devices.repeatEvent) + keys = [] + for _step in range(32): + self.devices.now += 25 + keys.append(self.translate(controls, tick).type == pygame.KEYDOWN) + # The first repeat after half a second, then one every tenth of a second. + self.assertEqual(keys.index(True), 19) + self.assertEqual(sum(keys), 4) + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, 0.0) + self.assertEqual(self.translate(controls, AXIS_MOTION).type, pygame.NOEVENT) + self.assertFalse(self.devices.timerRunning) + + def test_stick_resting_near_the_line_moves_once(self): + controls = self.make() + kinds = [] + for raw in (0.7, 0.5, 0.65, 0.5, 0.7): + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, raw) + kinds.append(self.translate(controls, AXIS_MOTION).type) + self.assertEqual(kinds.count(pygame.KEYDOWN), 1) + + def test_a_button_held_from_the_menu_is_not_a_new_press_in_the_game(self): + controls = self.make() + self.pad.press("south") + self.translate(controls, button_down("south")) + controls.update([]) + self.assertFalse(controls.pressed("accelerate")) + self.assertTrue(controls.held("accelerate")) + + def test_inputs_held_after_listening_do_not_move_the_menu(self): + controls = self.make() + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, 0.9) + controls.ignore_held_inputs() + self.assertEqual(self.translate(controls, AXIS_MOTION).type, pygame.NOEVENT) + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, 0.0) + self.translate(controls, AXIS_MOTION) + self.pad.stick(pygame.CONTROLLER_AXIS_LEFTY, 0.9) + self.assertEqual(self.translate(controls, AXIS_MOTION).key, pygame.K_DOWN) + + def test_module_translate_leaves_keys_alone_before_any_controls_exist(self): + self.module.Controls._instance = None + event = key_down(pygame.K_DOWN) + with patch.object(self.module.Controls, "get_instance", side_effect=AssertionError("made controls")): + self.assertIs(self.module.translate_event(event), event) + + +class ControlsMenuTests(ControlsTestCase): + def run_menu(self, controls, menuEvents, captureEvents=()): + self.devices.events = list(captureEvents) + speech = Mock() + speech.lastSpoken = {} + self.menuModule.Speech = Mock() + self.menuModule.Speech.get_instance.return_value = speech + with patch.object(pygame.event, "wait", side_effect=list(menuEvents) + [key_down(pygame.K_ESCAPE)]), \ + patch.object(pygame.event, "clear"): + self.menuModule.controls_menu({}, controls) + return [call.args[0] for call in speech.speak.call_args_list] + + def test_enter_listens_and_replaces_the_controller_binding(self): + controls = self.make() + down = key_down(pygame.K_DOWN) + spoken = self.run_menu(controls, [down, key_down(pygame.K_RETURN)], + [lambda: self.pad.press("r1"), button_down("r1"), + lambda: self.pad.press("r1", False), button_up("r1")]) + self.assertEqual(controls.get_bindings("horn", "pad"), ["r1"]) + self.assertEqual(controls.get_bindings("horn", "keyboard"), ["h"]) + self.assertEqual(spoken[0], "Controls. driving. Steer: left arrow and right arrow, left stick left and right, " + "d-pad left and d-pad right") + self.assertIn("Press a key or button for Horn.", spoken) + self.assertEqual(spoken[-1], "Horn: h, R1") + self.assertEqual(self.config.saved()["controller"], {"horn": "r1"}) + + def test_cross_that_opened_listening_is_not_taken_as_the_binding(self): + controls = self.make() + self.pad.press("south") + opening = controls.translate_event(button_down("south")) + self.run_menu(controls, [key_down(pygame.K_DOWN), opening], + [button_up("south"), lambda: self.pad.press("south", False), + key_down(pygame.K_j)]) + self.assertEqual(controls.get_bindings("horn", "keyboard"), ["j"]) + self.assertEqual(controls.get_bindings("horn", "pad"), ["l1"]) + + def test_a_held_button_and_another_make_a_chord(self): + controls = self.make() + self.run_menu(controls, [key_down(pygame.K_DOWN), key_down(pygame.K_INSERT)], + [lambda: self.pad.press("r1"), button_down("r1"), lambda: self.pad.press("north"), + button_down("north")]) + self.assertEqual(controls.get_bindings("horn", "pad"), ["l1", "r1+north"]) + + def test_clash_in_the_group_swaps_when_pressed_again(self): + controls = self.make() + presses = [button_down("west"), button_up("west")] + spoken = self.run_menu(controls, [key_down(pygame.K_DOWN), key_down(pygame.K_RETURN)], presses + presses) + self.assertEqual(controls.get_bindings("horn", "pad"), ["west"]) + self.assertEqual(controls.get_bindings("brake", "pad"), ["l1"]) + self.assertIn("square is already Brake. Press it again to swap, or Escape to cancel.", spoken) + self.assertEqual(spoken[-1], "Horn: h, square. Brake: down arrow, space, L1") + + def test_clash_is_cancelled_by_anything_else(self): + controls = self.make() + spoken = self.run_menu(controls, [key_down(pygame.K_DOWN), key_down(pygame.K_RETURN)], + [button_down("west"), button_up("west"), key_down(pygame.K_ESCAPE)]) + self.assertEqual(controls.get_bindings("horn", "pad"), ["l1"]) + self.assertEqual(spoken[-1], "Cancelled.") + + def test_listening_gives_up_after_five_quiet_seconds(self): + controls = self.make() + spoken = self.run_menu(controls, [key_down(pygame.K_DOWN), key_down(pygame.K_RETURN)]) + self.assertEqual(spoken[-1], "Cancelled.") + self.assertGreaterEqual(self.devices.now, 5000) + self.assertEqual(controls.get_bindings("horn", "pad"), ["l1"]) + + def test_axis_action_takes_a_pushed_stick_or_two_inputs(self): + controls = self.make() + self.run_menu(controls, [key_down(pygame.K_RETURN)], + [lambda: self.pad.stick(pygame.CONTROLLER_AXIS_RIGHTX, 1.0)]) + self.assertEqual(controls.get_bindings("steer", "pad"), ["rightStickX"]) + self.pad.stick(pygame.CONTROLLER_AXIS_RIGHTX, 0.0) + spoken = self.run_menu(controls, [key_down(pygame.K_RETURN)], [key_down(pygame.K_d), key_down(pygame.K_a)]) + self.assertEqual(controls.get_bindings("steer", "keyboard"), ["a/d"]) + self.assertIn("Now left.", spoken) + + def test_delete_removes_the_binding_pressed(self): + controls = self.make() + self.run_menu(controls, [key_down(pygame.K_DOWN), key_down(pygame.K_DOWN), key_down(pygame.K_DELETE)], + [key_down(pygame.K_SPACE)]) + self.assertEqual(controls.get_bindings("brake", "keyboard"), ["down"]) + + def test_reset_all_needs_enter_twice(self): + controls = self.make() + controls.set_bindings("horn", "pad", ["r1"]) + end = key_down(pygame.K_END) + up = key_down(pygame.K_UP) + enter = key_down(pygame.K_RETURN) + spoken = self.run_menu(controls, [end, up, enter]) + self.assertEqual(controls.get_bindings("horn", "pad"), ["r1"]) + self.assertEqual(spoken[-1], "Press Enter again to reset all controls.") + spoken = self.run_menu(controls, [end, up, enter, enter]) + self.assertEqual(controls.get_bindings("horn", "pad"), ["l1"]) + self.assertEqual(spoken[-1], "All controls reset to their defaults.") + + def test_rumble_options_change_and_are_felt(self): + controls = self.make() + end = key_down(pygame.K_END) + up = key_down(pygame.K_UP) + spoken = self.run_menu(controls, [end, up, up, up, key_down(pygame.K_LEFT), up, key_down(pygame.K_RETURN)]) + self.assertEqual(controls.rumbleStrength, 90) + self.assertFalse(controls.rumbleEnabled) + self.assertIn("Controller options. Reset all controls", spoken) + self.assertIn("Rumble strength, 90 percent", spoken) + self.assertEqual(spoken[-1], "Rumble, off") + self.assertEqual(len(self.pad.rumbles), 1) + + def test_escape_and_circle_leave(self): + controls = self.make() + circle = controls.translate_event(button_down("east")) + with patch.object(pygame.event, "wait", side_effect=[circle]), patch.object(pygame.event, "clear"): + self.menuModule.Speech = Mock() + self.menuModule.controls_menu({}, controls) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils.py b/utils.py index 3261a3f..ff0c56c 100644 --- a/utils.py +++ b/utils.py @@ -23,6 +23,7 @@ from .services import PathService, ConfigService, VolumeService from .sound import Sound from .speech import Speech from .scoreboard import Scoreboard +from .controls import Controls, translate_event, translate_events class Game: """Central class to manage all game systems.""" @@ -108,6 +109,9 @@ class Game: # Enable key repeat for volume controls pygame.key.set_repeat(500, 100) + # Listen to game controllers, so every menu works with one + Controls.get_instance().start() + # Load sound effects self.sound @@ -270,7 +274,7 @@ class Game: self.speech.speak(navText[currentIndex]) while True: - event = pygame.event.wait() + event = translate_event(pygame.event.wait()) if event.type == pygame.KEYDOWN: # Check for Alt modifier mods = pygame.key.get_mods() @@ -497,8 +501,10 @@ def x_powerbar(): pygame.draw.rect(screen, (255, 0, 0), (markerPos - 5, screen.get_height() // 2 - barHeight, 10, barHeight * 2)) pygame.display.flip() - for event in pygame.event.get(): - if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: + for event in translate_events(pygame.event.get()): + # Space, or cross on a controller + if event.type == pygame.KEYDOWN and (event.key == pygame.K_SPACE + or getattr(event, "button", None) == "south"): channel.stop() return position # This will return a value between -50 and 50 @@ -538,8 +544,10 @@ def y_powerbar(): pygame.draw.rect(screen, (255, 0, 0), (screen.get_width() // 2 - barWidth, markerPos - 5, barWidth * 2, 10)) pygame.display.flip() - for event in pygame.event.get(): - if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: + for event in translate_events(pygame.event.get()): + # Space, or cross on a controller + if event.type == pygame.KEYDOWN and (event.key == pygame.K_SPACE + or getattr(event, "button", None) == "south"): channel.stop() return power