如何在基于HTML的网站中添加konami代码?

Lor*_*cha 11 html javascript mp3 popup background-image

我被要求在我正在进行的网站上实施Konami Code.它应该做到以下几点:

  1. 改变背景图像

  2. 播放声音

  3. 弹出一些弹出窗口

使用javascript实现这一目标的最简单方法是什么?

w.s*_*ger 31

将下面的代码放在一个文件中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");
}
Run Code Online (Sandbox Code Playgroud)

编辑:将序列更改为b,而不是a,b.谢谢你的评论!

编辑2:调用activateCheats后将konamiCodePosition重置为0.谢谢你的评论!

  • 如果输入键序列为: 'up', 'up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', ',则代码将失败A'。原因:在第三个“向上”时,您的代码将正确地确定序列已被破坏,但在“else”块中错误地设置“konamiCodePosition = 0”。相反,在我的示例输入中,它应该重置为“1”,因为不正确的键(第三个“向上”)也是正确的第一个键。@w.stoettinger (2认同)

Pet*_*ter 15

紧凑版:

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/')})
Run Code Online (Sandbox Code Playgroud)


Ehs*_*Kia 9

我自己的紧凑和干净版本受到以下答案的启发:

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();
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,该activate()函数在触发时被调用。