evolving konami sequence

I am working on creating a .js file for a website that will trigger the embedding of a video when the konami code is entered: Up, Up, Down, Down, Left, Right, Left, Right, B, A, Start (enter). While entering the correct keys, the webpage should display a message like "keep going". If a wrong key is entered, it should display "wrong, try again" and allow the user to start over.

So far, I have managed to make the JavaScript work such that it displays an alert when the correct code is entered and a different alert for incorrect codes. However, I'm struggling with implementing the part where it prompts the user to try again upon entering the wrong code.


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 assistance would be highly appreciated.

Answer №1

if (document.addEventListener) {
    var count = 0;
    var code = [38,38,40,40,37,39,37,39,66,65,13];

    document.addEventListener("keydown", function(e){
        if (e.keyCode === code[count])
        {
            count++; //valid key at the valid point

            if (count == code.length)
            {
                alert("Access Granted");
            } else {
                alert("Keep going");
            }
        } else {
            // incorrect input, restart
            count = 0;
            alert("Wrong Code"); 
        }
   });
}

Answer №2

If you're looking for a fun interactive element to add to your website, consider implementing a Konami code easter egg. This JavaScript code snippet allows users to input the famous Konami cheat code by pressing specific keys on their keyboard.

 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);
};

Check out this live demonstration on JSFiddle.

Answer №3

Here is a simple solution that works for me:

const konamiCode = "38,38,40,40,37,39,37,39,66,65,13";
let keysEntered = [];
const konamiArr = konamiCode.split(',');

window.addEventListener("keydown", function(e){
    keysEntered.push(e.keyCode);

    const position = keysEntered.length - 1;

    if(keysEntered[position] !== konamiArr[position])
    {
        alert('Incorrect');
        keysEntered = [];
    }
    else if (keysEntered.join(',') === konamiCode) 
    {            
       alert('Correct! Konami code entered successfully.');
        keysEntered = [];
    };
}, true);

View the jsFiddle example here

Answer №4

Receiving an alert with each keystroke can be disruptive. A better approach would be to have a DIV display validated correct answers and only trigger an alert for incorrect ones.

function checker(){

     if (kc==11){

        kc=0;  // Reset the sequence. 

        // Add your desired function here. 
      }
     }

     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 keys on the keyboard.

     var kx=konamicode[kc]; // Represents current position in the code sequence.

     var res=document.getElementById('response');
     var dumb=wrong[kc];

      if (keynum==i){

 // Check if key matches sequence, reset sequence if it doesn't.

      if (i!=kx){
                 res.innerHTML='';
                 alert(dumb); // Alert user of mistake and reset sequence.
                 kc=0;
                 } 
             else {
             res.innerHTML=right[kc];   // Congratulate user and advance sequence.
             kc++;
             }

       }
     }
   checker();
       }

document.onkeyup = keyUp;

To show validated keystrokes, add a DIV in the body of the page.

<div id="response"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to assign innerHTML values to table cells using PHP?

I'm currently building a website that relies on a database to store information. I have created an array to hold the values retrieved from the database, and now I need to populate a table with these values. Each cell in the table has a numerical ID ra ...

Guide to automating tests on MAC using Protractor with Appium and IOS-Simulator

Is there a way to run automated tests using Protractor (or WebDriverJS) on a MAC with Appium and the IOS Simulator? We have been unsuccessful in running tests with the following configuration file, although it works fine with Selenium 2.0 - WebDriver. He ...

Content within Drawer featuring Material UI Scrollable Tabs

I am currently utilizing a material-ui drawer with the mini variant drawer structure. Inside this drawer, I have incorporated a series of tabs utilizing the prevent scroll buttons tabs design. The version of material-ui being used is 4.12.3. Regrettably, ...

Sorting an array using the Insertion sort algorithm in JavaScript / An undefined function

Currently, I am in the process of developing a JavaScript file that includes an insertion sort function, a method to validate a sorted array and return true or false, and a reverse insertion sort function that operates from the end of the array index towar ...

Ways to update state based on changes in localStorage values

Is there a way to update the state when the value of localStorage changes? For instance, I have a language switch button for French and English. When I click on English, it gets stored in localStorage. How can I ensure that the entire project switches to t ...

capturing the HTML title and storing it in a JavaScript variable

Is there a way to retrieve the title "Some Name" in the JS file and have it be populated by the hyperlink's title attribute, which is set to "sometitle" in the HTML code? JS var randomtext={ titleText:"Some Name",} HTML <a class="css" title="so ...

What is the best way to determine the quantity of request query parameters in an express.js application?

Currently, I find myself needing to individually verify each potential parameter. if (req.query.param1 !== undefined ) { } if (req.query.param2 !== undefined ) { } if (req.query.param3 !== undefined ) { } ... ...

Is the MUI Drawer Open 20% of the Time?

One issue I'm facing is with my MUI drawer - it's supposed to close after a menu item is clicked, but sometimes, about 1 out of 5 times, it remains open. I have based my current code on a helpful post on Stack Overflow. Take a look at the code s ...

JavaScript, specifically in the VueJS framework, consistently defaults to utilizing the final value within a

Describing my issue, I am using a for loop to extract elements from an array and assign them to a JSON value. It looks something like this: hotel={ rooms: 2, price: [ 100, 200 ], occupation: [ '1 child', '1 adult' ] I aim to push thi ...

Transfer picture information to the server on Internet Explorer versions 8 and 9

When it comes to sending image data to a server in FF and Chrome, we can use the following code: canvas.toDataURL("image/png"); This base 64 string is then decoded and extracted on the server. However, I am currently facing an issue with IE. Right now, t ...

Modify website styling using JavaScript to edit external CSS/SCSS files

I am looking to 'modify' a file that is stored on my server, for example: <link rel="stylesheet" href="css/plugin.scss"> Not only that, but I also want to specifically edit a line within the SASS file. In SASS, you can declare variables i ...

Choose specific GeoJSON elements using a mouse click - OpenLayers 3

I'm working with GeoJSON features that consist of multiple smaller features. When I hover over one of them, I'm hoping to have the entire layer selected, rather than just a portion of it. I'm not sure where to begin in order to make this ha ...

Arranging radio input options in alphabetical order

My attempts to alphabetically sort these items are not working as expected. Could you help me identify why it's not functioning correctly? You can check out my jsFiddle example by following this link. handleAlphaOrder = fun ...

Comparing mustache.js and dust.js: How can I select my list of schools?

I am currently experiencing difficulties with the High School and College arrays within the schools object when you check out my code on . Despite knowing that Mustache and Dust are logic-less, does this mean I am unable to incorporate logic when working ...

What is the best way to ensure a multi-page form is validated using HTML5 and JavaScript before progressing to the next page?

Currently, there are two functionalities at play. The submit button is not being recognized while the functionality in JS $(".next").click(function(){..} is working as expected. HTML This section involves 4 fieldsets. I am attempting to validate ...

Similar to the filter() method in Vanilla Javascript but behaves in a equivalent way to

Looking to convert some JQuery code to Vanilla JS. $('#myID :not(a, span)').contents().filter( function() { return this.nodeType === 3 && this.data.trim().length > 0;}) .wrap('<span class="mySpanClass" />'); I&a ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

Precommit hook failing to activate despite errors occurring

"scripts": { "precommit": "pretty-quick --staged & npm run lint & npm run test", "lint": "eslint 'src/**/*.{js,jsx}' --quiet --fix", "test": "cross-env CI=true react-scripts test --env=jsdom --coverage" } https://i.sstatic.net/M ...

Exploring ways to retrieve texture dimensions using Three.js

Can someone please advise me on how to retrieve the dimensions of a texture? I have set my texture using the following line of code: const texture = THREE.ImageUtils.loadTexture(src) Do I need to load the image in order to obtain its dimensions (and can ...

React does not support the map function

I've been struggling for three days to figure out why I am unable to place multiple elements in an array. Interestingly, when I try to access only one element using this.state.dat.nombre or dat.carrera, it works perfectly fine. However, when I attempt ...