Creating a Click Speed Test Game in HTML5
Published: 2020-02-27 07:50:17

HTML5, linked with the JavaScript programming language, it is the perfect solution to reach as several users who are interested in designing games in HTML5. The only limit now is the developers’ imagination and logic. 

In this tutorial, I suggest you design a game where the user will have to click a maximum number of times in 10 seconds. This game, named <a href="https://cpstest.org/">CPS Test</a> (click speed test), with simple rules will allow you to discover how to create your first little game in HTML5 with JavaScript.


#Rules for Click Speed Test Game:

As we stated in the introduction, the rules for Click Speed Test Game are quite simple. The aim for the user will be to click the maximum number of times within 10 seconds. 

- A click area box for letting the user to click a maximum number of times.
- A score area above the box where we will display a timer, the number of clicks and also the number of clicks done by the user within a given time frame.
- A logo for our game. It will be very interesting if you use logo for your game.


#Creating the HTML page

First, we start by creating the HTML page. It will contain the following details:

- A logo of our game
- A div for the scoring area with 3 span tags for refreshing the timer, the score, and clicks by seconds
- A div for the click area. We will add a button inside that div to let the user to start the game when he will click on the button.

For developing the rendering of the HTML page, we are going to write some CSS. Nothing out of the ordinary. The principal things to remember from the CSS part are as follows:

- The use of the user-select property set to none for avoiding selection of content when the user will click in the click area.
- The position property of the click area set to relative to let us center the start button inside it.
- The use of box-shadow property for the start button to customize it in a fancy way.


#Following is the HTML with CSS codes:


<html>	 
  
<head>	 
  
<title>Click Speed Game in HTML5</title>
 
  
<style type="text/css">

  
 #content {
 
  
 width: 200px;
  
 border: 1px dashed #dc0000;
	 
  
 font-size: 20px;
	 
  
 text-align: center;
	 
  
 margin: 0 auto;
	 
  
 margin-top: 50px;
	 
  
 padding: 20px;
	 
  
 user-select: none; 
  
 }
 
  
 	 
  
 #clickarea {	 
  
 width: 500px;	 
  
 height : 300px;	 
  
 border: 2px solid #dc0000;
 
  
 font-size: 20px;
	 
  
 text-align: center;
	 
  
 margin: 0 auto;
	 
  
 margin-top: 50px;
	 
  
 padding: 20px;
	 
  
 position: relative;
	 
  
 }	 
  
 	 
  
 #logo {
	 
  
 width: 200px;
	 
  
 height: 200px;
	 
  
 margin: 0 auto;
	 
  
 margin-top: 50px;
	 
  
 display: block;
	 
  
 user-select: none;
	 
  
 }	 
  
 	 
  
 #start {
	 
  
 position: absolute;
	 
  
 top: 50%; left: 50%;
	 
  
 transform: translate(-50%,-50%);
	 
  
 border: 0;
 
  
 line-height: 2.5;
	 
  
 padding: 0 20px; 
  
 font-size: 1rem;
 
  
 text-align: center;
	 
  
 color: #fff;
	 
  
 text-shadow: 1px 1px 1px #000;
 
  
 border-radius: 10px;
 
  
 background-color: rgba(220, 0, 0, 1);
 
  
 background-image: linear-gradient(to top left,
 
  
 rgba(0, 0, 0, .2),

  
 rgba(0, 0, 0, .2) 30%,
 
  
 rgba(0, 0, 0, 0));
 
  
 box-shadow: inset 2px 2px 3px rgba(255, 255, 255, .6),
 
  
 inset -2px -2px 3px rgba(0, 0, 0, .6);

 } 
  
 	 
  
 #start:hover {
 
  
 background-color: rgba(255, 0, 0, 1);
 
  
 } 
  
 	 
  
 #start:active {
 
  
 box-shadow: inset -2px -2px 3px rgba(255, 255, 255, .6),
 
  
 inset 2px 2px 3px rgba(0, 0, 0, .6);
 
  
 } 
  
 	 
  
</style>
 
  
</head>
 
  
<body>
 
  
 <img id="logo" src="cursor.png" />
 
  
 <div id="content">
 
  
 Timer: <span id="timer"></span><br/>
	 
  
 Score: <span id="score"></span><br/>

  
 Clicks/s: <span id="clicks"></span>
 
  
 </div>
 
  
 <div id="clickarea">
 
  
 <button id="start">Start</button>
	 
  
 </div>
 
  
</body>
	 
  
</html>


#Writing the logic of the Game in JavaScript

Our CPS Test Game looks great. Now, it’s time to address the logic of the game in JavaScript.


#Defining Followers:

- Store the score with the current number of clicks done by the user
- Set the duration of the game, named as duration. We set the value to 10 seconds.
- StartTime to save the start time of the game in milliseconds
- Ended which is a boolean indicating if the game is finished or not.


Then, we get DOM sources for the different HTML elements of our page we will need to update (timer, score, clicks by seconds, …).


#Starting the game:
The subsequent step is to write the code for the start game function. This function will be called when the user clicks the start button and start the game. Inside it, we hide the start button, we start the score and we show the game has started by setting the ended variable to false.

One of the most important parts of the game is the timer. Indeed, it will make the time growth during the game. We create a timer by using the set Interval function provided by JavaScript in the standard. We define a callback function inside the setInterval function which will be called each 1 millisecond.


Inside this callback, we have two possibilities:
- The timer has reached the duration of the game. If so, we mark the game as ended, we clear the timer by calling the clear interval function and we call the endGame function.
- The timer has not reached the duration of the game. If so, we update the time span with the current value of the timer and we update the clicks by seconds span.


#It gives us the following code for the start game function:

function startGame() {	 
  
 // we hide the start button	 
  
 hide(startBtn);	 
  
 score = -1;	 
  
 ended = false;	 
  
 // we get start time	 
  
 startTime = new Date().getTime();	 
  
 	 
  
 // we create a timer with the setInterval method	 
  
 var timerId = setInterval(function() {	 
  
 var total = (new Date().getTime() - startTime) / 1000;	 
  
 	 
  
 // while total lower than duration, we update timer and the clicks by seconds	 
  
 if (total < duration) {	 
  
 timerTxt.textContent = total.toFixed(3);	 
  
 clicksTxt.textContent = (score / total).toFixed(2);	 
  
 } else {	 
  
 // otherwise, the game is ended, we clear interval and we set game as ended	 
  
 ended = true;	 
  
 clearInterval(timerId);	 
  
 // we call the end game method	 
  
 endGame();	 
  
 }	 
  
 }, 1);	 
  
}



#Ending the game:

When the game is ended, the EndGame function is triggered. In that function, we write the final count for the score and the clicks by seconds of the current game. Then, we show the start button again to let the user start a new game if he wants. And then, we display an alert message to the player.

Following code for endgame function:
function endGame() {	 
  
 // we write final stats	 
  
 var clicsBySeconds = (score / duration).toFixed(2);	 
  
 timerTxt.textContent = duration.toFixed(3);	 
  
 clicksTxt.textContent = clicsBySeconds;	 
  
 // we show start button to play another game	 
  
 show(startBtn);	 
  
 	 
  
 // we display the result to the user in delayed mode 	 
  
 // to update DOM elements just before the alert	 
  
 setTimeout(function() {	 
  
 alert('You made ' + score + ' clicks in ' + duration + 	 
  
 ' seconds. It is ' + clicsBySeconds + ' clicks by seconds. Try again!');	 
  
 }, 10);	 
  
}


#Adding Click Event listeners:

The last step is to add the Click Event listeners. One is added for the start button letting us call the start game function when the player will click on it. The second is added to the click-box area. If the game is started, we renew the score by one when the player clicks. And we do not forget to update the score span with the news score.

Following code for Click Event Listener:
// we set a click event listener on the start button	 
  
startBtn.addEventListener("click", function(e) {	 
  
 startGame();	 
  
});	 
  
 	 
  
// we add a click event listener on the click 	 
  
// area div to update the score when the user will click	 
  
clickArea.addEventListener("click", function(e) {	 
  
 if (!ended) {	 
  
 score++;	 
  
 scoreTxt.textContent = score;	 
  
 }	 
  
});



#Complete source code for the CPS Test Game:

After assembling all parts of the code, we get the final code as follow:
<html>
	 
  
<head>
	 
  
<title>Click Speed Game in HTML5</title>
 
  
<style type="text/css">
 
  
 #content {

  
 width: 200px;
	 
  
 border: 1px dashed #dc0000;
	 
  
 font-size: 20px;
 
  
 text-align: center;
	 
  
 margin: 0 auto;
 
  
 margin-top: 50px;
	 
  
 padding: 20px;
 
  
 user-select: none;
 
  
 } 
  
		 
  
 #clickarea {
 
  
 width: 500px;
	 
  
 height : 300px;
 
  
 border: 2px solid #dc0000;
 
  
 font-size: 20px;
 
  
 text-align: center;
 
  
 margin: 0 auto;
 
  
 margin-top: 50px;
 
  
 padding: 20px;
	 
  
 position: relative;
	 
  
 }	 
  
		 
  
 #logo {
 
  
 width: 200px;
 
  
 height: 200px;
	 
  
 margin: 0 auto;
	 
  
 margin-top: 50px;
 
  
 display: block;
 
  
 user-select: none;
	 
  
 }
 
  
		 
  
 #start {
 
  
 position: absolute;
 
  
 top: 50%; left: 50%;<br>	 
  
 transform: translate(-50%,-50%);<br>	 
  
 border: 0;<br>	 
  
 line-height: 2.5;<br>	 
  
 padding: 0 20px;<br>	 
  
 font-size: 1rem;<br>	 
  
 text-align: center;<br>	 
  
 color: #fff;<br>	 
  
 text-shadow: 1px 1px 1px #000;<br>	 
  
 border-radius: 10px;<br>	 
  
 background-color: rgba(220, 0, 0, 1);<br>	 
  
 background-image: linear-gradient(to top left,<br>	 
  
 rgba(0, 0, 0, .2),<br>	 
  
 rgba(0, 0, 0, .2) 30%,<br>	 
  
 rgba(0, 0, 0, 0));<br>	 
  
 box-shadow: inset 2px 2px 3px rgba(255, 255, 255, .6),<br>	 
  
 inset -2px -2px 3px rgba(0, 0, 0, .6);<br>	 
  
 }<br> 
  
		 
  
 #start:hover {<br> 
  
 background-color: rgba(255, 0, 0, 1);<br>	 
  
 }<br>	 
  
		 
  
 #start:active {<br>	 
  
 box-shadow: inset -2px -2px 3px rgba(255, 255, 255, .6),<br>	 
  
 inset 2px 2px 3px rgba(0, 0, 0, .6);<br>	 
  
 }<br>	 
  
 	 
  
</style><br>	 
  
</head><br>	 
  
<body><br>	 
  
 <img id="logo" src="cursor.png" /><br>	 
  
 <div id="content"><br>	 
  
 Timer: <span id="timer"></span><br/>	 
  
 Score: <span id="score"></span><br/>	 
  
 Clicks/s: <span id="clicks"></span><br>	 
  
 </div><br>	 
  
 <div id="clickarea"><br>	 
  
 <button id="start">Start</button><br>	 
  
 </div><br>	 
  
 <script type="text/javascript"><br>	 
  
 var score; // to store the current score<br>	 
  
 var duration = 10; // 10 seconds<br>	 
  
 var startTime; // start time<br>	 
  
 var ended = true; // boolean indicating if game is ended<br>	 
  
 // we get DOM References for some HTML elements<br>	 
  
 var timerTxt = document.getElementById("timer");<br>	 
  
 var scoreTxt = document.getElementById("score");<br>	 
  
 var clicksTxt = document.getElementById("clicks");<br>	 
  
 var startBtn = document.getElementById("start");<br>	 
  
 var clickArea = document.getElementById("clickarea");<br>	 
  
 	 
  
 // we define two functions for showing or hiding a HTML element<br>	 
  
 var show = function(elem) {<br>	 
  
 elem.style.display = 'inline';<br>	 
  
 };<br>	 
  
 	 
  
 var hide = function(elem) {<br>	 
  
 elem.style.display = 'none';<br>	 
  
 };<br>	 
  
 	 
  
 // Method called when the game starts<br> 
  
 function startGame() {<br>	 
  
 hide(startBtn);<br> 
  
 score = -1;<br>	 
  
 ended = false;<br>	 
  
 // we get start time<br>	 
  
 startTime = new Date().getTime();<br>	 
  
 	 
  
 // we create a timer with the setInterval method<br>	 
  
 var timerId = setInterval(function() {<br>	 
  
 var total = (new Date().getTime() - startTime) / 1000;<br>	 
  
 	 
  
 // while total lower than duration, we update timer and the clicks by seconds<br>	 
  
 if (total < duration) {<br>	 
  
 timerTxt.textContent = total.toFixed(3);<br>	 
  
 clicksTxt.textContent = (score / total).toFixed(2);<br>	 
  
 } else {<br>	 
  
 // otherwise, the game is ended, we clear interval and we set game as ended<br>	 
  
 ended = true;<br>	 
  
 clearInterval(timerId);<br>	 
  
 // we call the end game method<br>	 
  
 endGame();<br>	 
  
 }<br>	 
  
 }, 1);<br>	 
  
 }<br>	 
  
 	 
  
 // end game method<br>	 
  
 function endGame() {<br>	 
  
 // we write final stats<br>	 
  
 var clicsBySeconds = (score / duration).toFixed(2);<br>	 
  
 timerTxt.textContent = duration.toFixed(3);<br>	 
  
 clicksTxt.textContent = clicsBySeconds;<br>	 
  
 // we show start button to play another game<br> 
  
 show(startBtn);<br>	 
  
 	 
  
 // we display the result to the user in delayed mode<br> 	 
  
 //to update DOM elements just before the alert<br>	 
  
 setTimeout(function() {<br>	 
  
 alert('You made ' + score + ' clicks in ' + duration +<br> 	 
  
 ' seconds. It is ' + clicsBySeconds +<br> 	 
  
 ' clicks by seconds. Try again!');<br>	 
  
 }, 10);<br>	 
  
 }<br>	 
  
 	 
  
 // we set a click event listener on the start button<br>	 
  
 startBtn.addEventListener("click", function(e) {<br>	 
  
 startGame();<br>	 
  
 });<br>	 
  
 	 
  
 // we add a click event listener on the click area div to update the score when the user will click<br>	 
  
 clickArea.addEventListener("click", function(e) {<br>	 
  
 if (!ended) {<br>	 
  
 score++;<br>	 
  
 scoreTxt.textContent = score;<br>	 
  
 }<br>	 
  
 });<br>	 
  
</script><br>	 
  
</body><br>	 
  
</html><br>



#Our CPS Test Game in Action:
The best part of the tutorial is there since we are going to play to our CPS Test Game! You can play here:

#To go further
To go further, you could add some additional features to the Click Speed Test Game like:

- Saving of the best score for the local player by using the HTML5 Web Storage API.
- A multiplayer version of the game by using the HTML5 WebSocket API.
- A global leaderboard for the game by storing the scores in a database at the server and by making a Web API for managing the scores.

Like you can observe, the possibilities for improving the CPS Test Game are various features.