BehaviorTreeFactory.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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}", config.Name));
  24. }
  25. return this.dictionary[config.Name](config);
  26. }
  27. private Node CreateTreeNode(Config config)
  28. {
  29. var node = this.CreateNode(config);
  30. if (config.SubConfigs == null)
  31. {
  32. return node;
  33. }
  34. foreach (var subConfig in config.SubConfigs)
  35. {
  36. var subNode = this.CreateTreeNode(subConfig);
  37. node.AddChild(subNode);
  38. }
  39. return node;
  40. }
  41. public BehaviorTree CreateTree(Config config)
  42. {
  43. var node = this.CreateTreeNode(config);
  44. return new BehaviorTree(node);
  45. }
  46. }
  47. }