Beispiel #1
0
        private bool FillStates(string input)
        {
            Regex           regex   = new Regex(@"\s*\w+\s*:\s*(\w|ε)\s*->\s*\w+\s*"); // Ввод по образцу [current]: [symbol] -> [next]
            MatchCollection matches = regex.Matches(input);

            if (matches.Count == 1)
            {
                string[] groups = input.Split(new char[] { ' ', ':', '-', '>' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < groups.Length; i = i + 3)
                {
                    if (Alphabet == "" || Alphabet.Contains(groups[i + 1][0]))
                    {
                        StateTable.Add(new TransRule(groups[i], groups[i + 1][0], groups[i + 2]));
                    }
                    else
                    {
                        Console.WriteLine($"Символ {groups[i + 1][0]} не включен во входной алфавит");
                        return(false);
                    }
                }
                return(true);
            }
            else
            {
                Console.WriteLine("Правило не соответствует установленному шаблону");
                return(false);
            }
        }
        public string VigenerFromString(Mode mode, string Text)
        {
            if (!CheckKey())
            {
                throw new Exception("Incorrect key value");
            }
            int           charIndex;    // index in alphabet
            int           msgIndex = 0; // index in message letters
            int           index    = 0; // index in all message chars
            int           keyIndex;     // index in key
            StringBuilder stringBuilder = new StringBuilder(Text);

            foreach (var character in Text)
            {
                if (!(Alphabet.Contains(Char.ToUpper(character)) || Alphabet.Contains(Char.ToLower(character))))
                {
                    index++; continue;
                }
                //shift of alphabet for encrypting and index of char in non-shifted alphabet for decrypting
                charIndex = Alphabet.IndexOf(Char.ToLower(character));
                // index of column in shifted alphabet
                keyIndex = Alphabet.IndexOf(Key[msgIndex % Key.Length]);
                if (mode == Mode.ENCRYPT)
                {
                    charIndex = (keyIndex + charIndex) % Alphabet.Length;
                }
                else
                {
                    charIndex = (charIndex - keyIndex + Alphabet.Length) % Alphabet.Length;
                }
                stringBuilder.Replace(character, Char.IsUpper(character) ? Char.ToUpper(Alphabet[charIndex]) : Char.ToLower(Alphabet[charIndex]), index, 1);
                msgIndex++; index++;
            }
            return(stringBuilder.ToString());
        }
Beispiel #3
0
 private void Validate(A letter)
 {
     if (!Alphabet.Contains(letter))
     {
         throw new ArgumentException(string.Format("The letter {0} is not recognized", letter));
     }
 }
Beispiel #4
0
        public bool AddCommand(int column, int row, Command command)
        {
            if (command is null)
            {
                TableCommand.Commands[row, column] = null;
                return(true);
            }

            if (!Alphabet.Contains(command.ChangeSim))
            {
                return(false);
            }
            if (column <= 0 || row <= 0 || column > TableCommand.Commands.GetLength(1) || row > TableCommand.Commands.GetLength(0))
            {
                return(false);
            }

            if (command.ChangeSim is '\0')
            {
                return(false);
            }
            if (command.State >= CountState || command.State < 0)
            {
                return(false);
            }

            TableCommand.Commands[row, column] = command;

            return(true);
        }
Beispiel #5
0
        private void rebuildSubstitutionMatrix()
        {
            string value = SubstitutionPass.ToUpperInvariant();

            StringBuilder  sb   = new StringBuilder();
            HashSet <char> seen = new HashSet <char>();

            foreach (char c in value)
            {
                // add character to matrix if unique and part of alphabet
                if (!seen.Contains(c) && Alphabet.Contains(c))
                {
                    sb.Append(c);
                    seen.Add(c);
                }
            }

            // fill matrix with remaining characters
            foreach (char c in Alphabet)
            {
                if (!seen.Contains(c))
                {
                    sb.Append(c);
                }
            }

            SubstitutionMatrix = sb.ToString();
            Debug.Assert(sb.Length == Alphabet.Length, "Matrix length != Alphabet length");
        }
Beispiel #6
0
        public double IndexOfCoincidence(List <char> Cipher)
        {
            Dictionary <char, double> counts = new Dictionary <char, double>();

            foreach (char s in Cipher)
            {
                if (Alphabet.Contains(s))
                {
                    if (counts.ContainsKey(s))
                    {
                        counts[s]++;
                    }
                    else
                    {
                        counts.Add(s, 1);
                    }
                }
            }

            double sum = 0.0;

            foreach (char s in counts.Keys)
            {
                sum += counts[s] * (counts[s] - 1);
            }
            return(sum / (double)(Cipher.Count * (Cipher.Count - 1)));
        }
Beispiel #7
0
        /// <summary>
        /// Run the machine using the given input.
        /// </summary>
        /// <param name="x">The input string.</param>
        /// <returns>True if the machine accepts the input string.</returns>
        public bool Run(char[] x)
        {
            var i       = 0;
            var current = InitialState;

            while (i < x.Length)
            {
                if (!Alphabet.Contains(x[i]))
                {
                    return(false);
                }
                if (x[i] == Alphabet.EmptyString)
                {
                    i++;
                    continue;
                }
                var q = Transitions[current, x[i]];
                if (q == null)
                {
                    return(false);
                }
                current = q.Q;
                i++;
            }
            return(current.Accepting);
        }
        /// <summary>
        /// Manually adds a letter to the set of recognizable letters.
        /// </summary>
        /// <param name="letter">Letter to recognize.</param>
        public void AddLetter(A letter)
        {
            if (Alphabet.Contains(letter))
            {
                return;
            }

            Alphabet.Add(letter);
        }
Beispiel #9
0
 protected void CheckWordInAlphabet(string w)
 {
     for (int i = 0; i < w.Length; i++)
     {
         if (!Alphabet.Contains(w[i]))
         {
             throw new AlphabetException(w[i], this);
         }
     }
 }
 private bool CheckKey()
 {
     foreach (var c in Key)
     {
         if (!Alphabet.Contains(c))
         {
             return(false);
         }
     }
     return(true);
 }
Beispiel #11
0
        public void SetValueToTapePoint(int keyIndex, char value)
        {
            if (keyIndex < Tape.Min || keyIndex > Tape.Max || value is '\0')
            {
                return;
            }

            if (Alphabet.Contains(value))
            {
                Tape.TapeDic[keyIndex].SetValue(value);
            }
        }
Beispiel #12
0
        public static string ReverseLetter(string str)
        {
            const string Alphabet  = "QqWwEeRrTtYyUuIiOoPpAaSsDdFfGgHhJjKkLlZzXxCcVvBbNnMm";
            var          sortedStr = str.Where(c => Alphabet.Contains(c));
            string       result    = "";

            foreach (char c in sortedStr.Reverse())
            {
                result += c;
            }

            return(result);
        }
Beispiel #13
0
        public void RemovePossibilityTest()
        {
            /*** ARRANGE ***/
            Alphabet alphabet = CreateDefaultAlphabet();
            Cell     target   = new Cell(alphabet);
            int      value    = 3;                      // arbitrary

            /*** ACT ***/
            target.RemovePossibility(value);

            /*** ASSERT ***/
            Assert.IsFalse(target.CanBe(value));        // value is no longer a possible value
            Assert.IsTrue(alphabet.Contains(value));    // alphabet remains unchanged
        }
Beispiel #14
0
        public (State, string) Run(string str)
        {
            string tape = $"{EmptyChar}{str}{EmptyChar}";

            State currentState = InputState;

            currentState.IsActive = true;
            int idx = 1;

            while (!currentState.IsOutput)
            {
                char curChar = tape[idx];

                if (!Alphabet.Contains(curChar))
                {
                    throw new InvalidOperationException("Alphabet doesn't contain this character");
                }

                var transition = currentState.GetTransition(curChar);

                if (transition == null)
                {
                    Console.WriteLine($"There is no transition for char '{curChar}' in state #{currentState.Id}");
                    break;
                }
                // zapis znak
                tape = $"{tape.Substring(0, idx)}{transition.LetterToWrite}{tape.Substring(idx + 1)}";

                currentState.IsActive = false;
                currentState          = transition.EndState;
                currentState.IsActive = true;

                idx = transition.DirectionToGo == Direction.Left ? --idx :
                      transition.DirectionToGo == Direction.Right ? ++idx : idx;

                if (idx < 0) // extend tape
                {
                    idx  = 0;
                    tape = EmptyChar + tape;
                }
                else if (idx >= tape.Length)
                {
                    idx   = tape.Length;
                    tape += EmptyChar;
                }
            }

            return(currentState, tape);
        }
Beispiel #15
0
        private void RebuildTranspositionCleanPassword()
        {
            string value = TranspositionPass.ToUpperInvariant();

            //if no transposition password was given, we use a default password of A, meaning, we have no transposition
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
            {
                value = "A";
            }

            // remove characters not part of alphabet
            List <char> cleanPassword = new List <char>();

            foreach (char c in value)
            {
                if (Alphabet.Contains(c))
                {
                    cleanPassword.Add(c);
                }
            }

            // copy and sort characters
            char[] keyChars = cleanPassword.ToArray();
            Array.Sort(keyChars);

            // determine column order
            int[] newColumnOrder = new int[keyChars.Length];
            for (int i = 0; i < keyChars.Length; i++)
            {
                int column = Array.IndexOf(keyChars, cleanPassword[i]);
                newColumnOrder[i] = column;
                keyChars[column]  = (char)0; // make sure the same character won't be found again
            }
            KeyColumnOrder = newColumnOrder;

            // build nice looking string for output (note: column numbers start with 0 in array, but 1 in string)
            StringBuilder keyWord = new StringBuilder();

            if (newColumnOrder.Length >= 1)
            {
                keyWord.Append((newColumnOrder[0] + 1));
                for (int i = 1; i < newColumnOrder.Length; i++)
                {
                    keyWord.Append("-" + (newColumnOrder[i] + 1));
                }
            }
            CleanTranspositionPass = keyWord.ToString();
        }
Beispiel #16
0
        public Result SetWordDefault(string wordDefault = "101")
        {
            //проверка на существование всех символов
            for (int i = 0; i < wordDefault.Length; i++)
            {
                if (!Alphabet.Contains(wordDefault[i]))
                {
                    wordDefault = wordDefault.Remove(i, 1);
                    i--;
                }
            }

            WordDefault = wordDefault;

            return(Tape.SetWordDefault(wordDefault));
        }
        /// <summary>
        /// The check recovery available.
        /// </summary>
        /// <param name="chain">
        /// Source sequence.
        /// </param>
        /// <param name="length">
        /// Length of L-gram.
        /// </param>
        /// <returns>
        /// true if chain is recoverable form L-grams.
        /// </returns>
        private bool CheckRecoveryAvailable(AbstractChain chain, int length)
        {
            var iterator = new IteratorStart(chain, length, 1);
            var alphabet = new Alphabet();

            while (iterator.Next())
            {
                if (alphabet.Contains(iterator.Current()))
                {
                    return false;
                }

                alphabet.Add(iterator.Current());
            }

            return true;
        }
    /// <summary>
    /// Remove non-letters from this string, swap them for '_'
    /// </summary>
    public static string LettersOnly(this string _string)
    {
        if (string.IsNullOrEmpty(_string))
        {
            return(string.Empty);
        }
        StringBuilder builder = new StringBuilder(_string);

        for (int i = 0; i < _string.Length; i++)
        {
            if (!Alphabet.Contains(_string[i].ToString().ToLower()))
            {
                builder.Remove(i, 1);
                builder.Insert(i, '_');
            }
        }
        return(builder.ToString());
    }
Beispiel #19
0
        public void DeleteValuesFromAlph(HashSet <char> removeAlph)
        {
            //проверка на существование всех символов в алфавите => новый алфавит для удаления создать
            removeAlph = removeAlph.Where(i => Alphabet.Contains(i)).ToHashSet();
            removeAlph.Remove(' ');
            //удалить символы из текущей строки

            WordDefault = new string(WordDefault.Where(i => !removeAlph.Contains(i)).ToArray());

            //удалить удалить символы из алфавита

            foreach (var item in removeAlph)
            {
                Alphabet.Remove(item);
            }
            Tape.SetWordDefault(WordDefault);
            GetNewTableMinus(CountState, Alphabet);
        }
Beispiel #20
0
        protected override void CheckConstraints() {
            base.CheckConstraints();
            foreach (var t in Transforms) {
                if (t.Key.q >= StatesCount | t.Value.qNext >= StatesCount) //transform states within states
                    throw new StateException(t.Key.q, this);
                else if (t.Key.ci.HasValue && !Alphabet.Contains(t.Key.ci.Value)) //input alphabet of transform key
                    throw new AlphabetException(t.Key.ci.Value, this);
                else if (t.Key.cw.HasValue && !WorkAlphabet.Contains(t.Key.cw.Value)) //work alphabet of transform key
                    throw new AlphabetException(t.Key.cw.Value, this);
                //BUG: contains string
                else if (t.Value.cw2 != null && !WorkAlphabet.Contains(t.Value.cw2[0])) //work alphabet of transform value
                    throw new AlphabetException(t.Value.cw2[0], this);
            }

            //accepted States in States
            for (int i = 0; i < AcceptedStates.Length; i++)
                if (AcceptedStates[i] >= StatesCount)
                    throw new StateException(AcceptedStates[i], this);
        }
Beispiel #21
0
 protected override void CheckConstraints() {
     base.CheckConstraints();
     foreach (var t in Transforms) {
         for (int i = 0; i < t.Value.Length; i++) {
             if (t.Key.q >= StatesCount)
                 throw new StateException(t.Key.q, this);
             else if (t.Value[i].qNext >= StatesCount)
                 throw new StateException(t.Value[i].qNext, this);
             else if (t.Key.ci.HasValue && !Alphabet.Contains(t.Key.ci.Value))
                 throw new AlphabetException(t.Key.ci.Value, this);
             else if (t.Key.cw.HasValue && !WorkAlphabet.Contains(t.Key.cw.Value))
                 throw new AlphabetException(t.Key.cw.Value, this);
             else if (t.Value[i].cw2 != null && t.Value[i].cw2 != "" && !WorkAlphabet.Contains(t.Value[i].cw2[0]))
                 throw new AlphabetException(t.Value[i].cw2[0], this);
         }
     }
     for (int i = 0; i < AcceptedStates.Length; i++)
         if (AcceptedStates[i] >= StatesCount)
             throw new StateException(AcceptedStates[i], this);
 }
Beispiel #22
0
 protected override void CheckConstraints()
 {
     base.CheckConstraints();
     foreach (var t in Transforms)
     {
         for (int i = 0; i < t.Value.Length; i++)
         {
             if (t.Key.q >= StatesCount) // q to high
             {
                 throw new StateException(t.Key.q, this);
             }
             if (t.Value[i] >= StatesCount) // qNext to high
             {
                 throw new StateException(t.Value[i], this);
             }
             if (t.Key.c.HasValue && !Alphabet.Contains(t.Key.c.Value)) // char not in alphabet
             {
                 throw new AlphabetException(t.Key.c.Value, this);
             }
         }
     }
 }
Beispiel #23
0
        /// <summary>
        /// Adiciona transição entre 2 estados.
        /// </summary>
        /// <param name="estadoOrigem">O estado origem do autômato.</param>
        /// <param name="consumirFita">O símbolo a ser avaliado.</param>
        /// <param name="estadoDestino">O estado destino.</param>

        public void AdicionarTransicao(string estadoOrigem, string estadoDestino, Symbol consumirPilha,
                                       Symbol consumirFita, params Symbol[] gravarPilha)
        {
            if (consumirPilha == null)
            {
                consumirPilha = Symbol.EmptySymbol;
            }
            SymbolList vars = new SymbolList();

            if (gravarPilha == null || gravarPilha.Length == 0)
            {
                vars.Add(Symbol.EmptySymbol);
            }
            else
            {
                vars.AddRange(gravarPilha);
            }


            foreach (var symbol in vars)
            {
                if (StackAlphabet.IndexOf(symbol) < 0 && symbol != Symbol.EmptySymbol && symbol != Symbol.StackFinal && symbol != Symbol.TapeFinal)
                {
                    StackAlphabet.Add(symbol);
                }
            }

            // Adiciona transições..
            if (States.ContainsKey(estadoOrigem) && States.ContainsKey(estadoDestino))
            {
                if (!Alphabet.Contains(consumirFita))
                {
                    Alphabet.Add(consumirFita);
                }

                States[estadoOrigem].AdicionarTransicao(States[estadoDestino], consumirFita, consumirPilha, vars);
            }
        }
Beispiel #24
0
        private static Key ReadKey(string path, Alphabet alphabet)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }

            char[] text = null;

            using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open), Encoding.GetEncoding(1251))) {
                text = new char[reader.BaseStream.Length];
                for (long i = 0, l = reader.BaseStream.Length; i < l; ++i)
                {
                    text[i] = reader.ReadChar();
                    if (!alphabet.Contains(text[i]))
                    {
                        throw new ArgumentException("Symbol " + text[i] + " is not in the given alphabet!");
                    }
                }
            }

            return(new Key(text, alphabet));
        }
        /// <summary>
        /// Checks if alphabet is appropriate for dna sequence,
        /// e.g. contains only nucleotide elements.
        /// </summary>
        /// <param name="alphabet">
        /// Alphabet to check.
        /// </param>
        public static void CheckDnaAlphabet(Alphabet alphabet)
        {
            if (alphabet.Cardinality > 4)
            {
                throw new Exception("DNA alphabet cardinality must be 4 or less");
            }

            var completeAlphabet = new Alphabet
            {
                new ValueString("A"),
                new ValueString("C"),
                new ValueString("T"),
                new ValueString("G")
            };

            for (int i = 0; i < alphabet.Cardinality; i++)
            {
                if (!completeAlphabet.Contains(alphabet[i]))
                {
                    throw new Exception("Alphabet contains at least 1 wrong element: " + alphabet[i]);
                }
            }
        }
Beispiel #26
0
        protected override void CheckConstraints()
        {
            base.CheckConstraints();
            foreach (var ti in Transforms)
            {
                foreach (char c in ti.Key.c)
                {
                    if (!BandAlphabet.Contains(c))
                    {
                        throw new Automat.AlphabetException(c, this);
                    }
                }

                foreach (char c in ti.Value.c2)
                {
                    if (!BandAlphabet.Contains(c))
                    {
                        throw new Automat.AlphabetException(c, this);
                    }
                }

                if (Alphabet.Contains(BlankSymbol))
                {
                    throw new Automat.AlphabetException(BlankSymbol, this);
                }

                if (ti.Key.q >= StatesCount)
                {
                    throw new Automat.StateException(ti.Key.q, this);
                }

                if (ti.Value.qNext >= StatesCount)
                {
                    throw new Automat.StateException(ti.Value.qNext, this);
                }
            }
        }
        public void Test_NotContains()
        {
            Alphabet alphabet = Alphabet.Decimal;

            Assert.False(alphabet.Contains('A'));
        }
        public void Test_Contains()
        {
            Alphabet alphabet = Alphabet.Decimal;

            Assert.True(alphabet.Contains('9'));
        }
Beispiel #29
0
 protected bool BelongsToAlphabet(char value)
 => Alphabet.Contains(value);
        /// <summary>
        /// (Overridable) Accepts an unassigned Puzzle and returns it created and populated with required values.
        /// </summary>
        /// <param name="Puzzle"></param>
        public virtual void InitializePuzzle(out Puzzle Puzzle)
        {
            List<string> puzzleRows = GetPuzzleContent();
            int[] cellValues = new int[puzzleRows[0].Length * puzzleRows.Count];
            Alphabet puzzleAlphabet = new Alphabet();

            ExtractMetadata(puzzleRows);

            // Assumption: All values in the puzzle's alphabet can be found among the pre-filled cells it contains.
            for (int rowIndex = 0; rowIndex < puzzleRows.Count; rowIndex++)
            {
                for (int columnIndex = 0; columnIndex < puzzleRows[rowIndex].Length; columnIndex++)
                {
                    string cellValue = puzzleRows[rowIndex].Substring(columnIndex, 1);
                    if (cellValue != _EmptyCellDesignator && !puzzleAlphabet.Contains(int.Parse(cellValue)))
                    {
                        puzzleAlphabet.Add(int.Parse(cellValue));
                    }
                    cellValues[rowIndex * puzzleRows.Count + columnIndex] = cellValue == _EmptyCellDesignator ? _EmptyCellValue : int.Parse(cellValue);
                }
            }

            Puzzle = new Puzzle(puzzleRows[0].Length, puzzleRows.Count, this.BoxWidth, this.BoxHeight, puzzleAlphabet);
            for (int cellIndex = 0; cellIndex < Puzzle.Cells.Count; cellIndex++)
            {
                Puzzle.Cells[cellIndex].Value = cellValues[cellIndex];
                if (Puzzle.Cells[cellIndex].Value != _EmptyCellValue)
                {
                    Puzzle.Cells[cellIndex].SetAsSolved();
                }
            }
            if (Puzzle.SolveCount == 0)
            {
                Puzzle.ErrorMessage = "Error: The puzzle has no starting values in it.";
            }
            else
            {
                Puzzle.ErrorMessage = null;
            }
        }
Beispiel #31
0
        public FiniteAutomaton(States q, Alphabet a, TransitionFunction d, State q0, AcceptingStates f)
        {
            States          = q;
            Alphabet        = a;
            Transitions     = d;
            InitialState    = q0;
            AcceptingStates = f;

            if (States.Count == 0)
            {
                throw new ArgumentException("The set of states cannot be empty.");
            }
            if (!States.Contains(InitialState))
            {
                throw new ArgumentException("The initial state does not exist in the set of states!");
            }
            foreach (var s in AcceptingStates)
            {
                if (!States.Contains(s))
                {
                    throw new ArgumentException($"The accepting state {s} does not exist in the set of states!");
                }
            }
            foreach (var t in Transitions)
            {
                if (!States.Contains(t.P) || !States.Contains(t.Q) || (t.A != Alphabet.EmptyString && !Alphabet.Contains(t.A)))
                {
                    throw new ArgumentException($"Invalid transition {t}");
                }
            }
        }
Beispiel #32
0
        private void ParsLine(string line)
        {
            string[] transition = line.Split(',');
            long     source;
            long     destination;

            //Recognize initial and final states and set source and destination.
            if (transition[0][0] == '*')
            {
                source = long.Parse(transition[0].Substring(2));
                if (source >= StateCount)
                {
                    throw InputIncorrectException;
                }

                if (!FinalStates.Contains(source))
                {
                    FinalStates.Add(source);
                }
            }
            else if (transition[0][0] == '-' && transition[0][1] == '>')
            {
                source = long.Parse(transition[0].Substring(3));
                if (!InitialStateSet)
                {
                    InitialState = source;
                }
                else if (InitialState != source || source >= StateCount)
                {
                    throw InputIncorrectException;
                }
            }
            else
            {
                source = long.Parse(transition[0].Substring(1));
            }

            if (transition[4][0] == '*')
            {
                destination = long.Parse(transition[4].Substring(2));
                if (destination >= StateCount)
                {
                    throw InputIncorrectException;
                }

                if (!FinalStates.Contains(destination))
                {
                    FinalStates.Add(destination);
                }
            }
            else if (transition[4][0] == '-' && transition[4][1] == '>')
            {
                destination = long.Parse(transition[4].Substring(3));
                if (!InitialStateSet)
                {
                    InitialState = destination;
                }
                else if (InitialState != destination || destination >= StateCount)
                {
                    throw InputIncorrectException;
                }
            }
            else
            {
                destination = long.Parse(transition[4].Substring(1));
            }

            //Check for transition alphabet correctness
            if (transition[1] != "_" && !Alphabet.Contains(transition[1][0]))
            {
                throw InputIncorrectException;
            }

            //Add transition
            Transitions[source].Item1.Add(destination);
            Transitions[source].Item2.Add(transition[1][0]);

            //Check for stack alphabet correctness
            if (transition[2].Length != 1)   //pop element
            {
                throw InputIncorrectException;
            }
            else if (transition[2][0] != '_' && transition[2][0] != StackInitialSymbol && !StackAlphabet.Contains(transition[2][0]))
            {
                throw InputIncorrectException;
            }

            if (transition[3] != "_" && transition[3].Length != 2)   //push element
            {
                throw InputIncorrectException;
            }
            foreach (char chr in transition[3])
            {
                if (chr != '_' && chr != StackInitialSymbol && !StackAlphabet.Contains(chr))
                {
                    throw InputIncorrectException;
                }
            }

            //Add pop and push elements
            Transitions[source].Item3.Add(transition[2][0]);
            Transitions[source].Item4.Add(transition[3]);
        }
Beispiel #33
0
        /// <summary>
        /// Has to be called every Update to ensure correct calling
        /// </summary>
        public void Update(GameTime gameTime)
        {
            // Shift pressed to lastPressed
            LastPressedKeys = new List <Keys>(PressedKeys);
            PressedKeys.Clear();

            KeyboardState state = Keyboard.GetState();

            PressedKeys.AddRange(state.GetPressedKeys());

            // Add simulated keys
            foreach (Keys key in SimulatedKeys)
            {
                if (!PressedKeys.Contains(key))
                {
                    PressedKeys.Add(key);
                }
            }

            // Get pressed time for gmkeyboard.string
            // Remove released keys
            foreach (Keys key in PressTime.Keys.ToList())
            {
                if (!PressedKeys.Contains(key))
                {
                    PressTime.Remove(key);
                }
            }
            // Add newly pressed keys to pressTime
            foreach (Keys key in PressedKeys)
            {
                if (!PressTime.ContainsKey(key))
                {
                    PressTime.Add(key, -gameTime.ElapsedGameTime.TotalMilliseconds);
                }
            }

            Dictionary <Keys, double> lastPressTime = new Dictionary <Keys, double>(PressTime);

            TriggeredKeys.Clear();
            // Handle KeyboardString
            foreach (Keys key in PressTime.Keys.ToList())
            {
                // Don't add key to string if it isn't allowed to
                if (Settings.AddSimulatedKeysToKeyboardString == false)
                {
                    if (SimulatedKeys.Contains(key))
                    {
                        break;
                    }
                }

                PressTime[key] += gameTime.ElapsedGameTime.TotalMilliseconds;
                bool shouldFire = false;

                // Fire if key is just pressed
                if (PressTime[key] == 0)
                {
                    shouldFire = true;
                }

                // Check if it should refire because key is hold
                if (PressTime[key] >= Settings.ReFireDelay)
                {
                    int maxTime = Settings.ReFireDelay + Settings.ReFireInterval * 20;
                    if (PressTime[key] > maxTime)
                    {
                        PressTime[key]     -= Settings.ReFireInterval * 20;
                        lastPressTime[key] -= Settings.ReFireInterval * 20;
                    }
                    for (int t = Settings.ReFireDelay; t < maxTime; t += Settings.ReFireInterval)
                    {
                        if (PressTime[key] > t && lastPressTime[key] < t)
                        {
                            shouldFire = true;
                        }
                    }
                }

                if (shouldFire)
                {
                    TriggeredKeys.Add(key);
                    // s = shift pressed?
                    bool   s         = Check(Keys.LeftShift) | Check(Keys.RightShift);
                    string keyString = key.ToString();
                    if (Alphabet.Contains(key))
                    {
                        s       = state.CapsLock ? !s : s; // Invert shift if CapsLock is on
                        String += s ? keyString : keyString.ToLower();
                    }
                    else
                    {
                        bool nl = state.NumLock;
                        switch (key)
                        {
                        case Keys.Space: String += " "; break;

                        case Keys.Back: if (String.Length > 0)
                            {
                                String = String.Substring(0, String.Length - 1);
                            }
                            break;

                        case Keys.D1: String += s ? "!" : "1"; break;

                        case Keys.D2: String += s ? "@" : "2"; break;

                        case Keys.D3: String += s ? "#" : "3"; break;

                        case Keys.D4: String += s ? "$" : "4"; break;

                        case Keys.D5: String += s ? "%" : "5"; break;

                        case Keys.D6: String += s ? "^" : "6"; break;

                        case Keys.D7: String += s ? "&" : "7"; break;

                        case Keys.D8: String += s ? "*" : "8"; break;

                        case Keys.D9: String += s ? "(" : "9"; break;

                        case Keys.D0: String += s ? ")" : "0"; break;

                        case Keys.OemComma: String += s ? "<" : ","; break;

                        case Keys.OemPeriod: String += s ? ">" : "."; break;

                        case Keys.OemQuestion: String += s ? "?" : "/"; break;

                        case Keys.OemSemicolon: String += s ? ":" : ";"; break;

                        case Keys.OemQuotes: String += s ? "\"" : "'"; break;

                        case Keys.OemPipe: String += s ? "|" : "\\"; break;

                        case Keys.OemMinus: String += s ? "_" : "-"; break;

                        case Keys.OemPlus: String += s ? "+" : "="; break;

                        case Keys.OemOpenBrackets: String += s ? "{" : "["; break;

                        case Keys.OemCloseBrackets: String += s ? "}" : "]"; break;

                        case Keys.OemTilde: String += s ? "~" : "`"; break;

                        case Keys.NumPad0: String += nl ? "0" : ""; break;

                        case Keys.NumPad1: String += nl ? "1" : ""; break;

                        case Keys.NumPad2: String += nl ? "2" : ""; break;

                        case Keys.NumPad3: String += nl ? "3" : ""; break;

                        case Keys.NumPad4: String += nl ? "4" : ""; break;

                        case Keys.NumPad5: String += nl ? "5" : ""; break;

                        case Keys.NumPad6: String += nl ? "6" : ""; break;

                        case Keys.NumPad7: String += nl ? "7" : ""; break;

                        case Keys.NumPad8: String += nl ? "8" : ""; break;

                        case Keys.NumPad9: String += nl ? "9" : ""; break;

                        case Keys.Multiply: String += "*"; break;

                        case Keys.Divide: String += "/"; break;

                        case Keys.Add: String += "+"; break;

                        case Keys.Subtract: String += "-"; break;

                        case Keys.Decimal: String += "."; break;

                        case Keys.Enter: String += Settings.ParseEnter ? "\n" : ""; break;

                        case Keys.Tab: String += Settings.ParseTab ? "\t" : ""; break;

                        default: break;
                        }
                    }

                    // Limit Keyboard.String length
                    if (String.Length > Settings.StoreLength)
                    {
                        String = String.Substring(String.Length - Settings.StoreLength);
                    }
                }
            }
        }