made some improvements on how the encounters trigger

This commit is contained in:
Sebastian Bularca
2026-05-22 13:47:44 +02:00
parent 8aea6f7eb3
commit dd049642b0
8 changed files with 174 additions and 58 deletions

View File

@@ -2,13 +2,12 @@ using System;
using System.Collections.Generic;
namespace Jovian.EncounterSystem {
/// <summary>Dispatches <see cref="IEncounterEvent"/> instances to per-type handlers. Unknown types are skipped.</summary>
/// <summary>Dispatches <see cref="IEncounterEvent"/> instances to per-type handlers.
/// Handlers return <c>true</c> to stop processing remaining events.</summary>
public class EncounterResolver {
private readonly Dictionary<Type, Action<IEncounterEvent, EncounterContext>> handlers = new();
private readonly Dictionary<Type, Func<IEncounterEvent, EncounterContext, bool>> 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).
public void Register<T>(Func<T, EncounterContext, bool> handler) where T : IEncounterEvent {
handlers[typeof(T)] = (evt, ctx) => handler((T)evt, ctx);
}
@@ -17,22 +16,26 @@ namespace Jovian.EncounterSystem {
}
/// <summary>Indexed iteration over <paramref name="events"/> — avoids the boxed enumerator
/// that an <c>IEnumerable&lt;T&gt;</c> parameter would force. <see cref="EncounterDialogOption.events"/>
/// is a <c>List</c>, which implements <c>IReadOnlyList</c>, so call sites just pass it directly.</summary>
/// that an <c>IEnumerable&lt;T&gt;</c> parameter would force. Stops when a handler
/// returns <c>true</c> or <see cref="EncounterContext.ShouldStopEvents"/> is set.</summary>
public void Resolve(IReadOnlyList<IEncounterEvent> events, EncounterContext context) {
if(events == null) {
return;
}
var count = events.Count;
for(int i = 0; i < count; i++) {
for(var i = 0; i < count; i++) {
var evt = events[i];
if(evt == null) {
if(evt == null || context.ShouldStopEvents) {
continue;
}
if(handlers.TryGetValue(evt.GetType(), out var handler)) {
handler(evt, context);
if(!handlers.TryGetValue(evt.GetType(), out var handler)) {
continue;
}
if(handler(evt, context)) {
context.ShouldStopEvents = true;
}
}
}