# SPDX-License-Identifier: MIT """``lynx-play``: a window for the board (pygame-ce), a host, not a specification. lynx-play CART [--machine lynx2] [--scale 3] [--rotation left|right|none] [--flip] [--eeprom TYPE[:ORG]] [--mute] [--frames N] What the host does, and the board's numbers it uses (charter: hosts run a tier and do not define behaviour): - Picture: each finished frame (Display.rgb) turned for the cart's rotation field (lynx_python.picture: right = a quarter turn clockwise) and scaled. ``--flip`` turns it half a turn and swaps the direction keys, for a left-handed player of a game without its own flip; a game's own flip (DISPCTL bit 1, SPRSYS Lefthand) is the game's drawing and is shown as drawn (C11: a host that also flips doubles it). - Pace: the frame period the board measures (Display.frame_period, ticks of 16 MHz), not a fixed 60 Hz; the window shows it. - Sound: Mikey's 32 kHz stereo samples (Mikey.mix), queued as they are made. - Input: arrows = joypad, Z = A (outer), X = B (inner), 1 / 2 = Option 1 / 2, Enter = Pause; Escape closes. - The cart's EEPROM is saved under ``$XDG_DATA_HOME/lynx-python/eeprom/``. No human has looked at this window yet: it is judged headless (``scripts/m8_frontend.py``, SDL's dummy drivers): window pixels against the board's frames, queued sound against the board's samples, the pace against the measured period, seeded faults. """ from __future__ import annotations import argparse import sys import time from pathlib import Path from lynx_python.__main__ import boot, run_frames from lynx_python.cart import load from lynx_python.machine import MACHINES from lynx_python.mikey import SAMPLE_RATE from lynx_python.mikey.display import HEIGHT, WIDTH TICKS_PER_SECOND = 16_000_000 # JOYSTICK bits as Suzy stores them (DOC Appx 2, Lefthand = 1 column; Suzy swaps the # directions for a game running with Lefthand = 0): up, down, left, right, option 1, # option 2, inner (B), outer (A). SWITCHES bit 0 = pause. UP, DOWN, LEFT, RIGHT, OPTION1, OPTION2, INNER, OUTER = 0x80, 0x40, 0x20, 0x10, 8, 4, 2, 1 class Host: """The window, the sound queue and the pace around one board.""" def __init__(self, cart: Path, machine: str = "lynx2", scale: int = 3, rotation: str | None = None, flip: bool = False, eeprom: str | None = None, audio: bool = True) -> None: # fmt: skip import pygame self.pygame = pygame overrides = {"eeprom": eeprom} if eeprom else None self.description = load(cart, overrides=overrides) self.board = boot(cart, machine, self.description) self.rotation = rotation or self.description.rotation self.flip = flip self.scale = scale turned = self.rotation in ("left", "right") self.size = (HEIGHT, WIDTH) if turned else (WIDTH, HEIGHT) pygame.display.init() self.window = pygame.display.set_mode((self.size[0] * scale, self.size[1] * scale)) pygame.display.set_caption(f"lynx-play: {self.description.name}") self.audio = audio self.channel = None self.sent = 0 # samples (left and right counted separately) handed to the mixer if audio: pygame.mixer.init(frequency=SAMPLE_RATE, size=-16, channels=2, buffer=1024) self.channel = pygame.mixer.Channel(0) self.board.mikey.start_audio(self.board.tick) self.frame_interval = 0.0 self.queued: list[bytes] = [] # for the headless judge: every buffer queued # -- one frame ------------------------------------------------------------------------ def step(self, keys: int = 0, pause: bool = False) -> None: board = self.board board.suzy.joystick = self._turn_keys(keys) board.suzy.switches = (board.suzy.switches & ~1) | (1 if pause else 0) run_frames(board, 1) self.present() if self.audio: self.queue_audio() period = board.mikey.display.frame_period if period: self.frame_interval = period / TICKS_PER_SECOND # the board's measured period def _turn_keys(self, keys: int) -> int: if not self.flip: return keys swapped = keys & 0x0F swapped |= UP if keys & DOWN else 0 swapped |= DOWN if keys & UP else 0 swapped |= LEFT if keys & RIGHT else 0 swapped |= RIGHT if keys & LEFT else 0 return swapped def frame_surface(self): """The board's last frame as a surface turned for the cart (and the flip).""" pygame = self.pygame rgb = self.board.mikey.display.rgb() surface = pygame.image.frombuffer(rgb, (WIDTH, HEIGHT), "RGB") angle = {"right": -90, "left": 90}.get(self.rotation, 0) # pygame: anticlockwise if self.flip: angle += 180 if angle % 360: surface = pygame.transform.rotate(surface, angle) return surface def present(self) -> None: pygame = self.pygame surface = self.frame_surface() if self.scale != 1: surface = pygame.transform.scale(surface, self.window.get_size()) self.window.blit(surface, (0, 0)) pygame.display.flip() def queue_audio(self) -> None: samples = self.board.mikey.samples new = samples[self.sent :] if not len(new): return self.sent = len(samples) data = new.tobytes() if sys.byteorder == "little" else _swapped(new) self.queued.append(data) sound = self.pygame.mixer.Sound(buffer=data) if self.channel.get_busy(): self.channel.queue(sound) else: self.channel.play(sound) # -- the loop --------------------------------------------------------------------------- def run(self, frames: int = 0) -> None: pygame = self.pygame keymap = { pygame.K_UP: UP, pygame.K_DOWN: DOWN, pygame.K_LEFT: LEFT, pygame.K_RIGHT: RIGHT, pygame.K_1: OPTION1, pygame.K_2: OPTION2, pygame.K_x: INNER, pygame.K_z: OUTER, } # fmt: skip keys = 0 pause = False count = 0 due = time.perf_counter() while not frames or count < frames: for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE ): return if event.type in (pygame.KEYDOWN, pygame.KEYUP): down = event.type == pygame.KEYDOWN if event.key == pygame.K_RETURN: pause = down elif event.key in keymap: keys = keys | keymap[event.key] if down else keys & ~keymap[event.key] self.step(keys, pause) count += 1 if self.frame_interval: pygame.display.set_caption( f"lynx-play: {self.description.name} ({1 / self.frame_interval:.2f} Hz)" ) due += self.frame_interval wait = due - time.perf_counter() if wait > 0: time.sleep(wait) else: due = time.perf_counter() # behind real time: do not try to catch up def _swapped(samples) -> bytes: copy = samples[:] copy.byteswap() return copy.tobytes() def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--machine", default="lynx2", choices=sorted(MACHINES)) parser.add_argument("--scale", type=int, default=3) parser.add_argument("--rotation", choices=("none", "left", "right")) parser.add_argument("--flip", action="store_true", help="turn half a turn for left hands") parser.add_argument("--eeprom", help="override the cart's EEPROM: none or TYPE[:ORG]") parser.add_argument("--mute", action="store_true") parser.add_argument("--frames", type=int, default=0, help="stop after N frames (0: never)") args = parser.parse_args(argv) host = Host(args.cart, args.machine, args.scale, args.rotation, args.flip, args.eeprom, audio=not args.mute) # fmt: skip host.run(args.frames) return 0 if __name__ == "__main__": sys.exit(main())