# SPDX-License-Identifier: MIT """The controller ports and the standard pad. DOC: fullsnes "SNES Controllers I/O Ports - Manual Reading" and "SNES Controllers Joypad": the pad is a 16-bit shift register latched by the strobe line (``$4016`` bit 0, shared by both ports) and clocked by each read of its data line; the order is B, Y, Select, Start, Up, Down, Left, Right, A, X, L, R, then four ID bits (0000 for the pad), then 1s. """ from __future__ import annotations # Bit positions in the 16-bit report, first-out bit first (DOC: fullsnes). BUTTONS = ("B", "Y", "SELECT", "START", "UP", "DOWN", "LEFT", "RIGHT", "A", "X", "L", "R") class Gamepad: """A standard SNES pad on one port.""" def __init__(self) -> None: self.pressed: set[str] = set() self._shift = 0 self._latched = False def report(self) -> int: """The 16 bits, first-out in bit 15.""" value = 0 for i, name in enumerate(BUTTONS): if name in self.pressed: value |= 0x8000 >> i return value def latch(self, level: bool) -> None: """Drive the strobe line; while high the register reloads continuously.""" if level: self._shift = self.report() self._latched = level def data(self) -> int: """Clock one bit out: data lines 0 and 1 (line 1 unused by the pad). DOC: after 16 bits the pad shifts in 1s (fullsnes "Joypad"). While the strobe is high the first bit (B) is read each time. """ if self._latched: return (self.report() >> 15) & 1 bit = (self._shift >> 15) & 1 self._shift = (self._shift << 1 | 1) & 0xFFFF return bit class NoController: """An empty port: the data lines read 0 (DOC: fullsnes, "no controller").""" def latch(self, level: bool) -> None: pass def data(self) -> int: return 0 __all__ = ["BUTTONS", "Gamepad", "NoController"]