Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

progressive konami code

Tags:

javascript

I am trying to create a .js file for a website that upon entering the konami code Up, Up, Down, Down, Left, Right, Left, Right, B, A, Start(enter) it will embed a video. However while entering the right keys the webpage should display something like "keep going", if a wrong key is entered it should display "wrong, try again", and allow them to start over.

I've manged to get the JavaScript working where upon entering the right code it displays an alert, and entering the wrong code displays a different code.

i've manged to get this much code using online resources but none of them explain how to get wrong, try again 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.

like image 605
Calsolum Avatar asked Mar 12 '12 16:03

Calsolum


2 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"); 
        }
   });
}
like image 123
Prescott Avatar answered Oct 31 '22 21:10

Prescott


You could 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/

like image 44
Nicola Peluchetti Avatar answered Oct 31 '22 22:10

Nicola Peluchetti