February 25, 2013

Konami Code Problem

I don't remember exactly why, but today my friends and I were talking about the old web, where all sites were made using a notepad or at most microsoft's frontpage, and google wasn't the most used search engine yet.

Back then we used an older version of HTML, with some cool features to play with. One of them was the <marquee> tag, that made all of it's content roll over the page. We tested it in Chrome, and surprise, it still works! Take a look:

They see me rolling...

So the first question that went through our computer scientist's minds was: "What if we made all website's content with a marquee tag?"

Then we figured out an easy way to do it using javascript:
var marqueefy = function () {
     var me = $(this).clone();
     var marquee = $('').html(me);
     $(this).replaceWith(marquee);
};

var marqueeAll = function () {
     var tagsToMarquee = ['li', 'a', 'span', 'h1', 'img', 'iframe', 'p', 'hr'];
     for (tag in tagsToMarquee) {
          $('body').find(tagsToMarquee[tag]).each(marqueefy);
};
And we just need to bind it to the document ready event:
$(document).ready(function () {
     marqueeAll();
});
It works! But suddenly one of us said: "Wait! What if it did more? Call this function only when the Konami Code is typed?". And so we did.
If you are not familiar with the Konami Code, you can see it's wikipedia's page. It's a well known code created by Konami that trigged a lot of secret stuff in their games. So we thought about doing it as a jQuery plugin, to be as easy as that to use:
$(document).KonamiCode(aFunction);
We used a stack data structure to build it, where every char typed is pushed to it, and when the enter key is typed, it runs a verification code to see if the sequence typed backwards is equal to the Konami Code. The javascript code is:
(function ($) {
     $.fn.KonamiCode = function (konamiFunction) {
          var codeSequence = new Array();
          var easterEggSequence = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13];
                
          return this.each(function () {
               $(this).keyup(function (e) {
               var typedSequence = new Array();

               codeSequence.push(e.keyCode);

               if (e.keyCode == 13) {
                    var i = 0;
                    while (i++ < easterEggSequence.length) {
                         typedSequence.push(codeSequence.pop());
                    }

                    if (typedSequence.reverse().toString() == easterEggSequence.toString())
                         konamiFunction();
                    else
                         codeSequence = new Array();
               }
          });
     });
};
})(jQuery);
And now it is perfectly possible to do:
$(document).KonamiCode(marqueeAll);
Cool, isn't it? That was a really fun codeventure to be in. Why don't you test it in our page? :) See ya!