156 lines
5.5 KiB
Python
156 lines
5.5 KiB
Python
from __future__ import annotations
|
|
|
|
import array
|
|
import math
|
|
from typing import Final
|
|
|
|
import pygame
|
|
|
|
from data.constants import AUDIO_SAMPLE_RATE, AUDIO_TONES
|
|
|
|
_SIZE_CODES: Final = {8: ("b", "B"), 16: ("h", "H"), 32: ("i", "I")}
|
|
|
|
|
|
def sound_for_message(message: str) -> str | None:
|
|
"""Map one log line to an effect key; None when the line stays silent."""
|
|
if message.startswith(("You hit", "Critical hit!")):
|
|
return "hit"
|
|
if "misses you" in message or message.startswith("You miss"):
|
|
return "miss"
|
|
if "hits you" in message or "scorched" in message:
|
|
return "hurt"
|
|
if message.startswith(("You pick up", "You quaff", "You read", "You equip")):
|
|
return "pickup"
|
|
if message.startswith("You descend to floor"):
|
|
return "stairs"
|
|
if message.startswith("You reach level"):
|
|
return "levelup"
|
|
if message.startswith("You died"):
|
|
return "death"
|
|
if message.startswith("You slew the Ancient Dragon"):
|
|
return "victory"
|
|
return None
|
|
|
|
|
|
class Audio:
|
|
"""Tiny in-memory tone synth over pygame.mixer.
|
|
|
|
Every failure mode — no device, odd mixer format, tone build error —
|
|
degrades to silence. Audio is feedback only and never touches game state.
|
|
"""
|
|
|
|
def __init__(self, sample_rate: int = AUDIO_SAMPLE_RATE) -> None:
|
|
self.sample_rate = sample_rate
|
|
self.muted = False
|
|
self.available = False
|
|
self._sounds: dict[str, pygame.mixer.Sound] = {}
|
|
|
|
def init(self) -> bool:
|
|
try:
|
|
if pygame.mixer.get_init() is None:
|
|
pygame.mixer.init(frequency=self.sample_rate, size=-16, channels=1)
|
|
spec = pygame.mixer.get_init()
|
|
sounds: dict[str, pygame.mixer.Sound] = {}
|
|
if spec is not None:
|
|
for name, tone in AUDIO_TONES.items():
|
|
sound = self._build(spec, *tone)
|
|
if sound is not None:
|
|
sounds[name] = sound
|
|
self._sounds = sounds
|
|
self.available = bool(sounds)
|
|
except Exception:
|
|
# boundary: any mixer failure means silent play, never a crash
|
|
self.available = False
|
|
self._sounds = {}
|
|
return self.available
|
|
|
|
def _build(
|
|
self,
|
|
spec: tuple[int, int, int],
|
|
frequency: int,
|
|
duration: float,
|
|
volume: float,
|
|
) -> pygame.mixer.Sound | None:
|
|
rate, size, channels = spec
|
|
codes = _SIZE_CODES.get(abs(size))
|
|
if codes is None or rate <= 0 or channels <= 0:
|
|
return None
|
|
code = codes[0] if size < 0 else codes[1]
|
|
peak = (1 << (abs(size) - 1)) - 1
|
|
bias = 0 if size < 0 else peak + 1
|
|
total = int(rate * duration)
|
|
if total <= 0:
|
|
return None
|
|
fade = max(1, total // 20)
|
|
samples = array.array(code)
|
|
for index in range(total):
|
|
envelope = min(1.0, index / fade, (total - 1 - index) / fade)
|
|
value = int(
|
|
bias
|
|
+ volume
|
|
* peak
|
|
* envelope
|
|
* math.sin(2 * math.pi * frequency * index / rate)
|
|
)
|
|
for _ in range(channels):
|
|
samples.append(value)
|
|
try:
|
|
return pygame.mixer.Sound(buffer=samples.tobytes())
|
|
except Exception:
|
|
return None
|
|
|
|
def play(self, effect: str) -> bool:
|
|
if self.muted or not self.available:
|
|
return False
|
|
sound = self._sounds.get(effect)
|
|
if sound is None:
|
|
return False
|
|
try:
|
|
sound.play()
|
|
return True
|
|
except Exception:
|
|
return False
|
|
|
|
def toggle_mute(self) -> bool:
|
|
self.muted = not self.muted
|
|
return self.muted
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Run from the repo root: python -m engine.audio
|
|
assert sound_for_message("You hit the Goblin for 8 damage!") == "hit"
|
|
assert sound_for_message("Critical hit! You hit the Orc for 24 damage!") == "hit"
|
|
assert sound_for_message("You miss the Goblin") == "miss"
|
|
assert sound_for_message("Goblin misses you") == "miss"
|
|
assert sound_for_message("Goblin hits you for 5 damage!") == "hurt"
|
|
assert sound_for_message("You are scorched for 15 damage!") == "hurt"
|
|
assert sound_for_message("You pick up the Healing Potion.") == "pickup"
|
|
assert sound_for_message("You quaff the Strength Potion.") == "pickup"
|
|
assert sound_for_message("You equip the Hunter's Bow.") == "pickup"
|
|
assert sound_for_message("You descend to floor 3.") == "stairs"
|
|
assert sound_for_message("You reach level 2! (HP +10, Power +1)") == "levelup"
|
|
assert sound_for_message("You died on floor 4. You reached level 3.") == "death"
|
|
assert (
|
|
sound_for_message("You slew the Ancient Dragon! You conquered Underdepths.")
|
|
== "victory"
|
|
)
|
|
assert sound_for_message("The Green Slime splits into 2 smaller slimes!") is None
|
|
|
|
real_init = pygame.mixer.init
|
|
|
|
def refuse(*args: object, **kwargs: object) -> None:
|
|
raise pygame.error("forced failure")
|
|
|
|
pygame.mixer.init = refuse # type: ignore[assignment]
|
|
broken = Audio()
|
|
assert broken.init() is False and broken.available is False
|
|
assert broken.play("hit") is False # silent, not fatal
|
|
assert broken.toggle_mute() is True
|
|
pygame.mixer.init = real_init # type: ignore[assignment]
|
|
|
|
live = Audio()
|
|
started = live.init()
|
|
assert live.available == started
|
|
live.play("hit") # must be safe on audio and audio-less machines alike
|
|
print(f"audio self-check: PASS (mixer available: {started})")
|