JavaScript Program to Guess a Random number between 1 to 100.
in this article, we will create Number guessing game by using JavaScript program. in this game user randomly enter the number till he can guess the exact number
to create a guessing number game you have knowledge of HTML and JavaScript:
first you have to install the visual studio code and then create a folder to store the below two Files:
-
after creating the new folder then create a file name Index.html and copy the below code then save it
Html Code:
-
Create a second file name script.js and copy the below code then save it:
JavaScript Code:
// Generate a random number between 1 and 100
const randomNumber = Math.floor(Math.random() * 100) + 1;
// Function to start the game
function startGame() {
let attempts = 0;
let guess;
while (guess !== randomNumber) {
guess = parseInt(prompt(“Guess a number between 1 and 100:”));
if (isNaN(guess)) {
alert(“Please enter a valid number.”);
} else {
attempts++;
if (guess < randomNumber) {
alert(“Too low! Try again.”);
} else if (guess > randomNumber) {
alert(“Too high! Try again.”);
} else {
alert(`Congratulations! You guessed the number ${randomNumber} in ${attempts} attempts.`);
}
}
}
}
// Start the game
startGame();
-
after saving the file click on Go live button in visual studio and now your game is start.
Visit more Blog’s: