Source file unity-csharp/game-ai/goap/WorldState.cs from the GDnD code examples. Download raw file
// GDnD wiki example
// Demonstrates: GOAP world state as a set of named bool facts (missing fact = false)
// Related pages: [[goal-oriented-action-planning]], [[behaviour-trees-vs-goap]]
using System.Collections.Generic;
using System.Linq;
// A world state is just "fact name -> true/false". The planner copies these,
// applies action effects to the copies, and checks whether a goal is met.
public class WorldState
{
private readonly Dictionary<string, bool> facts = new();
public WorldState() { }
public WorldState(WorldState other) { facts = new Dictionary<string, bool>(other.facts); }
public void CopyFrom(WorldState other)
{
facts.Clear();
foreach (var f in other.facts) facts[f.Key] = f.Value;
}
public bool Get(string fact) => facts.TryGetValue(fact, out bool value) && value;
public void Set(string fact, bool value) => facts[fact] = value;
// True when every condition (e.g. an action's preconditions or a goal) holds here.
public bool Satisfies(Dictionary<string, bool> conditions) =>
conditions.All(c => Get(c.Key) == c.Value);
// How many conditions are NOT yet met: the planner's heuristic.
public int CountUnmet(Dictionary<string, bool> conditions) =>
conditions.Count(c => Get(c.Key) != c.Value);
// A stable text key ("HasAxe,HasWood") so the planner can spot states it has already seen.
public string Key() =>
string.Join(",", facts.Where(f => f.Value).Select(f => f.Key).OrderBy(k => k));
public override string ToString() => "{" + Key() + "}";
}