"""Resilient generated sound effects. ``AudioEngine`` synthesizes a handful of short tones in memory (stdlib ``array`` written straight into a ``pygame.mixer.Sound`` buffer — no numpy, no asset files). It is constructed at the application boundary and is defensive at every step: if the mixer will not initialize (headless box, dummy driver, no device) or a single tone fails to build, audio is silently disabled and the game stays fully playable. The public API can never raise. Effect names: ``hit``, ``miss``, ``damage``, ``pickup``, ``stairs``, ``levelup``, ``death``, ``victory``. """ from __future__ import annotations import array import math __all__ = ["AudioEngine"] # (name, base_hz, duration_ms, volume, sweep_to_hz) # A gentle downward sweep reads as a "thud/hit", an upward chirp reads as # "pickup/levelup". Volumes are conservative so effects are quiet by default. _EFFECTS = { "hit": (220.0, 90, 0.28, 110.0), # quick down-sweep "miss": (330.0, 70, 0.18, 220.0), # soft blip "damage": (160.0, 160, 0.32, 70.0), # heavy thud "pickup": (520.0, 110, 0.26, 880.0), # rising chirp "stairs": (440.0, 180, 0.26, 660.0), "levelup": (523.0, 240, 0.30, 1046.0), # triumphant rise "death": (200.0, 480, 0.34, 60.0), # long fall "victory": (523.0, 520, 0.32, 1046.0), } class AudioEngine: """A best-effort, never-raising sound-effect player.""" def __init__(self) -> None: self.enabled: bool = False self.muted: bool = False self.sounds: dict = {} try: import pygame # local import keeps this importable without pygame except Exception: return # Initialize the mixer only if it has not been already. Any failure # (no device, dummy driver, denied) leaves audio disabled. try: if not pygame.mixer.get_init(): pygame.mixer.init() except Exception: self.enabled = False return fmt = None try: fmt = pygame.mixer.get_init() except Exception: fmt = None if not fmt: self.enabled = False return self.enabled = True try: self._build_all(pygame, fmt) except Exception: # A total build failure still leaves the engine usable (silent). self.sounds = {} # -- construction -------------------------------------------------------- def _build_all(self, pygame, fmt) -> None: freq, size, channels = fmt for name, (hz, ms, vol, end_hz) in _EFFECTS.items(): try: self.sounds[name] = self._make_tone(pygame, freq, size, channels, hz, end_hz, ms, vol) except Exception: # Skip the one bad tone; keep the rest. continue @staticmethod def _make_tone(pygame, freq: int, size: int, channels: int, start_hz: float, end_hz: float, ms: int, vol: float): """Render a swept, exponentially-decaying tone into a Sound buffer. Honors the mixer's signed-16-bit format (size == -16 or 16) and channel count (mono/stereo). Any other format falls back to signed 16-bit. """ n = max(1, int(freq * ms / 1000.0)) stereo = (channels or 1) >= 2 arr = array.array("h") sweep = (end_hz != start_hz) decay_tau = max(1.0, n / 3.0) # smooth exponential fade-out for i in range(n): t = i / freq frac = i / n hz = start_hz + (end_hz - start_hz) * frac if sweep else start_hz phase = 2.0 * math.pi * hz * t # Soft attack + exponential release to avoid clicks. env = (1.0 - math.exp(-i / max(1.0, n * 0.05))) * math.exp(-i / decay_tau) sample = int(max(-1.0, min(1.0, vol * env)) * 32767.0 * math.sin(phase)) arr.append(sample) if stereo: arr.append(sample) return pygame.mixer.Sound(buffer=arr.tobytes()) # -- public API ---------------------------------------------------------- def play(self, name: str) -> None: """Play ``name``; never raises. No-op when disabled or muted.""" if not self.enabled or self.muted: return snd = self.sounds.get(name) if snd is None: return try: snd.play() except Exception: pass def toggle_mute(self) -> bool: """Flip the mute flag and return the new state.""" self.muted = not self.muted return self.muted