Esempio n. 1
0
        public SessionInfo(Session oS)
        {
            if (oS.PathAndQuery.StartsWith("/state/", StringComparison.OrdinalIgnoreCase))
            {
                Type = SessionType.State;
                string[] pathSegments = oS.PathAndQuery.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                UserId = pathSegments[1];
                TapeId = pathSegments[2];
                StateAction = (StateAction) Enum.Parse(typeof(StateAction), pathSegments[3],true);
                return;
            }
            if (oS.PathAndQuery.StartsWith("/record/", StringComparison.OrdinalIgnoreCase))
            {
                Type = SessionType.Record;
            }
            if (oS.PathAndQuery.StartsWith("/play/", StringComparison.OrdinalIgnoreCase))
            {
                Type = SessionType.Playback;
            }
      
            if (oS.PathAndQuery.StartsWith("/export/", StringComparison.OrdinalIgnoreCase))
            {
                Type = SessionType.Export;
                string[] pathSegments = oS.PathAndQuery.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                UserId = pathSegments[1];
                TapeId = pathSegments[2];
                       
                return;
            }

            if (Type != SessionType.None)
            {
                string path = oS.PathAndQuery;

                switch (path)
                {
                    //#TODO: remove this
                    case "/blank.html":
                        //do nothing
                        break;
                    default:
                        string[] pathSegments = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                        UserId = pathSegments[1];
                        TapeId = pathSegments[2];
                        Host = pathSegments[3];
                        PathAndQuery = "/" + string.Join("/", pathSegments, 4, pathSegments.Length - 4);
                        break;
                }
            }
        }
Esempio n. 2
0
        /*public void addAction(string evt, StateAction action){
            if (!actionMap_.ContainsKey (evt)) {
                actionMap_.Add (evt, action);
            } else {

            }
        }*/
        public void addAction(string evt, StateAction action)
        {
            if (!actionMap_.ContainsKey (evt)) {
                actionMap_.Add (evt, action);
            } else {
                StateAction old = actionMap_[evt];
                actionMap_[evt] = delegate(FSMEvent e) {
                    string ret = null;
                    ret = old(e);
                    if(!string.IsNullOrEmpty(ret)){
                        return ret;
                    }
                    return action(e);

                };
            }
        }
		public ServerSideConnection(ITransport<StompFrame> transport, ServerData serverData)
		{
			_connectionNumber = Interlocked.Increment(ref _connectionCount);
			_logMessagePrefix = "#" + _connectionNumber + ": ";
			_transport = Verify.ArgumentNotNull(transport, "transport");
			_serverData = Verify.ArgumentNotNull(serverData, "serverData");
			_transport.ConnectedChanged += TransportConnectedChanged;
			_transport.FrameReady += TransportFrameReady;
			_transport.TransportException += TransportTransportException;
			_stateAction = ExpectingConnect;
			_incomingHeartBeatTimer = new Timer(HandleIncomingHeartBeatTimeout);
			_outgoingHeartBeatTimer = new Timer(HandleOutgoingHeartBeatTimeout);
			_connectTimer = new Timer(HandleConnectTimeout, null,
			                          (int) serverData.Config.ConnectFrameTimeout.TotalMilliseconds,
			                          Timeout.Infinite);
			Log.Debug(_logMessagePrefix + "Connect established");
		}
Esempio n. 4
0
        public void movePlayer(BufferedGraphics buffer, Bitmap bm)
        {
            switch (action)
            {
            //Đi xuống
            case StateAction.Down:
                indexrow = 0;
                if (indexcomlumn >= 0 && indexcomlumn < 3)
                {
                    indexcomlumn++;
                }
                else
                {
                    indexcomlumn = 0;
                    dx           = 0;
                    dy           = 10;
                    direction    = StateAction.Down;
                }
                break;

            //đi trái
            case StateAction.Left:
                indexrow = 1;
                if (indexcomlumn >= 0 && indexcomlumn < 3)
                {
                    indexcomlumn++;
                }
                else
                {
                    indexcomlumn = 0;
                    dx           = -10;
                    dy           = 0;
                    direction    = StateAction.Left;
                }
                break;

            //Đi phải
            case StateAction.Right:
                indexrow = 2;
                if (indexcomlumn >= 0 && indexcomlumn < 3)
                {
                    indexcomlumn++;
                }
                else
                {
                    indexcomlumn = 0;
                    dx           = 10;
                    dy           = 0;
                    direction    = StateAction.Right;
                }
                break;

            //Đi lên
            case StateAction.Up:
                indexrow = 3;
                if (indexcomlumn >= 0 && indexcomlumn < 3)
                {
                    indexcomlumn++;
                }
                else
                {
                    indexcomlumn = 0;
                    dx           = 0;
                    dy           = -10;
                    direction    = StateAction.Up;
                }
                break;

            case StateAction.Standing:
                dx = 0;
                dy = 0;
                switch (direction)
                {
                case StateAction.Down:
                    indexcomlumn = 0;
                    indexrow     = 0;
                    break;

                case StateAction.Left:
                    indexcomlumn = 0;
                    indexrow     = 1;
                    break;

                case StateAction.Right:
                    indexcomlumn = 0;
                    indexrow     = 2;
                    break;

                case StateAction.Up:
                    indexcomlumn = 0;
                    indexrow     = 3;
                    break;

                default:
                    break;
                }
                break;
            }
            drawPlayer(buffer, bm);
        }
Esempio n. 5
0
 public StateTransition(int nextState, BitValidator <T> validator, StateAction <T> action)
 {
     this.NextState = nextState;
     this.Validator = validator;
     this.Action    = action;
 }
Esempio n. 6
0
 public void SetEffect(StateAction action)
 {
     m_Effect       = CreateSummaryEffect(action);
     m_TimeToFinish = action.GetDurationInSeconds();
 }
		// ReSharper restore UnusedParameter.Local
		// ReSharper restore MemberCanBeMadeStatic.Local

		private void ExpectingConnect(StompFrame frame)
		{
			if (frame.Command != StompCommand.Connect
				&& frame.Command != StompCommand.Stomp)
			{
				string message = "Expecting " + StompCommand.Connected 
					+ " or " + StompCommand.Stomp
					+ " command, received " + frame.Command;
				Log.Error(_logMessagePrefix + message);
				var errorFrame = StompFrameUtils.CreateErrorFrame(message);
				_transport.SendFrame(errorFrame);
				DisconnectWithoutLocking();
				return;
			}

			var login = frame.Headers[StompHeader.Login];
			var passcode = frame.Headers[StompHeader.Passcode];

			if (!Authenticate(login, passcode))
			{
				string message = "Received " + frame.Command + " frame, Access denied";
				Log.Warn(_logMessagePrefix + message);
				var errorFrame = StompFrameUtils.CreateErrorFrame(message);
				_transport.SendFrame(errorFrame);
				DisconnectWithoutLocking();
				return;
			}

			Log.Debug(_logMessagePrefix + "Received " + frame.Command + " frame, authenticated OK");

			var sessionId = frame.Headers[StompHeader.Session];
			ServerSideSession session = null;

			if (sessionId != null)
			{
				session = _serverData.FindSession(sessionId);
				if (session == null)
				{
					Log.Warn(_logMessagePrefix + "Received " + frame.Command + " frame for non-existent session: " + sessionId);
					var message = ErrorMessages.SessionDoesNotExistPrefix + sessionId;
					var errorFrame = StompFrameUtils.CreateErrorFrame(message);
					_transport.SendFrame(errorFrame);
					DisconnectWithoutLocking();
					return;
				}

				if (!session.AddConnection(this))
				{
					var message = frame.Command + " frame requested a session already in use: " + sessionId;
					Log.Warn(_logMessagePrefix + message);
					var errorFrame = StompFrameUtils.CreateErrorFrame(message);
					_transport.SendFrame(errorFrame);
					DisconnectWithoutLocking();
					return;
				}

				Log.Debug(_logMessagePrefix + "Reconnected to session " + sessionId);
			}

			if (session == null)
			{
				session = _serverData.CreateSession();
				session.AddConnection(this);
				Log.Debug(_logMessagePrefix + "Created new session " + session.SessionId);
			}

			// helps with debugging if we give the session a more friendly name
			session.ClientId = frame.Headers[StompHeader.NonStandard.ClientId]; 
			_session = session;

			var connectedFrame = new StompFrame
			                     	{
			                     		Command = StompCommand.Connected,
			                     		Headers =
			                     			{
			                     				{StompHeader.Session, session.SessionId}
			                     			}
			                     	};

			if (frame.Headers[StompHeader.HeartBeat] == null)
			{
				// no heart-beat header received, so we default to 0,0
				_negotiatedHeartBeats = new HeartBeatValues(0, 0);
			}
			else
			{
				var otherHeartBeatValues = new HeartBeatValues(frame.Headers[StompHeader.HeartBeat]);
				var myHeartBeatValues = new HeartBeatValues(30000, 30000);
				_negotiatedHeartBeats = myHeartBeatValues.CombineWith(otherHeartBeatValues);
				connectedFrame.Headers[StompHeader.HeartBeat] = _negotiatedHeartBeats.ToString();
			}
			_transport.SendFrame(connectedFrame);
			StopConnectTimer();
			StartIncomingHeartBeatTimer();
			StartOutgoingHeartBeatTimer();
			_stateAction = Connected;
			Log.Debug(_logMessagePrefix + "Session " + session + " connected");
		}
Esempio n. 8
0
 /// <summary>
 /// This function requests or changes the AutoDJ functionality's state.
 /// </summary>
 /// <param name="action">
 /// The action can be either toggle or state.
 /// </param>
 public void RequestAutoDjState(StateAction action)
 {
     if (action == StateAction.Toggle)
     {
         if (!mbApiInterface.Player_GetAutoDjEnabled())
         {
             mbApiInterface.Player_StartAutoDj();
         }
         else
         {
             mbApiInterface.Player_EndAutoDj();
         }
     }
     EventBus.FireEvent(
         new MessageEvent(EventType.ReplyAvailable,
             new SocketMessage(Constants.PlayerAutoDj, Constants.Reply,
                 mbApiInterface.Player_GetAutoDjEnabled()).toJsonString()));
 }
Esempio n. 9
0
        private ActionValidationResult ValidateAction(StateAction stateAction)
        {
            InvalidContentActionReason reason;

            return(ValidateAction(stateAction, out reason));
        }
Esempio n. 10
0
 public State(T name, StateAction action)
 {
     stateName = name;
     Action    = action;
 }
Esempio n. 11
0
        private bool HasPermission(StateAction stateAction)
        {
            if (this.Node.Id == 0)
            {
                //for new content, creator needs to have AddNew permission for the parent
                if (!this.Node.Parent.Security.HasPermission(PermissionType.AddNew))
                    return false;

                //if this is a list type, the user must have a manage container permission for the parent
                if (!CheckManageListPermission(this.Node.NodeType, this.Node.Parent))
                    return false;
            }
            else
            {
                //otherwise the user needs to have Save permission for every action
                if (!this.Node.Security.HasPermission(PermissionType.Save))
                    return false;

                //if this is a list type, the user must have a manage container permission for the node
                if (!CheckManageListPermission(this.Node.NodeType, this.Node))
                    return false;
            }

            switch (stateAction)
            {
                case StateAction.Save:
                case StateAction.CheckOut:
                case StateAction.SaveAndCheckIn:
                case StateAction.CheckIn:
                    return !IsCheckedOutByAnotherUser(this.Node);

                case StateAction.UndoCheckOut:
                    //force and 'normal' undo operations
                    return !IsCheckedOutByAnotherUser(this.Node) ||
                        HasForceUndoCheckOutRight(this.Node);

                case StateAction.Publish:
                    return this.Node.Security.HasPermission(User.Current, PermissionType.Publish) && 
                        !IsCheckedOutByAnotherUser(this.Node);

                case StateAction.Approve:
                case StateAction.Reject:
                    return this.Node.Security.HasPermission(User.Current, PermissionType.Approve); 

                default:
                    throw new NotImplementedException("Unknown StateAction: " + stateAction);
            }
        }
Esempio n. 12
0
        private ActionValidationResult ValidateAction(StateAction stateAction)
        {
            if (!HasPermission(stateAction))
                return ActionValidationResult.Invalid;

            if (this.Node.Id == 0)
            {
                if (stateAction == StateAction.Save || stateAction == StateAction.SaveAndCheckIn)
                    return ActionValidationResult.Valid;
                return ActionValidationResult.InvalidOnNewNode;
            }

            var action = 0;
            switch (stateAction)
            {
                case StateAction.Save: action = 0; break;
                case StateAction.CheckOut: action = 1; break;
                case StateAction.CheckIn: action = 2; break;
                case StateAction.UndoCheckOut: action = 3; break;
                case StateAction.Publish: action = 4; break;
                case StateAction.Approve: action = 5; break;
                case StateAction.Reject: action = 6; break;
                case StateAction.SaveAndCheckIn: action = 7; break;
                default:
                    throw new NotImplementedException("Unknown StateAction: " + stateAction);
            }

            var status = 0;
            var versionStatus = this.Node.Locked ? VersionStatus.Locked : this.CurrentVersion.Status;

            switch (versionStatus)
            {
                case VersionStatus.Approved: status = 0; break;
                case VersionStatus.Locked: status = 1; break;
                case VersionStatus.Draft: status = 2; break;
                case VersionStatus.Rejected: status = 3; break;
                case VersionStatus.Pending: status = 4; break;
                default:
                    throw new NotImplementedException("Unknown VersionStatus: " + this.CurrentVersion.Status);
            }

            var mode = 0;
            switch (this.VersioningMode)
            {
                case VersioningMode.None: mode = 0; break;
                case VersioningMode.Major: mode = 1; break;
                case VersioningMode.Full: mode = 2; break;
                default:
                    throw new NotImplementedException("Unknown VersioningMode: " + this.VersioningMode);
            }
            var approving = this.HasApproving ? 1 : 0;

            if (!EnabledActions[15 * approving + 5 * mode + status][action])
                return ActionValidationResult.Invalid;
            return ActionValidationResult.Valid;
        }
Esempio n. 13
0
 private void AssertValidAction(StateAction stateAction)
 {
     var result = ValidateAction(stateAction);
     if (result == ActionValidationResult.Invalid)
         throw new InvalidContentActionException(String.Concat(
             "Cannot execute the content action. Approving:", this.HasApproving,
             ", versioning mode:", this.VersioningMode,
             ", status:", this.CurrentVersion.Status,
             ", requested action:", stateAction,
             ", content id:", this.Node.Id,
             ", path:", this.Node.Path, "."));
     if (result == ActionValidationResult.InvalidOnNewNode)
         throw new InvalidContentActionException(String.Concat(
                "Cannot execute the content action. The content is new. Requested action :", stateAction, ", path: ", this.Node.Path, "."));
 }
Esempio n. 14
0
 public State(StateAction _enterHandler, StateAction _updateHandler, StateAction _exitHandler)
 {
     enterHandler  = _enterHandler;
     updateHandler = _updateHandler;
     exitHandler   = _exitHandler;
 }
		private void DisconnectWithoutLocking()
		{
			if (_stateAction == ShuttingDown)
			{
				Log.Warn(_logMessagePrefix + "Ignoring duplicate Disconnect request");
			}
			else
			{
				_transport.Shutdown();
				_stateAction = ShuttingDown;
				StopAllTimers();
			}
		}
Esempio n. 16
0
        public void ReduceTest()
        {
            var reducer = new PagePushReducer();
            var state   = new State();

            state.SetValue <PageStack>(PageConst.StateStackKey, new PageStack());
            state.SetValue <PageDefinition>(PageConst.StateDefinitionKey, new PageDefinition
            {
                PermanentScenes = new[] { "PermanentScene1" },
                PageScenes      = new[]
                {
                    new PageScene
                    {
                        Name   = "Page1",
                        Scenes = new[]
                        {
                            "Scene1",
                            "Scene2"
                        },
                    },
                    new PageScene
                    {
                        Name   = "Page2",
                        Scenes = new[]
                        {
                            "Scene1",
                            "Scene3"
                        },
                    }
                }
            });
            state.SetValue <IDictionary <string, bool> >(SceneConst.StateKey, new Dictionary <string, bool>()
            {
                { "Scene1", true },
                { "Scene2", false },
                { "Scene3", false },
                { "Scene4", true },
                { "PermanentScene1", true },
            });
            state.SetValue <PageStack>(PageConst.StateStackKey, new PageStack());

            {
                var page = new Page {
                    Name = "Page1", Data = null
                };
                var action = new StateAction(reducer, "page", new Any(page));
                state = reducer.Reduce(state, action);

                var stack = state.GetValue <PageStack>(PageConst.StateStackKey);
                Assert.That(stack.Count, Is.EqualTo(1));
                Assert.That(stack.Peek().Name, Is.EqualTo("Page1"));

                var sceneMap = state.GetValue <IDictionary <string, bool> >(SceneConst.StateKey);
                Assert.That(sceneMap.Count, Is.EqualTo(5));
                Assert.That(sceneMap["Scene1"], Is.True);
                Assert.That(sceneMap["Scene2"], Is.True);
                Assert.That(sceneMap["Scene3"], Is.False);
                Assert.That(sceneMap["Scene4"], Is.False);
                Assert.That(sceneMap["PermanentScene1"], Is.True);
            }

            {
                var page = new Page {
                    Name = "Page2", Data = null
                };
                var action = new StateAction(reducer, "page", new Any(page));
                state = reducer.Reduce(state, action);

                var stack = state.GetValue <PageStack>(PageConst.StateStackKey);
                Assert.That(stack.Count, Is.EqualTo(2));
                Assert.That(stack.Peek().Name, Is.EqualTo("Page2"));

                var sceneMap = state.GetValue <IDictionary <string, bool> >(SceneConst.StateKey);
                Assert.That(sceneMap.Count, Is.EqualTo(5));
                Assert.That(sceneMap["Scene1"], Is.True);
                Assert.That(sceneMap["Scene2"], Is.False);
                Assert.That(sceneMap["Scene3"], Is.True);
                Assert.That(sceneMap["Scene4"], Is.False);
                Assert.That(sceneMap["PermanentScene1"], Is.True);
            }
        }
Esempio n. 17
0
        public void Add(T id, StateAction OnEnter, StateAction OnUpdate, StateAction OnExit)
        {
            var new_state = new State(id, OnEnter, OnUpdate, OnExit);

            states.Add(id, new_state);
        }
Esempio n. 18
0
 public void Reset()
 {
     activeStateAction = null;
 }
Esempio n. 19
0
        private bool HasPermission(StateAction stateAction, out InvalidContentActionReason reason)
        {
            // set this as permission error will be the most common reason
            reason = InvalidContentActionReason.NotEnoughPermissions;

            if (this.Node.Id == 0)
            {
                var parent = this.Node.Parent;

                // for new content, creator needs to have AddNew permission for the parent
                if (!parent.Security.HasPermission(PermissionType.AddNew))
                {
                    return(false);
                }

                // if this is a list type, the user must have a manage container permission for the parent
                if (!CheckManageListPermission(this.Node.NodeType, parent))
                {
                    return(false);
                }

                // do not call this.Node.Security.HasPermission method because the node has not exist yet.
                switch (stateAction)
                {
                case StateAction.Save:
                    return(true);

                case StateAction.CheckOut:
                case StateAction.SaveAndCheckIn:
                case StateAction.CheckIn:
                case StateAction.UndoCheckOut:
                case StateAction.Publish:
                case StateAction.Approve:
                case StateAction.Reject:
                    return(false);

                default:
                    throw new SnNotSupportedException("Unknown StateAction: " + stateAction);
                }
            }
            else
            {
                // otherwise the user needs to have Save permission for every action
                if (!this.Node.Security.HasPermission(PermissionType.Save))
                {
                    return(false);
                }

                // if this is a list type, the user must have a manage container permission for the node
                if (!CheckManageListPermission(this.Node.NodeType, this.Node))
                {
                    return(false);
                }

                var checkedOutByAnotherUser = IsCheckedOutByAnotherUser(this.Node);
                if (checkedOutByAnotherUser)
                {
                    reason = InvalidContentActionReason.CheckedOutToSomeoneElse;
                }

                switch (stateAction)
                {
                case StateAction.Save:
                case StateAction.CheckOut:
                case StateAction.SaveAndCheckIn:
                case StateAction.CheckIn:
                    return(!checkedOutByAnotherUser);

                case StateAction.UndoCheckOut:
                    // force and 'normal' undo operations
                    return(!checkedOutByAnotherUser || HasForceUndoCheckOutRight(this.Node));

                case StateAction.Publish:
                    return(this.Node.Security.HasPermission(User.Current, PermissionType.Publish) && !checkedOutByAnotherUser);

                case StateAction.Approve:
                case StateAction.Reject:
                    return(this.Node.Security.HasPermission(User.Current, PermissionType.Approve));

                default:
                    throw new SnNotSupportedException("Unknown StateAction: " + stateAction);
                }
            }
        }
Esempio n. 20
0
 public void CreateState(string name, StateAction action)
 {
     name = CreateState(name);
     m_States[name].AddStateAction(action);
 }
Esempio n. 21
0
 /// <summary>
 /// Sets N[s,a]'s value
 /// </summary>
 /// <param name="s">The state</param>
 /// <param name="a">The action</param>
 /// <param name="e">The value to be updated</param>
 protected virtual void __set_nsa_value(State s, Action a, NVal e) { var sig = new StateAction(s, a); if (!this.NSA.Contains(sig)) this.NSA.Add(sig, e); else this.NSA[sig] = e; }
Esempio n. 22
0
		public void addAction(string evt, StateAction action){
			actionMap_.Add (evt, action);
		}
Esempio n. 23
0
        /// <summary>
        /// Changes the player shuffle state. If the StateAction is Toggle then the current state is switched with it's opposite,
        /// if it is State the current state is dispatched with an Event.
        /// </summary>
        /// <param name="action"></param>
        public void RequestShuffleState(StateAction action)
        {
            if (action == StateAction.Toggle)
            {
                mbApiInterface.Player_SetShuffle(!mbApiInterface.Player_GetShuffle());
            }

            EventBus.FireEvent(
                new MessageEvent(
                    EventType.ReplyAvailable,
                    new SocketMessage(Constants.PlayerShuffle, Constants.Reply,
                        mbApiInterface.Player_GetShuffle()).toJsonString()));
        }
Esempio n. 24
0
        public void ReduceTest()
        {
            var reducer = new PagePopReducer();
            var state   = new State();

            state.SetValue <PageStack>(PageConst.StateStackKey, new PageStack());
            state.SetValue <PageDefinition>(PageConst.StateDefinitionKey, new PageDefinition
            {
                PageScenes = new[]
                {
                    new PageScene
                    {
                        Name   = "Page1",
                        Scenes = new[]
                        {
                            "Scene1",
                            "Scene2"
                        },
                    },
                    new PageScene
                    {
                        Name   = "Page2",
                        Scenes = new[]
                        {
                            "Scene1",
                            "Scene3"
                        },
                    }
                }
            });
            state.SetValue <IDictionary <string, bool> >(SceneConst.StateKey, new Dictionary <string, bool>()
            {
                { "Scene1", true },
                { "Scene2", false },
                { "Scene3", false },
            });

            {
                var pageStack = new PageStack();
                pageStack.Push(new Page {
                    Name = "Page1", Data = null
                });
                pageStack.Push(new Page {
                    Name = "Page2", Data = null
                });
                state.SetValue <PageStack>(PageConst.StateStackKey, pageStack);
            }

            // pop1
            {
                var action = new StateAction(reducer, "page", new Any());
                state = reducer.Reduce(state, action);

                var stack = state.GetValue <PageStack>(PageConst.StateStackKey);
                Assert.That(stack.Count, Is.EqualTo(1));
                Assert.That(stack.Peek().Name, Is.EqualTo("Page1"));

                var sceneMap = state.GetValue <IDictionary <string, bool> >(SceneConst.StateKey);
                Assert.That(sceneMap.Count, Is.EqualTo(3));
                Assert.That(sceneMap["Scene1"], Is.True);
                Assert.That(sceneMap["Scene2"], Is.True);
                Assert.That(sceneMap["Scene3"], Is.False);
            }

            // pop is failed if stack has only an element
            {
                var action = new StateAction(reducer, "page", new Any());
                state = reducer.Reduce(state, action);

                var stack = state.GetValue <PageStack>(PageConst.StateStackKey);
                Assert.That(stack.Count, Is.EqualTo(1));
                Assert.That(stack.Peek().Name, Is.EqualTo("Page1"));

                var sceneMap = state.GetValue <IDictionary <string, bool> >(SceneConst.StateKey);
                Assert.That(sceneMap.Count, Is.EqualTo(3));
                Assert.That(sceneMap["Scene1"], Is.True);
                Assert.That(sceneMap["Scene2"], Is.True);
                Assert.That(sceneMap["Scene3"], Is.False);
            }
        }
Esempio n. 25
0
    public void UpdateAI()
    {
        if (grid == null)
        {
            grid = GameObject.FindObjectOfType <Grid>();
        }

        if (myTurn && !didTurn)
        {
            didTurn = true;

            State boardState = GetBoardState();

            Debug.Log("State visited counter: " + boardState.TimesVisited);

            if (brain == null)
            {
                brain = new StateAgent(boardState);
            }
            else
            {
                brain.SetState(boardState);
            }

            //get action from brain, execute.

            StateAction action = brain.GetChosenActionForCurrentState();

            string[] moves = Regex.Split(action.ActionString, "to");
            string[] from  = Regex.Split(moves[0], "-");
            string[] to    = Regex.Split(moves[1], "-");

            Debug.Log(action.ActionString + ", Quality: " + action.GetDeepEvaluation() + " (" + action.ActionEvaluation + ") --- " + brain.LearnedStates + "///" + brain.EvaluatedActions);

            if (action.GetDeepEvaluation() != action.ActionEvaluation)
            {
                Debug.Log("///////////////////////////////////////////////////////////////");
            }

            foreach (Node n in grid.grid)
            {
                n.UnhighlightEat();
                n.UnhighlightMove();
            }

            Node fromNode = grid.GetNodeAt(int.Parse(from[1]), int.Parse(from[0]));
            Node toNode   = grid.GetNodeAt(int.Parse(to[1]), int.Parse(to[0]));

            fromNode.HighlightMove();
            toNode.HighlightEat();

            piece = fromNode.Piece;
            piece.Pickup();
            GameManager.Instance.GameState.Grab();
            int reward = 0;

            Piece tPiece = toNode.Piece;
            if (tPiece == null)
            {
                if (piece.IsPossibleMove(toNode))
                {
                    if (Rules.IsCheckMove(this, piece, toNode, true))
                    {
                        Debug.Log("Move checked, not allowed"); // do nothing

                        brain.EvaluateLastAction(-10000);
                        GameManager.Instance.GameState.Checkmate();
                        GameManager.Instance.GameOver(GameManager.Instance.PlayerOponent, GameOverType.CHECKMATE);
                    }
                    else
                    {
                        piece.MoveToXZ(toNode, Drop);
                        GameManager.Instance.GameState.Place();
                    }
                }
            }
            else
            {
                if (piece.IsPossibleEat(toNode))
                {
                    if (Rules.IsCheckEat(this, piece, toNode, true))
                    {
                        Debug.Log("Eat checked"); // do nothing

                        brain.EvaluateLastAction(-10000);
                        GameManager.Instance.GameState.Checkmate();
                        GameManager.Instance.GameOver(GameManager.Instance.PlayerOponent, GameOverType.CHECKMATE);
                    }
                    else
                    {
                        GCPlayer oppPlayer = GameManager.Instance.Opponent(this);

                        oppPlayer.brain.EvaluateLastAction(-tPiece.GetPieceValue());
                        reward = tPiece.GetPieceValue();

                        oppPlayer.RemovePiece(tPiece);
                        AddEatenPieces(tPiece);
                        tPiece.ScaleOut(0.2f, 1.5f);
                        piece.MoveToXZ(toNode, Drop);
                        GameManager.Instance.GameState.Place();
                    }
                }
            }

            State newState = GetBoardState();

            brain.PerformStateAction(action, newState);
            brain.EvaluateLastAction(reward);
        }
    }
Esempio n. 26
0
 public virtual void setStateAction(StateAction action)
 {
     throw new NotImplementedException();
 }
Esempio n. 27
0
        public ClientStateAction StateKey(int ClientId, string Message, int StateActionStateId)
        {
            ClientStateAction clientStateAction = null;

            StateActionState stateActionState = db.StateActionState.FirstOrDefault(s => s.StateActionStateId == StateActionStateId);
            StateAction      action           = db.StateActions.FirstOrDefault(x => x.StateActionId == stateActionState.StateActionId);

            StateActionState NewStateActionState;

            if (action.Name == "Rechazado")
            {
                NewStateActionState = db.StateActionState.FirstOrDefault(
                    s => s.ClientState.Name == "Rechazado" && s.StateAction.Name == "Rechazado");
                clientStateAction = CreateClientStateAction(ClientId, Message, NewStateActionState.StateActionStateId);
            }

            switch (stateActionState.ClientState.Name)
            {
            case "Lead":
                if (action.Name == "Llamada")
                {
                    NewStateActionState = db.StateActionState.FirstOrDefault(
                        s => s.ClientState.Name == "Contacto" && s.StateAction.Name == "llamada");
                    clientStateAction = CreateClientStateAction(ClientId, Message, NewStateActionState.StateActionStateId);
                }
                break;

            case "Contacto":
                if (action.Name == "Cita")
                {
                    NewStateActionState = db.StateActionState.FirstOrDefault(
                        s => s.ClientState.Name == "Visita" && s.StateAction.Name == "Cita");
                    clientStateAction = CreateClientStateAction(ClientId, Message, NewStateActionState.StateActionStateId);
                }
                break;

            case "Visita":
                if (action.Name == "Venta realizada")
                {
                    NewStateActionState = db.StateActionState.FirstOrDefault(
                        s => s.ClientState.Name == "Venta" && s.StateAction.Name == "Venta realizada");
                    clientStateAction = CreateClientStateAction(ClientId, Message, NewStateActionState.StateActionStateId);
                }
                break;

            case "Venta":
                if (action.Name == "Cerrar")
                {
                    NewStateActionState = db.StateActionState.FirstOrDefault(
                        s => s.ClientState.Name == "Vendido" && s.StateAction.Name == "Venta realizada");
                    clientStateAction = CreateClientStateAction(ClientId, Message, NewStateActionState.StateActionStateId);
                }
                break;

            case "Rechazado":
                if (action.Name == "Recuperar cliente")
                {
                    ClientStateAction clientStateActionToDelete = db.ClientStateAction.FirstOrDefault(
                        c => c.ClientId == ClientId && c.StateActionState.ClientState.Name == "Rechazado");
                    db.ClientStateAction.Remove(clientStateActionToDelete);
                    db.SaveChanges();
                    NewStateActionState = db.StateActionState.FirstOrDefault(
                        s => s.ClientState.Name == "Contacto" && s.StateAction.Name == "Informacion");
                    clientStateAction = CreateClientStateAction(ClientId, Message, NewStateActionState.StateActionStateId);
                }
                break;

            default:
                clientStateAction = null;
                break;
            }

            return(clientStateAction);
        }
Esempio n. 28
0
 public override void setStateAction(StateAction action)
 {
     stateAction = action;
 }
Esempio n. 29
0
 /// <summary>
 ///     A state transition which is only valid when the bit
 ///     is equal to the <code>validBit</code>.
 /// </summary>
 /// <param name="validBit"></param>
 /// <param name="action"></param>
 public StateTransition(int nextState, T validBit, StateAction <T> action)
 {
     this.NextState = nextState;
     this.Validator = (bit) => bit.Equals(validBit);
     this.Action    = action;
 }
 public void Add(T _key, StateAction _act)
 {
     this.stateTable.Add(_key, new State(_act.Start, _act.Update, _act.End));
 }
Esempio n. 31
0
 public UnitState(Point position, double time, StateAction stateAction)
 {
     this.position = position;
     this.Time     = time;
     this._action  = stateAction;
 }
Esempio n. 32
0
 public void addAction(string evt, StateAction action)
 {
     actionMap_.Add(evt, action);
 }
Esempio n. 33
0
 public Sprite(int x, int y, int dx, int dy, int width, int height, StateAction dir, StateAction act)
 {
     this.x           = x;
     this.y           = y;
     this.dx          = dx;
     this.dy          = dy;
     this.widthtActor = width;
     this.heightActor = height;
     direction        = dir;
     action           = act;
     realHeight       = this.heightActor;
     realWidth        = this.widthtActor;
 }
Esempio n. 34
0
 public StateEvent(TStateId state, StateAction action)
 {
     this.state  = state;
     this.action = action;
 }
        private void ResetActionList()
        {
            SerializedObject   obj      = new SerializedObject(state);
            SerializedProperty elements = obj.FindProperty("actions");

            actionList = new ReorderableObjectList(obj, elements);

            actionList.drawHeaderCallback = delegate(Rect rect) {
                EditorGUI.LabelField(rect, "Actions");
            };

            actionList.onAddCallback = delegate(ReorderableObjectList list) {
                FsmGUIUtility.SubclassMenu <StateAction> (delegate(Type type){
                    StateAction action = (StateAction)ScriptableObject.CreateInstance(type);
                    action.name        = type.GetCategory() + "." + type.Name;
                    action.hideFlags   = HideFlags.HideInHierarchy;
                    state.Actions      = ArrayUtility.Add <StateAction> (state.Actions, action);

                    if (EditorUtility.IsPersistent(state))
                    {
                        AssetDatabase.AddObjectToAsset(action, state);
                        AssetDatabase.SaveAssets();
                    }
                    list.index = list.count;
                    EditorUtility.SetDirty(state);
                });
            };

            actionList.drawElementCallback = delegate(int index, bool selected) {
                StateAction action  = state.Actions [index];
                bool        enabled = action.IsEnabled;
                if (selected)
                {
                    GUIStyle selectBackground = new GUIStyle("MeTransitionSelectHead")
                    {
                        stretchHeight = false,
                    };
                    selectBackground.overflow = new RectOffset(-1, -2, -2, 2);
                    GUILayout.BeginVertical(selectBackground);
                }
                action.IsOpen = GUIDrawer.ObjectTitlebar(action, action.IsOpen, ref enabled, FsmGUIUtility.ExecutableContextMenu(action, state));
                if (selected)
                {
                    GUILayout.EndVertical();
                }
                action.IsEnabled = enabled;
                if (action.IsOpen)
                {
                    GUIDrawer.OnGUI(action);
                }
            };

            actionList.onRemoveCallback = delegate(ReorderableObjectList list) {
                StateAction action = state.Actions[list.index];
                state.Actions = ArrayUtility.Remove <StateAction> (state.Actions, action);
                FsmEditorUtility.DestroyImmediate(action);
                list.index = list.index - 1;
                ErrorChecker.CheckForErrors();
                EditorUtility.SetDirty(state);
            };

            actionList.onContextClick = delegate(int index) {
                FsmGUIUtility.ExecutableContextMenu(state.Actions [index], state).ShowAsContext();
            };

            actionList.onHeaderContextClick = delegate() {
                GenericMenu menu = new GenericMenu();

                if (state.Actions.Length > 0)
                {
                    menu.AddItem(new GUIContent("Copy"), false, delegate {
                        copy      = new List <StateAction>(state.Actions);
                        copyState = state;
                    });
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Copy"));
                }

                if (copy == null)
                {
                    copy = new List <StateAction>();
                }

                copy.RemoveAll(x => x == null);
                if (copy.Count > 0)
                {
                    menu.AddItem(new GUIContent("Paste After"), false, delegate() {
                        for (int i = 0; i < copy.Count; i++)
                        {
                            ExecutableNode dest = FsmUtility.Copy(copy[i]);
                            state.Actions       = ArrayUtility.Add <StateAction>(state.Actions, (StateAction)dest);
                            FsmEditorUtility.ParentChilds(state);
                            EditorUtility.SetDirty(state);
                            //	NodeInspector.Dirty();
                            ErrorChecker.CheckForErrors();
                        }
                    });
                    menu.AddItem(new GUIContent("Paste Before"), false, delegate() {
                        for (int i = 0; i < copy.Count; i++)
                        {
                            ExecutableNode dest = FsmUtility.Copy(copy[i]);
                            state.Actions       = ArrayUtility.Insert <StateAction>(state.Actions, (StateAction)dest, 0);
                            FsmEditorUtility.ParentChilds(state);
                            EditorUtility.SetDirty(state);
                            //	NodeInspector.Dirty();
                            ErrorChecker.CheckForErrors();
                        }
                    });
                    if (copyState != state)
                    {
                        menu.AddItem(new GUIContent("Replace"), false, delegate() {
                            for (int i = 0; i < state.Actions.Length; i++)
                            {
                                FsmEditorUtility.DestroyImmediate(state.Actions[i]);
                            }
                            state.Actions = new StateAction[0];
                            ResetActionList();

                            for (int i = 0; i < copy.Count; i++)
                            {
                                ExecutableNode dest = FsmUtility.Copy(copy[i]);
                                state.Actions       = ArrayUtility.Add <StateAction>(state.Actions, (StateAction)dest);
                                FsmEditorUtility.ParentChilds(state);
                                EditorUtility.SetDirty(state);
                                //	NodeInspector.Dirty();
                                ErrorChecker.CheckForErrors();
                            }
                        });
                    }
                    else
                    {
                        menu.AddDisabledItem(new GUIContent("Replace"));
                    }
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Paste After"));
                    menu.AddDisabledItem(new GUIContent("Paste Before"));
                    menu.AddDisabledItem(new GUIContent("Replace"));
                }
                menu.ShowAsContext();
            };

            this.host.Repaint();
            if (FsmEditor.instance != null)
            {
                FsmEditor.instance.Repaint();
            }
        }
Esempio n. 36
0
 public override void ApplyDifferenceByAction(StatsDifference difference, StateAction action, float multiplier = 1)
 {
     Value += GetDifferenceValue(difference);
 }
Esempio n. 37
0
        private ActionValidationResult ValidateAction(StateAction stateAction, out InvalidContentActionReason reason)
        {
            if (!HasPermission(stateAction, out reason))
            {
                return(ActionValidationResult.Invalid);
            }

            if (this.Node.SavingState != ContentSavingState.Finalized && (stateAction != StateAction.CheckIn && stateAction != StateAction.UndoCheckOut))
            {
                reason = InvalidContentActionReason.MultistepSaveInProgress;
                return(ActionValidationResult.Invalid);
            }

            reason = InvalidContentActionReason.InvalidStateAction;

            if (this.Node.Id == 0)
            {
                if (stateAction == StateAction.Save || stateAction == StateAction.SaveAndCheckIn)
                {
                    return(ActionValidationResult.Valid);
                }

                return(ActionValidationResult.InvalidOnNewNode);
            }

            var action = 0;

            switch (stateAction)
            {
            case StateAction.Save: action = 0; break;

            case StateAction.CheckOut: action = 1; break;

            case StateAction.CheckIn: action = 2; break;

            case StateAction.UndoCheckOut: action = 3; break;

            case StateAction.Publish: action = 4; break;

            case StateAction.Approve: action = 5; break;

            case StateAction.Reject: action = 6; break;

            case StateAction.SaveAndCheckIn: action = 7; break;

            default:
                throw new SnNotSupportedException("Unknown StateAction: " + stateAction);
            }

            var status        = 0;
            var versionStatus = this.Node.Locked ? VersionStatus.Locked : this.CurrentVersion.Status;

            switch (versionStatus)
            {
            case VersionStatus.Approved: status = 0; break;

            case VersionStatus.Locked: status = 1; break;

            case VersionStatus.Draft: status = 2; break;

            case VersionStatus.Rejected: status = 3; break;

            case VersionStatus.Pending: status = 4; break;

            default:
                throw new SnNotSupportedException("Unknown VersionStatus: " + this.CurrentVersion.Status);
            }

            var mode = 0;

            switch (this.VersioningMode)
            {
            case VersioningMode.None: mode = 0; break;

            case VersioningMode.Major: mode = 1; break;

            case VersioningMode.Full: mode = 2; break;

            default:
                throw new SnNotSupportedException("Unknown VersioningMode: " + this.VersioningMode);
            }
            var approving = this.HasApproving ? 1 : 0;

            if (!EnabledActions[15 * approving + 5 * mode + status][action])
            {
                return(ActionValidationResult.Invalid);
            }
            return(ActionValidationResult.Valid);
        }
Esempio n. 38
0
 public UnitState(Point position, double time, StateAction stateAction)
 {
     this.position = position;
     this.Time = time;
     this._action = stateAction;
 }
 public static void ClearStates()
 {
     var a = new StateAction();
     a.clearing = true;
     actions.Enqueue(a);
 }
Esempio n. 40
0
        public void RunAction(string actionName)
        {
            StateAction action = _actions[actionName];

            RunAction(action);
        }
Esempio n. 41
0
 /// <summary>
 /// Mark a [s,a] visited and the result will be [s']
 /// </summary>
 /// <param name="s">The state</param>
 /// <param name="a">The action</param>
 /// <param name="sprim">The next state</param>
 protected void __visit(State s, Action a, State sprim) { var sig = new StateAction(s, a); if (!this.VisitedStateActions.Contains(sig)) this.VisitedStateActions.Add(sig, new List<State>() { sprim }); else (this.VisitedStateActions[sig] as List<State>).Add(sprim); }
Esempio n. 42
0
 private void UpdateBeforeAction(StateAction action)
 {
     UpdateStatsOneTime(action.GetEffectBefore(), action);
 }
Esempio n. 43
0
 /// <summary>
 /// Gets N[s,a]'s value if any exists or initializes it by 0.
 /// </summary>
 /// <param name="s">The state</param>
 /// <param name="a">The action</param>
 /// <returns>The value</returns>
 protected virtual NVal __get_nsa_value(State s, Action a) { var sig = new StateAction(s, a); if (!this.NSA.Contains(sig)) this.NSA.Add(sig, (NVal)0); return (NVal)this.NSA[sig]; }
Esempio n. 44
0
 private void UpdateAfterAction(StateAction action)
 {
     UpdateStatsOneTime(action.GetEffectAfter(), action);
 }
Esempio n. 45
0
 /// <summary>
 /// If the action equals toggle then it changes the repeat state, in any other case
 /// it just returns the current value of the repeat.
 /// </summary>
 /// <param name="action">toggle or state</param>
 /// <returns>Repeat state: None, All, One</returns>
 public void RequestRepeatState(StateAction action)
 {
     if (action == StateAction.Toggle)
     {
         switch (mbApiInterface.Player_GetRepeat())
         {
             case RepeatMode.None:
                 mbApiInterface.Player_SetRepeat(RepeatMode.All);
                 break;
             case RepeatMode.All:
                 mbApiInterface.Player_SetRepeat(RepeatMode.None);
                 break;
             case RepeatMode.One:
                 mbApiInterface.Player_SetRepeat(RepeatMode.None);
                 break;
         }
     }
     EventBus.FireEvent(
         new MessageEvent(EventType.ReplyAvailable,
             new SocketMessage(Constants.PlayerRepeat, Constants.Reply,
                 mbApiInterface.Player_GetRepeat()).toJsonString()));
 }
Esempio n. 46
0
        public void movePlayer(BufferedGraphics buffer, Bitmap bm)
        {
            switch (_action)
            {
            case StateAction.Down:
                _indexRow = 0;

                if (_indexColumn >= 0 && _indexColumn < _maxCols - 1)
                {
                    _indexColumn++;
                }
                else
                {
                    _indexColumn = 0;
                    _dx          = 0;
                    _dy          = 10;
                    _direction   = StateAction.Down;
                }
                break;

            case StateAction.Left:
                _indexRow = 1;
                if (_indexColumn >= 0 && _indexColumn < _maxCols - 1)
                {
                    _indexColumn++;
                }
                else
                {
                    _indexColumn = 0;
                    _dx          = -10;
                    _dy          = 0;
                    _direction   = StateAction.Left;
                }
                break;

            case StateAction.Right:
                _indexRow = 2;
                if (_indexColumn >= 0 && _indexColumn < _maxCols - 1)
                {
                    _indexColumn++;
                }
                else
                {
                    _indexColumn = 0;
                    _dx          = 10;
                    _dy          = 0;
                    _direction   = StateAction.Right;
                }
                break;

            case StateAction.Up:
                _indexRow = 3;
                if (_indexColumn >= 0 && _indexColumn < _maxCols - 1)
                {
                    _indexColumn++;
                }
                else
                {
                    _indexColumn = 0;
                    _dx          = 0;
                    _dy          = -10;
                    _direction   = StateAction.Up;
                }
                break;

            case StateAction.Standing:
                _dx = 0;
                _dy = 0;
                switch (_direction)
                {
                case StateAction.Down:
                    _indexColumn = 0;
                    _indexRow    = 0;
                    break;

                case StateAction.Left:
                    _indexColumn = 0;
                    _indexRow    = 1;
                    break;

                case StateAction.Right:
                    _indexColumn = 0;
                    _indexRow    = 2;
                    break;

                case StateAction.Up:
                    _indexColumn = 0;
                    _indexRow    = 3;
                    break;

                default:
                    break;
                }
                break;    //case StateAction.Standing
            }//switch (Action)

            drawPlayer(buffer, bm, _zoom);
        }
Esempio n. 47
0
 public WINTRUST_DATA(WINTRUST_FILE_INFO fileInfo)
 {
     cbStruct            = (uint)Marshal.SizeOf(typeof(WINTRUST_DATA));
     pInfoStruct         = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));
     Marshal.StructureToPtr(fileInfo, pInfoStruct, false);
     dwUnionChoice       = UnionChoice.File;
     pPolicyCallbackData = IntPtr.Zero;
     pSIPCallbackData    = IntPtr.Zero;
     dwUIChoice          = UiChoice.NoUI;
     fdwRevocationChecks = RevocationCheckFlags.None;
     dwStateAction       = StateAction.Ignore;
     hWVTStateData       = IntPtr.Zero;
     pwszURLReference    = IntPtr.Zero;
     dwProvFlags         = TrustProviderFlags.Safer;
     dwUIContext         = UIContext.Execute;
 }
Esempio n. 48
0
 private void CambiarEstadoTicket(Ticket oTicket, StateAction oAccion, string cMensaje = "")
 {
     _robot.SaveTicketNextState(cMensaje == "" ? oTicket : _Funciones.MesaDeControl(oTicket, cMensaje), oAccion.Id);
     _Funciones.CerrarDriver(_driverGlobal);
 }