Progressive code code

I am trying to create a .js file for a website that, by entering the code with the keys Up, Up, Down, Down, Left, Right, Left, Right, B, A, Start (enter), will insert a video, However, when entering the correct The web page should display something like โ€œkeep movingโ€, if the wrong key is entered, it should display โ€œincorrect, try againโ€ and allow them to start working.

I was able to process JavaScript when when I enter the correct code, it displays a warning, and entering the wrong code displays a different code.

I managed to get this code using online resources, but none of them explains how to make a mistake, try again a part

if (window.addEventListener) { var keys = [], konami = "38,38,40,40,37,39,37,39,66,65,13"; window.addEventListener("keydown", function(e){ keys.push(e.keyCode); if (keys.toString().indexOf(konami) >= 0) { alert('Right'); keys = []; }; if (keys.toString().indexOf(konami) < 0) { alert('Wrong'); keys = []; } }, true); 

};

Any help would be greatly appreciated.

+6
source share
3 answers
 if (window.addEventListener) { var index = 0; var konami = [38,38,40,40,37,39,37,39,66,65,13]; window.addEventListener("keydown", function(e){ if (e.keyCode === konami[index]) { index++; //valid key at the valid point if (index == konami.length) { alert("Correct"); } else { alert("Keep going"); } } else { // incorrect code restart index = 0; alert("Wrong"); } }); } 
+7
source

You can do something like

  if (window.addEventListener) { var keys = [], konami = "38,38,40,40,37,39,37,39,66,65,13".split(','); window.addEventListener("keydown", function(e){ keys.push(e.keyCode); console.log(e.keyCode); var lengthOfKeys = keys.length -1; if (konami[lengthOfKeys] == keys[lengthOfKeys]) { alert('Right'); if(konami.length === keys.length){ alert('complete!'); } }else{ alert('Wrong'); keys = []; } }, true); }; 

fiddle here http://jsfiddle.net/b6kuZ/

+2
source

This works for me:

 if (window.addEventListener) { var keys = [], konami = "38,38,40,40,37,39,37,39,66,65,13"; konami_arr = konami.split(','); window.addEventListener("keydown", function(e){ keys.push(e.keyCode); var position = keys.length-1; if(keys[position ] != konami_arr[position]) { alert('Wrong'); keys = []; } else if (keys.join(',') == konami) { alert('Right'); keys = []; }; }, true); } 

jsFiddle exmaple

0
source

Source: https://habr.com/ru/post/910520/


All Articles