# SPDX-License-Identifier: MIT """``a2600-play``: the board in a window (pygame-ce), for playing and for looking. A host, not part of the specification (charter "The tiers": windows run a tier, they do not define behaviour): it reads the keyboard and mouse into the controllers of controllers.py and savekey.py, runs the board a frame at a time, shows the television's frames through a palette (palettes.py), and plays the TIA's samples. The board is the reference, correct and not fast (about 15 % of real time on PyPy): the window shows what it gets, and the sound gaps between frames. Headless judging: run with ``SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy`` and ``--frames N --screenshot out.png``; the window then exits after N frames. Keys: arrows and Space for the left joystick (Space also fires a Driving controller, whose knob is Left/Right; Z and X are a Booster Grip's pins 5 and 9); I J K L and Right Shift for the right joystick; the mouse's x is paddle 0 (left button its fire) when paddles are in; keypads are 1 2 3 / Q W E / A S D / Z X C (left) and the numeric keypad (right). F1 Game Select, F2 Game Reset, F3 colour / black-and-white, F4 and F5 the left and right difficulty switches, Escape quits. """ from __future__ import annotations import argparse import os import sys from pathlib import Path from .controllers import BoosterGrip, DrivingController, Joystick, Keypads, Paddles from .machine import MACHINES from .palettes import PALETTES from .savekey import SaveKey, default_path from .system import System from .television import Television, frame_rgb # Host settings, not hardware behaviour: no evidence tag applies. AUDIO_RATE = 44_100 LEFT_DEVICES = ("joystick", "paddles", "driving", "booster", "keypad", "none") RIGHT_DEVICES = ("joystick", "paddles", "keypad", "savekey", "none") def _parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser(prog="a2600-play", description=__doc__.split("\n\n")[0]) p.add_argument("rom", type=Path) p.add_argument("--machine", default="ntsc", choices=("ntsc", "pal", "secam")) p.add_argument("--scheme", help="bank-switching scheme (default: identified)") p.add_argument("--left", default="joystick", choices=LEFT_DEVICES) p.add_argument("--right", default="joystick", choices=RIGHT_DEVICES) p.add_argument("--savekey-file", type=Path, help=f"default {default_path()}") p.add_argument("--palette", choices=sorted(PALETTES), help="default: the machine's") p.add_argument("--phosphor", action="store_true", help="blend each frame with the last") p.add_argument("--scale", type=int, default=3) p.add_argument("--mute", action="store_true") p.add_argument("--frames", type=int, help="stop after this many frames") p.add_argument("--screenshot", type=Path, help="save the last frame shown here on exit") return p class Controls: """The keyboard and mouse, read into the plugged-in devices.""" def __init__(self, system: System, left: str, right: str, savekey_file: Path) -> None: tia, riot = system.board.tia, system.board.riot clock = system.machine.timing.colour_clock_hz self.riot = riot self.paddles = ( Paddles(tia, clock) if "paddles" in (left, right) or left == "booster" else None ) self.keypads = Keypads(tia, riot) if "keypad" in (left, right) else None self.left_kind, self.right_kind = left, right self.left = { "joystick": lambda: Joystick(tia, riot, 0), "driving": lambda: DrivingController(tia, riot, 0), "booster": lambda: BoosterGrip(tia, riot, self.paddles, 0), }.get(left, lambda: None)() self.right = Joystick(tia, riot, 1) if right == "joystick" else None self.savekey = ( SaveKey(riot, system.machine.timing.cpu_hz, path=savekey_file) if right == "savekey" else None ) if self.paddles is not None: for i, kind in ((0, left), (2, right)): if kind == "paddles": self.paddles.position[i] = self.paddles.position[i + 1] = 0.5 def update(self, pg, keys, mouse_x: float, mouse_down: bool) -> None: k = pg if self.left_kind == "joystick": self.left.set( up=keys[k.K_UP], down=keys[k.K_DOWN], left=keys[k.K_LEFT], right=keys[k.K_RIGHT], fire=keys[k.K_SPACE], ) # fmt: skip elif self.left_kind == "driving": self.left.turn(keys[k.K_RIGHT] - keys[k.K_LEFT]) self.left.press(bool(keys[k.K_SPACE])) elif self.left_kind == "booster": self.left.set( up=keys[k.K_UP], down=keys[k.K_DOWN], left=keys[k.K_LEFT], right=keys[k.K_RIGHT], fire=keys[k.K_SPACE], pin5=keys[k.K_z], pin9=keys[k.K_x], ) # fmt: skip if self.right is not None: self.right.set( up=keys[k.K_i], down=keys[k.K_k], left=keys[k.K_j], right=keys[k.K_l], fire=keys[k.K_RSHIFT], ) # fmt: skip if self.paddles is not None and "paddles" in (self.left_kind, self.right_kind): # Paddle buttons are SWCHA D7 and D6 (left pair), D3 and D2 (right) (DOC: nocash). first = 0 if self.left_kind == "paddles" else 2 self.paddles.position[first] = 1.0 - mouse_x bit = 0x80 if first == 0 else 0x08 riot = self.riot riot.set_input_a(riot.input_a & ~bit if mouse_down else riot.input_a | bit) if self.keypads is not None: rows = ( (k.K_1, k.K_2, k.K_3), (k.K_q, k.K_w, k.K_e), (k.K_a, k.K_s, k.K_d), (k.K_z, k.K_x, k.K_c), ) # fmt: skip pad = ( (k.K_KP7, k.K_KP8, k.K_KP9), (k.K_KP4, k.K_KP5, k.K_KP6), (k.K_KP1, k.K_KP2, k.K_KP3), (k.K_KP_MULTIPLY, k.K_KP0, k.K_KP_DIVIDE), ) # fmt: skip for port, table in ((0, rows), (1, pad)): if (self.left_kind, self.right_kind)[port] == "keypad": self.keypads.pressed[port].clear() for r, row in enumerate(table): for c, key in enumerate(row): if keys[key]: self.keypads.pressed[port].add((r, c)) def _resample(samples: list[float], rate_in: float, phase: float) -> tuple[bytes, float]: """Linear resampling of ``samples`` (0..1) to AUDIO_RATE, as signed 16-bit mono.""" out = bytearray() step = rate_in / AUDIO_RATE t = phase n = len(samples) while t < n - 1: i = int(t) f = t - i v = samples[i] * (1 - f) + samples[i + 1] * f s = round((v - 0.5) * 32000) out += s.to_bytes(2, "little", signed=True) t += step return bytes(out), t - (n - 1) def main(argv: list[str] | None = None) -> int: args = _parser().parse_args(argv) try: import pygame except ImportError: print("a2600-play needs pygame-ce: pip install 'a2600-python[play]'", file=sys.stderr) return 2 options = {"scheme": args.scheme} if args.scheme else {} machine = MACHINES[f"Atari VCS ({args.machine.upper()})"] system = System.from_rom(args.rom, machine, **options) tv = Television(system.board.tia) controls = Controls(system, args.left, args.right, args.savekey_file or default_path()) palette = PALETTES[args.palette or machine.palette] rate_in = 2 * machine.timing.colour_clock_hz / 228 # two audio ticks a line pygame.init() sound = not args.mute and os.environ.get("SDL_AUDIODRIVER") != "dummy" if sound: pygame.mixer.init(AUDIO_RATE, -16, 1, 2048) channel = pygame.mixer.Channel(0) width, height = 160 * 2 * args.scale, 240 * args.scale screen = pygame.display.set_mode((width, height)) pygame.display.set_caption(f"a2600-play: {args.rom.name}") phase = 0.0 last: list[bytes] | None = None shown = None frames = 0 riot = system.board.riot running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE ): running = False elif event.type == pygame.KEYDOWN: toggles = {pygame.K_F3: 0x08, pygame.K_F4: 0x40, pygame.K_F5: 0x80} if event.key in toggles: riot.input_b ^= toggles[event.key] keys = pygame.key.get_pressed() # SWCHB D0 Game Reset, D1 Game Select: 0 while held (DOC: Stella Programmer's Guide). riot.input_b = (riot.input_b | 0x03) & ~( (0x01 if keys[pygame.K_F2] else 0) | (0x02 if keys[pygame.K_F1] else 0) ) mx, _ = pygame.mouse.get_pos() controls.update(pygame, keys, min(max(mx / width, 0.0), 1.0), pygame.mouse.get_pressed()[0]) system.run_frames(1) frames += 1 samples = system.board.tia.audio.take_samples() if sound and len(samples) > 1: data, phase = _resample(samples, rate_in, phase) if not channel.get_queue(): channel.queue(pygame.mixer.Sound(buffer=data)) frame = tv.frame if frame: rows = frame_rgb(frame[:240], palette) if args.phosphor and last is not None and len(last) == len(rows): rows = [ bytes((a + b) >> 1 for a, b in zip(r, p, strict=True)) for r, p in zip(rows, last, strict=True) ] last = rows image = pygame.image.frombuffer(b"".join(rows), (160, len(rows)), "RGB") shown = pygame.transform.scale(image, (width, len(rows) * args.scale)) screen.fill((0, 0, 0)) screen.blit(shown, (0, 0)) pygame.display.flip() if args.frames is not None and frames >= args.frames: running = False if args.screenshot and shown is not None: pygame.image.save(shown, str(args.screenshot)) pygame.quit() return 0 if __name__ == "__main__": sys.exit(main())