Created
July 20, 2011 03:27
-
-
Save anaisbetts/1094271 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <head> | |
| <script type="text/javascript" src="lib/jquery-1.6.2.js"></script> | |
| <script type="text/javascript" src="lib/rx.js"></script> | |
| <script type="text/javascript" src="lib/rx.jQuery.js"></script> | |
| </head> | |
| <body> | |
| <p id="content">Do you still remember the Konami code?</p> | |
| <p id="hint" style="display: none">Up Up Down Down Left Right Left Right b a Enter</p> | |
| </body> | |
| <script type="text/javascript" src="konamicode.js"></script> | |
| </html> | |
| <!-- vim: ts=2 sw=2 et : | |
| --> | |
| /* Detecting the Konami code in RxJS | |
| * | |
| * Here's a more complex example - let's check for the Konami Code on our | |
| * webpage and activate a cheat code if someone types it in. This looks more | |
| * complex than original example, but only because JavaScript has no equivalent | |
| * of Enumerable.SequenceEqual (i.e. check if two lists have the same elements) | |
| */ | |
| var up = 38; | |
| var down = 40; | |
| var left = 37; | |
| var right = 39; | |
| var b = 66; | |
| var a = 65; | |
| var enter = 13; | |
| var konamiCode = [up, up, down, down, left, right, left, right, b, a, enter]; | |
| var konamiCodeFound = $(window).toObservable("keydown") | |
| .Select(function(x) { return x.keyCode }) | |
| .BufferWithCount(konamiCode.length, 1) | |
| .Select(function(sequence) { | |
| // We now have two arrays, our konamiCode array, and an array of the last 7 | |
| // keys pressed - compare the two to see if they're equal (i.e. the last 7 | |
| // keys pressed was the Konami code) | |
| for (var i = 0; i < konamiCode.length; i++) { | |
| if (sequence[i] !== konamiCode[i]) { | |
| return true; | |
| } | |
| } | |
| return false; | |
| }); | |
| konamiCodeFound | |
| .Where(function(x) { return (x === true); }) | |
| .Timeout(3 * 1000) | |
| .Take(1) | |
| .Catch(Rx.Observable.Return(false)) | |
| .Subscribe(function(foundInTime) { | |
| $("#hint").fadeIn("fast"); | |
| }); | |
| konamiCodeFound | |
| .Subscribe(function(x) { | |
| if (x == true) { | |
| $("#content").text("CheatCode Found!"); | |
| } | |
| }); | |
| // vim: ts=2 sw=2 et : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment