The Wayback Machine - https://web.archive.org/web/20240613230535/https://www.geeksforgeeks.org/create-a-reflex-game-using-javascript/
Open In App

Create a Reflex Game using JavaScript

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 choose 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: 

html




<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>


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: 

html




<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>


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. 

javascript




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


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. 

javascript




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


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. 

javascript




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


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

javascript




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


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

javascript




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


Final Demonstration and complete code : 

html




<!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>


Output:



Similar Reads

Create a Minesweeper Game using HTML CSS & JavaScript
Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript. Preview of final output: Let us have a look at how
4 min read
Create a Bingo Game Using JavaScript
Bingo is a fun and popular game that relies on luck and strategy. In this tutorial, we'll show you how to make a simple Bingo game using JavaScript. Whether you're a beginner or just looking for a fun project, this guide will walk you through the process step by step. Prerequisites:HTMLCSSJavaScriptApproach:Before diving into the code, it's essenti
7 min read
Create a snake game using HTML, CSS and JavaScript
Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over. Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prerequisites:HTMLCSSJavaScriptApproachSelect the board
4 min read
Create a 2D Brick Breaker Game using HTML CSS and JavaScript
In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS &amp; JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is basically a classic arcade-style game where the us
8 min read
Create a Simon Game using HTML CSS & JavaScript
In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over. PrerequisitesHTMLCSSJavaScriptApproachCreate the different HT
5 min read
Create a Monty Hall game in Vanilla JavaScript
Monty Hall problem is a popular probability puzzle based on a television game show and named after its host, Monty Hall. In this Monty Hall game, There will be three closed doors and you will be given a choice to choose one of them. Behind one of the doors, there is a car and behind the other doors, goats. The host knows about the placement of the
10 min read
Create Magic Eight Ball Game in HTML CSS & JavaScript
We are to assume that the person will give us a question as input and once the input question comes in, The Magic Eight ball generates a random answer to the question. We will add a feature where in case of no input the ball says, "Sorry but I can't work with that". Preview Image: How the game will work?Firstly, We will take a question input that i
7 min read
Create a Math Sprint Game in HTML CSS & JavaScript
The math sprint game presents random math questions with four options. Players click the correct answer, and if correct, it's acknowledged; otherwise, an incorrect answer message is shown. A 20-second timer adds urgency, ending the game. The score (High Score) is displayed, along with buttons to start or restart the game. ApproachFirst, we make a f
5 min read
Create a Tic-Tac-Toe Game using jQuery
In this post, we are going to implement 2-player tic-tac-toe using jQuery. It is quite easy to develop with some simple validations and error checks. Player-1 starts playing the game and both the players make their moves in consecutive turns. The player who makes a straight 3-block chain wins the game. Here, we'll be implementing this game on the f
5 min read
Create Rock Paper Scissor Game using ReactJS
In this article, we will create Rock, Paper, Scissors game using ReactJS. This project basically implements class components and manages the state accordingly. The player uses a particular option from Rock, Paper, or Scissors and then Computer chooses an option randomly. The logic of scoring and winning is implemented using JSX. Let's have a look a
4 min read