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 sound
Bring some pop-up
What’s the easiest way to achieve this using javascript?
Advertisement
Answer
Place the code below in a file js/konami.js
and reference it in the body of your html file like this: <script src="js/konami.js"></script>
JavaScript
x
47
47
1
// a key map of allowed keys
2
var allowedKeys = {
3
37: 'left',
4
38: 'up',
5
39: 'right',
6
40: 'down',
7
65: 'a',
8
66: 'b'
9
};
10
11
// the 'official' Konami Code sequence
12
var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'];
13
14
// a variable to remember the 'position' the user has reached so far.
15
var konamiCodePosition = 0;
16
17
// add keydown event listener
18
document.addEventListener('keydown', function(e) {
19
// get the value of the key code from the key map
20
var key = allowedKeys[e.keyCode];
21
// get the value of the required key from the konami code
22
var requiredKey = konamiCode[konamiCodePosition];
23
24
// compare the key with the required key
25
if (key == requiredKey) {
26
27
// move to the next key in the konami code sequence
28
konamiCodePosition++;
29
30
// if the last key is reached, activate cheats
31
if (konamiCodePosition == konamiCode.length) {
32
activateCheats();
33
konamiCodePosition = 0;
34
}
35
} else {
36
konamiCodePosition = 0;
37
}
38
});
39
40
function activateCheats() {
41
document.body.style.backgroundImage = "url('images/cheatBackground.png')";
42
43
var audio = new Audio('audio/pling.mp3');
44
audio.play();
45
46
alert("cheats activated");
47
}
EDIT: changed the sequence to b, a instead of a, b. Thanks for the comment!
EDIT 2: reset the konamiCodePosition to 0 after activateCheats was called. Thanks for the comment!