Number Guessing Game
Day 4 of this coding challenge focused on building a Number Guessing Game. This project introduced random number generation, user interaction, loops, and conditional logic.
The goal of this challenge was to create a simple Number Guessing Game. The program generates a random number and keeps asking the user to guess until the correct answer is found.
I'm thinking of a number between 1 and 10.
Take a guess!
Your guess: 4
Too small!
Your guess: 7
Too big!
Your guess: 6
Congratulations! You guessed the number correctly in 3 attempts.Funny Debugging Moment
My first attempt contained a tiny syntax mistake:
const randomNumber:
Math.floor(Math.random() * 10) + 1:I accidentally used : instead of =. A small typo, but enough to break the entire program.
Building the Core Logic
After fixing the syntax issue, I implemented the basic game loop using while, prompt(), and conditional statements.
let randomNumber = Math.floor(Math.random() * 10) + 1;
let attempt = 0;
let repeat = true;
while(repeat) {
const userInput = prompt("I'm thinking of a number between 1 and 10. Take a guess!");
attempt++;
const guess = parseInt(userInput);
if (isNaN(guess)) {
console.log("Eh? Please enter a number 😄");
} else {
if (guess < randomNumber) {
console.log("Too small 😅");
} else if (guess > randomNumber) {
console.log("Too big 😅");
} else {
console.log(`🎉 Congratulations! You guessed the number correctly in ${attempt} attempts.`);
repeat = false;
}
}
}This version already worked, but there were still opportunities to improve the user experience.
Input Validation
To prevent invalid input from causing problems, I added validation using isNaN().
if (isNaN(guess)) {
console.log("Eh? Please enter a number 😄");
}Output: Please enter a number 😄
Adding a Scoring System
To make the game more rewarding, I added different messages based on how many attempts were needed to guess the number.
if(attempt <= 3) {
console.log("🔥 Pro move! You guessed it super fast.");
} else if (attempt <= 6) {
console.log("👍 Not bad! But you can do better.");
} else {
console.log("😅 Well, needs more practice. Keep trying!");
}Hard Mode
As a bonus challenge, I added a hard mode that expands the guessing range from 1–10 to 1–50.
let hardMode = confirm("Want to play in hard mode? (Numbers 1–50)");
let rangeText = hardMode ? "1 and 50" : "1 and 10";
let randomNumber = Math.floor(Math.random() * (hardMode ? 50 : 10)) + 1;The prompt message also becomes dynamic depending on the selected difficulty.
const userInput = prompt(
`I'm thinking of a number between ${rangeText}. Take a guess!`
);Final Interactive Version
The final version combines validation, scoring, difficulty selection, and looping into one complete experience.
let hardMode = confirm("Want to play in hard mode? (Numbers 1–50)");
let rangeText = hardMode ? "1 and 50" : "1 and 10";
let randomNumber = Math.floor(Math.random() * (hardMode ? 50 : 10)) + 1;
let attempt = 0;
let repeat = true;
// game loop here