Skip to content
9 July 2025
  • Facebook
  • LinkedIn
  • Pinterest

All Aspects Hub

A dynamic blogging website offering insightful articles on a wide range of topics for diverse readers.

Primary Menu
  • Automotive
  • Business
  • Education
  • Fashion
  • Finance
  • Health
  • Real Estate
  • Software
    • Coding
  • Entertainment
  • About Us
    • Write For Us
    • Contact Us
    • Terms of Use
    • DMCA Policy
  • Home
  • Coding
  • Code For Cosmic Ball Catcher: A Fun Web-Based Game For College Project
  • Coding

Code For Cosmic Ball Catcher: A Fun Web-Based Game For College Project

Shubham Joshi 13 July 2024
cosmic ball catcher game for college project

cosmic ball catcher game for college project

Table of Contents

Toggle
  • Introduction
  • Game Overview
  • Features
  • Game Code
    • HTML and CSS
  • Explanation of the Code
  • Conclusion

Introduction

Are you looking for a simple yet addictive game to pass the time? Look no further than “Cosmic Ball Catcher,” a web-based game that you can easily add to your website or play locally. This article will walk you through the game, its features, and the code behind it, so you can understand how it works and even modify it to suit your needs.

Game Overview

Cosmic Ball Catcher is a classic paddle game where the objective is to catch a falling ball using a paddle. The ball starts at the top of the canvas and falls toward the bottom, gaining speed as you progress. The challenge is to move the paddle left and right to catch the ball, increasing your score with each successful catch. The game ends when you miss the ball, and your score is displayed along with a leaderboard showcasing the top scores.

Features

  • Player Name Input: Allows players to enter their names before starting the game.
  • Dynamic Background: The background color changes every 10 points scored, adding a visual element to the game.
  • Leaderboard: Keeps track of the top 10 scores using localStorage, so even after closing the browser, the scores are preserved.
  • Responsive Design: The game adapts well to different screen sizes, providing a consistent experience across devices.

Game Code

Below is the complete code for Cosmic Ball Catcher. You can copy and paste this code into your HTML file to try it out.

HTML and CSS

<div class="entry-content">
    <style>
        .game-calculator {
            max-width: 400px;
            margin: 0 auto;
            background-color: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            font-family: 'Arial', sans-serif;
        }
        .game-calculator p.title {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 20px;
            font-size: 18px;
            font-weight: bold;
        }
        .input-group {
            margin-bottom: 15px;
        }
        .input-group label {
            display: block;
            margin-bottom: 5px;
            color: #34495e;
            font-weight: bold;
        }
        .input-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #bdc3c7;
            border-radius: 5px;
            font-size: 16px;
        }
        .start-btn, .retry-btn {
            width: 100%;
            padding: 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 18px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .start-btn:hover, .retry-btn:hover {
            background-color: #2980b9;
        }
        #gameCanvas {
            width: 100%;
            border: 1px solid #bdc3c7;
            border-radius: 5px;
            margin-top: 20px;
        }
        #score, #gameOver {
            margin-top: 20px;
            padding: 15px;
            background-color: #e8f6fc;
            border-radius: 5px;
            font-weight: bold;
            color: #2c3e50;
        }
        .footer {
            text-align: center;
            margin-top: 20px;
            color: #7f8c8d;
            font-style: italic;
        }
        #leaderboard {
            margin-top: 20px;
            width: 100%;
            border-collapse: collapse;
        }
        #leaderboard th, #leaderboard td {
            border: 1px solid #bdc3c7;
            padding: 8px;
            text-align: left;
        }
        #leaderboard th {
            background-color: #3498db;
            color: white;
        }
    </style>

    <div class="game-calculator">
        <p class="title"><strong>Cosmic Ball Catcher</strong></p>
        <div id="startScreen">
            <div class="input-group">
                <label for="playerName">Player Name</label>
                <input type="text" id="playerName" placeholder="Enter your name">
            </div>
            <button class="start-btn" onclick="startGame()">Start Game</button>
        </div>
        <canvas id="gameCanvas" width="400" height="400" style="display: none;"></canvas>
        <div id="score" style="display: none;">Score: 0</div>
        <div id="gameOver" style="display: none;"></div>
        <button class="retry-btn" onclick="retryGame()" style="display: none;">Retry</button>
        <table id="leaderboard">
            <thead>
                <tr>
                    <th>Rank</th>
                    <th>Name</th>
                    <th>Score</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <div class="footer">Cosmic Ball Catcher Hub</div>

JavaScript

<script>
    // Get DOM elements
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const scoreElement = document.getElementById('score');
    const gameOverElement = document.getElementById('gameOver');
    const leaderboardBody = document.querySelector('#leaderboard tbody');
    const retryButton = document.querySelector('.retry-btn');

    // Game variables
    let ballX, ballY, ballRadius, ballSpeed;
    let paddleWidth, paddleHeight, paddleX;
    let score;
    let playerName;
    let gameLoop;
    let leaderboard = [];
    let backgroundColor = '#f8f9fa';  // Initial background color

    // Initialize game state
    function initGame() {
        ballRadius = 10;
        ballX = Math.random() * (canvas.width - 2 * ballRadius) + ballRadius;
        ballY = ballRadius;
        ballSpeed = 2;

        paddleWidth = 80;
        paddleHeight = 10;
        paddleX = (canvas.width - paddleWidth) / 2;

        score = 0;
        scoreElement.textContent = `Score: ${score}`;
        backgroundColor = '#f8f9fa';  // Reset background color
    }

    // Draw the ball
    function drawBall() {
        ctx.beginPath();
        ctx.arc(ballX, ballY, ballRadius, 0, Math.PI * 2);
        ctx.fillStyle = '#e74c3c'; // Red color for the ball
        ctx.fill();
        ctx.closePath();
    }

    // Draw the paddle
    function drawPaddle() {
        ctx.beginPath();
        ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
        ctx.fillStyle = '#2c3e50';
        ctx.fill();
        ctx.closePath();
    }

    // Move the paddle based on mouse position
    function movePaddle(e) {
        const rect = canvas.getBoundingClientRect();
        paddleX = e.clientX - rect.left - paddleWidth / 2;

        if (paddleX < 0) {
            paddleX = 0;
        }
        if (paddleX + paddleWidth > canvas.width) {
            paddleX = canvas.width - paddleWidth;
        }
    }

    // Main game loop
    function update() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // Set background color
        ctx.fillStyle = backgroundColor;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        drawBall();
        drawPaddle();

        ballY += ballSpeed;

        // Check for collision with paddle
        if (ballY + ballRadius > canvas.height - paddleHeight &&
            ballX > paddleX && ballX < paddleX + paddleWidth) {
            score++;
            scoreElement.textContent = `Score: ${score}`;
            ballY = ballRadius;
            ballX = Math.random() * (canvas.width - 2 * ballRadius) + ballRadius;
            ballSpeed += 0.1;

            // Change background color every 10 points
            if (score % 10 === 0) {
                backgroundColor = `hsl(${Math.random() * 360}, 50%, 80%)`;
            }
        }

        // Check if ball is out
        if (ballY + ballRadius > canvas.height) {
            gameOver();
            return;
        }

        gameLoop = requestAnimationFrame(update);
    }

    // Handle game over
    function gameOver() {
        cancelAnimationFrame(gameLoop);
        updateLeaderboard();
        displayLeaderboard();
        canvas.style.display = 'none';
        scoreElement.style.display = 'none';
        gameOverElement.style.display = 'block';
        gameOverElement.textContent = `Game Over! ${playerName}, your score is: ${score}`;
        retryButton.style.display = 'block';
    }

    // Update leaderboard with new score
    function updateLeaderboard() {
        leaderboard.push({ name: playerName, score: score });
        leaderboard.sort((a, b) => b.score - a.score);
        leaderboard = leaderboard.slice(0, 10);  // Keep only top 10
        localStorage.setItem('cosmicBallLeaderboard', JSON.stringify(leaderboard));
    }

    // Display leaderboard on the page
    function displayLeaderboard() {
        leaderboardBody.innerHTML = '';
        leaderboard.forEach((entry, index) => {
            const row = leaderboardBody.insertRow();
            row.insertCell(0).textContent = index + 1;
            row.insertCell(1).textContent = entry.name;
            row.insertCell(2).textContent = entry.score;
        });
    }

    // Start the game
    function startGame() {
        playerName = document.getElementById('playerName').value.trim();
        if (playerName) {
            document.getElementById('startScreen').style.display = 'none';
            canvas.style.display = 'block';
            scoreElement.style.display = 'block';
            retryButton.style.display = 'none';
            initGame();
            canvas.addEventListener('mousemove', movePaddle);
            update();
        } else {
            alert('Please enter your name!');
        }
    }

    // Retry the game
    function retryGame() {
        gameOverElement.style.display = 'none';
        retryButton.style.display = 'none';
        canvas.style.display = 'block';
        scoreElement.style.display = 'block';
        initGame();
        update();
    }

    // Load leaderboard from localStorage
    const savedLeaderboard = localStorage.getItem('cosmicBallLeaderboard');
    if (savedLeaderboard) {
        leaderboard = JSON.parse(savedLeaderboard);
        displayLeaderboard();
    }
</script>

Explanation of the Code

  • HTML Structure: The HTML sets up the structure of the game, including the input field for the player’s name, the canvas element for the game, and the leaderboard table.
  • CSS Styling: The CSS styles the game container, input fields, buttons, canvas, and leaderboard for a clean and modern look.
  • JavaScript Logic: The JavaScript code handles the game logic, including initializing the game state, drawing the ball and paddle, handling paddle movement, updating the game loop, checking for collisions, managing the score, and handling game over conditions. It also manages the leaderboard using localStorage to keep track of the top scores.

Conclusion

Cosmic Ball Catcher is a simple yet engaging game that can be easily added to any website. The code provided is well-documented and easy to understand, allowing you to customize it as needed. Whether you’re a beginner looking to learn JavaScript or an experienced developer seeking a fun project, this game offers a great opportunity to explore web-based game development. Happy coding!

Tags: code for cosmic ball catcher game cosmic ball catcher game

Continue Reading

Previous: From Grandma’s Attic to Chic Outfit: Mastering Vintage Style
Next: The Electrifying Rise of EVs: 100+ Compelling Stats Powering the Global Automotive Revolution

Related Stories

online invoice generator
  • Business
  • Coding
  • Software

Effortlessly Create Professional Invoices with Our Invoice Generator

Shubham Joshi 29 June 2025
python project ideas
  • Coding
  • Education
  • Software

Python Project Ideas for Final Year IT Students

Shubham Joshi 2 June 2025
Social Media Usage in the USA
  • Business
  • Coding
  • Entertainment
  • Finance
  • Software

Social Media Usage Statistics in the USA – Historical Data (2019-2024) & Projections (2025-2029)

Shubham Joshi 31 May 2025

Recent Posts

  • Effortlessly Create Professional Invoices with Our Invoice Generator
  • Best 7 Social Media Management Tools for Small Businesses
  • Python Project Ideas for Final Year IT Students
  • Social Media Usage Statistics in the USA – Historical Data (2019-2024) & Projections (2025-2029)
  • India Regional OTT Platforms Statistics 2025

Recent Comments

No comments to show.

Archives

  • June 2025
  • May 2025
  • February 2025
  • January 2025
  • November 2024
  • October 2024
  • July 2024
  • June 2024
  • May 2024
  • March 2024
  • December 2023
  • November 2023
  • October 2023

Categories

  • Automotive
  • Blog
  • Business
  • Coding
  • Education
  • Entertainment
  • Fashion
  • Finance
  • Health
  • Real Estate
  • Software

Academic Projects Anime In India Best way to repair scratches on furniture Car Service Solutions chat app project code for cosmic ball catcher game cosmic ball catcher game Diesel Engine Care Diesel Engine Maintenance Diesel Engine Tips electic vehicles statistics Engine Longevity ev stats Fusion Of Tech And Transport gut microbiome healthy gut How to repair surface scratches improve digestion millenial money millenial money guide millenial money saving millenial saving guide Most Viewed Anime In India patient portal Preventative Maintenance probiotics project for students Python Programming regional OTT regional OTT statistics 2025 Scratch repair methods Scratch repair strategies small business social media management social media management social media tool Surface material damage prevention Surface material scratch repair Tech And Transport underrated anime series Underrated Anime Series of the Last Decade ut health Vintage Style yoga yoga school in rishikesh yoga teacher training

You may have missed

online invoice generator
  • Business
  • Coding
  • Software

Effortlessly Create Professional Invoices with Our Invoice Generator

Shubham Joshi 29 June 2025
social media platforms for small business
  • Software

Best 7 Social Media Management Tools for Small Businesses

Shubham Joshi 9 June 2025
python project ideas
  • Coding
  • Education
  • Software

Python Project Ideas for Final Year IT Students

Shubham Joshi 2 June 2025
Social Media Usage in the USA
  • Business
  • Coding
  • Entertainment
  • Finance
  • Software

Social Media Usage Statistics in the USA – Historical Data (2019-2024) & Projections (2025-2029)

Shubham Joshi 31 May 2025
  • Automotive
  • Business
  • Education
  • Fashion
  • Finance
  • Health
  • Real Estate
  • Software
  • Entertainment
  • About Us
  • Facebook
  • LinkedIn
  • Pinterest
Copyright © All rights reserved. | MoreNews by AF themes.