Introduction
In the world of web development, there’s no shortage of creative projects you can build to improve your skills. Today, we’re going to dive into the creation of a simple yet entertaining number guessing game using the power of HTML, CSS, and JavaScript. Whether you’re a beginner looking to strengthen your coding fundamentals or an experienced developer seeking a fun side project, this tutorial will walk you through the process step by step.
Check the result and code here
Getting Started: Setting Up the Game Screen
We’ll start by defining the structure of our game screen using HTML. Within a container div, we’ll have two main sections: the number pad and the game container. The number pad will contain buttons for numbers 0 through 9, while the game container will display the result, game status, and relevant information such as the prize value and selected number.
<!-- Game screen container -->
<div class="game-screen">
<!-- Number pad section -->
<div class="number-pad">
<div class="overlay"></div>
<!-- Number buttons -->
<div class="number">1</div>
<div class="number">2</div>
<div class="number">3</div>
<div class="number">4</div>
<div class="number">5</div>
<div class="number">6</div>
<div class="number">7</div>
<div class="number">8</div>
<div class="number">9</div>
<div class="number">0</div>
<!-- More number buttons... -->
<!-- Join button -->
<div class="join-btn">JOIN</div>
</div>
<!-- Game container section -->
<div class="game-container">
<!-- Result display section -->
<div class="result">
<!-- Display "Winner" text -->
Winner
<!-- Display the winning number (initially set to "-") -->
<div class="winner-number">-</div>
</div>
<!-- Game status section -->
<div class="game-status">
<!-- Game prize info -->
<div class="game-prize">
<!-- Display prize information -->
You can win
<!-- Display the prize value (initially set to 0 points) -->
<div class="game-prize-value">0 points</div>
</div>
<!-- Game point info -->
<div class="game-point">
<!-- Display points spent information -->
Points spent
<!-- Display the points spent value (initially set to 0 points) -->
<div class="game-point-value">0 points</div>
</div>
<!-- Selected number info -->
<div class="game-key">
<!-- Display selected number information -->
Selected Number
<!-- Display the selected number value (initially set to "--") -->
<div class="game-key-value">--</div>
</div>
</div> <!-- End of game-status -->
</div> <!-- End of game-container -->
</div> <!-- End of game-screen -->
Styling for Visual Appeal
To make our game visually appealing, we’ll add CSS styles to enhance the appearance of different elements. We’ll use colors, borders, shadows, and layout techniques to create a polished look for our game screen.
/* Apply transition effects to all elements */
* {
transition: all 0.15s ease-in-out;
}
/* Set background color for the body */
body {
background: #000;
}
/* Styling for the game screen container */
.game-screen {
border: 2px solid black;
display: grid;
grid-template-columns: 30% 70%;
background: linear-gradient(#36f, blue); /* Gradient background */
color: #fff; /* Text color */
}
/* Styling for the number pad section */
.number-pad {
background: #0d0; /* Green background */
}
/* Styling for the result display */
.result {
height: 200px; /* Set height */
border: 2px solid black; /* Border */
}
/* Styling for the game status section */
.game-status {
display: flex;
justify-content: center; /* Center align items */
}
/* Styling for each section within the game status */
.game-status > div {
border: 2px solid black; /* Border */
flex-grow: 1; /* Allow items to grow */
padding: 20px; /* Padding */
text-align: center; /* Center align text */
font-size: 20px; /* Font size */
font-weight: bold; /* Bold text */
font-family: arial; /* Font family */
}
/* Styling for the number pad section */
.number-pad {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 columns with equal width */
gap: 10px; /* Gap between grid items */
padding: 10px; /* Padding */
position: relative; /* Relative positioning */
overflow: hidden; /* Hide overflow */
}
/* Styling for each number button */
.number-pad > div {
display: grid;
place-content: center; /* Center align content */
border-radius: 20px; /* Rounded corners */
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.3), inset 0px 5px 10px rgba(255, 255, 255, 0.6); /* Box shadow */
user-select: none; /* Disable selection */
font-size: 20px; /* Font size */
font-family: arial; /* Font family */
font-weight: bold; /* Bold text */
}
/* Styling for active state of number buttons */
.number-pad > div:active {
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0), inset 0px 5px 10px rgba(255, 255, 255, 0), inset 0px 5px 10px rgba(0, 0, 0, 0.3), 0px 5px 10px rgba(255, 255, 255, 0.6); /* Box shadow */
}
/* Styling for the JOIN button */
.join-btn {
grid-column: 2/4; /* Span columns */
background: black; /* Black background */
z-index: 1; /* Set z-index */
}
/* Styling for the overlay in the number pad */
.number-pad .overlay {
position: absolute; /* Absolute positioning */
width: 100%; /* Full width */
height: 100%; /* Full height */
background: red; /* Red background */
border-radius: 0px; /* No border radius */
opacity: 0.3; /* Opacity */
box-shadow: none; /* No box shadow */
z-index: 0; /* Set z-index */
}
/* Styling for the result text */
.result {
font-size: 50px; /* Font size */
font-family: arial; /* Font family */
font-weight: 900; /* Bold text */
text-align: center; /* Center align text */
}
/* Styling for the winning number */
.winner-number {
font-size: 100px; /* Font size */
}
Adding Interactivity with JavaScript
Now comes the fun part – adding interactivity with JavaScript! We’ll implement the game logic, including starting the game, selecting numbers, determining the winner, and restarting the game if needed. We’ll use event listeners to capture user input and manipulate the game state accordingly.
javascriptCopy code
// Initialize variables for game state
let isGameStarted = false; // Flag to track if the game is started
let gamepoint = 0; // Points spent by the player
let gamePrize = 0; // Prize the player can win
let gamePrizePercentage = 500; // Percentage of points to be added as prize
let gameKey = ""; // Selected number by the player
let winnerNumber = -1; // Winning number generated randomly
// Select DOM elements
let numberpadOverlay = document.querySelector(".number-pad .overlay");
let numbers = document.querySelectorAll(".number");
let joinBtn = document.querySelector(".join-btn");
let gamepointValue = document.querySelector(".game-point-value");
let gamePrizeValue = document.querySelector(".game-prize-value");
let gameKeyValue = document.querySelector(".game-key-value");
let winnerNumberElement = document.querySelector(".winner-number");
// Event listener for the "JOIN" button to start the game
joinBtn.addEventListener("click", startGame);
// Event listener for each number button
for (let i = 0; i < numbers.length; i++) {
numbers[i].addEventListener("click", () => {
// Set the selected number
gameKey = numbers[i].innerText;
gameKeyValue.innerText = gameKey;
// Enable pointer events on the overlay
numberpadOverlay.style.pointerEvents = "all";
// Wait for a delay to simulate the game process
setTimeout(function() {
// Display the winning number
winnerNumberElement.innerText = winnerNumber;
// Check if the selected number matches the winning number
if (parseInt(winnerNumber) == parseInt(gameKey)) {
// If matched, player wins
setTimeout(function() {
alert("Winner!");
isGameStarted = false;
confirmToRestart();
}, 1000);
} else {
// If not matched, player loses
setTimeout(function() {
alert("You lose!");
isGameStarted = false;
confirmToRestart();
}, 1000);
}
}, 5000); // Wait for 5 seconds
});
}
// Function to confirm if the player wants to restart the game
function confirmToRestart() {
let shouldRestartGame = confirm("Do you want to restart the game?");
if (shouldRestartGame) {
// If player wants to restart, start a new game
startGame();
} else {
// If not, hide the "JOIN" button
joinBtn.style.zIndex = 0;
}
}
// Function to start the game
function startGame() {
// Initialize game state variables
isGameStarted = true;
gamepoint = 0;
gamePrize = 0;
gamePrizePercentage = 500;
// Generate a random winning number
winnerNumber = parseInt(Math.random() * 10);
console.log("w:" + winnerNumber);
// Prompt the player to enter points they want to spend
gamepoint = parseInt(prompt("Enter how points you want to spend?"));
// Calculate the prize based on the points spent
gamePrize = parseInt(gamepoint * gamePrizePercentage / 100) + gamepoint;
// Update the game status display with points and prize information
gamepointValue.innerText = gamepoint + " points";
gamePrizeValue.innerText = gamePrize + " points";
// Wait for a delay to start the game after displaying information
setTimeout(function() {
alert("Now Select a number from left side.");
joinBtn.style.zIndex = -1; // Hide the "JOIN" button
numberpadOverlay.style.pointerEvents = "none"; // Disable pointer events on the overlay
}, 1000);
}
Understanding the Game Logic
Let’s break down the game logic step by step:
- Initialization: We initialize variables to track game state, points, prize, and the winning number.
- Starting the Game: When the player clicks the “JOIN” button, the game generates a random winning number and prompts the player to enter the points they want to spend.
- Selecting a Number: After selecting a number from the number pad, the game checks if the selected number matches the winning number. If there’s a match, it alerts the player that they won; otherwise, it alerts them that they lost.
- Restarting the Game: After winning or losing, the player is prompted to restart the game. If they choose to restart, the game resets the state and starts a new game.
Conclusion: Start Coding Your Own Game Today!
Congratulations! You’ve successfully built a simple yet engaging number guessing game using HTML, CSS, and JavaScript. This project demonstrates the power of web development and provides a great opportunity to hone your skills while having fun. Feel free to customize and expand upon this project to add more features and challenges. Happy coding!
By following this tutorial, you’ll gain valuable experience in web development and have a fully functional game to show off to your friends and colleagues. So why wait? Start coding your own number guessing game today and unleash your creativity! Happy coding,
Cheers, Vishnu Rajoria
CSLab Software Training Institute (in Sikar)Â