from __future__ import annotations import math from array import array import pygame SAMPLE_RATE: int = 22050 MASTER_VOLUME: float = 0.25 # name -> list of (freq_start, freq_end, milliseconds) _TONES: dict[str, list[tuple[float, float, int]]] = { "hit": [(240, 180, 70)], "crit": [(330, 200, 60), (500, 380, 80)], "miss": [(120, 90, 60)], "hurt": [(200, 90, 160)], "pickup": [(420, 640, 90)], "use": [(520, 520, 60), (700, 700, 70)], "stairs": [(400, 380, 90), (320, 300, 90), (250, 230, 110)], "level_up": [(330, 330, 80), (440, 440, 80), (550, 550, 120)], "death": [(160, 55, 500)], "victory": [(392, 392, 120), (494, 494, 120), (587, 587, 120), (784, 784, 260)], "menu": [(500, 500, 40)], } def generate_tone( freq_start: float, freq_end: float, milliseconds: int, volume: float = MASTER_VOLUME ) -> array: """Linear frequency sweep as signed 16-bit mono samples.""" count = max(1, SAMPLE_RATE * milliseconds // 1000) samples = array("h", bytes(2 * count)) phase = 0.0 for i in range(count): t = i / count freq = freq_start + (freq_end - freq_start) * t phase += 2.0 * math.pi * freq / SAMPLE_RATE envelope = 1.0 - t * 0.5 # gentle decay so blips never click hard samples[i] = int(32000 * volume * envelope * math.sin(phase)) return samples class SoundEffects: """In-memory generated effects. Any mixer failure degrades to silence.""" def __init__(self) -> None: self.enabled = False self.muted = False self._sounds: dict[str, pygame.mixer.Sound] = {} try: pygame.mixer.init(frequency=SAMPLE_RATE, size=-16, channels=1) for name, notes in _TONES.items(): samples = array("h") for freq_start, freq_end, ms in notes: samples.extend(generate_tone(freq_start, freq_end, ms)) self._sounds[name] = pygame.mixer.Sound(buffer=samples.tobytes()) self.enabled = True except Exception: # ponytail: mixer/mem format quirks vary by platform; silence is always safe self.enabled = False def play(self, name: str) -> None: if not self.enabled or self.muted: return sound = self._sounds.get(name) if sound is not None: try: sound.play() except pygame.error: pass def toggle_mute(self) -> bool: self.muted = not self.muted return self.muted if __name__ == "__main__": import os os.environ.setdefault("SDL_AUDIODRIVER", "dummy") pygame.init() effects = SoundEffects() assert effects.enabled, "dummy audio driver should initialize the mixer" for name in _TONES: effects.play(name) effects.toggle_mute() assert effects.muted effects.play("hit") # must be silent, not crash # Forced mixer failure degrades to a fully-disabled, playable game. class _Broken: @staticmethod def init(**kwargs): raise pygame.error("no audio device") original = pygame.mixer.init pygame.mixer.init = _Broken.init try: broken = SoundEffects() finally: pygame.mixer.init = original assert not broken.enabled and not broken.play("hit") pygame.quit() print("audio self-check: PASS")