Beispiel #1
0
		public void Setup()
		{
			_customer = new Customer {Preferred = true};

			_actionNode = new ActionNode<Customer>(x => Trace.WriteLine("Called for " + x.Element.Object.Preferred));

			_constantNode = new ConstantNode<Customer>();

			_agenda = new PriorityQueueAgenda();

			_context = MockRepository.GenerateMock<RuleContext<Customer>>();
			var element = MockRepository.GenerateMock<SessionElement<Customer>>();
			element.Stub(x => x.Object).Return(_customer);
			_context.Stub(x => x.Element).Return(element);

			_context.Expect(x => x.EnqueueAgendaAction(0, null))
				.IgnoreArguments()
				.Repeat.AtLeastOnce()
				.WhenCalled(invocation =>
					{
						var priority = (int) invocation.Arguments[0];
						var action = invocation.Arguments[1] as Action;

						_agenda.Add(priority, action);
					});
		}
 public NodeLinkedList()
 {
     last = new DoNothingNode();
     first = new DoNothingNode();
     first.Next = last;
     last.Prev = first;
 }
        public virtual void WriteCode(TemplateContext ctx, ActionNode node)
        {
            var varStatement = ctx.CurrentDeclaration._private_(node.Meta.FullName, node.VarName);
            varStatement.InitExpression = new CodeObjectCreateExpression(node.Meta.FullName);

            foreach (var item in node.GraphItems.OfType<IActionIn>())
            {
                var contextVariable = item.Item;
                if (contextVariable == null)
                    continue;
                ctx._("{0}.{1} = {2}", varStatement.Name, item.Name, item.VariableName);
            }


            ctx._("{0}.System = System", varStatement.Name);


            foreach (var item in node.GraphItems.OfType<ActionBranch>())
            {
                var branchOutput = item.OutputTo<SequenceItemNode>();
                if (branchOutput == null) continue;
                if (DebugSystem.IsDebugMode)
                    ctx._("{0}.{1} = ()=> {{ System.StartCoroutine({2}()); }}", varStatement.Name, item.Name, item.VariableName);
                else
                    ctx._("{0}.{1} = {2}", varStatement.Name, item.Name, item.VariableName);
            }

            ctx._("{0}.Execute()", varStatement.Name);

            node.WriteActionOutputs(ctx);
        }
Beispiel #4
0
 public JumpNode(ActionNode partner)
 {
     if(partner != null) {
         this.jumpNode = partner;
     } else {
         throw new Exception("JumpNode needs something to jump to.");
     }
 }
 public void Add(ActionNode node)
 {
     ActionNode foreLast = last.Prev;
     last.Prev = node;
     node.Next = last;
     foreLast.Next = node;
     node.Prev = foreLast;
 }
 public void dequeue()
 {
     if (head.previous != null) {
         head = head.previous;
         head.next = null;
         return;
     }
     head = tail = null;
 }
 public void enqueue(string funcname, Transform target)
 {
     ActionNode temp = new ActionNode (funcname, target, tail);
     if (tail != null)
         tail.previous = temp;
     tail = temp;
     if (head == null)
         head = tail;
 }
Beispiel #8
0
		public void Building_a_agenda_from_the_consequence_rocks()
		{
			var context = MockRepository.GenerateMock<RuleContext<Customer>>();
			context.Expect(x => x.EnqueueAgendaAction(0, null)).IgnoreArguments();

			Action<int> action = null;
			action = MockRepository.GenerateMock<Action<int>>();
			var actionNode = new ActionNode(() => action(27));

			actionNode.Activate(context);

			context.VerifyAllExpectations();
		}
Beispiel #9
0
        public void ActionTick()
        {
            var node = new ActionNode<NumberTestNode>( ()=> new NumberTestNode(3)
                , (ntn) => ntn.Tick
                , (ntn) => ntn.Start
                , (ntn) => ntn.End);
            ITicker ticker = node;
            var result1 = ticker.Tick(0);
            ticker.Tick(0);
            var result2 = ticker.Tick(0);
            var result3 = ticker.Tick(0);

            Assert.AreEqual(TICKRESULT.RUNNING , result1);
            Assert.AreEqual(TICKRESULT.SUCCESS, result2);
            Assert.AreEqual(TICKRESULT.FAILURE, result3);
        }
Beispiel #10
0
        /// <summary>
        /// Selects an Item.
        /// <param name="item">The item to be selected.</param>
        /// </summary>
        void SelecteItem(Item item)
        {
            m_SelectedItem   = item;
            m_SelectedScript = item as Script;

            if (m_SelectedScript != null)
            {
                m_NodeEditor         = NodeEditor.CreateEditor(m_SelectedScript.type);
                m_SelectedNodeSample = ActionNode.CreateInstance(m_SelectedScript.type, null, null);
            }
            // It's a Category?
            else if (item is Category)
            {
                m_CurrentCategory = item as Category;
                m_SelectedScript  = null;
            }

            GUIUtility.hotControl      = 0;
            GUIUtility.keyboardControl = 0;
        }
Beispiel #11
0
        public void can_run_action()
        {
            var time = new TimeData(0);

            var invokeCount = 0;
            var testObject  =
                new ActionNode(
                    "some-action", 0,
                    t =>
            {
                Assert.Equal(time, t);

                ++invokeCount;
                return(Status.Running);
            }
                    );

            Assert.Equal(Status.Running, testObject.Tick(time));
            Assert.Equal(1, invokeCount);
        }
        /// <summary>
        /// Renders a dialog step
        /// </summary>
        /// <param name="data">Dialog Step Data</param>
        /// <param name="npc">Npc to which the dialog belongs</param>
        /// <returns>Dialog Step Render Result</returns>
        public async Task <ExportDialogStepRenderResult> RenderDialogStep(ExportDialogData data, KortistoNpc npc)
        {
            ActionNode actionNode = data.Action;

            if (actionNode == null)
            {
                return(null);
            }

            string actionContent = await BuildActionContent(actionNode, data, npc);

            ExportTemplate template = await _defaultTemplateProvider.GetDefaultTemplateByType(_project.Id, TemplateType.TaleAction);

            ExportDialogStepRenderResult renderResult = new ExportDialogStepRenderResult();

            renderResult.StepCode = ExportUtil.BuildPlaceholderRegex(Placeholder_ActionContent).Replace(template.Code, actionContent);
            renderResult.StepCode = ReplaceBaseStepPlaceholders(renderResult.StepCode, data, data.Children.FirstOrDefault() != null ? data.Children.FirstOrDefault().Child : null);

            return(renderResult);
        }
Beispiel #13
0
        /// <summary>
        /// Returns the valid action renderer for a node
        /// </summary>
        /// <param name="actionNode">Action Node</param>
        /// <returns>Action renderer</returns>
        private IActionRenderer GetActionRenderForNode(ActionNode actionNode)
        {
            int parsedActionType = 0;

            if (!int.TryParse(actionNode.ActionType, out parsedActionType))
            {
                _errorCollection.AddDialogUnknownActionTypeError(actionNode.ActionType);
                return(null);
            }

            ActionType actionType = (ActionType)parsedActionType;

            if (!_actionRenderes.ContainsKey(actionType))
            {
                _errorCollection.AddDialogUnknownActionTypeError(actionNode.ActionType);
                return(null);
            }

            return(_actionRenderes[actionType]);
        }
Beispiel #14
0
 public override void AddAction(int id, ActionNode an)
 {
     if (id == 0)
     {
         _cChunksAction = (CreateChunksAction)an;
     }
     if (id == 1)
     {
         _cBlockDataAction = (CreateBlockDataAction)an;
     }
     if (id == 2)
     {
         _terraformAction = (TerraformBlockDataAction)an;
     }
     if (id == 3)
     {
         _cMeshAction = (CreateMeshAction)an;
     }
     _allNodes.Add(an);
 }
Beispiel #15
0
        private ActionNode SelectionStatement()
        {
            ActionNode         itsAST;
            SourceCodePosition itsPos = _currentToken.SourcePosition;

            Accept(Token.TokenType.If);
            Accept(Token.TokenType.LeftParen);
            ExpressionNode itsExpr = Expression();

            Accept(Token.TokenType.RightParen);
            Accept(Token.TokenType.LeftBrace);
            ActionSequenceNode itsActions = ActionStatements();

            Accept(Token.TokenType.RightBrace);
            ActionSequenceNode itsElseifs = ElseIfStatements();
            ActionNode         itsElse    = ElseStatement();

            itsAST = new IfActionNode(itsExpr, itsActions, itsElseifs, itsElse, itsPos);
            return(itsAST);
        }
Beispiel #16
0
    // Use this for initialization
    void Start()
    {
        healthCheckNode = new ActionNode(CriticalHealthCheck);
        attackCheckNode = new ActionNode(CheckPlayerHealth);

        buffCheckRandomNode = new RandomBinaryNode();
        buffCheckNode       = new ActionNode(BuffCheck);
        buffCheckSequence   = new Sequence(new List <BTNode>
        {
            buffCheckRandomNode,
            buffCheckNode,
        });

        rootNode = new Selector(new List <BTNode>
        {
            healthCheckNode,
            attackCheckNode,
            buffCheckSequence,
        });
    }
Beispiel #17
0
    void Start()
    {
        player          = GameObject.Find("Player");
        rb              = GetComponent <Rigidbody2D>();
        initialPosition = rb.position;

        FreezeWorldComponent.FreezeEvent   += FreezeObject;
        FreezeWorldComponent.UnfreezeEvent += UnfreezeObject;

        worldState.Add("CanAttack", false);
        worldState.Add("ZeroHealthPoints", false);

        ActionNode attackNode = new ActionNode();

        attackNode.actionMethod = Attack;

        ActionNode moveNode = new ActionNode();

        moveNode.actionMethod = CheckAndUpdateMoveDirection;

        ActionNode dieNode = new ActionNode();

        dieNode.actionMethod = Die;

        BinaryNode attackDecisionNode = new BinaryNode();

        attackDecisionNode.yesNode  = attackNode;
        attackDecisionNode.noNode   = moveNode;
        attackDecisionNode.decision = "CanAttack";


        BinaryNode healthDecisionNode = new BinaryNode();

        healthDecisionNode.yesNode  = dieNode;
        healthDecisionNode.noNode   = attackDecisionNode;
        healthDecisionNode.decision = "ZeroHealthPoints";

        decisionTree = healthDecisionNode;

        rb.velocity = new Vector2(speed, 0);
    }
Beispiel #18
0
    override public double execute(double dt)
    {
        if (state == 0)
        {
            /*
             * ActionNode currentNode = MascaretUtils.getCurrentActionNode(agent);
             * MascaretHumanActions.changeConstraintValue(ui.DecisionAgent, "decisionValue", -1);
             * ui.decisionValue = -1;
             * choices = MascaretUtils.getOutgoingNodes(agent, currentNode);
             * MascaretHumanActions.setConstrainedEdges(MascaretUtils.getOutgoingEdges(agent, currentNode));
             * PrintSingleton.Instance.log("==================================== DECISION ========================================== " + choices.Count);
             * ui.DisplayChoices(choices, agentC);
             */

            ActionNode currentNode = MascaretUtils.getCurrentActionNode(agent);
            PrintSingleton.Instance.log("==================================== DECISION ========================================== " + currentNode.name);
            MascaretHumanActions.setConstrainedEdges(MascaretUtils.getOutgoingEdges(agent, currentNode));
            ui.DisplayChoices(MascaretUtils.getOutgoingNodes(agent, currentNode), agentC);
            state++;

            MascaretHumanActions.changeConstraintValue(ui.DecisionAgent, "decisionValue", -1);


            return(Time.deltaTime);
        }
        else
        {
            if (ui.decisionValue != -1)
            {
                PrintSingleton.Instance.log("Decision : " + ui.decisionValue);
                return(0);
            }

            /*else
             * {
             *  MascaretHumanActions.resetConstraints();
             *  return Time.deltaTime;
             * }*/
            return(Time.deltaTime);
        }
    }
Beispiel #19
0
    /// <summary>
    /// Used to set up the attacker type tree
    /// </summary>
    void SetupAttacker()
    {
        DecisionNode hasFlagNode = new DecisionNode(Decisions.Attacker_HasEnemyFlag, this);

        DecisionNode teamHasEnemyFlagNode = new DecisionNode(Decisions.Shared_TeamHasEnemyFlag, this);
        ActionNode   runBackAndScore      = new ActionNode(Actions.Attacker_GoBackToTeamFlag, this);

        hasFlagNode.AddFailureNode(teamHasEnemyFlagNode);
        hasFlagNode.AddSuccessNode(runBackAndScore);

        DecisionNode enemyInRadiusNode       = new DecisionNode(Decisions.Shared_IsEnemyInAttackRadius, this);
        DecisionNode enemySpottedNotInRadius = new DecisionNode(Decisions.Shared_HasSeenEnemy, this);

        teamHasEnemyFlagNode.AddFailureNode(enemyInRadiusNode);
        teamHasEnemyFlagNode.AddSuccessNode(enemySpottedNotInRadius);

        ActionNode attackTarget           = new ActionNode(Actions.Shared_AttackEnemyTarget, this);
        ActionNode followTeamMateWithFlag = new ActionNode(Actions.Shared_FollowTeamMateWithFlag, this);

        enemySpottedNotInRadius.AddSuccessNode(attackTarget);
        enemySpottedNotInRadius.AddFailureNode(followTeamMateWithFlag);

        DecisionNode isHealthLow = new DecisionNode(Decisions.Shared_IsHealthLow, this);
        ActionNode   findPickup  = new ActionNode(Actions.Shared_SearchForHealthpack, this);

        enemyInRadiusNode.AddFailureNode(isHealthLow);
        enemyInRadiusNode.AddSuccessNode(attackTarget);

        DecisionNode canTakeEnemyFlag = new DecisionNode(Decisions.Attacker_CanTakeEnemyFlag, this);

        isHealthLow.AddFailureNode(canTakeEnemyFlag);
        isHealthLow.AddSuccessNode(findPickup);

        ActionNode moveToEnemyFlag = new ActionNode(Actions.Attacker_MoveToEnemyFlag, this);
        ActionNode takeEnemyFlag   = new ActionNode(Actions.Attacker_TakeEnemyFlag, this);

        canTakeEnemyFlag.AddSuccessNode(takeEnemyFlag);
        canTakeEnemyFlag.AddFailureNode(moveToEnemyFlag);

        decTree = new DecisionTree(hasFlagNode);
    }
Beispiel #20
0
    void Update()
    {
        float dt = Time.deltaTime;

        //Process state
        switch (this.folkState)
        {
        default:
        case FolkState.Idle:
            idleState(dt);
            break;

        case FolkState.Wandering:
            wanderingState(dt);
            break;

        case FolkState.Travelling:
            travellingState(dt);
            break;
        }

        //Process actions

        Vector3 vect = new Vector3();

        float d = dt;

        while (actionQueue.Count > 0 && d > 0f)
        {
            ActionNode an = actionQueue[0];

            d = an.getVector(d, ref vect);

            transform.position += transform.TransformVector(vect);

            if (d > 0f)
            {
                actionQueue.Remove(an);
            }
        }
    }
Beispiel #21
0
    public INode GetNode(ushort Id, byte level)
    {
        NodeInfo pInfo = getNodeInfo(Id, level);

        if (pInfo == null)
        {
            return(null);
        }
        INode pNode = null;

        switch (pInfo.Type)
        {
        case 0:    //动画
            pNode = new ActionNode(Id);
            break;

        case 1:    //
            break;

        case 2:
            break;

        case 3:    //人物
            if (Id > 10000)
            {
                pNode = new Hero(1, 1);
            }
            else
            {
                pNode = new Soldier(1, 1);
            }
            break;

        case 4:    //飞行物
            break;

        case 5:
            break;
        }
        return(new INode());
    }
        /// <summary>
        /// Reset the supplied node properties.
        /// <param name="node">The node to be reseted.</param>
        /// </summary>
        public static void ResetNode(ActionNode node)
        {
            // Get the owner as an Uniyt object
            var ownerUnityObj = node != null ? node.owner as UnityEngine.Object : null;

            // Validate parameters
            if (ownerUnityObj != null)
            {
                // Register Undo
                #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2
                Undo.RegisterUndo(ownerUnityObj, "Reset Node");
                #else
                Undo.RecordObject(ownerUnityObj, "Reset Node");
                #endif

                node.name = node.GetType().Name;
                node.Reset();
                node.OnValidate();
                StateUtility.SetDirty(node.owner);
            }
        }
        public void SUCCESS2()
        {
            myTestsFuncs.counter = 0;
            myTestsFuncs.target  = 10;

            ActionNode T3 = new ActionNode(myTestsFuncs.CounterInc);

            ActionNode T2A = new ActionNode(myTestsFuncs.CounterInc);
            Inverter   T2B = new Inverter(T3);
            ActionNode T2C = new ActionNode(myTestsFuncs.CounterInc);

            List <Node> rootChildren = new List <Node> {
                T2A, T2B, T2C
            };

            Selector rootNode = new Selector(rootChildren);

            rootNode.Run();

            Assert.AreEqual(NodeStates.SUCCESS, rootNode.NodeState);
        }
Beispiel #24
0
        public static NodeLinkedList compile(LinkedListNode <Token> firstToken)
        {
            CompiledStatement cs = CompilerFactory.Instance.CreateCompiledStatement(firstToken);

            Compiled = cs.compile(ref firstToken);
            while (firstToken != null)
            {
                cs = CompilerFactory.Instance.CreateCompiledStatement(firstToken);
                NodeLinkedList nll = cs.compile(ref firstToken);
                Compiled.Add(nll);
            }
            ActionNode a = Compiled.First;

            while (a != null)
            {
                Console.WriteLine(a.GetType());
                a = a.Next;
            }

            return(Compiled);
        }
Beispiel #25
0
		public void Building_an_agenda_from_the_action_node_of_t()
		{
			var customer = new Customer();

			var wme = MockRepository.GenerateMock<SessionElement<Customer>>();
			wme.Stub(x => x.Object).Return(customer);

			var context = MockRepository.GenerateMock<RuleContext<Customer>>();
			context.Stub(x => x.Element).Return(wme);

			context.Expect(x => x.EnqueueAgendaAction(0, null)).IgnoreArguments();

			var action = MockRepository.GenerateMock<Action<RuleContext<Customer>>>();

			var node = new ActionNode<Customer>(x => action(x));

			node.Activate(context);


			context.VerifyAllExpectations();
		}
        public void AddTransition(ActionNode nodeFrom, ActionNode nodeTo, Func <bool> condition, Action transitionAction)
        {
            if (nodeFrom == null || nodeTo == null)
            {
                throw new ArgumentNullException("Must define a start and an end node.");
            }

            if (nodeFrom.Equals(nodeTo))
            {
                throw new Exception("Start node cannot equal end node.");
            }

            // Does not prevent the user from creating circular dependencies.
            transitionPool.Add(new Transition(context)
            {
                NodeFrom      = nodeFrom,
                NodeTo        = nodeTo,
                CanTransition = condition,
                ActionForward = transitionAction
            });
        }
Beispiel #27
0
    private void SetDecisionTree()
    {
        CheckNode playerVisible      = new CheckNode(PlayerVisible);
        CheckNode playerWithinRange  = new CheckNode(PlayerWithinRange);
        CheckNode playerSeenRecently = new CheckNode(PlayerSeenRecently);

        ActionNode attack       = new ActionNode(Attack);
        ActionNode moveToPlayer = new ActionNode(MoveToPlayer);
        ActionNode wander       = new ActionNode(Wander);

        playerVisible.True  = playerWithinRange;
        playerVisible.False = playerSeenRecently;

        playerWithinRange.True  = attack;
        playerWithinRange.False = moveToPlayer;

        playerSeenRecently.True  = moveToPlayer;
        playerSeenRecently.False = wander;

        decisionTree = new DecisionTree(playerVisible);
    }
        public void FAILURE1()
        {
            myTestsFuncs.counter = 0;
            myTestsFuncs.target  = 1;

            ActionNode T3 = new ActionNode(myTestsFuncs.CounterInc);

            ActionNode T2A = new ActionNode(myTestsFuncs.CounterInc);
            Inverter   T2B = new Inverter(T3);
            ActionNode T2C = new ActionNode(myTestsFuncs.CounterInc);

            List <Node> rootChildren = new List <Node> {
                T2A, T2B, T2C
            };

            Sequence rootNode = new Sequence(rootChildren);

            rootNode.Run();

            Assert.AreEqual(NodeStates.FAILURE, rootNode.NodeState);
        }
Beispiel #29
0
        public void Setup()
        {
            _primaryCalled   = new Future <Customer>();
            _secondaryCalled = new Future <Customer>();

            _customer = new Customer {
                Preferred = true
            };

            _actionNode = new ActionNode <Customer>(x => _primaryCalled.Complete(x.Element.Object));

            _constantNode = new ConstantNode <Customer>();

            var element = MockRepository.GenerateMock <SessionElement <Customer> >();

            element.Stub(x => x.Object).Return(_customer);

            _session = new StatefulSessionImpl(MockRepository.GenerateMock <RulesEngine>());

            _context = new SessionRuleContext <Customer>(_session, element);
        }
Beispiel #30
0
        private void ConnectTargets(EventNode Event, ActionNode Action)
        {
            if (!(Action.DotaAction is TargetedAction))
            {
                return;                                         //An action without targets doesn't need it's nodes resolved
            }
            TargetedAction ta = Action.DotaAction as TargetedAction;


            if (ta.Target.Preset == null)
            {
                return;                           //Not a preset.  TODO: Generated a Make Target node with the details of this target key
            }
            var outputItem = Event.GetTargetNodeFor(ta.Target.Preset);

            if (outputItem == null)
            {
                return;
            }

            graphControl1.Connect(outputItem, Action.TargetPin);
        }
Beispiel #31
0
    public ActionType GetCurrentDialog(out DialogDetail dialog, out SelectionDetail selection)
    {
        dialog    = null;
        selection = null;
        if (m_currentCollection != null && m_currentCollection.m_actions != null &&
            m_currentCollectionDialogID < m_currentCollection.m_actions.Count)
        {
            ActionNode action = m_currentCollection.m_actions[m_currentCollectionDialogID];
            switch (action.m_Type)
            {
            case "dialog":
                dialog = DialogDetail.ConversionFromXML(action.m_Detail);
                return(ActionType.Dialog);

            case "selection":
                selection = SelectionDetail.ConversionFromXML(action.m_Detail);
                return(ActionType.Selection);
            }
        }

        return(ActionType.None);
    }
        private void loadActionNodes()
        {
            InternalScriptSettings settings = new InternalScriptSettings();

            settings.DebugMode = DebugMode;
            settings.Cache     = cache;

            actionNodes = new Dictionary <string, ScraperNode>();
            foreach (XmlNode currAction in xml.DocumentElement.SelectNodes("child::action"))
            {
                ActionNode newNode = (ActionNode)ScraperNode.Load(currAction, settings);
                if (newNode != null && newNode.LoadSuccess)
                {
                    actionNodes[newNode.Name] = newNode;
                }
                else
                {
                    logger.Error("Error loading action node: " + currAction.OuterXml);
                    loadSuccessful = false;
                }
            }
        }
Beispiel #33
0
 public static int getChoiceScore(ActionNode choice)
 {
     if (choice.Action.Kind == "CallOperation")
     {
         foreach (ValuePin currentPin in choice.Action.ValuePins)
         {
             if (currentPin.name == "Feedback")
             {
                 PrintSingleton.Instance.log("Pin : " + currentPin.name + "   : " + currentPin.ValueSpec.getStringFromValue());
                 string   feedback_text = stringUtils.CleanString(currentPin.ValueSpec.getStringFromValue());
                 string[] feedbackDiv   = feedback_text.Split('_');
                 int      feedbackValue = -1;
                 if (Int32.TryParse(feedbackDiv[0], out feedbackValue))
                 {
                     return(feedbackValue);
                 }
                 //return CleanString(currentPin.ValueSpec.getStringFromValue());
             }
         }
     }
     return(-1);
 }
        // Token: 0x0600001B RID: 27 RVA: 0x000033B0 File Offset: 0x000015B0
        public static void SetupRufusInteraction()
        {
            GameObject gameObject = GameObject.Find("Dialogue_Rufus/NPC/DialogueTree_1_Initial");
            bool       flag       = gameObject != null;

            if (flag)
            {
                DialogueTreeController component = gameObject.GetComponent <DialogueTreeController>();
                bool flag2 = component != null;
                if (flag2)
                {
                    Graph            graph            = component.graph;
                    List <Node>      allNodes         = graph.allNodes;
                    StatementNodeExt statementNodeExt = allNodes.FirstOrDefault((Node n) => n != null && n is StatementNodeExt && ((StatementNodeExt)n).statement.text.Contains("Elatt however... I’ve had the honor to speak with him. He is very real. Having a god that was once man is comforting.")) as StatementNodeExt;
                    bool             flag3            = statementNodeExt != null;
                    if (flag3)
                    {
                        ActionNode actionNode = graph.AddNode <ActionNode>();
                        GiveReward giveReward = new GiveReward();
                        actionNode.action         = giveReward;
                        giveReward.RewardReceiver = GiveReward.Receiver.Instigator;
                        NodeCanvas.Tasks.Actions.ItemQuantity itemQuantity = new NodeCanvas.Tasks.Actions.ItemQuantity();
                        itemQuantity.Item = new BBParameter <ItemReference>(new ItemReference
                        {
                            ItemID = Templar.Instance.prayerInstance.ItemID
                        });
                        itemQuantity.Quantity = 1;
                        giveReward.ItemReward = new List <NodeCanvas.Tasks.Actions.ItemQuantity>
                        {
                            itemQuantity
                        };
                        statementNodeExt.outConnections[0] = Connection.Create(statementNodeExt, actionNode, -1, -1);
                        FinishNode finishNode = graph.AddNode <FinishNode>();
                        allNodes.Add(finishNode);
                        graph.ConnectNodes(actionNode, finishNode, -1, -1);
                    }
                }
            }
        }
    public BanditBossBehaviourTree(BanditBossBehaviour boss)
    {
        moveToPlayer           = new MoveAction(boss.Move, boss.FindPlayer);
        moveToThrowingPosition = new MoveAction(boss.Move, boss.PositionForHealthEvent);
        moveToHidingPlace      = new MoveAction(boss.Move, boss.HidingPlace);

        fireShotgun.OpenBranch(new ActionNode(boss.ShotgunAttack));
        throwMolotov.OpenBranch(new ActionNode(boss.Attack));
        ThisOrThat selectAttack = new ThisOrThat(throwMolotov, fireShotgun, boss.PlayerOnLowerLevel);

        healthEvent = new ActionNode(boss.HealthEvent);

        //TODO Define both weapon sequences and whistle sequence

        whistleAndRetreat.OpenBranch(
            whistle = new ActionNode(boss.WhistleToAllies),
            moveToHidingPlace,
            hide = new ActionNode(boss.Hide)
            );

        healthEventSeq.OpenBranch(
            new ConditionalAction(boss.HealthEventDue),
            moveToThrowingPosition,
            healthEvent,
            whistleAndRetreat
            );

        attack.OpenBranch(
            moveToPlayer,
            selectAttack
            );

        findBestAction.OpenBranch(
            healthEventSeq,
            attack
            );
        treeRoot = new Root();
        treeRoot.OpenBranch(findBestAction);
    }
Beispiel #36
0
    // Create the decision tree
    protected override void Start()
    {
        // Call base class Start()
        base.Start();

        // Create the leaf actions
        IDecisionTreeNode seek    = new ActionNode(SeekAction);
        IDecisionTreeNode nothing = new ActionNode(StandStillAction);
        IDecisionTreeNode patrol  = new ActionNode(PatrolAction);

        // Create the random decision behaviour node
        RandomDecisionBehaviour rdb = new RandomDecisionBehaviour(
            () => Random.value,
            () => Time.frameCount,
            randomDecisionDurationInFrames,
            0.55f);
        IDecisionTreeNode rndNode = new DecisionNode(
            rdb.RandomDecision, seek, nothing);

        // Create the root node
        root = new DecisionNode(PlayerInSight, rndNode, patrol);
    }
Beispiel #37
0
        public override void OnEditorRefresh()
        {
            State.MinorStructures.Clear();

            List <ActionNode>            nodes = new List <ActionNode> ();
            List <ActionNodePlaceholder> acps  = new List <ActionNodePlaceholder> ();

            ActionNode            node = null;
            ActionNodePlaceholder acp  = null;

            foreach (Transform child in transform)
            {
                if (child.gameObject.HasComponent <StructureBuilder> () || child.name.Contains("-STR"))
                {
                    MinorStructure ms = new MinorStructure();
                    ms.TemplateName = StructureBuilder.GetTemplateName(child.name);
                    ms.Position     = child.transform.localPosition;
                    ms.Rotation     = child.transform.localRotation.eulerAngles;
                    State.MinorStructures.Add(ms);
                }
                else if (child.gameObject.HasComponent <ActionNode> (out node))
                {
                    if (node.State.Users == ActionNodeUsers.AnyOccupant)
                    {
                        nodes.Add(node);
                    }
                }
                else if (child.gameObject.HasComponent <ActionNodePlaceholder> (out acp))
                {
                    if (acp.SaveToStructure)
                    {
                        acps.Add(acp);
                    }
                }
            }

            ActionNodePlaceholder.LinkNodes(acps, nodes, State.MovementNodes);
        }
        /// <summary>
        /// Paste the supplied nodes in the supplied ActionState.
        /// <param name="actionState">The ActionState to paste the node.</param>
        /// <param name="nodes">The nodes to be pasted.</param>
        /// <returns>The pasted nodes.</returns>
        /// </summary>
        public static ActionNode[] PasteNodes(InternalActionState actionState, ActionNode[] nodes)
        {
            var newNodes = new List <ActionNode>();

            // Validate parameters
            if (nodes != null && actionState != null)
            {
                // Register Undo
                #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2
                Undo.RegisterUndo(actionState, "Paste Node");
                #else
                Undo.RecordObject(actionState, "Paste Node");
                #endif

                // Copy nodes
                for (int i = 0; i < nodes.Length; i++)
                {
                    if (nodes[i] != null && !(nodes[i] is BranchNode))
                    {
                        ActionNode newNode = nodes[i].Copy(actionState);
                        if (newNode != null)
                        {
                            newNodes.Add(newNode);
                        }
                    }
                }

                if (newNodes.Count > 0)
                {
                    // Saves node and sets dirty flag
                    StateUtility.SetDirty(actionState);

                    // Reload actionState to update variables
                    actionState.LoadNodes();
                }
            }
            return(newNodes.ToArray());
        }
Beispiel #39
0
    //得到一个招式可连接的普通招式
    public ActionNode GetNormalNode(MeteorUnit owner, ActionNode source)
    {
        //普通攻击映射输入的行号
        int weapon = owner.GetWeaponType();

        //"1,5,9,13,25,35,48,61,73,91,95,101,108,123,"    "85,22,32,46,59,107,122,105,"   J 攻击  59较特殊,估计所有重武器的空中A都是338动作
        int[] GroundKeyMap = new int[] { 1, 5, 9, 13, 25, 35, 48, 61, 73, 91, 95, 101, 108, 123 };
        int[] AirKeyMap    = new int[] { 85, 22, 32, 46, 59, 107, 122, 105 };

        if (owner.IsOnGround())
        {
            for (int i = 0; i < source.target.Count; i++)
            {
                for (int j = 0; j < GroundKeyMap.Length; j++)
                {
                    if (GroundKeyMap[j] == source.target[i].KeyMap && owner.meteorController.Input.CheckPos(source.target[i].KeyMap, source.target[i].ActionIdx))
                    {
                        return(source.target[i]);
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < source.target.Count; i++)
            {
                for (int j = 0; j < AirKeyMap.Length; j++)
                {
                    if (AirKeyMap[j] == source.target[i].KeyMap && owner.meteorController.Input.CheckPos(source.target[i].KeyMap, source.target[i].ActionIdx))
                    {
                        return(source.target[i]);
                    }
                }
            }
        }

        return(null);
    }
Beispiel #40
0
        private void tvwActions_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                splcActions.Panel2Collapsed = true;

                ActionNode nd = e.Node as ActionNode;
                if (nd?.Checked ?? false)
                {
                    tbScript.Selection = new Range(tbScript, new Place(0, nd.StartLine), new Place(0, nd.EndLine));
                }

                if (!nd?.IsValid ?? false)
                {
                    splcActions.Panel2Collapsed = false;
                    lblErrors.Text = string.Join("\r\n", nd.ValidationErrors);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
Beispiel #41
0
    public static Node ToNode(this NodeType type)
    {
        Node toReturn = null;

        switch (type)
        {
          case NodeType.End:
        toReturn = new Node();
        break;
          case NodeType.OneOptionMessage:
        toReturn = new OneOptionMessageNode();
        break;
          case NodeType.TwoOptionMessage:
        toReturn = new TwoOptionMessageNode();
        break;
          case NodeType.FourOptionMessage:
        toReturn = new FourOptionMessageNode();
        break;
          case NodeType.TextboxMessage:
        toReturn = new Node();
        break;
          case NodeType.Action:
        toReturn = new ActionNode();
        break;
          case NodeType.StartSequence:
        toReturn = new StartSequenceNode();
        break;
          case NodeType.TimeLeap:
        toReturn = new TimeLeapNode();
        break;
          case NodeType.IngameDelay:
        toReturn = new IngameDelayNode();
        break;
        }

        return toReturn;
    }
Beispiel #42
0
 public ActionNode(string s, Transform t, ActionNode n)
 {
     funcname = s;
     target = t;
     next = n;
 }
        public override void WriteCode(TemplateContext ctx, ActionNode node)
        {
            var codeMethodReferenceExpression = new CodeMethodReferenceExpression(
                new CodeSnippetExpression(SystemType.FullName),
                Method.Name);
            if (this.InstanceInfo != null)
            {
                var instanceVar = node.InputVars.FirstOrDefault(p => p.ActionFieldInfo == this.InstanceInfo);
                if (instanceVar != null)
                {
                    codeMethodReferenceExpression = new CodeMethodReferenceExpression(new CodeSnippetExpression(instanceVar.VariableName),Method.Name);
                }
                
            }
            var _currentActionInvoker =
                new CodeMethodInvokeExpression(
                    codeMethodReferenceExpression);
           
            foreach (var x in Method.GetParameters())
            {
                var item = node.GraphItems.OfType<IActionItem>().FirstOrDefault(p => p.Name == x.Name);
                var input = item as IActionIn;
                if (input != null)
                {
                    if (input.ActionFieldInfo == InstanceInfo) continue;

                    if (input.ActionFieldInfo.IsGenericArgument)
                    {
                    }
                    else
                    {
                        _currentActionInvoker.Parameters.Add(
                            new CodeSnippetExpression((input.ActionFieldInfo.IsByRef ? "ref " : string.Empty) +
                                                      string.Format("{0}", input.VariableName)));
                    }
                }
                var @out = item as ActionOut;
                if (@out != null)
                {
                    if (@out.ActionFieldInfo != null && @out.ActionFieldInfo.IsReturn)
                    {
                 
                        continue;
                    }
                    _currentActionInvoker.Parameters.Add(
                        new CodeSnippetExpression(string.Format("out {0}", @out.VariableName)));
                }
                var branch = item as ActionBranch;
                if (branch != null)
                {
                    if (DebugSystem.IsDebugMode)
                    {
                        _currentActionInvoker.Parameters.Add(
                            new CodeSnippetExpression(string.Format("()=> {{ System.StartCoroutine({0}()); }}",
                                branch.VariableName)));
                    }
                    else
                    {
                        _currentActionInvoker.Parameters.Add(
                            new CodeSnippetExpression(string.Format("{0}", branch.VariableName)));
                    }
                }
            }

            var resultOut = node.GraphItems.OfType<IActionItem>().FirstOrDefault(p => p.ActionFieldInfo != null && p.ActionFieldInfo.IsReturn);
            if (resultOut == null)
            {
                ctx.CurrentStatements.Add(_currentActionInvoker);
            }
            else
            {
                var assignResult = new CodeAssignStatement(
                    new CodeSnippetExpression(resultOut.VariableName), _currentActionInvoker);
                ctx.CurrentStatements.Add(assignResult);
            }
        }
 public ActionAndWeight(float weight, ActionNode action)
 {
     _weight = weight;
     _action = action;
 }
Beispiel #45
0
    private float DrawActionNode(ActionNode node, float x, float y)
    {
        float fieldwidth = NODEWIDTH - PADDING * 2;

        EditorGUI.LabelField(new Rect(x + PADDING, y, fieldwidth * LABELWIDTH, FIELDHEIGHT), "Action");
        node.Action = EditorGUI.TextField(new Rect(x + PADDING + fieldwidth * LABELWIDTH, y, fieldwidth - fieldwidth * LABELWIDTH, FIELDHEIGHT), node.Action);
        y += FIELDHEIGHT + PADDING;

        if (GUI.Button(new Rect(x + PADDING , y, fieldwidth, FIELDHEIGHT), "Edit Data")) {
          ActionNodeEditor.ShowWindow(node);
        };
          y += FIELDHEIGHT + PADDING;

        return y;
    }
        private static void InitializeWithCommonValue(XElement element, Tree tree, ActionNode actionNode, string defaultIconName, string defaultLabelName = null, ActionLocation defaultActionLocation = null, List<PermissionType> defaultPermissionTypes = null)
        {
            XAttribute labelAttribute = element.Attribute("Label");
            XAttribute toolTipAttribute = element.Attribute("ToolTip");
            XAttribute iconAttribute = element.Attribute("Icon");

            if ((defaultLabelName == null) && (labelAttribute == null)) tree.AddValidationError(element.GetXPath(), "TreeValidationError.Common.MissingAttribute", "Label");

            actionNode.XPath = element.GetXPath();
            actionNode.Id = tree.BuildProcessContext.ActionIdCounter++;
            actionNode.Label = labelAttribute.GetValueOrDefault(defaultLabelName);
            actionNode.ToolTip = toolTipAttribute.GetValueOrDefault(actionNode.Label);
            actionNode.Icon = FactoryHelper.GetIcon(iconAttribute.GetValueOrDefault(defaultIconName));
            actionNode.Location = GetActionLocation(element, tree, defaultActionLocation);
            if (defaultPermissionTypes != null)
            {
                actionNode.PermissionTypes = defaultPermissionTypes;
            }
            else
            {
                actionNode.PermissionTypes = GetPermissionTypes(element, tree);
            }
        }
Beispiel #47
0
 /// <summary>
 /// clone
 /// </summary>
 /// <returns></returns>
 public IBehaviourNode Clone()
 {
     var behaviourNode = new ActionNode(this.action);
     base.CopyTo(behaviourNode);
     return behaviourNode;
 }
Beispiel #48
0
        public void Setup()
        {
            _primaryCalled = new Future<Customer>();
            _secondaryCalled = new Future<Customer>();

            _customer = new Customer {Preferred = true};

            _actionNode = new ActionNode<Customer>(x => _primaryCalled.Complete(x.Element.Object));

            _constantNode = new ConstantNode<Customer>();

            var element = MockRepository.GenerateMock<SessionElement<Customer>>();
            element.Stub(x => x.Object).Return(_customer);

            _session = new StatefulSessionImpl(MockRepository.GenerateMock<RulesEngine>());

            _context = new SessionRuleContext<Customer>(_session, element);
        }
 public ConditionalJumpNode(ActionNode trueNode, ActionNode falseNode)
 {
     nextOnFalse = falseNode;
     nextOnTrue = trueNode;
 }
 public ActionNodeViewModel(ActionNode graphItemObject, Invert.Core.GraphDesigner.DiagramViewModel diagramViewModel) :
         base(graphItemObject, diagramViewModel)
 {
 }
Beispiel #51
0
 public void nuke()
 {
     head = tail = null;
 }
 public void Add(NodeLinkedList nll)
 {
     last.Next = nll.first;
     nll.first.Prev = last;
     last = nll.last;
 }
Beispiel #53
0
        public void Only_those_that_are_matched_should_be_called()
        {
            var junction = new JoinNode<Customer>(_constantNode);
            junction.AddSuccessor(_actionNode);

            var alphaNodeA = new AlphaNode<Customer>();
            alphaNodeA.AddSuccessor(junction);

            var joinJunction = new JoinNode<Customer>(alphaNodeA);

            var alphaNodeB = new AlphaNode<Customer>();
            alphaNodeB.AddSuccessor(joinJunction);

            var actionNode = new ActionNode<Customer>(x => _secondaryCalled.Complete(x.Element.Object));

            var joinJunction2 = new JoinNode<Customer>(alphaNodeA);
            joinJunction2.AddSuccessor(actionNode);

            var alphaNodeC = new AlphaNode<Customer>();
            alphaNodeC.AddSuccessor(joinJunction2);

            var tree = new TypeNode<Customer>();

            var isPreferred = new ConditionNode<Customer>(x => x.Preferred);
            isPreferred.AddSuccessor(alphaNodeA);

            tree.AddSuccessor(isPreferred);

            tree.AddSuccessor(alphaNodeB);

            var isActive = new ConditionNode<Customer>(x => x.Active);
            isActive.AddSuccessor(alphaNodeC);
            tree.AddSuccessor(isActive);

            var visitor = new StringNodeVisitor();
            tree.Visit(visitor);

            Trace.WriteLine(visitor.Result);

            tree.Activate(_context);
            _session.Run();

            _primaryCalled.IsCompleted.ShouldBeTrue();
            _secondaryCalled.IsCompleted.ShouldBeFalse();
        }