Are you looking to improve your JavaScript skills by creating a program that can guess a random number? Look no further! This comprehensive guide will walk you through the steps to create a simple yet effective program that can guess a random number.
Understanding the Problem
The goal of the program is to have the computer generate a random number between 1 and 100 and then ask the user to guess the number. The program in Javascript will then provide feedback to the user to let them know if they need to guess higher or lower until they correctly guess the number.
Planning the Solution
Before we dive into the code, let’s take a moment to plan our solution.
- Generate a random number between 1 and 100.
- Ask the user to guess the number.
- Provide feedback to the user if their guess is too high or too low.
- Repeat steps 2 and 3 until the user correctly guesses the number.
Creating the Program
Now that we have a plan, let’s get to coding!
First, we will use the JavaScript Math.random()
method to generate a random number between 1 and 100. This method returns a random number between 0 and 1, so we will multiply it by 100 and round it down to the nearest whole number to get our random number.
let randomNumber = Math.floor(Math.random() * 100) + 1;
Next, we will use a while
loop to repeatedly ask the user to guess the number and provide feedback until they correctly guess the number.
let guess = prompt("Guess a number between 1 and 100:");
while (guess != randomNumber) {
if (guess < randomNumber) {
alert("Too low. Guess again.");
} else {
alert("Too high. Guess again.");
}
guess = prompt("Guess a number between 1 and 100:");
}
alert("You got it! The number was " + randomNumber + ".");
And that’s it! With just a few lines of code, we have created a program that can guess a random number.
Improving the Program in Javascript
While this program works, there is room for improvement. Let’s add a few features to make it more user-friendly.
First, let’s keep track of the number of guesses the user has made.
let randomNumber = Math.floor(Math.random() * 100) + 1;
let guess;
let guesses = 0;
guess = prompt("Guess a number between 1 and 100:");
while (guess != randomNumber) {
guesses++;
if (guess < randomNumber) {
alert("Too low. Guess again.");
} else {
alert("Too high. Guess again.");
}
guess = prompt("Guess a number between 1 and 100:");
}
alert("You got it in " + guesses + " guesses! The number was " + randomNumber + ".");
Next, let’s add a feature to allow the user to choose the range of numbers to guess from.
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
function guessNumber(min, max) {
let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
let userGuessed = false;
console.log(`Guess a number between ${min} and ${max}:`);
const guess = function() {
readline.question('Your guess: ', function(answer) {
let userGuess = parseInt(answer);
if (userGuess === randomNumber) {
userGuessed = true;
console.log('You guessed it right!');
readline.close();
} else if (userGuess < randomNumber) {
console.log('Too low.');
guess();
} else if (userGuess > randomNumber) {
console.log('Too high.');
guess();
}
});
};
guess();
readline.on('close', function() {
if (!userGuessed) {
console.log(`The number was ${randomNumber}.`);
}
});
}
guessNumber(1, 100);
This program uses the readline
module from Node.js to get input from the user and to output messages to the console. It generates a random number within the specified range using the Math.random()
method, and then prompts the user to guess the number. The guess
function is called recursively until the user correctly guesses the number or until the readline
interface is closed. If the user does not correctly guess the number, the answer is revealed at the end.
To generate a random number in JavaScript, we can use the Math.random()
method. This method returns a random decimal number between 0 and 1. To generate a random whole number between a range of values, we can multiply the result of Math.random()
by the range of values
Thanks for reading. Happy coding!