を使用しているここでの概念実証あなたがどんなで動作することができますです文字シーケンスのコレクション。私はあなたが文字と一致するだけであると仮定しています(Keys.Left
などの他のキーではありません)。
// Initialize the collection of strings to be matched against here.
string[] stringSequences = new string[] { "yes", "no", "hello" };
int maxLength = stringSequences.Max(s => s.Length);
// The buffer to hold the sequence of the last N characters.
string buffer = "";
while (true)
{
// Read the next character, and append it to the end of the buffer.
ConsoleKeyInfo next = Console.ReadKey();
buffer += next.KeyChar;
// If the buffer has exceeded our maximum length,
// trim characters from its start.
if (buffer.Length > maxLength)
buffer = buffer.Substring(1);
// Check whether the last n characters of the buffer
// correspond to any of the sequences.
string match = stringSequences.FirstOrDefault(s => buffer.EndsWith(s));
if (match != null)
{
// Match! Perform any custom processing here.
Console.WriteLine(Environment.NewLine + "Match: " + match);
}
}
編集:キーで動作するようになって。
私はKeys
に対して簡単にテストすることができないので、代わりにConsoleKey
を使用しました。ただし、コードを翻訳するのは難しいことではありません。
// Initialize the collection of key sequences to be matched against here.
ConsoleKey[][] keysSequences = new ConsoleKey[][]
{
new ConsoleKey[] { ConsoleKey.Y, ConsoleKey.E, ConsoleKey.S },
new ConsoleKey[] { ConsoleKey.N, ConsoleKey.O },
new ConsoleKey[] { ConsoleKey.H, ConsoleKey.E, ConsoleKey.L, ConsoleKey.L, ConsoleKey.O },
};
int maxLength = keysSequences.Max(ks => ks.Length);
// The buffer to hold the sequence of the last N keys.
List<ConsoleKey> buffer = new List<ConsoleKey>();
while (true)
{
// Read the next key, and append it to the end of the buffer.
ConsoleKeyInfo next = Console.ReadKey();
buffer.Add(next.Key);
// If the buffer has exceeded our maximum length,
// trim keys from its start.
if (buffer.Count > maxLength)
buffer.RemoveAt(0);
// Check whether the last n keys of the buffer
// correspond to any of the sequences.
ConsoleKey[] match = keysSequences.FirstOrDefault(ks =>
buffer.Skip(buffer.Count - ks.Length).SequenceEqual(ks));
if (match != null)
{
// Match! Perform any custom processing here.
Console.WriteLine(Environment.NewLine + "Match: " +
string.Concat(match.Select(k => k.ToString()).ToArray()));
}
}
リストまたはキュー –
kenny
目的を達成するためにこれらのデータ構造を使用する方法を説明できますか?私はちょうどそれの周りに私の頭を包むことはできません。ここでこのみコードの追跡エントリの –
例: http://stackoverflow.com/questions/469798/konami-code-in-c-sharp – roken