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
as a typescript module
const Konami = (() => {
// up, up, down, down, left, right, left, right, b, a, enter
const SEQUENCE: Array<number> = [
38,
38,
40,
40,
37,
39,
37,
39,
66,
65,
13,
];
let head: number = 0;
let isActive: boolean = false;
let callback: Function | undefined;
const start = (cb: Function): void => {
if (isActive) {
return;
}
window.addEventListener("keydown", onKeyDown);
callback = cb;
isActive = true;
};
const stop = (): void => {
if (!isActive) {
return;
}
isActive = false;
window.removeEventListener("keydown", onKeyDown);
};
const onKeyDown = (event) => {
if (event.keyCode === SEQUENCE[head]) {
head++;
if (head === SEQUENCE.length) {
if (callback instanceof Function) {
callback();
}
head = 0;
}
} else {
head = 0;
}
};
return {
start,
stop,
};
})();
export default Konami;
implementation:
Konami.start(() => { alert("konami sequence entered!"); });
notes: SEQUENCE is an array of the expected inputs. by using the head
var, the order checking and number of correct inputs is maintained. it also provides a simple way to restart if input deviates from the sequence. it also eliminates the needs for a "count" var.
Silentdrummer has a good answer. I'm not entirely sure, but I think it could end up taking up too much memory on typing intensive pages. It's good practice to reset. Either way, here's an alternative.
// Cheat Codes
neededkeys = [38,38,40,40,37,39,37,39,66,65], started = false, count = 0;
$(document).keydown(function(e) {
key = e.keyCode;
if (!started) {
if (key == 38) {
started = true;
}
}
if (started) {
if (neededkeys[count] == key) {
count++;
} else {
reset();
}
if (count == 10) {
reset();
// Do your stuff here
alert('Cheat Codes Activated');
$('body').css('background-color', '#FFA8A8');
// Turn down for what
var s=document.createElement('script');
s.setAttribute('src','https://nthitz.github.io/turndownforwhatjs/tdfw.js');
document.body.appendChild(s);
}
} else {
reset();
}
});
function reset() {
started = false;
count = 0;
}
compact version:
function onKonamiCode(cb) {
var input = '';
var key = '38384040373937396665';
document.addEventListener('keydown', function (e) {
input += ("" + e.keyCode);
if (input === key) {
return cb();
}
if (!key.indexOf(input)) return;
input = ("" + e.keyCode);
});
}
onKonamiCode(function () {alert('\o/')})
Piggybacking off Ehsan Kia,
I haven't seen anyone handling cases where the up key could be pressed 3+ times, and technically the code would have been input correctly.
Minified it a bit because the conditionals got long.
let c = 0;
const kCode = [38,38,40,40,37,39,37,39,66,65];
document.addEventListener('keydown', (e) => {
c = (e.keyCode == kCode[c] ? c + 1 : (e.keyCode-38 ? 0 : (c ? (kCode[c-1] == 38 ? c : 0) : 0)));
if(c == kCode.length) activate();
});