Creating a simple yet engaging number-guessing game is a great way to enhance your JavaScript skills. In this blog post, we'll walk through a project that involves HTML, CSS, and JavaScript to build a game where users guess a random number between 1 and 100. Let's dive into the code and explain how it all works.
HTML Structure
First, let's take a look at the HTML code. This is the structure of our web page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Number Guessing Game</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="../styles.css">
</head>
<body style="background-color:#212121; color:#fff;">
<div id="wrapper">
<h1>Number guessing game</h1>
<p>Try and guess a random number between 1 and 100.</p>
<p>You have 10 attempts to guess the right number.</p>
</br>
<form class="form">
<label for="guessField" id="guess">Guess a number</label>
<input type="text" id="guessField" class="guessField">
<input type="submit" id="subt" value="Submit guess" class="guessSubmit">
</form>
<div class="resultParas">
<p>Previous Guesses: <span class="guesses"></span></p>
<p>Guesses Remaining: <span class="lastResult">10</span></p>
<p class="lowOrHi"></p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS Styling
The CSS styles make the game visually appealing and user-friendly:
html {
font-family: sans-serif;
}
body {
width: 300px;
max-width: 750px;
min-width: 480px;
margin: 0 auto;
background-color: #212121;
}
.lastResult, .guesses {
color: white;
padding: 7px;
}
button, #subt {
background-color: #161616;
color: #fff;
width: 200px;
height: 50px;
border-radius: 10px;
font-size: 20px;
border: none;
margin-top: 50px;
}
#guessField {
color: #000;
width: 250px;
height: 50px;
font-size: 30px;
border: 5px solid #6c6d6d;
text-align: center;
margin-top: 25px;
}
#wrapper {
box-sizing: border-box;
text-align: center;
width: 450px;
height: 550px;
background-color: #474747;
color: #fff;
font-size: 25px;
margin: 0 auto;
}
h1 {
background-color: #161616;
color: #fff;
text-align: center;
}
p {
font-size: 16px;
text-align: center;
}
This is what our game looks like:
JavaScript Logic
The JavaScript code brings interactivity to our game. Let's go through it step by step:
let randomNumber = parseInt(Math.random() * 100 + 1);
console.log(randomNumber); // For debugging purposes
const submit = document.querySelector('#subt');
const userInput = document.querySelector('#guessField');
const guessSlot = document.querySelector('.guesses');
const remaining = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');
const startOver = document.querySelector('.resultParas');
const p = document.createElement('p');
let prevGuess = [];
let numGuess = 1;
let playGame = true;
if (playGame) {
submit.addEventListener('click', function (e) {
e.preventDefault();
const guess = parseInt(userInput.value);
console.log(guess); // For debugging purposes
validateGuess(guess);
});
}
function validateGuess(guess) {
if (isNaN(guess)) {
alert('Please enter a valid number');
} else if (guess < 1) {
alert('Please enter a number greater than 1');
} else if (guess > 100) {
alert('Please enter a number less than 100');
} else {
prevGuess.push(guess);
if (numGuess === 11) {
displayMessage(`Game Over. The random number was ${randomNumber}`);
endGame();
} else {
displayGuess(guess);
checkGuess(guess);
}
}
}
function checkGuess(guess) {
if (guess === randomNumber) {
displayMessage(`Congratulations! You guessed it right.`);
endGame();
} else if (guess < randomNumber) {
displayMessage(`Your guess is too low.`);
} else if (guess > randomNumber) {
displayMessage(`Your guess is too high.`);
}
}
function displayGuess(guess) {
userInput.value = '';
guessSlot.innerHTML += `${guess}, `;
numGuess++;
remaining.innerHTML = `${11 - numGuess} `;
}
function displayMessage(message) {
lowOrHi.innerHTML = `<h2>${message}</h2>`;
}
function endGame() {
userInput.value = '';
userInput.setAttribute('disabled', '');
p.classList.add('button');
p.innerHTML = `<h2 id="newGame">Start New Game</h2>`;
startOver.appendChild(p);
playGame = false;
newGame();
}
function newGame() {
const newGameButton = document.querySelector('#newGame');
newGameButton.addEventListener('click', function () {
randomNumber = parseInt(Math.random() * 100 + 1);
prevGuess = [];
numGuess = 1;
guessSlot.innerHTML = '';
remaining.innerHTML = '10';
userInput.removeAttribute('disabled');
startOver.removeChild(p);
playGame = true;
});
}
Here is the project in the working state after binding js to it:
Explanation of JavaScript Code
Random Number Generation:
let randomNumber = parseInt(Math.random() * 100 + 1);
This line generates a random number between 1 and 100. The
Math.random()
function generates a decimal number between 0 (inclusive) and 1 (exclusive), which is then multiplied by 100 and rounded off to the nearest integer usingparseInt()
.Selecting and creating the elements that we need:
const submit = document.querySelector('#subt'); const userInput = document.querySelector('#guessField'); const guessSlot = document.querySelector('.guesses'); const remaining = document.querySelector('.lastResult'); const lowOrHi = document.querySelector('.lowOrHi'); const startOver = document.querySelector('.resultParas'); const p = document.createElement('p'); let prevGuess = []; let numGuess = 1; let playGame = true;
here 'playGame = true', makes sure if the user is allowed to play game or not, this type of variable is common in such games.
Event Listener for Submit Button and initial condition to play game:
if (playGame) { submit.addEventListener('click', function (e) { e.preventDefault(); const guess = parseInt(userInput.value); console.log(guess); // For debugging purposes validateGuess(guess); }); }
This code adds an event listener to the submit button that prevents the default form submission behavior and calls the
validateGuess
function with the user's guess from the input box with id as 'guessField'.Validation of Guess:
function validateGuess(guess) { if (isNaN(guess)) { alert('Please enter a valid number'); } else if (guess < 1) { alert('Please enter a number greater than 1'); } else if (guess > 100) { alert('Please enter a number less than 100'); } else { prevGuess.push(guess); if (numGuess === 11) { displayMessage(`Game Over. The random number was ${randomNumber}`); endGame(); } else { displayGuess(guess); checkGuess(guess); } } }
This function checks if the user's input is a valid number between 1 and 100. If valid, it pushes the guess to the
prevGuess
array, If it is the 11th turn, then it ends that game, and if it's less than the 11th turn, then it displays the guess and also checks whether the guess is right or wrong.Checking the Guess:
function checkGuess(guess) { if (guess === randomNumber) { displayMessage(`Congratulations! You guessed it right.`); endGame(); } else if (guess < randomNumber) { displayMessage(`Your guess is too low.`); } else if (guess > randomNumber) { displayMessage(`Your guess is too high.`); } }
This function compares the user's guess with the random number and displays a message indicating whether the guess is too low, too high, or correct.
Displaying Guesses and Messages:
function displayGuess(guess) { userInput.value = ''; //clears the input box guessSlot.innerHTML += `${guess}, `; //adds previous guesses to guess slot numGuess++; //increases the number of guess remaining.innerHTML = `${11 - numGuess} `; //tells the remaining guess } function displayMessage(message) { lowOrHi.innerHTML = `<h2>${message}</h2>`; }
These functions handle displaying the user's previous guesses and messages indicating the guess status.
Ending the game:
function endGame() { userInput.value = ''; userInput.setAttribute('disabled', ''); p.classList.add('button'); p.innerHTML = `<h2 id="newGame">Start New Game</h2>`; startOver.appendChild(p); playGame = false; newGame(); }
userInput.value = '';
: This line clears the input field where the user enters their guess.userInput.setAttribute('disabled', '');
: This disables the input field, preventing the user from entering any more guesses.p.classList.add('button');
: This adds a CSS class namedbutton
to the paragraph elementp
. Thep
element was created earlier in the script and is used to hold the new game button.p.innerHTML =
<h2 id="newGame">Start New Game</h2>;
: This sets the inner HTML of thep
element to ah2
element with the text "Start New Game" and an ID ofnewGame
. This effectively creates a button for starting a new game.startOver.appendChild(p);
: This appends thep
element (which now contains the new game button) to thestartOver
element in the DOM, making the new game button visible on the page.playGame = false;
: This sets theplayGame
variable tofalse
, indicating that the current game session is over.newGame()
: This calls thenewGame
function, which sets up a new game by resetting the necessary variables and event listeners.
Restarting the game:
function newGame() { const newGameButton = document.querySelector('#newGame'); newGameButton.addEventListener('click', function () { randomNumber = parseInt(Math.random() * 100 + 1); prevGuess = []; numGuess = 1; guessSlot.innerHTML = ''; remaining.innerHTML = '10'; userInput.removeAttribute('disabled'); startOver.removeChild(p); playGame = true; }); }
The
newGame
function sets up a new game by:Generating a new random number.
Resetting the previous guesses and guess count.
Clearing the display for previous guesses and remaining attempts.
Enabling the input field for new guesses.
Removing the "Start New Game" button.
Setting the game state to indicate that a new game is in progress.