Esempio n. 1
0
        private IRecommendationEngine GetRecommendationEngine(CommerceDataSourceContext context, ParsedGenericCommerceDataSourceSettings settings, out ISet <string> toIgnoreItems)
        {
            var filter = settings.Filters.Find(f => f.Name == "ByProduct");

            if (filter != null)
            {
                var productId = (int)filter.GetParameterValue("ProductId");

                toIgnoreItems = new HashSet <string> {
                    productId.ToString()
                };

                return(new FeatureBasedRecommendationEngine(new[] { new Feature(productId.ToString()) }, RelatedItemsProviders.GetProviders(context.Instance)));
            }
            else
            {
                toIgnoreItems = new HashSet <string>();

                foreach (var behaviorType in BehaviorTypes.All())
                {
                    var store = BehaviorStores.Get(context.Instance, behaviorType);
                    foreach (var itemId in store.GetItemsUserHadBehaviorsOn(context.HttpContext.EnsureVisitorUniqueId(), 10000))
                    {
                        toIgnoreItems.Add(itemId);
                    }
                }

                return(RecommendationEngines.GetEngines(context.Instance));
            }
        }
Esempio n. 2
0
        public static void Initialize(string instance)
        {
            var defaultBehaviorWeights = new Dictionary <string, float>
            {
                { BehaviorTypes.View, .5f },
                { BehaviorTypes.AddToCart, .7f },
                { BehaviorTypes.Purchase, 1f }
            };

            foreach (var behaviorType in BehaviorTypes.All())
            {
                BehaviorStores.Register(instance, behaviorType, new SqlceBehaviorStore(instance, behaviorType));

                float weight = defaultBehaviorWeights[behaviorType];
                var   config = BehaviorConfig.Load(instance, behaviorType);
                if (config != null)
                {
                    weight = config.Weight;
                }

                var matrix = new SqlceSimilarityMatrix(instance, behaviorType, "Similarity_" + behaviorType);
                SimilarityMatrixes.Register(instance, behaviorType, matrix);
                RelatedItemsProviders.Register(instance, new ItemToItemRelatedItemsProvider(matrix), weight);
            }

            BehaviorReceivers.Set(instance, new BufferedBehaviorReceiver(new BehaviorReceiver(instance), 1000, TimeSpan.FromSeconds(5)));
            RecommendationEngines.Register(instance, CreateRecommendationEngines(instance));

            Schedulers.Start(instance);
            ScheduleJobs(instance);
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Noise"/> class.
        /// </summary>
        /// <param name="name">The identifier of the simulation.</param>
        /// <param name="output">The output node identifier.</param>
        /// <param name="reference">The reference output node identifier.</param>
        /// <param name="input">The input source identifier.</param>
        /// <param name="frequencySweep">The frequency sweep.</param>
        public Noise(string name, string output, string reference, string input, Sweep <double> frequencySweep) : base(name, frequencySweep)
        {
            Configurations.Add(new NoiseConfiguration(output, reference, input));

            // Add behavior types in the order they are (usually) called
            BehaviorTypes.Add(typeof(INoiseBehavior));
        }
    void Update()
    {
        if (behaviorSwitch)
        {
            if (Time.time >= behaviorSwitchDelay && behaviorCounter != -1)
            {
                if (behaviorCounter == 0)
                {
                    currentBehavior     = secondaryBehavior;
                    behaviorSwitchDelay = Time.time + secondaryBehaviorDuration;
                    delay           = secondaryBehaviorDelay;
                    behaviorCounter = 1;

                    if (permanentSwitch)
                    {
                        behaviorCounter = -1;
                    }
                }
                else
                {
                    currentBehavior     = primaryBehavior;
                    behaviorSwitchDelay = Time.time + primaryBehaviorDuration;
                    delay           = primaryBehaviorDelay;
                    behaviorCounter = 0;
                }
            }
        }
    }
Esempio n. 5
0
    public IBTNode GetTree(BehaviorTypes type)
    {
        XmlDocument xml = ReadFile(Enum.GetName(typeof(BehaviorTypes), type));

        return(CreateTreeFromXML(xml.ChildNodes));
        //return null;
    }
Esempio n. 6
0
        /// <summary>
        /// Set up the simulation.
        /// </summary>
        /// <param name="entities">Entities that are included in the simulation.</param>
        /// <exception cref="ArgumentNullException">circuit</exception>
        /// <exception cref="CircuitException">{0}: No circuit objects for simulation".FormatString(Name)</exception>
        protected virtual void Setup(EntityCollection entities)
        {
            if (entities == null)
            {
                throw new ArgumentNullException(nameof(entities));
            }
            if (entities.Count == 0)
            {
                throw new CircuitException("{0}: No circuit objects for simulation".FormatString(Name));
            }

            // Use the same comparers as the circuit. This is crucial because they use the same identifiers!
            EntityParameters = new ParameterPool(entities.Comparer);
            EntityBehaviors  = new BehaviorPool(entities.Comparer, BehaviorTypes.ToArray());

            // Create the variables that will need solving
            if (Configurations.TryGet(out CollectionConfiguration cconfig))
            {
                Variables        = new VariableSet(cconfig.VariableComparer ?? EqualityComparer <string> .Default);
                _cloneParameters = cconfig.CloneParameters;
            }
            else
            {
                Variables        = new VariableSet();
                _cloneParameters = false;
            }

            // Setup all entity parameters and behaviors
            SetupParameters(entities);
            SetupBehaviors(entities);
        }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FrequencySimulation"/> class.
        /// </summary>
        /// <param name="name">The identifier of the simulation.</param>
        /// <param name="frequencySweep">The frequency sweep.</param>
        protected FrequencySimulation(string name, Sweep <double> frequencySweep) : base(name)
        {
            Configurations.Add(new FrequencyConfiguration(frequencySweep));

            // Add behavior types in the order they are (usually) called
            BehaviorTypes.Add(typeof(IFrequencyBehavior));
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Noise"/> class.
        /// </summary>
        /// <param name="name">The identifier of the simulation.</param>
        public Noise(string name) : base(name)
        {
            Configurations.Add(new NoiseConfiguration());

            // Add behavior types in the order they are (usually) called
            BehaviorTypes.Add(typeof(INoiseBehavior));
        }
Esempio n. 9
0
        static void ScheduleJobs(string instance)
        {
            var scheduler = Schedulers.Get(instance);

            foreach (var behaviorType in BehaviorTypes.All())
            {
                var jobName = "Recompute similarity matrix (" + behaviorType + ")";
                var config  = JobConfig.Load(instance, jobName);
                if (config == null)
                {
                    config = new JobConfig
                    {
                        JobName   = jobName,
                        Interval  = TimeSpan.FromHours(24),
                        StartTime = new TimeOfDay(2, 0)
                    };
                }

                var job = new RecomputeSimilarityMatrixJob();

                scheduler.Schedule(jobName, job, config.Interval, config.StartTime, new Dictionary <string, string>
                {
                    { "BehaviorType", behaviorType }
                });
            }
        }
 public CreateCommand(IEngine engine, string name, int health, int damage, BehaviorTypes behavior, AttackTypes attack)
     : base(engine)
 {
     this.name     = name;
     this.health   = health;
     this.damage   = damage;
     this.behavior = behavior;
     this.attack   = attack;
 }
    void Start()
    {
        behaviorSwitchDelay = Time.time + primaryBehaviorDuration;
        currentBehavior     = primaryBehavior;
        delay = primaryBehaviorDelay;

        unit = GetComponent <Unit>();
        StartCoroutine("MoveToLocation");
    }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FrequencySimulation"/> class.
        /// </summary>
        /// <param name="name">The identifier of the simulation.</param>
        protected FrequencySimulation(string name) : base(name)
        {
            Configurations.Add(new FrequencyConfiguration());
            FrequencySimulationStatistics = new ComplexSimulationStatistics();
            Statistics.Add(typeof(ComplexSimulationStatistics), FrequencySimulationStatistics);

            // Add behavior types in the order they are (usually) called
            BehaviorTypes.Add(typeof(IFrequencyBehavior));
        }
 public CreateCommand(IEngine engine, string name, int health, int damage, BehaviorTypes behavior, AttackTypes attack)
     : base(engine)
 {
     this.name = name;
     this.health = health;
     this.damage = damage;
     this.behavior = behavior;
     this.attack = attack;
 }
Esempio n. 14
0
        /// <summary>
        /// Set up all behaviors previously created.
        /// </summary>
        /// <param name="entities">The circuit entities.</param>
        private void SetupBehaviors(EntityCollection entities)
        {
            var types = BehaviorTypes.ToArray();

            foreach (var entity in entities)
            {
                entity.CreateBehaviors(types, this, entities);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TimeSimulation"/> class.
        /// </summary>
        /// <param name="name">The identifier of the simulation.</param>
        protected TimeSimulation(string name) : base(name)
        {
            Configurations.Add(new TimeConfiguration());

            // Add the behavior in the order they are (usually) called
            BehaviorTypes.AddRange(new []
            {
                typeof(ITimeBehavior),
                typeof(IAcceptBehavior)
            });
        }
Esempio n. 16
0
 internal void HideButtons(BehaviorTypes triggers)
 {
     if (triggers == BehaviorTypes.Triggers)
     {
         Hide("Triggers");
     }
     if (triggers == BehaviorTypes.Actions)
     {
         Hide("Actions");
     }
 }
Esempio n. 17
0
    public void SetOptions(BehaviorBase[] behaviors, BehaviorTypes type)
    {
        if (type == BehaviorTypes.Actions)
        {
            SetLookAndFeel(behaviors, ActionButtons);
        }

        if (type == BehaviorTypes.Triggers)
        {
            SetLookAndFeel(behaviors, TriggerButtons);
        }
    }
Esempio n. 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseSimulation"/> class.
        /// </summary>
        /// <param name="name">The identifier of the simulation.</param>
        protected BaseSimulation(string name)
            : base(name)
        {
            Configurations.Add(new BaseConfiguration());

            // Add the necessary behaviors in the order that they are (usually) called
            BehaviorTypes.AddRange(new []
            {
                typeof(ITemperatureBehavior),
                typeof(IBiasingBehavior),
                typeof(IInitialConditionBehavior)
            });
        }
Esempio n. 19
0
 public void BuildObject(BehaviorTypes type, int count)
 {
     if (type == BehaviorTypes.Actions)
     {
         Destroy("Actions");
         Create("Actions", BehaviorTypes.Actions, count);
     }
     else
     {
         Destroy("Triggers");
         Create("Triggers", BehaviorTypes.Triggers, count);
     }
 }
Esempio n. 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TimeSimulation"/> class.
        /// </summary>
        /// <param name="name">The identifier of the simulation.</param>
        /// <param name="step">The step size.</param>
        /// <param name="final">The final time.</param>
        /// <param name="maxStep">The maximum step.</param>
        protected TimeSimulation(string name, double step, double final, double maxStep)
            : base(name)
        {
            Configurations.Add(new TimeConfiguration(step, final, maxStep));
            TimeSimulationStatistics = new TimeSimulationStatistics();
            Statistics.Add(typeof(TimeSimulationStatistics), TimeSimulationStatistics);

            // Add the behavior in the order they are (usually) called
            BehaviorTypes.AddRange(new []
            {
                typeof(ITimeBehavior),
                typeof(IAcceptBehavior)
            });
        }
Esempio n. 21
0
    private void Create(string underChild, BehaviorTypes buttonType, int count)
    {
        var canvasMenu = GetComponent<CanvasMenu>();
        List<GameObject> gameObjects = new List<GameObject>();
        for (int i = 0; i < count; i++)
        {
            GameObject button;
            if (count <= 5)
            {
                var offSet = buttonType == BehaviorTypes.Actions ? -13.0f : 13.0f;

                button = Instantiate(obj) as GameObject;
                button.transform.SetParent(this.transform.FindChild(underChild).transform);
                button.transform.localScale = new Vector3(1.2f, 1.2f, 1.2f);
                button.transform.localPosition = new Vector3(offSet, -85f * i - 50, 0);
            }
            else if (count > 5 && count < 8)
            {
                var offSet = buttonType == BehaviorTypes.Actions ? -13f : 13f;

                button = Instantiate(obj) as GameObject;
                button.transform.SetParent(this.transform.FindChild(underChild).transform);
                button.transform.localScale = new Vector3(1.1f, 1.1f, 1);
                button.transform.localPosition = new Vector3(offSet, -75f * i - 40, 0);
            }
            else
            {
                var offSet = buttonType == BehaviorTypes.Actions ? -37.5f : -12.5f;

                button = Instantiate(obj) as GameObject;
                button.transform.SetParent(this.transform.FindChild(underChild).transform, true);
                button.transform.localScale = new Vector3(0.75f, 0.75f, 1);
                button.transform.localPosition = new Vector3(offSet + 50 * (i % 2), -50f * Mathf.CeilToInt(i / 2) - 70f, 0);
            }

            gameObjects.Add(button);
        }

        if (buttonType == BehaviorTypes.Triggers)
        {
            canvasMenu.TriggerButtons = gameObjects.ToArray();
        }
        else
        {
            canvasMenu.ActionButtons = gameObjects.ToArray();
        }
    }
Esempio n. 22
0
        static WeightedRecommendationEngineCollection CreateRecommendationEngines(string instance)
        {
            var engines = new WeightedRecommendationEngineCollection();

            foreach (var behaviorType in BehaviorTypes.All())
            {
                var featureBuilder = new BehaviorBasedFeatureBuilder(() =>
                {
                    var store = BehaviorStores.Get(instance, behaviorType);
                    return(store.GetRecentBehaviors(50));
                });

                var engine = new FeatureBasedRecommendationEngine(featureBuilder, RelatedItemsProviders.GetProviders(instance));
                engines.Add(engine, 1f);
            }

            return(engines);
        }
Esempio n. 23
0
 public void ClearImages(BehaviorTypes behaviorType)
 {
     if (behaviorType == BehaviorTypes.Actions)
     {
         foreach (var item in Enum.GetValues(typeof(SpecialTypes)))
         {
             var visualGameObject = transform.Find("Special/" + Enum.GetName(typeof(SpecialTypes), item)).gameObject;
             visualGameObject.SetActive(false);
         }
     }
     if (behaviorType == BehaviorTypes.Triggers)
     {
         foreach (var item in Enum.GetValues(typeof(HoseTypes)))
         {
             var visualGameObject = transform.Find("Hose/" + Enum.GetName(typeof(HoseTypes), item)).gameObject;
             visualGameObject.SetActive(false);
         }
     }
 }
Esempio n. 24
0
        public static IBlob Create(string name, int health, int damage, BehaviorTypes behavior, AttackTypes attack)
        {
            int blobHealth = health;

            int attackDamage = new int();

            if (attack == AttackTypes.PutridFart)
            {
                attackDamage = damage;
            }
            else if (attack == AttackTypes.Blobplode)
            {
                attackDamage = 2 * damage;
            }

            IAttack blobAttack = AttackFactory.Create(attackDamage, attack);

            IBehavior blobBehavior = BehaviorFactory.Create(behavior);

            return(new Blob(name, blobHealth, damage, blobAttack, blobBehavior));
        }
        public static IBlob Create(string name, int health, int damage, BehaviorTypes behavior, AttackTypes attack)
        {
            int blobHealth = health;

            int attackDamage = new int();

            if (attack == AttackTypes.PutridFart)
            {
                attackDamage = damage;
            }
            else if (attack == AttackTypes.Blobplode)
            {
                attackDamage = 2 * damage;
            }

            IAttack blobAttack = AttackFactory.Create(attackDamage, attack);

            IBehavior blobBehavior = BehaviorFactory.Create(behavior);

            return new Blob(name, blobHealth, damage, blobAttack, blobBehavior);          
        }
Esempio n. 26
0
    public void BeginBehavior(BehaviorTypes type)
    {
        currentBehavior = type;
        AIPath.maxSpeed = stats[(int)type].movementSpeed;

        tilemapSeen.GetComponent <TilemapRenderer>().enabled = false;
        switch (type)
        {
        case BehaviorTypes.IDLE:
        {
            timeLeftPausing = idlePauseTime;
            break;
        }

        case BehaviorTypes.WANDER_TOWARDS:
        {
            break;
        }

        case BehaviorTypes.RUN_TO_SOUND:
        {
            break;
        }

        case BehaviorTypes.FREAKOUT:
        {
            targetAStar.position     = transform.position;
            timeLeftPausing          = freakOutPauses * 3;
            timeBeforeBehaviorChange = freakOutTime;
            SetUpFreakoutGrid();
            break;
        }

        case BehaviorTypes.CHASE_PLAYER:
        {
            break;
        }
        }
    }
 public Behavior(BehaviorTypes types)
 {
     this.Types = types;
     this.IsTriggered = false;
 }
Esempio n. 28
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /*
        The AIBuilder method creates a config for a AI enabled entity.
        Currently it psuedorandomly assigns stats, eventually options for chosen stats and weighted random stats
        will be added.
        The AIBuilder will require switch logic to pick a set of nonconflicting behaviors.
    */
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public AIConfig AIBuilder(string type, int rWeight)
    {
        if(rWeight > (maxStatValue * numOfStats)){
            Debug.LogError("Weight is too high for the number of stats given their maximums.");
            Debug.Break();
        }
        StatCollectionClass member = gameObject.GetComponent<StatCollectionClass>();
        decisionType = type;
        bool AImade = false;
        bool isMelee = false;
        bool isHybrid = false;
        bool isAggressive = false;
        bool isStalker = false;
        bool hasMagic = false;
        bool isCautious = false;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*
            We need to vary the stats based on weight.
            Look at the weight and see if the even split (average) is between the values is over statMax (our maximum
            normalized stat value).
            If it is, assign randomly from a range between statmin to statMax.
            Otherwise assign randomly statmin to the dividend of weight total with # of stats and add the modulus
            remainder. This will give stats that fairly equalized to the weight. Let AdjustStats fix any underages or
            overages.
        */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        int[] split = new int[numOfStats];

        if ((rWeight / numOfStats) > maxStatValue) { //Upper bound on stats, might not be needed if things are weighted right.
            int remain = rWeight;
            for (int i = 0; i < numOfStats; i++) {
                split [i] = Random.Range (minStatValue, maxStatValue);
                //For Testing: print ("Random value for stat #" + i.ToString () + " : " + split [i].ToString ());
                remain = remain - split [i];
            }
        } else {
            for (int i = 0; i < numOfStats; i++) {
                split [i] = Random.Range (minStatValue, (rWeight / numOfStats) + rWeight % numOfStats);
                //For Testing: print ("Random value for stat #" + i.ToString () + " : " + split [i].ToString ());
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*
         	Sum all the stats together to so we can compare it to weight.
         	Calculate the expected sum and actual sum diff for our AdjustStats call.
        */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        int sumR;
        AdjustStats (split, rWeight);

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*
             Finally check that the final sum is correct.
         	 If the sum is correct set AImade true and carry on!
             Otherwise throw nasty errors and annoy us.
             TODO Have this loop back to AdjustStats, error if it fails to properly adjust it again.(We should never
             hit this second call ideally.)
        */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        //Testing
        //for(int j = 0; j < numOfStats; j++){
            //print("Final random stats" + split[j].ToString());
        //}
        //

        sumR = sumArray (split);
        //print ("The sum is " + sumR.ToString () + " It is supposed to be " + rWeight.ToString ());

        if (sumR == rWeight) {
            AImade = true;
        }

        if (AImade) {
            AssignStats(split);
        } else {
            Debug.LogError ("AIManager failed to create a proper AIBuild");
        }

        AIConfig config = new AIConfig ();

        #pragma warning disable
        BehaviorTypes assignBehavior = new BehaviorTypes ();
        #pragma warning restore

        switch(type){
        case "mob":
            if(member.health > 0){
                //Visual adjustments for health thresholds.
            }
            if(member.mana > 0){
                //Visual adjustments for mana thresholds.
                hasMagic = true;
            }
            if(member.strength > 6){
                isMelee = true;
                isAggressive = true;
                //Visual adjustments for being melee.
            }
            if(member.intellect > 6 && member.strength >= member.intellect){
                isCautious = true;
                isHybrid = true;
                //Visual adjustments for being cautious.
            }
            if(member.intellect > 6 && member.intellect >= member.strength){
                isStalker = true;
                //Visual adjustments for being a stalker.
            }

            config.isMelee = isMelee;
            config.isHybrid = isHybrid;
            config.hasMagic = hasMagic;
            config.isAggressive = isAggressive;
            config.isCautious = isCautious;
            config.isStalker = isStalker;

            if(isHybrid)
                config = assignBehavior.intializeHybridGeneric (config);
            else if(isMelee)
                config = assignBehavior.intializeMeleeGeneric (config);
            else
                config = assignBehavior.intializeRangedGeneric (config);

            AssignModifiers(config);
            config.isMade = AImade;
            break;
        case "npc":
            //Stuff might go here?
            break;
        case "boss":
            //Boss mechanics to be decided.
            break;
        default:
            Debug.LogError (type + ": is not a supported type.");
            break;
        }

        print(config.ToString ());

        return config;
    }
 public Behavior(BehaviorTypes types)
 {
     this.Types       = types;
     this.IsTriggered = false;
 }
Esempio n. 30
0
 ///<summary>
 ///Tests if a specific bit of <see cref="_flags"/> is set
 ///</summary>
 ///<param name="bt"></param>
 ///<returns>
 ///true if a specific bit of <see cref="_flags"/> is set
 ///</returns>
 private bool On(BehaviorTypes bt)
 {
     return (Flags & (int) bt) == (int) bt;
 }
Esempio n. 31
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /*
     *      The AIBuilder method creates a config for a AI enabled entity.
     *      Currently it psuedorandomly assigns stats, eventually options for chosen stats and weighted random stats
     *      will be added.
     *      The AIBuilder will require switch logic to pick a set of nonconflicting behaviors.
     */
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public AIConfig AIBuilder(string type, int rWeight)
    {
        if (rWeight > (maxStatValue * numOfStats))
        {
            Debug.LogError("Weight is too high for the number of stats given their maximums.");
            Debug.Break();
        }
        StatCollectionClass member = gameObject.GetComponent <StatCollectionClass>();

        decisionType = type;
        bool AImade       = false;
        bool isMelee      = false;
        bool isHybrid     = false;
        bool isAggressive = false;
        bool isStalker    = false;
        bool hasMagic     = false;
        bool isCautious   = false;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /*
         *      We need to vary the stats based on weight.
         *      Look at the weight and see if the even split (average) is between the values is over statMax (our maximum
         *      normalized stat value).
         *      If it is, assign randomly from a range between statmin to statMax.
         *      Otherwise assign randomly statmin to the dividend of weight total with # of stats and add the modulus
         *      remainder. This will give stats that fairly equalized to the weight. Let AdjustStats fix any underages or
         *      overages.
         */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        int[] split = new int[numOfStats];

        if ((rWeight / numOfStats) > maxStatValue)           //Upper bound on stats, might not be needed if things are weighted right.
        {
            int remain = rWeight;
            for (int i = 0; i < numOfStats; i++)
            {
                split [i] = Random.Range(minStatValue, maxStatValue);
                //For Testing: print ("Random value for stat #" + i.ToString () + " : " + split [i].ToString ());
                remain = remain - split [i];
            }
        }
        else
        {
            for (int i = 0; i < numOfStats; i++)
            {
                split [i] = Random.Range(minStatValue, (rWeight / numOfStats) + rWeight % numOfStats);
                //For Testing: print ("Random value for stat #" + i.ToString () + " : " + split [i].ToString ());
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /*
         *      Sum all the stats together to so we can compare it to weight.
         *      Calculate the expected sum and actual sum diff for our AdjustStats call.
         */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        int sumR;

        AdjustStats(split, rWeight);

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /*
         *       Finally check that the final sum is correct.
         *       If the sum is correct set AImade true and carry on!
         *       Otherwise throw nasty errors and annoy us.
         *       TODO Have this loop back to AdjustStats, error if it fails to properly adjust it again.(We should never
         *       hit this second call ideally.)
         */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        //Testing
        //for(int j = 0; j < numOfStats; j++){
        //print("Final random stats" + split[j].ToString());
        //}
        //

        sumR = sumArray(split);
        //print ("The sum is " + sumR.ToString () + " It is supposed to be " + rWeight.ToString ());

        if (sumR == rWeight)
        {
            AImade = true;
        }


        if (AImade)
        {
            AssignStats(split);
        }
        else
        {
            Debug.LogError("AIManager failed to create a proper AIBuild");
        }

        AIConfig config = new AIConfig();

                #pragma warning disable
        BehaviorTypes assignBehavior = new BehaviorTypes();
                #pragma warning restore

        switch (type)
        {
        case "mob":
            if (member.health > 0)
            {
                //Visual adjustments for health thresholds.
            }
            if (member.mana > 0)
            {
                //Visual adjustments for mana thresholds.
                hasMagic = true;
            }
            if (member.strength > 6)
            {
                isMelee      = true;
                isAggressive = true;
                //Visual adjustments for being melee.
            }
            if (member.intellect > 6 && member.strength >= member.intellect)
            {
                isCautious = true;
                isHybrid   = true;
                //Visual adjustments for being cautious.
            }
            if (member.intellect > 6 && member.intellect >= member.strength)
            {
                isStalker = true;
                //Visual adjustments for being a stalker.
            }

            config.isMelee      = isMelee;
            config.isHybrid     = isHybrid;
            config.hasMagic     = hasMagic;
            config.isAggressive = isAggressive;
            config.isCautious   = isCautious;
            config.isStalker    = isStalker;

            if (isHybrid)
            {
                config = assignBehavior.intializeHybridGeneric(config);
            }
            else if (isMelee)
            {
                config = assignBehavior.intializeMeleeGeneric(config);
            }
            else
            {
                config = assignBehavior.intializeRangedGeneric(config);
            }


            AssignModifiers(config);
            config.isMade = AImade;
            break;

        case "npc":
            //Stuff might go here?
            break;

        case "boss":
            //Boss mechanics to be decided.
            break;

        default:
            Debug.LogError(type + ": is not a supported type.");
            break;
        }


        print(config.ToString());

        return(config);
    }
 public static IBehavior Create(BehaviorTypes type)
 {
     return(new Behavior(type));
 }
 public static IBehavior Create(BehaviorTypes type)
 {
     return new Behavior(type);
 }
Esempio n. 34
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /*
        The AIBuilder method creates a config for a AI enabled entity.
        Currently it psuedorandomly assigns stats, eventually options for chosen stats and weighted random stats
        will be added.
        The AIBuilder will require switch logic to pick a set of nonconflicting behaviors.
    */
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
    public AIConfig AIBuilder(string type, int rWeight, int minStatValue, int maxStatValue)
    {
        if(rWeight > (maxStatValue * numOfStats)){
            Debug.LogError("Weight is too high for the number of stats given their maximums.");
            return default(AIConfig);
        }

        GameObject unitySucks = new GameObject ();

        AIConfig config = new AIConfig ();
        config.statExchange = unitySucks.AddComponent<StatCollectionClass> ();

        if (config.statExchange.Equals (null)) {
            Debug.LogError("Unity sucks");
        }

        bool AImade = false;
        bool isMelee = false;
        bool isHybrid = false;
        bool isAggressive = false;
        bool isStalker = false;
        bool hasMagic = false;
        bool isCautious = false;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*
            We need to vary the stats based on weight.
            Look at the weight and see if the even split (average) is between the values is over statMax (our maximum
            normalized stat value).
            If it is, assign randomly from a range between statmin to statMax.
            Otherwise assign randomly statmin to the dividend of weight total with # of stats and add the modulus
            remainder. This will give stats that fairly equalized to the weight. Let AdjustStats fix any underages or
            overages.
        */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        int[] split = new int[numOfStats];

        if ((rWeight / numOfStats) > maxStatValue) { //Upper bound on stats, might not be needed if things are weighted right.
            int remain = rWeight;
            for (int i = 0; i < numOfStats; i++) {
                split [i] = Random.Range (minStatValue, maxStatValue);
                remain = remain - split [i];
            }
        } else {
            for (int i = 0; i < numOfStats; i++) {
                split [i] = Random.Range (minStatValue, (rWeight / numOfStats) + rWeight % numOfStats);
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*
         	Sum all the stats together to so we can compare it to weight.
         	Calculate the expected sum and actual sum diff for our AdjustStats call.
        */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        int sumR;
        AdjustStats (split, rWeight, minStatValue, maxStatValue);

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*
             Finally check that the final sum is correct.
         	 If the sum is correct set AImade true and carry on!
             Otherwise throw nasty errors and annoy us.
             TODO Have this loop back to AdjustStats, error if it fails to properly adjust it again.(We should never
             hit this second call ideally.)
        */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        sumR = sumArray (split);
        if (sumR == rWeight) {
            AImade = true;
        }

        if (AImade) {
            AssignStats(split, unitySucks.GetComponent<StatCollectionClass>());
        } else {
            Debug.LogError ("AIManager failed to create a proper AIBuild");
        }

        #pragma warning disable
        BehaviorTypes assignBehavior = new BehaviorTypes ();
        #pragma warning restore

        switch(type){
        case "mob":
            if(config.statExchange.health > 0){
            }
            if(config.statExchange.mana > 0){
                hasMagic = true;
            }
            if(config.statExchange.strength > 6){
                isMelee = true;
                isAggressive = true;
            }
            if(config.statExchange.intellect > 6 && config.statExchange.strength >= config.statExchange.intellect){
                isCautious = true;
                isHybrid = true;
            }
            if(config.statExchange.intellect > 6 && config.statExchange.intellect >= config.statExchange.strength){
                isStalker = true;
            }

            if(isMelee && !isHybrid){
                float str = config.statExchange.strength;
                float scale = (1.5f * (1f + str/50f));
                transform.localScale = new Vector3(scale, scale, 0);
                config.AIType = "Melee";
            }else if(isHybrid){
                transform.localScale = new Vector3(2f, 2f, 0);
                config.AIType = "Hybrid";
            }else{
                transform.localScale = new Vector3(1.8f, 1.8f, 0);
                config.AIType = "Ranged";
            }

            config.isMelee = isMelee;
            config.isHybrid = isHybrid;
            config.hasMagic = hasMagic;
            config.isAggressive = isAggressive;
            config.isCautious = isCautious;
            config.isStalker = isStalker;

            if(isHybrid)
                config = assignBehavior.intializeHybridGeneric(config);
            else if(isMelee)
                config = assignBehavior.intializeMeleeGeneric(config);
            else
                config = assignBehavior.intializeRangedGeneric(config);

            AssignModifiers(config);
            config.isMade = AImade;
            break;
        case "npc":
            //Stuff might go here?
            break;
        case "boss":
            if(config.statExchange.health > 0){
            }
            if(config.statExchange.mana > 0){
                hasMagic = true;
            }
            if(config.statExchange.strength > 6){
                isMelee = true;
                isAggressive = true;
            }
            if(config.statExchange.intellect > 6 && config.statExchange.strength >= config.statExchange.intellect){
                isCautious = true;
                isHybrid = true;
            }
            if(config.statExchange.intellect > 6 && config.statExchange.intellect >= config.statExchange.strength){
                isStalker = true;
            }

            if(isMelee && !isHybrid){
                float str = config.statExchange.strength;
                float scale = (1.5f * (1f + str/50f));
                transform.localScale = new Vector3(scale, scale, 0);
                config.AIType = "Melee";
            }else if(isHybrid){
                transform.localScale = new Vector3(2f, 2f, 0);
                config.AIType = "Hybrid";
            }else{
                transform.localScale = new Vector3(1.8f, 1.8f, 0);
                config.AIType = "Ranged";
            }
            config.isMelee = isMelee;
            config.isHybrid = isHybrid;
            config.hasMagic = hasMagic;
            config.isAggressive = isAggressive;
            config.isCautious = isCautious;
            config.isStalker = isStalker;

            if(isHybrid)
                config = assignBehavior.intializeHybridGeneric(config);
            else if(isMelee)
                config = assignBehavior.intializeMeleeGeneric(config);
            else
                config = assignBehavior.intializeRangedGeneric(config);

            AssignModifiers(config);
            config.isMade = AImade;
            break;
        default:
            Debug.LogError (type + ": is not a supported type.");
            break;
        }
        print(config.ToString ());

        StartCoroutine ("waitToDestroy", unitySucks);
        //Destroy (unitySucks);
        return config;
    }