コード例 #1
0
        public void NotifyUIDepthChanged(AbstractUI ui, StateContext state, int index = -1)
        {
            if (m_uiToNode.TryGetValue(ui, out Node value))
            {
                value.uis.Remove(ui);
                m_uiToNode.Remove(ui);
            }
            else
            {
                ui.canvas.set_worldCamera(m_cameraPrefab);
            }
            Node orCreateNode = GetOrCreateNode(state);

            if (index == -1)
            {
                orCreateNode.uis.Add(ui);
            }
            else
            {
                orCreateNode.uis.Insert(index, ui);
            }
            m_uiToNode.Add(ui, orCreateNode);
            if (ui.get_gameObject().get_activeInHierarchy())
            {
                m_updateOrder = true;
            }
        }
コード例 #2
0
        public void CacheContext(IUpdateContext updateContext)
        {
            var chatId = updateContext.Update.GetChatId();

            if (chatId.HasValue)
            {
                StateContext currentState = _stateCache.GetState(chatId.Value);
                if (updateContext.Update.CallbackQuery != null)
                {
                    string[] parts = updateContext.Update.CallbackQuery.Data.Split("::");

                    if (parts.Length == 0)
                    {
                        throw new ArgumentException("Invalid CallbackQuery state - button must contain data with state id ended with ::");
                    }

                    currentState.ApplyCommand(parts[0]);

                    if (parts.Length > 1)
                    {
                        updateContext.Items.Add("Data", parts[1]);
                    }
                }
                updateContext.Items.Add("History", currentState.HistoryAsList());
                updateContext.Items.Add("State", currentState.TopCommand);
            }
        }
コード例 #3
0
        private IEnumerator StartGame(FightInfo fightInfo)
        {
            StatesUtility.ClearOptionLayer();
            yield return(ApplyFightInfos(fightInfo));

            yield return(m_ui.GotoVersusAnim());

            yield return((object)new WaitForTime(2f));

            StateLayer   defaultLayer = StateManager.GetDefaultLayer();
            StateContext currentState = defaultLayer.GetChildState();

            if (currentState != null)
            {
                defaultLayer.ClearChildState(0);
                while ((int)currentState.get_loadState() == 8)
                {
                    yield return(null);
                }
            }
            FightState fightState = new FightState(fightInfo);

            defaultLayer.SetChildState(fightState, 0);
            VersusState versusState = new VersusState(m_ui, fightState);

            this.SetChildState(versusState, 0);
        }
コード例 #4
0
ファイル: State.cs プロジェクト: sokoide/design-patterns
 public void Do(StateContext ctx, string str)
 {
     if (str == "tick")
     {
         ctx.ChangeState(TitleState.Instance);
     }
 }
コード例 #5
0
ファイル: State.cs プロジェクト: sokoide/design-patterns
 public void Do(StateContext ctx, string str)
 {
     if (str == "monster")
     {
         ctx.ChangeState(GameOverState.Instance);
     }
 }
コード例 #6
0
        private static bool DoSegement(ref StateContext context, int position, Action <string> complete, Action <string> error)
        {
            switch (context.Character)
            {
            case '@':
            case '[':
                context.State = State.Exit;
                complete(context.Accept(1));
                return(true);

            case '/':
            case '\\':
                context.State = State.Slash;
                complete(context.Accept(1));
                return(true);
            }

            if (Validate(context.Character))
            {
                return(true);
            }

            error(GetIllegalCharacterExceptionMessage(context.Character, position));
            return(false);
        }
コード例 #7
0
 private void OnCurrentTargetUnavailable(object sender, EventArgs args)
 {
     if (StateContext.CurrentState == this)
     {
         StateContext.ChangeState(this, targetingState);
     }
 }
コード例 #8
0
ファイル: MainMenuState.cs プロジェクト: AlexMeuer/Rubik
        public MainMenuState(StateContext context, ITinyMessengerHub messengerHub, ILogger logger, IRubiksCubeFactory rubiksCubeFactory)
            : base(context, messengerHub, logger)
        {
            this.rubiksCubeFactory = rubiksCubeFactory;

            screen = new MainMenuScreen(AdvanceToGame, QuitGame);
        }
コード例 #9
0
ファイル: patrolState.cs プロジェクト: Enconemy/StealthGame
 public void HandleInput(E_Input input, StateContext stateCon)
 {
     if (input == E_Input.DetectedPlayer)
     {
         stateCon.CurrentState = EnemyStates.Chase;
     }
 }
コード例 #10
0
 private void AttackDecidedCallback()
 {
     if (StateContext.CurrentState == this)
     {
         StateContext.ChangeState(this, attackingState);
     }
 }
コード例 #11
0
        private ReturnValue ProcessStateStopStartOutput(StateContext context)
        {
            string state = context.Output.SplitAndTrim(Environment.NewLine)
                           .Where(x => x.StartsWith("STATE"))
                           .Select(x => x.EverythingAfterLast(" "))
                           .FirstOrDefault();

            ReturnValue returnValue = ReturnValue.Ok();

            if (context.CommandType == CommandType.Start)
            {
                returnValue = CheckOutputForErrors(context.Output, 1056);
            }
            else if (context.CommandType == CommandType.Stop)
            {
                returnValue = CheckOutputForErrors(context.Output, 1062);
            }
            else if (context.CommandType == CommandType.State && state == null)
            {
                returnValue = ReturnValue.Error(ErrorType.ServiceStateNotFound, "Failed to find the state");
            }

            return(returnValue.IsSuccess
                ? ReturnValue.Ok(state)
                : returnValue);
        }
コード例 #12
0
 public override void Enter()
 {
     base.Enter();
     StateContext.RegisterTickListener(StateContext.CurrentCombatStrategy);
     StateContext.PursueTargetedEnemy();
     StateContext.SelectPerformedAttack();
 }
コード例 #13
0
ファイル: GameHub.cs プロジェクト: destiny159/Typeracer
 public void endGame()
 {
     userCount              = 0;
     characterCount         = 0;
     observer               = new ConcreteSubject();
     givenWord              = "";
     xpRate                 = 1;
     abilityXpRate          = 1;
     lastAbilityUser        = "";
     playerList             = new List <Player>();
     lastWord               = new WordPrototype("empty");
     usedClone              = false;
     target                 = new Adapter();
     pointsColorAbstraction = new PointsColorRefinedAbstraction();
     skinAbstraction        = new SkinAbstraction();
     facade                 = new Facade();
     collection             = new Collection();
     iterator               = collection.CreateIterator();
     firstLevel             = new FirstLevelWord();
     secondLevel            = new SecondLevelWord();
     thirdLevel             = new ThirdLevelWord();
     h1              = new ReverseWordHandler();
     h2              = new FullWordHandler();
     h3              = new PartWordHandler();
     h4              = new LengthWordHandler();
     _stateContext   = new StateContext(new WinterState());
     chatroom        = new Chatroom();
     originator      = new Originator();
     caretaker       = new Caretaker();
     parametersGroup = new ParametersGroup();
 }
コード例 #14
0
ファイル: Server.cs プロジェクト: menohack/GlebForgeServer
        /// <summary>
        /// This method runs the server by continually executing state transitions.
        /// </summary>
        private void Run()
        {
            try
            {
                stream = client.GetStream();
                StateContext context = new StateContext(this);

                while (true)
                {
                    context.Next();
                }
            }
            catch (Exception e)
            {
                //IOExceptions and TimeoutExceptions have the same behavior
                Console.WriteLine(e.Message);
                client.Close();


                Player updatedPlayer = new Player(player);
                updatedPlayer.LoggedIn = false;
                if (player != null && player.LoggedIn)
                {
                    if (!players.TryUpdate(player.Name, updatedPlayer, player))
                    {
                        throw new Exception("F**k you");
                    }
                }

                //if (player != null && player.LoggedIn)
                //	player.LoggedIn = false;
                closeServer(this);
                return;
            }
        }
コード例 #15
0
ファイル: State.cs プロジェクト: sokoide/design-patterns
 public void Do(StateContext ctx, string str)
 {
     if (str == "startbutton")
     {
         ctx.ChangeState(GameState.Instance);
     }
 }
コード例 #16
0
ファイル: Indexes.cs プロジェクト: interess/GGJ2018
 public MenuButtonIdIndex(StateContext context) : base()
 {
     groupToWatch = context.GetGroup(Matcher <StateEntity> .AllOf(StateMatcher.MenuButtonId));
     groupToWatch.OnEntityAdded   += Added;
     groupToWatch.OnEntityUpdated += Updated;
     groupToWatch.OnEntityRemoved += Removed;
 }
コード例 #17
0
ファイル: Indexes.cs プロジェクト: interess/GGJ2018
 public ChannelIndex(StateContext context) : base()
 {
     groupToWatch = context.GetGroup(Matcher <StateEntity> .AllOf(StateMatcher.Channel));
     groupToWatch.OnEntityAdded   += Added;
     groupToWatch.OnEntityUpdated += Updated;
     groupToWatch.OnEntityRemoved += Removed;
 }
コード例 #18
0
    public override void Enter(StateContext context)
    {
        base.Enter(context);
        SetMenuPanel(context.manager.elementsPanel);
        tweener      = pageMap.body.GetComponentInChildren <UITweener>();
        tweenerTrans = tweener.transform;
        tweenerTrans.localPosition = Vector3.zero;
        playset = context.playset;
        var title = pageMap.AddLabel(pageMap.head, context.manager.prefabs.styledLabel);

        title.text        = playset.name;
        title.effectStyle = UILabel.Effect.Outline;
        title.color       = Color.red;
        title.fontSize    = 26;
        var grid = pageMap.body.GetComponentInChildren <UIGrid>();

        grid.cellWidth = Screen.width;
        subPages       = new List <PlaysetElementsSubPage>(grid.GetComponentsInChildren <PlaysetElementsSubPage>());
        while (subPages.Count < 4)
        {
            subPages.Add(
                NGUITools.AddChild(grid.gameObject, context.manager.prefabs.elementsSubPage).GetComponent <PlaysetElementsSubPage>());
        }
        grid.Reposition();
        SetUpButtons();
        SetUpContents();
    }
コード例 #19
0
        private static bool DoString(ref StateContext context, int position)
        {
            if (context.Flags.IsEscaping())
            {
                context.Accept(Escape(context.Character));
                context.Flags.IsEscaping(false);
            }
            else
            {
                if (context.Character == '\\')
                {
                    context.Flags.IsEscaping(true);
                }
                else if (context.Character == context.Flags.GetStringQuote())
                {
                    context.State = State.Parameter;
                    context.AppendParameterConstant(context.Stack.Peek());
                }
                else
                {
                    context.Accept();
                }
            }

            return(true);
        }
コード例 #20
0
        private void OnReturnClick()
        {
            m_ui.returnButton.set_interactable(false);
            StateContext childState = this.GetChildState();

            GotoPreviousState(childState);
        }
コード例 #21
0
 public SoLongAndThanksForAllTheFish(
     StateContext stateContext,
     IQueryHandler <GetYourQuestion, string> getYourQuestionIQueryHandler)
 {
     _stateContext = stateContext;
     _getYourQuestionIQueryHandler = getYourQuestionIQueryHandler;
 }
コード例 #22
0
ファイル: AttackState.cs プロジェクト: Enconemy/StealthGame
 public void HandleInput(E_Input input, StateContext stateCon)
 {
     if (input == E_Input.OutOfRange)
     {
         stateCon.CurrentState = EnemyStates.Chase;
     }
 }
コード例 #23
0
    public override void Enter(StateContext context)
    {
        base.Enter(context);
//		menuPanel = context.manager.logoPanel;
//		menuPanel.SetActive(true);
        context.manager.WaitForIt(1f, new EventDelegate(GoToBrowsePlaysets));
    }
コード例 #24
0
ファイル: CameraController.cs プロジェクト: AlexMeuer/Rubik
        public CameraController(UnityEngine.Camera camera, ITinyMessengerHub messengerHub, ILogger logger, IStore store)
        {
            this.camera       = camera;
            this.messengerHub = messengerHub;
            this.logger       = PrefixedLogger.ForType <CameraController>(logger);

            var transform = camera.transform;

            cameraPivot = transform.parent;

            defaultPosition = transform.position;
            defaultRotation = transform.rotation.eulerAngles;

            context = new StateContext(this.logger, store);

            context.TransitionTo(
                new WaitingForDragState(context,
                                        messengerHub,
                                        this.logger,
                                        camera));

            context.Disable();

            spinSubscriptionToken = messengerHub.Subscribe <SpinCamera360Message>(OnSpinRequested);

            enableDisableSubscriptionToken = messengerHub.Subscribe <EnableCameraControlMessage>(EnableControl);

            resetPositionSubscriptionToken = messengerHub.Subscribe <ResetCameraMessage>(Reset);

            orbitSubscriptionToken = messengerHub.Subscribe <CameraOrbitRequestMessage>(Orbit);
        }
コード例 #25
0
        static void StateTester()
        {
            #region sample 1
            // Setup context in a state
            var c = new StateContext(new ConcreteStateA());

            // Issue requests, which toggles state
            c.Request();
            c.Request();
            c.Request();
            c.Request();
            #endregion

            #region sample 2
            // Open a new account
            var account = new Account("Jim Johnson");

            // Apply financial transactions
            account.Deposit(500.0);
            account.Deposit(300.0);
            account.Deposit(550.0);
            account.PayInterest();
            account.Withdraw(2000.00);
            account.Withdraw(1100.00);
            #endregion
        }
コード例 #26
0
        public static TransitionState DoTransition([NotNull] StateContext nextState, [CanBeNull] StateContext previousState, [CanBeNull] StateContext parentState = null)
        {
            TransitionState transitionState = new TransitionState(nextState, previousState);

            (parentState ?? ((object)((previousState != null) ? previousState.get_parent() : null)) ?? ((object)StateManager.GetDefaultLayer())).SetChildState(transitionState, 0);
            return(transitionState);
        }
コード例 #27
0
ファイル: OptionsState.cs プロジェクト: binaryfs/SharpSnake
        public OptionsState(StateContext context) : base(context)
        {
            InputMap.AddMapping(Terminal.TK_UP, ActionType.MoveUp);
            InputMap.AddMapping(Terminal.TK_DOWN, ActionType.MoveDown);
            InputMap.AddMapping(Terminal.TK_LEFT, ActionType.MoveLeft);
            InputMap.AddMapping(Terminal.TK_RIGHT, ActionType.MoveRight);
            InputMap.AddMapping(Terminal.TK_ENTER, ActionType.Activate);

            var speedPicker = new Picker <GameSpeed>("Speed", HandleChangeSpeed);

            speedPicker.AddOption("Slow", GameSpeed.Slow);
            speedPicker.AddOption("Medium", GameSpeed.Medium);
            speedPicker.AddOption("Fast", GameSpeed.Fast);
            speedPicker.SelectOption(Context.Settings.Speed);

            var themePicker = new Picker <PaletteId>("Palette", HandleChangeTheme);

            themePicker.AddOption("Default", PaletteId.Default);
            themePicker.AddOption("Monochrome", PaletteId.Monochrome);
            themePicker.SelectOption(Context.Settings.PaletteId);

            Menu = new Menu();
            Menu.AddItem(themePicker);
            Menu.AddItem(speedPicker);
            Menu.AddItem(new Button("Return", () => RequestPopState()));
        }
コード例 #28
0
        private static bool DoNone(ref StateContext context)
        {
            if (context.IsWhitespace())
            {
                return(true);
            }

            switch (context.Character)
            {
            case '*':
                context.State = State.Asterisk;
                return(true);

            case '!':
                context.State = State.Exclude;
                return(true);

            case '}':
                return(context.Pop() != null);

            case ',':
                return(true);

            default:
                if (context.IsLetterOrUnderscore())
                {
                    context.Accept();
                    context.State = State.Include;
                    return(true);
                }

                context.OnError($"SyntaxError: Contains the illegal character '{context.Character}' in the data schema.");
                return(false);
            }
        }
コード例 #29
0
        private static bool DoAsterisk(ref StateContext context)
        {
            if (context.IsWhitespace())
            {
                return(true);
            }

            switch (context.Character)
            {
            case ',':
                context.Include("*");
                context.State = State.None;
                return(true);

            case '}':
                context.Include("*");
                context.Pop();
                context.State = State.None;
                return(true);

            default:
                context.OnError($"SyntaxError: Contains the illegal character '{context.Character}' in the data schema.");
                return(false);
            }
        }
コード例 #30
0
        private static bool DoGutter(ref StateContext context, int position)
        {
            switch (context.Character)
            {
            case '.':
                context.State = State.Separator;
                return(true);

            case '[':
                context.State = State.Indexer;

                //追加索引器表达式,并将索引器加入到递归栈中
                context.AppendIndexer();

                return(true);

            default:
                if (context.IsWhitespace())
                {
                    return(true);
                }

                context.OnError(GetIllegalCharacterExceptionMessage(context.Character, position));
                return(false);
            }
        }
コード例 #31
0
ファイル: StatePattern.cs プロジェクト: david--liu/code_kata
 public int MoveDown(StateContext stateContext)
 {
     if (stateContext.Counter < StateContext.limit)
     {
         stateContext.State = new NormalState();
         Console.Write("||");
     }
     stateContext.Counter -= 5;
     return stateContext.Counter;
 }
コード例 #32
0
ファイル: StatePattern.cs プロジェクト: david--liu/code_kata
 public void Main()
 {
     var stateContext = new StateContext();
     stateContext.State = new NormalState();
     var r = new Random(37);
     for (var i = 5; i <= 25; i++)
     {
         var command = r.Next(3);
         Console.Write(stateContext.Request(command) + " ");
     }
     Console.WriteLine();
 }
コード例 #33
0
ファイル: SelectFigureState.cs プロジェクト: ABAmvrosov/Tess
 protected override void ChangeState(StateContext context) {
     switch (context.stateMark) {
         case StateMark.Figure:
             Figure figure = (Figure) context.contextObject;
             if (figure.CanMove) {
                 GameManager.TheFigureManager.SelectedFigure = figure;
                 GameManager.TheBoardController.HighlightPossibleMoves(figure);
                 GameManager.GM.GameState = new MoveFigureState();
                 StateChanged();
             }
             break;
     }
 }
コード例 #34
0
ファイル: ChooseCardState.cs プロジェクト: ABAmvrosov/Tess
 protected override void ChangeState(StateContext context) {
     switch (context.stateMark) {
         case StateMark.MoveCard: 
             GameManager.TheFigureManager.ActivateFigures();
             GameManager.GM.GameState = new SelectFigureState();
             StateChanged();
             break;
         case StateMark.GroundCard:
             GameManager.GM.GameState = new PlaceGroundState();
             StateChanged();
             break;
     }
 }
コード例 #35
0
ファイル: MoveFigureState.cs プロジェクト: ABAmvrosov/Tess
 protected override void ChangeState(StateContext context) {
     switch (context.stateMark) {
         case StateMark.Figure:
             Figure figure = (Figure) context.contextObject;
             Tile destTile = GameManager.TheBoardController.GetTile(figure.Coordinates);
             if (!figure.IsEnemy()) {
                 break;
             }
             GameManager.TheFigureManager.Move(destTile);
             DetermineNextState();
             break;
         case StateMark.Tile:
             Tile destination = (Tile) context.contextObject;
             if (destination.PossibleMove) {
                 GameManager.TheFigureManager.Move(destination);
                 DetermineNextState();
             }
             break;
     }
 }
コード例 #36
0
ファイル: StateMachine.cs プロジェクト: hahmed/HangFire
        public string CreateInState(
            Job job,
            IDictionary<string, string> parameters,
            State state)
        {
            if (job == null) throw new ArgumentNullException("job");
            if (parameters == null) throw new ArgumentNullException("parameters");
            if (state == null) throw new ArgumentNullException("state");

            var invocationData = job.MethodData.Serialize();

            var jobId = _connection.CreateExpiredJob(
                invocationData, 
                job.Arguments.ToArray(),
                parameters,
                TimeSpan.FromHours(1));

            var context = new StateContext(jobId, job.MethodData);
            ChangeState(context, state, null);

            return jobId;
        }
コード例 #37
0
ファイル: State.cs プロジェクト: ABAmvrosov/Tess
 protected abstract void ChangeState (StateContext context);
コード例 #38
0
ファイル: StateMachine.cs プロジェクト: hahmed/HangFire
        public bool TryToChangeState(
            string jobId, State toState, string[] fromStates)
        {
            if (jobId == null) throw new ArgumentNullException("jobId");
            if (toState == null) throw new ArgumentNullException("toState");
            if (fromStates == null) throw new ArgumentNullException("fromStates");

            // To ensure that job state will be changed only from one of the
            // specified states, we need to ensure that other users/workers
            // are not able to change the state of the job during the
            // execution of this method. To guarantee this behavior, we are
            // using distributed application locks and rely on fact, that
            // any state transitions will be made only within a such lock.
            using (_connection.AcquireJobLock(jobId))
            {
                var jobData = _connection.GetJobStateAndInvocationData(jobId);

                if (jobData == null)
                {
                    // The job does not exist. This may happen, because not
                    // all storage backends support foreign keys. 
                    return false;
                }

                if (!fromStates.Contains(jobData.State, StringComparer.OrdinalIgnoreCase))
                {
                    return false;
                }

                MethodData methodData = null;
                bool loadSucceeded = true;

                try
                {
                    methodData = MethodData.Deserialize(jobData.InvocationData);
                }
                catch (JobLoadException ex)
                {
                    // If the job type could not be loaded, we are unable to
                    // load corresponding filters, unable to process the job
                    // and sometimes unable to change its state (the enqueued
                    // state depends on the type of a job).

                    toState = new FailedState(ex)
                    {
                        Reason = String.Format(
                            "Could not change the state of the job '{0}' to the '{1}'. See the inner exception for details.",
                            toState.Name, jobId)
                    };

                    loadSucceeded = false;
                }

                var context = new StateContext(jobId, methodData);
                var stateChanged = ChangeState(context, toState, jobData.State);

                return loadSucceeded && stateChanged;
            }
        }
コード例 #39
0
ファイル: StateMachine.cs プロジェクト: hahmed/HangFire
        internal virtual void ApplyState(
            StateContext stateContext, 
            State electedState,
            string oldStateName,
            IEnumerable<IApplyStateFilter> filters)
        {
            var context = new ApplyStateContext(
                _connection, stateContext, electedState, oldStateName);

            context.ApplyState(GetHandlers(), filters);
        }
コード例 #40
0
ファイル: StateMachine.cs プロジェクト: hahmed/HangFire
        internal virtual State ElectState(
            StateContext stateContext, 
            State toState,
            string fromStateName,
            IEnumerable<IElectStateFilter> filters)
        {
            var context = new ElectStateContext(
                stateContext, toState, fromStateName, _connection);

            return context.ElectState(filters);
        }
コード例 #41
0
 public DragAndDropMessageState(SpriteFont font, StateContext context)
     : base(font, context)
 {
     _font = font;
 }
コード例 #42
0
ファイル: StateMachineFacts.cs プロジェクト: hahmed/HangFire
        public void ChangeState_AppliesState_AndReturnsTrue()
        {
            var stateMachine = CreateStateMachineMock();
            var context = new StateContext("1", MethodData.FromExpression(() => Console.WriteLine()));
            
            var result = stateMachine.Object.ChangeState(
                context, _state.Object, OldStateName);

            stateMachine.Verify(x => x.ApplyState(
                context, _state.Object, OldStateName, It.IsNotNull<IEnumerable<IApplyStateFilter>>()));
            Assert.True(result);
        }
コード例 #43
0
ファイル: StateMachineFacts.cs プロジェクト: hahmed/HangFire
        public void ChangeState_AppliesOnlyElectedState()
        {
            var stateMachine = CreateStateMachineMock();
            var context = new StateContext("1", MethodData.FromExpression(() => Console.WriteLine()));
            var electedState = new Mock<State>();

            stateMachine
                .Setup(x => x.ElectState(
                    context, _state.Object, OldStateName, It.IsNotNull<IEnumerable<IElectStateFilter>>()))
                .Returns(electedState.Object);

            stateMachine.Object.ChangeState(context, _state.Object, OldStateName);

            stateMachine.Verify(x => x.ApplyState(
                context, electedState.Object, OldStateName, It.IsAny<IEnumerable<IApplyStateFilter>>()));
        }
コード例 #44
0
ファイル: Tile.cs プロジェクト: ABAmvrosov/Tess
	void OnMouseDown () {
        StateContext context = new StateContext(this, StateMark.Tile);
        GameManager.GM.HandleActionByState(context);			
	}
コード例 #45
0
ファイル: StateMachineFacts.cs プロジェクト: hahmed/HangFire
        public void ChangeState_AppliesFailedState_WhenThereIsAnException()
        {
            var stateMachine = CreateStateMachineMock();
            var context = new StateContext("1", MethodData.FromExpression(() => Console.WriteLine()));
            var exception = new NotSupportedException();

            stateMachine.Setup(x => x.ApplyState(
                context, _state.Object, OldStateName, It.IsAny<IEnumerable<IApplyStateFilter>>()))
                .Throws(exception);

            var result = stateMachine.Object.ChangeState(
                context, _state.Object, OldStateName);

            stateMachine.Verify(x => x.ApplyState(
                context, 
                It.Is<FailedState>(s => s.Exception == exception), 
                OldStateName,
                It.Is<IEnumerable<IApplyStateFilter>>(f => !f.Any())));
            Assert.False(result);
        }
コード例 #46
0
ファイル: StateMachineFacts.cs プロジェクト: hahmed/HangFire
        public void ApplyState_RunsAllHandlers()
        {
            // Arrange
            var handler1 = new Mock<StateHandler>();
            handler1.Setup(x => x.StateName).Returns(StateName);

            var handler2 = new Mock<StateHandler>();
            handler2.Setup(x => x.StateName).Returns(StateName);

            _handlers.Add(handler1.Object);
            _handlers.Add(handler2.Object);

            var stateMachine = CreateStateMachine();
            var context = new StateContext("1", MethodData.FromExpression(() => Console.WriteLine()));

            // Act
            stateMachine.ApplyState(
                context, _state.Object, OldStateName, Enumerable.Empty<IApplyStateFilter>());

            // Assert
            handler1.Verify(x => x.Apply(
                It.Is<ApplyStateContext>(c => 
                    c.JobId == context.JobId 
                    && c.MethodData == context.MethodData 
                    && c.NewState == _state.Object 
                    && c.OldStateName == OldStateName),
                It.IsAny<IWriteOnlyTransaction>()));
        }
コード例 #47
0
ファイル: GameManager.cs プロジェクト: ABAmvrosov/Tess
 public void HandleActionByState(StateContext context) {
     GameState.HandleAction(context);
 }
コード例 #48
0
ファイル: State.cs プロジェクト: ABAmvrosov/Tess
 public virtual void HandleAction(StateContext context) {
     ChangeState(context);
     Messenger.Broadcast("StateChanged");
 }
コード例 #49
0
ファイル: StatePattern.cs プロジェクト: david--liu/code_kata
 public int MoveUp(StateContext stateContext)
 {
     stateContext.Counter += 5;
     return stateContext.Counter;
 }
コード例 #50
0
ファイル: StateMachine.cs プロジェクト: hahmed/HangFire
        internal virtual bool ChangeState(StateContext context, State toState, string oldStateName)
        {
            try
            {
                var filterInfo = GetFilters(context.MethodData);

                var electedState = ElectState(context, toState, oldStateName, filterInfo.ElectStateFilters);
                ApplyState(context, electedState, oldStateName, filterInfo.ApplyStateFilters);

                // State transition was succeeded.
                return true;
            }
            catch (Exception ex)
            {
                var failedState = new FailedState(ex)
                {
                    Reason = "An exception occurred during the transition of job's state"
                };

                // We should not use any state changed filters, because
                // some of the could cause an exception.
                ApplyState(context, failedState, oldStateName, Enumerable.Empty<IApplyStateFilter>());

                // State transition was failed due to exception.
                return false;
            }
        }
コード例 #51
0
ファイル: GroundCard.cs プロジェクト: ABAmvrosov/Tess
 protected override void ActivateCard() {
     StateContext contex = new StateContext(this, StateMark.GroundCard);
     GameManager.GM.HandleActionByState(contex);
 } 
コード例 #52
0
        public void HandlingExitActionException()
        {
            const string StateMachineName = "test machine";
            const States CurrentStateId = States.A;
            var stateMachineInformationMock = this.CreateStateMachineInformation(StateMachineName, CurrentStateId);
            var stateMock = this.CreateStateMock(CurrentStateId);
            var stateContext = new StateContext<States, Events>();
            var exception = new Exception("test exception");

            this.testee.HandlingExitActionException(stateMachineInformationMock.Object, stateMock.Object, stateContext, ref exception);

            this.log4Net.LogContains(
                Level.Error,
                "Exception in exit action of state A of state machine test machine: System.Exception: test exception");
        }
コード例 #53
0
ファイル: Server.cs プロジェクト: menohack/GlebForgeServer
        /// <summary>
        /// This method runs the server by continually executing state transitions.
        /// </summary>
        private void Run()
        {
            try
            {
                stream = client.GetStream();
                StateContext context = new StateContext(this);

                while (true)
                    context.Next();
            }
            catch (Exception e)
            {
                //IOExceptions and TimeoutExceptions have the same behavior
                Console.WriteLine(e.Message);
                client.Close();

                Player updatedPlayer = new Player(player);
                updatedPlayer.LoggedIn = false;
                if (player != null && player.LoggedIn)
                    if (!players.TryUpdate(player.Name, updatedPlayer, player))
                        throw new Exception("F**k you");

                //if (player != null && player.LoggedIn)
                //	player.LoggedIn = false;
                closeServer(this);
                return;
            }
        }
コード例 #54
0
ファイル: MessageState.cs プロジェクト: tuannsofta/kinect4bag
 public MessageState(SpriteFont font, StateContext context)
     : base(context)
 {
     _font = font;
 }
コード例 #55
0
 public LoadingMessageState(SpriteFont font, StateContext context)
     : base(font, context)
 {
     _font = font;
 }
コード例 #56
0
ファイル: CheckState.cs プロジェクト: DreamAmazon/DreamAmazon
 protected CheckState(StateContext context)
 {
     Context = context;
 }