Example #1
0
    public void Init()
    {
        GameWorld = GameObject.FindGameObjectWithTag("world").GetComponent<World>();
        GameStateMachine = GameObject.FindGameObjectWithTag("stateMachine").GetComponent<StateMachine>();

        ActionList = new List<Action_Base>();
    }
        void Awake()
        {
            tween = GetComponent<Tween>();
            tween.autoPlay = false;

            machine = new StateMachine<GateFSM>(this);
        }
Example #3
0
        public void Assign_BugIsAlreadyAssignedAndSelfTransitionNotPermitted_TransitionNotRun()
        {
            //arrange
            _stateMachine = new StateMachine<BugState, TransitionActionStatus>("state machine name",
                                                                               _transitions,
                                                                               permitSelfTransition: false,
                                                                               initialState: new BugState.Open());
            var bug = new BugStateful(_bug, _stateMachine);
            TransitionActionStatus transitionActionStatus;
            const string assigneeEmail1 = "*****@*****.**";
            const string assigneeEmail2 = "*****@*****.**";

            //act
            bug.Assign(assigneeEmail1, out transitionActionStatus);

            var exceptionCaught = false;
            try
            {
                bug.Assign(assigneeEmail2, out transitionActionStatus);
            }
            catch (SelfTransitionException)
            {
                exceptionCaught = true;
            }

            //assert
            Assert.That(exceptionCaught, Is.EqualTo(true));
            Assert.That(bug.CurrentState, Is.TypeOf<BugState.Assigned>());
            Assert.That(bug.Bug.AssigneeEmail, Is.EqualTo(assigneeEmail1));
            Assert.That(transitionActionStatus, Is.EqualTo(TransitionActionStatus.NotRun));
        }
Example #4
0
	// Use this for initialization
	void Start () {
		navAgent = GetComponent<NavMeshAgent> ();
		home = GameObject.Find ("Home");

		fsm = new StateMachine<GhostAI> (this);
		fsm.setState (new ScatterState ());
	}
    /// <summary>
    /// Assigns the animation to the character.
    /// </summary>
    static void AssignAnimationToCharacter(AnimationClip clip, GameObject character)
    {
        //create a new controller
        UnityEditorInternal.AnimatorController my_controller = new UnityEditorInternal.AnimatorController();
        my_controller.name = "generic_controller";

        //check if the animator component is already attached to the character
        if (character.GetComponent<Animator>() == null)
            character.AddComponent<Animator>();

        //create the state machine with the animation clip
        StateMachine sm = new StateMachine();
        sm.AddState("default_state");
        sm.GetState(0).SetMotion(0, clip);

        //check if the controller already has a based layer
        if (my_controller.GetLayerCount() == 0)
            my_controller.AddLayer("Base Layer");
        //set the state machine
        my_controller.SetLayerStateMachine(0, sm);

        //assign the controller
        Animator animator = (Animator)character.GetComponent<Animator>();
        UnityEditorInternal.AnimatorController.SetAnimatorController(animator,my_controller);
    }
Example #6
0
 public RegularState(StateMachine parent, bool isTough, params int[] agroBorders)
     : base(parent)
 {
     borders = agroBorders;
     AgroBorder = GetNextBorder(parent.Screen, agroBorders);
     this.isTough = isTough;
 }
    public void InitialTransition()
    {
        //This is an odd request by a user, where they wanted to use methods declared in a super class. By default we expect this to fail, but we can enable this behaivour
        //by removing BindingFlags.DeclaredOnly from the reflection routine in StateMachine.cs

        fsm = engine.Initialize<States>(behaviour, States.One);
        fsm.ChangeState(States.Two);

        //Test for when we want to include superclass methods
        //Assert.AreEqual(1, behaviour.oneStats.enterCount);
        //Assert.AreEqual(0, behaviour.oneStats.updateCount);
        //Assert.AreEqual(0, behaviour.oneStats.lateUpdateCount);
        //Assert.AreEqual(1, behaviour.oneStats.exitCount);
        //Assert.AreEqual(1, behaviour.oneStats.finallyCount);

        //Assert.AreEqual(1, behaviour.twoStats.enterCount);
        //Assert.AreEqual(0, behaviour.twoStats.updateCount);
        //Assert.AreEqual(0, behaviour.twoStats.lateUpdateCount);
        //Assert.AreEqual(0, behaviour.twoStats.exitCount);
        //Assert.AreEqual(0, behaviour.twoStats.finallyCount);

        //Test for no superclass methods
        Assert.AreEqual(0, behaviour.oneStats.enterCount);
        Assert.AreEqual(0, behaviour.oneStats.updateCount);
        Assert.AreEqual(0, behaviour.oneStats.lateUpdateCount);
        Assert.AreEqual(0, behaviour.oneStats.exitCount);
        Assert.AreEqual(0, behaviour.oneStats.finallyCount);

        Assert.AreEqual(0, behaviour.twoStats.enterCount);
        Assert.AreEqual(0, behaviour.twoStats.updateCount);
        Assert.AreEqual(0, behaviour.twoStats.lateUpdateCount);
        Assert.AreEqual(0, behaviour.twoStats.exitCount);
        Assert.AreEqual(0, behaviour.twoStats.finallyCount);
    }
		protected override void Check()
		{
			var sm = new StateMachine<S>(S.A);

			sm.Transition(
				from: S.A,
				to: S.B);

			(sm == S.B).ShouldBe(true);

			sm.Transition(
				from: S.B,
				to: S.A,
				guard: false);

			(sm == S.B).ShouldBe(true);

			sm.Transition(
				from: S.A,
				to: S.A);

			(sm == S.B).ShouldBe(true);

			var x = 0;
			sm.Transition(
				from: S.B,
				to: S.C,
				guard: x == 0,
				action: () => x = 17);

			(sm == S.C).ShouldBe(true);
			x.ShouldBe(17);
		}
Example #9
0
 // Use this for initialization
 void Start ()
 {
     GoToMiddleOfTile();
     speed_max = 3;
     state_machine = new StateMachine();
     state_machine.ChangeState(new StateKeeseNormal(this, GetComponent<SpriteRenderer>(), flap));
 }
Example #10
0
 //inform player move
 public override void onEnterState( StateMachine  prevState)
 {
     base.onEnterState(prevState);
     this.prevState = prevState;
     actionPoint = 1;
     this.targetLayer = GameController.instance.interactLayer;
 }
Example #11
0
    protected override void Start()
    {
        base.Start();//gets the start from living entity
        startingHealth += startingHealth/100*waveStats._percentHP;
        health = startingHealth;
        print(health + "hp");
        /** we halen een referentie op naar de state machine */
        stateMachine = GetComponent<StateMachine>();
        //anim.GetComponent<Animator>();
        /** we voegen de verschillende states toe aan de state machine */
		MakeStates();

        /** we geven de eerste state door (rondlopen) */
        if (patrol)
        {
            stateMachine.SetState(StateID.Patrol);
        }
        else if(charge)
        {
            stateMachine.SetState(StateID.Charge);
        }
        else
        {
            stateMachine.SetState(StateID.Wandering);
        }

    }
Example #12
0
	public override void onEnterState ( StateMachine  prevState)
	{
		base.onEnterState(prevState);
		this.prevState = prevState;
		//open menu
		setCurrentState( main_state );
	}
 public static void ShowWithTarget(StateMachine target) {
     var editor = GetWindow<StateMachineEditor>();
     editor.machine = target;
     editor.stateSelected = null;
     editor.transitionSelected = null;
     editor.Show();
 }
Example #14
0
        public AdcStateMachine(User user)
        {
            _states[AdcProtocolState.Unknown] = new UnknownState(user);
            _states[AdcProtocolState.Protocol] = new ProtocolState(user);
            _states[AdcProtocolState.Identify] = new IdentifyState(user);
            _states[AdcProtocolState.Normal] = new NormalState(user);

            _stateMachine = new StateMachine<AdcProtocolState, StateMachineEvent, Command>(
                () => user.StateManager.GetOrAddStateAsync(StoredState, AdcProtocolState.Unknown),
                state => user.StateManager.SetStateAsync(StoredState, state));

            _stateMachine
                .ConfigureState(_states[AdcProtocolState.Unknown])
                .SwitchTo(AdcProtocolState.Protocol, StateMachineEvent.ClientOpened)
                .ElseSwitchTo(AdcProtocolState.Unknown);

            _stateMachine
                .ConfigureState(_states[AdcProtocolState.Protocol])
                .ConfigureIfChoice(new SupportsChoice(user))
                .ConfigureIfChoice(new ProtocolStatusChoice(user))
                .ConfigureElseTransition(new ProtocolToUnknownTransition(user));

            _stateMachine
                .ConfigureState(_states[AdcProtocolState.Identify])
                .ConfigureIfChoice(new IdentifyInfChoice(user))
                .ConfigureIfChoice(new IdentifyStatusChoice(user))
                .ConfigureElseTransition(new IdentifyToUnknownTransition(user));

            _stateMachine
                .ConfigureState(_states[AdcProtocolState.Normal])
                .ConfigureTransition(new NormalToUnknownTransition(user))
                .ConfigureIfChoice(new NormalStatusChoice(user))
                .ConfigureElseTransition(new NormalProcessing(user));
        }
		public override void OnEnable() {
			base.OnEnable();
			
			stateMachine = (StateMachine)target;
			stateMachineObject = stateMachine.gameObject;
			HideLayersAndStates();
		}
Example #16
0
 public AgroState(StateMachine parent, int agroBorder)
     : base(parent)
 {
     this.agroBorder = agroBorder;
     oldBalance = Spawner.GetInstance().FriendliesPerEnemies;
     Spawner.GetInstance().FriendliesPerEnemies = 2;
 }
Example #17
0
		public static void Run () {
			var model = new StateMachine<Instance>("compTest");
			var initial = new PseudoState<Instance>("initial", model, PseudoStateKind.Initial);

			var activity1 = new State<Instance>("activity1", model);
			var activity2 = new State<Instance>("activity2", model);
			var activity3 = new State<Instance>("activity3", model);
			var junction1 = new PseudoState<Instance>("junction1", model, PseudoStateKind.Junction);
			var junction2 = new PseudoState<Instance>("junction2", model, PseudoStateKind.Junction);
			var end = new FinalState<Instance>("end", model);

			var subInitial = new PseudoState<Instance>("subInitial", activity2, PseudoStateKind.Initial);
			var subEnd = new FinalState<Instance>("subEnd", activity2);

			subInitial.To(subEnd);
			initial.To(activity1);
			activity1.To(activity2);
			activity2.To(junction1);
			junction1.To(junction2).Else();
			junction2.To(activity3).Else();
			activity3.To(end);

			model.Validate();

			var instance = new Instance("transitions");
			model.Initialise(instance);

			Trace.Assert(model.IsComplete(instance));
		}
Example #18
0
		public static void Run () {
			var model = new StateMachine<Instance>("model");

			var initial = new PseudoState<Instance>("initial", model);

			var choice = new PseudoState<Instance>("choice", model, PseudoStateKind.Choice);
			var junction = new PseudoState<Instance>("junction", model, PseudoStateKind.Junction);

			var finalState = new FinalState<Instance>("final", model);

			initial.To(choice);
			choice.To(junction).When(i => i.Int1 == 0).Effect(i => i.Int1 = 1);
			choice.To(finalState).Else();
			junction.To(choice).When(i => i.Int2 == 0).Effect(i => i.Int2 = 2);

			model.Validate();

			var instance = new Instance("else");

			model.Initialise(instance);

			Trace.Assert(model.IsComplete(instance));
			Trace.Assert(instance.Int1 == 1);
			Trace.Assert(instance.Int2 == 2);
		}
Example #19
0
        public void CompositeStateTest()
        {
            var sm = new StateMachine();

              var s0 = CreateState("0");
              var s0States = new StateCollection();
              s0.ParallelSubStates.Add(s0States);
              sm.States.Add(s0);

              var s00 = CreateState("00");
              s0States.Add(s00);
              var s01 = CreateState("01");
              s0States.Add(s01);

              var t0 = new Transition
              {
            SourceState = s0,
            TargetState = s0,
              };
              t0.Action += (s, e) => _events = _events + "A0";

              sm.Update(TimeSpan.FromSeconds(1));
              sm.Update(TimeSpan.FromSeconds(1));
              t0.Fire();
              sm.Update(TimeSpan.FromSeconds(1));
              sm.Update(TimeSpan.FromSeconds(1));

              Assert.AreEqual("E0E00U00U0U00U0X00X0A0E0E00U00U0U00U0", _events);
        }
Example #20
0
        public GuardTest()
        {
            this.testee = new StateMachine<StateMachine.States, StateMachine.Events>();

            this.testee.Initialize(StateMachine.States.A);
            this.testee.EnterInitialState();
        }
        public void StayInSameStateTwoStates_Transition()
        {
            var sm = new StateMachine<State, Trigger>(State.A);

            sm.Configure(State.A)
                .InternalTransition(Trigger.X, (t) => { })
                .Permit(Trigger.Y, State.B);

            sm.Configure(State.B)
                    .InternalTransition(Trigger.X, (t) => { })
                    .Permit(Trigger.Y, State.A);

            // This should not cause any state changes
            Assert.AreEqual(State.A, sm.State);
            sm.Fire(Trigger.X);
            Assert.AreEqual(State.A, sm.State);

            // Change state to B
            sm.Fire(Trigger.Y);

            // This should also not cause any state changes
            Assert.AreEqual(State.B, sm.State);
            sm.Fire(Trigger.X);
            Assert.AreEqual(State.B, sm.State);
        }
Example #22
0
        public FieldPlayer(SoccerTeam homeTeam,
                      int homeRegionIndex,
                      State<FieldPlayer> startState,
                      Vector2D heading,
                      Vector2D velocity,
                      double mass,
                      double maxForce,
                      double maxSpeed,
                      double maxTurnRate,
                      double scale,
                      PlayerBase.PlayerRoles role)
            : base(homeTeam, homeRegionIndex, heading, velocity, mass, maxForce, maxSpeed, maxTurnRate, scale, role)
        {
            _stateMachine = new StateMachine<FieldPlayer>(this);

            if (startState != null)
            {
                _stateMachine.CurrentState = _stateMachine.PreviousState = startState;
                _stateMachine.GlobalState = GlobalPlayerState.Instance;
                _stateMachine.CurrentState.Enter(this);
            }

            _steeringBehaviors.Seperation = true;

            //set up the kick regulator
            _kickRegulator = new Regulator(ParameterManager.Instance.PlayerKickFrequency);
        }
Example #23
0
		public static void Run () {
			var model = new StateMachine<Instance>("history");

			var initial = new PseudoState<Instance>("initial", model, PseudoStateKind.Initial);
			var shallow = new State<Instance>("shallow", model);
			var deep = new State<Instance>("deep", model);
			var end = new FinalState<Instance>("final", model);

			var s1 = new State<Instance>("s1", shallow);
			var s2 = new State<Instance>("s2", shallow);

			initial.To(shallow);
			new PseudoState<Instance>("shallow", shallow, PseudoStateKind.ShallowHistory).To(s1);
			s1.To(s2).When<string>(c => c == "move");
			shallow.To(deep).When<string>(c => c == "go deep");
			deep.To(shallow).When<string>(c => c == "go shallow");
			s2.To(end).When<string>(c => c == "end");

			model.Validate();

			var instance = new Instance("history");

			model.Initialise(instance);

			model.Evaluate(instance, "move");
			model.Evaluate(instance, "go deep");
			model.Evaluate(instance, "go shallow");
			model.Evaluate(instance, "end");

			Trace.Assert(model.IsComplete(instance));
		}
Example #24
0
 public WaitingState(StateMachine sm, CameraManager cam, Game game, float time, Team TeamOnSuper)
     : base(sm, cam, game)
 {
     this.remainingTime = time;
     this.TeamOnSuper = TeamOnSuper;
     this.onWiningPoints = false;
 }
Example #25
0
 public WaitingState(StateMachine sm, CameraManager cam, Game game, float time, Team team, bool _onWiningPoints)
     : base(sm, cam, game)
 {
     this.remainingTime 	= time;
     this.TeamOnSuper 	= team;
     this.onWiningPoints = true;
 }
Example #26
0
        public void ExposesCorrectUnderlyingTrigger()
        {
            var transtioning = new StateMachine<State, Trigger>.TransitioningTriggerBehaviour(
                Trigger.X, State.C, () => true);

            Assert.AreEqual(Trigger.X, transtioning.Trigger);
        }
Example #27
0
        public void WhenGuardConditionTrue_IsGuardConditionMetIsTrue()
        {
            var transtioning = new StateMachine<State, Trigger>.TransitioningTriggerBehaviour(
                Trigger.X, State.C, () => true);

            Assert.IsTrue(transtioning.IsGuardConditionMet);
        }
Example #28
0
 // Use this for initialization
 void Start()
 {
     sm = StateMachine<States>.Initialize(this);
     sm.ChangeState(States.Lobby);
     resourceManager = this.GetComponent<ResourceManager>();
     currentPlayer = playerManager.currentPlayer;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="StateMachine"/> class.
 /// </summary>
 /// <param name="sm">Sm.</param>
 public StateMachine(StateMachine sm)
     : this()
 {
     if(sm != null){
         SetAllStatus(sm._status[0],sm._status[1],sm._status[2]);
     }
 }
 private bool TryGetStateMachine(out StateMachine stateMachine)
 {
     stateMachine = null;
     ITextBuffer textBuffer;
     return _weakTextBuffer.TryGetTarget(out textBuffer) &&
         textBuffer.Properties.TryGetProperty(typeof(StateMachine), out stateMachine);
 }
Example #31
0
 public GameRules()
 {
     state = new StateMachine(State.MakeStates());
 }
Example #32
0
 public override void Awake(StateMachine stateMachine)
 {
     _data = stateMachine.GetComponent <BasicMonsterData>();
 }
Example #33
0
File: State.cs Project: molvin/LD48
 public void Initialize(object Owner, StateMachine StateMachine)
 {
     this.Owner        = Owner;
     this.StateMachine = StateMachine;
     Initialize();
 }
Example #34
0
        private void SetupStateMachine(StateMachine stateMachine, IArea garden)
        {
            stateMachine.AddOffState()
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.Off);

            stateMachine.AddState(new StatefulComponentState("Te"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.Off);

            stateMachine.AddState(new StatefulComponentState("G"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.Off);

            stateMachine.AddState(new StatefulComponentState("W"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.Off);

            stateMachine.AddState(new StatefulComponentState("D"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.Off);

            stateMachine.AddState(new StatefulComponentState("Ti"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.On);

            stateMachine.AddState(new StatefulComponentState("G+W"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.Off);

            stateMachine.AddState(new StatefulComponentState("Te+G+W"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.Off)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.Off);

            stateMachine.AddState(new StatefulComponentState("Te+G+W+D+Ti"))
            .WithActuator(garden.GetLamp(Garden.LampTerrace), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampGarage), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampTap), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.SpotlightRoof), BinaryStateId.On)
            .WithActuator(garden.GetLamp(Garden.LampRearArea), BinaryStateId.On);
        }
Example #35
0
 public CombatState(GameObject go, StateMachine sm, State previous) : base(go, sm)
 {
     _previous = previous;
 }
Example #36
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            if (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(_subPath, !VersionCheckState.IsLatest(), _enableJsonValidation);
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }

            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            _session = new Session(new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath, false, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            _session.Client.ApiFailure = new ApiFailureStrategy(_session);
            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;
            UseNearbyPokestopsTask.UpdateTimeStampsPokestop      += SaveTimeStampsPokestopToDisk;
            CatchPokemonTask.UpdateTimeStampsPokemon             += SaveTimeStampsPokemonToDisk;

            ProgressBar.Fill(100);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            QuitEvent.WaitOne();
        }
Example #37
0
 public override void EnterState(StateMachine parent)
 {
     startTime     = Time.fixedTime;
     startPosition = parent.transform.position;
     startPosition = parent.transform.position + Vector3.forward * distance;
 }
 public override void Awake(StateMachine stateMachine)
 {
     _protagonistScript = stateMachine.GetComponent <Protagonist>();
 }
Example #39
0
 public WanderState(StateMachine mothmachine)
 {
     moth = mothmachine;
 }
Example #40
0
 public PlayerDead(StateMachine _stateMachine) : base(_stateMachine)
 {
 }
Example #41
0
        private IStateMachine <State, Message> CreateStateMachine()
        {
            var machine = new StateMachine <State, Message>();

            machine.AddState(State.Began, message =>
            {
                var groupApi      = _serviceProvider.GetService <IGroupApiProvider>().GetGroupApi();
                var randomManager = _serviceProvider.GetService <IRandomDataProvider>();
                var keyboard      = new KeyboardBuilder().AddButton(BackwardText, "", KeyboardButtonColor.Default).Build();
                groupApi.Messages.Send(new MessagesSendParams()
                {
                    Message  = "Отправь мне сообщением свой ник. Его можно будет сменить в любой момент.",
                    PeerId   = message.PeerId,
                    RandomId = randomManager.GetInt(),
                    Keyboard = keyboard
                });
            });
            machine.AddState(State.NickTyped, message =>
            {
                var nick            = message.Text;
                var userId          = message.PeerId ?? 0;
                var groupApi        = _serviceProvider.GetService <IGroupApiProvider>().GetGroupApi();
                var nicknameManager = _serviceProvider.GetService <INicknameManager>();
                var randomManager   = _serviceProvider.GetService <IRandomDataProvider>();
                nicknameManager.SetNickname(userId, nick);
                var keyboard = new KeyboardBuilder().AddButton(BackwardText, "", KeyboardButtonColor.Default).Build();
                groupApi.Messages.Send(new MessagesSendParams()
                {
                    Message  = $"Хорошо {nick}. Теперь это имя будет использоваться в группе",
                    PeerId   = message.PeerId,
                    Keyboard = keyboard,
                    RandomId = randomManager.GetInt()
                });
            });
            machine.AddState(State.WrongNickTyped, message =>
            {
                var groupApi      = _serviceProvider.GetService <IGroupApiProvider>().GetGroupApi();
                var randomManager = _serviceProvider.GetService <IRandomDataProvider>();
                var keyboard      = new KeyboardBuilder().AddButton(BackwardText, "", KeyboardButtonColor.Default).Build();
                groupApi.Messages.Send(new MessagesSendParams()
                {
                    Message  = $"Недопустимый ник!",
                    PeerId   = message.PeerId,
                    Keyboard = keyboard,
                    RandomId = randomManager.GetInt()
                });
            });
            machine.AddTransitCondition(State.Begin, State.Began, message => message.Text == TypeNickTitle);
            machine.AddTransitCondition(State.Began, State.NickTyped, message =>
            {
                var nicknameManager = _serviceProvider.GetService <INicknameManager>();
                return(nicknameManager.IsValid(message.Text));
            });
            machine.AddTransitCondition(State.Began, State.WrongNickTyped, message =>
            {
                var nicknameManager = _serviceProvider.GetService <INicknameManager>();
                return(!nicknameManager.IsValid(message.Text));
            });
            machine.AddTransitCondition(State.WrongNickTyped, State.Began, message => message.Text == BackwardText);

            return(machine);
        }
Example #42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Autoflow.WorkflowEngine{T,TContext}"/> class.
        /// </summary>
        /// <param name="workflowDefinition"></param>
        /// <param name="currentState"></param>
        /// <param name="workflowContext"></param>
        public WorkflowEngine(WorkflowDefinition <T, TContext> workflowDefinition,
                              WorkflowState <T, TContext> currentState,
                              TContext workflowContext)
        {
            Guard.ArgumentIsNotNull(workflowDefinition, nameof(workflowDefinition));

            _onTransitionedEvent = new OnWorkflowTransitionedEvent <T, TContext>();
            _workflowContext     = workflowContext;

            _workflowDefinition = workflowDefinition;
            CurrentState        = currentState ?? workflowDefinition.Transitions.First().FromState;
            _stateMachine       = new StateMachine <WorkflowState <T, TContext>, WorkflowTrigger <T> >(() => CurrentState, s => CurrentState = s);

            //  Get a distinct list of states with a trigger from state configuration
            //  "State => Trigger => TargetState
            var states = workflowDefinition.Transitions.AsQueryable()
                         .Select(x => x.FromState)
                         .Distinct()
                         .Select(x => x)
                         .ToList();

            //  Assign triggers to states
            foreach (var state in states)
            {
                var triggers = workflowDefinition.Transitions.AsQueryable()
                               .Where(config => config.FromState == state)
                               .Select(config => new
                {
                    Trigger        = config.TriggeredBy,
                    TargetState    = config.ToState,
                    GuardCondition = config.GuardCondition,
                    IsReentrant    = config.IsReentry
                })
                               .ToList();

                var stateConfig = _stateMachine.Configure(state);

                foreach (var trig in triggers)
                {
                    if (trig.GuardCondition == null)
                    {
                        if (trig.IsReentrant)
                        {
                            stateConfig.PermitReentry(trig.Trigger);
                        }
                        else
                        {
                            if (trig.Trigger != null)
                            {
                                stateConfig.Permit(trig?.Trigger, trig?.TargetState);
                            }
                        }
                    }
                    else
                    {
                        if (trig.Trigger != null)
                        {
                            stateConfig.PermitIf(trig?.Trigger, trig?.TargetState, ConditionalGuard(trig?.GuardCondition));
                        }
                    }
                }

                //actions
                //var actions = workflowDefinition.States.Where();

                if (state.SuperState != null)
                {
                    stateConfig.SubstateOf(state.SuperState);
                }

                if (state.EntryAction != null)
                {
                    stateConfig.OnEntry(t => ExecuteAction(t, state.EntryAction));
                }

                if (state.ExitAction != null)
                {
                    stateConfig.OnExit(t => ExecuteAction(t, state.ExitAction));
                }
            }
            // Handle exceptions
            _stateMachine.OnUnhandledTrigger(OnUnhandledTrigger);

            // For all the state transitions
            _stateMachine.OnTransitioned(OnTransitionAction);
        }
Example #43
0
 private new void Start()
 {
     base.Start();
     stateMachine = new StateMachine <Sis>(this, startingState, initActionsBatch);
 }
    void Start()
    {
        _rigidbody2D = transform.GetComponent <Rigidbody2D>();

        _stateMachine = PrepareStateMachine();
    }
            public void ThrowsIfArgumentIsNull()
            {
                Action callWithNull = () => StateMachine.Start(null);

                callWithNull.Should().Throw <ArgumentNullException>();
            }
Example #46
0
    private float _maxFallDistance = 4f;     //Used to adjust particle emission intensity

    public override void Awake(StateMachine stateMachine)
    {
        _dustController      = stateMachine.GetComponent <PlayerEffectController>();
        _transform           = stateMachine.transform;
        _characterController = stateMachine.GetComponent <CharacterController>();
    }
Example #47
0
 public override void Awake(StateMachine stateMachine)
 {
     _battler = stateMachine.GetComponent <Battler>();
 }
 public override void Awake(StateMachine stateMachine)
 {
     _characterController = stateMachine.GetComponent <CharacterController>();
 }
Example #49
0
 public static void Reset()
 {
     StateMachine._instance = null;
 }
Example #50
0
 private void Start()
 {
     st = FindObjectOfType <StateMachine>();
 }
Example #51
0
 public EnemyState(StateMachine stateMachine) : base(stateMachine)
 {
 }
 public static Result PerformIfPossible <TStatus, TAction>(this StateMachine <TStatus, TAction> stateMachine, TAction action, Error error)
 {
     return(stateMachine
            .CanPerform(action, error)
            .OnSuccess(() => stateMachine.Fire(action)));
 }
 void CreateSuperSubstatePair(out StateMachine <State, Trigger> .StateRepresentation super, out StateMachine <State, Trigger> .StateRepresentation sub)
 {
     super = CreateRepresentation(State.A);
     sub   = CreateRepresentation(State.B);
     super.AddSubstate(sub);
     sub.Superstate = super;
 }
Example #54
0
 public PlayerStateAttack(Player player)
 {
     _player       = player;
     _stateMachine = player.StateMachine;
     attackNum     = 0;
 }
 public void EnemyWins()
 {
     EnemyTurnEnded?.Invoke();
     StateMachine.ChangeState <EnemyWinCardGameState>();
     Debug.Log("Enemy wins!");
 }
 public override void Awake(StateMachine stateMachine)
 {
     groundCollider = stateMachine.GetComponent <PlayerSensorHandler>().GetGroundCollider();
 }
Example #57
0
 protected override void Initialize()
 {
     DontDestroyOnLoad(this.gameObject);
     stateMachine = new StateMachine <SceneName>();
 }
Example #58
0
 // Use this for initialization
 public GamePlayer(int playerID, GameObject go) : base(playerID)
 {
     m_pStateMachine = new StateMachine <GamePlayer>(this);
 }
Example #59
0
 public override void Awake(StateMachine stateMachine)
 {
     //TODO: Remove this. We don't need to rely on a timer hidden in the attack config of the weapon,
     //since our attacks depend on the lenght of the animation anyway
     _reloadDuration = stateMachine.gameObject.GetComponentInChildren <Attack>(true).AttackConfig.AttackReloadDuration;
 }
Example #60
0
 public override void Awake()
 {
     base.Awake();
     _stateMachine = StateMachine <PlayerStates> .Initialize(this, PlayerStates.Idle);
 }