forked from Shardstone/trail-into-darkness
36 lines
1.3 KiB
C#
36 lines
1.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Jovian.EncounterSystem {
|
|
/// <summary>Dispatches <see cref="IEncounterEvent"/> instances to per-type handlers. Unknown types are skipped.</summary>
|
|
public class EncounterResolver {
|
|
private readonly Dictionary<Type, Action<IEncounterEvent, EncounterContext>> handlers = new();
|
|
|
|
public void Register<T>(Action<T, EncounterContext> handler) where T : IEncounterEvent {
|
|
// Wrap the typed delegate so the dictionary can hold handlers for any event type uniformly.
|
|
// Cast is safe because the wrapper is only invoked via lookup under typeof(T).
|
|
handlers[typeof(T)] = (evt, ctx) => handler((T)evt, ctx);
|
|
}
|
|
|
|
public void Unregister<T>() where T : IEncounterEvent {
|
|
handlers.Remove(typeof(T));
|
|
}
|
|
|
|
public void Resolve(IEnumerable<IEncounterEvent> events, EncounterContext context) {
|
|
if(events == null) {
|
|
return;
|
|
}
|
|
|
|
foreach(var evt in events) {
|
|
if(evt == null) {
|
|
continue;
|
|
}
|
|
|
|
if(handlers.TryGetValue(evt.GetType(), out var handler)) {
|
|
handler(evt, context);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|