About this Project
A classic number guessing game that demonstrates fundamental JavaScript concepts. Players try to guess a randomly generated number between 1 and 100, receiving feedback after each attempt.
Key Features:
- Random number generation
- User input validation
- Interactive feedback system
- Attempt tracking
Learning Outcomes:
- DOM manipulation
- Event handling
- Conditional logic
- State management
Number Guessing Game
Try to guess the number between 1 and 100!
View Solution
Here's how the Number Guessing Game is implemented:
- Generate a random number between 1 and 100 using Math.random()
- Track the number of attempts using a counter variable
- Compare user's guess with the target number and provide feedback
- Implement game reset functionality
Key Code Implementation
const game = {
targetNumber: null,
attempts: 0,
init() {
this.targetNumber = Math.floor(Math.random() * 100) + 1;
this.attempts = 0;
this.updateMessage('');
},
makeGuess(guess) {
this.attempts++;
if (guess === this.targetNumber) {
this.updateMessage(`Congratulations! You got it in ${this.attempts} tries!`, 'success');
return true;
}
const hint = guess > this.targetNumber ? 'Too high!' : 'Too low!';
this.updateMessage(hint);
return false;
},
updateMessage(text, type = '') {
const messageEl = document.getElementById('message');
messageEl.textContent = text;
messageEl.className = type;
}
};
// Event Handlers
function handleGuess() {
const input = document.getElementById('guess');
const guess = parseInt(input.value);
if (isNaN(guess) || guess < 1 || guess > 100) {
game.updateMessage('Please enter a valid number between 1 and 100');
return;
}
game.makeGuess(guess);
input.value = '';
input.focus();
}
function resetGame() {
game.init();
document.getElementById('guess').value = '';
}
// Initialize game on load
game.init();
Key Concepts Used
- Object-Oriented Design: Using an object to encapsulate game state and methods
- Event Handling: Managing user input and button clicks
- DOM Manipulation: Updating the UI based on game state
- Input Validation: Ensuring valid user input before processing