BehaviorTreeFactory.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. this.dictionary.Add("not", config => new Not(config));
  14. }
  15. public void Register(string name, Func<Config, Node> action)
  16. {
  17. this.dictionary.Add(name, action);
  18. }
  19. private Node CreateNode(Config config)
  20. {
  21. if (!this.dictionary.ContainsKey(config.Name))
  22. {
  23. throw new KeyNotFoundException(string.Format("CreateNode cannot found: {0}",
  24. config.Name));
  25. }
  26. return this.dictionary[config.Name](config);
  27. }
  28. private Node CreateTreeNode(Config config)
  29. {
  30. var node = this.CreateNode(config);
  31. if (config.SubConfigs == null)
  32. {
  33. return node;
  34. }
  35. foreach (var subConfig in config.SubConfigs)
  36. {
  37. var subNode = this.CreateTreeNode(subConfig);
  38. node.AddChild(subNode);
  39. }
  40. return node;
  41. }
  42. public BehaviorTree CreateTree(Config config)
  43. {
  44. var node = this.CreateTreeNode(config);
  45. return new BehaviorTree(node);
  46. }
  47. }
  48. }