BehaviorTreeFactory.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. namespace BehaviorTree
  4. {
  5. public class BehaviorTreeFactory
  6. {
  7. private readonly Dictionary<string, Func<Config, Node>> dictionary =
  8. new Dictionary<string, Func<Config, Node>>();
  9. public BehaviorTreeFactory()
  10. {
  11. this.dictionary.Add("selector", config => new Selector(config));
  12. this.dictionary.Add("sequence", config => new Sequence(config));
  13. }
  14. public void Register(string name, Func<Config, Node> action)
  15. {
  16. this.dictionary.Add(name, action);
  17. }
  18. private Node CreateNode(Config config)
  19. {
  20. if (!this.dictionary.ContainsKey(config.Name))
  21. {
  22. throw new KeyNotFoundException(string.Format("CreateNode cannot found: {0}", config.Name));
  23. }
  24. return this.dictionary[config.Name](config);
  25. }
  26. public BehaviorTree CreateTree(Config config)
  27. {
  28. var node = this.CreateNode(config);
  29. if (config.SubConfigs == null)
  30. {
  31. return new BehaviorTree(node);
  32. }
  33. foreach (var subConfig in config.SubConfigs)
  34. {
  35. var subNode = this.CreateNode(subConfig);
  36. node.AddChild(subNode);
  37. }
  38. return new BehaviorTree(node);
  39. }
  40. }
  41. }