Back to Coding Resources
Play the Game
Try the game you'll build in this tutorial
🎲 Guess the Number!
I'm thinking of a number between 1 and 100
Attempts
0
High Score
-
What You'll Learn
- Generate random numbers with Math.random()
- Handle user input and validation
- Use conditional statements (if/else)
- Update the DOM dynamically
- Track game state with variables
- Implement a scoring system
Step-by-Step Tutorial
1 Create the HTML Structure
Build the game interface with an input field, buttons, and display areas.
<div class="game-container">
<h2>Guess the Number!</h2>
<p>I'm thinking of a number between 1 and 100</p>
<div class="game-info">
<div>Attempts: <span id="attempts">0</span></div>
<div>High Score: <span id="highScore">-</span></div>
</div>
<input type="number" id="guessInput" placeholder="Enter guess" />
<button onclick="checkGuess()">Submit</button>
<button onclick="resetGame()">New Game</button>
<div id="message">Make your first guess!</div>
</div>
2 Initialize Game Variables
Set up variables to track the secret number, attempts, and high score.
let secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let highScore = localStorage.getItem('highScore') || '-';
// Update high score display
document.getElementById('highScore').textContent = highScore;
3 Create the Check Guess Function
Write logic to compare user's guess with the secret number.
function checkGuess() {
const guess = parseInt(document.getElementById('guessInput').value);
const messageEl = document.getElementById('message');
// Validate input
if (!guess || guess < 1 || guess > 100) {
messageEl.textContent = '⚠️ Please enter a number between 1 and 100';
messageEl.className = 'message warning';
return;
}
attempts++;
document.getElementById('attempts').textContent = attempts;
// Check if correct
if (guess === secretNumber) {
messageEl.textContent = `🎉 Correct! You got it in ${attempts} attempts!`;
messageEl.className = 'message success';
updateHighScore();
} else if (guess < secretNumber) {
messageEl.textContent = '📈 Too low! Try a higher number';
messageEl.className = 'message info';
} else {
messageEl.textContent = '📉 Too high! Try a lower number';
messageEl.className = 'message error';
}
// Clear input
document.getElementById('guessInput').value = '';
}
4 Implement High Score Tracking
Save and update the best score using localStorage.
function updateHighScore() {
const currentHighScore = localStorage.getItem('highScore');
if (!currentHighScore || attempts < parseInt(currentHighScore)) {
localStorage.setItem('highScore', attempts);
document.getElementById('highScore').textContent = attempts;
}
}
5 Add Reset Game Function
Allow players to start a new game with a new random number.
function resetGame() {
secretNumber = Math.floor(Math.random() * 100) + 1;
attempts = 0;
document.getElementById('attempts').textContent = '0';
document.getElementById('guessInput').value = '';
const messageEl = document.getElementById('message');
messageEl.textContent = 'New game started! Make your first guess.';
messageEl.className = 'message info';
}
Complete Source Code
Full working code - copy and paste to create your game
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing Game</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: Arial, sans-serif;
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 2rem;
}
.game-container {
background: white;
border-radius: 20px;
padding: 3rem;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
max-width: 500px;
width: 100%;
text-align: center;
}
h2 { color: #4facfe; font-size: 2rem; margin-bottom: 1rem; }
.game-info {
display: flex;
justify-content: space-around;
margin: 1.5rem 0;
padding: 1rem;
background: #f9fafb;
border-radius: 12px;
}
.info-value { font-size: 1.8rem; font-weight: 700; color: #4facfe; }
input {
width: 100%;
padding: 1rem;
font-size: 1.5rem;
border: 3px solid #4facfe;
border-radius: 12px;
text-align: center;
margin: 1rem 0;
}
button {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
color: white;
border: none;
padding: 1rem 2rem;
font-size: 1.1rem;
border-radius: 12px;
cursor: pointer;
margin: 0.5rem;
}
button:hover { opacity: 0.9; }
.message {
margin: 1.5rem 0;
padding: 1rem;
border-radius: 12px;
font-weight: 600;
min-height: 60px;
display: flex;
align-items: center;
justify-content: center;
}
.success { background: #d1fae5; color: #065f46; }
.error { background: #fee2e2; color: #991b1b; }
.info { background: #dbeafe; color: #1e40af; }
.warning { background: #fef3c7; color: #92400e; }
</style>
</head>
<body>
<div class="game-container">
<h2>🎲 Guess the Number!</h2>
<p>I'm thinking of a number between 1 and 100</p>
<div class="game-info">
<div><div>Attempts</div><div class="info-value" id="attempts">0</div></div>
<div><div>High Score</div><div class="info-value" id="highScore">-</div></div>
</div>
<input type="number" id="guessInput" placeholder="Enter your guess" min="1" max="100" />
<div>
<button onclick="checkGuess()">Submit Guess</button>
<button onclick="resetGame()">New Game</button>
</div>
<div class="message info" id="message">Make your first guess!</div>
</div>
<script>
let secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let highScore = localStorage.getItem('highScore') || '-';
document.getElementById('highScore').textContent = highScore;
function checkGuess() {
const guess = parseInt(document.getElementById('guessInput').value);
const messageEl = document.getElementById('message');
if (!guess || guess < 1 || guess > 100) {
messageEl.textContent = '⚠️ Please enter a number between 1 and 100';
messageEl.className = 'message warning';
return;
}
attempts++;
document.getElementById('attempts').textContent = attempts;
if (guess === secretNumber) {
messageEl.textContent = `🎉 Correct! You got it in ${attempts} attempts!`;
messageEl.className = 'message success';
updateHighScore();
} else if (guess < secretNumber) {
messageEl.textContent = '📈 Too low! Try a higher number';
messageEl.className = 'message info';
} else {
messageEl.textContent = '📉 Too high! Try a lower number';
messageEl.className = 'message error';
}
document.getElementById('guessInput').value = '';
}
function updateHighScore() {
const currentHighScore = localStorage.getItem('highScore');
if (!currentHighScore || attempts < parseInt(currentHighScore)) {
localStorage.setItem('highScore', attempts);
document.getElementById('highScore').textContent = attempts;
}
}
function resetGame() {
secretNumber = Math.floor(Math.random() * 100) + 1;
attempts = 0;
document.getElementById('attempts').textContent = '0';
document.getElementById('guessInput').value = '';
const messageEl = document.getElementById('message');
messageEl.textContent = 'New game started! Make your first guess.';
messageEl.className = 'message info';
}
// Allow Enter key to submit
document.getElementById('guessInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') checkGuess();
});
</script>
</body>
</html>
Enhance Your Game
- Add difficulty levels (easy: 1-50, hard: 1-200)
- Display number of guesses remaining
- Add sound effects for wins and losses
- Show hint after 5 wrong guesses
- Create a guess history list
- Add animations and transitions