"""Generated sound effects with graceful silent fallback. Audio is feedback only: it never alters game state or blocks input. The mixer is initialized at the application boundary; if init fails (no device, headless CI), self.enabled stays False and every call becomes a silent no-op. Sounds are built in memory from array.array tone samples matched to the mixer's format -- no asset files are loaded. """ from __future__ import annotations import array import math import pygame # name -> (frequency_hz, duration_ms, volume) _EFFECTS: dict[str, tuple[int, int, float]] = { "hit": (330, 60, 0.30), "miss": (150, 70, 0.18), "damage": (110, 130, 0.40), "pickup": (660, 70, 0.28), "stairs": (520, 120, 0.28), "levelup": (740, 170, 0.32), "death": (90, 280, 0.45), "victory": (880, 340, 0.38), } class Audio: def __init__(self) -> None: self.enabled: bool = False self.muted: bool = False self.sounds: dict = {} self._freq: int = 22050 self._size: int = -16 self._channels: int = 2 try: pygame.mixer.init() except Exception: return try: info = pygame.mixer.get_init() if info: self._freq, self._size, self._channels = info for name, spec in _EFFECTS.items(): try: snd = self._build_sound(*spec) except Exception: continue self.sounds[name] = snd self.enabled = bool(self.sounds) except Exception: self.enabled = False self.sounds = {} def _build_sound(self, freq_hz: int, dur_ms: int, volume: float): n = max(1, int(self._freq * dur_ms / 1000)) size = self._size channels = self._channels if abs(size) == 8: typecode = "b" if size < 0 else "B" peak = 127 zero = 0 if size < 0 else 128 signed = size < 0 else: # treat anything 16-bit-or-wider as signed 16-bit; mixer default. typecode = "h" peak = 32767 zero = 0 signed = True samples: list[int] = [] for i in range(n): t = i / self._freq env = max(0.0, 1.0 - i / n) wave = math.sin(2 * math.pi * freq_hz * t) * env * volume val = int(wave * peak) if signed else int(zero + wave * peak) samples.append(val) interleaved: list[int] = [] for v in samples: interleaved.extend([v] * channels) arr = array.array(typecode, interleaved) return pygame.mixer.Sound(buffer=arr.tobytes()) def play(self, name: str) -> None: 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) -> None: self.muted = not self.muted