Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add konami code in a website based on html?

Tags:

I was asked to implement the Konami Code in a website I'm currently working on. It should do the following:

  1. Change Background Image

  2. Play sound

  3. Bring some pop-up

What's the easiest way to achieve this using javascript?


People also ask

How do you program a Konami Code?

Up, Up, Down, Down, Left, Right, Left, Right, B, A. It's called the Konami Code, and it often meant the difference between life and death in a video game back in the 1980s. Perform those button presses in the right sequence, and you'll unlock cheats that help you win.

What does Up Up Down Down Left Right Left Right BA Start do?

To use the code, players would press up, up, down, down, left, right, left, right, B, A and the Start button on the controller to make games easier. It was named after the popular Japanese gaming and entertainment company Konami, where Hashimoto worked.


1 Answers

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>

// a key map of allowed keys  var allowedKeys = {    37: 'left',    38: 'up',    39: 'right',    40: 'down',    65: 'a',    66: 'b'  };    // the 'official' Konami Code sequence  var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'];    // a variable to remember the 'position' the user has reached so far.  var konamiCodePosition = 0;    // add keydown event listener  document.addEventListener('keydown', function(e) {    // get the value of the key code from the key map    var key = allowedKeys[e.keyCode];    // get the value of the required key from the konami code    var requiredKey = konamiCode[konamiCodePosition];      // compare the key with the required key    if (key == requiredKey) {        // move to the next key in the konami code sequence      konamiCodePosition++;        // if the last key is reached, activate cheats      if (konamiCodePosition == konamiCode.length) {        activateCheats();        konamiCodePosition = 0;      }    } else {      konamiCodePosition = 0;    }  });    function activateCheats() {    document.body.style.backgroundImage = "url('images/cheatBackground.png')";      var audio = new Audio('audio/pling.mp3');    audio.play();      alert("cheats activated");  }

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!

like image 80
w.stoettinger Avatar answered Sep 18 '22 12:09

w.stoettinger