Konami Code in C#

后端 未结 11 2138
执笔经年
执笔经年 2020-12-07 19:07

I am looking to have a C# application implement the Konami Code to display an Easter Egg. http://en.wikipedia.org/wiki/Konami_Code

What is the best way to do this?<

11条回答
  •  眼角桃花
    2020-12-07 19:47

    Here is another implementation, based on James answer and comments:

    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
        public class KonamiSequence
        {
            private readonly Keys[] _code = { Keys.Up, Keys.Up, Keys.Down, Keys.Down, Keys.Left, Keys.Right, Keys.Left, Keys.Right, Keys.B, Keys.A };
            private int _index = 0;
    
            public bool IsCompletedBy(Keys key)
            {
                if (key == _code[_index]) {
                    if (_index == _code.Length - 1) {
                        _index = 0;
                        return true;
                    }
                    ++_index;
                } else {
                    _index = 0;
                }
    
                return false;
            }
        }
    }
    
    • Doesn't bother caching _code.Length (see this article), however note it's accessed only when a key from the sequence is typed.
    • Accepts the case "UUUUUUUUUUDDLRLRBA".
    • Of course, resets the sequence if a wrong key is typed.

提交回复
热议问题