Example #1
0
    private float calculateNaiveBayes(DecisionData question)
    {
        int decisionCount = 0;
        int total         = 0;

        Dictionary <Enum, int> factorCounts = new Dictionary <Enum, int> ();
        Dictionary <Enum, int> factorTotals = new Dictionary <Enum, int> ();

        Dictionary <Enum, Dictionary <string, int> > factorData = new Dictionary <Enum, Dictionary <string, int> > ();

        foreach (var factor in question.factors)
        {
            factorCounts [factor.Value] = 0;
            factorTotals [factor.Value] = 0;
            //factorData [factor.Value] ["Count"] = 0;
            //factorData [factor.Value] ["Total"] = 0;
        }


        foreach (var data in playerDecisionFrequency)
        {
            total += data.Value;
            foreach (var factorT in question.factors)
            {
                if (data.Key.factors [factorT.Key].Equals(factorT.Value))
                {
                    factorTotals [factorT.Value] += data.Value;
                }
            }
            if (data.Key.decision == question.decision)
            {
                decisionCount += data.Value;
                foreach (var factor in question.factors)
                {
                    if (data.Key.factors [factor.Key].Equals(factor.Value))
                    {
                        factorCounts[factor.Value] += data.Value;
                    }
                }
            }
        }
        Debug.Log("The total is " + total);
        Debug.Log("Decision count is " + decisionCount);
        //calculate probability from counts.
        float p  = 1.0f;
        float fP = 1.0f;

        foreach (var factor in factorCounts)
        {
            Debug.Log(factor.Key.ToString() + ": " + factor.Value);
            Debug.Log(factor.Key.ToString() + " total: " + factorTotals[factor.Key]);
            p /= decisionCount;
            p *= factor.Value;
            Debug.Log("p now is " + p);
            fP /= total;
            fP *= factorTotals[factor.Key];
        }
        Debug.Log("The final value should be " + ((float)decisionCount / (float)total) + " * " + p);
        return((float)decisionCount / (float)total * p);
    }
Example #2
0
        public override void WriteDataXML(XElement ele, ElderScrollsPlugin master)
        {
            XElement subEle;

            if (EditorID != null)
            {
                ele.TryPathTo("EditorID", true, out subEle);
                EditorID.WriteXML(subEle, master);
            }
            if (DecisionData != null)
            {
                ele.TryPathTo("DecisionData", true, out subEle);
                DecisionData.WriteXML(subEle, master);
            }
            if (AdvancedData != null)
            {
                ele.TryPathTo("AdvancedData", true, out subEle);
                AdvancedData.WriteXML(subEle, master);
            }
            if (SimpleData != null)
            {
                ele.TryPathTo("SimpleData", true, out subEle);
                SimpleData.WriteXML(subEle, master);
            }
        }
Example #3
0
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the decider will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the decider will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            // Create blackboard.
            Blackboard blackboard = new Blackboard();

            // Add parent blackboards.
            if (this.Blackboard != null)
            {
                blackboard.Parents.Add(this.Blackboard);
            }

            blackboard.Parents.Add(agentData.Blackboard);

            // Setup blackboard.
            Blackboard previousBlackboard = agentData.Blackboard;

            agentData.Blackboard = blackboard;

            // Deactivate child.
            IDecisionData childDecisionData = null;
            float         decisionValue     = this.DecideChild(agentData, ref childDecisionData);

            // Tear down.
            agentData.Blackboard = previousBlackboard;

            // Create decision data.
            if (decisionValue > 0.0f)
            {
                decisionData = new DecisionData {
                    Blackboard = blackboard, ChildDecisionData = childDecisionData
                };
            }

            return(decisionValue);
        }
Example #4
0
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the task will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the task will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            List <IDecisionData> childrenDecisionData = new List <IDecisionData>();

            // Check if all children want to run.
            float maxChildDecisionValue = 0.0f;

            foreach (ITask child in this.Children)
            {
                IDecisionData childDecisionData  = null;
                float         childDecisionValue = child.Decide(agentData, ref childDecisionData);
                maxChildDecisionValue = Math.Max(maxChildDecisionValue, childDecisionValue);

                // If one doesn't want to run, we don't run the whole task.
                if (childDecisionValue <= 0.0f)
                {
                    return(0.0f);
                }

                childrenDecisionData.Add(childDecisionData);
            }

            decisionData = new DecisionData {
                ChildrenDecisionData = childrenDecisionData
            };

            return(maxChildDecisionValue);
        }
Example #5
0
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Execution status after activation. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            DecisionData taskDecisionData = (DecisionData)decisionData;

            // Create child blackboard.
            Data data = new Data {
                Blackboard = taskDecisionData.Blackboard, PreviousBlackboard = agentData.Blackboard
            };

            agentData.CurrentTaskData = data;

            // Setup blackboard.
            Setup(agentData, data);

            // Activate child.
            ExecutionStatus result = this.ActivateChild(agentData, taskDecisionData.ChildDecisionData);

            if (result != ExecutionStatus.Running)
            {
                // Tear down.
                TearDown(agentData, data);
            }

            return(result);
        }
        public override DecisionData Decision(int rollNumber)
        {
            DecisionData data = new DecisionData(rollNumber);
            data.diceRoll = (rollNumber * rollNumber);

            // Decide what the 
            return data;
        }
        public IDecisionTreeNode VisitDecision(DecisionData data)
        {
            var type     = decisionTypes[data.Type];
            var decision = (BaseDecision)Activator.CreateInstance(type);
            var onTrue   = data.OnTrue.Accept(this);
            var onFalse  = data.OnFalse.Accept(this);

            decision.Init(onTrue, onFalse);

            return(log(decision));
        }
        public override DecisionData Decision(int rollNumber)
        {
            DecisionData data = new DecisionData(rollNumber);

            if (rollNumber <= 0)
                data.diceRoll = 0;
            else
                data.diceRoll = (rollNumber / rollNumber);

            // Decide what the 
            return data;
        }
        public override DecisionData Decision(int rollNumber)
        {
            DecisionData data = new DecisionData();

            if (m_SubtractRollNumber == 0)
                data.diceRoll = (m_Number - rollNumber);
            else
                data.diceRoll = (rollNumber - m_Number);

            // Decide what the 
            return data;
        }
Example #10
0
        protected override void Seed(DurandalAuthDbContext context)
        {
            var userManager = new UserManager <UserProfile>(new UserStore <UserProfile>(context));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            if (!roleManager.RoleExists("Administrator"))
            {
                roleManager.Create(new IdentityRole("Administrator"));
            }

            if (!roleManager.RoleExists("User"))
            {
                roleManager.Create(new IdentityRole("User"));
            }

            if (userManager.FindByName("admin") == null)
            {
                var user = new UserProfile {
                    UserName = "******", Email = "*****@*****.**", EmailConfirmed = true
                };
                var result = userManager.Create(user, "admin1234");
                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Administrator");
                }
            }

            var uow = new DurandalAuthDbContext();

            var hasChanges = false;

            //SetCategoryData(uow);
            ProvinceData.SetProvinceData(uow, ref hasChanges);
            GenderData.SetGenderData(uow, ref hasChanges);
            // EthnicityData.SetEthnicityData(uow, ref hasChanges);
            //LanguageData.SetLanguageData(uow, ref hasChanges);
            EmploymentData.SetEmploymentStatus(uow, ref hasChanges);

            /* PsiraGradeData.SetPsiraGradeData(uow, ref hasChanges);
             * SecurityTrainingData.SetSecurityTrainingData(uow, ref hasChanges);*/
            DecisionData.SetYesNoLookupData(uow, ref hasChanges);
            //PsiraCategoryData.SetPsiraCategoryLookup(uow, ref hasChanges);
            //CityData.SetCityNameData(uow, ref hasChanges);
            AddressData.SetAddressData(uow, ref hasChanges);
            //MaritalStatusData.SetMaritalStatusData(uow, ref hasChanges);
            EntityTypeData.SetEntityData(uow, ref hasChanges);
            TitleData.SetTitleData(uow, ref hasChanges);

            if (hasChanges)
            {
                uow.SaveChanges();
            }
        }
        public override DecisionData Decision(int rollNumber)
        {
            DecisionData data = new DecisionData(rollNumber);

            if (rollNumber == 1)
                data.route = Route.eAlternative1;
            else if (rollNumber == 2)
                data.route = Route.eAlternative2;
            else if (rollNumber == 3)
                data.route = Route.eAlternative3; 

            // Decide what the 
            return data;
        }
Example #12
0
        public override void ReadData(ESPReader reader, long dataEnd)
        {
            while (reader.BaseStream.Position < dataEnd)
            {
                string subTag = reader.PeekTag();

                switch (subTag)
                {
                case "EDID":
                    if (EditorID == null)
                    {
                        EditorID = new SimpleSubrecord <String>();
                    }

                    EditorID.ReadBinary(reader);
                    break;

                case "CSTD":
                    if (DecisionData == null)
                    {
                        DecisionData = new CombatStyleDecision();
                    }

                    DecisionData.ReadBinary(reader);
                    break;

                case "CSAD":
                    if (AdvancedData == null)
                    {
                        AdvancedData = new CombatStyleAdvanced();
                    }

                    AdvancedData.ReadBinary(reader);
                    break;

                case "CSSD":
                    if (SimpleData == null)
                    {
                        SimpleData = new CombatStyleSimple();
                    }

                    SimpleData.ReadBinary(reader);
                    break;

                default:
                    throw new Exception();
                }
            }
        }
Example #13
0
 public override void WriteData(ESPWriter writer)
 {
     if (EditorID != null)
     {
         EditorID.WriteBinary(writer);
     }
     if (DecisionData != null)
     {
         DecisionData.WriteBinary(writer);
     }
     if (AdvancedData != null)
     {
         AdvancedData.WriteBinary(writer);
     }
     if (SimpleData != null)
     {
         SimpleData.WriteBinary(writer);
     }
 }
Example #14
0
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the task will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the task will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            float         decideValue       = 0.0f;
            int           selectedChildIdx  = -1;
            IDecisionData childDecisionData = null;

            if (this.DecideForFirstPossible(agentData, ref selectedChildIdx, ref decideValue, ref childDecisionData))
            {
                // Create decision data to pass to use in Activate() method.
                decisionData = new DecisionData
                {
                    SelectedChildIdx  = selectedChildIdx,
                    ChildDecisionData = childDecisionData
                };

                return(decideValue);
            }

            return(0.0f);
        }
Example #15
0
        public override void ReadDataXML(XElement ele, ElderScrollsPlugin master)
        {
            XElement subEle;

            if (ele.TryPathTo("EditorID", false, out subEle))
            {
                if (EditorID == null)
                {
                    EditorID = new SimpleSubrecord <String>();
                }

                EditorID.ReadXML(subEle, master);
            }
            if (ele.TryPathTo("DecisionData", false, out subEle))
            {
                if (DecisionData == null)
                {
                    DecisionData = new CombatStyleDecision();
                }

                DecisionData.ReadXML(subEle, master);
            }
            if (ele.TryPathTo("AdvancedData", false, out subEle))
            {
                if (AdvancedData == null)
                {
                    AdvancedData = new CombatStyleAdvanced();
                }

                AdvancedData.ReadXML(subEle, master);
            }
            if (ele.TryPathTo("SimpleData", false, out subEle))
            {
                if (SimpleData == null)
                {
                    SimpleData = new CombatStyleSimple();
                }

                SimpleData.ReadXML(subEle, master);
            }
        }
Example #16
0
        public override DecisionData Decision(int rollNumber)
        {
            DecisionData data = new DecisionData(rollNumber);

            if (m_DecisionFlag == "equal")
            {
                if (rollNumber == m_Number )
                    data.route = Route.eAlternative1;
            }
            else if (m_DecisionFlag == "lessthan")
            {
                if (rollNumber < m_Number)
                    data.route = Route.eAlternative1;
            }
            else if (m_DecisionFlag == "greaterthan")
            {
                if (rollNumber > m_Number)
                    data.route = Route.eAlternative1;
            }
             
            // Decide what the 
            return data;
        }
Example #17
0
    public override void OnBar(Bar bar)
    {
        //Testing
        //Console.WriteLine(bar.DateTime.ToString());
        //testing
        if ( (bar.DateTime.TimeOfDay < startOfDay.TimeOfDay)
            //||
            //(bar.DateTime.TimeOfDay > endOfDay)
            )
        {
            //testing
            //Console.WriteLine("Not within trading hours. Ignoring data.");
            return;
            //testing
        }

        so_180_a.updateStochasticOscillator(bar.DateTime,
                                           bar.Open,
                                           bar.High,
                                           bar.Low,
                                           bar.Close);

        so_180_b.updateStochasticOscillator(bar.DateTime,
                                           bar.Open,
                                           bar.High,
                                           bar.Low,
                                           bar.Close);

        so_45_a.updateStochasticOscillator(bar.DateTime,
                                           bar.Open,
                                           bar.High,
                                           bar.Low,
                                           bar.Close);

        so_45_b.updateStochasticOscillator(bar.DateTime,
                                           bar.Open,
                                           bar.High,
                                           bar.Low,
                                           bar.Close);

        ema_180.updateExpentialMovingAverage(bar.DateTime, bar.Open, bar.High, bar.Low, bar.Close);
        ema_45.updateExpentialMovingAverage(bar.DateTime, bar.Open, bar.High, bar.Low, bar.Close);

        DecisionData ddata = new DecisionData();
        ddata.strategy = this;
        ddata.bar = bar;
        ddata.so_180_a = so_180_a;
        ddata.so_180_b = so_180_b;
        ddata.so_45_a = so_45_a;
        ddata.so_45_b = so_45_b;
        ddata.ema_45 = ema_45;
        ddata.ema_180 = ema_180;

        if(ddata.so_180_a.saActive &&
            ddata.so_180_b.saActive &&
            ddata.so_45_a.saActive &&
            ddata.so_45_b.saActive &&
            ddata.ema_45.emaActive &&
            ddata.ema_180.emaActive)
        {
            //testing
            //System.Console.WriteLine("Data acquired ... algo active.");
            //testing
            decisionUnit.run(ddata);
        }

        //testing
        //System.Console.WriteLine(bar);
        //testing

        //Prints Timestamp, %k, %D, EMA, ClosePrice
        //String output = bar.DateTime.ToString() + "\t" + so_180.getLastPercentK() + "\t" + so_180.getLastSmoothedPercentK() + "\t" + so_180.getLastPercentD() + "\t" + ema.getLastEMA().ToString() + "\t" + bar.Close;
        //Console.WriteLine(output);
    }
Example #18
0
    void handleScenario1(DecisionData data)
    {
        //Sell Trigger1 data
        double thirdEma45 = data.ema_45.getLastNEMA(2);
        double previousEma45 = data.ema_45.getLastNEMA(1);
        double currentEma45 = data.ema_45.getLastNEMA(0);

        //Sell Trigger2 data
        double thirdSo180BPercentk = data.so_180_b.getLastNPercentK(2);
        double previousSo180BPercentk = data.so_180_b.getLastNPercentK(1);
        double currentSo180BPercentk = data.so_180_b.getLastNPercentK(0);
        double currentSo180BUpperThreshold = data.so_180_b.getHighThreshold();

        //Sell Trigger3 data

        //Sell Trigger6 data
        List<double> ema45RegData = new List<double>();
        for (int i = 0; i < 10; i++)
        {
            ema45RegData.Add(data.ema_45.getLastNEMA(i + 1));
        }
        Boolean dataDropFromReg = dataDropsFromRegression(ema45RegData, currentEma45);

        Boolean sellTrigger1 = false; // [45] EMA is negative for 2 candles
        Boolean sellTrigger2 = false; // [180]21,4,5 is Above the 80 threshold and %K slope goes neg.
                                      // && [45] EMA goes negative

        Boolean sellTrigger3 = false; //[45] sell if after 10 candles, 40% of profit is lost
        Boolean sellTrigger4 = false; // sell if price drops 3% below buy price
        Boolean sellTrigger5 = false; // sell half of position at 4% profit
        Boolean sellTrigger6 = false; // create regression line after 10 candles and sell if next candle drops out of regression

        if (thirdEma45 > previousEma45 &&
            previousEma45 > currentEma45)
        {
            sellTrigger1 = true;
            //SELL!
        }

        if ((currentSo180BPercentk > currentSo180BUpperThreshold &&
            previousSo180BPercentk > currentSo180BPercentk)

            &&

            (previousEma45 > currentEma45))
        {
            sellTrigger2 = true;
            //Sell!
        }

        if (dataDropFromReg)
        {
            sellTrigger6 = true;
            //sell!
        }
    }
Example #19
0
 public Boolean triggerScenario3(DecisionData data)
 {
     return false;
 }
Example #20
0
    public Boolean triggerScenario2(DecisionData data)
    {
        //Trigger 1 data
        double previousEma45 = data.ema_45.getLastNEMA(1);
        double currentEma45 = data.ema_45.getLastNEMA(0);

        //Trigger 2 data
        double currentSo180APercentk = data.so_180_a.getLastNPercentK(0);
        double currentSo180ALowerThreshold = data.so_180_a.getLowThreshold();
        int lowerThresholdAllowance = 10;

        Boolean trigger1 = false; //EMA[45] has positive slope
        Boolean trigger2 = false; // [180] 14,3,3 gives buy signal

        if (previousEma45 < currentEma45)
        {
            trigger1 = true;
        }

        if (currentSo180APercentk > currentSo180ALowerThreshold &&
            currentSo180APercentk < (currentSo180ALowerThreshold + lowerThresholdAllowance))
        {
            trigger2 = true;
        }

        return (trigger1 && trigger2);
    }
Example #21
0
    public Boolean triggerScenario1(DecisionData data)
    {
        //testing data
        double curr_180_percent_d = data.so_180_b.getLastNPercentD(0);
        //testing data

        //Trigger 1 data
        double previousEma45 = data.ema_45.getLastNEMA(1);
        double currentEma45 = data.ema_45.getLastNEMA(0);

        //Trigger 2 data
        double currentSo180BPercentk = data.so_180_b.getLastNPercentK(0);
        currentSo180BPercentk = currentSo180BPercentk * 100;
        double currentSo180BLowerThreshold = data.so_180_b.getLowThreshold();
        int lowerThresholdAllowance = 10;

        //Trigger 3 data
        double previousSo45APercentK = data.so_45_a.getLastNPercentK(1);
        double currentSo45APercentK = data.so_45_a.getLastNPercentK(0);

        double previousSo45APercentD = data.so_45_a.getLastNPercentD(1);
        double currentSo45APercentD = data.so_45_a.getLastNPercentD(0);

        double previousSo45BPercentK = data.so_45_b.getLastNPercentK(1);
        double currentSo45BPercentK = data.so_45_b.getLastNPercentK(0);

        double previousSo45BPercentD = data.so_45_b.getLastNPercentD(1);
        double currentSo45BPercentD = data.so_45_b.getLastNPercentD(0);

        Boolean trigger1 = false; //EMA[45] has positive slope
        Boolean trigger2 = false; // [180] 14,4,5 gives buy signal
        Boolean trigger3 = false; //[45] both stochastics are positive

        if (previousEma45 < currentEma45)
        {
            trigger1 = true;

        }

        if (currentSo180BPercentk > currentSo180BLowerThreshold &&
            currentSo180BPercentk < (currentSo180BLowerThreshold + lowerThresholdAllowance))
        {
            trigger2 = true;
        }

        if ((previousSo45APercentK < currentSo45APercentK) &&
             (previousSo45APercentD < currentSo45APercentD) &&
             (previousSo45BPercentK < currentSo45BPercentK) &&
             (previousSo45BPercentD < currentSo45BPercentD))
        {
            trigger3 = true;
        }

        //TeSTING
        System.Console.WriteLine("======");
        System.Console.WriteLine("Current %k = " + currentSo180BPercentk.ToString());
        System.Console.WriteLine("Crrent %d = " + curr_180_percent_d.ToString());
        System.Console.WriteLine("Lowerthresh= " + currentSo180BLowerThreshold.ToString());
        System.Console.WriteLine("allowance = " + lowerThresholdAllowance.ToString());
        System.Console.WriteLine("Trigger Status [" + trigger1 + ", " + trigger2 + ", " + trigger3);
        System.Console.WriteLine("======");
        if (trigger1 && trigger2 && trigger3) {
            Environment.Exit(0);
        }
        //TESTING

        return (trigger1 && trigger2 && trigger3);
    }
Example #22
0
    public void run(DecisionData data)
    {
        if (currentScenario == Scenario.none)
        {
            if (triggerScenario1(data))
            {
                //Trigger buy action for scenario1
                currentScenario = Scenario.scenario1;
                double limitPrice = data.bar.Close + .02;
                double price = data.bar.Close;
                String msg = "Placing buy order: amt: " + price.ToString() + " Limit: " + limitPrice.ToString();
                System.Console.WriteLine(msg);
                data.strategy.buyOrder = data.strategy.LimitOrder(OpenQuant.API.OrderSide.Buy, data.strategy.buyQty, limitPrice);
                data.strategy.buyOrder.Send();
                placeOrder(data, OpenQuant.API.OrderSide.Buy, data.strategy.buyQty, limitPrice);

            }
            else if (triggerScenario2(data))
            {
                //Trigger buy action for scenario2
                currentScenario = Scenario.scenario2;
            }
            else if (triggerScenario3(data))
            {
                //Trigger buy action for scenario3
                currentScenario = Scenario.scenario3;
            }

        }
        else
        {
            switch (currentScenario)
            {
                case Scenario.scenario1:
                    handleScenario1(data);
                    break;

                case Scenario.scenario2:
                    break;

            }
        }
    }
Example #23
0
 public void placeOrder(DecisionData data, OpenQuant.API.OrderSide side, double qty, double limit)
 {
     double price = data.bar.Close;
     String msg = "Placing order:  side: " + side.ToString() + " amt: " + price.ToString() + " Limit: " + limit.ToString() + " Qty: " + qty.ToString();
     System.Console.WriteLine(msg);
     if(side == OpenQuant.API.OrderSide.Buy)
     {
         data.strategy.buyOrder = data.strategy.LimitOrder(OpenQuant.API.OrderSide.Buy, qty, limit);
         data.strategy.buyOrder.Send();
     }
     else
     {
         data.strategy.sellOrder = data.strategy.LimitOrder(OpenQuant.API.OrderSide.Sell, qty, limit);
         data.strategy.sellOrder.Send();
     }
 }
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the decider will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the decider will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            // Create blackboard.
            Blackboard blackboard = new Blackboard();

            // Add parent blackboards.
            if (this.Blackboard != null)
            {
                blackboard.Parents.Add(this.Blackboard);
            }

            blackboard.Parents.Add(agentData.Blackboard);

            // Setup blackboard.
            Blackboard previousBlackboard = agentData.Blackboard;
            agentData.Blackboard = blackboard;

            // Deactivate child.
            IDecisionData childDecisionData = null;
            float decisionValue = this.DecideChild(agentData, ref childDecisionData);

            // Tear down.
            agentData.Blackboard = previousBlackboard;

            // Create decision data.
            if (decisionValue > 0.0f)
            {
                decisionData = new DecisionData { Blackboard = blackboard, ChildDecisionData = childDecisionData };
            }

            return decisionValue;
        }
Example #25
0
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> The SlashGames.AI.BehaviorTrees.Enums.ExecutionStatus. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            DecisionData selectorDecisionData = decisionData as DecisionData;

            if (selectorDecisionData == null)
            {
                throw new InvalidCastException(string.Format("Decision data was null or not of correct type."));
            }

            Data data = new Data {
                ActiveChildIdx = selectorDecisionData.SelectedChildIdx
            };

            agentData.CurrentTaskData = data;

            // Activate selected child.
            IDecisionData   childDecisionData = selectorDecisionData.ChildDecisionData;
            ExecutionStatus executionStatus   = ExecutionStatus.None;

            while (executionStatus == ExecutionStatus.None)
            {
                // Update child.
                ExecutionStatus childExecutionStatus = this.ActivateChild(
                    data.ActiveChildIdx, agentData, childDecisionData);

                switch (childExecutionStatus)
                {
                case ExecutionStatus.Success:
                {
                    // Invoke callback.
                    this.InvokeOnSuccess();

                    executionStatus = ExecutionStatus.Success;
                }

                break;

                case ExecutionStatus.Failed:
                case ExecutionStatus.None:
                {
                    // Try next child.
                    float decideValue      = 0.0f;
                    int   selectedChildIdx = -1;
                    if (this.CheckForTakeOverDecider(
                            agentData, data, ref selectedChildIdx, ref decideValue, ref childDecisionData))
                    {
                        data.ActiveChildIdx = selectedChildIdx;
                    }
                    else
                    {
                        executionStatus = ExecutionStatus.Failed;
                    }
                }

                break;

                default:
                {
                    executionStatus = childExecutionStatus;
                }

                break;
                }
            }

            return(executionStatus);
        }
Example #26
0
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> The SlashGames.AI.BehaviorTrees.Enums.ExecutionStatus. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            DecisionData parallelDecisionData = decisionData as DecisionData;

            if (parallelDecisionData == null)
            {
                throw new ArgumentException("Got invalid decision data, expected data for Parallel task.");
            }

            Data data = new Data();

            // Activate all children.
            ExecutionStatus executionStatus = ExecutionStatus.Running;

            data.ChildrenData = new ITaskData[this.Children.Count];
            ++agentData.CurrentDeciderLevel;
            for (int childIdx = 0; childIdx < this.Children.Count; childIdx++)
            {
                ExecutionStatus childExecutionStatus = this.Children[childIdx].Activate(
                    agentData, parallelDecisionData.ChildrenDecisionData[childIdx]);
                if (childExecutionStatus == ExecutionStatus.Failed)
                {
                    // If one fails, all others also fail.
                    executionStatus = ExecutionStatus.Failed;

                    // Don't continue as we already have a result.
                    break;
                }

                // If main task already succeeded, sub tasks don't have to be activated.
                if (childExecutionStatus == ExecutionStatus.Success && childIdx == this.MainTaskIndex)
                {
                    executionStatus = ExecutionStatus.Success;
                    break;
                }

                // If not running, the child task don't have to be added to running children.
                if (childExecutionStatus != ExecutionStatus.Running)
                {
                    continue;
                }

                data.ChildrenData[childIdx] = agentData.CurrentTaskData;
                data.RunningChildren.Add(childIdx);
            }

            if (executionStatus != ExecutionStatus.Running)
            {
                // Deactivate remaining running children.
                foreach (int childIdx in data.RunningChildren)
                {
                    agentData.CurrentTaskData = data.ChildrenData[childIdx];
                    this.Children[childIdx].Deactivate(agentData);
                }
            }

            --agentData.CurrentDeciderLevel;

            // Store task data.
            agentData.CurrentTaskData = data;

            return(executionStatus);
        }