Sam 3a34759094
Some checks failed
Build Simulation and Test / Run All Tests (push) Failing after 8m17s
Add core simulation components and configuration classes
Major rewrite.
2025-11-08 19:17:40 -06:00

77 lines
2.5 KiB
Python

"""Simple event bus for decoupled component communication."""
from typing import Dict, List, Callable, Any
from dataclasses import dataclass
from enum import Enum
class EventType(Enum):
"""Types of simulation events."""
SIMULATION_STATE_CHANGED = "simulation_state_changed"
WORLD_TICK_COMPLETED = "world_tick_completed"
ENTITY_ADDED = "entity_added"
ENTITY_REMOVED = "entity_removed"
SELECTION_CHANGED = "selection_changed"
TIMING_UPDATE = "timing_update"
@dataclass
class Event:
"""Event data structure."""
type: EventType
data: Dict[str, Any]
timestamp: float = None
def __post_init__(self):
import time
if self.timestamp is None:
self.timestamp = time.time()
class EventBus:
"""Simple event bus for decoupled communication."""
def __init__(self):
self._subscribers: Dict[EventType, List[Callable]] = {}
self._event_history: List[Event] = []
self._max_history = 1000
def subscribe(self, event_type: EventType, callback: Callable[[Event], None]):
"""Subscribe to an event type."""
if event_type not in self._subscribers:
self._subscribers[event_type] = []
self._subscribers[event_type].append(callback)
def unsubscribe(self, event_type: EventType, callback: Callable[[Event], None]):
"""Unsubscribe from an event type."""
if event_type in self._subscribers:
try:
self._subscribers[event_type].remove(callback)
except ValueError:
pass
def publish(self, event: Event):
"""Publish an event to all subscribers."""
# Store in history
self._event_history.append(event)
if len(self._event_history) > self._max_history:
self._event_history.pop(0)
# Notify subscribers
if event.type in self._subscribers:
for callback in self._subscribers[event.type]:
try:
callback(event)
except Exception as e:
print(f"Error in event callback: {e}")
def get_recent_events(self, event_type: EventType = None, count: int = 10) -> List[Event]:
"""Get recent events, optionally filtered by type."""
events = self._event_history
if event_type:
events = [e for e in events if e.type == event_type]
return events[-count:]
def clear_history(self):
"""Clear event history."""
self._event_history.clear()