Files
mrgameeng/src/MrGameEng.Simulation/AI/Blackboard.cs
T

51 lines
2.0 KiB
C#

namespace MrGameEng.AI;
/// <summary>
/// A small typed key/value store for an agent's working memory: perceived facts, a current target, a
/// cached path goal — whatever the considerations and actions need to share without being threaded
/// through method signatures. Keys are case-sensitive strings; values are stored boxed, so the
/// blackboard is a convenience for cold paths (perception, planning), not the per-frame hot loop.
/// </summary>
public sealed class Blackboard
{
private readonly Dictionary<string, object?> _values = new(StringComparer.Ordinal);
/// <summary>The number of keys currently stored.</summary>
public int Count => _values.Count;
/// <summary>Stores <paramref name="value"/> under <paramref name="key"/>, replacing any existing entry.</summary>
public void Set<T>(string key, T value) => _values[key] = value;
/// <summary>
/// Reads the value under <paramref name="key"/> as <typeparamref name="T"/>. Returns <c>false</c> when
/// the key is missing or holds a value of a different type.
/// </summary>
public bool TryGet<T>(string key, out T value)
{
if (_values.TryGetValue(key, out var stored) && stored is T typed)
{
value = typed;
return true;
}
value = default!;
return false;
}
/// <summary>
/// Reads the value under <paramref name="key"/>, or returns <paramref name="fallback"/> when the key is
/// missing or holds a different type.
/// </summary>
public T GetOrDefault<T>(string key, T fallback = default!) =>
TryGet<T>(key, out var value) ? value : fallback;
/// <summary>True when <paramref name="key"/> has a value (of any type).</summary>
public bool Has(string key) => _values.ContainsKey(key);
/// <summary>Removes <paramref name="key"/>. Returns true when it was present.</summary>
public bool Remove(string key) => _values.Remove(key);
/// <summary>Drops every stored value.</summary>
public void Clear() => _values.Clear();
}