NUMBER GUESSING GAME JAVASCRIPT

NUMBER GUESSING GAME JAVASCRIPT

IS JAVASCRIPT GOOD FOR GAMES ?

WHAT YOU WILL BE LEARNING ?

You will be learning use of "random()" function along with "floor()".

you will be learning the use of "addEventListener()"

you will be learning to generate random number between 1 and 20 and allowing user to enter any random number between 1 and 20.If his guess becomes same as the computer generated number he wins or he will be allowed to guess further.

Hopefully at the end of this article, things will become more clear than they were at the beginning of this article.

If you want to build a WEB GAMES than javascript is at its best.But if you want to build a mobile gaming app then other programming languages are recommended like python.Python is platform independent(cross-platform).

Building a web games with HTML5 is a great choice because it can be runned in all modern browsers.

Requirements For this Number Guessing Game

  • basic knowledge of HTML5.
  • basic knowledge of CSS
  • basic knowledge of Javascript
  • Any source code editor like (notepad++,sublime,atom).

BELOW IS THE SNAPSHOT OF THE GAME.

dodge the ball game

In this step-by-step html5 dodging ball game tutorial we undergo a simple source code of dodging ball game written entirely in pure HTML, CSS, JavaScript.

We will starting with only what is necessary to complete each step.

You will learn how to draw a container(game layout), the balls and collision detection.

In this game the user needs to dodge the provided ball with the other ball.

If he/she fails to do so then they losses the game.

Take it as a source of coding inspiration.

LET'S START THE GAME DEVELOPMENT.

Create a page called "index.html"


        <html>
        	<head>
        		<title>JavaScript Number Guess</title>
        		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1 user-scalable=no">
        		<!-- TODO let the user submit a guess by pressing return -->
            <link href="css/bootstrap.min.css" rel="stylesheet">
            <link href="css/mdb.lite.min.css" rel="stylesheet">
            <link href="css/style.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">

        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

        <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.11/css/mdb.min.css" rel="stylesheet">

          <style>
        	// Adding CSS Code
          </style>
        	</head>
        	<body>
            <div class="container" >
              <div class="row">
                <div class="col-md-12">
        									<div id="game" style="background:#eeff41;-webkit-box-shadow: 10px 10px 15px 0px rgba(0,0,0,0.75);
        					-moz-box-shadow: 10px 10px 15px 0px rgba(0,0,0,0.75);
        					box-shadow: 10px 10px 15px 0px rgba(0,0,0,0.75);">
        								       <h1 class="text-center mb-2 p-2" style="background:#c0ca33;margin:0 auto;width:70%;">GUESS THE CORRECT DIGIT</h1>
        					        		  <div class="p-2" id="statusArea" style="background:#ff4444; border-radius: 23px 23px 23px 23px;-moz-border-radius: 23px 23px 23px 23px;-webkit-border-radius: 23px 23px 23px 23px;border: 0px solid #000000;-webkit-box-shadow: 10px 10px 15px 0px rgba(255,68,68,1);-moz-box-shadow: 10px 10px 15px 0px rgba(255,68,68,1);box-shadow: 10px 10px 15px 0px rgba(255,68,68,1);">
        					        				<p class="text-white">ENTER A NO. BETWEEN 1 AND 20</p>
        					        			</div>
        					              <div class="md-form">
        					               <input type="number" id="userGuess" class="form-control">
        					              </div>
        					            <button  id="buttonArea" class="btn peach-gradient">GUESS</button>
        					      			<div id="historyArea">
        					      				<h2>Your Previous Guesses</h2>
        					            <ul class="list-group">
        					              <li id="historyList" class="list-group-item disabled p-5"></li>
        					            </ul>
        					      			</div>
        							     </div>
        								 </div>
        							 </div>
        						 </div>
            <script>
        		//Adding javascript code
            </script>

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.11/js/mdb.min.js"></script>
        	</body>
        </html>
      
  • A heading is given with "DODGE THE BALLL".
  • A game container is created with the class selector called "container-game".
  • A defender ball is created with the class selector called "ball-1".
  • An opponent ball is created with the class selector called "ball-2".

Below is the snapshot for how the layout looks after dumping the above code in the index.html.

dodge the ball game

The output is nothing but just a sentence called "DODGE THE BALL". The output is quite boring because still we haven't added any CSS and Javascript stuff.

LET'S PUT CSS CODE INSIDE STYLE TAG



  <style>
  body {
  	margin: 10px;
  	background-color: #cccccc;
  	font-family: Arial, sans-serif;
  }

  .button {
  	margin-top: 10px;
  	border-radius: 10px;
  	border-color: #000000;
  	border-style: solid;
  	border-width: 1px;
  	width: 20%;
  	padding: 5px;
  	text-align: center;
  	font-weight: bold;
  }

  #historyArea {
  	margin-top: 10px;
  	padding-left: 5px;
  	padding-right: 5px;
  }

  #game {
  	background-color: #ffffff;
  	border-radius: 10px;
  	border-style: solid;
  	border-width: 3px;
  	border-color: #cccccc;
  	padding: 10px;
  	transition-property: background-color;
  	transition-duration: 3s;
  }

  #statusArea {
  	font-size: 120%;
  }

  #footerArea {
  	text-align: center;
  	margin-top:5px;
  	font-size: 90%;
  	font-style: italic;
  }
  </style>


     

Below is the output after adding CSS code into the page.

dodge the ball game

LET'S PUT JAVASCRIPT CODE INSIDE SCRIPT TAG



 <script>

 var secretNumber = 0,
 	numberOfGuesses = 0;

 function writeMessage(elementId, message, appendMessage) {
 	var elemToUpdate = document.getElementById(elementId);
 	if (appendMessage) {
 		elemToUpdate.innerHTML = elemToUpdate.innerHTML + message;
 	} else {
 		elemToUpdate.innerHTML = message;
 	}
 };

 function newGame() {
 	secretNumber = Math.floor(Math.random() * 20) + 1;
 	numberOfGuesses = 0;
 	writeMessage('historyList', '');
 }


 function userGuessed() {
 	var userGuessed = document.getElementById('userGuess').value;
 	var statusArea = document.getElementById('statusArea');
 	var historyList = document.getElementById('historyList');
 	if (userGuessed.length == 0 || ! (userGuessed > 0 && userGuessed < 20)) {
 		// Nothing entered or our of range.
 		writeMessage('statusArea', '

Please enter a number 1-100 and press the Guess button.

'); } else if (userGuessed.indexOf('.') != -1) { writeMessage('statusArea', '

Please enter a whole number 1-100 and press the Guess button.

'); } else { numberOfGuesses++; if (userGuessed == secretNumber) { // Got it writeMessage('statusArea', '

You got me in ' + numberOfGuesses +' guesses, I was thinking ' + secretNumber + '. Let\'s go again...

'); newGame(); } else if (userGuessed < secretNumber) { // User needs to guess higher writeMessage('statusArea', '

You need to guess higher than ' + userGuessed + ', try again...

'); writeMessage('historyList', '
  • ' + userGuessed +' (too low)
  • ', true); document.getElementById("game").style.backgroundColor="#e74c3c"; } else { // User needs to guess lower writeMessage('statusArea', '

    You need to guess lower than ' + userGuessed + ', try again...

    '); writeMessage('historyList', '
  • ' + userGuessed + ' (too high)
  • ', true); document.getElementById("game").style.backgroundColor="black"; } } document.getElementById('userGuess').value = ''; } window.onload = function() { newGame(); var z = document.getElementById('buttonArea'); z.addEventListener('click', userGuessed); }; </script>

    addEventListener()

    It is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired.

    SYNTAX => "element.addEventListener(event, listener);"

    "event" => vent can be like "click" and "mousedown"

    "Listner" => It can be a JavaScript function which respond to the event occur.

    MATH.RANDOM IN JAVASCRIPT

    In javascript , math.random() is used to get random numbers between 0 and 1.

    To get random number between 1 and 10 multiply it with 10 (math.random() * 10).

    About author
    Supreet Patil
    I am a web developer.I have started the journey of web development two years ago. I have shared a bit of one of mini project.I hope you have loved it.
    E-mail:psupreet12@gmail.com
    Leave a reply

    LEARN MORE

    Below I have given some links to enhance your knowledge.