예제 #1
0
        public void TestParallel2()
        {
            IParent node = new ParallelNode(true);

            node.Add(new Coroutine(() => _Step(3, true)));
            node.Add(new Coroutine(() => _Step(2, false)));
            node.Add(new Coroutine(() => _Step(1, false)));

            var r1 = node.Tick(0);
            var r2 = node.Tick(0);
            var r3 = node.Tick(0);
            var r4 = node.Tick(0);
            var r5 = node.Tick(0);


            var r6  = node.Tick(0);
            var r7  = node.Tick(0);
            var r8  = node.Tick(0);
            var r9  = node.Tick(0);
            var r10 = node.Tick(0);

            Assert.AreEqual(r1, TICKRESULT.RUNNING);
            Assert.AreEqual(r2, TICKRESULT.RUNNING);
            Assert.AreEqual(r3, TICKRESULT.RUNNING);
            Assert.AreEqual(r4, TICKRESULT.RUNNING);
            Assert.AreEqual(r5, TICKRESULT.FAILURE);
            Assert.AreEqual(r6, TICKRESULT.RUNNING);
            Assert.AreEqual(r7, TICKRESULT.RUNNING);
            Assert.AreEqual(r8, TICKRESULT.RUNNING);
            Assert.AreEqual(r9, TICKRESULT.RUNNING);
            Assert.AreEqual(r10, TICKRESULT.FAILURE);
        }
        public static void Parallel <TTickData, TState>(
            this BehaviourTreeNodeDecoratorBuilder <TTickData, TState> builder, string name, int successCount, int failureCount,
            Action <BehaviourTreeNodeSequenceBuilder <TTickData, TState> > config)
        {
            var newNode = new ParallelNode <TTickData, TState>(name, successCount, failureCount);

            builder.Decorate(newNode, config);
        }
        public static BehaviourTreeNodeSequenceBuilder <TTickData, TState> Parallel <TTickData, TState>(
            this BehaviourTreeNodeSequenceBuilder <TTickData, TState> builder, string name, int successCount, int failureCount,
            Action <BehaviourTreeNodeSequenceBuilder <TTickData, TState> > config)
        {
            var newNode = new ParallelNode <TTickData, TState>(name, successCount, failureCount);

            return(builder.Add(newNode, config));
        }
예제 #4
0
        /// <summary>
        /// Create a parallel node.
        /// </summary>
        public BehaviorTreeBuilder Parallel()
        {
            var parallelNode = new ParallelNode(rootNode);

            parentNodeStack.Peek().AddChild(parallelNode);
            parentNodeStack.Push(parallelNode);

            return(this);
        }
예제 #5
0
        private static void ParseNodeParallel(ScriptProgram scriptProgram, Node root, TokenStream stream)
        {
            var node = new ParallelNode();

            root.AddChildNode(node);

            ParseNodeChildren(scriptProgram, node, stream);

            //throw new NotImplementedException("TODO Check node parameters and parse the children");
        }
예제 #6
0
    public static ParallelNode Create(params QueryPlanNode[] nodes)
    {
        var parallel = new ParallelNode();

        foreach (QueryPlanNode node in nodes)
        {
            parallel.AddNode(node);
        }
        return(parallel);
    }
예제 #7
0
        public void Execution(IEnumerable <IBehaviourTreeNode <int, int> > nodes, int successCount, int failureCount, BehaviourTreeState expectedState)
        {
            var parallelNode = new ParallelNode <int, int>("test", successCount, failureCount);

            foreach (var node in nodes)
            {
                parallelNode.AddNode(node);
            }

            var func = parallelNode.Compile();

            Assert.Equal(expectedState, func(1, 1));
        }
예제 #8
0
        /// <summary>
        /// Create a parallel node.
        /// </summary>
        public BehaviourTreeBuilder Parallel(int numRequiredToFail, int numRequiredToSucceed)
        {
            AssertCanModify();
            var name = _idGenerator.GetId(typeof(ParallelNode));

            var parallelNode = new ParallelNode(name, numRequiredToFail, numRequiredToSucceed);

            if (_parentNodeStack.Count > 0)
            {
                _parentNodeStack.Peek().AddChild(parallelNode);
            }

            _parentNodeStack.Push(parallelNode);
            return(this);
        }
        Result CreateParallel(int s, int f, int p, int e, int u, params Result [] args)
        {
            IContext ctx = new SimpleContext();

            Node root = new ParallelNode("Root", null, s, f, p, e, u);

            foreach (var arg in args)
            {
                root.Children.Add(new AlwaysCmd(arg));
            }

            var ret = root.Tick(ctx);

            return(ret);
        }
예제 #10
0
        public override void OnRefresh()
        {
            // 窗口打开动画
            if (_isPlayOpenAnimation == false)
            {
                _isPlayOpenAnimation = true;
                ITweenNode tween = ParallelNode.Allocate(
                    _animRectTrans.transform.TweenScaleTo(0.8f, Vector3.one).SetEase(TweenEase.Bounce.EaseOut),
                    _animRectTrans.transform.TweenAnglesTo(0.4f, new Vector3(0, 0, 720))
                    );
                TweenGrouper.Play(tween);
            }

            // 闪烁动画
            TweenGrouper.Play(_animImg.TweenColor(0.5f, Color.green, Color.red).SetLoop(ETweenLoop.PingPong));
        }
예제 #11
0
    public void SwithControlNode(int type, ref BaseNode node)
    {
        switch (type)
        {
        case 1:
            node = new SelectNode();
            break;

        case 2:
            node = new SequenceNode();
            break;

        case 3:
            node = new ParallelNode();
            break;
        }
    }
        Node AddParallel(Random r)
        {
            var c = r.Next() % 5;

            c++;
            var n = new ParallelNode(RandomName("Name", r),
                                     null,
                                     r.Next() % 3,
                                     r.Next() % 3,
                                     r.Next() % 3,
                                     r.Next() % 3,
                                     r.Next() % 3);

            for (int i = 0; i < c; i++)
            {
                AddDecoratorOrLeaf(n, r);
            }
            return(n);
        }
예제 #13
0
        public void Compilation(IEnumerable <IBehaviourTreeNode <int, int> > nodes, bool success)
        {
            var parallelNode = new ParallelNode <int, int>("test", 1, 1);

            foreach (var node in nodes)
            {
                parallelNode.AddNode(node);
            }

            if (success)
            {
                var func = parallelNode.Compile();

                Assert.NotNull(func);
            }
            else
            {
                Assert.Throws <BehaviourTreeCompilationException>(() => parallelNode.Compile());
            }
        }
예제 #14
0
        public static Node MakeRootNode(Node root)
        {
            if (root == null)
            {
                root = ParallelNode.New("Root", ParallelNode.Operator.OR, null);
            }
            root.Clear();

            root.AddNodes(
                LastFirstSelectorNode.New("Action")
                .AddNodes(
                    LastFirstSelectorNode.New("Alive Actions", new PreconditionIsDead(false))
                    .AddNodes(
                        PlayerActionNode.New("Attack", PlayerActionType.Cast, new PreconditionIsNodeAction()),
                        PlayerActionNode.New("Hit", PlayerActionType.Hit, new PreconditionIsNodeAction())
                        )
                    ),
                LastFirstSelectorNode.New("Posture")
                .AddNodes(
                    LastFirstSelectorNode.New("In Air + Gravity",
                                              new PreconditionAnd(
                                                  new PreconditionIsOnGround(false),
                                                  new PreconditionIsGravityEnabled(true)
                                                  ))
                    .AddNodes(
                        PlayerPostureNode.New("Falling Alive", PlayerPosture.FallingAlive, new PreconditionIsDead(false)),
                        PlayerPostureNode.New("Falling Dead", PlayerPosture.FallingDead, new PreconditionIsDead(true))
                        ),
                    LastFirstSelectorNode.New("On Ground", new PreconditionIsOnGround(true))
                    .AddNodes(
                        PlayerPostureNode.New("Empty", PlayerPosture.Empty, new PreconditionIsNodePosture()),
                        PlayerPostureNode.New("Idle", PlayerPosture.Idle, new PreconditionIsNodePosture()),
                        PlayerPostureNode.New("Running", PlayerPosture.Running, new PreconditionIsNodePosture()),
                        PlayerPostureNode.New("Dead", PlayerPosture.Dead, new PreconditionIsNodePosture())
                        )
                    )
                );
            return(root);
        }
예제 #15
0
    protected override ITask GetBrain()
    {
        SequentialNode wander = SequentialNode.Create(2)
                                .Load(new MoveToRandom())
                                .Load(new WaitForNavStrict());

        ParallelNode wanderControl = ParallelNode.Create(2, CompletionPolicy.Any)
                                     .Load(new UntilUserControlled())
                                     .Load(wander);

        mUserControl = new ManualController();

        PrioritySelector main = PrioritySelector.Create(2)
                                .Load(IsUserControlled.Instance, mUserControl)
                                .Load(TrueCondition.Instance, wanderControl);

        SequentialNode root = SequentialNode.Create(2)
                              .Load(new SetUseCrowd(true))
                              .Load(main);

        ITask result = new KeepActive(root);

        return(result);
    }
예제 #16
0
 void Init(int numRequiredToFail = 0, int numRequiredToSucceed = 0)
 {
     testObject = new ParallelNode("some-parallel", numRequiredToFail, numRequiredToSucceed);
 }
예제 #17
0
 /// <summary>
 /// clone
 /// </summary>
 /// <returns></returns>
 public IBehaviourNode Clone()
 {
     var behaviourNode = new ParallelNode();
     base.CopyToCompositeNode(behaviourNode);
     return behaviourNode;
 }
예제 #18
0
    void Start()
    {
        _behaviorTreeController = new BehaviorTreeController();

        // rootとなるSequencer
        SequencerNode rootNode = new SequencerNode();

        rootNode.name = "rootノード";

        // 出発
        ActionNode departure = new ActionNode();

        departure.name = "出発する";
        departure.SetRunningFunc(() => {
            Debug.LogError("出発");
            return(NodeStatus.SUCCESS);
        });

        // HP確認のDecorator
        DecoratorNode confirmationHp = new DecoratorNode();

        confirmationHp.name = "HP確認するのDecorator";
        confirmationHp.SetConditionFunc(() => {
            return(_myHp >= 100 ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // 敵に寄る
        ActionNode enemyApproach = new ActionNode();

        enemyApproach.name = "敵に寄るアクションノード";
        enemyApproach.SetRunningFunc(() => {
            Debug.LogError("敵に寄る");
            return(NodeStatus.SUCCESS);
        });

        // HP確認のDecoratorの子供登録
        confirmationHp.AddChild(enemyApproach);

        // 友達2人を呼ぶParallelNode
        ParallelNode callFriendAB = new ParallelNode();

        callFriendAB.name = "友達2人を呼ぶParallelNode";

        // 友達A
        ActionNode friendA = new ActionNode();

        friendA.name = "友達Aを呼ぶ";
        friendA.SetRunningFunc(() => {
            Debug.LogError("友達A");
            return(NodeStatus.SUCCESS);
        });

        // 友達B
        ActionNode friendB = new ActionNode();

        friendB.name = "友達Bを呼ぶ";
        friendB.SetRunningFunc(() => {
            Debug.LogError("友達B");
            return(NodeStatus.SUCCESS);
        });

        // 友達2人を呼ぶParallelNodeの子供登録
        callFriendAB.AddChild(friendA);
        callFriendAB.AddChild(friendB);

        // スキルを繰り返し行うRepeaterNode
        RepeaterNode skillRepeater = new RepeaterNode();

        skillRepeater.name = "スキルを繰り返し行うRepeaterNode";

        // スキルを選択するSelector
        SelectorNode selectSkill = new SelectorNode();

        selectSkill.name = "スキルを選択するSelector";

        // スキルAの発動を確認するDecorator
        DecoratorNode triggerSkillA = new DecoratorNode();

        triggerSkillA.name = "スキルAの発動を確認するDecorator";
        triggerSkillA.SetConditionFunc(() => {
            int probability = Mathf.Clamp(probabilitySkillA, 0, 100);
            int random      = Random.Range(0, 100);
            return(probability > random ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // スキルA
        ActionNode skillA = new ActionNode();

        skillA.name = "skillA";
        skillA.SetRunningFunc(() => {
            Debug.LogError("skillA");
            _enemyHp -= 50;
            return(NodeStatus.SUCCESS);
        });

        // スキルAの発動を確認するDecoratorの子供登録
        triggerSkillA.AddChild(skillA);


        // スキルB
        ActionNode skillB = new ActionNode();

        skillB.name = "skillB";
        skillB.SetRunningFunc(() => {
            Debug.LogError("skillB");
            _enemyHp -= 60;
            return(NodeStatus.SUCCESS);
        });

        // スキルを選択するSelectorの子供登録
        selectSkill.AddChild(triggerSkillA);
        selectSkill.AddChild(skillB);

        // スキルを繰り返し行うRepeaterNodeの子供登録
        skillRepeater._repeatNum = 2;
        skillRepeater.AddChild(selectSkill);

        // 敵の生存を確認するSelector
        SelectorNode enemySurvial = new SelectorNode();

        enemySurvial.name = "敵の生存を確認するSelector";

        // 敵が死んでいるか確認するDecorator
        DecoratorNode enemyDied = new DecoratorNode();

        enemyDied.name = "敵が死んでいるか確認するDecorator";
        enemyDied.SetConditionFunc(() => {
            return(_enemyHp <= 0 ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // 敵が死んでいる
        ActionNode died = new ActionNode();

        died.name = "敵が死んでいる";
        died.SetRunningFunc(() => {
            Debug.LogError("End1");
            Debug.LogError("EnemyHp : " + _enemyHp);
            return(NodeStatus.SUCCESS);
        });

        // 敵が死んでいるか確認するDecoratorの子供登録
        enemyDied.AddChild(died);

        // 敵が生きているか確認するDecorator
        DecoratorNode enemyAlive = new DecoratorNode();

        enemyAlive.name = "敵が生きているか確認するDecorator";
        enemyAlive.SetConditionFunc(() => {
            return(_enemyHp > 0 ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // 敵が生きている
        ActionNode alive = new ActionNode();

        alive.name = "敵が生きている";
        alive.SetRunningFunc(() => {
            Debug.LogError("End2");
            Debug.LogError("EnemyHp : " + _enemyHp);
            return(NodeStatus.SUCCESS);
        });

        // 敵が生きているか確認するDecoratorの子供登録
        enemyAlive.AddChild(alive);

        // 敵の生存を確認するSelectorの子供登録
        enemySurvial.AddChild(enemyDied);
        enemySurvial.AddChild(enemyAlive);


        // rootノードの子供登録
        rootNode.AddChild(departure);
        rootNode.AddChild(confirmationHp);
        rootNode.AddChild(callFriendAB);
        rootNode.AddChild(skillRepeater);
        rootNode.AddChild(enemySurvial);

        // ツリー実行
        _behaviorTreeController.Initialize(rootNode);
        _behaviorTreeController.OnStart();
    }
예제 #19
0
 public BehaviourTreeParallelBuilder(TFinalizeResult parent, ParallelNode <TBlackboard> group)
 {
     _parent = parent;
     _group  = group;
 }
예제 #20
0
        private static Node ConstuctNode(BinaryReader br, Guid id, NodeType nodeType, CommandType commandType)
        {
            //Console.WriteLine(nodeType);
            switch (nodeType)
            {
            case NodeType.Script:
            {
                var scriptNode = new ScriptNode();
                scriptNode.Id = id;
                scriptNode.readData(br);
                return(scriptNode);
            }

            case NodeType.Page:
            {
                var pageNode = new PageNode();
                pageNode.Id = id;
                pageNode.readData(br);
                return(pageNode);
            }

            case NodeType.OnceOnly:
            {
                var onceOnly = new OnceOnlyNode();
                onceOnly.Id = id;
                onceOnly.readData(br);
                return(onceOnly);
            }

            case NodeType.ConditionalTrue:
            {
                var node = new ConditionalTrueNode();
                node.Id = id;
                node.readData(br);
                return(node);
            }

            case NodeType.ConditionalFalse:
            {
                var node = new ConditionalFalseNode();
                node.Id = id;
                node.readData(br);
                return(node);
            }

            case NodeType.OptionsChoice:
            {
                var node = new ShowOptionsNode();
                node.Id = id;
                node.readData(br);
                return(node);
            }

            case NodeType.Option:
            {
                var node = new OptionNode();
                node.Id = id;
                node.readData(br);
                return(node);
            }

            case NodeType.ParallelNode:
            {
                var node = new ParallelNode();
                node.Id = id;
                node.readData(br);
                return(node);
            }

            case NodeType.BlockNode:
            {
                var node = new BlockNode();
                node.Id = id;
                node.readData(br);
                return(node);
            }

            case NodeType.Command:
            {
                switch (commandType)
                {
                case CommandType.Say:
                {
                    var command = new SayNode();
                    command.Id = id;
                    command.readData(br);
                    return(command);
                }

                case CommandType.CallPage:
                {
                    var command = new CallPageNode();
                    command.Id = id;
                    command.readData(br);
                    return(command);
                }

                case CommandType.Return:
                {
                    var command = new ReturnNode();
                    command.Id = id;
                    command.readData(br);
                    return(command);
                }

                case CommandType.Wait:
                {
                    var command = new WaitNode();
                    command.Id = id;
                    command.readData(br);
                    return(command);
                }

                case CommandType.Print:
                {
                    var command = new PrintNode();
                    command.Id = id;
                    command.readData(br);
                    return(command);
                }

                default:
                    throw new Exception("Unhandled Node Type:" + nodeType + ":" + commandType);
                }
            }

            // case NodeType.Say
            default:
                throw new Exception("Unhandled Node Type:" + nodeType);
            }
            return(null);
        }
예제 #21
0
    void GenerateBehaviors()
    {
        Animator a = GetAnimator();

        ////////////////////////////////// Movement //////////////////////////////////

        EvadeNode     evade     = new EvadeNode(this.rB, speed, 0.4f, 25);
        IsBlockedNode isBlocked = new IsBlockedNode(transform, evade, 1, 1);
        MoveNode      move      = new MoveNode(rB, target, speed, atkRange);

        SequenceNode evading = new SequenceNode(new List <Node>()
        {
            isBlocked, evade
        });
        SelectorNode movement = new SelectorNode(new List <Node>()
        {
            evading, move
        });

        ////////////////////////////////// Death //////////////////////////////////

        HealthCheckNode         isDead              = new HealthCheckNode(this, 0, true);
        ClampSuccessNode        isDeadClamped       = new ClampSuccessNode(isDead);
        AnimationNode           deathAnim           = new AnimationNode(a, "Die");
        OnAnimationCompleteNode onDeathAnimComplete = new OnAnimationCompleteNode(a, "Die");
        DestroyNode             destroy             = new DestroyNode(this.gameObject);

        SequenceNode death = new SequenceNode(new List <Node> {
            isDeadClamped, deathAnim, onDeathAnimComplete, destroy
        });

        ////////////////////////////////// Cover //////////////////////////////////

        HealthCheckNode   isLow         = new HealthCheckNode(this, consideredLowHP, true);
        SoundNode         hurtSFX       = new SoundNode(Sound.SeaMonsterHurt);
        RandomNode        chanceHurtSFX = new RandomNode(hurtSFX, 0.4f);
        ColorFlashNode    hurtFlash     = new ColorFlashNode(GetMaterial(), Color.red, 3, 1);
        RecoverHealthNode hpRecover     = new RecoverHealthNode(this, hpRecoveryMultiplier);
        FindCover         findCover     = new FindCover(this, target, 10);

        SequenceNode hurting = new SequenceNode(new List <Node>()
        {
            chanceHurtSFX, hurtFlash
        });
        SequenceNode recovering = new SequenceNode(new List <Node>()
        {
            hpRecover, hurting
        });
        SequenceNode covering = new SequenceNode(new List <Node>()
        {
            findCover, movement
        });
        ParallelNode recoveringAndCovering = new ParallelNode(new List <Node>()
        {
            recovering, covering
        }, 2);

        SequenceNode cover = new SequenceNode(new List <Node>()
        {
            isLow, recoveringAndCovering
        });

        ////////////////////////////////// Attack //////////////////////////////////

        // Condition To Start Attack Sequence
        IsInRangeNode isInATKRange = new IsInRangeNode(atkRange, transform, target);

        // Attack Sequence
        AnimationNode readyUpAnim = new AnimationNode(a, "Aim");
        LookNode      aim         = new LookNode(rB, target, 1, 12, 7);
        AnimationNode strikeAnim  = new AnimationNode(a, "Fire");
        TimerNode     atkTimer    = new TimerNode(1);

        // Wrapping Nodes
        SequenceNode attackPattern = new SequenceNode(new List <Node>()
        {
            readyUpAnim, aim, strikeAnim, atkTimer
        });
        ResetOnStateNode resetATK  = new ResetOnStateNode(attackPattern, NodeState.SUCCESS);
        SequenceNode     attacking = new SequenceNode(new List <Node>()
        {
            isInATKRange, resetATK
        });
        SelectorNode attack = new SelectorNode(new List <Node>()
        {
            attacking, movement
        });


        ////////////////////////////////// Patrol //////////////////////////////////

        PatrolNode   patrolMove     = new PatrolNode(rB, Mathf.RoundToInt(speed * 0.7f), 0.5f, 6, 20, 1.5f, 4);
        SelectorNode evadeAndPatrol = new SelectorNode(new List <Node>()
        {
            evading, patrolMove
        });

        SpotTargetNode spotTarget = new SpotTargetNode(transform, 40, 80, LayerMask.NameToLayer("Target"), LayerMask.NameToLayer("Enemy"));

        FlagNode      flag          = new FlagNode(NodeState.SUCCESS, NodeState.FAILURE);
        FlagActivator flagActivator = new FlagActivator(flag);

        SequenceNode spotAndStop = new SequenceNode(new List <Node>()
        {
            spotTarget, flagActivator
        });

        SelectorNode patroling = new SelectorNode(new List <Node>()
        {
            spotAndStop, evadeAndPatrol
        });
        SequenceNode patrol = new SequenceNode(new List <Node>()
        {
            flag, patroling
        });

        ////////////////////////////////// Top Node //////////////////////////////////

        topNode = new Tree(new SelectorNode(new List <Node>()
        {
            death, cover, patrol, attack
        }));

        BehaviorTreeManager.AddTree(topNode);
    }