我被要求执行Konami代码
在我目前正在使用的网站上。它应该执行以下操作:

  • 更改背景图像
  • 播放声音
  • 弹出一些

  • 使用javascript实现此目的的最简单方法是什么?

    最佳答案

    将下面的代码放置在文件js/konami.js中,并像这样在html文件的主体中引用它:<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");
    }


    编辑:将顺序更改为b,而不是a,b。感谢您的评论!

    编辑2:在调用activateCheats之后,将konamiCodePosition重置为0。感谢您的评论!

    09-27 01:14