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>
<html>
<head>
<meta charset="utf-8">
<title>NUMBER GUESSING GAME</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="main">
<div class="board">
<form>
<input type="number" placeholder="Enter a number" name="" id="inputGuess">
<p class="result" id="result"></p>
<button type="button" class="submit">GUESS</button>
</form>
</div>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
Lets add some styles to make it look good
In the index.css add
.board{
display: grid;
width: 400px;
text-align: center;
background: darkcyan;
justify-content: center;
}
input{
padding: 10px;
margin: 10px;
}
button{
color: white;
background: blue;
font-size: 30px;
margin-bottom: 15px;
}
.main{
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
Body
Lets add the following code in the index.js file in the button section
onclick="Guess()"
as
<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.
Thank for making it to this point.