sevenx_engine 0.2.11

Engine de jogos 2D/3D completa com suporte Android, física, áudio, partículas, tilemap, UI, eventos e sistema 3D avançado com PBR.
Documentation
use std::collections::HashMap;

/// Tipos de eventos customizáveis.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EventType {
    PlayerDied,
    EnemyKilled,
    CoinCollected,
    LevelComplete,
    GameOver,
    Custom(String),
}

/// Dados do evento.
#[derive(Debug, Clone)]
pub struct EventData {
    pub event_type: EventType,
    pub data: HashMap<String, String>,
}

impl EventData {
    pub fn new(event_type: EventType) -> Self {
        Self {
            event_type,
            data: HashMap::new(),
        }
    }

    pub fn with_data(mut self, key: &str, value: &str) -> Self {
        self.data.insert(key.to_string(), value.to_string());
        self
    }

    pub fn get(&self, key: &str) -> Option<&String> {
        self.data.get(key)
    }
}

/// Callback para eventos.
pub type EventCallback = Box<dyn FnMut(&EventData)>;

/// Sistema de eventos.
pub struct EventSystem {
    listeners: HashMap<EventType, Vec<EventCallback>>,
    event_queue: Vec<EventData>,
}

impl EventSystem {
    pub fn new() -> Self {
        Self {
            listeners: HashMap::new(),
            event_queue: Vec::new(),
        }
    }

    /// Registra um listener para um tipo de evento.
    pub fn on<F>(&mut self, event_type: EventType, callback: F)
    where
        F: FnMut(&EventData) + 'static,
    {
        self.listeners
            .entry(event_type)
            .or_insert_with(Vec::new)
            .push(Box::new(callback));
    }

    /// Emite um evento imediatamente.
    pub fn emit(&mut self, event: EventData) {
        if let Some(callbacks) = self.listeners.get_mut(&event.event_type) {
            for callback in callbacks {
                callback(&event);
            }
        }
    }

    /// Adiciona um evento à fila para processamento posterior.
    pub fn queue(&mut self, event: EventData) {
        self.event_queue.push(event);
    }

    /// Processa todos os eventos na fila.
    pub fn process_queue(&mut self) {
        let events: Vec<EventData> = self.event_queue.drain(..).collect();
        for event in events {
            self.emit(event);
        }
    }

    /// Remove todos os listeners de um tipo de evento.
    pub fn clear_listeners(&mut self, event_type: &EventType) {
        self.listeners.remove(event_type);
    }

    /// Remove todos os listeners.
    pub fn clear_all_listeners(&mut self) {
        self.listeners.clear();
    }
}

impl Default for EventSystem {
    fn default() -> Self {
        Self::new()
    }
}