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

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

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!