Friday, May 15, 2009

An easy, understandable Konami Code implementation (using Javascript with JQuery)

This is just a quick post on my own Konami Code algorithm. If you haven't heard of the Konami Code, I'd like to refer you to sitepoint's article on it and Wikipedia.

My algorithm uses an array of integers, that represent the keyCodes that correspond to the Konami Code: var konamiCode = [38,38,40,40,37,39,37,39,66,65];

Furthermore it used an index: konamiIndex. This index starts at and resets to 0. If a key is pressed, the algorithm checks if that key corresponds to the konamiCode array at the position of the current index. So if the index is currently 0, a keypress will check if the keyCode is equal to konamiCode[konamiIndex] which evaluates to konamiCode[0], which is keyCode 38, which is up.

If the pressed keyCode is correct for the Konami code, the konamiIndex increments by one. If then the konamiIndex equals the length of the konami code array, we have a winner!

My code:


var konamiCode = [38,38,40,40,37,39,37,39,66,65];
var konamiIndex = 0;
$(document).keydown(function(e) {
if(e.keyCode == konamiCode[konamiIndex]) {
konamiIndex++;
if (konamiIndex == konamiCode.length) {
// You are in Konami code territory!
alert("Konami!");
konamiIndex = 0; // Reset the index
} else {
konamiIndex = 0;
}
}
});

No comments: