Create a Reflex Game using JavaScript

A reflex game is a simple fun game that measures your responding speed. It is quite simple to make and understand. We will be designing a reflex game that will calculate your responding speed. The rules are simple just press the stop button when you see the change in background color, and the time you took in doing so will be your speed.
The game provides you a variety of colors to chose from. A faster response will show a better quote of praising than a slower one.
So let us start with the basic HTML Layout.
The HTML Layout:
The HTML layout defines how your page will be looking. This part completely depends on your creativity. Just keep in mind to create a blank white background, so that the change is visible.
Other elements required are:

  1. A header containing the name of the game and some other information.
  2. A form element which could include the select from below option. This is required so that the user can choose from a number of options the particular color it wants.
  3. Two buttons : One for starting the game and the other for pressing the stop button.

Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <title>Reflex Game</title>
</head>
  
<body>
    <center><strong>
      <h1 style="color: black">Reflex Game</h1>
      </strong></center>
        <center>
            <h2>Test your Response time!</h2>
        </center>
        <center>
            <h3>How To Play</h3>
            <p>Click on "Start" first, and wait until the 
              background color changes. As soon as it
              changes, hit "stop!"
            </p>
  
            <br>
            <form name="response">
                Change background color to:
                <select name="bgColorChange">
                    <option selected>deeppink
                        <option>aliceblue
                        <option>crimson
                        <option>darkkhaki
                        <option>cadetblue
                        <option>darkorchid
                        <option>coral
                        <option>chocolate
                        <option>mediumslateblue
                        <option>tomato
                        <option>darkslategray
                        <option>limegreen
                        <option>cornflowerblue
                        <option>darkolivegreen
                </select>
                <br>
                <br>
  
                <input type="button" class="btn"
                       value="Start" onClick="startit()">
                <input type="button" class="btn" 
                       value="Stop" onClick="stopTest()">
            </form>
        </center>
</body>
  
</html>

chevron_right


Note:
This is the most basic HTML Layout. You may add OR remove any other portions into it.
The CSS Styling:
You may add your own custom CSS wherever possible. Here I’ll be just adding some basic CSS to the buttons.
Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

<style>
  input[type=button]
{    
    background-color: #77797c;
    border: none;
    border-radius: 10%;
    color: white;
    padding: 16px 32px;
    text-decoration: none;
    margin: 4px 2px;
    cursor: pointer;
}
  </style>

chevron_right


Main Logic of the game:
The main logic of the game is defined using JavaScript. The JavaScript used here is also quite basic and only a little knowledge of JavaScript would be enough for understanding this.

We’ll be making 5 basic functions for the working of this game:
Step 1:
Starting the game. The start button will be required for this function. This function will be executed once the user presses the Start button.



filter_none

edit
close

play_arrow

link
brightness_4
code

function startTest()
{
    document.body.style.background=document.response.bgColorChange.options[
document.response.bgColorChange.selectedIndex].text;
    bgChangeStarted=true;
    startTime=new Date();
}

chevron_right


Step 2:
The next function will be the remark() function. This function will include the remarks that the game will show on completion of the game.

filter_none

edit
close

play_arrow

link
brightness_4
code

function remark(responseTime)
{
    var responseString="";
    if (responseTime < 0.20)
        responseString="Well done!";
    if (responseTime >= 0.30 && responseTime < 0.20)
        responseString="Nice!";
    if (responseTime >=0.40 && responseTime < 0.30)
        responseString="Could be better...";
    if (responseTime >=0.50 && responseTime < 0.60)
        responseString="Keep practicing!";
    if (responseTime >=0.60 && responseTime < 1)
        responseString="Have you been drinking?";
    if (responseTime >=1)
        responseString="Did you fall asleep?";
  
    return responseString;
}

chevron_right


Step 3:
The next stopTest() function will be executed on pressing the stop button. There can be 3 options that can be executed on pressing the stop button:
First, successful completetion, telling the response time.
Second, if user presses stop button before pressing the start button.
Third, if user presses the stop button before changing of the color.

filter_none

edit
close

play_arrow

link
brightness_4
code

function stopTest()
{
    if(bgChangeStarted)
    {
        endTime=new Date();
        var responseTime=(endTime.getTime()-startTime.getTime())/1000;
  
        document.body.style.background="white";       
        alert("Your response time is: " + responseTime + 
" seconds " + "\n" + remark(responseTime));
        startPressed=false;
        bgChangeStarted=false;
    }
    else
    {
        if (!startPressed)
        {
            alert("press start first to start test");
        }
        else
        {       
            clearTimeout(timerID);
            startPressed=false;             
            alert("cheater! you pressed too early!");
        }               
    }
}

chevron_right


Step 4 :
The fourth function is to get a random response time for changing of the background.

filter_none

edit
close

play_arrow

link
brightness_4
code

function randNumber()
{
    randSeed = (randMULTIPLIER * randSeed + randINCREMENT) % (1 << 31);
    return((randSeed >> 15) & 0x7fff) / 32767;
}

chevron_right


Final Step:
The final function is to ensure that start button is not pressed twice.

filter_none

edit
close

play_arrow

link
brightness_4
code

function startit()
{
    if(startPressed)
    {
        alert("Already started. Press stop to stop");
        return;
    }
    else
    {
        startPressed=true
        timerID=setTimeout('startTest()', 6000*randNumber());
    }
}

chevron_right


Final Demonstration and complete code :

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    
  <style>
  input[type=button]{    
  background-color: #77797c;
    border: none;
    border-radius: 10%;
    color: white;
    padding: 16px 32px;
    text-decoration: none;
    margin: 4px 2px;
    cursor: pointer;
}
  </style>
  
    <title>Reflex Game</title>
</head>
<body><script language="JavaScript">
  
  
var startTime=new Date();
var endTime=new Date();
var startPressed=false;
var bgChangeStarted=false;
var maxWait=20;
var timerID;
  
function startTest()
{
    document.body.style.background=document.response.bgColorChange.options[
document.response.bgColorChange.selectedIndex].text;
    bgChangeStarted=true;
    startTime=new Date();
}
  
function remark(responseTime)
{
    var responseString="";
    if (responseTime < 0.20)
        responseString="Well done!";
    if (responseTime >= 0.30 && responseTime < 0.20)
        responseString="Nice!";
    if (responseTime >=0.40 && responseTime < 0.30)
        responseString="Could be better...";
    if (responseTime >=0.50 && responseTime < 0.60)
        responseString="Keep practicing!";
    if (responseTime >=0.60 && responseTime < 1)
        responseString="Have you been drinking?";
    if (responseTime >=1)
        responseString="Did you fall asleep?";
  
    return responseString;
}
  
function stopTest()
{
    if(bgChangeStarted)
    {
        endTime=new Date();
        var responseTime=(endTime.getTime()-startTime.getTime())/1000;
  
        document.body.style.background="white";       
        alert("Your response time is: " + responseTime +
    " seconds " + "\n" + remark(responseTime));
        startPressed=false;
        bgChangeStarted=false;
    }
    else
    {
        if (!startPressed)
        {
            alert("press start first to start test");
        }
        else
        {       
            clearTimeout(timerID);
            startPressed=false;             
            alert("cheater! you pressed too early!");
        }               
    }
}
  
var randMULTIPLIER=0x015a4e35;
var randINCREMENT=1;
var today=new Date();
var randSeed=today.getSeconds();
function randNumber()
{
    randSeed = (randMULTIPLIER * randSeed + randINCREMENT) % (1 << 31);
    return((randSeed >> 15) & 0x7fff) / 32767;
}
  
function startit()
{
    if(startPressed)
    {
        alert("Already started. Press stop to stop");
        return;
    }
    else
    {
        startPressed=true; 
        timerID=setTimeout('startTest()', 6000*randNumber());
    }
}
// --> 
    </script>
        <center><strong><h1 style="color: black">Reflex Game</h1></center></strong>
        <center>
        <h2>Test your Response time!</h2>
        </center>
        <center><h3>How To Play</h3>
        <p>Click on "Start" first, and wait until the
 background color changes. As soon as it changes, hit "stop!"
        </p>
  
        <br>
        <form name="response">
        Change background color to: 
        <select name="bgColorChange">
        <option selected>deeppink
        <option>aliceblue
        <option>crimson
        <option>darkkhaki
        <option>cadetblue
        <option>darkorchid
        <option>coral
        <option>chocolate
        <option>mediumslateblue
        <option>tomato
        <option>darkslategray
        <option>limegreen
        <option>cornflowerblue
        <option>darkolivegreen
        </select><br>
        <br>
  
        <input type="button" class="btn" value="Start" onClick="startit()">
        <input type="button" class="btn" value="Stop" onClick="stopTest()">
        </form>
        </center>
  
  
    </body>
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.