Ejemplo n.º 1
0
    private bool AddBehavior(BehaviorType bt)
    {
        // 检查条件
        for (int i = 0; i < (int)(BehaviorType.BT_End); i++)
        {
            if (behavior_condition_matrix[(int)bt, i] == 1)
            {
                if (HasBehaviorType((BehaviorType)i))
                {
                    return(false);
                }
            }
        }

        // 执行行为
        AddBehaviorType(bt);

        // 产生结果
        for (int i = 0; i < (int)(BehaviorType.BT_End); i++)
        {
            if (behavior_result_matrix[(int)bt, i] == 1)
            {
                RemoveBehaviorType((BehaviorType)i);
            }
        }
        AddBehaviorType(bt);

        return(true);
    }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Character"/> class.
 /// </summary>
 /// <param name="world">World character currently resides in.</param>
 /// <param name="x">The tile x position.</param>
 /// <param name="y">The tile y position.</param>
 /// <param name="behavior">The type of behavior controlling this character</param>
 public Character(World world, int x, int y, BehaviorType behavior = BehaviorType.None)
 {
     this.world = world;
     this.x = this.newX = x;
     this.y = this.newY = y;
     _baseType = -1;
     _hairType = -1;
     _legsType = -1;
     _torsoType = -1;
     _headType = -1;
     _shieldType = -1;
     _weaponType = -1;
     this.behavior = new CharacterBehavior(this, behavior);
     // Set default stats based on behavior
     switch (behavior)
     {
         case BehaviorType.Villager:
             this.maxHealth = this.health = 100;
             this.attack = 5;
             this.defense = 0;
             this.friendly = true;
             break;
         case BehaviorType.None:
         default:
             this.maxHealth = this.health = 1;
             this.attack = this.defense = 0;
             this.friendly = true;
             break;
     }
 }
Ejemplo n.º 3
0
 public Behavior(
     BehaviorType type,
     bool enabled = true)
 {
     this.enabled = enabled;
     this.type    = type;
 }
Ejemplo n.º 4
0
        public static void Add(BehaviorType behavior, int categoryID, string productSKU, string searchString,
                               int adID, int promoID, string pageUrl)
        {
            //get the page from the server
            if (pageUrl == string.Empty)
            {
                pageUrl = System.Web.HttpContext.Current.Request.Url.PathAndQuery;
            }

            string sessionID = System.Web.HttpContext.Current.Session.SessionID;

            Tracker track = new Tracker();

            track.Behavior     = behavior;
            track.CategoryID   = categoryID;
            track.ProductSKU   = productSKU;
            track.SearchString = searchString;
            track.AdID         = adID;
            track.PromoID      = promoID;
            track.PageURL      = pageUrl;
            track.SessionID    = sessionID;
            track.UserName     = Utility.GetUserName();

            Add(track);
        }
Ejemplo n.º 5
0
 public void SetBehavior(BehaviorType behavior)
 {
     switch (behavior)
     {
         case BehaviorType.FastAttack:
             this.Behavior = new FastAttack(owner);
             break;
         case BehaviorType.SmartAttack:
             this.Behavior = new SmartAttack(owner);
             break;
         case BehaviorType.StandAndDefend:
             this.Behavior = new StandAndDefend(owner);
             break;
         case BehaviorType.EvadeAndShoot:
             this.Behavior = new EvadeAndShoot(owner);
             break;
         case BehaviorType.Flee:
             this.Behavior = new Flee(owner);
             break;
         case BehaviorType.NoAI:
             this.Behavior = new NoAI(owner);
             break;
         default:
             this.Behavior = new StandAndDefend(owner);
             break;
     }
 }
Ejemplo n.º 6
0
        internal static IBehaviorHandler CreateBehaviorHandler(BehaviorType behaviorType, IActor actor, WeakReference <MixedRealityExtensionApp> appRef)
        {
            if (s_behaviorHandlerTypeLookup.ContainsKey(behaviorType))
            {
                var methodInfo = s_behaviorHandlerTypeLookup[behaviorType].GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic);
                if (methodInfo != null)
                {
                    try
                    {
                        return((IBehaviorHandler)methodInfo.Invoke(null, new object[] { actor, appRef }));
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                        return(null);
                    }
                }
                else
                {
                    throw new NotImplementedException($"A handler for the behavior type {behaviorType.ToString()} exists but does not have a static create method implemented on it.");
                }
            }

            MixedRealityExtensionApp app;

            if (appRef.TryGetTarget(out app))
            {
                app.Logger.LogError($"Trying to create a behavior of type {behaviorType.ToString()}, but no handler is registered for the given type.");
            }
            return(null);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Removes the behavior with the specified BehaviorType.
        /// Void operation if there is no behavior of that type to remove.
        /// </summary>
        /// <param name="behaviorType">The <see cref="BehaviorType"/>.</param>
        public void RemoveBehavior(BehaviorType behaviorType)
        {
            var wasInteractor = IsInteractor;

            _behaviors.RemoveAll(x => x.BehaviorType == behaviorType);
            NotifyIfInteractorStatusChanged(wasInteractor);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Updates or creates a resource based on the resource identifier. The PUT operation is used to update or create a resource by identifier.  If the resource doesn't exist, the resource will be created using that identifier.  Additionally, natural key values cannot be changed using this operation, and will not be modified in the database.  If the resource &quot;id&quot; is provided in the JSON body, it will be ignored as well.
        /// </summary>
        /// <param name="id">A resource identifier specifying the resource to be updated.</param>
        /// <param name="IfMatch">The ETag header value used to prevent the PUT from updating a resource modified by another consumer.</param>
        /// <param name="body">The JSON representation of the &quot;behaviorType&quot; resource to be updated.</param>
        /// <returns>A RestSharp <see cref="IRestResponse"/> instance containing the API response details.</returns>
        public IRestResponse PutBehaviorType(string id, string IfMatch, BehaviorType body)
        {
            var request = new RestRequest("/behaviorTypes/{id}", Method.PUT);

            request.RequestFormat = DataFormat.Json;

            request.AddUrlSegment("id", id);
            // verify required params are set
            if (id == null || body == null)
            {
                throw new ArgumentException("API method call is missing required parameters");
            }
            request.AddHeader("If-Match", IfMatch);
            request.AddBody(body);
            request.Parameters.First(param => param.Type == ParameterType.RequestBody).Name = "application/json";
            var response = client.Execute(request);

            var location = response.Headers.FirstOrDefault(x => x.Name == "Location");

            if (location != null && !string.IsNullOrWhiteSpace(location.Value.ToString()))
            {
                body.id = location.Value.ToString().Split('/').Last();
            }
            return(response);
        }
Ejemplo n.º 9
0
        private static BehaviorType ReadBehavior(XmlNode xmlBehavior)
        {
            if (xmlBehavior == null)
            {
                return(new BehaviorType());
            }
            List <double> l = new List <double>();

            string[]     s = XmlUtilities.GetAttributeValue(xmlBehavior, "list").Split(new char[] { ',' });
            BehaviorType b = new BehaviorType();

            foreach (string str in s)
            {
                if (str != "")
                {
                    l.Add(double.Parse(str));
                }
            }
            b.behaviorList = l;
            return(b);

            /*
             * if (xmlBehavior == null)
             *  return new BehaviorType();
             * List<double> l = new List<double>();
             * string[] s = XmlUtilities.GetAttributeValue(xmlBehavior, "vals").Split(new char[] { ',' });
             * BehaviorType b = new BehaviorType();
             * foreach (string str in s)
             * {
             *  if(str!="")
             *      l.Add(double.Parse(str));
             * }
             * b.behaviorList = l;
             * return b;*/
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Create a XmlElement that contains all data required to save in file
        /// </summary>
        /// <returns></returns>
        public XmlElement ToXmlElement()
        {
            XmlElement behavior = new XmlElement("Behavior");

            behavior.SetAttributeValue("BehaviorType", BehaviorType.ToString());
            behavior.SetAttributeValue("Name", Name);
            behavior.SetAttributeValue("Id", Id);
            behavior.SetAttributeValue("Weight", Weight);
            behavior.SetAttributeValue("Concurrency", Concurrency.ToString());

            //if (_Parameters != null && _Parameters.Count > 0)
            //{
            //    XmlElement childParameters = new XmlElement("ChildParameters");
            //    foreach (var p in _Parameters)
            //        childParameters.AppendChild(p.ToXmlElement());
            //    behavior.AppendChild(childParameters);
            //}

            if (!string.IsNullOrEmpty(Comment))
            {
                XmlElement comment = new XmlElement("Comment");
                comment.Value = Comment;
                behavior.AppendChild(comment);
            }


            WriteAttributes(behavior); // allow subclass to add additional data
            return(behavior);
        }
Ejemplo n.º 11
0
    public static Behavior CreateBehavior(BehaviorType type)
    {
        if (type == BehaviorType.Move)
        {
            return(new MoveBehavior());
        }
        if (type == BehaviorType.Turn)
        {
            return(new TurnBehavior());
        }
        if (type == BehaviorType.Dash)
        {
            return(new DashBehavior());
        }
        if (type == BehaviorType.Follow)
        {
            return(new FollowBehavior());
        }
        if (type == BehaviorType.JoyStickMove)
        {
            return(new JoyStickBehavior());
        }
        if (type == BehaviorType.Adsorb)
        {
            return(new AdsorbBehavior());
        }

        Debug.LogWarning("Undefined Behavior Type");
        return(null);
    }
Ejemplo n.º 12
0
        // 在Behavior List中,每种类型的Behavior,最多只有一个
        public void RemoveBehavior(BehaviorType type)
        {
            LinkedListNode <Behavior> cur_node = _ActiveBehaviorList.First;

            while (cur_node != null)
            {
                Behavior b = cur_node.Value;
                if (b.Type == type)
                {
                    if (!b.IsInCallback)
                    {
                        if (b.OnFinishCallbackRef != null)
                        {
                            b.OnFinishCallbackRef.Release();
                            b.OnFinishCallbackRef = null;
                        }
                        b.OnRemove();
                        _InactiveBehaviorList.AddLast(b);
                        _ActiveBehaviorList.Remove(b);

                        if (b.Type == BehaviorType.Turn)
                        {
                            _ActiveTurnBehaviorList.Remove(b);
                        }
                    }
                    break;
                }
                else
                {
                    cur_node = cur_node.Next;
                }
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Create a timer by specifying Interval and (optional) type
 /// </summary>
 /// <param name="interval">Interval in milliseconds of timer</param>
 /// <param name="behavior">Once or Continuously</param>
 public Timer(TimeSpan interval, BehaviorType behavior = BehaviorType.RunOnce)
 {
     Behavior     = behavior;
     Interval     = interval;
     _syncRunning = new object();
     _timer       = new System.Threading.Timer(TimerCallbackFunc, null, 100, (int)Interval.TotalMilliseconds);
 }
Ejemplo n.º 14
0
 public AIObjectiveIdle(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1) : base(character, objectiveManager, priorityModifier)
 {
     Behavior        = BehaviorType.Passive;
     standStillTimer = Rand.Range(-10.0f, 10.0f);
     walkDuration    = Rand.Range(0.0f, 10.0f);
     chairCheckTimer = Rand.Range(0.0f, chairCheckInterval);
     CalculatePriority();
 }
Ejemplo n.º 15
0
 protected void ValidateBehaviorType(BehaviorType expected, Type actualInterface)
 {
     if (BehaviorType != expected)
     {
         Logger.ErrorS("action", "for action named {0}, behavior implements " +
                       "{1}, so behaviorType should be {2} but was {3}", Name, actualInterface.Name, expected, BehaviorType);
     }
 }
Ejemplo n.º 16
0
 public BehaviorAttribute(BehaviorType type, WoWClass @class = WoWClass.None, WoWSpec spec =(WoWSpec) int.MaxValue, WoWContext context = WoWContext.All, int priority = 0)
 {
     Type = type;
     SpecificClass = @class;
     SpecificSpec = spec;
     SpecificContext = context;
     PriorityLevel = priority;
 }
Ejemplo n.º 17
0
 public BehaviorAttribute(BehaviorType type, WoWClass @class = WoWClass.None, WoWSpec spec = (WoWSpec)int.MaxValue, WoWContext context = WoWContext.All, int priority = 0)
 {
     Type            = type;
     SpecificClass   = @class;
     SpecificSpec    = spec;
     SpecificContext = context;
     PriorityLevel   = priority;
 }
Ejemplo n.º 18
0
        public static Composite GetComposite(WoWClass wowClass, WoWSpec spec, BehaviorType behavior, WoWContext context, out int behaviourCount)
        {
            behaviourCount = 0;
            if (_methods.Count <= 0)
            {
                Logger.Write("Building method list");
                foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    // All behavior methods should not be generic, and should have zero parameters, with their return types being of type Composite.
                    _methods.AddRange(
                        type.GetMethods(BindingFlags.Static | BindingFlags.Public).Where(
                            mi => !mi.IsGenericMethod && mi.GetParameters().Length == 0).Where(
                                mi => mi.ReturnType.IsAssignableFrom(typeof (Composite))));
                }
                Logger.Write("Added " + _methods.Count + " methods");
            }
            var matchedMethods = new Dictionary<BehaviorAttribute, Composite>();

            foreach (MethodInfo mi in _methods)
            {
                // If the behavior is set as ignore. Don't use it? Duh?
                if (mi.GetCustomAttributes(typeof(IgnoreBehaviorCountAttribute), false).Any())
                    continue;

                // If there's no behavior attrib, then move along.
                foreach (var a in mi.GetCustomAttributes(typeof(BehaviorAttribute), false))
                {
                    var attribute = a as BehaviorAttribute;
                    if (attribute == null)
                        continue;

                    // Check if our behavior matches with what we want. If not, don't add it!
                    if (IsMatchingMethod(attribute, wowClass, spec, behavior, context))
                    {
                        Logger.Write(string.Format("Matched {0} to behavior {1} for {2} {3} with priority {4}", mi.Name,
                            behavior, wowClass.ToString().CamelToSpaced(), spec.ToString().CamelToSpaced(),
                            attribute.PriorityLevel));

                        // if it blows up here, you defined a method with the exact same attribute and priority as one already found
                        matchedMethods.Add(attribute, mi.Invoke(null, null) as Composite);
                    }
                }
            }
            // If we found no methods, rofls!
            if (matchedMethods.Count <= 0)
            {
                return null;
            }

            var result = new PrioritySelector();
            foreach (var kvp in matchedMethods.OrderByDescending(mm => mm.Key.PriorityLevel))
            {
                result.AddChild(kvp.Value);
                behaviourCount++;
            }

            return result;
        }
Ejemplo n.º 19
0
    public void EndBehavior()
    {
        if (currentBehavior != null)
        {
            if (currentBehavior.Controller.CurrentBehaviors.Contains(previousBehavior))
            {
                foreach (OldEntityClass e in previousBehavior.Arguments)
                {
                    Debug.Log("Removing " + previousBehavior.formula + " (" + e + ") ");
                }
                currentBehavior.Controller.CurrentBehaviors.Remove(previousBehavior);
            }

            if (currentBehavior.Controller.CurrentBehaviors.Contains(currentBehavior))
            {
                foreach (OldEntityClass e in currentBehavior.Arguments)
                {
                    Debug.Log("Removing " + currentBehavior.formula + " (" + e + ") ");
                }
                currentBehavior.Controller.CurrentBehaviors.Remove(currentBehavior);
            }

            if (previousBehavior != null)
            {
                foreach (OldEntityClass arg in previousBehavior.Arguments)
                {
                    bool argInUse = false;
                    foreach (Behavior beh in currentBehavior.Controller.CurrentBehaviors)
                    {
                        if (beh.Arguments.Contains(arg))
                        {
                            argInUse = true;
                            break;
                        }
                    }
                    arg.InUse = argInUse;
                }
            }

            foreach (OldEntityClass arg in currentBehavior.Arguments)
            {
                bool argInUse = false;
                foreach (Behavior beh in currentBehavior.Controller.CurrentBehaviors)
                {
                    if (beh.Arguments.Contains(arg))
                    {
                        argInUse = true;
                        break;
                    }
                }
                arg.InUse = argInUse;
            }
        }

        currentBehaviorType = BehaviorType.None;
        currentBehavior     = null;
        InUse = false;
    }
    protected override void SwitchMode(BehaviorType nextMode)
    {
        mode = nextMode;
        AbstractBehavior b = CurBehavior();

        agent.speed        = b.data.moveSpeed;
        agent.angularSpeed = b.data.turnSpeed;
        agent.acceleration = b.data.acceleration;
    }
Ejemplo n.º 21
0
        public virtual Enum GetCurrBehavior(BehaviorType type)
        {
            if (type == BehaviorType.FireMode)
            {
                return(_fireMode);
            }

            return(null);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CharacterBehavior"/> class.
 /// </summary>
 /// <param name="character">Character that this behavior is attached to.</param>
 /// <param name="behavior">The behavior type.</param>
 public CharacterBehavior(Character character, BehaviorType behavior)
 {
     if (rand == null)
     {
         rand = new Random();
     }
     this.character = character;
     this.behavior = behavior;
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Gets a behavior cache entry based on a behavior type and a predicate.
        /// </summary>
        /// <param name="type">Behavior type.</param>
        /// <param name="predicate">Predicate.</param>
        /// <returns></returns>
        private BehaviorEntryCache GetBehaviorEntry(BehaviorType type, Func <BehaviorEntryCache, bool> predicate)
        {
            if (!_behaviors.TryGetValue(type, out IList <BehaviorEntryCache> behaviors))
            {
                throw new KeyNotFoundException($"No behaviors for type {type}.");
            }

            return(behaviors.FirstOrDefault(predicate));
        }
Ejemplo n.º 24
0
 public Blob(string name, int health, int damage, BehaviorType behavior, IAttack attack)
 {
     this.attack   = attack;
     this.behavior = behavior;
     Damage        = damage;
     currentDamage = damage;
     Health        = health;
     Name          = name;
 }
Ejemplo n.º 25
0
    //-----------------------------------------------------------------------------------------
    // 是否在空闲状态
    //-----------------------------------------------------------------------------------------
    public bool IsInBehavior(BehaviorType eType)
    {
        if (m_curBehavior == eType)
        {
            return(true);
        }

        return(false);
    }
Ejemplo n.º 26
0
 /// <summary>
 /// Set a specific behavior weight (value must be greater than 0)
 /// Return true if behavior has been set else false.
 /// </summary>
 public bool AssignWeight(BehaviorType behavior, float value)
 {
     if (_weights.ContainsKey(behavior) && value > 0)
     {
         _weights[behavior] = value;
         return(true);
     }
     return(false);
 }
Ejemplo n.º 27
0
 public Behavior(Action <bool> doBehavior, Action <bool> undoBehavior, BehaviorType type, bool isModify = true, CombineType combineType = CombineType.Independent)
 {
     Do               = doBehavior;
     Undo             = undoBehavior;
     IsDone           = IsUndone = false;
     Type             = type;
     IsModify         = isModify;
     CombineType      = combineType;
     CreateFrameCount = Time.frameCount;
 }
Ejemplo n.º 28
0
        public void SetThrow(Vector2Int target)
        {
            this.behavior  = BehaviorType.Throw;
            this.nextCoord = target;

            this.actionRequest.Name  = Status.Name;
            this.actionRequest.Pow   = 20;
            this.actionRequest.Coord = Coord;
            this.actionRequest.Area.Add(target);
        }
Ejemplo n.º 29
0
 public Blob(string name, int health, int attackDamage, BehaviorType behaviorType, AttackType attackType)
 {
     this.Name         = name;
     this.AttackDamage = attackDamage;
     this.InitHealth(health);
     this.BehaviorType   = behaviorType;
     this.AttackType     = attackType;
     this.triggerCounter = 0;
     this.initialDamage  = attackDamage;
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Create an instance of Behavior
 /// </summary>
 /// <param name="name">Name of Behavior</param>
 /// <param name="behaviorType">Type of behavior (specified by subclass)</param>
 protected Behavior(string name, BehaviorType behaviorType)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw new ArgumentException("Invalid Behavior name");
     }
     this.Name   = name;
     this.Type   = behaviorType;
     this.Weight = 1;
 }
Ejemplo n.º 31
0
    void Start()
    {
        if (behaviorType == BehaviorType.RANDOM)
        {
            int nrOfBehaviorTypes = System.Enum.GetValues(typeof(BehaviorType)).Length - 1;
            behaviorType = (BehaviorType)Random.Range(0, nrOfBehaviorTypes);
        }

        CheckBehavior();
    }
Ejemplo n.º 32
0
 /// <summary>Pushes the behavior to the stack, making it the executing one.</summary>
 /// <param name="behavior">The behavior to push.</param>
 private void PushBehavior(BehaviorType behavior)
 {
     // Remove all behaviors induced by this type of behavior and
     // the old instance, as well, then push the new behavior.
     while (_currentBehaviors.Contains(behavior))
     {
         _currentBehaviors.Pop();
     }
     _currentBehaviors.Push(behavior);
 }
Ejemplo n.º 33
0
 public Blob(string name, int health, int attackDamage, BehaviorType behaviorType, AttackType attackType)
 {
     this.Name = name;
     this.AttackDamage = attackDamage;
     this.InitHealth(health);
     this.BehaviorType = behaviorType;
     this.AttackType = attackType;
     this.triggerCounter = 0;
     this.initialDamage = attackDamage;
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Updates the type of behavior for the agent.
 /// </summary>
 /// <param name="behaviorType"> The new behaviorType for the Agent
 /// </param>
 public void SetBehaviorType(BehaviorType behaviorType)
 {
     if (m_PolicyFactory.m_BehaviorType == behaviorType)
     {
         return;
     }
     m_PolicyFactory.m_BehaviorType = behaviorType;
     m_Brain?.Dispose();
     m_Brain = m_PolicyFactory.GeneratePolicy(Heuristic);
 }
Ejemplo n.º 35
0
        private static void WriteBehavior(XmlElement xmlBehavior, double[] obj, BehaviorType behavior)
        {
            string outstring = "";

            for (int i = 0; i < behavior.behaviorList.Count; i++)
            {
                outstring += behavior.behaviorList[i].ToString() + ",";
            }

            XmlUtilities.AddAttribute(xmlBehavior, "vals", outstring);
        }
Ejemplo n.º 36
0
 internal BehaviorActionHandler(
     BehaviorType behaviorType,
     string actionName,
     WeakReference <MixedRealityExtensionApp> appRef,
     Guid attachedActorId)
 {
     _actionName      = actionName;
     _behaviorType    = behaviorType;
     _appRef          = appRef;
     _attachedActorId = attachedActorId;
 }
Ejemplo n.º 37
0
	public override void Awake() {
		base.Awake();
		
		Cost = new Resources {
			Stone = 0
		};

		Behavior = BehaviorType.StoneMiner;
		CurrentAction = CitizenState.Idle;
		navAgent = GetComponent<NavMeshAgent>();
		navAgent.stoppingDistance = 0;
	}
Ejemplo n.º 38
0
        // Note: A constructor summary is auto-generated by the doc builder.
        /// <summary></summary>
        /// <param name="interval">The interval for the timer.</param>
        /// <param name="behavior">The behavior for the timer (run once or continuously).</param>
        public Timer(TimeSpan interval, BehaviorType behavior)
        {
            if (Program.Dispatcher == null)
            {
                Debug.Print("WARN: null Program.Dispatcher in GT.Timer constructor");
            }

            this.dt = new DispatcherTimer(Program.Dispatcher ?? Dispatcher.CurrentDispatcher);
            this.dt.Interval = interval;
            this.dt.Tick += new EventHandler(dt_Tick);
            this.Behavior = behavior;
        }
Ejemplo n.º 39
0
 public static Character GetPeasant(int index, BehaviorType bh)
 {
     Character c = new Character(bh);
     c.BasicSkills = new BasicSkills(4, 2, 2, 2, 2, 2, 2, 1, 1, 1);
     c.CC_weapon = new Axe();
     c.Armor = None();
     if (index == 0)
         c.SetImage("Square1.png");
     else
         c.SetImage("Square2.png");
     return c;
 }
Ejemplo n.º 40
0
 public static Character GetKnight(int index, BehaviorType bh)
 {
     Character c = new Character(bh);
     c.BasicSkills = new BasicSkills(5, 3, 6, 3, 4, 4, 4, 6, 8, 2);
     c.CC_weapon = new Sword();
     c.Armor = FullPlate();
     if (index == 0)
         c.SetImage("Square1.png");
     else
         c.SetImage("Square2.png");
     return c;
 }
Ejemplo n.º 41
0
    public ECBehavior GetBehavior(BehaviorType tp)
    {
        LinkedList<ECBehavior> cache = m_cache[(int)tp];

        if (cache.Count != 0)
        {
            ECBehavior beh = cache.Last.Value;
            cache.RemoveLast();
            return beh;
        }

        return null;
    }
Ejemplo n.º 42
0
    private IEnumerator CheckForPlayer()
    {
        int layer = 1 << LayerMask.NameToLayer("Player");
        while (true)
        {
            if(Physics.CheckSphere(_transform.position,detectionDistance, layer))
            {
                _currentBehavior = BehaviorType.ATTACK;
            } else {
                _currentBehavior = BehaviorType.IDLE;
                target = null;
            }

            yield return new WaitForSeconds(idleResetTime);
        }
    }
Ejemplo n.º 43
0
        public Unit(Vector3 Position, StatDistribution Specialization, BehaviorType PrimitiveAI)
        {
            this.Position = Position;
            IndexablePosition[0] = Position.X;
            IndexablePosition[1] = Position.Y;
            IndexablePosition[2] = Position.Z;
            this.TargetPosition = Position;

            this.HitPoints = DefaultHP;
            this.Damage = DefaultDamage;
            this.Speed = DefaultSpeed;
            this.Range = DefaultRange;
            switch (Specialization)
            {
                case StatDistribution.Health:
                    this.HitPoints *= 2.0;
                    this.Speed *= 0.5f;
                    break;
                case StatDistribution.Range:
                    this.Range *= 1.5f;
                    this.Damage *= 0.5;
                    break;
                case StatDistribution.Damage:
                    this.Damage *= 2.0;
                    this.HitPoints *= 0.5;
                    break;
                case StatDistribution.Speed:
                    this.Speed *= 2.0f;
                    this.Range *= 0.75f;
                    break;
                case StatDistribution.Default:
                default:
                    break;
            }

            switch (PrimitiveAI)
            {
                case BehaviorType.BuddyUp:
                    this.Update = Behavior_BuddyUp;
                    break;
                case BehaviorType.Default:
                default:
                    this.Update = Behavior_Default;
                    break;
            }
        }
Ejemplo n.º 44
0
 internal static string HookName(BehaviorType typ)
 {
     return "Singular." + typ.ToString();
 }
Ejemplo n.º 45
0
        private static bool IsMatchingMethod(BehaviorAttribute attribute, WoWClass wowClass, WoWSpec spec, BehaviorType behavior, WoWContext context)
        {
            if (attribute.SpecificClass != wowClass && attribute.SpecificClass != WoWClass.None)
                return false;
            if ((attribute.Type & behavior) == 0)
                return false;
            if ((attribute.SpecificContext & context) == 0)
                return false;
            if (attribute.SpecificSpec != (WoWSpec)int.MaxValue && attribute.SpecificSpec != spec)
                return false;

            Logger.WriteDebug("IsMatchingMethod({0}, {1}, {2}, {3}) - {4}, {5}, {6}, {7}, {8}", wowClass, spec, behavior,
                context, attribute.SpecificClass, attribute.SpecificSpec, attribute.Type, attribute.SpecificContext,
                attribute.PriorityLevel);
            return true;
        }
Ejemplo n.º 46
0
        private static Composite AddCommonBehaviorPrefix( Composite composite, BehaviorType behav)
        {
            if (behav == BehaviorType.LossOfControl)
            {
                composite = new Decorator(
                    ret => HaveWeLostControl,
                    new PrioritySelector(
                        new Action(r =>
                        {
                            if (!StyxWoW.IsInGame)
                            {
                                Logger.WriteDebug(Color.White, "Not in game...");
                                return RunStatus.Success;
                            }

                            return RunStatus.Failure;
                        }),
                        new ThrottlePasses(1, 1, new Decorator(ret => Me.Fleeing, new Action(r => { Logger.Write( LogColor.Hilite, "FLEEING! (loss of control)"); return RunStatus.Failure; }))),
                        new ThrottlePasses(1, 1, new Decorator(ret => Me.Stunned, new Action(r => { Logger.Write( LogColor.Hilite, "STUNNED! (loss of control)"); return RunStatus.Failure; }))),
                        new ThrottlePasses(1, 1, new Decorator(ret => Me.IsSilenced(), new Action(r => { Logger.Write( LogColor.Hilite, "SILENCED! (loss of control)"); return RunStatus.Failure; }))),
                        new Throttle(1,
                            new PrioritySelector(
                                composite ?? new ActionAlwaysFail(),
                                new Decorator(
                                    ret => SingularSettings.Instance.UseRacials,
                                    new PrioritySelector(
                                        Spell.Cast("Will of the Forsaken", on => Me, ret => Me.Race == WoWRace.Undead && Me.Fleeing),
                                        Spell.Cast("Every Man for Himself", on => Me, ret => Me.Race == WoWRace.Human && (Me.Stunned || Me.Fleeing))
                                        )
                                    ),

                                Item.UseEquippedTrinket(TrinketUsage.CrowdControlled),
                                Item.UseEquippedTrinket(TrinketUsage.CrowdControlledSilenced)
                                )
                            ),
                        new ActionAlwaysSucceed()
                        )
                    );
            }

            if (behav == BehaviorType.Rest)
            {
                Composite combatInRestCheck;
                if (!SingularSettings.Debug)
                    combatInRestCheck = new ActionAlwaysFail();
                else
                    combatInRestCheck = new Throttle(
                        1,
                        new ThrottlePasses(
                            1,
                            TimeSpan.FromSeconds(1),
                            RunStatus.Failure,
                            new Decorator(
                                req => Me.IsActuallyInCombat,
                                new Sequence(
                                    new PrioritySelector(
                                        new ThrottlePasses(
                                            1, 5,
                                            new Action(r => Logger.Write(Color.Yellow, "Bot Error: {0} or plugin called Rest behavior while in combat", SingularRoutine.GetBotName()))
                                            ),
                                        new Action(r => Logger.WriteDebug(Color.Yellow, "Bot Error: {0} or plugin called Rest behavior while in combat", SingularRoutine.GetBotName()))
                                        ),
                                    new ActionAlwaysFail()
                                    )
                                )
                            )
                        );

                composite = new LockSelector(
                    new CallWatch("Rest",
                        new Decorator(
                            ret => !Me.IsFlying && AllowBehaviorUsage() && !SingularSettings.Instance.DisableNonCombatBehaviors,
                            new PrioritySelector(

                                // TestDynaWait(),

                                // following is to allow cancelling of kiting in progress
                                new Decorator(
                                    ret => Kite.IsKitingActive(),
                                    new HookExecutor(HookName("KitingBehavior"))
                                    ),

                                new Decorator(
                                    req => ShouldWeFightDuringRest(),
                                    new PrioritySelector(
                                        Safers.EnsureTarget(),
                                        new Decorator(
                                            req => Unit.ValidUnit(Me.CurrentTarget) && Me.CurrentTarget.SpellDistance() < 45,
                                            new PrioritySelector(
                                                new ThrottlePasses(
                                                    1, TimeSpan.FromSeconds(15), RunStatus.Failure,
                                                    new Action(r => Logger.WriteDiagnostic(LogColor.Hilite, "Forcing combat from Rest Behavior")),
                                                    new ActionAlwaysFail()
                                                    ),
                                                SingularRoutine.Instance.HealBehavior,
                                                SingularRoutine.Instance.CombatBuffBehavior,
                                                SingularRoutine.Instance.CombatBehavior,
                                                new ActionAlwaysSucceed()
                                                )
                                            )
                                        )
                                    ),

                                // new Action(r => { _guidLastTarget = 0; return RunStatus.Failure; }),
                                new Decorator(
                                    req => !OkToCallBehaviorsWithCurrentCastingStatus(allow: LagTolerance.No),
                                    new ActionAlwaysSucceed()
                                    ),

                                // lost control in Rest -- force a RunStatus.Failure so we don't loop in Rest
                                new Sequence(
                                    SingularRoutine.Instance._lostControlBehavior,
                                    new ActionAlwaysFail()
                                    ),

                                // skip Rest logic if we lost control (since we had to return Fail to prevent Rest loop)
                                new Decorator(
                                    req => !HaveWeLostControl,
                                    composite ?? new ActionAlwaysFail()
                                    )
                                )
                            )
                        )
                    );
            }

            if (behav == BehaviorType.PreCombatBuffs)
            {
                Composite precombatInCombatCheck;
                if (!SingularSettings.Debug)
                    precombatInCombatCheck = new ActionAlwaysFail();
                else
                    precombatInCombatCheck = new Throttle(
                        1,
                        new ThrottlePasses(
                            1,
                            TimeSpan.FromSeconds(1),
                            RunStatus.Failure,
                            new Decorator(
                                req => Me.IsActuallyInCombat,
                                new Sequence(
                                    new PrioritySelector(
                                        new ThrottlePasses(
                                            1, 5,
                                            new Action(r => Logger.Write(Color.Yellow, "Bot Error: {0} or plugin called PreCombatBuff behavior while in combat", SingularRoutine.GetBotName()))
                                            ),
                                        new Action(r => Logger.WriteDebug(Color.Yellow, "Bot Error: {0} or plugin called PreCombatBuff behavior while in combat", SingularRoutine.GetBotName()))
                                        ),
                                    new ActionAlwaysFail()
                                    )
                                )
                            )
                        );

                composite = new LockSelector(
                    new CallWatch("PreCombat",
                        new Decorator(  // suppress non-combat buffing if standing around waiting on DungeonBuddy or BGBuddy queues
                            ret => !Me.Mounted
                                && !Me.HasAnyAura("Darkflight")
                                && !SingularSettings.Instance.DisableNonCombatBehaviors
                                && AllowNonCombatBuffing(),
                            new PrioritySelector(
                                new Decorator(
                                    req => !OkToCallBehaviorsWithCurrentCastingStatus(),
                                    Spell.WaitForGcdOrCastOrChannel()
                                    ),
                                Helpers.Common.CreateUseTableBehavior(),
                                Helpers.Common.CreateUseSoulwellBehavior(),

                                Item.CreateUseFlasksBehavior(),
                                Item.CreateUseScrollsBehavior(),

                                composite ?? new ActionAlwaysFail()
                                )
                            )
                        )
                    );
            }

            if (behav == BehaviorType.PullBuffs)
            {
                composite = new LockSelector(
                    new CallWatch("PullBuffs",
                        new Decorator(
                            ret => AllowBehaviorUsage() && OkToCallBehaviorsWithCurrentCastingStatus(),
                            composite ?? new ActionAlwaysFail()
                            )
                        )
                    );
            }

            if (behav == BehaviorType.Pull)
            {
                composite = new LockSelector(
                    new CallWatch("Pull",
                        new Decorator(
                            ret => AllowBehaviorUsage(), // && (!Me.GotTarget() || !Blacklist.Contains(Me.CurrentTargetGuid, BlacklistFlags.Combat)),
                            new PrioritySelector(
                                new Decorator(
                                    ret => !HotkeyDirector.IsCombatEnabled,
                                    new ActionAlwaysSucceed()
                                    ),
            #if BOTS_NOT_CALLING_PULLBUFFS
                            _pullBuffsBehavior,
            #endif
                                CreateLogTargetChanges(BehaviorType.Pull, "<<< PULL >>>"),
                                Item.CreateThunderLordGrappleBehavior(),
                                composite ?? new ActionAlwaysFail()
                                )
                            )
                        )
                    );
            }

            if (behav == BehaviorType.Heal)
            {
                Composite behavHealingSpheres = new ActionAlwaysFail();
                if (SingularSettings.Instance.MoveToSpheres)
                {
                    behavHealingSpheres = new ThrottlePasses(
                        1, 1,
                        new Decorator(
                            ret => Me.HealthPercent < SingularSettings.Instance.SphereHealthPercentInCombat && Singular.ClassSpecific.Monk.Common.AnySpheres(SphereType.Life, SingularSettings.Instance.SphereDistanceInCombat),
                            Singular.ClassSpecific.Monk.Common.CreateMoveToSphereBehavior(SphereType.Life, SingularSettings.Instance.SphereDistanceInCombat)
                            )
                        );
                }

                composite = new LockSelector(
                    new CallWatch("Heal",

                        // following must occur before any cast or movement during Combat
                        Generic.CreateCancelShadowmeld(),

                        SingularRoutine.Instance._lostControlBehavior,
                        new Decorator(
                            ret => Kite.IsKitingActive(),
                            new HookExecutor(HookName("KitingBehavior"))
                            ),
                        new Decorator(
                            ret => AllowBehaviorUsage() && OkToCallBehaviorsWithCurrentCastingStatus(),
                            new PrioritySelector(
                                Generic.CreatePotionAndHealthstoneBehavior(),
                                composite ?? new ActionAlwaysFail(),
                                behavHealingSpheres
                                )
                            )
                        )
                    );
            }

            if (behav == BehaviorType.CombatBuffs)
            {
                composite = new LockSelector(
                    new CallWatch("CombatBuffs",
                        new Decorator(
                            ret => AllowBehaviorUsage() && OkToCallBehaviorsWithCurrentCastingStatus(),
                            new PrioritySelector(
                                new Decorator(ret => !HotkeyDirector.IsCombatEnabled, new ActionAlwaysSucceed()),
                                Generic.CreateUseTrinketsBehaviour(),
                                Generic.CreatePotionAndHealthstoneBehavior(),
                                Item.CreateUseXPBuffPotionsBehavior(),
                                Generic.CreateRacialBehaviour(),
                                Generic.CreateGarrisonAbilityBehaviour(),
                                composite ?? new ActionAlwaysFail()
                                )
                            )
                        )
                    );
            }

            if (behav == BehaviorType.Combat)
            {
                composite = new LockSelector(
                    new CallWatch("Combat",
                        new Decorator(
                            ret => AllowBehaviorUsage(), // && (!Me.GotTarget() || !Blacklist.Contains(Me.CurrentTargetGuid, BlacklistFlags.Combat)),
                            new PrioritySelector(
                                new Decorator(
                                    ret => !HotkeyDirector.IsCombatEnabled,
                                    new ActionAlwaysSucceed()
                                    ),
                                CreatePullMorePull(),
                                CreateLogTargetChanges(BehaviorType.Combat, "<<< ADD >>>"),
                                composite ?? new ActionAlwaysFail()
                                )
                            )
                        )
                    );
            }

            if (behav == BehaviorType.Death)
            {
                composite = new LockSelector(
                    new CallWatch("Death",
                        new Decorator(
                            ret => AllowBehaviorUsage(),
                            new PrioritySelector(
                                new Action(r => { ResetCurrentTarget(); return RunStatus.Failure; }),
                                new Decorator(
                                    req => !OkToCallBehaviorsWithCurrentCastingStatus(),
                                    Spell.WaitForGcdOrCastOrChannel()
                                    ),
                                composite ?? new ActionAlwaysFail()
                                )
                            )
                        )
                    );
            }

            return composite;
        }
Ejemplo n.º 47
0
        private static void WriteBehavior(XmlElement xmlBehavior, BehaviorType behavior)
        {
            string outstring = "";

            for(int i=0;i<behavior.behaviorList.Count;i++)
            {
                outstring += behavior.behaviorList[i].ToString() + ",";
            }

            if(behavior.objectives!=null) {
             for(int i=0;i<behavior.objectives.Length;i++)
                outstring+=" O"+i+":"+behavior.objectives[i];
            }
            XmlUtilities.AddAttribute(xmlBehavior,"list",outstring);
        }
Ejemplo n.º 48
0
 public IgnoreBehaviorCountAttribute(BehaviorType type)
 {
     Type = type;
 }
Ejemplo n.º 49
0
    public void EndBehavior()
    {
        if (currentBehavior != null) {
            if (currentBehavior.Controller.CurrentBehaviors.Contains (previousBehavior)) {
                foreach (OldEntityClass e in previousBehavior.Arguments)
                    Debug.Log ("Removing " + previousBehavior.formula + " (" + e + ") ");
                currentBehavior.Controller.CurrentBehaviors.Remove (previousBehavior);
            }

            if (currentBehavior.Controller.CurrentBehaviors.Contains (currentBehavior)) {
                foreach (OldEntityClass e in currentBehavior.Arguments)
                    Debug.Log ("Removing " + currentBehavior.formula + " (" + e + ") ");
                currentBehavior.Controller.CurrentBehaviors.Remove (currentBehavior);
            }

            if (previousBehavior != null) {
                foreach (OldEntityClass arg in previousBehavior.Arguments) {
                    bool argInUse = false;
                    foreach (Behavior beh in currentBehavior.Controller.CurrentBehaviors) {
                        if (beh.Arguments.Contains (arg)) {
                            argInUse = true;
                            break;
                        }
                    }
                    arg.InUse = argInUse;
                }
            }

            foreach (OldEntityClass arg in currentBehavior.Arguments) {
                bool argInUse = false;
                foreach (Behavior beh in currentBehavior.Controller.CurrentBehaviors) {
                    if (beh.Arguments.Contains (arg)) {
                        argInUse = true;
                        break;
                    }
                }
                arg.InUse = argInUse;
            }
        }

        currentBehaviorType = BehaviorType.None;
        currentBehavior = null;
        InUse = false;
    }
 private bool EnsureComposite(bool error, BehaviorType type, out Composite composite)
 {
     Logger.WriteDebug("Creating " + type + " behavior.");
     int count = 0;
     composite = CompositeBuilder.GetComposite(_myClass, TalentManager.CurrentSpec, type, CurrentWoWContext, out count);
     if ((composite == null || count <= 0) && error)
     {
         StopBot(
             string.Format(
                 "Singular currently does not support {0} for this class/spec combination, in this context! [{1}, {2}, {3}]", type, _myClass,
                 TalentManager.CurrentSpec, CurrentWoWContext));
         return false;
     }
     return composite != null;
 }
Ejemplo n.º 51
0
 public virtual void LoadItem(XElement ItemNode)
 {
     base.LoadItem(ItemNode);
     description = ItemNode.Attribute("description").Value ?? "";
     itemBehavior = (new BehaviorType()).GetBehaviorType(ItemNode.Attribute("behavior").Value ?? "");
 }
Ejemplo n.º 52
0
 public Character(BehaviorType behavior)
 {
     Components.Add(new BehaviorComponent(this, behavior));
     Components.Add(new MoveComponent(this));
     Components.Add(new CombatComponent(this));
 }
Ejemplo n.º 53
0
 public void TriggerBehavior(BehaviorType pType)
 {
     if (pType == BehaviorType.None)
     {
         Console.WriteLine("ERROR: No behavior type specified for target ship");
     }
     else if (pType == BehaviorType.VelocityReversal)
     {
         Behavior_VelocityReversal b = new Behavior_VelocityReversal(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.PathLaser)
     {
         Behavior_PathLaser b = new Behavior_PathLaser(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.ThrustShip)
     {
         Behavior_ThrustShip b = new Behavior_ThrustShip(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.TurnLeft)
     {
         Behavior_TurnLeft b = new Behavior_TurnLeft(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.TurnRight)
     {
         Behavior_TurnRight b = new Behavior_TurnRight(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.SlowShip)
     {
         Behavior_SlowShip b = new Behavior_SlowShip(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.BulletSpam)
     {
         Behavior_BulletSpam b = new Behavior_BulletSpam(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.SuicideBomb)
     {
         Behavior_SuicideBomb b = new Behavior_SuicideBomb(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.ChargeLaser)
     {
         Behavior_ChargeLaser b = new Behavior_ChargeLaser(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.DualWield)
     {
         Behavior_DualWield b = new Behavior_DualWield(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else if (pType == BehaviorType.RearGuns)
     {
         Behavior_RearGuns b = new Behavior_RearGuns(this);
         b.Trigger();
         mActiveBehaviors.Add(b);
     }
     else
     {
         Console.WriteLine("ERROR: Behavior type was not a recognized BehaviorType");
     }
 }
Ejemplo n.º 54
0
        public static Composite GetComposite(WoWClass wowClass, TalentSpec spec, BehaviorType behavior, WoWContext context, out int behaviourCount)
        {
            behaviourCount = 0;
            if (_methods.Count <= 0)
            {
                Logger.Write("Building method list");
                foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    _methods.AddRange(type.GetMethods(BindingFlags.Static | BindingFlags.Public));
                }
                Logger.Write("Added " + _methods.Count + " methods");
            }
            var matchedMethods = new Dictionary<int, PrioritySelector>();
            foreach (MethodInfo mi in
                _methods.Where(
                    mi =>
                    !mi.IsGenericMethod &&
                    mi.GetParameters().Length == 0)
                    .Where(
                        mi =>
                        mi.ReturnType == typeof(Composite) ||
                        mi.ReturnType.IsSubclassOf(typeof(Composite))))
            {
                //Logger.WriteDebug("[CompositeBuilder] Checking attributes on " + mi.Name);
                bool classMatches = false, specMatches = false, behaviorMatches = false, contextMatches = false, hasIgnore = false;
                int thePriority = 0;
                var theBehaviourType = BehaviorType.All;
                var theIgnoreType = BehaviorType.All;
                foreach (object ca in mi.GetCustomAttributes(false))
                {
                    if (ca is ClassAttribute)
                    {
                        var attrib = ca as ClassAttribute;
                        if (attrib.SpecificClass != WoWClass.None && attrib.SpecificClass != wowClass)
                        {
                            continue;
                        }
                        //Logger.WriteDebug(mi.Name + " has my class");
                        classMatches = true;
                    }
                    else if (ca is SpecAttribute)
                    {
                        var attrib = ca as SpecAttribute;
                        if (attrib.SpecificSpec != TalentSpec.Any && attrib.SpecificSpec != spec)
                        {
                            continue;
                        }
                        //Logger.WriteDebug(mi.Name + " has my spec");
                        specMatches = true;
                    }
                    else if (ca is BehaviorAttribute)
                    {
                        var attrib = ca as BehaviorAttribute;
                        if ((attrib.Type & behavior) == 0)
                        {
                            continue;
                        }
                        //Logger.WriteDebug(mi.Name + " has my behavior");
                        theBehaviourType = attrib.Type;
                        behaviourCount++;
                        behaviorMatches = true;
                    }
                    else if (ca is ContextAttribute)
                    {
                        var attrib = ca as ContextAttribute;

                        if (SingularSettings.Instance.UseInstanceRotation)
                        {
                            if ((attrib.SpecificContext & WoWContext.Instances) == 0)
                                continue;
                        }
                        else if ((attrib.SpecificContext & context) == 0)
                        {
                             continue;
                        }
                        //Logger.WriteDebug(mi.Name + " has my context");
                        contextMatches = true;
                    }
                    else if (ca is PriorityAttribute)
                    {
                        var attrib = ca as PriorityAttribute;
                        thePriority = attrib.PriorityLevel;
                    }
                    else if (ca is IgnoreBehaviorCountAttribute)
                    {
                        var attrib = ca as IgnoreBehaviorCountAttribute;
                        hasIgnore = true;
                        theIgnoreType = attrib.Type;
                    }
                }

                if (behaviorMatches && hasIgnore && theBehaviourType == theIgnoreType)
                {
                    behaviourCount--;
                }

                // If all our attributes match, then mark it as wanted!
                if (classMatches && specMatches && behaviorMatches && contextMatches)
                {
                    Logger.WriteDebug("{0} is a match!", mi.Name);
                    if (!hasIgnore)
                    {
                        Logger.Write(" Using {0} for {1} - {2} (Priority: {3})", mi.Name, spec.ToString().CamelToSpaced().Trim(), behavior, thePriority);
                    }
                    else
                    {
                        Logger.WriteDebug(" Using {0} for {1} - {2} (Priority: {3})", mi.Name, spec.ToString().CamelToSpaced().Trim(), behavior, thePriority);
                    }
                    Composite matched;
                    try
                    {
                        matched = (Composite) mi.Invoke(null, null);
                    }
                    catch (Exception e)
                    {
                        Logger.Write("ERROR Creating composite: {0}\n{1}", mi.Name, e.StackTrace);
                        continue;
                    }
                    if (!matchedMethods.ContainsKey(thePriority))
                    {
                        matchedMethods.Add(thePriority, new PrioritySelector(matched));
                    }
                    else
                    {
                        matchedMethods[thePriority].AddChild(matched);
                    }
                }
            }
            // If we found no methods, rofls!
            if (matchedMethods.Count <= 0)
            {
                return null;
            }

            // Return the composite match we found. (Note: ANY composite return is fine)
            return matchedMethods.OrderByDescending(mm => mm.Key).First().Value;
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Ensures we have a composite for the given BehaviorType.  
        /// </summary>
        /// <param name="error">true: report error if composite not found, false: allow null composite</param>
        /// <param name="type">BehaviorType that should be loaded</param>
        /// <returns>true: composite loaded and saved to hook, false: failure</returns>
        private bool EnsureComposite(bool silent, bool error, WoWContext context, BehaviorType type)
        {
            int count = 0;
            Composite composite;

            // Logger.WriteDebug("Creating " + type + " behavior.");

            composite = CompositeBuilder.GetComposite(Class, TalentManager.CurrentSpec, type, context, out count);

            // handle those composites we need to default if not found
            if (composite == null && type == BehaviorType.Rest)
                composite = Helpers.Rest.CreateDefaultRestBehaviour();

            if ((composite == null || count <= 0) && error)
            {
                StopBot(string.Format("Singular does not support {0} for this {1} {2} in {3} context!", type, StyxWoW.Me.Class, TalentManager.CurrentSpec, context));
                return false;
            }

            composite = AddCommonBehaviorPrefix(composite, type);

            // replace hook we created during initialization
            TreeHooks.Instance.ReplaceHook(HookName(type), composite ?? new ActionAlwaysFail());

            return composite != null;
        }
Ejemplo n.º 56
0
    public void PromptBehavior(string pred, List<string> args)
    {
        Behavior behavior = GetBehaviorByName (pred);

        if (behavior != null) {
            CurrentBehaviorTypeProperty = currentBehaviorType = behavior.type;
            currentBehavior.SetNewBehavior (args);
        }
        else {
            Debug.Log("Behavior " + pred + " not found on entity " + gameObject.name);
        }
    }
Ejemplo n.º 57
0
        public static Composite MoveBehaviorInlineToCombat( BehaviorType bt )
        {
            string hookNameOrig = HookName(bt);
            string hookNameInline = hookNameOrig + "-INLINE";

            if (BehaviorType.Combat != Dynamics.CompositeBuilder.CurrentBehaviorType)
            {
                Logger.WriteDiagnostic("MoveBehaviorInline: suppressing Inline for {0} behavior", Dynamics.CompositeBuilder.CurrentBehaviorType);
                return new ActionAlwaysFail();
            }

            if (Instance == null)
            {
                StopBot(string.Format("MoveBehaviorInline: PROGRAM ERROR - SingularRoutine.Instance not initialized yet for {0} !!!!", bt));
                return null;
            }

            if (bt == Dynamics.CompositeBuilder.CurrentBehaviorType)
            {
                StopBot(string.Format("MoveBehaviorInline: PROGRAM ERROR - referenced behavior({0}) == current behavior({1}) !!!!", bt, bt));
                return null;
            }

            // on creation, move hook composite (if exists) from default to inline hook
            Composite composite = new ActionAlwaysFail();
            if (TreeHooks.Instance.Hooks.ContainsKey(hookNameOrig))
            {
                if (TreeHooks.Instance.Hooks[hookNameOrig].Count() == 1)
                {
                    composite = TreeHooks.Instance.Hooks[hookNameOrig].First().Composite;
                    if (composite == null)
                    {
                        StopBot(string.Format("MoveBehaviorInline: PROGRAM ERROR - not composite for behavior({0}) !!!!", bt));
                        return null;
                    }

                    TreeHooks.Instance.ReplaceHook(hookNameInline, composite);
                    TreeHooks.Instance.RemoveHook(hookNameOrig, composite);
                    Logger.WriteFile("MoveBehaviorInline: moving {0} behavior within {1} {2}", bt, Dynamics.CompositeBuilder.CurrentBehaviorName, Dynamics.CompositeBuilder.CurrentBehaviorPriority);
                }
            }

            return new HookExecutor(hookNameInline);
        }
Ejemplo n.º 58
0
			public virtual void loadFrom(BinaryReader reader, PersistContext ctx)
			{
				backColor = ctx.loadColor();
				behavior = (BehaviorType)reader.ReadInt32();
				arrowHead = (ArrowHead)reader.ReadInt32();
				arrowBase = (ArrowHead)reader.ReadInt32();
				arrowInterm = (ArrowHead)reader.ReadInt32();
				arrowHeadSize = (float)reader.ReadDouble();
				arrowBaseSize = (float)reader.ReadDouble();
				arrowIntermSize = (float)reader.ReadDouble();
				shadowsStyle = (ShadowsStyle)reader.ReadInt32();
				boxFillColor = ctx.loadColor();
				arrowFillColor = ctx.loadColor();
				boxFrameColor = ctx.loadColor();
				arrowColor = ctx.loadColor();
				alignToGrid = reader.ReadBoolean();
				showGrid = reader.ReadBoolean();
				gridColor = ctx.loadColor();
				gridSize = (float)reader.ReadDouble();
				boxStyle = (BoxStyle)reader.ReadInt32();
				shadowColor = ctx.loadColor();
				imagePos = (ImageAlign)reader.ReadInt32();
				textColor = ctx.loadColor();
				activeMnpColor = ctx.loadColor();
				selMnpColor = ctx.loadColor();
				disabledMnpColor = ctx.loadColor();
				arrowStyle = (ArrowStyle)reader.ReadInt32();
				arrowSegments = reader.ReadInt16();
				scrollX = (float)reader.ReadDouble();
				scrollY = (float)reader.ReadDouble();

				// zoomFactor was a short, now it is a float
				if (ctx.FileVersion < 19)
					zoomFactor = reader.ReadInt16();
				else
					zoomFactor = reader.ReadSingle();

				penDashStyle = (DashStyle)reader.ReadInt32();
				penWidth = (float)reader.ReadDouble();
				int c = reader.ReadInt32();
				defPolyShape = reader.ReadBytes(c);
				docExtents = ctx.loadRectF();
				shadowOffsetX = (float)reader.ReadDouble();
				shadowOffsetY = (float)reader.ReadDouble();
				tableFillColor = ctx.loadColor();
				tableFrameColor = ctx.loadColor();
				tableRowsCount = reader.ReadInt32();
				tableColumnsCount = reader.ReadInt32();
				tableColWidth = (float)reader.ReadDouble();
				tableRowHeight = (float)reader.ReadDouble();
				tableCaptionHeight = (float)reader.ReadDouble();
				tableCaption = reader.ReadString();
				arrowCascadeOrientation = (Orientation)reader.ReadInt32();
				tableCellBorders = (CellFrameStyle)reader.ReadInt32();
				boxIncmAnchor = (ArrowAnchor)reader.ReadInt32();
				boxOutgAnchor = (ArrowAnchor)reader.ReadInt32();
				boxesExpandable = reader.ReadBoolean();
				tablesScrollable = reader.ReadBoolean();
			}
Ejemplo n.º 59
0
        public static Composite GetComposite(ActorClass actorClass, BehaviorType behavior, out int behaviourCount)
        {
            behaviourCount = 0;
            if (Methods.Count <= 0)
            {
                Logger.Write("Building method list");
                foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    Methods.AddRange(type.GetMethods(BindingFlags.Static | BindingFlags.Public));
                }
                Logger.Write("Added " + Methods.Count + " methods");
            }
            var matchedMethods = new Dictionary<int, PrioritySelector>();

            foreach (MethodInfo mi in
                Methods.Where(
                    mi =>
                    !mi.IsGenericMethod &&
                    mi.GetParameters().Length == 0)
                    .Where(
                        mi =>
                        mi.ReturnType == typeof(Composite) ||
                        mi.ReturnType.IsSubclassOf(typeof(Composite))))
            {
                //Logger.WriteDebug("[CompositeBuilder] Checking attributes on " + mi.Name);
                bool classMatches = false;
                bool behaviorMatches = false;
                bool hasIgnore = false;
                int thePriority = 0;
                var theBehaviourType = BehaviorType.All;
                var theIgnoreType = BehaviorType.All;
                try
                {
                    foreach (object ca in mi.GetCustomAttributes(false))
                    {
                        if (ca is ClassAttribute)
                        {
                            var attrib = ca as ClassAttribute;
                            // Class specific
                            if (attrib.CharacterClass != actorClass)
                            {
                                //Logger.Write("Attribute Class does not match. [" + attrib.SpecificClass + " != " + torClass + "]");
                                continue;
                            }

                            //Logger.WriteDebug(mi.Name + " has my class");
                            classMatches = true;
                        }
                        else if (ca is BehaviorAttribute)
                        {
                            var attrib = ca as BehaviorAttribute;
                            if ((attrib.Type & behavior) == 0)
                            {
                                continue;
                            }
                            //Logger.WriteDebug(mi.Name + " has my behavior");
                            theBehaviourType = attrib.Type;
                            behaviourCount++;
                            behaviorMatches = true;
                        }
                        else if (ca is PriorityAttribute)
                        {
                            var attrib = ca as PriorityAttribute;
                            thePriority = attrib.PriorityLevel;
                        }
                        else if (ca is IgnoreBehaviorCountAttribute)
                        {
                            var attrib = ca as IgnoreBehaviorCountAttribute;
                            hasIgnore = true;
                            theIgnoreType = attrib.Type;
                        }
                    }
                }
                catch
                {
                    Logger.Write("Error getting custom attributes for " + mi.Name);
                    continue;
                }

                if (behaviorMatches && hasIgnore && theBehaviourType == theIgnoreType)
                {
                    behaviourCount--;
                }

                // If all our attributes match, then mark it as wanted!
                if (classMatches && behaviorMatches)
                {
                    Logger.Write("{0} is a match!", mi.Name);
                    Logger.Write("Using {0} for {1} (Priority: {2})", mi.Name, behavior, thePriority);
                    Composite matched;
                    try
                    {
                        matched = (Composite)mi.Invoke(null, null);
                    }
                    catch (Exception e)
                    {
                        Logger.Write("ERROR Creating composite: {0}\n{1}", mi.Name, e.StackTrace);
                        continue;
                    }
                    if (!matchedMethods.ContainsKey(thePriority))
                    {
                        matchedMethods.Add(thePriority, new PrioritySelector(matched));
                    }
                    else
                    {
                        matchedMethods[thePriority].AddChild(matched);
                    }
                }
            }
            // If we found no methods, rofls!
            if (matchedMethods.Count <= 0)
            {
                return null;
            }

            // Return the composite match we found. (Note: ANY composite return is fine)
            return matchedMethods.OrderByDescending(mm => mm.Key).First().Value;
        }
Ejemplo n.º 60
0
    Behavior GetBehaviorByType(BehaviorType btype)
    {
        Behavior behavior = null;
        Behavior[] behaviors = GetComponents<Behavior> ();

        foreach (Behavior beh in behaviors)
        {
            if (beh.type == btype)
            {
                behavior = beh;
                break;
            }
        }

        return behavior;
    }