Open In App

Slider and Ball Game using Computer Graphics in C++

Last Updated : 04 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Computer graphics provide an exciting platform for developing fun and interactive games. In this article, we will walk you through the creation of a simple yet entertaining slider and ball game using the C++ programming language and the graphics.h library.

Prerequisites: C++ Graphics and Development Environment Setup. Refer to this article for setup.

slider game in C++

Slider Game in C++

Slider and Balls Game in C++

This game features colorful balls, moving sliders, and a scoring system. Here, we will have three different color balls randomly moving inside the frame with different positions and velocities. After the collision with the boundary, they will bounce as a perfectly elastic collision. There will also be three sliders of different colors corresponding to the balls. When the balls collide with the same color slider, it will be counted as 1 point. The color that reaches the 10 points first wins the game.

Components of the Game

The following functions are used for the corresponding tasks:

  • initgraph(&gd, &gm, NULL): Initializes the graphics library and creates a graphical window.
  • setbkcolor(CYAN): Sets the background color of the window to cyan.
  • bar(…): Draws rectangles for sliders and bars.
  • circle(…): Draws circles for the balls.
  • getpixel(…): Retrieves the color of a pixel at a given location.
  • outtextxy(…): Outputs text on the screen.
  • delay(…): Pauses the program execution for a specified time.
  • kbhit(): Checks if a key has been pressed.

Approach

  1. Initialize the graphics environment and set the background color.
  2. Create sliders of different colors (red, green, and blue) with varying speeds.
  3. Generate colorful balls with random positions, velocities, and directions.
  4. Continuously update the positions of the sliders and balls while checking for collisions.
  5. Calculate the scores(penalty if collide with wrong slider) based on ball-slider collisions and display them.
  6. If a player reaches a score of 10, display the winner and exit the game.

C++ Program to Implement Slider and Balls Game

C++




// Include necessary libraries
#include <algorithm>
#include <conio.h>
#include <graphics.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize the graphics environment
    int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);
    // Set the background color
    setbkcolor(CYAN);
    // Define variables and constants for sliders, bars,
    // colors, and scoring
    int barWidth = 20;
    int barHeight = 120;
    int spaceBetweenBars = 50;
    int minY = 50;
    int maxY = getmaxy() - 50;
    int barX = getmaxx() - 50 - barWidth;
  
    srand(time(NULL));
  
    int yellowColor = YELLOW;
    int cyanColor = BLACK;
    int magentaColor = MAGENTA;
    int otherColor = WHITE;
  
    int redBarY = minY;
    int greenBarY = minY + spaceBetweenBars;
    int blueBarY = minY + 2 * spaceBetweenBars;
    int redBarVelocity = 3;
    int greenBarVelocity = 5;
    int blueBarVelocity = 10;
  
    int redColor = RED;
    int greenColor = GREEN;
    int blueColor = BLUE;
  
    int scoreRed = 0;
    int scoreGreen = 0;
    int scoreBlue = 0;
  
    int ballRadius = 10;
  
    // Create arrays to store ball colors, positions,
    // velocities, and directions
    vector<int> colors;
    for (int i = 0; i < 9; ++i) {
        if (i < 2)
            colors.push_back(redColor);
        else if (i < 4)
            colors.push_back(greenColor);
        else if (i < 6)
            colors.push_back(blueColor);
        else if (i == 6)
            colors.push_back(yellowColor);
        else if (i == 7)
            colors.push_back(cyanColor);
        else if (i == 8)
            colors.push_back(magentaColor);
        else
            colors.push_back(otherColor);
    }
  
    vector<int> ballX;
    for (int i = 0; i < colors.size(); ++i) {
        ballX.push_back(rand() % (getmaxx() + ballRadius)
                        / 2);
    }
    vector<int> ballY;
    for (int i = 0; i < colors.size(); ++i) {
        ballY.push_back(rand()
                            % (getmaxy() - ballRadius * 2)
                        + ballRadius);
    }
    vector<int> ballVelocitiesX(colors.size(),
                                rand() % 5 + 5);
    vector<int> ballVelocitiesY(colors.size(),
                                rand() % 5 + 5);
    vector<int> ballDirectionsX(colors.size(), 1);
    vector<int> ballDirectionsY(colors.size(), 1);
    // Game loop
    while (!kbhit()) {
        clearviewport();
        // Update slider positions
        redBarY += redBarVelocity;
        greenBarY += greenBarVelocity;
        blueBarY += blueBarVelocity;
  
        if (redBarY <= minY
            || redBarY + barHeight >= maxY) {
            redBarVelocity *= -1;
        }
        if (greenBarY <= minY
            || greenBarY + barHeight >= maxY) {
            greenBarVelocity *= -1;
        }
        if (blueBarY <= minY
            || blueBarY + barHeight >= maxY) {
            blueBarVelocity *= -1;
        }
        // Draw sliders
        setcolor(redColor);
        setfillstyle(SOLID_FILL, redColor);
        bar(barX, redBarY, barX + barWidth,
            redBarY + barHeight);
        setcolor(greenColor);
        setfillstyle(SOLID_FILL, greenColor);
        bar(barX, greenBarY, barX + barWidth,
            greenBarY + barHeight);
        setcolor(blueColor);
        setfillstyle(SOLID_FILL, blueColor);
        bar(barX, blueBarY, barX + barWidth,
            blueBarY + barHeight);
        // Update ball positions
        for (int i = 0; i < colors.size(); ++i) {
            ballX[i]
                += ballVelocitiesX[i] * ballDirectionsX[i];
            if (ballX[i] >= barX - barWidth
                || ballX[i] - ballRadius <= 0) {
                ballDirectionsX[i] *= -1;
  
                if (ballX[i] - ballRadius > 0) {
                    setcolor(YELLOW);
                    circle(barX, ballY[i], 10);
                    int hitBarColor
                        = getpixel(barX + 10, ballY[i]);
                    // Handle ball-slider collisions and
                    // update scores
                    if (hitBarColor == colors[i]
                        && colors[i] == RED) {
                        scoreRed += 4;
                    }
                    else if (hitBarColor == colors[i]
                             && colors[i] == GREEN) {
                        scoreGreen += 4;
                    }
                    else if (hitBarColor == colors[i]
                             && colors[i] == BLUE) {
                        scoreBlue += 4;
                    }
                    else if (hitBarColor && colors[i]
                             && colors[i] != GREEN
                             && colors[i] != RED
                             && colors[i] != BLUE
                             && hitBarColor == RED) {
                        scoreRed--;
                    }
                    else if (hitBarColor && colors[i]
                             && colors[i] != GREEN
                             && colors[i] != RED
                             && colors[i] != BLUE
                             && hitBarColor == GREEN) {
                        scoreGreen--;
                    }
                    else if (hitBarColor && colors[i]
                             && colors[i] != GREEN
                             && colors[i] != RED
                             && colors[i] != BLUE
                             && hitBarColor == BLUE) {
                        scoreBlue--;
                    }
                }
            }
  
            ballY[i]
                += ballVelocitiesY[i] * ballDirectionsY[i];
            if (ballY[i] > getmaxy() - ballRadius - 5
                || ballY[i] <= ballRadius) {
                ballDirectionsY[i] *= -1;
            }
            // Draw balls
            setcolor(colors[i]);
            setfillstyle(SOLID_FILL, colors[i]);
            fillellipse(ballX[i], ballY[i], ballRadius,
                        ballRadius);
        }
        // Display scores
        setcolor(WHITE);
        const char* scoreText = "Score: ";
        outtextxy(20, 40, const_cast<char*>(scoreText));
  
        char redScoreText[10], greenScoreText[10],
            blueScoreText[10];
        sprintf(redScoreText, "Red: %d", scoreRed);
        sprintf(greenScoreText, "Green: %d", scoreGreen);
        sprintf(blueScoreText, "Blue: %d", scoreBlue);
  
        outtextxy(70, 40, redScoreText);
        outtextxy(120, 40, greenScoreText);
        outtextxy(180, 40, blueScoreText);
        // Check for a winner and exit the game if necessary
        if (scoreRed >= 10 || scoreGreen >= 10
            || scoreBlue >= 10) {
            clearviewport();
            setcolor(WHITE);
            settextstyle(6, 0, 4);
            const char* winners = "Congratulations";
            outtextxy(100, getmaxy() / 4,
                      const_cast<char*>(winners));
            delay(500);
            if (scoreRed >= 10) {
                const char* red_w = "RED is WINNER";
                outtextxy(100, getmaxy() / 2 + 30,
                          const_cast<char*>(red_w));
            }
            if (scoreGreen >= 10) {
                const char* green_w = "GREEN is WINNER";
                outtextxy(100, getmaxy() / 2 + 30,
                          const_cast<char*>(green_w));
            }
            if (scoreBlue >= 10) {
                const char* blue_w = "BLUE is WINNER";
                outtextxy(100, getmaxy() / 2 + 30,
                          const_cast<char*>(blue_w));
            }
            const char* out = "Press any key to EXIT";
            outtextxy(100, getmaxy() / 2 + 200,
                      const_cast<char*>(out));
            break;
        }
  
        delay(10);
    }
    // Wait for a key press before closing the window
    while (!kbhit()) {
        delay(100);
    }
    // Close the graphics environment
    closegraph();
    return 0;
}


Output

The output of this program will be a graphical window displaying colorful balls, sliders, and scores. When a player wins, the game displays a congratulatory message with the winner’s color.

Note: This code requires a specific library setup and may not work on online Integrated Development Environments (IDEs).

Conclusion

Creating a slider and ball game in computer graphics is a fun project that allows you to practice your programming skills and learn more about graphical user interfaces. This article provided a step-by-step guide to developing the game, including code with comments to help you understand the process. Feel free to modify and expand upon this game to add more features and complexity. Happy coding!

Frequently Asked Questions (FAQs)

Q1. What are the prerequisites for running this game?

Answer:

To run this game, you’ll need a C++ development environment that supports the graphics library, such as Turbo C++ or Code::Blocks with the graphics.h and conio.h library installed.

Q2. Can I customize the game, such as the colors or scoring rules?

Answer:

Yes, you can customize various aspects of the game. You can change the colors of the sliders, balls, and backgrounds by modifying the color constants in the code. You can also adjust the scoring rules and add new features or obstacles to make the game more challenging.

Q3. How can I expand upon this game or add new features?

Answer:

You can expand the game by adding new features such as power-ups, obstacles, or different game modes. You can also make the game more complex by introducing additional sliders, balls, or levels. The code provided in the article serves as a foundation that can be built upon.

Q4. Are there any alternative graphics libraries that can be used for this game?

Answer:

Yes, there are alternative graphics libraries like SDL (Simple DirectMedia Layer) and SFML (Simple and Fast Multimedia Library) that can be used for creating games in C++. These libraries provide more advanced graphics and multimedia capabilities.

Q5. Can this game be adapted for touchscreen devices or mobile platforms?

Answer:

Adapting this game for touchscreen or mobile platforms would require significant modifications and a different set of libraries or frameworks. Mobile game development typically involves platforms like Android (using Java or Kotlin) or iOS (using Swift or Objective-C).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads