Let’s design the HTML Game for fun and exciting. At the end of this article I provide the complete source code of this game. Before starting, first create a new game folder. In that folder create three separate files index.html, styles.css, script.js and also download some sounds like bomb sound, thunder sound in the same folder for sound effects. Let’s start
Introduction to HTML Game Design
HTML, CSS, and JavaScript are powerful tools for creating interactive web content, including games. These technologies each play a crucial role in the development process:
HTML (HyperText Markup Language)
HTML is like the building blocks of a webpage. It helps arrange things like text, buttons, and images on the screen. For a game, HTML is used to create the space where the game will be shown, such as the game canvas and other parts that make up the game layout.
CSS (Cascading Style Sheets)
CSS helps make the game look good by adding styles. It allows developers to control things like colors, fonts, and spacing. With CSS, the game can have a nice, consistent design, making it more visually attractive and enjoyable to play.
JavaScript
JavaScript adds interactivity to the game. It lets developers control how the game works, change the game state, and respond to actions like mouse clicks or keyboard presses. With JavaScript, the game becomes interactive, allowing players to engage with it in real-time.
By combining HTML, CSS, and JavaScript, developers can create fun and interactive games that work directly in web browsers. This means no need for extra plugins or software installations. Players can just open their browser, go to the game’s URL, and start playing right away. This combination of technologies makes web-based game development easy and flexible, making games accessible to everyone.
Setting Up the Project
Let’s start by setting up the project structure and creating the necessary files:
HTML File (index.html)
Head Section
The <head> section includes metadata and resource links:
<strong><!DOCTYPE html>
<html <em>lang</em>="en">
<head>
<meta <em>charset</em>="UTF-8">
<meta <em>name</em>="viewport" <em>content</em>="width=device-width, initial-scale=1.0">
<title>Fruit Catcher Game</title>
<link <em>rel</em>="stylesheet" <em>href</em>="styles.css">
</head>
<body>
<!-- Game content goes here -->
<script <em>src</em>="script.js"></script>
</body>
</html>
</strong>
- <meta charset=”UTF-8″>: Sets the document’s character encoding to UTF-8, allowing it to correctly display a wide range of characters.
- <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>: Ensures the page is responsive by setting the viewport width to match the device’s width.
- <title>Fruit Catcher Game</title>: Defines the title of the web page, which is shown in the browser tab.
- <link rel=”stylesheet” href=”styles.css”>: Links to an external CSS file (styles.css) containing the styling rules for the page, defining the appearance of the game.
Designing the Game Layout
Next, let’s design the layout of our game using HTML and CSS. We’ll create elements for the game container, basket, falling items, score display, level display, and game over message.
<strong><div <em>id</em>="game-container">
<div <em>id</em>="basket"></div>
<div <em>id</em>="falling-item"></div>
<div <em>id</em>="score">Score: <span <em>id</em>="score-value">0</span></div>
<div <em>id</em>="level">Level: <span <em>id</em>="level-value">1</span></div>
<div <em>id</em>="game-over" <em>class</em>="hidden">Game Over! Your final score is: <span <em>id</em>="final-score"></span></div>
</div>
<button <em>id</em>="start-button">Start Game</button>
<button <em>id</em>="stop-game">Stop Game</button>
<button <em>id</em>="pause-game">Pause Game</button>
<audio <em>id</em>="catch-sound" <em>src</em>="catch-sound.mp3" <em>preload</em>="auto"></audio>
<audio <em>id</em>="bomb-sound" <em>src</em>="bomb-sound.mp3" <em>preload</em>="auto"></audio>
</strong>
Detailed Explanation
Game Container (<div id=”game-container”>):
- This is the main container for the game. All other game elements are nested within this container.
- This helps in organizing the game’s layout and can be styled to control the overall appearance and dimensions of the game area.
Basket (<div id=”basket”>):
- Represents the player’s control element, typically positioned at the bottom of the game container.
- This element can be styled and moved horizontally to catch falling items.
Falling Item (<div id=”falling-item”>):
- Represents items that fall from the top of the game container. These can be objects the player needs to catch or avoid.
- The position of this element will change during gameplay to simulate falling.
Score Display (<div id=”score”>):
- Displays the current score of the player.
- The <span id=”score-value”>0</span> element holds the numerical score value, which can be updated during the game.
Level Display (<div id=”level”>):
- Displays the current level of the game.
- The <span id=”level-value”>1</span> element holds the level number, which can be incremented as the game progresses.
Game Over Message (<div id=”game-over” class=”hidden”>):
- Displays a game over message when the game ends.
- The class=”hidden” attribute initially hides this message. This class can be removed with JavaScript to show the message when the game is over.
- The <span id=”final-score”></span> element will display the player’s final score.
Start Game Button (<button id=”start-button”>Start Game</button>):
- This button initiates the game when clicked.
- The id=”start-button” allows it to be easily referenced and controlled via JavaScript.
Stop Game Button (<button id=”stop-game”>Stop Game</button>):
- This button stops the game when clicked.
- The id=”stop-game” allows it to be easily referenced and controlled via JavaScript.
Pause Game Button (<button id=”pause-game”>Pause Game</button>):
- This button pauses the game when clicked.
- The id=”pause-game” allows it to be easily referenced and controlled via JavaScript.
Must Read
- A Guide To Web Scraping in Python Using Beautiful Soup
- How to Create Customer Service Chatbots
- How to make Flappy Bird Game – HTML, CSS and JavaScript
- How to Develop a PDF-to-Audio Converter with Python
- Free Online MP4 to MP3 Converter with Python
Catch Sound (<audio id=”catch-sound” script src=”catch-sound.mp3″ preload=”auto”></audio>):
- An audio element that plays a sound when an item is caught.
- The preload=”auto” attribute ensures the sound is loaded and ready to play when needed.
Bomb Sound (<audio id=”bomb-sound” script src=”bomb-sound.mp3″ preload=”auto”></audio>):
- An audio element that plays a sound when a bomb or negative item is caught.
- The preload=”auto” attribute ensures the sound is loaded and ready to play when needed.
Interaction with CSS and JavaScript
- CSS:
- CSS will be used to style these elements, controlling their appearance, position, size, colors, and any animations or transitions.
- For example, you can style the #basket to look like a basket and position it at the bottom of the #game-container.
- JavaScript:
- JavaScript will handle the game logic, such as moving the basket, dropping items, checking for collisions, updating the score and level, and displaying the game over message.
- Event listeners will be attached to the buttons to start, stop, and pause the game.
- The audio elements can be triggered to play sounds at appropriate game events, like catching an item or hitting a bomb.

Styling the Game Elements
We’ll apply CSS styles to the game elements to give them the desired appearance and layout.
<strong>body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
margin: 0;
font-family: Arial, sans-serif;
}
#game-container {
position: relative;
width: 400px;
height: 500px;
background-color: #fff;
border: 2px solid #000;
overflow: hidden;
}
#basket {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
width: 80px;
height: 80px;
background-color: #ff4500;
border-radius: 50%;
}
#falling-item {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 50px;
height: 50px;
background-color: #008000;
border-radius: 50%;
}
#score, #level {
position: absolute;
font-size: 20px;
font-weight: bold;
color: #333;
}
#score {
top: 20px;
left: 20px;
}
#level {
top: 50px;
left: 20px;
}
button {
margin: 5px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
#game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 24px;
color: red;
display: none;
}
.hidden {
display: none;
}</strong>
Adding Game Functionality with JavaScript
The JavaScript code adds interactivity and game logic to the HTML elements defined for the game. Let’s see the functionality step by step:
Setup and Initialization
<strong>document.addEventListener('DOMContentLoaded', () => {
// Grabbing HTML elements
const basket = document.getElementById('basket');
const fallingItem = document.getElementById('falling-item');
const scoreValue = document.getElementById('score-value');
const levelValue = document.getElementById('level-value');
const startButton = document.getElementById('start-button');
const stopGameButton = document.getElementById('stop-game');
const pauseGameButton = document.getElementById('pause-game');
const gameOverText = document.getElementById('game-over');
const catchSound = document.getElementById('catch-sound');
const bombSound = document.getElementById('bomb-sound');
// Game variables
let score = 0;
let level = 1;
let gameContainer = document.getElementById('game-container');
let gameHeight = gameContainer.offsetHeight;
let gameWidth = gameContainer.offsetWidth;
let fallingSpeed = 5;
let gameRunning = false;
let animationFrameId;
const negativeThreshold = -10; // Game over when score reaches this threshold
// Array of items
const items = [
{ type: 'fruit', color: '#008000', score: 1 },
{ type: 'fruit', color: '#ffa500', score: 2 },
{ type: 'fruit', color: '#800080', score: 3 },
{ type: 'fruit', color: '#ffff00', score: 4 },
{ type: 'bomb', color: '#ff0000', score: -5 }
];</strong>
Event Listener
An event listener in JavaScript listens for specific actions, like when a user clicks a button or when something on the page changes. The DOMContentLoaded
event happens when the HTML document is completely loaded and ready. This makes sure the code runs only after all the page elements are available, preventing errors that could happen if the code tries to interact with elements that haven’t loaded yet.
Grabbing Elements
Retrieving elements in JavaScript means selecting specific parts of the webpage (HTML elements) so you can work with them.
Selection Methods: You can use methods like document.getElementById
, document.getElementsByClassName
, document.getElementsByTagName
, document.querySelector
, and document.querySelectorAll
to find and select elements on the page.
Storing in Variables: After selecting an element, you store it in a variable. This makes it easy to update or change things like the element’s content, style, or other properties later in the code.
Game Variables
Game variables are mportant for managing the state and dynamics of a game.
Initialization: Setting initial values for different aspects of the game.
- Score: Tracks the player’s progress or achievements.
- Level: Indicates the current difficulty or stage of the game.
- Game Dimensions: Refers to the size of the game area, such as its width and height.
- Falling Speed: Determines how quickly items (like fruits or bombs) fall, impacting the game’s difficulty.
- Game State Flags: Boolean variables that monitor whether the game is active, paused, or over, thus controlling the game’s flow based on user interactions and events.
Items Array
Defines different types of items (fruits and bombs) with their properties (color and score impact).
Updating Score and Level
<strong>function updateScore() {
scoreValue.textContent = score;
}
function updateLevel() {
levelValue.textContent = level;
}</strong>
- Update Score: Changes the score displayed on the screen.
- Update Level: Changes the level displayed on the screen.
Moving the Basket
<strong> function moveBasket(e) {
if (!gameRunning) return;
const x = e.clientX - gameContainer.offsetLeft;
basket.style.left = Math.min(Math.max(x - (basket.offsetWidth / 2), 0), gameWidth - basket.offsetWidth) + 'px';
}</strong>
Move Basket: Moves the basket horizontally based on the mouse’s X position. Ensures the basket stays within the game container’s boundaries.
Dropping Items
<strong> function dropItem() {
const maxX = gameWidth - fallingItem.offsetWidth;
const randomX = Math.floor(Math.random() * maxX);
const randomItem = items[Math.floor(Math.random() * items.length)];
fallingItem.style.left = randomX + 'px';
fallingItem.style.top = '0px';
fallingItem.style.backgroundColor = randomItem.color;
fallingItem.dataset.type = randomItem.type;
fallingItem.dataset.score = randomItem.score;
}</strong>
Drop Item: Randomly positions an item at the top of the game container and assigns its type, color, and score.
Checking for Collisions
<strong> function checkCollision() {
const basketRect = basket.getBoundingClientRect();
const fallingItemRect = fallingItem.getBoundingClientRect();
if (fallingItemRect.bottom >= basketRect.top &&
fallingItemRect.left <= basketRect.right &&
fallingItemRect.right >= basketRect.left &&
fallingItemRect.top <= basketRect.bottom) {
if (fallingItem.dataset.type === 'fruit') {
score += parseInt(fallingItem.dataset.score);
catchSound.play();
updateScore();
dropItem();
increaseDifficulty();
} else if (fallingItem.dataset.type === 'bomb') {
bombSound.play();
gameOver();
}
}
}</strong>
Check Collision: Detects if the falling item overlaps with the basket. If it’s a fruit, the score increases, and a new item is dropped. If it’s a bomb, the game ends.
Increasing Difficulty
Increase Difficulty: Increases the falling speed of items and increments the level for every 10 points scored.
Game Loop
<strong> function gameLoop() {
if (!gameRunning) return;
const newY = fallingItem.offsetTop + fallingSpeed;
fallingItem.style.top = newY + 'px';
if (newY >= gameHeight) {
dropItem();
deductPoints();
}
checkCollision();
animationFrameId = requestAnimationFrame(gameLoop);
}</strong>
Game Loop: Continuously updates the position of the falling item, checks for collisions, and handles items reaching the bottom. Uses requestAnimationFrame for smooth animation.
Deducting Points
<strong> function deductPoints() {
score -= 2; // You can adjust the amount of points to deduct here
updateScore();
}</strong>
Deduct Points: Decreases the score when an item reaches the bottom without being caught.
Game Control Functions
<strong> function startGame() {
gameRunning = true;
score = 0;
level = 1; // Initialize level
fallingSpeed = 5;
updateScore();
updateLevel();
gameOverText.classList.add('hidden');
dropItem();
gameLoop();
}
function stopGame() {
gameRunning = false;
cancelAnimationFrame(animationFrameId);
gameOverText.textContent = 'Game Over! Your final score is: ' + score;
gameOverText.classList.remove('hidden');
}
function pauseGame() {
gameRunning = false;
cancelAnimationFrame(animationFrameId);
}
function gameOver() {
stopGame();
}</strong>
- Start Game: Resets game variables and starts the game loop.
- Stop Game: Stops the game, displays the final score, and shows the game over message.
- Pause Game: Pauses the game by stopping the animation frame.
- Game Over: Stops the game, triggered when a bomb is caught.
Event Listeners
<strong> startButton.addEventListener('click', startGame);
stopGameButton.addEventListener('click', stopGame);
pauseGameButton.addEventListener('click', pauseGame);
window.addEventListener('mousemove', moveBasket);
});</strong>
- Event Listeners: Attach functions to handle user interactions:
- startButton starts the game.
- stopGameButton stops the game.
- pauseGameButton pauses the game.
- window listens for mouse movements to move the basket.
By combining these functionalities, the game becomes interactive, with a moving basket, falling items, score and level updates, and sound effects. The game logic ensures smooth gameplay, collision detection, and difficulty adjustment.
Trending
How To Build An Instagram Bot Using Python And InstaPy
Adding Sound Effects
Sound effects enhance the gaming experience. The HTML includes audio elements for catch and bomb sounds, and the JavaScript code plays these sounds at appropriate events (catching a fruit or hitting a bomb).

Enhancing the Game
To further enhance the game, you can:
- Add More Items: Introduce different types of fruits with varying point values.
- Improve Graphics: Use images for the basket and items instead of colored divs.
- Mobile Compatibility: Ensure the game works smoothly on mobile devices by adding touch event listeners.
- High Scores: Implement a high score system that saves and displays the highest score achieved.
- Different Levels: Introduce new challenges or obstacles as the player progresses to higher levels.
How to Play the Game
- To start the game, click the “Start Game” button. The falling item will start moving downwards, and the player’s goal is to catch fruits with the basket while avoiding bombs.
- Move the basket left or right using your mouse to catch falling fruits. Each fruit caught earns you points, while catching a bomb ends the game.
- The game speed increases as you progress, and the level increases every time you score 10 points.
- You can pause the game at any time by clicking the “Pause Game” button, and you can stop the game by clicking the “Stop Game” button.
- The game ends when you catch a bomb or when your score reaches a negative threshold.
Conclusion
Creating a simple “Catch-the-Fruit” game is a great way to learn the basics of HTML, CSS, and JavaScript. By building this game, you have explored how to structure an HTML document, style it with CSS, and add interactivity using JavaScript. You can expand on this foundation to create more complex and engaging games.
Trending
How to Build a Stunning Business Website from Scratch
Catch the fruit game – Source Code
HTML (index.html)
<strong><!DOCTYPE html>
<html <em>lang</em>="en">
<head>
<meta <em>charset</em>="UTF-8">
<meta <em>name</em>="viewport" <em>content</em>="width=device-width, initial-scale=1.0">
<title>Fruit Catcher Game</title>
<link <em>rel</em>="stylesheet" <em>href</em>="styles.css">
</head>
<body>
<div <em>id</em>="game-container">
<div <em>id</em>="basket"></div>
<div <em>id</em>="falling-item"></div>
<div <em>id</em>="score">Score: <span <em>id</em>="score-value">0</span></div>
<div <em>id</em>="level">Level: <span <em>id</em>="level-value">1</span></div>
<div <em>id</em>="game-over" <em>class</em>="hidden">Game Over! Your final score is: <span <em>id</em>="final-score"></span></div>
</div>
<button <em>id</em>="start-button">Start Game</button>
<button <em>id</em>="stop-game">Stop Game</button>
<button <em>id</em>="pause-game">Pause Game</button>
<audio <em>id</em>="catch-sound" <em>src</em>="catch-sound.mp3" <em>preload</em>="auto"></audio>
<audio <em>id</em>="bomb-sound" <em>src</em>="bomb-sound.mp3" <em>preload</em>="auto"></audio>
<script <em>src</em>="script.js"></script>
</body>
</html></strong>
CSS (styles.css)
<strong>#game-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
margin: 0;
font-family: Arial, sans-serif;
}
#game-container {
position: relative;
width: 400px;
height: 500px;
background-color: #fff;
border: 2px solid #000;
overflow: hidden;
}
#basket {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
width: 80px;
height: 80px;
background-color: #ff4500;
border-radius: 50%;
}
#falling-item {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 50px;
height: 50px;
background-color: #008000;
border-radius: 50%;
}
#score, #level {
position: absolute;
font-size: 20px;
font-weight: bold;
color: #333;
}
#score {
top: 20px;
left: 20px;
}
#level {
top: 50px;
left: 20px;
}
button {
margin: 5px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
#game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 24px;
color: red;
display: none;
}
.hidden {
display: none;
}</strong>
JavaScript (script.js)
<strong>document.addEventListener('DOMContentLoaded', () => {
const basket = document.getElementById('basket');
const fallingItem = document.getElementById('falling-item');
const scoreValue = document.getElementById('score-value');
const levelValue = document.getElementById('level-value');
const startButton = document.getElementById('start-button');
const stopGameButton = document.getElementById('stop-game');
const pauseGameButton = document.getElementById('pause-game');
const gameOverText = document.getElementById('game-over');
const catchSound = document.getElementById('catch-sound');
const bombSound = document.getElementById('bomb-sound');
let score = 0;
let level = 1;
let gameContainer = document.getElementById('game-container');
let gameHeight = gameContainer.offsetHeight;
let gameWidth = gameContainer.offsetWidth;
let fallingSpeed = 5;
let gameRunning = false;
let animationFrameId;
const negativeThreshold = -10; // Game over when score reaches this threshold
const items = [
{ type: 'fruit', color: '#008000', score: 1 },
{ type: 'fruit', color: '#ffa500', score: 2 },
{ type: 'fruit', color: '#800080', score: 3 },
{ type: 'fruit', color: '#ffff00', score: 4 },
{ type: 'bomb', color: '#ff0000', score: -5 }
];
function updateScore() {
scoreValue.textContent = score;
}
function updateLevel() {
levelValue.textContent = level;
}
function moveBasket(<em>e</em>) {
if (!gameRunning) return;
const x = e.clientX - gameContainer.offsetLeft;
basket.style.left = Math.min(Math.max(x - (basket.offsetWidth / 2), 0), gameWidth - basket.offsetWidth) + 'px';
}
function dropItem() {
const maxX = gameWidth - fallingItem.offsetWidth;
const randomX = Math.floor(Math.random() * maxX);
const randomItem = items[Math.floor(Math.random() * items.length)];
fallingItem.style.left = randomX + 'px';
fallingItem.style.top = '0px';
fallingItem.style.backgroundColor = randomItem.color;
fallingItem.dataset.type = randomItem.type;
fallingItem.dataset.score = randomItem.score;
}
function checkCollision() {
const basketRect = basket.getBoundingClientRect();
const fallingItemRect = fallingItem.getBoundingClientRect();
if (fallingItemRect.bottom >= basketRect.top &&
fallingItemRect.left <= basketRect.right &&
fallingItemRect.right >= basketRect.left &&
fallingItemRect.top <= basketRect.bottom) {
if (fallingItem.dataset.type === 'fruit') {
score += parseInt(fallingItem.dataset.score);
catchSound.play();
updateScore();
dropItem();
increaseDifficulty();
} else if (fallingItem.dataset.type === 'bomb') {
bombSound.play();
gameOver();
}
}
}
function increaseDifficulty() {
fallingSpeed += 0.5; // Increase falling speed
if (score % 10 === 0) {
level++; // Increase level every 10 points
updateLevel();
}
}
function gameLoop() {
if (!gameRunning) return;
const newY = fallingItem.offsetTop + fallingSpeed;
fallingItem.style.top = newY + 'px';
if (newY >= gameHeight) {
dropItem();
deductPoints();
}
checkCollision();
animationFrameId = requestAnimationFrame(gameLoop);
}
function deductPoints() {
// Deduct points when the falling item reaches the bottom without being caught
score -= 2; // You can adjust the amount of points to deduct here
updateScore();
}
function startGame() {
gameRunning = true;
score = 0;
level = 1; // Initialize level
fallingSpeed = 5;
updateScore();
updateLevel();
gameOverText.classList.add('hidden');
dropItem();
gameLoop();
}
function stopGame() {
gameRunning = false;
cancelAnimationFrame(animationFrameId);
gameOverText.textContent = 'Game Over! Your final score is: ' + score;
gameOverText.classList.remove('hidden');
}
function pauseGame() {
gameRunning = false;
cancelAnimationFrame(animationFrameId);
}
function gameOver() {
stopGame();
}
startButton.addEventListener('click', startGame);
stopGameButton.addEventListener('click', stopGame);
pauseGameButton.addEventListener('click', pauseGame);
window.addEventListener('mousemove', moveBasket);
});</strong>
External Resources For Game Development
- Offers comprehensive documentation, tutorials, and guides on HTML, CSS, and JavaScript, crucial for web game development.
- A popular HTML5 game framework providing extensive documentation, tutorials, and examples for building web games.
Introduction to HTML Game Development
- A community-driven platform with articles, tutorials, and forums covering various game development topics, including HTML game development.
- A dedicated community forum for HTML5 game development, facilitating discussions, resource sharing, and networking among developers.
- Hosts numerous open-source HTML game projects, libraries, and frameworks, offering valuable learning opportunities through contributions and browsing repositories.
FAQ’S
1. What is HTML game design?
Explore the basics of HTML game design and how it differs from traditional game development approaches.
2. How do I get started with building HTML games?
Discover step-by-step instructions for initiating your journey into HTML game development, including essential tools and resources.
3. What are the key components of a Catch-the-Fruit game?
Learn about the essential elements required to create an engaging Catch-the-Fruit game, from gameplay mechanics to visual aesthetics.
4. Can beginners build HTML games?
Yes, You can Find out how accessible HTML game development is for newcomers, with insights into learning curves, resources, and community support.
5. What skills do I need to develop HTML games?
Explore the foundational skills necessary to succeed in HTML game development, including programming languages, design principles, and creativity.
6. How can I enhance my HTML game with sound effects?
Discover techniques for incorporating immersive sound effects into your HTML game, elevating the player experience and adding depth to gameplay.
Pingback: How to Build a Stunning Business Website from Scratch - EmiTechLogic
Pingback: A Guide To Web Scraping in Python Using Beautiful Soup - EmiTechLogic