Crack the Code: A Fun JavaScript Guessing Game
The Magic Behind the Game
The guessNumber()
function is the core of this operation. It generates a random number between 1 and 10 using the following code:
function guessNumber() {
return Math.floor(Math.random() * 10) + 1;
}
This function works by:
- Generating a random decimal value between 0 and 1 using
Math.random()
. - Multiplying the result by 10 to create a number between 0 and 10.
- Rounding down the decimal value to the nearest whole number using
Math.floor()
, ensuring the random number is an integer between 1 and 10.
The User Takes a Guess
Now it’s time for the user to take a stab at guessing the mysterious number. A prompt invites the user to enter a number between 1 and 10, which is then converted to an integer using the parseInt()
function:
const userGuess = parseInt(prompt("Enter a number between 1 and 10:"));
This ensures that our program can compare the user’s input to the randomly generated number.
The Game Loop
The real magic happens in the while loop, where the program repeatedly asks the user for input until they correctly guess the number:
let numberOfTries = 0;
while (true) {
const userGuess = parseInt(prompt("Enter a number between 1 and 10:"));
numberOfTries++;
if (userGuess === guessNumber()) {
alert(`Congratulations! You guessed the number in ${numberOfTries} tries.`);
break;
} else {
alert("Sorry, try again!");
}
}
The if...else
statement is the gatekeeper, checking if the user’s guess matches the random number. If the conditions are met, the program celebrates the user’s victory. Otherwise, it encourages them to try again.
The Power of Comparison
At the heart of this program lies the comparison operator (===
), which checks if the user’s guess is equal to the random number:
if (userGuess === guessNumber()) {... }
This operator is a crucial part of the if...else
statement, determining the program’s next move. Want to learn more about comparison operators? Explore the world of JavaScript comparison operators and discover the secrets behind conditional statements.
Learn more about JavaScript comparison operators.