Mini-Build: Number Guessing Game
Apply everything from this module — loops, conditionals, break, and logic — to build a number guessing game. This mini-project reinforces control flow concepts through practical application.
Game Logic
- Generate a random number between 1 and 100
- Player guesses — check if too high, too low, or correct
- Track number of attempts
- Use a while loop — keep going until correct guess
- Use if/else — give feedback on each guess
- Use break — exit when correct
Number Guessing Game Code
// Number Guessing Game
const secretNumber = Math.floor(Math.random() * 100) + 1;
console.log("🎮 Number Guessing Game!");
console.log("I'm thinking of a number between 1 and 100...");
// Simulate guesses (in real app, use prompt() or input field)
const guesses = [50, 75, 62, 68, 65, 67];
let attempts = 0;
for (const guess of guesses) {
attempts++;
console.log(`\nGuess #${attempts}: ${guess}`);
if (guess === secretNumber) {
console.log(`🎉 Correct! The number was ${secretNumber}!`);
console.log(`You got it in ${attempts} attempts!`);
break;
} else if (guess < secretNumber) {
console.log("📈 Too low! Try higher.");
} else {
console.log("📉 Too high! Try lower.");
}
}
// Alternative: direct simulation
console.log("\n--- Automated game ---");
const target = Math.floor(Math.random() * 100) + 1;
let low = 1, high = 100, tries = 0;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
tries++;
if (mid === target) {
console.log(`Found ${target} in ${tries} tries! (Binary search)`);
break;
} else if (mid < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}Tip
Tip
Binary search (dividing the range in half each guess) finds any number in 1-100 in at most 7 guesses. This demonstrates why algorithms matter — brute force might take 100 guesses, but a smart approach takes only 7.
Never swallow errors silently. Log, report, recover gracefully.
Common Mistake
Warning
Using Math.random() without Math.floor() gives a decimal, not a whole number. Always use Math.floor(Math.random() * max) + 1 for random integers. Without floor, you get values like 3.7482 instead of clean numbers.
Practice Task
Note
Extend the guessing game: (1) Add a maximum attempts limit (e.g., 7 tries). (2) Track and display the best score across multiple rounds. (3) Add difficulty levels: easy (1-50), medium (1-100), hard (1-1000).
Quick Quiz
Key Takeaways
- Apply everything from this module — loops, conditionals, break, and logic — to build a number guessing game.
- Generate a random number between 1 and 100
- Player guesses — check if too high, too low, or correct
- Track number of attempts