javascript 如何在基于html的网站中添加konami代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31626852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add konami code in a website based on html?
提问by LordSacha
I was asked to implement the Konami Code in a website I'm currently working on. It should do the following:
我被要求在我目前正在开发的网站中实施 Konami 代码。它应该执行以下操作:
Change Background Image
Play sound
Bring some pop-up
更改背景图像
播放声音
带来一些弹出窗口
What's the easiest way to achieve this using javascript?
使用 javascript 实现这一目标的最简单方法是什么?
回答by w.stoettinger
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>
将下面的代码放在一个文件中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");
}
EDIT: changed the sequence to b, a instead of a, b. Thanks for the comment!
编辑:将序列更改为 b, a 而不是 a, b。感谢您的评论!
EDIT 2: reset the konamiCodePosition to 0 after activateCheats was called. Thanks for the comment!
编辑 2:在调用 activateCheats 后将 konamiCodePosition 重置为 0。感谢您的评论!
回答by Peter
compact version:
紧凑版:
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/')})
回答by Ehsan Kia
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.
在这种情况下,该activate()
函数在触发时被调用。
回答by Goose
Silentdrummer has a good answer. I'm not entirely sure, but I think it could end up taking up too much memory on typing intensive pages. It's good practice to reset. Either way, here's an alternative.
Silentdrummer 有一个很好的答案。我不完全确定,但我认为它最终可能会在输入密集页面时占用太多内存。重置是个好习惯。无论哪种方式,这里都有一个替代方案。
// Cheat Codes
neededkeys = [38,38,40,40,37,39,37,39,66,65], started = false, count = 0;
$(document).keydown(function(e) {
key = e.keyCode;
if (!started) {
if (key == 38) {
started = true;
}
}
if (started) {
if (neededkeys[count] == key) {
count++;
} else {
reset();
}
if (count == 10) {
reset();
// Do your stuff here
alert('Cheat Codes Activated');
$('body').css('background-color', '#FFA8A8');
// Turn down for what
var s=document.createElement('script');
s.setAttribute('src','https://nthitz.github.io/turndownforwhatjs/tdfw.js');
document.body.appendChild(s);
}
} else {
reset();
}
});
function reset() {
started = false;
count = 0;
}
回答by paul.selectable
as a typescript module
作为打字稿模块
const Konami = (() => {
// up, up, down, down, left, right, left, right, b, a, enter
const SEQUENCE: Array<number> = [
38,
38,
40,
40,
37,
39,
37,
39,
66,
65,
13,
];
let head: number = 0;
let isActive: boolean = false;
let callback: Function | undefined;
const start = (cb: Function): void => {
if (isActive) {
return;
}
window.addEventListener("keydown", onKeyDown);
callback = cb;
isActive = true;
};
const stop = (): void => {
if (!isActive) {
return;
}
isActive = false;
window.removeEventListener("keydown", onKeyDown);
};
const onKeyDown = (event) => {
if (event.keyCode === SEQUENCE[head]) {
head++;
if (head === SEQUENCE.length) {
if (callback instanceof Function) {
callback();
}
head = 0;
}
} else {
head = 0;
}
};
return {
start,
stop,
};
})();
export default Konami;
implementation:
执行:
Konami.start(() => { alert("konami sequence entered!"); });
Konami.start(() => { alert("konami sequence entered!"); });
notes:SEQUENCE is an array of the expected inputs. by using the head
var, the order checking and number of correct inputs is maintained. it also provides a simple way to restart if input deviates from the sequence. it also eliminates the needs for a "count" var.
注意:SEQUENCE 是预期输入的数组。通过使用head
var,可以维护顺序检查和正确输入的数量。如果输入偏离序列,它还提供了一种简单的重新启动方法。它还消除了对“计数”变量的需求。
回答by Mage'sFolly
This is a solution I came up with around 3 or 4 years ago. In my case I chose keyUpto keep it separate from any actions that occur from keyDownevents. Also there is no need to specify what keys are allowable since the for loopchecks which key was released against all the keys on the keyboard.
这是我大约 3 或 4 年前提出的解决方案。就我而言,我选择了keyUp以使其与keyDown事件发生的任何操作分开。也没有必要指定哪些键是允许的,因为for 循环会根据键盘上的所有键检查哪个键被释放。
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();
}
回答by StackOverflow
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.
要创建您自己的“Konami 代码”,请在您的 HTML 代码中添加以下代码片段。PS:将 const secretCode 更改为......你想要的任何东西:)。使用当前代码,您必须键入“向上箭头”按钮,然后是“h”,然后是“i”,最后是“向下箭头”按钮。
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>
回答by GammaGames
I really liked Peter's answer, so I made it namespaced and made the callback optional. I also used jquery because I like it ˉ\_(ツ)_/ˉ
我真的很喜欢 Peter 的回答,所以我将它命名为命名空间并使回调成为可选的。我也用过jquery,因为我喜欢它ˉ\_(ツ)_/ˉ
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("????????");
}
else {
return callback();
}
}
if (!Konami.key.indexOf(input)) return;
input = ("" + e.keyCode);
});
}
Konami.offCode = function() {
$(document).off("keydown");
}
Konami.onCode();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>