I was asked to implement the Konami Code in a website I\'m currently working on. It should do the following:
Change Background Image
Play s
This is a solution I came up with around 3 or 4 years ago. In my case I chose keyUp to keep it separate from any actions that occur from keyDown events. Also there is no need to specify what keys are allowable since the for loop checks which key was released against all the keys on the keyboard.
var konamicode = [38,38,40,40,37,39,37,39,66,65];
var kc=0;
function checker() {
if (kc==10) {
// What you want to occur when code matches goes in here.
kc=0; // This resets the sequence.
alert("It Worked!");
}
}
function keyUp(e) {
var keynum;
if (window.event) { keynum = event.keyCode; }
else if (e.which) { keynum = e.which; }
for (i = 0; i < 222; i++) { // The 222 represents all the keys on the keyboard.
var kx=konamicode[kc]; // kx represents the current position in the code sequence.
if (keynum == i) {
// Checks to see if key matches sequence, and resets sequence if it doesn't.
if (i!=kx){kc=0;} else {kc++;}
}
}
checker();
}