Nairobi, Kenya

How to use math function to create a JavaScript game – partb

How to use math function to create a JavaScript game – part b

Having built the logic on part- a lets now build the user interface.

Our user interface is going to have three parts

  • The user input form
  • A button
  • Text display part

In the index.html part add the following

<!DOCTYPE html>
	<meta charset="utf-8">
	<title>NUMBER GUESSING GAME</title>
	<link rel="stylesheet" type="text/css" href="index.css">
<div class="main">
	<div class="board">
			<input type="number" placeholder="Enter a number" name="" id="inputGuess">
			<p class="result" id="result"></p>
			<button type="button"  class="submit">GUESS</button>
<script type="text/javascript" src="index.js"></script>


Lets add some styles to make it look good

In the index.css add

	display: grid;
	width: 400px;
	text-align: center;
	background: darkcyan;
	justify-content: center;
	padding: 10px;
	margin: 10px;

	color: white;
	background: blue;
	font-size: 30px;
	margin-bottom: 15px;

	justify-content: center;
	display: grid;
	margin-top: 10%;

We are done with styling the user interface lets connect the logic using the user interface


In the index.js lets have


Lets add the following code in the index.js file in the button section



<button onclick="Guess()" class="submit">GUESS</button>

So we are going to create a function called Guess()

Then in the function we will use conditional statements to check if a number is larger,smaller or equal to the number guessed.

JavaScript program

In creating this game we are going to use the JavaScript math function we had used in part a

const guessNumber = Math.floor(Math.random() * 100)

    const Guess = () =>{
      let guessValue = inputGuess.value
      if (guessValue === guessNumber) {
        document.getElementById("result").innerHTML = "You win"
      } else if (guessValue >guessNumber ) {
        document.getElementById("result").innerHTML = "Your guess was " + guessValue + ". Too high. You loose Try Again!"
      } else if (guessValue < guessNumber ) {
       document.getElementById("result").innerHTML = "Your guess was " + guessValue + ". Too low. You loose Try Again!"

We are done with connecting our logic with the user interface

You can play this game with your friend but Play at your own risk.

final UI

Thank for making it to this point.