Added the system from trail
This commit is contained in:
49
Runtime/EncounterResolver.cs
Normal file
49
Runtime/EncounterResolver.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Jovian.EncounterSystem {
|
||||
/// <summary>
|
||||
/// Dispatches <see cref="IEncounterEvent"/> instances (authored on dialog options) to per-type
|
||||
/// handlers registered at composition time. Unknown event types are silently skipped.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The resolver stores handlers keyed by concrete event <see cref="Type"/>. Registration wraps a
|
||||
/// typed delegate in a closure that casts back to the concrete type — the cast is safe because
|
||||
/// we only ever invoke the wrapped delegate via the dictionary lookup under the same key.
|
||||
/// </remarks>
|
||||
public class EncounterResolver {
|
||||
private readonly Dictionary<Type, Action<IEncounterEvent, EncounterContext>> handlers = new();
|
||||
|
||||
/// <summary>Register a handler for a concrete event type. Replaces any prior registration.</summary>
|
||||
/// <typeparam name="T">The event type to handle.</typeparam>
|
||||
/// <param name="handler">The delegate invoked with the cast event and the resolution context.</param>
|
||||
public void Register<T>(Action<T, EncounterContext> handler) where T : IEncounterEvent {
|
||||
handlers[typeof(T)] = (evt, ctx) => handler((T)evt, ctx);
|
||||
}
|
||||
|
||||
/// <summary>Remove the handler registered for event type <typeparamref name="T"/>, if any.</summary>
|
||||
public void Unregister<T>() where T : IEncounterEvent {
|
||||
handlers.Remove(typeof(T));
|
||||
}
|
||||
|
||||
/// <summary>Dispatch each event in <paramref name="events"/> to its registered handler, in order.
|
||||
/// Null events and events with no registered handler are skipped.</summary>
|
||||
/// <param name="events">The ordered event list (typically from an <see cref="EncounterDialogOption"/>).</param>
|
||||
/// <param name="context">Per-resolution context passed to every handler.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user