Konami Code in C#

后端 未结 11 2166
执笔经年
执笔经年 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:41

    The answer can be found in Reactive Extensions. You need a sliding buffer for this to work. Meaning you have to compare the latest ten keystrokes with the Konami code. This works using two different statements

    • A window to get a stream of streams (eventually leading to 10 simultaneous streams)
    • A buffer to summarize each stream into an IList

    The buffer within RX does both these tasks for us. Buffers the last 10 items and skips 1 (so effectively creates 10 buffers).

            var keysIO = Observable.FromEventPattern(this, "KeyDown")
                                        .Select(arg => arg.EventArgs.Key)
                                        .Buffer(10, 1)
                                        .Select(keys => Enumerable.SequenceEqual(keys, _konamiArray))
                                        .Where(result => result)
                                        .Subscribe(i =>
                                                        {
                                                            Debug.WriteLine("Found Konami");
                                                        });
    

    EDIT: Removed the timed solution., too complex

    EDIT II: I cracked the time-out solution as well. The beauty of SelectMany :-)

            var keysIO = Observable.FromEventPattern(this, "KeyDown")
                                .Select(e => e.EventArgs.Key)
                                .Window(10, 1)
                                .SelectMany(obs => obs.Buffer(TimeSpan.FromSeconds(10), 10))
                                .Where(keys => Enumerable.SequenceEqual(_konamiArray, keys))
                                .Subscribe(keys => Debug.Write("Found Konami"));
    

提交回复
热议问题