diff --git a/src/BehaviourTree.FluentBuilder.Tests/BehaviourTreeExpressionPrinter.cs b/src/BehaviourTree.FluentBuilder.Tests/BehaviourTreeExpressionPrinter.cs index 2e4271c..a879ab9 100644 --- a/src/BehaviourTree.FluentBuilder.Tests/BehaviourTreeExpressionPrinter.cs +++ b/src/BehaviourTree.FluentBuilder.Tests/BehaviourTreeExpressionPrinter.cs @@ -1,11 +1,11 @@ -using System; -using System.Linq; +using System.Linq; using System.Text; +using BehaviourTree; using BehaviourTree.Behaviours; using BehaviourTree.Composites; using BehaviourTree.Decorators; -namespace BehaviourTree +namespace BehaviourTreeBuilder.Tests { public sealed class BehaviourTreeExpressionPrinter : IVisitor>, diff --git a/src/BehaviourTree/BehaviourTreeConsoleLogger.cs b/src/BehaviourTree/BehaviourTreeConsoleLogger.cs new file mode 100644 index 0000000..0c0dd38 --- /dev/null +++ b/src/BehaviourTree/BehaviourTreeConsoleLogger.cs @@ -0,0 +1,113 @@ +using System; +using System.Linq; +using BehaviourTree.Behaviours; +using BehaviourTree.Composites; +using BehaviourTree.Decorators; + +namespace BehaviourTree +{ + public sealed class BehaviourTreeConsoleLogger : + IVisitor>, + IVisitor>, + IVisitor>, + IVisitor>, + IVisitor> + where TContext : IClock + { + private int _depth; + + public void Visit(IBehaviour obj) + { + Visit((dynamic)obj); + } + + public void Visit(Condition obj) + { + PrintNode(obj); + } + + public void Visit(BaseBehaviour obj) + { + PrintNode(obj); + } + + public void Visit(CompositeBehaviour obj) + { + PrintNode(obj); + VisitChildren(obj); + } + + public void Visit(DecoratorBehaviour obj) + { + PrintNode(obj); + VisitChild(obj); + } + + private void VisitChildren(CompositeBehaviour obj) + { + _depth++; + + foreach (var child in obj.Children) + { + child.Accept(this); + } + + _depth--; + } + + private void VisitChild(DecoratorBehaviour obj) + { + _depth++; + + obj.Child.Accept(this); + + _depth--; + } + + private void PrintNode(IBehaviour obj) + { + var indentation = GetIndentation(); + var name = GetName(obj); + var color = GetColor(obj.Status); + + Console.ForegroundColor = color; + + var nodeExpression = $"{indentation}{name}"; + + Console.WriteLine(nodeExpression); + + Console.ResetColor(); + } + + private static ConsoleColor GetColor(BehaviourStatus status) + { + switch (status) + { + case BehaviourStatus.Ready: return ConsoleColor.Blue; + case BehaviourStatus.Running: return ConsoleColor.Gray; + case BehaviourStatus.Succeeded: return ConsoleColor.Green; + case BehaviourStatus.Failed: return ConsoleColor.Red; + default: throw new ArgumentOutOfRangeException(nameof(status), status, null); + } + } + + private string GetIndentation() + { + return string.Join(string.Empty, Enumerable.Repeat(" ", _depth)); + } + + private static string GetName(IBehaviour obj) + { + if (!string.IsNullOrWhiteSpace(obj.Name)) + { + return obj.Name; + } + + var type = obj.GetType(); + + // TODO: check for generic + + return type.Name; + } + } +}