Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function only by correct series of keys

I'm not exactly into this professionally, but just out of curiosity since only VERY recently. Thus I only have the most basic OF basic knowledge.

My current experiment is this; can you program a series of keys, to execute a specific function, and only in the correct order? I'm saying like a game combo (ie: the famous Konami Code easter egg, consisting of '↑', '↑', '↓', '↓', '←', '→', '←', '→', 'B', 'A', and 'Start')

If, say, I use 'onkeydown' to do this, it only registers that one key, not taking into regard any keys pressed earlier or after (or so I believe). If not, I would have to somehow record what came before and... waaaay out of my little fishies league.

Is there a way to do such a thing, hopefully simpler and easier? Please don't expect me to know much, and please no JQuery or another such js library :D usage.

Could you script in the Konami Code as an example? The js char codes for this pattern would be 38 38 40 40 37 39 37 39 66 65 13, replacing the Nintendo 'Start' with 'Enter' key.

like image 378
Terrornado Avatar asked Nov 29 '25 17:11

Terrornado


2 Answers

Here's a working example, if you mess up, you can simply restart the sequence and it will forgive you. Also, if you want a different combination, just change "keys".

<!DOCTYPE html>
<html>
<head>
<script>
var keys=[38,38,40,40,37,39,37,39,66,65];
var buff=[];
function collect(e){
  buff.push(e.keyCode);
  if(buff.length>keys.length){
    buff=buff.splice(1);
  }
  if(keys==buff.toString()){ 
    alert("Let's Play!");
  }
  e.preventDefault();
  e.stopPropagation();
}
</script>
</head>
<body>
<DIV contenteditable=true onkeydown="collect(event)">Click here to accept keystrokes</DIV>
</body>
</html>

I put the key capture in a DIV, but you can add it to the document.body instead and it will listen everywhere on the page.

like image 159
alfadog67 Avatar answered Dec 01 '25 07:12

alfadog67


Just listen for keys and compare against something :

var konami = [38,38,40,40,37,39,37,39,66,65],
    pushed = [];

document.onkeyup = function(e) {
    pushed.push(e.which);

    for (var i=0; i<pushed.length; i++) {
        if (pushed[i] != konami[i]) pushed = [];
    }

    if (pushed.length == konami.length) alert('konami code');
}

FIDDLE

like image 24
adeneo Avatar answered Dec 01 '25 07:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!