How to make a guessing game in JavaScript
source link: https://dev.to/heheprogrammer/how-to-make-a-guessing-game-in-javascript-4c6c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to make a guessing game in JavaScript
Aug 15
・2 min read
So in this tutorial we are going to make a simple number guessing game which will generate a random number between 0 - 10 ( you can set the max number to whatever you want ) and then if the user guess the correct number it will show or else wrong answer will be shown.
Join my discord server and talk with many programmers in there
- First 25 people to join will get special role
<input type="text" placeholder="Your Guess" id="inputfield">
<button id="inputsubmit">Submit</button>
<!-- The results will be shown here -->
<div id="result"></div>
const inputfield = document.getElementById('inputfield')
const inputsubmit = document.getElementById('inputsubmit')
const result = document.getElementById('result')
const random = Math.floor(Math.random() * 10)
inputsubmit.addEventListener('click', () => {
const inputvalue = inputfield.value
const input = parseInt(inputvalue)
if ( random === input ) {
result.innerText = "Correct answer"
} else {
result.innerText = "Wrong answer"
}
})
Play the upgraded number guessing game made by me
ok so in html we only make a input field for guessing the number, a button to submit that guess and a div to show the results.
in javascript we are getting all of those things in html using getElementById and then we generating a random number using Math.random() and multiplying it by 10 ( this is the max number change it to whatever you want.
now we adding a event listener to our button then making a const named inputvalue and passing inputfield.value in it then we are using parseInt to get the integer value of inputvalue.
now we just using a if statement so if random === input then we will write "Correct Answer" in our result div and else we will write "Wrong Answer" in our result div.
THANKS for reading this much :D
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK