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

前端 未结 10 1269
野性不改
野性不改 2020-12-13 01:21

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 s

相关标签:
10条回答
  • 2020-12-13 01:25

    To create your own "Konami Code" add the following Code snippet in your HTML Code. PS: Change the const secretCode to ... what ever you want :). With the current code you have to type 'arrow up' button, then 'h' then 'i' and last but not least the 'arrow down' button.

    Questions? Please ask.

    <script>
    const pressed = [];
    const secretCode = 'ArrowUphiArrowDown';
    
    window.addEventListener('keyup', (e) => {
        console.log(e.key);
        pressed.push(e.key);
        pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length);
    
        if(pressed.join('').includes(secretCode)) {
            console.log("Any source code that will be executed if you enter the correct code.");
        }
    
        console.log(pressed);
    })
    </script>
    
    0 讨论(0)
  • 2020-12-13 01:29

    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!

    0 讨论(0)
  • 2020-12-13 01:30

    Use the following code.

    const keySequence = [];
    let konamiString = '';
    const konamiCode = [
      'ArrowUp',
      'ArrowUp',
      'ArrowDown',
      'ArrowDown',
      'ArrowLeft',
      'ArrowRight',
      'ArrowLeft',
      'ArrowRight',
      'b',
      'a'
    ];
    
    document.addEventListener('keydown', function(e) {
      // To make sure it freezes the scroll when 
      // the first two keypresses are "ArrowUp"
      if (keySequence[0] === 'ArrowUp' && keySequence[1] === 'ArrowUp' && e.key === 'ArrowDown') {
        e.preventDefault();
      }
    });
    
    document.addEventListener('keyup', function(e) {
      const doc = document.documentElement;
      const top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    
      // This make sure it only work
      // when the window `scrollTop` is 0.
      if (top === 0) {
        keySequence.push(e.key);
        keySequence.splice(-konamiCode.length - 1, keySequence.length - konamiCode.length);
        konamiString = konamiCode.join('');
    
        if (keySequence.join('').includes(konamiString)) {
          // Trigger your easter egg here
        }
      }
    });
    

    The code also checks for the scrollTop of the window so that it won't scroll down when the first two keypresses are "ArrowUp" and the scrollTop of the window is 0

    I'm already using this code on my blog without any hiccup.

    0 讨论(0)
  • 2020-12-13 01:36

    I really liked Peter's answer, so I made it namespaced and made the callback optional. I also used jquery because I like it ¯\_(ツ)_/¯

    var Konami = Konami || {};
    
    Konami.key = '38384040373937396665';
    
    Konami.onCode = function(callback) {
        var input = '';
        $(document).on("keydown", function(e) {
            input += ("" + e.keyCode);
            if (input === Konami.key) {
                if(typeof callback == 'undefined') {
                    return alert("⬆⬆⬇⬇⬅➡⬅➡                                                                    
    0 讨论(0)
  • 2020-12-13 01:38

    My own compact and cleaned version inspired by the answers here:

    let cursor = 0;
    const KONAMI_CODE = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
    document.addEventListener('keydown', (e) => {
      cursor = (e.keyCode == KONAMI_CODE[cursor]) ? cursor + 1 : 0;
      if (cursor == KONAMI_CODE.length) activate();
    });
    

    In this case, the activate() function is called when triggered.

    0 讨论(0)
  • 2020-12-13 01:39

    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();
    }
    
    0 讨论(0)
提交回复
热议问题