Beispiel #1
0
 public static Composite CreateWarriorCombatPullMore()
 {
     return(new Throttle(
                2,
                new Decorator(
                    req => SingularRoutine.CurrentWoWContext == WoWContext.Normal &&
                    Me.GotTarget() &&
                    !Me.CurrentTarget.IsPlayer &&
                    !Me.CurrentTarget.IsTagged &&
                    !Me.HasAura("Charge") &&
                    !Me.CurrentTarget.HasAnyOfMyAuras("Charge Stun", "Warbringer") &&
                    !Me.CurrentTarget.IsWithinMeleeRange,
                    new PrioritySelector(
                        Common.CreateChargeBehavior(),
                        Spell.Cast("Heroic Throw", req => Me.IsSafelyFacing(Me.CurrentTarget) && !Me.CurrentTarget.IsWithinMeleeRange),
                        Spell.Cast("Taunt", req => SingularSettings.Instance.EnableTaunting),
                        new Decorator(
                            req => SpellManager.HasSpell("Throw") && Me.CurrentTarget.SpellDistance().Between(6, 27),
                            new Sequence(
                                new Action(r => StopMoving.Now()),
                                new Wait(1, until => !Me.IsMoving, new ActionAlwaysSucceed()),
                                Spell.Cast(s => "Throw", mov => true, on => Me.CurrentTarget, req => true, cancel => false),
                                new WaitContinue(1, until => !Me.IsCasting, new ActionAlwaysSucceed())
                                )
                            )
                        )
                    )
                ));
 }
Beispiel #2
0
 public MountHandler(ILogger logger, ConfigurableInput input, ClassConfiguration classConfig, Wait wait, PlayerReader playerReader, StopMoving stopMoving)
 {
     this.logger       = logger;
     this.classConfig  = classConfig;
     this.input        = input;
     this.wait         = wait;
     this.playerReader = playerReader;
     this.stopMoving   = stopMoving;
 }
Beispiel #3
0
 private static Throttle CreateGuardianWildChargeBehavior(UnitSelectionDelegate onUnit = null)
 {
     return(new Throttle(7,
                         new Sequence(
                             Spell.CastHack("Wild Charge", onUnit ?? (on => Me.CurrentTarget), ret => MovementManager.IsClassMovementAllowed && Me.Shapeshift == ShapeshiftForm.Bear && (Me.CurrentTarget.Distance + Me.CurrentTarget.CombatReach).Between(10, 25)),
                             new Action(ret => StopMoving.Clear()),
                             new Wait(1, until => !Me.GotTarget() || Me.CurrentTarget.IsWithinMeleeRange, new ActionAlwaysSucceed())
                             )
                         ));
 }
        public StuckDetector(PlayerReader playerReader, WowProcess wowProcess, IPlayerDirection playerDirection, StopMoving stopMoving, ILogger logger)
        {
            this.playerReader    = playerReader;
            this.wowProcess      = wowProcess;
            this.stopMoving      = stopMoving;
            this.logger          = logger;
            this.playerDirection = playerDirection;

            ResetStuckParameters();
        }
        public StuckDetector(ILogger logger, ConfigurableInput input, PlayerReader playerReader, IPlayerDirection playerDirection, StopMoving stopMoving)
        {
            this.logger = logger;
            this.input  = input;

            this.playerReader    = playerReader;
            this.stopMoving      = stopMoving;
            this.playerDirection = playerDirection;

            ResetStuckParameters();
        }
Beispiel #6
0
        private static bool MovementToggle()
        {
            _MovementEnabled = _MovementEnabled ? false : true;
            if (!_MovementEnabled)
            {
                StopMoving.Now();
            }

#if !REACT_TO_HOTKEYS_IN_PULSE
            MovementKeyHandler();
#endif
            return(_MovementEnabled);
        }
Beispiel #7
0
 public static Composite CreateDeathGripBehavior()
 {
     return(new Sequence(
                Spell.Cast("Death Grip",
                           req => !MovementManager.IsMovementDisabled &&
                           (SingularRoutine.CurrentWoWContext != WoWContext.Instances || !Me.GroupInfo.IsInParty || Me.IsTank) &&
                           Me.CurrentTarget.DistanceSqr > 10 * 10 &&
                           (((Me.CurrentTarget.IsPlayer || Me.CurrentTarget.TaggedByMe) && !Me.CurrentTarget.IsMovingTowards()) || (!Me.CurrentTarget.TaggedByOther && Dynamics.CompositeBuilder.CurrentBehaviorType == BehaviorType.Pull))
                           ),
                new DecoratorContinue(req => Me.IsMoving, new Action(req => StopMoving.Now())),
                new WaitContinue(1, until => !Me.GotTarget() || Me.CurrentTarget.IsWithinMeleeRange, new ActionAlwaysSucceed())
                ));
 }
Beispiel #8
0
 internal static void HandleContextChanged(object sender, WoWContextEventArg e)
 {
     if (e.CurrentContext != WoWContext.Battlegrounds)
     {
         BattlegroundStart = DateTime.UtcNow;
     }
     else
     {
         BattlegroundStart = DateTime.UtcNow + TimeSpan.FromSeconds(120);   // just add enough for now... accurate time set by event handler
     }
     if (e.PreviousContext == WoWContext.Battlegrounds)
     {
         StopMoving.AsSoonAsPossible(when => Styx.StyxWoW.IsInGame);
     }
 }
        public GoapAgent(ILogger logger, GoapAgentState goapAgentState, ConfigurableInput input, AddonReader addonReader, HashSet <GoapGoal> availableGoals, IBlacklist blacklist)
        {
            this.logger         = logger;
            this.GoapAgentState = goapAgentState;
            this.input          = input;

            this.addonReader  = addonReader;
            this.playerReader = addonReader.PlayerReader;

            this.addonReader.CreatureHistory.KillCredit -= OnKillCredit;
            this.addonReader.CreatureHistory.KillCredit += OnKillCredit;

            this.stopMoving = new StopMoving(input, playerReader);

            this.AvailableGoals = availableGoals.OrderBy(a => a.CostOfPerformingAction);
            this.blacklist      = blacklist;

            this.planner = new GoapPlanner(logger);
        }
Beispiel #10
0
        private static Composite HealthFunnel(int petMinHealth, int petMaxHealth = 99)
        {
            return(new Decorator(
                       ret => GetCurrentPet() != WarlockPet.None &&
                       Me.Pet.HealthPercent < petMinHealth &&
                       !Spell.IsSpellOnCooldown("Health Funnel") &&
                       Me.Pet.Distance < 45 &&
                       Me.Pet.InLineOfSpellSight &&
                       !TalentManager.IsSelected((int)WarlockTalents.SoulLink),
                       new Sequence(
                           new PrioritySelector(
                               // glyph of health funnel prevents Soulburn: Health Funnel from being used
                               new Decorator(ret => TalentManager.HasGlyph("Health Funnel"), new ActionAlwaysSucceed()),
                               CastSoulburn(ret =>
            {
                if (Me.Specialization == WoWSpec.WarlockAffliction)
                {
                    if (Me.CurrentSoulShards > 0 && Spell.CanCastHack("Soulburn", Me))
                    {
                        Logging.WriteDiagnostic("Soulburn should follow to make instant health funnel");
                        return true;
                    }
                    Logging.WriteDiagnostic("soulburn not available, shards={0}", Me.CurrentSoulShards);
                }
                return false;
            }),

                               // neither of instant funnels available, so stop moving
                               new Sequence(
                                   new Action(ctx => StopMoving.Now()),
                                   new Wait(1, until => !Me.IsMoving, new ActionAlwaysSucceed()))),
                           new Decorator(ret => Spell.CanCastHack("Health Funnel", Me.Pet), new ActionAlwaysSucceed()),
                           new Action(ret => Logging.WriteDiagnostic("Casting Health Funnel on Pet @ {0:F1}%", Me.Pet.HealthPercent)),
                           new PrioritySelector(
                               Spell.Cast(ret => "Health Funnel", mov => false, on => Me.Pet, req => Me.HasAura("Soulburn") || TalentManager.HasGlyph("Health Funnel")),
                               Spell.Cast(ret => "Health Funnel", mov => true, on => Me.Pet, req => true, cancel => !Me.GotAlivePet || Me.Pet.HealthPercent >= petMaxHealth)),
                           Common.CreateWaitForLagDuration())));
        }
Beispiel #11
0
        /// <summary>
        /// invoke on CurrentTarget if not tagged. use ranged instant casts if possible.  this
        /// is a blend of abilities across all specializations
        /// </summary>
        /// <returns></returns>
        public static Composite CreateDeathKnightPullMore()
        {
            if (SingularRoutine.CurrentWoWContext != WoWContext.Normal)
            {
                return(new ActionAlwaysFail());
            }

            return(new Throttle(
                       2,
                       new Decorator(
                           req => Me.GotTarget() &&
                           !Me.CurrentTarget.IsPlayer &&
                           !Me.CurrentTarget.IsTagged &&
                           !Me.CurrentTarget.IsWithinMeleeRange,
                           new PrioritySelector(
                               new Sequence(
                                   ctx => Me.CurrentTarget,
                                   Spell.Cast("Death Grip", on => (on as WoWUnit)),
                                   new DecoratorContinue(req => Me.IsMoving, new Action(req => StopMoving.Now())),
                                   new WaitContinue(TimeSpan.FromMilliseconds(500), until => !Me.IsMoving, new ActionAlwaysSucceed()),
                                   new WaitContinue(1, until => (until as WoWUnit).IsWithinMeleeRange, new ActionAlwaysSucceed())
                                   ),
                               Spell.Cast("Dark Command", req => Me.Specialization == WoWSpec.DeathKnightBlood)
                               )
                           )
                       ));
        }
    public Transform[] allEevees;   //necesitamos saber donde estan todos los eevee


    void Start()
    {
        //INICIALIZAMOS LA DATA DEL EXTERIOR
        kineticsAgent   = agent.kineticsAgent;
        steeringAgent   = agent.steeringAgent;
        kineticsTrainer = trainer.kineticsAgent;
        kineticsRival   = rival.kineticsAgent;

        Vector3 center = Vector3.zero;// Necesitamos el centro de masa de los eevee

        for (int k = 0; k < allEevees.Length; k++)
        {
            center += allEevees[k].transform.position;
        }

        center = center / allEevees.Length; // Centro de masas

        //piedras
        stones = GameObject.FindGameObjectsWithTag("Stone");


        Stack <GameObject> stonesStack = new Stack <GameObject>(stones);


        //Inicializamos grafo y A*
        graph = graphComponent.graph;
        aStar = new PathFindAStar(graph, null, null, null, walkable);

        //Inicializamos seek
        seek = new Seek(kineticsAgent, kineticsAgent, maxAccel);

        //obstaculos
        GameObject[]    obstacles     = GameObject.FindGameObjectsWithTag("Obstacle");
        obstacle_data[] obstaclesData = new obstacle_data[obstacles.Length];

        for (int k = 0; k < obstacles.Length; k++)
        {
            obstaclesData[k] = obstacles[k].GetComponent <obstacle_data>();
        }



        //COMENZAMOS A CONSTRUIR LA MAQUINA DE ESTADOS

        //1. ACCIONES:

        UpdateAStarGameObject     updateAStar  = new UpdateAStarGameObject(stonesStack, aStar, graph, kineticsAgent, walkable);
        FollowPathOfPoints        followPath   = new FollowPathOfPoints(steeringAgent, seek, null, false);
        PopGameObject             popStone     = new PopGameObject(stonesStack);
        DestroyGameObject         destroyStone = new DestroyGameObject(stonesStack);
        UpdateFollowPathWithAstar updateFollow = new UpdateFollowPathWithAstar(followPath, aStar, obstaclesData);
        UpdateAStarTarget         updateAStar2 = new UpdateAStarTarget(aStar, graph, kineticsAgent, graph.GetNode(550), walkable);
        StopMoving         stop               = new StopMoving(kineticsAgent, steeringAgent);
        RunSprite          showRunSprite      = new RunSprite(pokemonData);
        Evolve             evolve             = new Evolve(pokemonData, "Sun", updateAStar, updateAStar2, aStar);
        updateEvolveMethod updateEvolve       = new updateEvolveMethod(evolve, stonesStack);
        ShowIcon           showExclamation    = new ShowIcon(this.gameObject, "Exclamation");
        DisableIcon        disableExclamation = new DisableIcon(this.gameObject, "Exclamation");
        ShowIcon           showSweat          = new ShowIcon(this.gameObject, "Sweat");
        DisableIcon        disableSweat       = new DisableIcon(this.gameObject, "Sweat");



        //2. ESTADOS:

        List <Action> entryActions; //aqui iremos guardanndo todas las acciondes de entrada
        List <Action> exitActions;  //aqui iremos guardanndo todas las acciones de salida
        List <Action> actions;      //aqui guardaremos todas las acciones intermedias

        //2.a estado para esperar sin hacer nada
        entryActions = new List <Action>()
        {
            stop
        };                                       //al entrar al estado debemos parar
        actions     = new List <Action>();
        exitActions = new List <Action>();

        State wait = new State(actions, entryActions, exitActions);


        //2.b estado para sorprenderse
        entryActions = new List <Action>()
        {
            showExclamation
        };                                                  //al entrar al estado debemos sorprendernos
        actions     = new List <Action>();
        exitActions = new List <Action>()
        {
            disableExclamation
        };                                                   //al salir dejamos de sorprendernos

        State alert = new State(actions, entryActions, exitActions);

        //2.c estado para perseguir piedra
        entryActions = new List <Action>()
        {
            updateAStar, updateFollow, showSweat
        };                                                                       //al entrar al estado debemos actualizar el a* y luego el camino
        actions = new List <Action>()
        {
            followPath
        };                                 //durante la accion seguimos el camino
        exitActions = new List <Action>(); //al salir no hacemos nada

        State followStone = new State(actions, entryActions, exitActions);

        //2.d estado para perseguir punto de encuentro
        entryActions = new List <Action>()
        {
            updateAStar2, updateFollow
        };                                                             //al entrar al estado debemos actualizar el a* y luego el camino
        actions = new List <Action>()
        {
            followPath
        };                                 //durante la accion seguimos el camino
        exitActions = new List <Action>(); //al salir no hacemos nada

        State followReunionPoint = new State(actions, entryActions, exitActions);

        //3. CONDICIONES:

        TooCloseToPoint closeTrainer     = new TooCloseToPoint(center, kineticsTrainer, radiusAlert);
        TooCloseToPoint veryCloseTrainer = new TooCloseToPoint(center, kineticsTrainer, radiusRun);
        TooCloseToPoint closeRival       = new TooCloseToPoint(center, kineticsRival, radiusAlert);
        TooCloseToPoint veryCloseRival   = new TooCloseToPoint(center, kineticsRival, radiusRun);

        //Estas son las que de verdad necesitamos
        OrCondition  anyTargetClose     = new OrCondition(closeTrainer, closeRival);
        OrCondition  anyTargetVeryClose = new OrCondition(veryCloseRival, veryCloseTrainer);
        NotCondition noOneClose         = new NotCondition(anyTargetClose);
        NotCondition noOneVeryClose     = new NotCondition(anyTargetVeryClose);

        GameObjectGone    stoneGone      = new GameObjectGone(stonesStack);                //si una piedra es obtenida por alguien mas
        AllGameObjectGone allStoneGone   = new AllGameObjectGone(stonesStack);             //si se acaban las piedras
        ArrivedToStone    arrivedToStone = new ArrivedToStone(stonesStack, transform, 2f); //si alcanzamos una piedra



        //4. TRANSICIONES:

        Transition closeHuman     = new Transition(anyTargetClose, new List <Action>(), alert);
        Transition noHumanClose   = new Transition(noOneClose, new List <Action>(), wait);
        Transition veryCloseHuman = new Transition(anyTargetVeryClose, new List <Action>()
        {
            showRunSprite
        }, followStone);
        Transition stoneLost = new Transition(stoneGone, new List <Action> {
            popStone
        }, followStone);
        Transition allStonesLost = new Transition(allStoneGone, new List <Action> {
            evolve, disableSweat
        }, followReunionPoint);
        Transition reachStone = new Transition(arrivedToStone, new List <Action> {
            updateEvolve, evolve, destroyStone, popStone, disableSweat
        }, followReunionPoint);



        //4.1 AGREGAMOS TRANSICIONES A ESTADOS

        List <Transition> transitions;

        transitions = new List <Transition>()
        {
            closeHuman
        };
        wait.transitions = transitions;

        transitions = new List <Transition>()
        {
            veryCloseHuman, noHumanClose
        };
        alert.transitions = transitions;

        transitions = new List <Transition>()
        {
            allStonesLost, stoneLost, reachStone
        };
        followStone.transitions = transitions;

        followReunionPoint.transitions = new List <Transition>();



        //5 MAQUINA DE ESTADOS
        State[] states = new State[] { wait, alert, followStone, followReunionPoint };
        eeveeMachine = new StateMachine(states, wait);
    }
Beispiel #13
0
        public static Composite CreateThunderLordGrappleBehavior()
        {
            const int FROSTFIRE_RIDGE_ZONEID   = 6720;
            const int THUNDERLORD_GRAPPLE_ITEM = 101677;

            if (!SingularSettings.Instance.ToysAllowUse)
            {
                return(new ActionAlwaysFail());
            }

            if (SingularRoutine.CurrentWoWContext != WoWContext.Normal)
            {
                return(new ActionAlwaysFail());
            }

            if (!Me.IsMelee())
            {
                return(new ActionAlwaysFail());
            }

            return(new Throttle(
                       15,
                       new Decorator(
                           req => Me.ZoneId == FROSTFIRE_RIDGE_ZONEID,
                           new Decorator(
                               req => MovementManager.IsClassMovementAllowed && // checks Movement and GapCloser capability flags
                               CanUseCarriedItem(THUNDERLORD_GRAPPLE_ITEM) &&
                               Me.GotTarget() &&
                               Me.CurrentTarget.SpellDistance() >= 20 &&
                               Me.CurrentTarget.InLineOfSight &&
                               Me.IsSafelyFacing(Me.CurrentTarget) &&
                               (DateTime.UtcNow - Utilities.EventHandlers.LastNoPathFailure) > TimeSpan.FromSeconds(15),
                               new Sequence(
                                   new Action(r =>
            {
                const int THUNDERLORD_GRAPPLE_SPELL = 150258;
                WoWSpell grapple = WoWSpell.FromId(THUNDERLORD_GRAPPLE_SPELL);
                if (grapple != null && Me.CurrentTarget.SpellDistance() < grapple.MaxRange)
                {
                    return RunStatus.Success;
                }
                return RunStatus.Failure;
            }),
                                   new Action(r => StopMoving.Now()),
                                   new Wait(
                                       TimeSpan.FromMilliseconds(500),
                                       until => !Me.IsMoving,
                                       new ActionAlwaysSucceed()
                                       ),
                                   new Action(r =>
            {
                WoWItem item = FindItem(THUNDERLORD_GRAPPLE_ITEM);
                UseItem(item, Me.CurrentTarget);
            }),
                                   new Wait(
                                       1,
                                       until => Spell.IsCastingOrChannelling(),
                                       new ActionAlwaysSucceed()
                                       ),
                                   new Action(r => Logger.WriteDebug("ThunderlordGrapple: start @ {0:F1} yds", Me.CurrentTarget.Distance)),
                                   new Wait(
                                       3,
                                       until => !Spell.IsCastingOrChannelling(),
                                       new ActionAlwaysSucceed()
                                       ),
                                   new PrioritySelector(
                                       new Sequence(
                                           new Wait(
                                               1,
                                               until => !Me.IsMoving || Me.CurrentTarget.IsWithinMeleeRange,
                                               new ActionAlwaysSucceed()
                                               ),
                                           new Action(r => Logger.WriteDebug("ThunderlordGrapple: ended @ {0:F1} yds", Me.CurrentTarget.Distance))
                                           ),
                                       // allow following to Succeed so we Throttle the behavior even on failure at this point
                                       new Action(r => Logger.WriteDebug("ThunderlordGrapple: failed unexpectedly @ {0:F1} yds", Me.CurrentTarget.Distance))
                                       )
                                   )
                               )
                           )
                       ));
        }
Beispiel #14
0
    // public float radiusAlert = 40f;//radio para alertarse
    // public float radiusRun = 35f;//radio para huir


    void Start()
    {
        //INICIALIZAMOS LA DATA DEL EXTERIOR
        kineticsAgent      = agent.kineticsAgent;
        steeringAgent      = agent.steeringAgent;
        kineticsTrainer    = trainer.kineticsAgent;
        kineticsRival      = rival.kineticsAgent;
        sightSensor        = sightComponent.sensor;
        sightSensorPokemon = sightComponentPokemon.sensor;
        soundSensor        = soundComponent.sensor;



        //Piedras
        stones = GameObject.FindGameObjectsWithTag("Stone");
        List <GameObject> stonesList = new List <GameObject>(stones);


        //Inicializamos grafo y A*
        graph = graphComponent.graph;
        aStar = new PathFindAStar(graph, null, null, null, walkable);

        //Inicializamos seek
        seek = new Seek(kineticsAgent, kineticsAgent, maxAccel);

        //Inicializamos lookwehereyougoing
        look = new LookWhereYouAreGoing(kineticsAgent);

        //Obstaculos
        GameObject[]    obstacles     = GameObject.FindGameObjectsWithTag("Obstacle");
        obstacle_data[] obstaclesData = new obstacle_data[obstacles.Length];

        for (int k = 0; k < obstacles.Length; k++)
        {
            obstaclesData[k] = obstacles[k].GetComponent <obstacle_data>();
        }

        //Puntos estrategicos
        strategicPoints = pointsComponent.coverNodes;



        //COMENZAMOS A CONSTRUIR LA MAQUINA DE ESTADOS

        //1. ACCIONES:

        //acciones relacionadas a astar
        FollowPathOfPoints        followPath       = new FollowPathOfPoints(steeringAgent, seek, null, false);
        UpdateFollowPathWithAstar updateFollow     = new UpdateFollowPathWithAstar(followPath, aStar, obstaclesData);
        UpdateAstarBestCoverPoint updateAstarCover = new UpdateAstarBestCoverPoint(strategicPoints, transform, new Transform[] { kineticsRival.transform, kineticsTrainer.transform }, obstaclesData, graph, aStar, walkable);
        UpdateAStarSeenStone      updateAstarStone = new UpdateAStarSeenStone(sightSensor, aStar, graph, transform, walkable);
        //acciones de manejo de giros
        SetAngularSpeed setDefaultRotation = new SetAngularSpeed(kineticsAgent, 10f);
        SetAngularSpeed setZeroRotation    = new SetAngularSpeed(kineticsAgent, 0f);
        StopMoving      stop       = new StopMoving(kineticsAgent, steeringAgent);
        LookWhereGoing  lookAction = new LookWhereGoing(look, steeringAgent);
        //acciones de manejo de srpites
        ShowDefaultSprite defaultSprite = new ShowDefaultSprite(pokemonData);
        RunSprite         showRunSprite = new RunSprite(pokemonData);
        Evolve2           evolve;
        ShowIcon          showExclamation    = new ShowIcon(this.gameObject, "Exclamation");
        DisableIcon       disableExclamation = new DisableIcon(this.gameObject, "Exclamation");
        ShowIcon          showSweat          = new ShowIcon(this.gameObject, "Sweat");
        DisableIcon       disableSweat       = new DisableIcon(this.gameObject, "Sweat");
        //acciones de asistencia
        ResetSensor     resetSight        = new ResetSensor(sightSensor);
        ResetSensor     resetSightPokemon = new ResetSensor(sightSensorPokemon);
        ResetSensor     resetSound        = new ResetSensor(soundSensor);
        ResetSensorList resetSensors      = new ResetSensorList(new List <ResetSensor>()
        {
            resetSight, resetSound, resetSightPokemon
        });
        //acciones de tiempo
        SetTimer setAlertTime;
        //acciones que modifican la maquina de estados misma
        RemoveStateTransition removeTouchStone;
        RemoveStateTransition removeSawStone;
        RemoveStateTransition removeSawStone2;
        RemoveAction          removeDefaultSpriteAction;
        RemoveAction          removeRunSpriteAction;
        RemoveAction          removeRunSpriteAction2;



        //2. ESTADOS:

        List <Action> entryActions; //aqui iremos guardanndo todas las acciondes de entrada
        List <Action> exitActions;  //aqui iremos guardanndo todas las acciones de salida
        List <Action> actions;      //aqui guardaremos todas las acciones intermedias

        //2.a estado para esperar sin hacer nada
        //durante este estado eevee estara quieto hasta que algun humano lo haga reaccionar
        entryActions = new List <Action>()
        {
            stop, defaultSprite, setZeroRotation, resetSensors
        };                                                                                     //al entrar al estado debemos parar y sentarnos
        removeDefaultSpriteAction = new RemoveAction(defaultSprite, entryActions);
        actions = new List <Action>()
        {
        };                            //hacer guardia girando
        exitActions = new List <Action>()
        {
        };

        State wait = new State(actions, entryActions, exitActions);


        //2.b estado para sorprenderse
        //durante este estado eevee dara vueltas en alterta angustiado porque escucho algo, este estado durara solo cierto tiempo
        entryActions = new List <Action>()
        {
            showExclamation, setDefaultRotation
        };                                                                      //al entrar al estado debemos sorprendernos
        actions = new List <Action>()
        {
        };
        exitActions = new List <Action>()
        {
            disableExclamation, setZeroRotation
        };                                                                    //al salir dejamos de sorprendernos

        State alert = new State(actions, entryActions, exitActions);

        //2.c estado para perseguir piedra
        //durante este estado eevee se concentrara unicamente en buscar las piedra que vio
        entryActions = new List <Action>()
        {
            updateAstarStone, updateFollow, showExclamation, showRunSprite
        };                                                                                                 //al entrar al estado debemos actualizar el a* y luego el camino
        removeRunSpriteAction2 = new RemoveAction(showRunSprite, entryActions);
        actions = new List <Action>()
        {
            followPath, lookAction
        };                                                   //durante la accion seguimos el camino
        exitActions = new List <Action>()
        {
            disableExclamation
        };                                                    //al salir no hacemos nada

        State followStone = new State(actions, entryActions, exitActions);

        //2.d estado para perseguir punto de encuentro
        //durante este estado eevee buscara donde esconderse, puede verse interrumpido si accidentalmente toca una piedra o se comprometio su escondite
        entryActions = new List <Action>()
        {
            updateAstarCover, updateFollow, showSweat, showRunSprite, resetSensors
        };                                                                                                         //al entrar al estado debemos actualizar el a* y luego el camino
        removeRunSpriteAction = new RemoveAction(showRunSprite, entryActions);
        actions = new List <Action>()
        {
            followPath, lookAction
        };                                                   //durante la accion seguimos el camino
        exitActions = new List <Action>()
        {
            disableSweat
        };                                              //al salir no hacemos nada

        State followCoverPoint = new State(actions, entryActions, exitActions);

        //2.extra dummy states
        //estos estados son de relleno para facilitar la activacion de ciertas acciones en le orden adecuado
        entryActions = new List <Action>(); //al entrar al estado debemos parar y sentarnos
        actions      = new List <Action>(); //hacer guardia girando
        exitActions  = new List <Action>(); //al salir no hacemos nada

        State evolveState1 = new State(actions, entryActions, exitActions);
        State evolveState2 = new State(actions, entryActions, exitActions);



        //3. CONDICIONES:

        SawSomething       sawStone            = new SawSomething(sightSensor, "Stone");               //si vemos una piedra evolutiva
        SawSomething       sawHuman            = new SawSomething(sightSensor, "Human");               //si vemos una persona
        HeardSomething     heardHumanClose     = new HeardSomething(soundSensor, "Human", 0f);         //si escuchamos a un humano cerca
        HeardSomething     heardHumanVeryClose = new HeardSomething(soundSensor, "Human", 5f);         //si escuchamos a un  humanos muy cerca
        TouchedGameObjects touchedStone        = new TouchedGameObjects(stonesList, transform, "Sun"); //si tocamos una piedra evolutiva

        evolve = new Evolve2(pokemonData, touchedStone, updateAstarCover, aStar);
        FollowArrived       arrived        = new FollowArrived(followPath, transform);                      //si llegamos al objetivo de follow
        PokemonInCoverPoint otherInMyCover = new PokemonInCoverPoint(aStar, sightSensorPokemon, transform); //si vemos que un pokemon se metio en nuestro escondite

        TimeOut alertTimeOut = new TimeOut(5f);

        setAlertTime = new SetTimer(alertTimeOut);
        TrueCondition alwaysTrue = new TrueCondition();


        //4. TRANSICIONES:

        List <Action> transitionsActions;
        List <Action> noActions = new List <Action>();

        transitionsActions = new List <Action>()
        {
            setAlertTime
        };
        Transition heardCloseHuman     = new Transition(heardHumanClose, transitionsActions, alert);
        Transition seemsSafe           = new Transition(alertTimeOut, noActions, wait);
        Transition heardVeryCloseHuman = new Transition(heardHumanVeryClose, noActions, followCoverPoint);

        transitionsActions = new List <Action>()
        {
        };
        Transition sawAhuman        = new Transition(sawHuman, transitionsActions, followCoverPoint);
        Transition sawAstone        = new Transition(sawStone, transitionsActions, followStone);
        Transition pokemonInMyCover = new Transition(otherInMyCover, transitionsActions, followCoverPoint);

        //transiciones dummy
        transitionsActions = new List <Action>()
        {
            evolve
        };
        Transition evolving1 = new Transition(alwaysTrue, transitionsActions, followCoverPoint);
        Transition evolving2 = new Transition(alwaysTrue, transitionsActions, wait);


        transitionsActions = new List <Action>()
        {
            evolve, removeDefaultSpriteAction, removeRunSpriteAction, removeRunSpriteAction2
        };
        Transition touchStone1 = new Transition(touchedStone, transitionsActions, evolveState1);
        Transition touchStone2 = new Transition(touchedStone, transitionsActions, evolveState2);

        //si evolucionamos debemos quitar las transiciones relacionadas a las stones
        removeSawStone   = new RemoveStateTransition(sawAstone, followCoverPoint);
        removeSawStone2  = new RemoveStateTransition(sawAstone, alert);
        removeTouchStone = new RemoveStateTransition(touchStone1, followCoverPoint);
        transitionsActions.Add(removeSawStone);
        transitionsActions.Add(removeSawStone2);
        transitionsActions.Add(removeTouchStone);

        Transition arrivedFollowEnd = new Transition(arrived, noActions, wait);

        //4.1 AGREGAMOS TRANSICIONES A ESTADOS

        List <Transition> transitions;

        transitions = new List <Transition>()
        {
            sawAhuman, heardCloseHuman
        };
        wait.transitions = transitions;

        transitions = new List <Transition>()
        {
            sawAhuman, sawAstone, heardVeryCloseHuman, seemsSafe
        };
        alert.transitions = transitions;

        transitions = new List <Transition>()
        {
            evolving1
        };
        evolveState1.transitions = transitions;

        transitions = new List <Transition>()
        {
            evolving2
        };
        evolveState2.transitions = transitions;


        transitions = new List <Transition>()
        {
            touchStone1, sawAstone, pokemonInMyCover, arrivedFollowEnd, sawAhuman
        };
        followCoverPoint.transitions = transitions;

        transitions = new List <Transition>()
        {
            touchStone2, arrivedFollowEnd, pokemonInMyCover
        };
        followStone.transitions = transitions;



        //5 MAQUINA DE ESTADOS
        State[] states = new State[] { wait, alert, followCoverPoint, followStone, evolveState1, evolveState2 };
        eeveeMachine = new StateMachine(states, wait);
    }
        public HashSet <GoapGoal> CreateGoals(ClassConfiguration classConfig, IBlacklist blacklist)
        {
            var availableActions = new HashSet <GoapGoal>();

            List <WowPoint> pathPoints, spiritPath;

            GetPaths(out pathPoints, out spiritPath, classConfig);

            var playerDirection = new PlayerDirection(addonReader.PlayerReader, wowProcess, logger);
            var stopMoving      = new StopMoving(wowProcess, addonReader.PlayerReader);

            var castingHandler = new CastingHandler(wowProcess, addonReader.PlayerReader, logger, classConfig, playerDirection, NpcNameFinder);

            var stuckDetector      = new StuckDetector(addonReader.PlayerReader, wowProcess, playerDirection, stopMoving, logger);
            var followRouteAction  = new FollowRouteGoal(addonReader.PlayerReader, wowProcess, playerDirection, pathPoints, stopMoving, NpcNameFinder, blacklist, logger, stuckDetector, classConfig, pather);
            var walkToCorpseAction = new WalkToCorpseGoal(addonReader.PlayerReader, wowProcess, playerDirection, spiritPath, pathPoints, stopMoving, logger, stuckDetector, pather);

            availableActions.Clear();

            if (classConfig.Mode == Mode.CorpseRun)
            {
                availableActions.Add(new WaitGoal(logger));
                availableActions.Add(new CorpseRunGoal(addonReader.PlayerReader, wowProcess, playerDirection, spiritPath, stopMoving, logger, stuckDetector));
            }
            else if (classConfig.Mode == Mode.AttendedGather)
            {
                availableActions.Add(followRouteAction);
                availableActions.Add(new CorpseRunGoal(addonReader.PlayerReader, wowProcess, playerDirection, spiritPath, stopMoving, logger, stuckDetector));
            }
            else
            {
                if (classConfig.Mode == Mode.AttendedGrind)
                {
                    availableActions.Add(new WaitGoal(logger));
                }
                else
                {
                    availableActions.Add(followRouteAction);
                    availableActions.Add(walkToCorpseAction);
                }
                availableActions.Add(new TargetDeadGoal(wowProcess, logger));
                availableActions.Add(new ApproachTargetGoal(wowProcess, addonReader.PlayerReader, stopMoving, logger, stuckDetector, classConfig));

                if (classConfig.WrongZone.ZoneId > 0)
                {
                    availableActions.Add(new WrongZoneGoal(addonReader.PlayerReader, wowProcess, playerDirection, logger, stuckDetector, classConfig));
                }

                if (classConfig.Parallel.Sequence.Count > 0)
                {
                    availableActions.Add(new ParallelGoal(wowProcess, addonReader.PlayerReader, stopMoving, classConfig.Parallel.Sequence, castingHandler, logger));
                }

                var lootAction = new LootGoal(wowProcess, addonReader.PlayerReader, addonReader.BagReader, stopMoving, logger, classConfig);
                lootAction.AddPreconditions();
                availableActions.Add(lootAction);

                if (classConfig.Loot)
                {
                    lootAction = new PostKillLootGoal(wowProcess, addonReader.PlayerReader, addonReader.BagReader, stopMoving, logger, classConfig);
                    lootAction.AddPreconditions();
                    availableActions.Add(lootAction);
                }

                try
                {
                    var genericCombat = new CombatGoal(wowProcess, addonReader.PlayerReader, stopMoving, logger, classConfig, castingHandler);
                    availableActions.Add(genericCombat);
                    availableActions.Add(new PullTargetGoal(wowProcess, addonReader.PlayerReader, NpcNameFinder, stopMoving, logger, castingHandler, stuckDetector, classConfig));

                    foreach (var item in classConfig.Adhoc.Sequence)
                    {
                        availableActions.Add(new AdhocGoal(wowProcess, addonReader.PlayerReader, stopMoving, item, castingHandler, logger));
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex.ToString());
                }

                var pathProviders = new List <IRouteProvider>
                {
                    followRouteAction,
                    walkToCorpseAction
                };

                if (classConfig.VendorLocation.X > 0 && !string.IsNullOrEmpty(classConfig.VendorTargetKey))
                {
                    var vendorAction = new VendorGoal(addonReader.PlayerReader, wowProcess, playerDirection, stopMoving, logger, stuckDetector, classConfig, pather, this.addonReader.BagReader);
                    availableActions.Add(vendorAction);
                    pathProviders.Add(vendorAction);
                }
                else
                {
                    logger.LogWarning("Vendor location or target key is not defined, so no vendoring when bags are full.");
                }


                if (classConfig.RepairLocation.X > 0 && !string.IsNullOrEmpty(classConfig.RepairTargetKey))
                {
                    var repairAction = new RepairGoal(addonReader.PlayerReader, wowProcess, playerDirection, stopMoving, logger, stuckDetector, classConfig, pather, this.addonReader.BagReader);
                    availableActions.Add(repairAction);
                    pathProviders.Add(repairAction);
                }
                else
                {
                    availableActions.Add(new ItemsBrokenGoal(addonReader.PlayerReader, logger));
                    logger.LogWarning("Repair location or target key is not defined, so bot will stop if gear is red.");
                }

                this.RouteInfo = new RouteInfo(pathPoints, spiritPath, pathProviders, addonReader.PlayerReader);
            }

            return(availableActions);
        }
Beispiel #16
0
    void Start()
    {
        //INICIALIZAMOS LA DATA DEL EXTERIOR
        kineticsAgent = agent.kineticsAgent;
        steeringAgent = agent.steeringAgent;

        //POKEMONES
        pokemons = GameObject.FindGameObjectsWithTag("Pokemon");

        //barajeamos lo pokemones
        (new Utilities()).Shuffle(pokemons);

        pokemonKins = new Stack <Kinetics>();
        //creamos la pila de kinetics de los pokemones
        for (int i = 0; i < pokemons.Length; i++)
        {
            pokemonKins.Push(pokemons[i].GetComponent <static_data>().kineticsAgent);
        }

        //obstaculos
        GameObject[]    obstacles     = GameObject.FindGameObjectsWithTag("Obstacle");
        obstacle_data[] obstaclesData = new obstacle_data[obstacles.Length];

        for (int k = 0; k < obstacles.Length; k++)
        {
            obstaclesData[k] = obstacles[k].GetComponent <obstacle_data>();
        }

        //Inicializamos grafo y A*
        graph = graphComponent.graph;
        aStar = new PathFindAStar(graph, null, null, null, walkable);

        //Inicializamos seek
        seek = new Seek(kineticsAgent, kineticsAgent, maxAccel);

        //Inicializamos lookwehereyougoing
        look = new LookWhereYouAreGoing(kineticsAgent);


        //COMENZAMOS A CONSTRUIR LA MAQUINA DE ESTADOS

        //1. ACCIONES:

        UpdateAStar               updateAstar   = new UpdateAStar(pokemonKins, aStar, graph, kineticsAgent, walkable);
        FollowPathOfPoints        followPath    = new FollowPathOfPoints(steeringAgent, seek, null, false);
        RemovePokemon             removePokemon = new RemovePokemon(pokemonKins);
        UpdateFollowPathWithAstar updateFollow  = new UpdateFollowPathWithAstar(followPath, aStar, obstaclesData);
        StopMoving stop = new StopMoving(kineticsAgent, steeringAgent);

        //2. ESTADOS:

        List <Action> entryActions; //aqui iremos guardanndo todas las acciondes de entrada
        List <Action> exitActions;  //aqui iremos guardanndo todas las acciones de salida
        List <Action> actions;      //aqui guardaremos todas las acciones intermedias

        //2.a estado para seguir path

        entryActions = new List <Action>()
        {
            updateAstar, updateFollow
        };                                                            //al entrar al estado debemos
        //actualizar astar y el camino nuevo que da aStar darselo a follow
        actions = new List <Action>()
        {
            followPath
        };                                 //durante la accion seguimos el camino
        exitActions = new List <Action>(); //al salir no hacemos nada

        State followState = new State(actions, entryActions, exitActions);

        //2.b

        entryActions = new List <Action>()
        {
            stop
        };
        actions     = new List <Action>();
        exitActions = new List <Action>();

        State stopState = new State(actions, entryActions, exitActions);


        //3. CONDICIONES:

        AllCaught        allCaught            = new AllCaught(pokemonKins);           //ayudara a saber si todos los pokemon fueron atrpados
        CurrentWasCaught currentPokemonCaught = new CurrentWasCaught(pokemonKins);    //ayuda a saber si el pokemon actual en la pila fue atrapado
        PokemonMoved     pokemonMoved         = new PokemonMoved(pokemonKins, aStar); //ayudara a saber si el pokemon que estamos siguiendo se sale de su triangulo

        //4. TRANSICIONES:

        Transition caughtTarget = new Transition(currentPokemonCaught, new List <Action>()
        {
            removePokemon
        }, followState);
        Transition movedTarget      = new Transition(pokemonMoved, new List <Action>(), followState);
        Transition caughtAllTargets = new Transition(allCaught, new List <Action>(), stopState);

        //4.1 AGREGAMOS TRANSICIONES A ESTADOS

        List <Transition> transitions = new List <Transition>()
        {
            caughtAllTargets, caughtTarget, movedTarget
        };

        followState.transitions = transitions;

        stopState.transitions = new List <Transition>();

        //5 MAQUINA DE ESTADOS
        State[] states = new State[] { followState, stopState };
        rivalMachine = new StateMachine(states, followState);
    }
Beispiel #17
0
 protected void StopMovingMethod(object?o)
 {
     Velocity = new THUnity2D.Vector(Velocity.angle, 0);
     StopMoving?.Invoke(o);
 }
Beispiel #18
0
        public HashSet <GoapGoal> CreateGoals(ClassConfiguration classConfig, IBlacklist blacklist)
        {
            var availableActions = new HashSet <GoapGoal>();

            List <WowPoint> pathPoints, spiritPath;

            GetPaths(out pathPoints, out spiritPath, classConfig);

            var playerDirection = new PlayerDirection(logger, input, addonReader.PlayerReader);
            var stopMoving      = new StopMoving(input, addonReader.PlayerReader);

            var castingHandler = new CastingHandler(logger, input, addonReader.PlayerReader, classConfig, playerDirection, npcNameFinder);

            var stuckDetector      = new StuckDetector(logger, input, addonReader.PlayerReader, playerDirection, stopMoving);
            var followRouteAction  = new FollowRouteGoal(logger, input, addonReader.PlayerReader, playerDirection, pathPoints, stopMoving, npcNameFinder, blacklist, stuckDetector, classConfig, pather);
            var walkToCorpseAction = new WalkToCorpseGoal(logger, input, addonReader.PlayerReader, playerDirection, spiritPath, pathPoints, stopMoving, stuckDetector, pather);

            availableActions.Clear();

            if (classConfig.Mode == Mode.CorpseRun)
            {
                availableActions.Add(new WaitGoal(logger));
                availableActions.Add(new CorpseRunGoal(addonReader.PlayerReader, input, playerDirection, spiritPath, stopMoving, logger, stuckDetector));
            }
            else if (classConfig.Mode == Mode.AttendedGather)
            {
                availableActions.Add(followRouteAction);
                availableActions.Add(new CorpseRunGoal(addonReader.PlayerReader, input, playerDirection, spiritPath, stopMoving, logger, stuckDetector));
            }
            else
            {
                if (classConfig.Mode == Mode.AttendedGrind)
                {
                    availableActions.Add(new WaitGoal(logger));
                }
                else
                {
                    availableActions.Add(followRouteAction);
                    availableActions.Add(walkToCorpseAction);
                }
                availableActions.Add(new ApproachTargetGoal(logger, input, addonReader.PlayerReader, stopMoving, stuckDetector));

                if (classConfig.WrongZone.ZoneId > 0)
                {
                    availableActions.Add(new WrongZoneGoal(addonReader.PlayerReader, input, playerDirection, logger, stuckDetector, classConfig));
                }

                if (classConfig.Parallel.Sequence.Count > 0)
                {
                    availableActions.Add(new ParallelGoal(logger, input, addonReader.PlayerReader, stopMoving, classConfig.Parallel.Sequence, castingHandler));
                }

                if (classConfig.Loot)
                {
                    var lootAction = new LootGoal(logger, input, addonReader.PlayerReader, addonReader.BagReader, stopMoving, classConfig, npcNameFinder);
                    lootAction.AddPreconditions();
                    availableActions.Add(lootAction);

                    if (classConfig.Skin)
                    {
                        availableActions.Add(new SkinningGoal(logger, input, addonReader.PlayerReader, addonReader.BagReader, addonReader.equipmentReader, stopMoving, classConfig, npcNameFinder));
                    }
                }

                try
                {
                    var genericCombat = new CombatGoal(logger, input, addonReader.PlayerReader, stopMoving, classConfig, castingHandler);
                    availableActions.Add(genericCombat);
                    availableActions.Add(new PullTargetGoal(logger, input, addonReader.PlayerReader, npcNameFinder, stopMoving, castingHandler, stuckDetector, classConfig));

                    availableActions.Add(new CreatureKilledGoal(logger, addonReader.PlayerReader, classConfig));
                    availableActions.Add(new ConsumeCorpse(logger, addonReader.PlayerReader));

                    foreach (var item in classConfig.Adhoc.Sequence)
                    {
                        availableActions.Add(new AdhocGoal(logger, input, item, addonReader.PlayerReader, stopMoving, castingHandler));
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex.ToString());
                }


                foreach (var item in classConfig.NPC.Sequence)
                {
                    availableActions.Add(new AdhocNPCGoal(logger, input, addonReader.PlayerReader, playerDirection, stopMoving, npcNameFinder, stuckDetector, classConfig, pather, item, blacklist));
                    item.Path.AddRange(ReadPath(item.Name, item.PathFilename));
                }

                var pathProviders = availableActions.Where(a => a is IRouteProvider)
                                    .Cast <IRouteProvider>()
                                    .ToList();

                this.RouteInfo = new RouteInfo(pathPoints, spiritPath, pathProviders, addonReader.PlayerReader);

                this.pather.DrawLines(new List <LineArgs>()
                {
                    new LineArgs  {
                        Spots = pathPoints, Name = "grindpath", Colour = 2, MapId = addonReader.PlayerReader.ZoneId
                    },
                    new LineArgs {
                        Spots = spiritPath, Name = "spirithealer", Colour = 3, MapId = addonReader.PlayerReader.ZoneId
                    }
                });
            }

            return(availableActions);
        }
Beispiel #19
0
        public TouchEffect(Grid self, Trace t, double minRange)
        {
            center = t.Center;
            InputDevice d = null;

            MainBall = new Ellipse {
                Fill = DefaultBrush,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top,
                Height = t.Radius * 2,
                Width  = t.Radius * 2,
                Margin = new Thickness {
                    Left = t.Center.X - t.Radius, Top = t.Center.Y - t.Radius
                }
            };
            Ball = new Ellipse {
                Fill   = DefaultBrush,
                Width  = t.Radius,
                Height = t.Radius,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top,
            };
            Line = new Line {
                StrokeThickness     = t.Radius / 11,
                HorizontalAlignment = HorizontalAlignment.Left,
                Stroke            = DefaultBrush,
                VerticalAlignment = VerticalAlignment.Top,
                IsHitTestVisible  = false
            };
            EventHandler <TouchEventArgs> start = (s, e) => {
                if (Disabled || d != null)
                {
                    return;
                }
                d = e.Device;
                MoveTo(e.GetTouchPoint(self).Position);
                t.Released = false;
                var sc = RandomColor();
                Ball.Fill   = MainBall.Fill = new RadialGradientBrush(sc);
                Line.Stroke = new LinearGradientBrush(sc);
                ReadyToMove?.Invoke(t.Clone());
            };

            MainBall.TouchDown += start;
            Ball.TouchDown     += start;
            Line.X1             = t.Center.X;
            Line.Y1             = t.Center.Y;
            MoveTo(t.Center);
            self.Children.Add(Line);
            self.Children.Add(Ball);
            self.Children.Add(MainBall);
            Func <TouchEventArgs, bool> tryMove = e => {
                if (e.Device != d)
                {
                    return(false);
                }
                var to = e.GetTouchPoint(self).Position;
                t.Direction = to - t.Center;
                MoveTo(to);
                return(true);
            };

            self.TouchMove += (s, e) => {
                if (tryMove(e))
                {
                    Moving?.Invoke(t.Clone());
                }
            };
            self.TouchLeave += (s, e) => {
                if (!tryMove(e))
                {
                    return;
                }
                d          = null;
                t.Released = true;
                if (t.Direction.Length < minRange)
                {
                    t.Direction = new Vector();
                    Reset();
                }
                else
                {
                    StopMoving?.Invoke(t.Clone());
                }
            };
        }
Beispiel #20
0
 private void AnalyzePacket(byte[] aBuffer, PacketDirection aType)
 {
     switch (aType)
     {
         case PacketDirection.ClientToServer: break; // maybe later
         case PacketDirection.ServerToClient:
             // TODO : Here should be different types of mu protocol packets with parsing and event-based processing
             CommonServerToClientPacket cstcpTemp = new CommonServerToClientPacket(aBuffer);
             switch (cstcpTemp.ClassType)
             {
                 case PacketClass.C1:
                     switch (cstcpTemp.MesTypeC1)
                     {
                         case MessageTypeC1.PublicSpeech:
                             if (OnPublicSpeach != null)
                             {
                                 using ( PublicSpeech pspTemp = new PublicSpeech(aBuffer) )
                                     AsyncHelper.FireAndForget(OnPublicSpeach, pspTemp);
                             }
                             break;
                         case MessageTypeC1.CharacterList:
                             if (OnCharacterList != null)
                             {
                                 using ( CharacterList clTemp = new CharacterList(aBuffer) )
                                     AsyncHelper.FireAndForget(OnCharacterList, clTemp);
                             }
                             break;
                         case MessageTypeC1.DamageReceived:
                             if (OnDamageReceived != null)
                             {
                                 using ( DamageReceived drTemp = new DamageReceived(aBuffer) )
                                     AsyncHelper.FireAndForget(OnDamageReceived, drTemp);
                             }
                             break;
                         case MessageTypeC1.Death:
                             if (OnDeath != null)
                             {
                                 using ( Death dTemp = new Death(aBuffer) )
                                     AsyncHelper.FireAndForget(OnDeath, dTemp);
                             }
                             break;
                         case MessageTypeC1.OpenCreateGuildWindow:
                             if (OnOpenCreateGuildWindow != null)
                                 AsyncHelper.FireAndForget(OnOpenCreateGuildWindow);
                             break;
                         case MessageTypeC1.OpenVaultWindow:
                             if (OnOpenVaultWindow != null)
                                 AsyncHelper.FireAndForget(OnOpenVaultWindow);
                             break;
                         case MessageTypeC1.PlayerPosition:
                             if (OnLivingPosition != null)
                             {
                                 using ( LivingPosition ppTemp = new LivingPosition(aBuffer) )
                                     AsyncHelper.FireAndForget(OnLivingPosition, ppTemp);
                             }
                             break;
                         case MessageTypeC1.PutItem:
                             if (OnPutItem != null)
                             {
                                 using ( PutItem piTemp = new PutItem(aBuffer) )
                                     AsyncHelper.FireAndForget(OnPutItem, piTemp);
                             }
                             break;
                         case MessageTypeC1.ServerText:
                             if (OnServerText != null)
                             {
                                 using ( ServerText stTemp = new ServerText(aBuffer) )
                                     AsyncHelper.FireAndForget(OnServerText, stTemp);
                             }
                             break;
                         case MessageTypeC1.TraiderInfo:
                             if (OnTraiderInfo != null)
                             {
                                 using ( TraiderInfo tiTemp = new TraiderInfo(aBuffer) )
                                     AsyncHelper.FireAndForget(OnTraiderInfo, tiTemp);
                             }
                             break;
                         case MessageTypeC1.StopMoving:
                             if (OnStopMoving != null)
                             {
                                 using ( StopMoving smTemp = new StopMoving(aBuffer) )
                                     AsyncHelper.FireAndForget(OnStopMoving, smTemp);
                             }
                             break;
                         case MessageTypeC1.GameServerAnswer:
                             if (OnGameServerAnswer != null)
                             {
                                 using ( GameServerAnswer gsaTemp = new GameServerAnswer(aBuffer) )
                                     AsyncHelper.FireAndForget(OnGameServerAnswer, gsaTemp);
                             }
                             break;
                         case MessageTypeC1.UpdateHealth:
                             if (OnUpdateHealth != null)
                             {
                                 using ( UpdateHealth uhTemp = new UpdateHealth(aBuffer) )
                                     AsyncHelper.FireAndForget(OnUpdateHealth, uhTemp);
                             }
                             break;
                         case MessageTypeC1.UpdateMana:
                             if (OnUpdateMana != null)
                             {
                                 using ( UpdateMana umTemp = new UpdateMana(aBuffer) )
                                     AsyncHelper.FireAndForget(OnUpdateMana, umTemp);
                             }
                             break;
                     }
                     break;
             }
             if ((cstcpTemp.ClassType != PacketClass.Unknown) && (cstcpTemp.Length < aBuffer.Length))
             {
                 byte[] subArray = new byte[aBuffer.Length - cstcpTemp.Length];
                 Array.Copy(aBuffer, cstcpTemp.Length, subArray, 0, aBuffer.Length - cstcpTemp.Length);
                 AnalyzePacket(subArray, aType);
             }
             break;
     }
 }
Beispiel #21
0
        public HashSet <GoapGoal> CreateGoals(ClassConfiguration classConfig, IBlacklist blacklist)
        {
            var availableActions = new HashSet <GoapGoal>();

            List <WowPoint> pathPoints, spiritPath;

            GetPaths(out pathPoints, out spiritPath, classConfig);

            var playerDirection = new PlayerDirection(addonReader.PlayerReader, wowProcess, logger);
            var stopMoving      = new StopMoving(wowProcess, addonReader.PlayerReader);

            var castingHandler = new CastingHandler(wowProcess, addonReader.PlayerReader, logger, classConfig, playerDirection, NpcNameFinder);

            var stuckDetector      = new StuckDetector(addonReader.PlayerReader, wowProcess, playerDirection, stopMoving, logger);
            var followRouteAction  = new FollowRouteGoal(addonReader.PlayerReader, wowProcess, playerDirection, pathPoints, stopMoving, NpcNameFinder, blacklist, logger, stuckDetector, classConfig);
            var walkToCorpseAction = new WalkToCorpseGoal(addonReader.PlayerReader, wowProcess, playerDirection, spiritPath, pathPoints, stopMoving, logger, stuckDetector);

            this.RouteInfo = new RouteInfo(pathPoints, spiritPath, followRouteAction, walkToCorpseAction);

            availableActions.Clear();

            if (classConfig.Mode == Mode.CorpseRun)
            {
                availableActions.Add(new WaitGoal(logger));
                availableActions.Add(new CorpseRunGoal(addonReader.PlayerReader, wowProcess, playerDirection, spiritPath, stopMoving, logger, stuckDetector));
            }
            else if (classConfig.Mode == Mode.AttendedGather)
            {
                availableActions.Add(followRouteAction);
                availableActions.Add(new CorpseRunGoal(addonReader.PlayerReader, wowProcess, playerDirection, spiritPath, stopMoving, logger, stuckDetector));
            }
            else
            {
                availableActions.Add(new ItemsBrokenGoal(addonReader.PlayerReader, logger));

                if (classConfig.Mode == Mode.AttendedGrind)
                {
                    availableActions.Add(new WaitGoal(logger));
                }
                else
                {
                    availableActions.Add(followRouteAction);
                    availableActions.Add(walkToCorpseAction);
                }
                availableActions.Add(new TargetDeadGoal(wowProcess, logger));
                availableActions.Add(new ApproachTargetGoal(wowProcess, addonReader.PlayerReader, stopMoving, logger, stuckDetector, classConfig));

                if (classConfig.WrongZone.ZoneId > 0)
                {
                    availableActions.Add(new WrongZoneGoal(addonReader.PlayerReader, wowProcess, playerDirection, logger, stuckDetector, classConfig));
                }

                if (classConfig.Parallel.Sequence.Count > 0)
                {
                    availableActions.Add(new ParallelGoal(wowProcess, addonReader.PlayerReader, stopMoving, classConfig.Parallel.Sequence, castingHandler, logger));
                }

                var lootAction = new LootGoal(wowProcess, addonReader.PlayerReader, addonReader.BagReader, stopMoving, logger, classConfig);
                lootAction.AddPreconditions();
                availableActions.Add(lootAction);

                if (classConfig.Loot)
                {
                    lootAction = new PostKillLootGoal(wowProcess, addonReader.PlayerReader, addonReader.BagReader, stopMoving, logger, classConfig);
                    lootAction.AddPreconditions();
                    availableActions.Add(lootAction);
                }

                try
                {
                    var genericCombat = new CombatGoal(wowProcess, addonReader.PlayerReader, stopMoving, logger, classConfig, castingHandler);
                    availableActions.Add(genericCombat);
                    availableActions.Add(new PullTargetGoal(wowProcess, addonReader.PlayerReader, NpcNameFinder, stopMoving, logger, castingHandler, stuckDetector, classConfig));

                    foreach (var item in classConfig.Adhoc.Sequence)
                    {
                        availableActions.Add(new AdhocGoal(wowProcess, addonReader.PlayerReader, stopMoving, item, castingHandler, logger));
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex.ToString());
                }
            }

            return(availableActions);
        }
Beispiel #22
0
        public override void Pulse()
        {
            #region Pulse - check for conditions that we should not Pulse during

            /*
             * if (!StyxWoW.IsInGame)
             * {
             *  if (DateTime.UtcNow > _nextNotInGameMsgAllowed)
             *  {
             *      Logger.WriteDebug(Color.HotPink, "info: not in game");
             *      _nextNotInGameMsgAllowed = DateTime.UtcNow.AddSeconds(30);
             *  }
             *  return;
             * }
             * _nextNotInGameMsgAllowed = DateTime.MinValue;
             *
             * if (!StyxWoW.IsInWorld)
             * {
             *  if (DateTime.UtcNow > _nextNotInWorldMsgAllowed)
             *  {
             *      Logger.WriteDebug(Color.HotPink, "info: not in world");
             *      _nextNotInWorldMsgAllowed = DateTime.UtcNow.AddSeconds(30);
             *  }
             *  return;
             * }
             * _nextNotInWorldMsgAllowed = DateTime.MinValue;
             */

            #endregion

            _pulsePhase++;

            if (_pulsePhase == 1)
            {
                if (WaitForLatencyCheck.IsFinished)
                {
                    Latency = StyxWoW.WoWClient.Latency;
                    WaitForLatencyCheck.Reset();
                }

                // output messages about pulldistance and behaviorflag changes here
                MonitorPullDistance();
                MonitorBehaviorFlags();

/*
 *              // now if combat disabled, bail out
 *              bool combatDisabled = Bots.Grind.BehaviorFlags.Combat != (Bots.Grind.LevelBot.BehaviorFlags & Bots.Grind.BehaviorFlags.Combat);
 *              if (combatDisabled != _lastCombatDisabledState)
 *              {
 *                  _lastCombatDisabledState = combatDisabled;
 *                  Logger.Write(Color.HotPink,
 *                      combatDisabled
 *                          ? "info: botbase disabled BehaviorFlags.Combat"
 *                          : "info: botbase enabled BehaviorFlags.Combat"
 *                      );
 *              }
 */
                // check time since last call and be sure user knows if Singular isn't being called
                if (SingularSettings.Debug)
                {
                    TimeSpan since = CallWatch.TimeSpanSinceLastCall;
                    if (since.TotalSeconds > (4 * CallWatch.SecondsBetweenWarnings))
                    {
                        if (!Me.IsGhost && !Me.Mounted && !Me.IsFlying && DateTime.UtcNow > _nextNoCallMsgAllowed)
                        {
                            Logger.WriteDebug(Color.HotPink, "info: {0:F0} seconds since {1} BotBase last called Singular", since.TotalSeconds, GetBotName());
                            _nextNoCallMsgAllowed = DateTime.UtcNow.AddSeconds(4 * CallWatch.SecondsBetweenWarnings);
                        }
                    }
                }

                UpdateDiagnosticFPS();
            }
            else if (_pulsePhase == 2)
            {
                // talentmanager.Pulse() intense if does work, so return if true
                if (TalentManager.Pulse())
                {
                    return;
                }

                // check and output casting state information
                UpdateDiagnosticCastingState();

                UpdatePullMoreConditionals();

                // Update the current context, check if we need to rebuild any behaviors.
                UpdateContext();
            }
            else if (_pulsePhase == 3)
            {
                _pulsePhase = 0;

                // Pulse our StopAt manager
                StopMoving.Pulse();

                PetManager.Pulse();

                // Double cast maintenance
                Spell.MaintainDoubleCast();

                HotkeyDirector.Pulse();

                WatchAurasForProcs();
            }

            if (Me.Class == WoWClass.Warlock)
            {
                ClassSpecific.Warlock.Common.CancelBurningRushIfNeeded(fromPulse: true);
            }

            // Output if Target changed
            CheckCurrentTarget();

            // Output if Pet or Pet Target changed
            CheckCurrentPet();

            // check Targeting pulses
            if (HealerManager.NeedHealTargeting)
            {
                BotBase bot = GetCurrentBotBase();
                if (bot != null && (bot.PulseFlags & PulseFlags.Targeting) != PulseFlags.Targeting)
                {
                    HealerManager.Instance.Pulse();
                }
            }
            else if (TankManager.NeedTankTargeting && Group.MeIsTank)
            {
                BotBase bot = GetCurrentBotBase();
                if (bot != null && (bot.PulseFlags & PulseFlags.Targeting) != PulseFlags.Targeting)
                {
                    TankManager.Instance.Pulse();
                }
            }
        }
Beispiel #23
0
    public float radiusRun   = 15f; //radio para huir

    void Start()
    {
        //INICIALIZAMOS LA DATA DEL EXTERIOR
        kinGlameow      = glameow.kineticsAgent;
        steeringGlameow = glameow.steeringAgent;
        kineticsTarget  = target.kineticsAgent;
        kineticsTrainer = trainer.kineticsAgent;
        kineticsRival   = rival.kineticsAgent;

        Vector3 center = (kinGlameow.transform.position + kineticsTarget.transform.position) / 2;


        //COMENZAMOS A CONSTRUIR LA MAQUINA DE ESTADOS

        //1. ACCIONES:

        //este es seek pero en verdad como meowth le hace seek tambien pareciera que huye
        FollowTarget seekTarget = new FollowTarget(steeringGlameow, kinGlameow, kineticsTarget, maxSeekAccel);
        //el target es null porque todavia no sabemos cual trainer se  acercara
        ArriveToTarget arriveTrainer = new ArriveToTarget(steeringGlameow, kinGlameow, null, MaxAccelerationArrive, glameow.maxspeed, targetRadiusArrive, slowRadiusArrive);

        Kinetics[] targets = new Kinetics[2];
        targets[0] = kineticsTrainer;
        targets[1] = kineticsRival;

        SetArriveTarget setTrainer = new SetArriveTarget(targets, arriveTrainer);
        //seek closes
        StopMoving  stop               = new StopMoving(kinGlameow, steeringGlameow);
        ShowIcon    showHeart          = new ShowIcon(this.gameObject, "Heart");
        DisableIcon disableHeart       = new DisableIcon(this.gameObject, "Heart");
        ShowIcon    showSweat          = new ShowIcon(this.gameObject, "Sweat");
        DisableIcon disableSweat       = new DisableIcon(this.gameObject, "Sweat");
        ShowIcon    showExclamation    = new ShowIcon(this.gameObject, "Exclamation");
        DisableIcon disableExclamation = new DisableIcon(this.gameObject, "Exclamation");


        //2. ESTADOS:

        List <Action> entryActions; //aqui iremos guardanndo todas las acciondes de entrada
        List <Action> exitActions;  //aqui iremos guardanndo todas las acciones de salida
        List <Action> actions;      //aqui guardaremos todas las acciones intermedias

        //2.a estado para huir de anamorado (meowth)

        entryActions = new List <Action>()
        {
            showSweat
        };                                            //al entrar al estado ponemos un corazon
        actions = new List <Action>()
        {
            seekTarget
        };                                       //durante el estado perseguimos al enamorado
        exitActions = new List <Action>()
        {
            disableSweat
        };                                             //al salir quitamos el corazon

        State stalked = new State(actions, entryActions, exitActions);


        //2.b estado para alertarse de entrenador cercano

        entryActions = new List <Action>()
        {
            showExclamation, stop
        };                                                       //al entrar al estado debemos mostrar un signo de exclamacion
        actions     = new List <Action>();
        exitActions = new List <Action>()
        {
            disableExclamation
        };                                                  //al salir quitamos el signo


        State alert = new State(actions, entryActions, exitActions);


        //2.c estado para perseguir enamorado al entrenador

        entryActions = new List <Action> {
            setTrainer, showHeart
        };
        actions = new List <Action>()
        {
            arriveTrainer
        };
        exitActions = new List <Action> {
            disableHeart
        };


        State stalkTrainer = new State(actions, entryActions, exitActions);



        //3. CONDICIONES:

        TooCloseToPoint closeCenterTrainer = new TooCloseToPoint(center, kineticsTrainer, radiusAlert);
        TooClose        closeTrainer       = new TooClose(kinGlameow, kineticsTrainer, radiusAlert);
        TooClose        veryCloseTrainer   = new TooClose(kinGlameow, kineticsTrainer, radiusRun);
        TooCloseToPoint closeCenterRival   = new TooCloseToPoint(center, kineticsRival, radiusAlert);
        TooClose        closeRival         = new TooClose(kinGlameow, kineticsRival, radiusAlert);
        TooClose        veryCloseRival     = new TooClose(kinGlameow, kineticsRival, radiusRun);


        //Estas son las que de verdad necesitamos
        OrCondition  anyTargetCloseCenter = new OrCondition(closeCenterRival, closeCenterTrainer);
        OrCondition  anyTargetClose       = new OrCondition(closeTrainer, closeRival);
        OrCondition  anyTargetVeryClose   = new OrCondition(veryCloseRival, veryCloseTrainer);
        NotCondition noOneClose           = new NotCondition(anyTargetClose);


        List <Action> noActions = new List <Action>();
        //4. TRANSICIONES:
        Transition anyHumanClose     = new Transition(anyTargetCloseCenter, noActions, alert);
        Transition noHumanClose      = new Transition(noOneClose, noActions, stalkTrainer);
        Transition anyHumanVeryClose = new Transition(anyTargetVeryClose, noActions, stalkTrainer);



        //4.1 AGREGAMOS TRANSICIONES A ESTADOS
        List <Transition> transitions = new List <Transition>()
        {
            anyHumanClose
        };

        stalked.transitions = transitions;

        transitions = new List <Transition>()
        {
            noHumanClose, anyHumanVeryClose
        };
        alert.transitions = transitions;

        transitions = new List <Transition>();
        stalkTrainer.transitions = transitions;

        //5 MAQUINA DE ESTADOS
        State[] states = new State[] { stalked, alert, stalkTrainer };
        glameowMachine = new StateMachine(states, stalked);
    }
    public float radiusRun   = 15f; //radio para huir

    void Start()
    {
        //INICIALIZAMOS LA DATA DEL EXTERIOR
        kinMeowth       = meowth.kineticsAgent;
        steeringMeowth  = meowth.steeringAgent;
        kineticsTarget  = target.kineticsAgent;
        kineticsTrainer = trainer.kineticsAgent;
        kineticsRival   = rival.kineticsAgent;

        // Centro de masa de glameow y meowth sera util pra cierta condicion
        Vector3 center = (kinMeowth.transform.position + kineticsTarget.transform.position) / 2;

        //COMENZAMOS A CONSTRUIR LA MAQUINA DE ESTADOS

        //1. ACCIONES:

        FollowTarget seekTarget  = new FollowTarget(steeringMeowth, kinMeowth, kineticsTarget, maxSeekAccel);
        FollowTarget seekWorried = new FollowTarget(steeringMeowth, kinMeowth, kineticsTarget, 100f);

        Kinetics[] targets = new Kinetics[2];
        targets[0] = kineticsTrainer;
        targets[1] = kineticsRival;
        RunFromTargets runFromTargets     = new RunFromTargets(steeringMeowth, kinMeowth, targets, maxSeekAccel * 5);
        StopMoving     stop               = new StopMoving(kinMeowth, steeringMeowth);
        UpdateMaxSpeed moreMaxSpeed       = new UpdateMaxSpeed(meowth, meowth.maxspeed * 5); // esto ayudara a aumentar la maxspeed
        UpdateMaxSpeed speedBackToNormal  = new UpdateMaxSpeed(meowth, meowth.maxspeed);     // esto guarda la maxspeed original para volverla a poner asi
        ShowIcon       showHeart          = new ShowIcon(this.gameObject, "Heart");
        DisableIcon    disableHeart       = new DisableIcon(this.gameObject, "Heart");
        ShowIcon       showSweat          = new ShowIcon(this.gameObject, "Sweat");
        DisableIcon    disableSweat       = new DisableIcon(this.gameObject, "Sweat");
        ShowIcon       showExclamation    = new ShowIcon(this.gameObject, "Exclamation");
        DisableIcon    disableExclamation = new DisableIcon(this.gameObject, "Exclamation");



        //2. ESTADOS:

        List <Action> entryActions; //aqui iremos guardanndo todas las acciondes de entrada
        List <Action> exitActions;  //aqui iremos guardanndo todas las acciones de salida
        List <Action> actions;      //aqui guardaremos todas las acciones intermedias

        //2.a estado para perseguir enamorado (glameow)

        entryActions = new List <Action>()
        {
            showHeart
        };                                            //al entrar al estado ponemos un corazon
        actions = new List <Action>()
        {
            seekTarget
        };                                       //durante el estado perseguimos al enamorado
        exitActions = new List <Action>()
        {
            disableHeart
        };                                             //al salir quitamos el corazon

        State stalkTarget = new State(actions, entryActions, exitActions);


        //2.b estado para alertarse de entrenador cercano

        entryActions = new List <Action>()
        {
            showExclamation, stop
        };                                                       //al entrar al estado debemos mostrar un signo de exclamacion
        actions     = new List <Action>();
        exitActions = new List <Action>()
        {
            disableExclamation
        };                                                  //al salir quitamos el signo


        State alert = new State(actions, entryActions, exitActions);

        //2,c estado para perseguir sin corazon
        entryActions = new List <Action>();//al entrar al estado ponemos un corazon
        actions      = new List <Action>()
        {
            seekTarget
        };                                 //durante el estado perseguimos al enamorado
        exitActions = new List <Action>(); //al salir quitamos el corazon

        State stalk = new State(actions, entryActions, exitActions);


        //2.d estado para huir del entrenador

        entryActions = new List <Action>()
        {
            moreMaxSpeed
        };
        actions = new List <Action>()
        {
            runFromTargets
        };
        exitActions = new List <Action>()
        {
            speedBackToNormal
        };


        State runAway = new State(actions, entryActions, exitActions);

        //2.e estado para preocuparse por alguien y seguirlo preocupado


        entryActions = new List <Action>()
        {
            showSweat, disableHeart, disableExclamation
        };
        actions = new List <Action>()
        {
            seekWorried
        };
        exitActions = new List <Action>()
        {
            disableSweat
        };

        State worry = new State(actions, entryActions, exitActions);


        //3. CONDICIONES:

        TooCloseToPoint closeCenterTrainer = new TooCloseToPoint(center, kineticsTrainer, radiusAlert);
        TooClose        closeTrainer       = new TooClose(kinMeowth, kineticsTrainer, radiusAlert);
        TooClose        veryCloseTrainer   = new TooClose(kinMeowth, kineticsTrainer, radiusRun);
        TooCloseToPoint closeCenterRival   = new TooCloseToPoint(center, kineticsRival, radiusAlert);
        TooClose        closeRival         = new TooClose(kinMeowth, kineticsRival, radiusAlert);
        TooClose        veryCloseRival     = new TooClose(kinMeowth, kineticsRival, radiusRun);


        //Estas son las que de verdad necesitamos
        OrCondition  anyTargetCloseCenter = new OrCondition(closeCenterRival, closeCenterTrainer);
        OrCondition  anyTargetClose       = new OrCondition(closeTrainer, closeRival);
        OrCondition  anyTargetVeryClose   = new OrCondition(veryCloseRival, veryCloseTrainer);
        NotCondition noOneClose           = new NotCondition(anyTargetClose);
        NotCondition noOneVeryClose       = new NotCondition(anyTargetVeryClose);

        WasCaught targetCaught = new WasCaught(kineticsTarget);


        List <Action> noActions = new List <Action>();
        //4. TRANSICIONES:
        Transition anyHumanCloseCenter = new Transition(anyTargetCloseCenter, noActions, alert);
        Transition anyHumanClose       = new Transition(anyTargetClose, noActions, alert);
        Transition noHumanClose        = new Transition(noOneClose, noActions, stalk);
        Transition anyHumanVeryClose   = new Transition(anyTargetVeryClose, noActions, runAway);
        Transition noHumanVeryClose    = new Transition(noOneVeryClose, noActions, alert);
        Transition targetWasCaught     = new Transition(targetCaught, noActions, worry);

        //4.1 AGREGAMOS TRANSICIONES A ESTADOS
        List <Transition> transitions = new List <Transition>()
        {
            anyHumanCloseCenter, targetWasCaught
        };

        stalkTarget.transitions = transitions;

        transitions = new List <Transition>()
        {
            noHumanClose, anyHumanVeryClose, targetWasCaught
        };
        alert.transitions = transitions;

        transitions = new List <Transition>()
        {
            anyHumanClose, targetWasCaught
        };
        stalk.transitions = transitions;

        transitions = new List <Transition>()
        {
            noHumanVeryClose, targetWasCaught
        };
        runAway.transitions = transitions;

        worry.transitions = new List <Transition>();//es un sumidero

        //5 MAQUINA DE ESTADOS
        State[] states = new State[] { stalkTarget, alert, stalk, runAway, worry };
        meowthMachine = new StateMachine(states, stalkTarget);
    }