Embark on an HTML game design journey as you craft your debut Catch-the-Fruit game, mastering essential concepts and techniques.
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
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 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 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 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.
Let’s start by setting up the project structure and creating the necessary files:
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>
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>
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>
The JavaScript code adds interactivity and game logic to the HTML elements defined for the game. Let’s see the functionality step by step:
<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>
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.
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 are mportant for managing the state and dynamics of a game.
Initialization: Setting initial values for different aspects of the game.
Defines different types of items (fruits and bombs) with their properties (color and score impact).
<strong>function updateScore() {
scoreValue.textContent = score;
}
function updateLevel() {
levelValue.textContent = level;
}</strong>
<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.
<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.
<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.
Increase Difficulty: Increases the falling speed of items and increments the level for every 10 points scored.
<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.
<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.
<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>
<strong> startButton.addEventListener('click', startGame);
stopGameButton.addEventListener('click', stopGame);
pauseGameButton.addEventListener('click', pauseGame);
window.addEventListener('mousemove', moveBasket);
});</strong>
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
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).
To further enhance the game, you can:
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
<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>
<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>
<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>
Phaser
Introduction to HTML Game Development
Explore the basics of HTML game design and how it differs from traditional game development approaches.
Discover step-by-step instructions for initiating your journey into HTML game development, including essential tools and resources.
Learn about the essential elements required to create an engaging Catch-the-Fruit game, from gameplay mechanics to visual aesthetics.
Yes, You can Find out how accessible HTML game development is for newcomers, with insights into learning curves, resources, and community support.
Explore the foundational skills necessary to succeed in HTML game development, including programming languages, design principles, and creativity.
Discover techniques for incorporating immersive sound effects into your HTML game, elevating the player experience and adding depth to gameplay.
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.
View Comments