Загрузить файлы в «/»
This commit is contained in:
122
sound_manager.py
Normal file
122
sound_manager.py
Normal file
@@ -0,0 +1,122 @@
|
||||
|
||||
|
||||
import pygame
|
||||
|
||||
from typing import List, Dict
|
||||
|
||||
|
||||
|
||||
class SoundManager:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
pygame.mixer.init()
|
||||
|
||||
self.sounds = {}
|
||||
|
||||
self.music_volume = 0.5
|
||||
|
||||
self.sound_volume = 0.7
|
||||
|
||||
self.visual_effects = []
|
||||
|
||||
|
||||
|
||||
def handle_events(self, sound_events: List[Dict]) -> List[Dict]:
|
||||
|
||||
self.visual_effects = []
|
||||
|
||||
for event in sound_events:
|
||||
|
||||
self.play_sound(event.get('type'))
|
||||
|
||||
return self.visual_effects
|
||||
|
||||
|
||||
|
||||
def play_sound(self, event_name: str) -> None:
|
||||
|
||||
if event_name not in self.sounds:
|
||||
|
||||
self._load_sound(event_name)
|
||||
|
||||
|
||||
|
||||
sound = self.sounds.get(event_name)
|
||||
|
||||
if sound:
|
||||
|
||||
sound.set_volume(self.sound_volume)
|
||||
|
||||
sound.play()
|
||||
|
||||
|
||||
|
||||
self._create_visual_effect(event_name)
|
||||
|
||||
|
||||
|
||||
def set_volume(self, levels: Dict[str, float]) -> None:
|
||||
|
||||
self.music_volume = levels.get('music', self.music_volume)
|
||||
|
||||
self.sound_volume = levels.get('sound', self.sound_volume)
|
||||
|
||||
pygame.mixer.music.set_volume(self.music_volume)
|
||||
|
||||
|
||||
|
||||
def _load_sound(self, event_name: str) -> None:
|
||||
|
||||
sound_paths = {
|
||||
|
||||
'unit_attack': 'sounds/attack.wav',
|
||||
|
||||
'building_complete': 'sounds/building_complete.wav',
|
||||
|
||||
'unit_selected': 'sounds/select.wav',
|
||||
|
||||
'resource_gathered': 'sounds/gather.wav',
|
||||
|
||||
'error': 'sounds/error.wav'
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
path = sound_paths.get(event_name)
|
||||
|
||||
if path:
|
||||
|
||||
try:
|
||||
|
||||
self.sounds[event_name] = pygame.mixer.Sound(path)
|
||||
|
||||
except pygame.error:
|
||||
|
||||
print(f"Failed to load sound: {path}")
|
||||
|
||||
self.sounds[event_name] = None
|
||||
|
||||
|
||||
|
||||
def _create_visual_effect(self, event_name: str) -> None:
|
||||
|
||||
effect_map = {
|
||||
|
||||
'unit_attack': {'type': 'flash', 'color': (255, 0, 0), 'duration': 0.2},
|
||||
|
||||
'building_complete': {'type': 'sparkle', 'color': (0, 255, 0), 'duration': 1.0},
|
||||
|
||||
'resource_gathered': {'type': 'glow', 'color': (255, 255, 0), 'duration': 0.5}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
effect = effect_map.get(event_name)
|
||||
|
||||
if effect:
|
||||
|
||||
self.visual_effects.append(effect)
|
||||
|
||||
Reference in New Issue
Block a user