Beispiel #1
0
 public void AddState(State state)
 {
     if (null == m_statesDict)
         m_statesDict = new Dictionary<Type, State>();
     if(!m_statesDict.ContainsKey(state.GetType()))
         m_statesDict.Add(state.GetType(), state);
 }
Beispiel #2
0
        public void AddArc(State s)
        {
            if (_arcsMap.ContainsKey(s.Name))
            {
                throw new StateMachineException(ErrorCodes.AlreadyPresentArc, StateMachineException.MakeArcName(Name, s.Name));
            }

            Arc a = new Arc(this, s);
            _arcsMap[s.Name] = a;
        }
Beispiel #3
0
 public void ChangeState(Type stateType)
 {
     if (null != m_statesDict && m_statesDict.ContainsKey(stateType))
     {
         if (null != m_curState)
             m_curState.OnLeave();
         m_curState = m_statesDict[stateType];
         m_curState.OnEnter();
     }
 }
Beispiel #4
0
        public Arc(State source, State target)
        {
            Source = source;
            Target = target;

            _transitCallbacks = new List<ArcCallbackInvoker>();

            if (IsUnlinked)
            {
                throw new StateMachineException(ErrorCodes.InvalidArc, StateMachineException.MakeArcName(source.Name, target.Name));
            }
        }
        public ActiveStateMachine(Dictionary<string, State> stateList, int queueCapacity)
        {
            StateList = stateList;
            _initialState = new State("InitialState", null, null, false, null);

            TriggerQueue = new BlockingCollection<string>(queueCapacity);

            InitStateMachine();
            RaiseStateMachineSystemEvent("State Machine Initialized", "System Ready to Start");

            StateMachineEngine = EngineState.Initialized;
        }
Beispiel #6
0
        public Arc this[State s]
        {
            get
            {
                if (!_arcsMap.ContainsKey(s.Name))
                {
                    return null;
                }

                return _arcsMap[s.Name];
            }
        }
        public static Machine Deserialize(string fileName)
        {
            Machine machine = new Machine();
            XmlDocument xml = new XmlDocument();
            xml.Load(fileName);
            XmlElement xmlMachine = xml["machine"];

            var states = xmlMachine["States"];
            foreach (XmlElement xmlState in states)
            {
                State state = new State();
                var attributes = xmlState.Attributes;
                state.Name = attributes[0].Value;
                state.IsLast = Convert.ToBoolean(attributes[1].Value);
                machine.States.Add(state);
            }

            var letters = xmlMachine["Alphabet"];
            foreach (XmlElement xmlLetter in letters)
            {
                Letter letter = new Letter();
                var attributes = xmlLetter.Attributes;
                letter.Name = attributes[0].Value;
                letter.Description = attributes[1].Value;
                machine.Alphabet.Letters.Add(letter);
            }

            var functions = xmlMachine["Functions"];
            foreach (XmlElement xmlFunction in functions)
            {
                Function function = new Function();
                var attributes = xmlFunction.Attributes;
                function.Name = attributes[0].Value;
                function.From = machine.States.Where(n => n.Name == attributes[1].Value).ToList()[0];
                function.To = machine.States.Where(n => n.Name == attributes[2].Value).ToList()[0];
                function.Letter = machine.Alphabet.Letters.Where(n => n.Name == attributes[3].Value).ToList()[0];
                machine.Functions.Add(function);
            }

            try
            {
                var firstState = xmlMachine.LastChild;
                var stateName = firstState.Attributes[0].Value;
                machine.FirstState = machine.States.Where(n => n.Name == stateName).ToList()[0];
            }
            catch
            {
                machine.FirstState = null;
            }

            return machine;
        }
Beispiel #8
0
 public void ChangeState(State to)
 {
     state = to;
 }
Beispiel #9
0
 public VendingMachine()
 {
     Console.WriteLine("The Vending Machine is now online: product costs 25c");
     state = Start.Instance();
 }
Beispiel #10
0
 public Function(string name, State from, State to, Letter letter)
 {
     this.name = name;
     this.from = from;
     this.to = to;
     this.letter = letter;
 }
Beispiel #11
0
 public Function()
 {
     this.name = "";
     this.from = new State();
     this.to = new State();
     this.letter = new Letter();
 }
Beispiel #12
0
 //TODO прикрутить к проверкам функций алфавит.
 /// <summary>
 /// Добавление нового состояния.
 /// Добавление просиходит только тогда, когда такого состояния в автомате нет.
 /// </summary>
 /// <param name="newState">Состояние, которое мы хотим добавить</param>
 public void AddNewState(State newState)
 {
     if (newState.Name.Length > 0)
     {
         foreach (State state in States)
         {
             if (state == newState) throw new ArgumentException("Такое состояние уже есть!");
         }
         States.Add(newState);
     }
     else
     {
         throw new ArgumentException("Таконе название не допустимо!");
     }
 }
Beispiel #13
0
        /// <summary>
        /// Составление языка автомата
        /// </summary>
        /// <param name="state"></param>
        /// <param name="word"></param>
        /// <param name="way"></param>
        /// <returns></returns>
        private List<List<Letter>> Language(State state, List<Letter> word, List<State> way)
        {
            way.Add(state); // Составляем путь
            //State currentState = new State();
            //currentState = FirstState;
            List<List<Letter>> itog = new List<List<Letter>>();
            if (MyMath.getCount(way, state) > 1) // если мы гдето зациклелись
            {
                // Делаем бесконечный цикл (внешний вид)
                var index = MyMath.getPos(word, way);
                //word.RemoveAt(word.Count-1);
                word.Insert(index, new Letter("(", ""));
                word.Add(new Letter(")*    как база + ещё", ""));
                itog.Add(word);
                way.RemoveAt(way.Count-1);
            }
            else
            {

                if (state.IsLast) // если мы уже получили распознаваемое слово
                {
                    if (word.Count == 0) itog.Add(new List<Letter>() { new Letter("epsilon", "") });
                    else itog.Add(word);
                }
                foreach (Function function in functions)
                {
                    // Смотрим, куда можно пойти
                    if (function.From == state)
                    {

                        var newWord = new List<Letter>();
                        foreach (Letter letter in word)
                        {
                            newWord.Add(letter);
                        }
                        newWord.Add(function.Letter); // Создаем копию слова
                        //
                        var d = Language(function.To, newWord, way); // рекурсивно вызываем
                        //itog.AddRange(d);
                        foreach (List<Letter> a in d)
                        {
                            // добавляем все слова, полученные рекурсивно
                            if (!itog.Contains(a)) itog.Add(a);
                        }
                    }
                }
                way.RemoveAt(way.Count - 1); // поднимаемся на уровень вверх
            }

            return itog;
        }
Beispiel #14
0
 public Machine()
 {
     this.states = new ObservableCollection<State>();
     this.functions = new ObservableCollection<Function>();
     this.firstState = new State();
     this.alphabet = new Alphabet();
 }
Beispiel #15
0
        public void removeState(State state)
        {
            for (int i = 0; i < functions.Count; i++)
            {
                if ((functions[i].From == state) || (functions[i].To == state))
                {
                    removeFunction(functions[i]);
                    i--;
                }

            }
            states.Remove(state);
        }
Beispiel #16
0
        public List<String> GetLanguage(State state, List<Letter> word, List<State> way)
        {
            List<string> list = new List<string>();
            var a = Language(state, word, way);

            foreach (List<Letter> someWord in a)
            {
                var wordic = "";
                foreach (Letter letter in someWord)
                {
                    wordic += letter.Name + " ";
                }
                if (!list.Contains(wordic)) list.Add(wordic);
            }
            return list;
        }
Beispiel #17
0
        //Проверяем слово на распознаваемость
        public bool CheckWord(List<Letter> word)
        {
            State currentState = new State();
            currentState = FirstState; // Начинаем поиск с 1ой вершины
            try
            {

                // Проверяем, есть ли буквы слова в алфавите автомата
                if (CanRead(word))
                {

                    foreach (Letter letter in word) //Идем по всем буквам слова
                    {
                        bool temp = true;
                        foreach (Function function in Functions) // Прверяем, куда мы можем уйти
                        {
                            // Если из текущего состояния, по букве слова мы можем перейти
                            if ((function.From == currentState) && (function.Letter == letter) && (temp))
                            {
                                // то перехоим
                                temp = false;
                                currentState = function.To; // меняем состояние
                            }

                        }
                        if (temp) return false; // Нету перехода из состояния по букве слова
                    }
                }
                else return false; // нет нужных букв в алфавите
            }
            catch (Exception)
            {
                return false;
            }
            return currentState.IsLast; // Если не вытели раньше, то сово распознано
        }
 public static void serializeFirstState(State state,XmlTextWriter writer)
 {
     writer.WriteStartElement("FirstState");
     writer.WriteAttributeString("Name", state.Name);
     writer.WriteEndElement();
 }
Beispiel #19
0
 protected virtual void ChangeState(VendingMachine vm, State s)
 {
     vm.ChangeState(s);
 }
Beispiel #20
0
 /// <summary>
 /// Считает количество вхождений вершины в пути
 /// </summary>
 /// <param name="states"></param>
 /// <param name="state"></param>
 /// <returns></returns>
 public static int getCount(List<State> states, State state)
 {
     int count = 0;
     foreach (State fstate in states)
     {
         if (state == fstate) count++;
     }
     return count;
 }
Beispiel #21
0
 public Machine(ObservableCollection<State> states, ObservableCollection<Function> functions, State state, Alphabet alphabet)
 {
     this.firstState = state;
     this.states = states;
     this.functions = functions;
     this.Alphabet = alphabet;
 }
Beispiel #22
0
 public void Reset()
 {
     m_statesDict.Clear();
     m_curState = null;
 }
Beispiel #23
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="way"></param>
 /// <param name="state"></param>
 /// <returns></returns>
 private static int find(List<State> way, State state)
 {
     for (int i = 0; i < way.Count; i++)
     {
         if (way[i] == state) return i;
     }
     return -1;
 }